Skip to content

Instantly share code, notes, and snippets.

@TannerRogalsky
Created January 23, 2017 13:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TannerRogalsky/1e9950c116bc88a94cc0cf9ff571cff2 to your computer and use it in GitHub Desktop.
Save TannerRogalsky/1e9950c116bc88a94cc0cf9ff571cff2 to your computer and use it in GitHub Desktop.
Fast vertex setting in Love using ImageData and the FFI
local num_verts = 100000
local vertices = {}
for i=1,num_verts do
vertices[i] = {0, 0, 0, 0, 255, 255, 255, 255}
end
local ffi = require('ffi')
ffi.cdef[[
typedef struct {
float x, y;
float s, t;
unsigned char r, g, b, a;
} fm_vertex;
]]
local vertex_size = ffi.sizeof('fm_vertex')
local pixel_size = ffi.sizeof('unsigned char[4]')
local imageData = love.image.newImageData(num_verts / pixel_size * vertex_size, 1)
local data = ffi.cast("fm_vertex*", imageData:getPointer())
local times = {}
local mesh = love.graphics.newMesh(num_verts, 'fan', 'stream')
function love.load()
for i=0,num_verts-1 do
local vertex = data[i]
vertex.r = 255
vertex.g = 255
vertex.b = 255
vertex.a = 255
end
end
local t = 0
function love.update(dt)
t = t + dt
local radius = 300
for i=1,num_verts do
local phi = (i - 1) / num_verts * math.pi * 2
vertices[i][1] = math.cos(phi) * radius + math.cos(t + phi) * radius / 4
vertices[i][2] = math.sin(phi) * radius
local vertex = data[i - 1]
vertex.x = vertices[i][1]
vertex.y = vertices[i][2]
end
local start = love.timer.getTime()
-- mesh:setVertices(vertices) -- SLOW
mesh:setVertices(imageData) -- FAST
local stop = love.timer.getTime()
local time = stop - start
table.insert(times, time)
end
function love.draw()
love.graphics.draw(mesh, love.graphics.getWidth() / 2, love.graphics.getHeight() / 2)
end
function love.keypressed()
local total = 0
for i,time in ipairs(times) do
total = total + time
end
print('average', string.format("%0.32f", total / #times))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment