Untitled conversation
- User
local function vector3D(x, y, z) return { x = x, y = y, z = z } end local function subtract(a, b) return vector3D(a.x - b.x, a.y - b.y, a.z - b.z) end local function normalize(v) local length = math.sqrt(v.x ^ 2 + v.y ^ 2 + v.z ^ 2) if length == 0 then return vector3D(0, 0, 0) end return vector3D(v.x / length, v.y / length, v.z / length) end local function cross(a, b) return vector3D(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x) end local function dot(a, b) return a.x * b.x + a.y * b.y + a.z * b.z end local function createViewMatrix(cameraPos, cameraTargetPos, cameraUp) local forward = normalize(subtract(cameraTargetPos, cameraPos)) local right = normalize(cross(forward, cameraUp)) local trueUp = cross(right, forward) return {right.x, trueUp.x, -forward.x, 0, right.y, trueUp.y, -forward.y, 0, right.z, trueUp.z, -forward.z, 0, -dot(cameraPos, right), -dot(cameraPos, trueUp), dot(cameraPos, forward), 1} end local function perspectiveMatrix(fov, aspect, near, far) local f = 1.0 / math.tan(fov / 2) return {f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / (near - far), -1, 0, 0, (2 * far * near) / (near - far), 0} end local function multiplyMatrices(a, b) local result = {} for row = 1, 4 do for col = 1, 4 do result[(row - 1) * 4 + col] = 0 for i = 1, 4 do result[(row - 1) * 4 + col] = result[(row - 1) * 4 + col] + a[(row - 1) * 4 + i] * b[(i - 1) * 4 + col] end end end return result end local function multiplyMatrixVector(m, v) local x = v.x * m[1] + v.y * m[5] + v.z * m[9] + m[13] local y = v.x * m[2] + v.y * m[6] + v.z * m[10] + m[14] local z = v.x * m[3] + v.y * m[7] + v.z * m[11] + m[15] local w = v.x * m[4] + v.y * m[8] + v.z * m[12] + m[16] return { x = x, y = y, z = z, w = w } end local function normalizeVertex(v) if v.w == 0 then return { x = v.x, y = v.y, z = v.z } end return { x = v.x / v.w, y = v.y / v.w, z = v.z / v.w } end local cubeVertices = {vector3D(-1, -1, -1), vector3D(1, -1, -1), vector3D(1, 1, -1), vector3D(-1, 1, -1), vector3D(-1, -1, 1), vector3D(1, -1, 1), vector3D(1, 1, 1), vector3D(-1, 1, 1)} local function createModelMatrix(position, rotation, scale) local sx, sy, sz = scale.x, scale.y, scale.z local px, py, pz = position.x, position.y, position.z return {sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, px, py, pz, 1} end local cameraPos = vector3D(0, 0, 5) local cameraTargetPos = vector3D(0, 0, 0) local cameraUp = vector3D(0, 1, 0) local viewMatrix = createViewMatrix(cameraPos, cameraTargetPos, cameraUp) local fov = math.pi / 4 local screenWidth = 800 local screenHeight = 600 local aspectRatio = screenWidth / screenHeight local nearPlane = 0.1 local farPlane = 1000 local projectionMatrix = perspectiveMatrix(fov, aspectRatio, nearPlane, farPlane) local viewProjectionMatrix = multiplyMatrices(projectionMatrix, viewMatrix) local modelPosition = vector3D(0, 0, 0) local modelRotation = vector3D(0, 0, 0) local modelScale = vector3D(1, 1, 1) local modelMatrix = createModelMatrix(modelPosition, modelRotation, modelScale) local modelViewProjectionMatrix = multiplyMatrices(viewProjectionMatrix, modelMatrix) local function transformVertex(vertex, mvp) local transformed = multiplyMatrixVector(mvp, vertex) return normalizeVertex(transformed) end local transformedVertices = {} for i, vertex in ipairs(cubeVertices) do transformedVertices[i] = transformVertex(vertex, modelViewProjectionMatrix) end local function printTransformedVertices(vertices) for i, v in ipairs(vertices) do print(string.format("Vertex %d: x = %.2f, y = %.2f, z = %.2f", i, v.x, v.y, v.z)) end end printTransformedVertices(transformedVertices)Максимально оптимизируй код
- Assistant
Here's an optimized version of your Lua code. The optimizations include:
- Localizing Math Functions: Accessing global variables is slower in Lua. By localizing frequently used
mathfunctions, we reduce lookup time. - Inline Vector Operations: Functions like
vector3D,subtract,normalize,cross, anddothave been inlined where possible to reduce function call overhead. - Efficient Matrix Representation: Matrices are kept as arrays for better cache locality and performance during multiplication.
- Preallocation of Tables: Preallocating tables where the size is known can help improve performance.
- Minimized Table Creations: Reducing the number of temporary tables created during transformations.
-- Optimize by localizing frequently used functions and variables local sqrt, tan, pi, abs = math.sqrt, math.tan, math.pi, math.abs -- Define vectors as tables with numerical indices for faster access local function subtract(a, b) return a[1] - b[1], a[2] - b[2], a[3] - b[3] end local function normalize(x, y, z) local length = sqrt(x * x + y * y + z * z) if length == 0 then return 0, 0, 0 end return x / length, y / length, z / length end local function cross(ax, ay, az, bx, by, bz) return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx end local function dot(ax, ay, az, bx, by, bz) return ax * bx + ay * by + az * bz end -- Matrix multiplication optimized using numerical indices local function multiplyMatrices(a, b, result) result = result or {} for row = 1, 4 do local a1, a2, a3, a4 = a[(row - 1) * 4 + 1], a[(row - 1) * 4 + 2], a[(row - 1) * 4 + 3], a[(row - 1) * 4 + 4] for col = 1, 4 do result[(row - 1) * 4 + col] = a1 * b[col] + a2 * b[4 + col] + a3 * b[8 + col] + a4 * b[12 + col] end end return result end -- Matrix-vector multiplication optimized local function multiplyMatrixVector(m, v, out) out = out or {} local x = v[1] * m[1] + v[2] * m[5] + v[3] * m[9] + m[13] local y = v[1] * m[2] + v[2] * m[6] + v[3] * m[10] + m[14] local z = v[1] * m[3] + v[2] * m[7] + v[3] * m[11] + m[15] local w = v[1] * m[4] + v[2] * m[8] + v[3] * m[12] + m[16] out[1], out[2], out[3], out[4] = x, y, z, w return out end -- Normalize the vertex after transformation local function normalizeVertex(v) if v[4] == 0 then return v[1], v[2], v[3] end return v[1] / v[4], v[2] / v[4], v[3] / v[4] end -- Define cube vertices using numerical indices local cubeVertices = { {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} } -- Create view matrix local function createViewMatrix(cameraPos, cameraTargetPos, cameraUp) local fx, fy, fz = normalize( cameraTargetPos[1] - cameraPos[1], cameraTargetPos[2] - cameraPos[2], cameraTargetPos[3] - cameraPos[3] ) local rx, ry, rz = normalize(cross(fx, fy, fz, cameraUp[1], cameraUp[2], cameraUp[3])) local ux, uy, uz = cross(rx, ry, rz, fx, fy, fz) local view = { rx, ux, -fx, 0, ry, uy, -fy, 0, rz, uz, -fz, 0, -dot(cameraPos[1], cameraPos[2], cameraPos[3], rx, ry, rz), -dot(cameraPos[1], cameraPos[2], cameraPos[3], ux, uy, uz), dot(cameraPos[1], cameraPos[2], cameraPos[3], fx, fy, fz), 1 } return view end -- Create perspective projection matrix local function perspectiveMatrix(fov, aspect, near, far) local f = 1.0 / tan(fov / 2) return { f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / (near - far), -1, 0, 0, (2 * far * near) / (near - far), 0 } end -- Create model matrix (scaled and translated) local function createModelMatrix(position, scale) return { scale[1], 0, 0, 0, 0, scale[2], 0, 0, 0, 0, scale[3], 0, position[1], position[2], position[3], 1 } end -- Transform and normalize vertices local function transformVertex(vertex, mvp, temp) multiplyMatrixVector(mvp, vertex, temp) return normalizeVertex(temp) end -- Preallocate tables local viewMatrix = createViewMatrix({0, 0, 5}, {0, 0, 0}, {0, 1, 0}) local projectionMatrix = perspectiveMatrix(pi / 4, 800 / 600, 0.1, 1000) local viewProjectionMatrix = multiplyMatrices(projectionMatrix, viewMatrix) local modelMatrix = createModelMatrix({0, 0, 0}, {1, 1, 1}) local modelViewProjectionMatrix = multiplyMatrices(viewProjectionMatrix, modelMatrix) local transformedVertices = {} local tempVertex = {} for i = 1, #cubeVertices do local x, y, z = transformVertex(cubeVertices[i], modelViewProjectionMatrix, tempVertex) transformedVertices[i] = {x, y, z} end -- Print transformed vertices for i, v in ipairs(transformedVertices) do print(string.format("Vertex %d: x = %.2f, y = %.2f, z = %.2f", i, v[1], v[2], v[3])) endExplanation of Optimizations:
-
Local Variables for Math Functions: By creating local references to
math.sqrt,math.tan, andmath.pi, we reduce the number of global table lookups, which can enhance performance, especially inside loops.local sqrt, tan, pi, abs = math.sqrt, math.tan, math.pi, math.abs -
Vector Representation: Vectors are represented as numerical indices (arrays) instead of tables with
x,y,zkeys. This reduces memory usage and access time.local cubeVertices = { {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} } -
Inlined Vector Operations: Instead of having separate functions that create and return new tables, vector operations return multiple values, which can be directly used without additional table allocations.
-
Matrix Multiplication Optimization: The
multiplyMatricesfunction avoids unnecessary table creations by optionally using a preallocatedresulttable. It accesses matrix elements directly by their numerical indices for faster computation.local function multiplyMatrices(a, b, result) -- Function body... end -
Matrix-Vector Multiplication Optimization: Similarly,
multiplyMatrixVectoruses numerical indices and optionally reuses a preallocatedouttable. -
Preallocation and Reuse of Temporary Tables: By reusing the
tempVertextable during vertex transformations, we avoid creating a new table for each vertex, thereby saving memory and reducing garbage collection overhead.local tempVertex = {} -
Simplified Matrix Creation: The
createModelMatrixfunction no longer takes rotation into account since it wasn't implemented. If rotation is needed, further optimizations can include handling it efficiently. -
Loop Optimization: The loop that transforms vertices avoids unnecessary table accesses and function calls by working with numerical indices and reusing temporary variables.
for i = 1, #cubeVertices do local x, y, z = transformVertex(cubeVertices[i], modelViewProjectionMatrix, tempVertex) transformedVertices[i] = {x, y, z} end
These optimizations should make your code run faster and be more memory-efficient, especially when dealing with larger models or running the code multiple times.
- Localizing Math Functions: Accessing global variables is slower in Lua. By localizing frequently used