Skip to content

Rotating 3D models with quaternions

In this guide, you will load an OBJ model and render it with quaternion rotation.

Before starting, make sure you have:

  • CC:Tweaked installed
  • DirectGPU installed
  • A DirectGPU display

Get the DirectGPU peripheral and create a display:

local gpu = peripheral.wrap("directgpu_1") or peripheral.find("directgpu")
local displayId = gpu.autoDetectAndCreateDisplay(1)

Define a simple triangle model:

local modelData = [[
v -0.5 -0.5 0
v 0.5 -0.5 0
v 0 0.5 0
f 1 2 3
]]
local modelId = gpu.load3DModel(modelData)

Configure the camera to view the model:

gpu.setupCamera(displayId, 50, 0.05, 100)
gpu.setCameraPosition(displayId, 0, 0, -4)
gpu.lookAt(displayId, 0, 0, 0)

Create a quaternion rotating around the Y axis:

local angle = math.rad(90)
local half = angle / 2
local qx = 0
local qy = math.sin(half)
local qz = 0
local qw = math.cos(half)

Clear the framebuffer, clear the depth buffer, and draw the model passing the quaternion after the color args:

gpu.clear(displayId, 0, 0, 0)
gpu.clearZBuffer(displayId)
gpu.draw3DModel(displayId, modelId, 0, 0, 0, 0, 0, 0, 1, 255, 255, 255, qx, qy, qz, qw)
if gpu.updateDisplay then
gpu.updateDisplay(displayId)
end

The model is now drawn rotated using the quaternion.