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
Учебные материалы

Матричные преобразования

A lot of calculations in UNIGINE are performed by using matrices. Actually, matrix transformations are one of the main concepts of 3D engines. This article contains an explanation of matrix transformations with usage examples. Многие вычисления в UNIGINE выполняются с использованием матриц. Собственно, матричные преобразования - одна из основных концепций 3D-движков. Эта статья содержит объяснение матричных преобразований с примерами использования.

See AlsoСмотрите также#

TransformationsТрансформации#

In simple terms, a matrix in 3D graphics is an array of numbers arranged in rows and columns: Проще говоря, матрица в трехмерной графике - это массив чисел, упорядоченных по строкам и столбцам:

Usually, 4x4 matrices are used. Such size (4x4) of matrices is caused by the translation state in 3D space. When you put a new node into the world, it has a 4x4 world transform matrix that defines the position of the node in the world. Обычно используются матрицы 4x4 . Такой размер матриц (4х4) обусловлен состоянием трансляции в трехмерном пространстве. Когда вы помещаете новый узел в мир, он имеет мировую матрицу трансформации мира 4x4, которая определяет его положение в мире.

In UNIGINE, matrices are column major (column-oriented). Hence, the first column of the transform matrix represents the X vector of the local coordinate system (v1), the second represents the Y vector (v2), the third represents the Z vector (v3), and the fourth represent the translation vector t. First three columns show directions of local coordinate axes (rotation) and the scale of the origin. The last column contains the translation of the local origin relatively to the world origin. В UNIGINE матрицы являются основными по столбцам (ориентированными по столбцам). Следовательно, первый столбец матрицы преобразования представляет вектор X локальной системы координат ( v1 ), второй представляет вектор Y ( v2 ), третий представляет вектор Z ( v3 ), а четвертый представляет вектор перемещения t . Первые три столбца показывают направления локальных осей координат ( поворот ) и масштаб начала координат. Последний столбец содержит перемещение локального начала координат относительно мирового.

Identity MatrixЕдиничная матрица#

The world origin has the following matrix: Начало координат имеет следующую матрицу:

This matrix is called identity matrix, a matrix with ones on the main diagonal, and zeros elsewhere. If a matrix is multiplied by the identity matrix, that won't change anything: the resulting matrix will be the same as it was before multiplying. Эта матрица называется единичной матрицей , матрицей с единицами на главной диагонали и нулями в другом месте. Если матрица умножается на единичную матрицу, это ничего не изменит: результирующая матрица будет такой же, как и до умножения.

If the local origin has the identity matrix, it means the local origin and the world origin are coincident. Если локальное начало координат имеет единичную матрицу, это означает, что местное начало координат и мировое начало координат совпадают .

RotationВращение#

To change the orientation of the local origin, the first three columns of the matrix should be changed. Чтобы изменить ориентацию локального начала координат, следует изменить первые три столбца матрицы.

To rotate the origin along different axes, you should use proper matrices: Чтобы повернуть начало координат по разным осям, вы должны использовать соответствующие матрицы:

In the matrices given above, α is a rotation angle along the axis. В приведенных выше матрицах α - это угол поворота вдоль оси.

The next matrix shows the rotation of the local origin along the Y axis at 45 degrees: Следующая матрица показывает поворот локального начала координат по оси Y на 45 градусов:

TranslationПеремещение#

The last column of the transform matrix shows the position of the local origin in the world relatively to the world origin. The next matrix shows the translation of the origin. The translation vector t is (3, 0, 2). Последний столбец матрицы преобразования показывает положение локального начала координат в мире относительно начала координат. Следующая матрица показывает перемещение начала координат. Вектор перемещения t равен (3, 0, 2) .

ScalingМасштабирование#

The length of the vector shows the scale coefficient along the axis. Длина вектора показывает масштабный коэффициент по оси.

To calculate the vector length (also known as magnitude), you should find a square root of the sum of the squares of vector components. The formula is the following: Чтобы вычислить длину вектора (также известную как величина ), вы должны найти квадратный корень из суммы квадратов компонентов вектора. Формула следующая:

Vector Length
|vector length| = √(x² + y² + z²)

The following matrix scales the local origin up to 2 units along all axes. Следующая матрица масштабирует местное начало координат до 2 единиц по всем осям.

Cumulating TransformationsНакопление преобразований#

The order of matrix transformations in code is very important. Порядок преобразования матриц в коде очень важен.

If you want to implement a sequence of cumulating transformations, the transformations order in code should be as follows: Если вы хотите реализовать последовательность кумулирующих преобразований, порядок преобразований в коде должен быть следующим:

Transformation order
TransformedVector = TransformationMatrixN * ... * TransformationMatrix2 * TransformationMatrix1 * Vector

Transformations are applied one by one starting from TransformationMatrix1 and ending with TransformationMatrixN. Преобразования применяются одно за другим, начиная с TransformationMatrix1 и заканчивая TransformationMatrixN.

Exampleпример#

This example shows the difference between two orders of matrix transformations. Этот пример показывает разницу между двумя порядками преобразования матриц.

The code example below gets the material ball object. In the first case, rotation is followed by translation and in the second case, translation is followed by rotation. В приведенном ниже примере кода получается объект материального шара. В первом случае за вращением следует перемещение, а во втором случае за перемещением следует поворот.

In the AppWorldLogic.h file, define the material_ball node smart pointer. В файле AppWorldLogic.h определите указатель для узла material_ball.

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

/* ... */

class AppWorldLogic : public Unigine::WorldLogic {
	
public:
	/* .. */
private:
	Unigine::NodePtr material_ball;
};

In the AppWorldLogic.cpp file, perform the following: В файле AppWorldLogic.cpp выполните следующие действия:

  • Include the UnigineEditor.h, UnigineVisualizer.h, UnigineConsole.h headers. Включите заголовки UnigineEditor.h, UnigineVisualizer.h, UnigineConsole.h.
  • Use using namespace Unigine and using namespace Unigine::Math directives: names of the Unigine and Unigine::Math namespaces will be injected into global namespace. Используйте директивы using namespace Unigine и using namespace Unigine::Math: имена пространств имен Unigine и Unigine::Math будут вставлены в глобальное пространство имен.
  • Enable the visualizer by passing show_visualizer 1 command to the run() function of the Console class. Включите визуализатор, передав команду show_visualizer 1 функции run() класса Console.
  • Get the material ball from the Editor. Получите material ball из редактора.
  • Create new rotation and translation matrices. Создайте новые матрицы поворота и перемещения.
  • Calculate new transformation matrix and apply it to the material ball. Рассчитайте новую матрицу преобразования и примените ее к material ball.
  • Render the world origin by using renderVector() method of the Visualizer class. Визуализируйте происхождение мира с помощью метода renderVector() класса Visualizer.
Исходный код (C++)
// AppWorldLogic.cpp file
#include "AppWorldLogic.h"
#include "UnigineWorld.h"
#include "UnigineVisualizer.h"
#include "UnigineConsole.h"

// inject Unigine and Unigine::Math namespaces names to global namespace
using namespace Unigine;
using namespace Unigine::Math;

/* ... */

int AppWorldLogic::init() {
	
	// enable the visualizer for world origin rendering
	Console::run("show_visualizer 1");

	// get the material ball
	material_ball = World::getNodeByName("material_ball");

	// create rotation and translation matrices
	Mat4 rotation_matrix = (Mat4)rotateZ(-90.0f);
	Mat4 translation_matrix = (Mat4)translate(vec3(0.0f, 3.0f, 0.0f));

	// create a new transformation matrix for the material ball
	// by multiplying the current matrix by rotation and translation matrices
	Mat4 transform = translation_matrix * rotation_matrix * material_ball->getTransform();
	
	// set the transformation matrix to the material ball
	material_ball->setTransform(transform);	

	return 1;
}

int AppWorldLogic::update() {
	// render world origin
	Visualizer::renderVector(Vec3(0.0f,0.0f,0.1f), Vec3(1.0f,0.0f,0.1f), vec4_red);
	Visualizer::renderVector(Vec3(0.0f,0.0f,0.1f), Vec3(0.0f,1.0f,0.1f), vec4_green);
	Visualizer::renderVector(Vec3(0.0f,0.0f,0.1f), Vec3(0.0f,0.0f,1.1f), vec4_blue);

	return 1;
}

To change the order, just change the line of cumulating transformations: Чтобы изменить порядок, достаточно изменить строку накопления преобразований:

Исходный код (C++)
Mat4 transform = rotation_matrix * translation_matrix * material_ball->getTransform();

The result will be different. The pictures below show the difference (camera is located at the same place). Результат будет другим. На фотографиях ниже показана разница (камера расположена в том же месте).

Order: rotation and translation Порядок: вращение и перемещение
Order: translation and rotation Порядок: перемещение и вращение

The pictures above show the position of the meshes related to the world origin. На изображениях выше показано положение сеток относительно начала мира.

Matrix HierarchyМатричная иерархия#

One more important concept is the matrix hierarchy. When a node is added into the world as a child of another node, it has a transformation matrix that is related to the parent node. That is why the Node class distinguishes between the functions getTransform(), setTransform() and getWorldTransform(), setWorldTransform(), which return the local and the world transformation matrices respectively. Еще одно важное понятие - матричная иерархия. Когда узел добавляется в мир как дочерний по отношению к другому узлу, он имеет матрицу преобразования, связанную с родительским узлом. Вот почему класс Node различает функции getTransform(), setTransform() и getWorldTransform(), setWorldTransform(), которые возвращают локальную и мировую матрицы преобразования соответственно.

Примечание
If the added node has no parent, this node uses the World transformation matrix. Если у добавленного узла нет родителя, этот узел использует мировую матрицу трансформации .

What is the reason of using a matrix hierarchy? To move a node relative to another node. And when you move a parent node, child nodes will also be moved. В чем причина использования матричной иерархии? Чтобы переместить узел относительно другого узла. И когда вы перемещаете родительский узел, дочерние узлы также будут перемещены.

Parent origin is the same with the world origin Родительское происхождение совпадает с мировым происхождением
Parent origin has been moved and the child origin has also been moved Родительский источник был перемещен, и дочерний источник также был перемещен

Pictures above show the main point of the matrix hierarchy. When the parent origin (node) is moved, the chlld origin will also be moved and the local transformation matrix of the child would not be changed. But the world transformation matrix of the child will be changed. If you need the world transformation matrix of the child related to the world origin, you should use the getWorldTransform(), setWorldTransform() functions; in case, when you need the local transformation matrix of the child related to the parent, you should use the getTransform(), setTransform() functions. Рисунки выше показывают суть матричной иерархии. Когда родительский источник (узел) перемещается, происхождение chlld также будет перемещено, и локальная матрица преобразования дочернего элемента не будет изменена. Но матрица преобразования мира ребенка будет изменена. Если вам нужна матрица преобразования мира дочернего элемента, связанная с началом координат мира, вы должны использовать функции getWorldTransform(), setWorldTransform(); в случае, когда вам нужна локальная матрица преобразования дочернего элемента, связанного с родительским, вы должны использовать функции getTransform(), setTransform().

Exampleпример#

The following example shows how important the matrix hierarchy is. Следующий пример показывает, насколько важна иерархия матриц.

In this example, we get the node and clone it. Then we change transformation matrices of these nodes. We review two cases: В этом примере мы получаем узел и клонируем его. Затем мы меняем матрицы преобразования этих узлов. Рассмотрим два случая:

  1. The two nodes are independent. Два узла независимы.
  2. One node is the child of the other. Один узел является дочерним для другого.

In the AppWorldLogic.h file, define smart pointers of the material_ball child and parent nodes. В файле AppWorldLogic.h определите интеллектуальные указатели дочерних и родительских узлов material_ball.

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

/* ... */

class AppWorldLogic : public Unigine::WorldLogic {
	
public:
	/* .. */
private:
	Unigine::NodePtr material_ball_child;
	Unigine::NodePtr material_ball_parent;
};

In the AppWorldLogic.cpp, implement the following code: В AppWorldLogic.cpp реализуйте следующий код:

Исходный код (C++)
// AppWorldLogic.cpp
#include "AppWorldLogic.h"
#include "UnigineEditor.h"
#include "UnigineVisualizer.h"
#include "UnigineConsole.h"
#include "UnigineLog.h"

using namespace Unigine;
using namespace Unigine::Math;

int AppWorldLogic::init() {
	
	// enable the visualizer for world origin rendering
	Console::run("show_visualizer 1");

	// get the material ball and clone it
	material_ball_child = World::getNodeByName("material_ball");
	material_ball_parent = material_ball_child->clone();

	// make the one node the child of another
	material_ball_parent->addChild(material_ball_child);

	// create rotation and translation matrices for the first material_ball
	Mat4 rotation_matrix = (Mat4)rotateZ(-90.0f);
	Mat4 translation_matrix = (Mat4)translate(vec3(3.0f, 0.0f, 0.0f));

	// create translation matrix for the second (parent) material ball
	Mat4 translation_matrix_clone = (Mat4)translate(vec3(0.5f, 0.0f, 1.0f));

	// create new transformation matrices for the material balls
	Mat4 transform = translation_matrix * rotation_matrix * material_ball_child->getTransform();
	Mat4 transform_clone = translation_matrix_clone * material_ball_parent->getTransform();
	
	// set the transformation matrices to the material balls
	material_ball_child->setTransform(transform);
	material_ball_parent->setTransform(transform_clone);


	return 1;
}

int AppWorldLogic::update() {
	// render world origin
	Visualizer::renderVector(Vec3(0.0f,0.0f,0.1f), Vec3(1.0f,0.0f,0.1f), vec4_red);
	Visualizer::renderVector(Vec3(0.0f,0.0f,0.1f), Vec3(0.0f,1.0f,0.1f), vec4_green);
	Visualizer::renderVector(Vec3(0.0f,0.0f,0.1f), Vec3(0.0f,0.0f,1.1f), vec4_blue);

	return 1;
}

int AppWorldLogic::shutdown() {
	// clear smart pointers
	material_ball_child.clear();
	material_ball_parent.clear();

	return 1;
}

If you comment the following line: Если закомментировать следующую строку:

Исходный код (C++)
// make the one node the child of another
material_ball_parent->addChild(material_ball_child);

you get a different result: вы получите другой результат:

Parent-child nodes Родительско-дочерние узлы
Nodes are independent Узлы независимы

When nodes are independent, they have different local and world transformation matrices. In case of parent-child nodes, the child's local transformation matrix remains the same after moving, but the world transformation matrix is changed (you can check that by using the debug profiler). Когда узлы независимы, они имеют разные локальные и мировые матрицы преобразования. В случае узлов родитель-потомок локальная матрица преобразования дочернего элемента остается прежней после перемещения, но матрица преобразования мира изменяется (вы можете проверить это с помощью профилировщика отладки).

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