Modding:Setting up your Development Environment/ru: Difference between revisions

From Vintage Story Wiki
(Created page with "Или перейдите на страницу '''Расширенные элементы''', чтобы создать свой первый р...")
(Created page with "Но это не обязательно при создании нового мода, так как команда <code>dotnet new vsmod</code> установить новую версию шаблона, если она доступна.")
 
(38 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>{{GameVersion|1.15}}
<languages/>
 
{{GameVersion|1.18.8-rc.1}}
__FORCETOC__
__FORCETOC__
== Программное обеспечение ==
== Программное обеспечение ==


Когда вы будете готовы приступить к кодированию модов для Vintage Story, вы, вероятно, захотите настроить среду разработки, которая упростит процесс кодирования и тестирования ваших творений. Есть несколько приложений, которые помогут вам в разработке модов. Вот несколько предложений:
Когда вы будете готовы приступить к кодированию модов для Vintage Story, вы, вероятно, захотите настроить среду разработки, которая упростит процесс кодирования и тестирования ваших творений. Vintage Story разрабатывается на C# и начиная с версии 1.18.8 мы перешли на .NET 7.
 
Есть несколько приложений, которые помогут вам в разработке модов. Вот некоторые из них, поддерживающие наш шаблон:
 
* [https://www.visualstudio.com/ru/vs/community/ Visual Studio Community] — это бесплатная и очень мощная среда разработки от Microsoft и, возможно, имеет наилучшую поддержу С# и .NET, которые в свою очередь тоже разработаны Microsoft. Это также инструмент, который команда Vintage Story использует при билде игры. Она также имеет [https://www.visualstudio.com/vs/mac/ MacOS версию]. При использовании установите пакет <code>.NET desktop development</code>.
 
* [https://www.jetbrains.com/rider/ Jetbrains Rider] — это платная, мощная и удобная среда разработки специально спроектированная для .NET. Поскольку она создана для .NET, она также имеет очень хорошую поддержку всех функций, которые могут вам понадобиться, и при этом является полностью кроссплатформенной. Она также используется командой Vintage Story при разработке игры.
 
* [https://code.visualstudio.com/ Visual Studio Code] — это бесплатный, лёгкий и универсальный редактор кода, разработанный Microsoft. Он поддерживает множество языков программирования и предлагает широкий выбор функциональных расширений. Расширение для поддержки C# — отличный выбор для начала создания модов. Этот редактор широко используется нашим сообществом мододелов.
 
Хоть вы и можете использовать любой редактор для работы с исходном кодом, мы настоятельно рекомендуем использовать один из вышеперечисленных инструментов, чтобы ваши процессы стали гораздо удобнее.
 
Выберите одну из вышеперечисленных IDE или другие альтернативы. Мы предлагаем использовать '''Visual Studio Community''' для Windows. Для Linux вы можете использовать '''Visual Studio Code''' или '''Rider'''.
 
Примечание: Если вы используете Linux и собираетесь ставить Visual Studio Code или Rider из '''Flatpak''' или '''snap'''? имейте в виду, что могут возникнуть некоторые проблемы с использованием .NET или переменных среды. Так что, по возможности используйте нативные методы установки.
 
 
Далее вам нужно будет установить [https://dotnet.microsoft.com/en-us/download/dotnet/7.0 .NET 7 SDK] (Комплект для разработки программного обеспечения), который также будет включать .NET 7 Dekstop Runtime, необходимый для запуска игры начиная с версии 1.18.8-rc.1.
 
Убедитесь, что .NET 7 SDK установился правильно, выполнив следующую команду в терминале:
 
''В Windows откройте приложение Windows PowerShell, которое предустановлено во всех современных версиях Windows (10 / 11).''
 
<syntaxhighlight lang=shell>
dotnet --list-sdks
</syntaxhighlight>
 
Она выведет список установленных SDK, одна из которых, должна иметь <code>7.0.xxx</code>. Если это так, то можете продолжать.
 
<div lang="en" dir="ltr" class="mw-content-ltr">
== Setup the Environment ==
Our Mod template makes use of the environment variable <code>VINTAGE_STORY</code>. Which we will set up to contain the path of where your game is installed. The use of the environment helps to keep the setup and the template simple so we recommend using it and will cover it in this article.
</div>


* [https://www.visualstudio.com/en/vs/community/ Visual Studio Community] это бесплатная и очень мощная среда разработки, описанная в руководстве ниже. Это также инструмент, который команда Vintage Story использует для создания игры. Он также имеет [https://www.visualstudio.com/vs/mac/ MacOS версию].
<div lang="en" dir="ltr" class="mw-content-ltr">
The <code>VINTAGE_STORY</code> Environment Variable simplifies reusing your Vintage Story game installation path and helps if multiple modders work on the same project to reference the <code>VINTAGE_STORY</code> Environment Variable and have their game installed where ever they want.
</div>


* [https://www.jetbrains.com/rider/ Jetbrains Rider] — это бесплатная и современная среда разработки с бесшовной поддержкой проектов, сочетаний клавиш и макетов Visual Studio. Это корпоративный продукт, и некоторые функции заблокированы лицензией (проверка дублирования кода, инструменты веб-разработчика), но все функции, необходимые для разработки модов VS, бесплатны. Функции индексации/перехода к ссылкам и встроенные функции декомпиляции очень эффективны, так как вы можете нажать на метод, который использует Vintage Story, и он покажет вам код, стоящий за ним. Обратите внимание, что в настоящее время в нем есть одна ошибка + задокументировано обходное решение. [https://github.com/anegostudios/vsmodexamples/issues/11 тут].
=== Windows ===


* [https://code.visualstudio.com/ Visual Studio Code] очень облегченная версия Visual Studio. Наш драгоценный член сообщества [https://twitter.com/koppeh?lang=en copygirl] использует этот инструмент, а также [https://github.com/copygirl/howto-example-mod написал инструкцию по настройке github]
<div lang="en" dir="ltr" class="mw-content-ltr">
Here you have two options to set the environment variable:
* Use this short PowerShell script. Open the ''Windows PowerShell'' Application and paste the following into it and hit ''ENTER''
<syntaxhighlight lang=shell>
[Environment]::SetEnvironmentVariable("VINTAGE_STORY", "$Env:AppData\Vintagestory", "User")
</syntaxhighlight>
</div>


* [https://www.monodevelop.com/ MonoDevelop] — еще одна IDE, более легкая, чем Visual Studio Community.
<div lang="en" dir="ltr" class="mw-content-ltr">
Change <code>$Env:AppData\Vintagestory</code> if you used a custom installation path for your game.
</div>


* [https://notepad-plus-plus.org/ Notepad++] ваш самый простой инструмент для редактирования текста с некоторыми дополнительными функциями. На самом деле, вы можете кодировать моды в любом текстовом редакторе. Однако при программировании отсутствует мгновенная контекстно-зависимая обратная связь, что очень полезно. Если вы выберете этот путь, вы сможете использовать саму игру для проб и ошибок, перезагрузив их во время игры.
<div lang="en" dir="ltr" class="mw-content-ltr">
* Follow these manual steps to set the Environment variable
Search in Windows search for <code>Edit the system environment variables</code> > <code>Environment Variables...</code> > User variables for USER > New > Add insert the Variable name: <code>VINTAGE_STORY</code> and add the path to your Vintage Story installation.
[[File:Win env.png|400px|center|frameless|alt=Setup Windows environment variable]]
</div>


== Установить средство разработки ==
<div lang="en" dir="ltr" class="mw-content-ltr">
For example, the default installation directory would be <code>C:\Users\<Username>\AppData\Roaming\Vintagestory</code>, (replace <Username> with your username) if you are not sure where yours is type <code>%appdata%</code> into the URL field in the File Explorer and hit ENTER. It will take you to your AppData\Roaming folder where Vintage Story should be installed if you haven't changed the default installation location.
</div>


VintageStory разработан на C#. Выберите одну из вышеперечисленных IDE или другие альтернативы. Мы предлагаем использовать '''Visual Studio Community''' для Windows. Для Linux вы можете использовать '''Visual Studio Code''', '''Rider''' или '''MonoDevelop'''.
<div lang="en" dir="ltr" class="mw-content-ltr">
[[File:Win appdata.png|400px|frameless|center|alt=find the default installation path of vintage story]]
Note:
Do not confuse the <code>AppData\Roaming\VintagestoryData</code> directory with the <code>AppData\Roaming\Vintagestory</code> folder. The <code>VintagestoryData</code> directory only holds your Settings, Logs, Savegames and Mods.
</div>


После загрузки IDE вы можете получить проект [https://github.com/anegostudios/vsmodtemplate мода] или вручную настроить проект мода. Шаблон мода предлагает удобный инструмент для настройки нескольких проектов модов, а также для быстрой упаковки и получения готового к отправке мода.
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Linux and Mac ===
To set an environment variable in Linux/Mac you need to add the following to your shells startup file:
</div>


=== Руководство по установке в Windows/macOS с Visual Studio ===
<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang=shell>
export VINTAGE_STORY="$HOME/ApplicationData/vintagestory"
</syntaxhighlight>
Replace the path with the one where your Vintagestory installation is located. The above path should point to your install when you installed Vintagestory using the install.sh script.
</div>


{| class="wikitable"
<div lang="en" dir="ltr" class="mw-content-ltr">
|-
Run <code>echo $SHELL</code> in a terminal to see what shell you are using.
! scope="col"| OS
</div>
! scope="col"| Repo
! scope="col"| Command
|-
| Windows
| [https://visualstudio.microsoft.com/downloads/ скачать exe]
| Запустить загруженный файл
|-
| macOS
| [https://visualstudio.microsoft.com/downloads/ скачать dmg]
| Запустить загруженный файл
|}


=== Руководство по установке на Linux/macOS с MonoDevelop ===
<div lang="en" dir="ltr" class="mw-content-ltr">
* For Bash place it in: <code>~/.bashrc</code> or <code>~/.bash_profile</code> at the end
* For Zsh place it in: <code>~/.zshrc</code> or <code>~/.zprofile</code> at the end
* If you use another shell see their documentation on how their shell startup file is called
Note: If you are using <code>~/.bash_profile</code> or <code>~/.zprofile</code> you will have to Logout and Login again to apply the changes. When using <code>~/.bashrc</code> or <code>~/.zshrc</code> you only need to restart the application that needs to use the environment variable (Visual Studio, Rider, Visual Studio Code, Terminal).
</div>


Вы можете использовать MonoDevelop IDE для создания модов VS в Linux. Инструкции по загрузке приведены ниже, выберите свою ОС и перейдите по ссылке, чтобы добавить репозиторий, затем запустите команду установки.


{| class="wikitable"
== Создание мода  ==
|-
! scope="col"| OS
! scope="col"| Repo
! scope="col"| Command
|-
| Debian 8-10
| [https://www.monodevelop.com/download/#fndtn-download-lin-debian repo]
| <code>sudo apt-get install monodevelop</code>
|-
| Ubuntu 14.04-20.04
| [https://www.monodevelop.com/download/#fndtn-download-lin-ubuntu repo]
| <code>sudo apt-get install monodevelop</code>
|-
| CentOS / RedHat
| [https://www.monodevelop.com/download/#fndtn-download-lin-centos repo]
| <code>yum install monodevelop</code>
|-
| Используя Flatpak
| [http://flatpak.org/getting.html Скачать Flatpak]
| <code>flatpak install --user --from https://download.mono-project.com/repo/monodevelop.flatpakref</code>
|-
| macOS
| [https://www.monodevelop.com/developers/building-monodevelop/ руководство по сборке]
| Используйте Visual Studio или соберите из исходного кода
|-
| Другие
| [https://github.com/mono/monodevelop Компиляции из исходников]
| Следуйте инструкциям для компиляции из исходников
|}


=== Руководство по установке на Linux / macOS с Visual Studio Code ===  
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Mod Template package ===
</div>


Вы можете использовать Visual Studio Code для создания модов VS в Linux. Инструкции по загрузке приведены ниже, выберите свою ОС и перейдите по ссылке, чтобы загрузить ее.
<div lang="en" dir="ltr" class="mw-content-ltr">
The first and recommended option would be to use the ''template package''.
</div>


{| class="wikitable"
<div lang="en" dir="ltr" class="mw-content-ltr">
|-
Install the mod [https://github.com/anegostudios/VSdotnetModTemplates Mod template package] using the following command on the Terminal:
! scope="col"| OS
</div>
! scope="col"| Download
! scope="col"| Command
|-
| Debian 8-10
| [https://code.visualstudio.com/download скачать deb]
| <code>sudo dpkg -i /path/to/vscode/file.deb && sudo apt-get install -f</code>
|-
| Ubuntu 18.04-20.04
| [https://code.visualstudio.com/download скачать deb]
| <code>sudo apt install /path/to/vscode/file.deb</code>
|-
| CentOS / RedHat / Fedora / SUSE
| [https://code.visualstudio.com/download скачать rpm]
| <code>rpm -ih /path/to/vscode/file.rpm</code>
|-
| Arch
| [https://aur.archlinux.org/packages/visual-studio-code-bin пакет]
| <code>yay -S visual-studio-code-bin</code>
|-
| Использовать Snap
| [https://snapcraft.io/docs/installing-snapd скачать <code>snapd</code>]
| <code>sudo snap install code --classic</code>
|-
| macOS
| [https://code.visualstudio.com/download скачать zip]
| Запустить загруженный файл
|-
| Другие
| [https://github.com/microsoft/vscode компилирование из исходников]
| Следуйте инструкциям для компиляции из исходников
|}


=== Руководство по установке на Windows / Linux / macOS с JetBrains Rider ===
<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang=shell>
dotnet new install VintageStory.Mod.Templates
</syntaxhighlight>
</div>


Вы можете использовать Jetbrains Rider для создания модов VS в Linux. Инструкции по загрузке приведены ниже, выберите свою ОС и перейдите по ссылке, чтобы загрузить ее.
<div lang="en" dir="ltr" class="mw-content-ltr">
This will download the latest mod template package from [https://www.nuget.org/packages/VintageStory.Mod.Templates nuget.org]
</div>


{| class="wikitable"
<div lang="en" dir="ltr" class="mw-content-ltr">
|-
Once the template is installed you will see it inside Visual Studio and Rider. From there you can use the templates to create a new Project.
! scope="col"| OS
</div>
! scope="col"| Download
! scope="col"| Command
|-
| Windows
| [https://www.jetbrains.com/rider/download/#section=windows скачать exe]
| Запустить загруженный файл
|-
| Arch
| [https://aur.archlinux.org/packages/rider Пакет]
| <code>yay -S rider mono mono-msbuild</code>
|-
| Используя Toolbox
| [https://www.jetbrains.com/help/idea/installation-guide.html#toolbox СкачатьToolbox]
| Следуйте приведенным инструкциям для вашей ОС
|-
| Используя Snap
| [https://snapcraft.io/docs/installing-snapd Скачать <code>snapd</code>]
| <code>sudo snap install rider --classic</code>
|-
| macOS
| [https://www.jetbrains.com/rider/download/#section=mac Скачать dmg]
| Запустить загруженный файл
|-
| Другие
| [https://www.jetbrains.com/rider/download/#section=linux Скачать <code>.tar.gz</code>]
| <code>sudo tar -xzf ideaIU.tar.gz -C /opt && cd /opt/idea-dir-edit-me && sudo ./idea.sh</code>
|}


== Шаблоны модов ==


* [https://github.com/anegostudios/vsmodtemplate/releases/latest '''Официальный шаблон мода для Visual Studio'''] который рассматривается в этой статье.
==== Visual Studio ====
* [https://github.com/copygirl/howto-example-mod установка copygirl's VSCode]


== Настройка с использованием официального шаблона мода ==
<div lang="en" dir="ltr" class="mw-content-ltr">
We advise you to check the option  <code>Place solution and project in the same directory</code> for Visual Studio
This will flatten the project tree by one folder and make it easier to navigate.
</div>


Для начала загрузите решение VSModTemplate с [https://github.com/anegostudios/vsmodtemplate/releases/latest GitHub]. Теперь вам просто нужно распаковать zip-архив в нужное место.
<div lang="en" dir="ltr" class="mw-content-ltr">
If you don't want the log output to show up in a separate window you can check the option <code>SuppressWindowsConsoleWindow</code>. When enabled the log output will still be shown inside the Visual Studio Debug Output.
</div>


[[File:VSMods9.png]]
<div lang="en" dir="ltr" class="mw-content-ltr">
Open Visual Studio and click on ''Create a new project''. If you installed the ''VintageStory.Mod.Templates'' you can then select '''Vintage Story Mod'''.
<gallery mode="packed-hover" widths=400px heights=300px>
File:Vs-cp-template.png|Visual Studio Mod Template
File:Vs-cp-template-setup.png|Visual Studio Mod Template setup
File:Vs-cp-template-options.png|Visual Studio Mod Template options
</gallery>
</div>


Перейдите к <code>vsmodtemplate-x.y.z</code> и дважды щелкните <code>VSMods.sln</code> (работает, только если установлена Visual Studio). В качестве альтернативы вы также можете запустить Visual Studio, нажав <code>File -> Open -> Project/Solution...</code>, перейти к извлеченной папке и выбрать <code>VSMods.sln</code>.
==== Rider ====


Но прежде чем вы сможете начать работать, вы должны сначала настроить ModTools.
<div lang="en" dir="ltr" class="mw-content-ltr">
We advise you to check the option <code>Put solution and project in the same directory</code> for Rider.
This will flatten the project tree by one folder and make it easier to navigate.
</div>


=== Запустить ModTools ===
<div lang="en" dir="ltr" class="mw-content-ltr">
Open Rider and click on ''New Solution''. If you installed the ''VintageStory.Mod.Templates'' you can then select '''Vintage Story Mod'''.
</div>


ModTools позволяет вам довольно легко выполнять различные задачи, вводя команду. Для каждой платформы требуется свой способ запуска.
<div lang="en" dir="ltr" class="mw-content-ltr">
Обратите внимание, что инструменты модификации были протестированы только с Visual Studio и MonoDevelop, но они не требуются для модификации игры, они просто упрощают некоторые задачи.
[[File:Rider-cp-template.png|400px|frameless|center|alt=Rider Mod Template|Rider Mod Template]]
</div>


==== Windows ====


Дважды щелкните <code>vsmodtools.exe</code>.
<div lang="en" dir="ltr" class="mw-content-ltr">
Note: Unfortunately as of writing this Rider does not support those template options as Visual Studio in the UI yet but you can check this [https://youtrack.jetbrains.com/issue/RIDER-16759/Support-parameters-in-custom-project-templates issue] for updates.
For now you can make use of those options using the CLI see the  [[#Visual Studio Code|Visual Studio Code]] section for how to use it.
</div>


==== Linux ====
==== Visual Studio Code ====


Откройте терминал, перейдите в эту папку и введите <code>mono vsmodtools.exe</code>.
<div lang="en" dir="ltr" class="mw-content-ltr">
To create a new Mod using the template when using Visual Studio Code you have to resort to using the command line for now since there is no UI that supports the options as well.
Open a folder in Visual Studio Code where you want your mod to be. Then open the terminal within Visual Studio code ''Terminal'' > ''New Terminal''.
</div>  


==== Mac OS ====
<div lang="en" dir="ltr" class="mw-content-ltr">
* Create a new Mod Project with launch.json and task.json to easily start it and a Solution file. ''Other IDE's create that automatically so that is why we have this additional <code>--AddSolutionFile</code> flag for VS Code.''
<syntaxhighlight lang=shell>
dotnet new vsmod --IncludeVSCode --AddSolutionFile
</syntaxhighlight>
</div>


Дважды щелкните <code>modtools.command</code>.
<div lang="en" dir="ltr" class="mw-content-ltr">
For all possible options run the following in the terminal:
<syntaxhighlight lang=shell>
dotnet new vsmod --help
</syntaxhighlight>
</div>


[[File:ModTools.png]]
<div lang="en" dir="ltr" class="mw-content-ltr">
Once you opened or created a template Visual Studio will prompt you to install the recommended extension, click on ''Show Recommendations'' and install the the pre-release version of the [https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit C# Dev Kit] extension. This will also install the required [https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp C#] automatically for you.
These two extensions are recommended and will add Syntax highlighting, Autocomlet and many more much-needed features for writing C# code.
</div>


=== Настройка ===
<div lang="en" dir="ltr" class="mw-content-ltr">
==== Other / Commandline ====
If want to use the Commandline you can use all template options on the Commandline in any Terminal Application with the help of the ''dotnet'' command.
</div>


{{Syntax|setup [optional path]}}
<div lang="en" dir="ltr" class="mw-content-ltr">
* Create a new VS mod in the folder ''mytestmod'' in the current location of the terminal.
<syntaxhighlight lang=shell>
dotnet new vsmod --AddSolutionFile -o mytestmod
</syntaxhighlight>
</div>


Прежде чем делать что-либо еще, вы должны настроить свое рабочее пространство. Просто введите <code>setup</code>, и он автоматически попытается найти каталог установки Vintage Story. Если он не может найти его, вам будет предложено ввести полный путь. После того, как вы введете свой путь, он обновит файлы вашего проекта, чтобы вы могли начать с ним работать. Теперь снова откройте проект и запустите первый тест, нажав <code>Start</code> [[File:VSMods10.png]]. Если все настроено правильно, должна запуститься Vintage Story.
<div lang="en" dir="ltr" class="mw-content-ltr">
* or create a dll/code only mod
<syntaxhighlight lang=shell>
dotnet new vsmoddll --AddSolutionFile -o mytestmod
</syntaxhighlight>
</div>


=== Настройка проекта (ZIP) ===
<div lang="en" dir="ltr" class="mw-content-ltr">
For all possible options run the following in the terminal:
<syntaxhighlight lang=shell>
dotnet new vsmod --help
</syntaxhighlight>
</div>


Система исходных модов позволяет вам создавать zip-моды, которые могут отправлять исходный код помимо своих активов. Исходный код компилируется во время выполнения движком modloader. Это имеет большое преимущество в том, что оно открыто и легко модифицируется во время выполнения, но также имеет один существенный недостаток, заключающийся в том, что встроенный компилятор исходного кода может компилировать код только до версии C# 6.0, поэтому более новые функции языка не поддерживаются. Если это для вас шоу-стоппер, мы советуем вам собрать скомпилированный мод.
<div lang="en" dir="ltr" class="mw-content-ltr">
When using the Commandline you can specify these options like so:
</div>


==== Добавить мод ====
<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang=shell>
# Will create a new Mod Project with the dependency for VSSurvivalMod
dotnet new vsmod --AddSolutionFile --IncludeVSSurvivalMod -o mytestmod
</syntaxhighlight>
</div>


{{Syntax|add <modid>}}
<br>
----
<br>


Добавляет новый проект мода в вашу рабочую область, а также создает <code>assets</code>, папку <code>src</code> и файл <code>modinfo.json</code>. Мод будет добавлен в ваше визуальное студийное решение и загружен Vintage Story. Обязательно заполните всю дополнительную информацию в <code>modinfo.json</code>.
<div lang="en" dir="ltr" class="mw-content-ltr">
Finally in <code>mytestmod\mytestmod\modinfo.json</code>
change the <code>name</code>, <code>modid</code> , <code>authors</code> and <code>description</code> to describe your mod.
</div>


==== Удалить мод ====
==== Обновление шаблонов ====


{{Syntax|delete <modid>}}
Чтобы обновить все установленные шаблоны, выполните команду:
<syntaxhighlight lang=shell>
dotnet new update
</syntaxhighlight>


Перед выполнением убедитесь, что ваш проект закрыт, иначе вы можете столкнуться с некоторыми трудностями. Запуск этой команды полностью (необратимо) удалит данный мод.
Но это не обязательно при создании нового мода, так как команда <code>dotnet new vsmod</code> установить новую версию шаблона, если она доступна.


==== Упаковка мода ====
==== Структура папок ====
{{Syntax|pack <modid>}}


Создает zip-файл мода и помещает его в <code>/releases/<modid>/<modid>_v<modversion>.zip</code>. Этот файл готов к использованию и может быть передан другим людям.
Вот обзор того, где находятся файлы в вашем моде.
<table id="treeviewtable" class="table table-bordered tt-table" style='table-layout: fixed'>
  <tr style=''>
    <th width='300' align='left'>Название</th>
    <th width='600' align='left'>Описание</th>
  </tr>
  <tr>
    <td><div class="tt" data-tt-id="root">mytestmod</div></td>
    <td></td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_vscode" data-tt-parent="root">.vscode</div></td>
    <td>Если вы указали --IncludeVSCode, то эта папка будет содержать всё необходимое для запуска, упаковки и дебага вашего мода в Visual Studio Code.</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_cakebuild" data-tt-parent="root">CakeBuild</div></td>
    <td>Этот проект содержит код, который билдит mytestmod_x.x.x.zip. Вы можете выполнить его, выбрав CakeBuild в Run Configuration.</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_mytestmod" data-tt-parent="root">mytestmod</div></td>
    <td>Это ваш проект. Он содержит весь ваш код, ассеты и modinfo.json</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_assets" data-tt-parent="p_mytestmod">assets</div></td>
    <td>Ваши ассеты. Смотри '''{{pll|Modding:Asset System|nsp=0}}'''</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_modinfo" data-tt-parent="p_mytestmod">modinfo.json</div></td>
    <td>Описывает ваш мод. Автор, зависимости, название и многое другое. Смотри '''{{pll|Modinfo}}'''</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_properties" data-tt-parent="p_mytestmod">Properties</div></td>
    <td></td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_launchsettings" data-tt-parent="p_releases_properties">launchSettings.json</div></td>
    <td>Здесь содержится информация о том, как запустить ваш мод (Visual Studio, Rider). Вы можете добавить пользовательские параметры запуска, чтобы, например, при старте запускаться прямо в мир. Запустите Vintagestory.exe -h, чтобы увидеть все параметры из терминала, открытого в папке Vintagestory.</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_csproj" data-tt-parent="p_mytestmod">mymod.csproj</div></td>
    <td>csproj вашего мода. Содержит информацию о версии .NET и зависимостях (например, VintagestoryAPI).</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases" data-tt-parent="root">Releases</div></td>
    <td>Будет содержать релиз вашего мода после выполнения CakeBuild.</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_mymtestmod" data-tt-parent="p_releases">mytestmod</div></td>
    <td>Файлы мода перед упаковкой в .zip архив.</td>
  </tr>
  <tr>
    <td scope="row"><div class="tt" data-tt-id="p_releases_zip" data-tt-parent="p_releases">mytestmod_x.x.x.zip</div></td>
    <td>Готовый к релизу мод в виде zip-архива.</td>
  </tr>


{{Syntax|pack-all}}
</table>


Упаковывает все моды в вашем рабочем пространстве одновременно.
=== Проект-шаблон мода ===


=== Настройка проекта (скомпилированный ZIP) ===
<div lang="en" dir="ltr" class="mw-content-ltr">
Use the [https://github.com/anegostudios/vsmodtemplate Github Mod template] to create a new mod
</div>


И dll, и zip-моды имеют свои преимущества и недостатки, так почему бы не объединить их вместе? Настройка этого проекта очень похожа на zip. Вместо того, чтобы добавлять исходный код в zip-файл, он использует скомпилированную dll. Это позволяет вам иметь все преимущества dll, сохраняя при этом структуру активов zip mod.


==== Добавить мод ====
<div lang="en" dir="ltr" class="mw-content-ltr">
The Github Mod template provides an easy way to get the basics for mod setup so you can start directly with adding your modifications to the game.
</div>


{{Syntax|add <modid> compiled}}
<div lang="en" dir="ltr" class="mw-content-ltr">
* Without using git and Github account
</div>


Добавляет скомпилированный шаблон zip-мода в вашу рабочую область. Разница в том, что он использует скомпилированную dll вместо фактического исходного кода. Все остальные команды аналогичны zip.
<div lang="en" dir="ltr" class="mw-content-ltr">
To get a copy of the template click the <code><> Code</code> button on the GitHub repository site. Then download the template as ZIP file and extract it.
</div>


==== Установить мод ====
<div lang="en" dir="ltr" class="mw-content-ltr">
* Using Github and or git command
</div>


{{Syntax|set <modid> <source&#124;compiled>}}
<div lang="en" dir="ltr" class="mw-content-ltr">
You can directly click on <code>Use this template</code> on the GitHub repository site to create a copy of it to your GitHub account.
After that, you can clone your new repository to your computer.
</div>


Устанавливает данный zip-мод либо в исходный, либо в скомпилированный. Это может быть полезно, если вы захотите позже изменить тип вашего мода.
<div lang="en" dir="ltr" class="mw-content-ltr">
If you do not use GitHub just clone the repo and upload it to your preferred Git hosting provider (Gitlab, BitBucket, ...)
</div>


=== Настройка проекта (DLL) ===
<div lang="en" dir="ltr" class="mw-content-ltr">
<br>
With a local copy of the template, you can go ahead and open the ''ModTemplate.sln'' either in Visual Studio, Rider or Open the folder in Visual Studio Code. The Template is ready to use for any of the aforementioned IDE's. Now you can already start the mod with the game.
</div>


Модификации Dll намного мощнее исходных модов, но у них есть два основных недостатка. Во-первых, они не могут нести ресурсы, которые будут загружены игрой, во-вторых, потому что они настолько мощные, что могут быть опасны. Кроме того, моды dll могут (в отличие от других) иметь перекрестные ссылки на моды, предоставлять API и использовать C # 7. Мы рекомендуем этот тип модов для более опытных разработчиков модов.
<div lang="en" dir="ltr" class="mw-content-ltr">
When opened you need to change the following to release the mod since a mod has to have a unique ''modid'' for the VSModDB:
<br>
</div>


==== Добавить мод ====
<div lang="en" dir="ltr" class="mw-content-ltr">
In <code>modtemplate\resources\modinfo.json</code>
change the <code>name</code>, <code>modid</code> , <code>authors</code> and <code>description</code> to describe your mod.
</div>


{{Syntax|add-dll <modid>}}
<div lang="en" dir="ltr" class="mw-content-ltr">
For a full list of available options see '''[[Modinfo | Modinfo]]'''.
</div>


Добавляет новый проект мода в вашу рабочую область. Сгенерированный файл <code>AssemblyInfo.cs</code> будет находиться в вашей папке свойств, он содержит информацию о моде (имя, автор, версия, описание и т. д.), поэтому обязательно измените их, прежде чем распространять мод среди других людей. . Мод будет добавлен в ваше визуальное студийное решение и загружен VintageStory.
<div lang="en" dir="ltr" class="mw-content-ltr">
The <code>modid</code> has to contain only lowercase letters and numbers. No special chars, whitespaces, uppercase letters, etc. are allowed.
</div>


==== Удалить мод ====
<div lang="en" dir="ltr" class="mw-content-ltr">
Next, rename the folder <code>modtemplate\resources\assets\mymodid</code> to match what your <code>modid</code> is.
</div>


{{Syntax|delete <modid>}}
<div lang="en" dir="ltr" class="mw-content-ltr">
Finally change in the file <code>modtemplate\modtemplateModSystem.cs</code> the line
<syntaxhighlight lang=cs>
Lang.Get("mymodid:hello")
</syntaxhighlight>
from <code>mymodid</code> to your new modid.
</div>


Перед выполнением убедитесь, что ваш проект закрыт, иначе вы можете столкнуться с некоторыми трудностями. Запуск этой команды полностью (необратимо) удалит данный мод.
<div lang="en" dir="ltr" class="mw-content-ltr">
The file <code>modtemplate\modtemplateModSystem.cs</code> can be called whatever you like.
</div>


==== Выпуск Мода ====
<div lang="en" dir="ltr" class="mw-content-ltr">
(Optional) Further, you can change the name <code>ModTemplate</code> to whatever you like as long as you change all of the following:
* Folder <code>ModTemplate</code>
* File <code>ModTemplate\ModTemplate.csproj</code>
* In File <code>CakeBuild\Program.cs</code> on line
<syntaxhighlight lang=cs>
ProjectName = "ModTemplate";
</syntaxhighlight>
</div>


Как только вы запустите VintageStory в своей рабочей области, мод DLL будет скомпилирован. Вы можете найти его в папке <code>mods</code> под именем: <code><modid>.dll</code>. Если вы хотите загрузить этот мод или поделиться им с друзьями, вам нужно использовать этот файл.
<div lang="en" dir="ltr" class="mw-content-ltr">
''If you are on linux and used the Github Template'' make sure to update in <code>ModTemplate\Properties\launchSettings.json</code> the <code>executablePath</code>. There you need to remove the <code>.exe</code>
</div>


== Ручная настройка ==
=== Запуск мода ===


* Создать новый проект
==== Запуск мода в Visual Studio ====
* Добавьте как минимум ссылку на библиотеку <code>VintageStoryApi.dll</code> (в Windows она находится в каталоге установки)
[[File:Vs-cp-start.png|600px|frameless|center|alt=Запуск мода в Visual Studio|Запуск мода в Visual Studio]]
* Откройте свойства проекта. В разделе отладки выберите «Запустить внешнюю программу», выберите <code>VintageStory.exe</code>. Также настройте рабочий каталог, в котором находится исполняемый файл.
* Если вы компилируете в файл .dll, настройте атрибут ModInfo в файле AssemblyInfo.cs ([пример https://github.com/anegostudios/vsmodtemplate/blob/master/Properties/AssemblyInfo.cs])
** Добавьте следующие аргументы командной строки: <code>-openWorld="modsamplestest" -pcreativebuilding --addModPath="C:\path\to\your\bin\folder" --addOrigin="C:\path\to\your\assets\folder\if\you\have\any"</code>
* Если вы хотите отправить исходный мод или мод с активами, настройте <code>modinfo.json</code> ([https://github.com/copygirl/CarryCapacity/blob/master/resources/modinfo.json пример ]). Убедитесь, что ваши папки настроены таким образом, что modPath содержит modinfo.json и папку с именем «src», содержащую ваши исходные файлы. При желании он также может содержать папку активов для ваших активов.
** Добавьте следующие аргументы командной строки: <code>-openWorld="modsamplestest" -pcreativebuilding --addModPath="C:\path\to\your\modPath"</code>
* Я рекомендую добавить в ваш проект файл [https://github.com/anegostudios/vsmodexamples/blob/master/Mods/RedirectLogs/src/RedirectLogs.cs RedirectLogs.cs], чтобы вы могли видеть вывод журнала в своем Окно вывода визуальной студии. Однако не отправляйте свой мод вместе с ним.
* Запустите проект и надейтесь на лучшее :D
* Чтобы отправить мод, посмотрите [[Mod Packaging/ru|Упаковка мода]]


Если у вас возникли проблемы, вы можете узнать из проекта [https://github.com/anegostudios/vsmodexamples vsmodexamples]
==== Запуск мода в Rider ====
<gallery mode="packed-hover" widths=500px heights=100px>
File:Rider-cp-start-new-ui.png|Запуск мода в Rider (Новый UI)
File:Rider-cp-start.png|Запуск мода в Rider
</gallery>
==== Запуск мода в Visual Studio Code ====
[[File:Vsc-cp-start.png|400px|frameless|center|alt=Запуск мода в Visual Studio Code|Запуск мода в Visual Studio Code]]
 
Если у вас возникли проблемы, вы можете узнать больше из проекта [https://github.com/anegostudios/vsmodexamples vsmodexamples]
 
== Упаковка мода ==
 
<div lang="en" dir="ltr" class="mw-content-ltr">
With the new template, we are using the [https://cakebuild.net/ Cake] build system. This includes a second Project within the Solution in the template.
In all supported IDE's you can select from the dropdown that you used to launch the mod the <code>CakeBuild</code> option and run it.
''When using Visual Studio Code you can also create a package by running the package task. For that got to <code>Terminal</code> > <code>Run Task...</code> and select <code>package</code>.''
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
It will perform a JSON validation on your assets so they are at least parsable by Newtonsoft.Json and then build a <code>Releases/mymodid_1.0.0.zip</code>. The version is taken from the <code>mymod/modinfo.json</code> file.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
Congratulations now you have your mod development environment set up and a ready-to-release mod package.
</div>
 
<div lang="en" dir="ltr" class="mw-content-ltr">
Note: Make sure you use your own unique <code>modid</code> else you won't be able to upload the mod to the VSModDB.
</div>


= Дальнейшее продвижение =
= Дальнейшее продвижение =


Если вам удалось настроить среду разработки и запустить Vintage Story через проект '''VSMods''' в вашей среде IDE, то пришло время приступить к работе над своим первым модом кода. На данный момент есть много вариантов, которые вы можете выбрать, поскольку моды кода могут изменить практически любой аспект игры. Тем не менее, лучше всего начать с блоков и элементов (поскольку к этому моменту вы уже должны быть знакомы с их созданием с использованием JSONS).
Если вам удалось настроить среду разработки и запустить Vintage Story через проект мода в вашей IDE, то пришло время приступить к работе над своим первым модом кода. На данный момент есть много вариантов, которые вы можете выбрать, поскольку моды кода могут изменить практически любой аспект игры. Тем не менее, лучше всего начать с блоков и элементов (поскольку к этому моменту вы уже должны быть знакомы с их созданием используя JSON-ы).
 
Перейдите на страницу '''[[Modding:Advanced Blocks/ru|Расширенные блоки]]''', чтобы создать свой первый расширенный блок кода.


Или перейдите на страницу '''[[Modding:Advanced Items/ru|Расширенные элементы]]''', чтобы создать свой первый расширенный элемент кода.
Перейдите на страницу '''[[Modding:Advanced Blocks/ru|Продвинутые блоки]]''', чтобы создать свой первый продвинутый блок кода.


{{Navbox/modding/ru|Vintage Story}}
Или перейдите на страницу '''{{Not translated|Modding:Advanced Items/ru|Продвинутые предметы|Modding:Advanced Items}}''', чтобы создать свой первый продвинутый предмет кода.
{{Navbox/modding}}

Latest revision as of 10:32, 6 December 2023

Other languages:

Эта страница проверялась в последний раз для версии Vintage Story 1.18.8-rc.1.


Программное обеспечение

Когда вы будете готовы приступить к кодированию модов для Vintage Story, вы, вероятно, захотите настроить среду разработки, которая упростит процесс кодирования и тестирования ваших творений. Vintage Story разрабатывается на C# и начиная с версии 1.18.8 мы перешли на .NET 7.

Есть несколько приложений, которые помогут вам в разработке модов. Вот некоторые из них, поддерживающие наш шаблон:

  • Visual Studio Community — это бесплатная и очень мощная среда разработки от Microsoft и, возможно, имеет наилучшую поддержу С# и .NET, которые в свою очередь тоже разработаны Microsoft. Это также инструмент, который команда Vintage Story использует при билде игры. Она также имеет MacOS версию. При использовании установите пакет .NET desktop development.
  • Jetbrains Rider — это платная, мощная и удобная среда разработки специально спроектированная для .NET. Поскольку она создана для .NET, она также имеет очень хорошую поддержку всех функций, которые могут вам понадобиться, и при этом является полностью кроссплатформенной. Она также используется командой Vintage Story при разработке игры.
  • Visual Studio Code — это бесплатный, лёгкий и универсальный редактор кода, разработанный Microsoft. Он поддерживает множество языков программирования и предлагает широкий выбор функциональных расширений. Расширение для поддержки C# — отличный выбор для начала создания модов. Этот редактор широко используется нашим сообществом мододелов.

Хоть вы и можете использовать любой редактор для работы с исходном кодом, мы настоятельно рекомендуем использовать один из вышеперечисленных инструментов, чтобы ваши процессы стали гораздо удобнее.

Выберите одну из вышеперечисленных IDE или другие альтернативы. Мы предлагаем использовать Visual Studio Community для Windows. Для Linux вы можете использовать Visual Studio Code или Rider.

Примечание: Если вы используете Linux и собираетесь ставить Visual Studio Code или Rider из Flatpak или snap? имейте в виду, что могут возникнуть некоторые проблемы с использованием .NET или переменных среды. Так что, по возможности используйте нативные методы установки.


Далее вам нужно будет установить .NET 7 SDK (Комплект для разработки программного обеспечения), который также будет включать .NET 7 Dekstop Runtime, необходимый для запуска игры начиная с версии 1.18.8-rc.1.

Убедитесь, что .NET 7 SDK установился правильно, выполнив следующую команду в терминале:

В Windows откройте приложение Windows PowerShell, которое предустановлено во всех современных версиях Windows (10 / 11).

dotnet --list-sdks

Она выведет список установленных SDK, одна из которых, должна иметь 7.0.xxx. Если это так, то можете продолжать.

Setup the Environment

Our Mod template makes use of the environment variable VINTAGE_STORY. Which we will set up to contain the path of where your game is installed. The use of the environment helps to keep the setup and the template simple so we recommend using it and will cover it in this article.

The VINTAGE_STORY Environment Variable simplifies reusing your Vintage Story game installation path and helps if multiple modders work on the same project to reference the VINTAGE_STORY Environment Variable and have their game installed where ever they want.

Windows

Here you have two options to set the environment variable:

  • Use this short PowerShell script. Open the Windows PowerShell Application and paste the following into it and hit ENTER
[Environment]::SetEnvironmentVariable("VINTAGE_STORY", "$Env:AppData\Vintagestory", "User")

Change $Env:AppData\Vintagestory if you used a custom installation path for your game.

  • Follow these manual steps to set the Environment variable

Search in Windows search for Edit the system environment variables > Environment Variables... > User variables for USER > New > Add insert the Variable name: VINTAGE_STORY and add the path to your Vintage Story installation.

Setup Windows environment variable

For example, the default installation directory would be C:\Users\<Username>\AppData\Roaming\Vintagestory, (replace <Username> with your username) if you are not sure where yours is type %appdata% into the URL field in the File Explorer and hit ENTER. It will take you to your AppData\Roaming folder where Vintage Story should be installed if you haven't changed the default installation location.

find the default installation path of vintage story

Note: Do not confuse the AppData\Roaming\VintagestoryData directory with the AppData\Roaming\Vintagestory folder. The VintagestoryData directory only holds your Settings, Logs, Savegames and Mods.

Linux and Mac

To set an environment variable in Linux/Mac you need to add the following to your shells startup file:

export VINTAGE_STORY="$HOME/ApplicationData/vintagestory"

Replace the path with the one where your Vintagestory installation is located. The above path should point to your install when you installed Vintagestory using the install.sh script.

Run echo $SHELL in a terminal to see what shell you are using.

  • For Bash place it in: ~/.bashrc or ~/.bash_profile at the end
  • For Zsh place it in: ~/.zshrc or ~/.zprofile at the end
  • If you use another shell see their documentation on how their shell startup file is called

Note: If you are using ~/.bash_profile or ~/.zprofile you will have to Logout and Login again to apply the changes. When using ~/.bashrc or ~/.zshrc you only need to restart the application that needs to use the environment variable (Visual Studio, Rider, Visual Studio Code, Terminal).


Создание мода

Mod Template package

The first and recommended option would be to use the template package.

Install the mod Mod template package using the following command on the Terminal:

dotnet new install VintageStory.Mod.Templates

This will download the latest mod template package from nuget.org

Once the template is installed you will see it inside Visual Studio and Rider. From there you can use the templates to create a new Project.


Visual Studio

We advise you to check the option Place solution and project in the same directory for Visual Studio This will flatten the project tree by one folder and make it easier to navigate.

If you don't want the log output to show up in a separate window you can check the option SuppressWindowsConsoleWindow. When enabled the log output will still be shown inside the Visual Studio Debug Output.

Open Visual Studio and click on Create a new project. If you installed the VintageStory.Mod.Templates you can then select Vintage Story Mod.

Rider

We advise you to check the option Put solution and project in the same directory for Rider. This will flatten the project tree by one folder and make it easier to navigate.

Open Rider and click on New Solution. If you installed the VintageStory.Mod.Templates you can then select Vintage Story Mod.

Rider Mod Template


Note: Unfortunately as of writing this Rider does not support those template options as Visual Studio in the UI yet but you can check this issue for updates. For now you can make use of those options using the CLI see the Visual Studio Code section for how to use it.

Visual Studio Code

To create a new Mod using the template when using Visual Studio Code you have to resort to using the command line for now since there is no UI that supports the options as well. Open a folder in Visual Studio Code where you want your mod to be. Then open the terminal within Visual Studio code Terminal > New Terminal.

  • Create a new Mod Project with launch.json and task.json to easily start it and a Solution file. Other IDE's create that automatically so that is why we have this additional --AddSolutionFile flag for VS Code.
dotnet new vsmod --IncludeVSCode --AddSolutionFile

For all possible options run the following in the terminal:

dotnet new vsmod --help

Once you opened or created a template Visual Studio will prompt you to install the recommended extension, click on Show Recommendations and install the the pre-release version of the C# Dev Kit extension. This will also install the required C# automatically for you. These two extensions are recommended and will add Syntax highlighting, Autocomlet and many more much-needed features for writing C# code.

Other / Commandline

If want to use the Commandline you can use all template options on the Commandline in any Terminal Application with the help of the dotnet command.

  • Create a new VS mod in the folder mytestmod in the current location of the terminal.
dotnet new vsmod --AddSolutionFile -o mytestmod
  • or create a dll/code only mod
dotnet new vsmoddll --AddSolutionFile -o mytestmod

For all possible options run the following in the terminal:

dotnet new vsmod --help

When using the Commandline you can specify these options like so:

# Will create a new Mod Project with the dependency for VSSurvivalMod
dotnet new vsmod --AddSolutionFile --IncludeVSSurvivalMod -o mytestmod




Finally in mytestmod\mytestmod\modinfo.json change the name, modid , authors and description to describe your mod.

Обновление шаблонов

Чтобы обновить все установленные шаблоны, выполните команду:

dotnet new update

Но это не обязательно при создании нового мода, так как команда dotnet new vsmod установить новую версию шаблона, если она доступна.

Структура папок

Вот обзор того, где находятся файлы в вашем моде.

Название Описание
mytestmod
.vscode
Если вы указали --IncludeVSCode, то эта папка будет содержать всё необходимое для запуска, упаковки и дебага вашего мода в Visual Studio Code.
CakeBuild
Этот проект содержит код, который билдит mytestmod_x.x.x.zip. Вы можете выполнить его, выбрав CakeBuild в Run Configuration.
mytestmod
Это ваш проект. Он содержит весь ваш код, ассеты и modinfo.json
assets
Ваши ассеты. Смотри Модинг:Система ассетов
modinfo.json
Описывает ваш мод. Автор, зависимости, название и многое другое. Смотри Модинфо
Properties
launchSettings.json
Здесь содержится информация о том, как запустить ваш мод (Visual Studio, Rider). Вы можете добавить пользовательские параметры запуска, чтобы, например, при старте запускаться прямо в мир. Запустите Vintagestory.exe -h, чтобы увидеть все параметры из терминала, открытого в папке Vintagestory.
mymod.csproj
csproj вашего мода. Содержит информацию о версии .NET и зависимостях (например, VintagestoryAPI).
Releases
Будет содержать релиз вашего мода после выполнения CakeBuild.
mytestmod
Файлы мода перед упаковкой в .zip архив.
mytestmod_x.x.x.zip
Готовый к релизу мод в виде zip-архива.

Проект-шаблон мода

Use the Github Mod template to create a new mod


The Github Mod template provides an easy way to get the basics for mod setup so you can start directly with adding your modifications to the game.

  • Without using git and Github account

To get a copy of the template click the <> Code button on the GitHub repository site. Then download the template as ZIP file and extract it.

  • Using Github and or git command

You can directly click on Use this template on the GitHub repository site to create a copy of it to your GitHub account. After that, you can clone your new repository to your computer.

If you do not use GitHub just clone the repo and upload it to your preferred Git hosting provider (Gitlab, BitBucket, ...)


With a local copy of the template, you can go ahead and open the ModTemplate.sln either in Visual Studio, Rider or Open the folder in Visual Studio Code. The Template is ready to use for any of the aforementioned IDE's. Now you can already start the mod with the game.

When opened you need to change the following to release the mod since a mod has to have a unique modid for the VSModDB:

In modtemplate\resources\modinfo.json change the name, modid , authors and description to describe your mod.

For a full list of available options see Modinfo.

The modid has to contain only lowercase letters and numbers. No special chars, whitespaces, uppercase letters, etc. are allowed.

Next, rename the folder modtemplate\resources\assets\mymodid to match what your modid is.

Finally change in the file modtemplate\modtemplateModSystem.cs the line

Lang.Get("mymodid:hello")

from mymodid to your new modid.

The file modtemplate\modtemplateModSystem.cs can be called whatever you like.

(Optional) Further, you can change the name ModTemplate to whatever you like as long as you change all of the following:

  • Folder ModTemplate
  • File ModTemplate\ModTemplate.csproj
  • In File CakeBuild\Program.cs on line
ProjectName = "ModTemplate";

If you are on linux and used the Github Template make sure to update in ModTemplate\Properties\launchSettings.json the executablePath. There you need to remove the .exe

Запуск мода

Запуск мода в Visual Studio

Запуск мода в Visual Studio

Запуск мода в Rider

Запуск мода в Visual Studio Code

Запуск мода в Visual Studio Code

Если у вас возникли проблемы, вы можете узнать больше из проекта vsmodexamples

Упаковка мода

With the new template, we are using the Cake build system. This includes a second Project within the Solution in the template. In all supported IDE's you can select from the dropdown that you used to launch the mod the CakeBuild option and run it. When using Visual Studio Code you can also create a package by running the package task. For that got to Terminal > Run Task... and select package.

It will perform a JSON validation on your assets so they are at least parsable by Newtonsoft.Json and then build a Releases/mymodid_1.0.0.zip. The version is taken from the mymod/modinfo.json file.

Congratulations now you have your mod development environment set up and a ready-to-release mod package.

Note: Make sure you use your own unique modid else you won't be able to upload the mod to the VSModDB.

Дальнейшее продвижение

Если вам удалось настроить среду разработки и запустить Vintage Story через проект мода в вашей IDE, то пришло время приступить к работе над своим первым модом кода. На данный момент есть много вариантов, которые вы можете выбрать, поскольку моды кода могут изменить практически любой аспект игры. Тем не менее, лучше всего начать с блоков и элементов (поскольку к этому моменту вы уже должны быть знакомы с их созданием используя JSON-ы).

Перейдите на страницу Продвинутые блоки, чтобы создать свой первый продвинутый блок кода.

Или перейдите на страницу Продвинутые предметы en, чтобы создать свой первый продвинутый предмет кода.

Icon Sign.png

Wondering where some links have gone?
The modding navbox is going through some changes! Check out Navigation Box Updates for more info and help finding specific pages.

Modding
Modding Introduction Getting Started Пакет тем
Content Modding Content Mods Developing a Content Mod Basic Tutorials Intermediate Tutorials Advanced Tutorials Content Mod Concepts
Code Modding Code Mods Setting up your Development Environment
Property Overview ItemEntityBlockBlock BehaviorsBlock ClassesBlock EntitiesBlock Entity BehaviorsWorld properties
Workflows & Infrastructure Modding Efficiency TipsMod-engine compatibilityMod ExtensibilityVS Engine
Additional Resources Community Resources Modding API Updates Programming Languages List of server commandsList of client commandsClient startup parametersServer startup parameters
Example ModsAPI DocsGitHub Repository