конвертировать ID3DXMatrixStack в DirectXMath

Правильно ли он конвертирует ID3DXMatrixStack в DirectXMath следующим образом:

#include <stack>
#include <iostream>
#include <DirectXMath.h>

class MatrixStack {
    std::deque<DirectX::XMFLOAT4X4> m_MatrixStack;

public:
    MatrixStack() {
        DirectX::XMFLOAT4X4 identity;
        DirectX::XMStoreFloat4x4(&identity, DirectX::XMMatrixIdentity());
        m_MatrixStack.push_back(identity);
    }
    void Push() {
        m_MatrixStack.push_back(m_MatrixStack.back());
    }
    void Pop() {
        if (!m_MatrixStack.empty()) {
            m_MatrixStack.pop_back();
        }
    }
    void MultMatrix(DirectX::FXMMATRIX other) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(&m_MatrixStack.back(), DirectX::XMMatrixMultiply(currentMatrix, other));
    }
    void MultMatrix(const DirectX::XMFLOAT4X4& other) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMMATRIX otherMatrix = DirectX::XMLoadFloat4x4(&other);
        DirectX::XMStoreFloat4x4(&m_MatrixStack.back(), DirectX::XMMatrixMultiply(currentMatrix, otherMatrix));
    }
    void MultMatrixLocal(DirectX::FXMMATRIX other) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(&m_MatrixStack.back(), DirectX::XMMatrixMultiply(other, currentMatrix));
    }
    void MultMatrixLocal(const DirectX::XMFLOAT4X4& other) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMMATRIX otherMatrix = DirectX::XMLoadFloat4x4(&other);
        DirectX::XMStoreFloat4x4(&m_MatrixStack.back(), DirectX::XMMatrixMultiply(otherMatrix, currentMatrix));
    }
    void LoadIdentity() {
        DirectX::XMFLOAT4X4 identity;
        DirectX::XMStoreFloat4x4(&m_MatrixStack.back(), DirectX::XMMatrixIdentity());
    }
    void LoadMatrix(const DirectX::XMFLOAT4X4& other) {
        m_MatrixStack.back() = other;
    }
    void LoadMatrix(DirectX::FXMMATRIX other) {
        DirectX::XMStoreFloat4x4(&m_MatrixStack.back(), other);
    }
    DirectX::XMFLOAT4X4& GetTop() {
        return m_MatrixStack.back();
    }
    void RotateAxis(const DirectX::XMFLOAT3& axis, float angle) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMVECTOR axis3f = DirectX::XMLoadFloat3(&axis);
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                currentMatrix,
                DirectX::XMMatrixRotationAxis(axis3f, angle)
            )
        );
    }
    void RotateAxis(DirectX::FXMVECTOR axis, float angle) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                currentMatrix,
                DirectX::XMMatrixRotationAxis(axis, angle)
            )
        );
    }
    void RotateAxisLocal(const DirectX::XMFLOAT3& axis, float angle) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMVECTOR axis3f = DirectX::XMLoadFloat3(&axis);
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                DirectX::XMMatrixRotationAxis(axis3f, angle),
                currentMatrix
            )
        );
    }
    void RotateAxisLocal(const DirectX::FXMVECTOR& axis, float angle) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                DirectX::XMMatrixRotationAxis(axis, angle),
                currentMatrix
            )
        );
    }
    void RotateYawPitchRoll(float yaw, float pitch, float roll) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                currentMatrix,
                DirectX::XMMatrixRotationRollPitchYaw(pitch, yaw, roll)
            )
        );
    }
    void RotateYawPitchRollLocal(float yaw, float pitch, float roll) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                DirectX::XMMatrixRotationRollPitchYaw(pitch, yaw, roll),
                currentMatrix
            )
        );
    }
    void Scale(float x, float y, float z) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                currentMatrix,
                DirectX::XMMatrixScaling(x, y, z)
            )
        );
    }
    void ScaleLocal(float x, float y, float z) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                DirectX::XMMatrixScaling(x, y, z),
                currentMatrix
            )
        );
    }
    void Translate(float x, float y, float z) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                currentMatrix,
                DirectX::XMMatrixTranslation(x, y, z)
            )
        );
    }
    void TranslateLocal(float x, float y, float z) {
        DirectX::XMMATRIX currentMatrix = DirectX::XMLoadFloat4x4(&m_MatrixStack.back());
        DirectX::XMStoreFloat4x4(
            &m_MatrixStack.back(),
            DirectX::XMMatrixMultiply(
                DirectX::XMMatrixTranslation(x, y, z),
                currentMatrix
            )
        );
    }
};

Предоставляет механизм, позволяющий вставлять и извлекать матрицы из стека матриц. Реализация стека матриц — это эффективный способ отслеживания матриц при обходе иерархии преобразований. Стек матриц для хранения преобразований в виде матриц. Реализация иерархии сцен Матричный стек упрощает построение иерархических моделей, в которых сложные объекты конструируются из ряда более простых объектов. Сцена или иерархия преобразования обычно представлена ​​древовидной структурой данных. Каждый узел в древовидной структуре данных содержит матрицу. Конкретная матрица представляет собой изменение систем координат от родительского узла к узлу. Например, если вы моделируете человеческую руку, вы можете реализовать следующую иерархию. В этой иерархии матрица Body помещает тело в мир: матрица UpperArm содержит вращение плеча, матрица LowerArm содержит вращение локтя, а матрица Hand содержит вращение запястья. относительно мира, вы просто перемножаете все матрицы от Тела до Руки вместе. Предыдущая иерархия слишком упрощена, потому что у каждого узла есть только один дочерний элемент. Если вы начнете моделировать руку более подробно, вы, вероятно, добавите пальцы и большой палец. Каждую цифру можно добавить в иерархию как дочерние элементы Hand. Если вы пройдете полный график руки в глубину — сначала пройдя как можно дальше по одному пути, прежде чем перейти к следующему пути, — чтобы нарисовать сцену, вы выполните последовательность сегментированного рендеринга. Например, для рендеринга рукой и пальцами вы реализуете следующую схему.

  1. Вставьте ручную матрицу в стопку матриц.
  2. Нарисуйте руку.
  3. Вставьте матрицу Thumb в стек матриц.
  4. Нарисуйте большой палец.
  5. Извлеките матрицу Thumb из стопки.
  6. Вставьте матрицу Finger 1 в стек матриц.
  7. Нарисуйте первый палец.
  8. Извлеките матрицу Finger 1 из стопки.
  9. Вставьте матрицу Finger 2 в стек матриц. Продолжайте таким же образом, пока не будут визуализированы все пальцы и большой палец.

После того, как вы завершите рендеринг пальцев, вы должны вытащить матрицу Hand из стека. Вы можете проследить этот базовый процесс в коде на следующих примерах. Когда вы обнаружите узел во время поиска в глубину древовидной структуры данных, поместите матрицу на верх стека матриц.

MatrixStack-> Push ();

MatrixStack-> MultMatrix (pNode-> матрица);

Когда вы закончите с узлом, снимите матрицу с вершины стека матриц.

MatrixStack-> Pop ();

Таким образом, матрица наверху стека всегда представляет мировое преобразование текущего узла, поэтому перед отрисовкой каждого узла вы должны установить матрицу.

// Adds a matrix to the stack.
// This method increments the count of items on the stack by 1, duplicating the current matrix.
// The stack will grow dynamically as more items are added.
void Push();

// Removes the current matrix from the top of the stack.
// Note that this method decrements the count of items on the stack by 1, effectively
// removing the current matrix from the top of the stack and promoting a matrix to the top of the
// stack. If the current count of items on the stack is 0, then this method returns without performing
// any action. If the current count of items on the stack is 1, then this method empties the stack.
void Pop();

// Determines the product of the current matrixand the given matrix.
// This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin
// m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat);
// This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.
void MultMatrix(DirectX::FXMMATRIX other);

// Determines the product of the current matrixand the given matrix.
// This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin
// m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat);
// This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.
void MultMatrix(const DirectX::XMFLOAT4X4& other);

// Determines the product of the given matrix and the current matrix.
// This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).
// m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos];
// This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.
void MultMatrixLocal(DirectX::FXMMATRIX other);

// Determines the product of the given matrix and the current matrix.
// This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).
// m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos];
// This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.
void MultMatrixLocal(const DirectX::XMFLOAT4X4& other);

// Loads identity in the current matrix.
// The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients,
// which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged.
// The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations,
// translations, and any other transformations that can be represented by a 4x4 matrix.
void LoadIdentity();

// Loads the given matrix into the current matrix.
void LoadMatrix(const DirectX::XMFLOAT4X4& other);

// Loads the given matrix into the current matrix.
void LoadMatrix(DirectX::FXMMATRIX other);

// Retrieves the current matrix at the top of the stack.
// Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix.
DirectX::XMFLOAT4X4& GetTop();

// Rotates (relative to world coordinate space) around an arbitrary axis.
// axis - arbitrary axis of rotation
// angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.
// This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
// D3DXMATRIX tmp;
// D3DXMatrixRotationAxis(&tmp, pV, angle);
// m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;
// Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.
void RotateAxis(const DirectX::XMFLOAT3& axis, float angle);

// Rotates (relative to world coordinate space) around an arbitrary axis.
// axis - arbitrary axis of rotation
// angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.
// This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
// D3DXMATRIX tmp;
// D3DXMatrixRotationAxis(&tmp, pV, angle);
// m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;
// Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.
void RotateAxis(DirectX::FXMVECTOR axis, float angle);

// Rotates (relative to the object's local coordinate space) around an arbitrary axis.
// axis - arbitrary axis of rotation
// angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.
// This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
// D3DXMATRIX tmp;
// D3DXMatrixRotationAxis(&tmp, pV, angle);
// m_stack[m_currentPos] = tmp * m_stack[m_currentPos];
// Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.
void RotateAxisLocal(const DirectX::XMFLOAT3& axis, float angle);

// Rotates (relative to the object's local coordinate space) around an arbitrary axis.
// axis - arbitrary axis of rotation
// angle - Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.
// This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
// D3DXMATRIX tmp;
// D3DXMatrixRotationAxis(&tmp, pV, angle);
// m_stack[m_currentPos] = tmp * m_stack[m_currentPos];
// Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.
void RotateAxisLocal(const DirectX::FXMVECTOR& axis, float angle);

// Rotates around (relative to world coordinate space).
// The yaw around the y-axis in radians.
// The pitch around the x-axis in radians.
// The roll around the z-axis in radians.
// This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
// D3DXMATRIX tmp;
// D3DXMatrixRotationYawPitchRoll(&tmp, yaw, pitch, roll);
// m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;
// Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.
void RotateYawPitchRoll(float yaw, float pitch, float roll);

// Rotates around (relative to world coordinate space).
// The yaw around the y-axis in radians.
// The pitch around the x-axis in radians.
// The roll around the z-axis in radians.
// This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
// D3DXMATRIX tmp;
// D3DXMatrixRotationYawPitchRoll(&tmp, yaw, pitch, roll);
// m_stack[m_currentPos] = tmp * m_stack[m_currentPos];
// Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.
void RotateYawPitchRollLocal(float yaw, float pitch, float roll);

// Scale the current matrix about the world coordinate origin.
// This method right-multiplies the current matrix with the computed scale matrix. The transformation is about the current world origin.
// D3DXMATRIX tmp;
// D3DXMatrixScaling(&tmp, x, y, z);
// m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;
void Scale(float x, float y, float z);

// Scale the current matrix about the object origin.
// This method left-multiplies the current matrix with the computed scale matrix. The transformation is about the local origin of the object.
// D3DXMATRIX tmp;
// D3DXMatrixScaling(&tmp, x, y, z);
// m_stack[m_currentPos] = tmp * m_stack[m_currentPos];
void ScaleLocal(float x, float y, float z);

// Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z)
// This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin).
// D3DXMATRIX tmp;
// D3DXMatrixTranslation(&tmp, x, y, z);
// m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;
void Translate(float x, float y, float z);

// Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.
// This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object).
// D3DXMATRIX tmp;
// D3DXMatrixTranslation(&tmp, x, y, z);
// m_stack[m_currentPos] = tmp * m_stack[m_currentPos];
void TranslateLocal(float x, float y, float z);

0

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *