This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
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
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы

Основной цикл движка

This article describes in detail the steps taken by the UNIGINE engine when the Engine::update(), Engine::render(), and Engine::swap() functions are called. For other steps and general information about execution sequence, see the Execution Sequence article.В этой статье подробно описаны действия, выполняемые движком UNIGINE при вызове функций Engine::update(), Engine::render() и Engine::swap(). Для других шагов и общей информации о последовательности выполнения см. статью Последовательность выполнения.

Примечание
Each stage of the main loop is initiated by the application window created during the Initialization stage.Каждый этап основного цикла инициируется окном приложения, создаваемым на этапе инициализации.

The total time the main loop has taken is displayed by the Total counter in the Performance Profiler.Общее время, затраченное на основной цикл, отображается счетчиком Total в Профилировщике производительности .

UpdateUpdate#

The update part of the execution sequence includes the following:Этап обновления (update) в последовательности выполнения включает следующее:

  1. The FPS value of the application starts to be calculated.Начинается расчет значения FPS приложения.

    Примечание
    Calculation of FPS starts only with the second rendered frame, while the very first one is skipped.Расчет FPS начинается только со второго отрендеренного кадра, а самый первый пропускается.
  2. All pending console commands that were called during the previous frame are executed. The commands are executed in the beginning of the update() cycle, but before the scripts are updated, because otherwise they may violate the current process of rendering or physical calculations. Выполняются все ожидающие консольные команды, которые были вызваны в предыдущем кадре. Команды выполняются в начале цикла update(), но до обновления скриптов, поскольку в противном случае они могут нарушить текущий процесс рендеринга или физических вычислений.
  3. If a world has been unloaded during the previous frame, another world is loaded: WorldLogic::init().Если мир был выгружен во время предыдущего кадра, загружается другой мир: WorldLogic::init().
  4. If the restart_main_window console command was executed previously (not in the current update stage), world shaders are created.Если консольная команда restart_main_window была выполнена ранее (не на текущем этапе обновления), создаются шейдеры мира.

  5. Properties, input, and controls are updated.Обновление свойств (properties), ввод и элементов управления.
  6. Update of streamed textures, sound, and landscape.Обновление потоковых текстур, звука и данных ландшафта.
  7. Game FPS and materials are updated.Обновление Game FPS и материалов.
  8. Ambient sound sources timers are updated.Обновление таймеров источников окружающего звука.
  9. The World Logic init() function for the newly loaded world is called.Вызывается функция World Logic init() для вновь загруженного мира.
  10. The update() function of all plugins is called. What happens during it, solely depends on the content of this custom function.Вызывается функция update() всех плагинов . Что происходит во время этого, зависит исключительно от содержимого этой настраиваемой функции.
  11. The Editor-related Logic is updated by calling the Editor update() function.Логика, связанная с редактором, обновляется путем вызова функции Editor update().
  12. The System Logic is updated. The default system script update() function performs the following:
    • 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 (set by the MOUSE_SOFT definition), or not handled by the system (set by the MOUSE_USER definition, which allows input handling by some custom module).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 (set by the MOUSE_SOFT definition), or not handled by the system (set by the MOUSE_USER definition, which allows input handling by some custom module).
    • The main menu logic is updated (if the MENU_USER definition is not set).The main menu logic is updated (if the MENU_USER definition is not set).
    • Other system-related user input is handled. For example, the world state is saved or restored, or a screenshot of the current UNIGINE window contents is made, if required.Other system-related user input is handled. For example, the world state is saved or restored, or a screenshot of the current UNIGINE window contents is made, if required.
    • If the GPU Monitor plugin is initialized (the HAS_GPU_MONITOR definition is set), the plugin output is displayed in the application window and additional console commands become available.If the GPU Monitor plugin is initialized (the HAS_GPU_MONITOR definition is set), the plugin output is displayed in the application window and additional console commands become available.

      Внимание
      Функционал, описанный в этом параграфе, недоступен в Community редакции SDK.
      Чтобы использовать этот функционал вам необходимо получить лицензию на Sim SDK.
    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 (set by the MOUSE_SOFT definition), or not handled by the system (set by the MOUSE_USER definition, which allows input handling by some custom module).The main menu logic is updated (if the MENU_USER definition is not set).Other system-related user input is handled. For example, the world state is saved or restored, or a screenshot of the current UNIGINE window contents is made, if required.If the GPU Monitor plugin is initialized (the HAS_GPU_MONITOR definition is set), the plugin output is displayed in the application window and additional console commands become available.
    Обновление Системной логики. Функция update() по умолчанию системного скрипта выполняет следующее:
    • 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 (set by the MOUSE_SOFT definition), or not handled by the system (set by the MOUSE_USER definition, which allows input handling by some custom module).Системный скрипт обрабатывает события от мыши. Он контролирует, захватывается ли мышь при нажатии (по умолчанию), курсор мыши исчезает, если он не перемещается в течение некоторого времени (устанавливается дефайном MOUSE_SOFT), или не обрабатывается системой (устанавливается дефайном MOUSE_USER, что позволяет обрабатывать ввод с помощью какого-то кастомного модуля).
    • The main menu logic is updated (if the MENU_USER definition is not set).Обновление логики главного меню (если не задан дефайн MENU_USER).
    • Other system-related user input is handled. For example, the world state is saved or restored, or a screenshot of the current UNIGINE window contents is made, if required.Обработка другого пользовательского ввода, связанного с системой. Например, сохранение или восстановление состояния мира, или выполнение снимка экрана с текущим содержимым окна UNIGINE, если требуется.
    • If the GPU Monitor plugin is initialized (the HAS_GPU_MONITOR definition is set), the plugin output is displayed in the application window and additional console commands become available.Если плагин GPU Monitorинициализирован (задан дефайн HAS_GPU_MONITOR), вывод плагина отображается в окне приложения и становятся доступными дополнительные консольные команды.

      Внимание
      Функционал, описанный в этом параграфе, недоступен в Community редакции SDK.
      Чтобы использовать этот функционал вам необходимо получить лицензию на Sim SDK.
  13. If the world is loaded (it can be done from the console or via the System Logic), the World Logic gets updated. In the World Logic update() function, you can code frame-by-frame behavior of your application (see details here). Если мир загружен (это можно сделать из консоли или через системную логику), то выполняется обновление логики мира (World Logic). В функции World Logic update() вы можете закодировать покадровое поведение вашего приложения (подробнее см. здесь ).

    Примечание
    Physics, if any, and continuous operations (pushing a car forward depending on current motor's RPM, simulating wind blowing constantly, performing immediate collision response, etc.), can be implemented separately in the updatePhysics() function. This function is called with a fixed frame rate (while the update() function is called each frame).Физика, при использовании, и непрерывные операции (толкание автомобиля вперед в зависимости от текущей скорости вращения двигателя, имитация постоянного ветра, немедленное реагирование на столкновение и т.д.) Могут быть реализованы отдельно в функции updatePhysics(). Эта функция вызывается с фиксированной частотой кадров (в то время как функция update() вызывается для каждого кадра).

    The world and its world logic are updated in the following order:Мир и его логика обновляются в следующем порядке:

    1. The World Logic updateAsyncThread() function is executed. It is designed to perform logic functions that should be called every frame independently of the rendering thread. This function doesn't block the Main Thread.Выполняется функция World Logic updateAsyncThread(). Она предназначена для выполнения логических функций, которые должны вызываться в каждом кадре независимо от потока рендеринга. Эта функция не блокирует главный поток.
    2. The World Logic updateSyncThread() function is executed: all parallel logic functions that should be executed before update(). This function blocks the Main Thread until all calls are completed.Выполняется функция World Logic updateSyncThread(): все функции параллельной логики, которые должны выполняться до update(). Эта функция блокирует главный поток до тех пор, пока не будут завершены все вызовы.
    3. The World Logic update() function is executed: node parameters are updated, transformations for non-physical nodes are set and so on.Выполняется функция World Logic update(): обновляются параметры ноды, устанавливаются преобразования для нефизических нод и так далее.
    4. The state of nodes existing in the world is updated (mostly for visible nodes): skinned animation is played, particle systems spawn new particles, players are repositioned, and so on. Triggered world callbacks are added to a stack (they will be executed later).Обновление состояния существующих в мире нод в основном для видимых нод): воспроизводится анимация со скинами, системы частиц порождают новые частицы, перемещаются игроки и т.д. Инициированные мировые обратные вызовы добавляются в стек (они будут выполнены позже ).
    5. World Expressions are updated. Code in World Expressions can be written via UnigineEditor.Обновление World Expressions. Код в World Expressions можно написать через UnigineEditor.
    6. GUI is updated.Обновление графического интерфейса.
    7. The World Logic postUpdate() function is called.Вызывается функция World Logic postUpdate().
  14. The System Logic postUpdate() function is executed, if necessary (see details here). It can access the updated data on node states and correct the behavior accordingly in the same frame.При необходимости выполняется функция System Logic postUpdate() (подробнее см. здесь ). Она может использоваться для получения доступа к обновленным данным о состояниях нод и соответствующего корректирования поведения в том же кадре.
  15. The Editor Logic postUpdate() function is executed.Выполняется функция Editor Logic postUpdate().
  16. The postUpdate() function of all plugins is called.Вызывается функция postUpdate() всех плагинов.
  17. The world spatial tree is updated.Обновление пространственного дерева мира.
  18. The file system is updated.Обновление файловой системы.

At the end of the update stage, physics and pathfinding start to be updated in their separate threads. Then they perform their tasks on all available threads in parallel to rendering.В конце этапа обновления физика и поиск пути начинают обновляться в отдельных потоках . Затем они выполняют свои задачи во всех доступных потоках параллельно с рендерингом .

Примечание
Nodes with computationally heavy bodies (like clothes and ropes) should not have one parent; otherwise, they will be updated in one thread.Ноды с вычислительно тяжелыми телами (такими как одежда и веревки) не должны иметь одного общего родителя; в противном случае они будут обновляться в одном потоке.

The total time of update stage is displayed by the Update counter in the Performance Profiler.Общее время этапа update отображается счетчиком Update в Профилировщике производительности .

RenderingRendering#

As soon as the update stage is completed, UNIGINE can start rendering the world. In parallel, the pathfinding is performed in a separate thread. Depending on the physics update mode, parts of the physics calculations are performed in the main thread or in parallel to it. This approach enables to effectively balance the load between CPU and GPU, and thus allows for higher framerate in the UNIGINE-based application.Как только этап обновления завершен, UNIGINE может начать рендеринг мира. Параллельно выполняется поиск пути в отдельном потоке. В зависимости от режима обновления физики , части физических расчетов выполняются в основном потоке или параллельно ему . Такой подход позволяет эффективно балансировать нагрузку между процессором и графическим процессором и, таким образом, обеспечивает более высокую частоту кадров в приложении на основе UNIGINE.

Here is what happens during the render stage:Вот что происходит на этапе рендеринга:

Рендер Физика Поиск пути
  1. The Editor Logic render() function is called.Вызывается функция Editor Logic render().
  2. The render() function of plugins is called, if they exist.Вызывается render() функция плагинов , если они используются.
  3. UNIGINE renders the graphics scene (the world) and the sound scene, as they should be in the current frame. The graphics scene is sent to GPU, while the sound scene is sent to the sound card. As soon as the CPU finishes preparation of data and feeds rendering commands to the GPU, the GPU becomes busy with rendering the frame.

    The total time of rendering stage is displayed by the Render CPU counter in the Performance Profiler. After that, the CPU is free, so we can load it with calculations we need.The total time of rendering stage is displayed by the Render CPU counter in the Performance Profiler. After that, the CPU is free, so we can load it with calculations we need.

    The total time of rendering stage is displayed by the Render CPU counter in the Performance Profiler. After that, the CPU is free, so we can load it with calculations we need.
    UNIGINE визуализирует графическую сцену (мир) и звуковую сцену так, как они должны быть в текущем кадре. Графическая сцена отправляется на GPU, а звуковая сцена отправляется на звуковую карту. Как только ЦП завершает подготовку данных и передает команды рендеринга на ГП, ГП начинает выполнять рендеринг кадра.

    The total time of rendering stage is displayed by the Render CPU counter in the Performance Profiler. After that, the CPU is free, so we can load it with calculations we need.Общее время этапа рендеринга отображается в Профилировщике производительности счетчиком Render CPU. После этого ЦП освободится, поэтому мы можем загрузить его нужными нам вычислениями.

  4. The gui() function of plugins (if any) is called.Вызывается функция плагинов gui() (при наличии).
  5. At last and atop of all, GUI is rendered, if required. And the total time of interface rendering is displayed by the Interface counter in the Performance Profiler.Наконец, при необходимости, отображается графический интерфейс. А общее время рендеринга интерфейса отображается в Профилировщике производительности счетчиком Interface.
  1. The physics module calls the plugin updatePhysics() function, if it exists.Модуль физики вызывает функцию updatePhysics() плагинов, при их использовании.
  2. The physics module calls the world logic updatePhysics() function. In the updatePhysics() function, you can modify physics.

    The updatePhysics() function is not called each frame. The physics module has its own fixed framerate, which does not depend on the rendering framerate. During each of such physics frames (or ticks), a number of calculation iterations are performed (updatePhysics() is called before each iteration).The updatePhysics() function is not called each frame. The physics module has its own fixed framerate, which does not depend on the rendering framerate. During each of such physics frames (or ticks), a number of calculation iterations are performed (updatePhysics() is called before each iteration).

    The updatePhysics() function is not called each frame. The physics module has its own fixed framerate, which does not depend on the rendering framerate. During each of such physics frames (or ticks), a number of calculation iterations are performed (updatePhysics() is called before each iteration).
    Модуль физики вызывает функцию World Logic updatePhysics(). В функции updatePhysics() вы можете изменить физику .

    The updatePhysics() function is not called each frame. The physics module has its own fixed framerate, which does not depend on the rendering framerate. During each of such physics frames (or ticks), a number of calculation iterations are performed (updatePhysics() is called before each iteration).Функция updatePhysics()вызывается не в каждом кадре. В физическом модуле есть собственная фиксированная частота кадров , которая не зависит от частоты кадров рендеринга . Во время каждого такого физического кадра (или такта) выполняется ряд итераций вычислений (updatePhysics()вызывается перед каждой итерацией).

  3. The physics module is updated: internal physics simulation starts. During this step, UNIGINE performs collision detection for all objects that have physical bodies and collision shapes.
    In the Performance Profiler, the total time of updatePhysics() together with physics simulation is displayed by the Total Physics counter.
    Обновление модуля физики: запускается симуляция внутренней физики. На этом этапе UNIGINE выполняет обнаружение столкновений для всех объектов, имеющих физические тела и коллизионные формы (shapes).
    В Профилировщике производительности , общее время updatePhysics() вместе с физическим моделированием отображается счетчиком Physics CPU.

SwapSwap#

The swap stage is the last one in the main loop. It includes the following:Этап Swap - последний в основном цикле. Он включает в себя следующее:

  1. If the screenshot console command is executed previously, on this stage, the taken screenshot is saved in folder where all application data is stored.Если ранее была выполнена консольная команда screenshot, на этом этапе сделанный снимок экрана сохраняется в папке, где все Данные приложений хранится.
  2. Synchronization of physics and pathfinding with the rendered world, i.e. waiting for all additional threads to finish their tasks. Results of the physical calculations are applied to the world. That is, on the previous step we have calculated how physical bodies with collision shapes have changed their position and orientation (due to our update-based logic or interaction). Now these transformations can be finally applied to nodes, i.e. rendered meshes.Синхронизация физики и поиска пути с визуализированным миром, т.е. ожидание, пока все дополнительные потоки завершат свои задачи. Результаты физических расчетов применяются к миру. То есть на предыдущем шаге мы вычислили, как физические тела с формами столкновения изменили свое положение и ориентацию (из-за нашей логики или взаимодействия, основанного на обновлении). Теперь эти преобразования можно, наконец, применить к нодам, то есть к визуализированным мешам.

    Примечание
    As the synchronization of physics follows the rendering stage (in default Async Rendering physics mode), applied physical transformations will be visible on the screen only in the next frame. To calculate physics before the rendering enable the Before Rendering physics mode.Поскольку синхронизация физики следует за этапом рендеринга (в режиме физики по умолчанию Async Rendering), примененные физические преобразования будут видны на экране только в следующем кадре. Для расчета физики перед рендерингом включите режим физики Before Rendering.
  3. The World Logic swap() function is executed. It operates with the results of the updateAsyncThread() function.Выполняется функция World Logic swap(). Она работает с результатами функции updateAsyncThread().
  4. The plugin swap() function is called, if it exists.Вызывается функция плагина swap(), если она существует.
  5. Unloading of the world, if another world is going to be loaded in the next frame.Выполняется выгрузка мира, если в следующем кадре будет загружен другой мир.
  6. Deletion of all objects that are planned to be deleted.Удаление всех объектов, которые планируется удалить.
  7. Values shown in the Performance Profiler are updated.Обновление значений, отображаемых в Профилировщике производительности.

After the swap stage is completed, the application window initiates GPU buffers swapping as described here.После завершения этапа Swap окно приложения инициирует перестановку буферов графического процессора, как описано здесь .

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