This page has been translated automatically.
Видеоуроки
Interface
Essentials
Advanced
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Настройки и предпочтения
Работа с проектами
Настройка параметров узла
Setting Up Materials
Настройка свойств
Освещение
Landscape Tool
Sandworm
Использование инструментов редактора для конкретных задач
Extending Editor Functionality
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World Objects
Звуковые объекты
Объекты поиска пути
Players
Программирование
Настройка среды разработки
Примеры использования
UnigineScript
C++
C#
Унифицированный язык шейдеров UUSL
File Formats
Rebuilding the Engine Tools
GUI
Двойная точность координат
API
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Art Samples
Tutorials
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

Система логики приложения

In UNIGINE, you can implement application logic in the following ways:В UNIGINE вы можете реализовать логику приложения следующими способами:

  • in C++ or C#На C++ или C#
  • combining C++ or C# with UnigineScript — in this case, the execution sequence for each implemented method, corresponding to a certain stage of the application's life cycle (i.e., init(), update(), postUpdate(), etc.), is the following:
    1. UnigineScript functionUnigineScript function
    2. C++/C# methodC++/C# method
    UnigineScript functionC++/C# method
    Сочетая C++ или C# с UnigineScript - в данном случае последовательность выполнения для каждого реализованного метода, соответствующая определенному этапу жизненного цикла приложения (т.е.init(), update(), postUpdate()и т.д.) выглядит следующим образом:
    1. UnigineScript functionФункция UnigineScript
    2. C++/C# methodC++ / C# метод

The application logic has three basic components that have different lifetimes: Логика приложения состоит из трех основных компонентов, которые имеют разное время жизни:

  • World logic. It takes effect only when the world is loaded. For projects that use UnigineScript only, the logic is written to the world script (each particular world can have its own script). A default script is created as a *.usc file named after your project at the project creation. Such files are stored in the data/ folder.
    For applications that use C++ AppWorldLogic.cpp is created, and for C# applications — AppWorldLogic.cs. These files are stored in the <your_project_folder>/source/ folder and stay loaded during the whole engine runtime. They have implemented methods to put your logic code inside. WorldLogic in C++/C# (unlike UnigineScript) works with every loaded world, so you can't assign a specific WorldLogic to a certain world.
    World logic. Существует только тогда, когда мир загружен. Для проектов, использующих только UnigineScript, логика записывается в скрипт мира (каждый мир может иметь свой собственный сценарий). Этот сценарий по умолчанию генерируется как файл *.usc, с именем вашего проекта при его создании. Такие файлы хранятся в папке data/.
    Для приложений, использующих C++, создается AppWorldLogic.cpp, а для приложений C# - AppWorldLogic.cs. Эти файлы хранятся в папке <your_project_folder>/source/ и остаются загруженным в течение всего времени работы движка. В них реализованы методы в которые вы можете поместить свой код. WorldLogic в C++/C# (в отличие от UnigineScript) работает с каждым загруженным миром, поэтому конкретный WorldLogic определенному миру назначить нельзя.
  • System logic. It exists during the application life cycle. The logic is implemented in the default system script named unigine.usc and stored in the data/ folder of your project as the core.ung archive. You can put your logic in this file if you use UnigineScript only. You can also inherit SystemLogic class and implement your logic in C++ or C#. System logic. Существует в течение всего жизненного цикла приложения. Логика реализована в системном скрипте по умолчанию с именем unigine.usc и хранится в папке data/ вашего проекта в виде архива core.ung. Вы можете поместить свою логику в этот файл, если используете только UnigineScript. Вы также можете унаследовать класс SystemLogic и реализовать свою логику на C++ или C#.
  • Editor logic. This component is to be used in case you need to implement your own Editor. It has more implemented methods providing you with clear understanding of the current Engine events (a node has been created, a property has been deleted, a material has been changed, etc.). You can inherit EditorLogic class and implement your logic in C++ or C#. Or you can create a UnigineScript file and add it using the -editor_script path_to_file.usc command-line argument.
    Примечание
    When you create a new C++ / C# project, it has already inherited World Logic class (AppWorldLogic), System Logic class (AppSystemLogic), and Editor Logic class (AppEditorLogic) with implemented methods to put your logic code inside. When you create a new C++ / C# project, it has already inherited World Logic class (AppWorldLogic), System Logic class (AppSystemLogic), and Editor Logic class (AppEditorLogic) with implemented methods to put your logic code inside.
    When you create a new C++ / C# project, it has already inherited World Logic class (AppWorldLogic), System Logic class (AppSystemLogic), and Editor Logic class (AppEditorLogic) with implemented methods to put your logic code inside.
    Editor logic. Этот компонент следует использовать в случае, если вам нужен собственный редактор. В нем реализовано больше методов, дающих вам четкое представление о текущих событиях Engine (создана нода, удалено свойство, изменен материал и т.д.). Вы можете унаследовать свой класс от класса EditorLogic и реализовать свою логику на C++ или C#. Или можно создать файл UnigineScript и добавить его с помощью аргумента командной строки "-editor_script path_to_file.usc".
    Примечание
    When you create a new C++ / C# project, it has already inherited World Logic class (AppWorldLogic), System Logic class (AppSystemLogic), and Editor Logic class (AppEditorLogic) with implemented methods to put your logic code inside. Когда вы создаете новый C++/C# проект, он уже имеет унаследованый класс логики мира ( AppWorldLogic ), класс системной логики (AppSystemLogic) и класс логики редактора (AppEditorLogic) с реализованными методами для помещения кода вашей логики.

If a project uses UnigineScript only, its execution sequence is strictly defined in scripts and cannot be modified.
If a project is created using C++ or C#, a programmer can control the execution sequence by manually calling Engine's init(), update(), postUpdate(), swap(), and shutdown() methods when required and add logic anywhere between these blocks, as shown in the C++ sample <UnigineSDK>/source/samples/Api/Render/Screenshot/Screenshot.cpp.
Если в проекте используется только UnigineScript, то для него последовательность исполнения строго определена в скриптах и не может быть изменена.
Если проект создается с использованием C++ или C#, программист может контролировать последовательность выполнения, вручную вызывая методы Engine init(), update(), postUpdate(), swap() и shutdown(), когда это необходимо, и добавлять логику в любом месте между этими блоками, как показано в примере C++ <UnigineSDK>/source/samples/Api/Render/Screenshot/Screenshot.cpp.

World LogicЛогика мира (World Logic)#

If the World Logic is implemented in UnigineScript, it is loaded or unloaded at the same time as the world itself is loaded or unloaded. The World Logic implemented in C++/C# stays loaded during the whole UNIGINE engine runtime. The World Logic may use the following methods, which are available for both UnigineScript and C++/C#: Если логика мира реализована на UnigineScript, она загружается или выгружается одновременно с загрузкой или выгрузкой самого мира. Логика мира, реализованная на C++ / C#, остается загруженной в течение всего времени работы движка UNIGINE. World Logic может использовать следующие методы, доступные как для UnigineScript, так и для C++ / C#:

Исходный код (C++)
#include "AppWorldLogic.h"

AppWorldLogic::AppWorldLogic() {

}

AppWorldLogic::~AppWorldLogic() {

}

int AppWorldLogic::init() {

	return 1;
}

int AppWorldLogic::update() {

	return 1;
}

int AppWorldLogic::postUpdate() {

	return 1;
}

int AppWorldLogic::updatePhysics() {

	return 1;
}

int AppWorldLogic::shutdown() {

	return 1;
}

int AppWorldLogic::save(const Unigine::StreamPtr &stream) {
	UNIGINE_UNUSED(stream);
	return 1;
}

int AppWorldLogic::restore(const Unigine::StreamPtr &stream) {
	UNIGINE_UNUSED(stream);
	return 1;
}

init() functionФункция init()#

Engine calls this function on the world initialization. The code inside should initialize resources for your world scene during the world start.Движок вызывает эту функцию при инициализации мира. Код внутри должен инициализировать ресурсы для вашей сцены во время запуска мира.

updateAsyncThread() functionФункция updateAsyncThread()#

In the updateAsyncThread() function, you can specify all logic functions you want to be called every frame independently of the rendering thread. This function does not block the Main Thread.В функции updateAsyncThread() вы можете указать все логические функции, которые вы хотите вызывать в каждом кадре независимо от потока рендеринга. Эта функция не блокирует основной поток.

Примечание
This function does not have protection locks, so it is not recommended to modify other components inside this function, unless you are absolutely sure, that these components won't be modified or removed elsewhere.Эта функция не имеет защитных блокировок, поэтому не рекомендуется изменять другие компоненты внутри этой функции, если вы не уверены, что эти компоненты не будут изменены или удалены где-либо еще.

updateSyncThread() functionФункция updateSyncThread()#

In the updateSyncThread() function, you can specify any parallel logic functions to be executed before the Update(). This function blocks the Main Thread until all calls are completed.В функции updateSyncThread() вы можете указать любые функции параллельной логики, которые будут выполняться перед Update(). Эта функция блокирует основной поток до тех пор, пока не будут завершены все вызовы.

Примечание
This function should be used to call only the API methods related to the current node: the node itself, its materials and properties.Эта функция должна использоваться для вызова только методов API, относящихся к текущей ноде: самой ноде, ее материалам и свойствам.

update() functionФункция update()#

In the update() function, you can specify all logic-related functions you want to be called every frame while your application is executed. Engine calls this function before updating each render frame.В функции update() вы можете указать все связанные с логикой функции, которые вы хотите вызывать в каждом кадре во время выполнения вашего приложения. Движок вызывает эту функцию перед обновлением каждого кадра рендеринга.

postUpdate() functionФункция postUpdate()#

This is an additional function used to correct behavior after the state of the node has been updated. Engine calls this function before rendering each render frame.Это дополнительная функция, используемая для исправления поведения после обновления состояния ноды. Движок вызывает эту функцию перед рендерингом каждого кадра.

updatePhysics() functionФункция updatePhysics()#

This function is used to control physics in your application. Engine calls this function before updating each physics frame.Эта функция используется для управления физикой в вашем приложении. Движок вызывает эту функцию перед обновлением каждого кадра физики.

swap() functionФункция swap()#

This function is designed to operate with the results of the updateAsyncThread() function — all other methods (threads) have already been performed and are idle. After this function, only two actions occur:Эта функция предназначена для работы с результатами функции updateAsyncThread() - все остальные методы (потоки) уже выполнены и простаивают. После этой функции происходят только два действия:

  • All objects that are queued for deletion are deleted.Все объекты, поставленные в очередь на удаление, удаляются.
  • Profiler is updated.Профайлер обновлен.

shutdown() functionФункция shutdown()#

The function is called when the world is unloaded, and is used to delete resources that were created during world script execution to avoid memory leaks. Engine calls this function on the world shutdown. Inside this function, you should delete all pointers to created objects.Функция вызывается, когда мир выгружается, и используется для удаления ресурсов, которые были созданы во время выполнения сценария мира, чтобы избежать утечек памяти. Движок вызывает эту функцию при выключении мира. Внутри этой функции вы должны удалить все указатели на созданные объекты.

save() and restore() functionsФункции save() и restore()#

The save() function saves custom user data to a file. Engine calls this function when the world is saving its state. To restore data from a file, you need to use the restore() function. Engine calls this function when the world is restoring its state.Функция save() сохраняет пользовательские данные в файл. Движок вызывает эту функцию, когда мир сохраняет свое состояние (state). Чтобы восстановить данные из файла, вам нужно использовать функцию restore(). Движок вызывает эту функцию, когда мир восстанавливает свое состояние (state).

Примечание
The basic recommended workflow is to have a single AppWorldLogic class to process all worlds in your project. However, you can split world-specific code between separate classes inherited from WorldLogic.Основной рекомендуемый подход - иметь один класс AppWorldLogic для обработки всех миров в вашем проекте. Однако вы можете разделить специфичный для мира код между отдельными классами унаследованными от WorldLogic.

System LogicСистемная логика (System Logic)#

The System Logic stays loaded during the whole UNIGINE Engine runtime. It may use the following methods, which are available for both UnigineScript and C++/C#: Системная логика остается загруженной в течение всего времени работы UNIGINE Engine. Могут использоваться следующие методы, доступные как для UnigineScript, так и для C++ / C#:

Исходный код (C++)
#include "AppSystemLogic.h"

AppSystemLogic::AppSystemLogic() {

}

AppSystemLogic::~AppSystemLogic() {

}

int AppSystemLogic::init() {
	return 1;
}

int AppSystemLogic::update() {
	return 1;
}

int AppSystemLogic::postUpdate() {
	return 1;
}

int AppSystemLogic::shutdown() {
	return 1;
}

int AppSystemLogic::destroyRenderResources() {
	return 1;
}

init() functionФункция init()#

Engine calls this function on initialization. Here you should put the code that you want to be executed during the system script initialization.Движок вызывает эту функцию при инициализации. Здесь вы можете поместить код, который вы хотите выполнить при инициализации системного скрипта.

update() functionФункция update()#

Engine calls this function before updating each render frame. Here you should put the code that you want to be updated each frame. The logic should be related to the engine job. These are the examples of operations that are performed by a default system script:Движок вызывает эту функцию перед обновлением каждого кадра рендеринга. Здесь вы можете поместить код, который вы хотите обновлять каждый кадр. Логика должна быть связана с работой движка. Это примеры операций, выполняемых системным скриптом по умолчанию:

  • The system script handles the mouse. It controls whether the mouse is grabbed when clicked (by default), the mouse cursor disappears when not moved for some time, or not handled by the system.Системный скрипт обрабатывает события от мыши. Он контролирует, захватывается ли мышь при нажатии (по умолчанию), курсор мыши исчезает, если не перемещается в течение некоторого времени, или не обрабатывается системой.
  • Main menu logic is updated.Обновление логики главного меню.
  • Other system-related user input is handled.Обработка другого пользовательского ввода, связанного с системой.

postUpdate() functionФункция postUpdate()#

Engine calls this function before rendering each render frame. It can access the updated data on node states and correct the behavior accordingly in the same frame.Движок вызывает эту функцию перед рендерингом каждого кадра. Он может получить доступ к обновленным данным о состояниях нод и соответствующим образом скорректировать поведение в том же кадре.

shutdown() functionФункция shutdown()#

Engine calls this function on application shutdown. You should release all the resources that you created for system script.Движок вызывает эту функцию при завершении работы приложения. Вы должны освободить все ресурсы, которые вы создали для системного скрипта.

destroyRenderResources() functionФункция destroyRenderResources()#

Engine calls this function when the video mode is changed or application is restarted (i.e. video_restart is called). It is used to reinitialize the graphics context if application directly uses any OpenGL or DirectX commands).Движок вызывает эту функцию при изменении видеорежима или перезапуске приложения (т.е. вызывается video_restart). Она используется для повторной инициализации графического контекста, если приложение напрямую использует какие-либо команды OpenGL или DirectX).

Editor LogicЛогика редактора (Editor Logic)#

This component is to be used in case you need to implement your own Editor. It has more implemented methods providing you with clear understanding of the current Engine events (a node has been created, a property has been deleted, a material has been changed, etc.).Этот компонент следует использовать в случае, если вам нужен собственный редактор. В нем реализовано больше методов, дающих вам четкое представление о текущих событиях Engine (создана нода, удалено свойство, изменен материал и т.д.).

The Editor Logic may use the following methods, which are available for both UnigineScript and C++/C#: Логика редактора может использовать следующие методы, доступные как для UnigineScript, так и для C++ / C#:

Исходный код (C++)
#include "AppEditorLogic.h"

AppEditorLogic::AppEditorLogic() {
	
}

AppEditorLogic::~AppEditorLogic() {
	
}

int AppEditorLogic::init() {
	return 1;
}

int AppEditorLogic::update() {
	return 1;
}

int AppEditorLogic::postUpdate() {
	return 1;
}

int AppEditorLogic::shutdown() {
	return 1;
}

int AppEditorLogic::destroyRenderResources() {
	return 1;
}

int AppEditorLogic::worldInit() {
	return 1;
}

int AppEditorLogic::worldShutdown() {
	return 1;
}

int AppEditorLogic::worldSave() {
	return 1;
}

init() functionФункция init()#

The engine calls this function on the world initialization. It initializes all belongings of UnigineEditor.Движок вызывает эту функцию при инициализации мира. Он инициализирует все, что принадлежит UnigineEditor.

update() functionФункция update()#

If the editor is loaded, the engine calls this function before updating each render frame. Here you can put some editor-related logic that should be updated each frame.Если редактор загружен, движок вызывает эту функцию перед обновлением каждого кадра рендеринга. Здесь вы можете поместить логику, связанную с редактором, которая должна обновляться каждый кадр.

postUpdate() functionФункция postUpdate()#

If the editor is loaded, the engine calls this function before rendering each render frame.Если редактор загружен, движок вызывает эту функцию перед рендерингом каждого кадра.

shutdown() functionФункция shutdown()#

The engine calls this function on editor shutdown. Engine applications may continue running.Движок вызывает эту функцию при завершении работы редактора. Приложения Engine могут продолжать работать.

destroyRenderResources() functiondestroyRenderResources()#

The engine calls this function when the video mode is changed or the application is restarted (i.e. video_restart is called). The function is used to reinitialize the graphics context (if the application directly uses any OpenGL or DirectX commands)Движок вызывает эту функцию при изменении видеорежима или перезапуске приложения (т.е. вызывается video_restart). Функция используется для повторной инициализации графического контекста (если приложение напрямую использует какие-либо команды OpenGL или DirectX)

worldInit() functionФункция worldInit()#

If the editor is loaded, the Engine calls this function on the world initialization. Use this function, if you want to initialize something before the World Logic starts its init() function. Если редактор загружен, Движок вызывает эту функцию при инициализации мира. Используйте эту функцию, если вы хотите что-то инициализировать до того, как World Logic запустит свою функцию init().

worldShutdown() functionФункция worldShutdown()#

If the editor is loaded, the engine calls this function on the world shutdown.Если редактор загружен, движок вызывает эту функцию при выключении мира.

worldSave() functionФункция worldSave()#

If the editor is loaded, the Engine calls this function on saving the world.Если редактор загружен, Движок вызывает эту функцию при сохранении мира.

Последнее обновление: 16.07.2021
Build: ()