Skip to content

Textured models with quaternion rotation

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

Before starting, make sure you have:

  • CC:Tweaked installed
  • DirectGPU installed
  • A DirectGPU display
  • A Base64 encoded texture image

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 textured triangle model:

local modelData = [[
v -0.5 -0.5 0
v 0.5 -0.5 0
v 0 0.5 0
vt 0 1
vt 1 1
vt 0.5 0
f 1/1 2/2 3/3
]]

Load the model and its texture:

local textureData = "base64_png_here"
local modelId = gpu.load3DModel(modelData)
local textureId = gpu.loadTexture(textureData)

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 that rotates over time:

local angle = os.clock()
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 textured model passing the quaternion after the color args:

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

The textured model is now drawn rotating over time using the quaternion.