# Saving a mesh in an image.

It would be nice to be able to store binary data, like an array of vec3’s. I’ve made two functions to store the data in an image while waiting for this functionality. I guess I could store texture data in the same if I wanted to, now just making up some texture coords…

Since the space 0-255 is quite small I normalize the data which you then need to scale up and tell the origin when loading it.

``````function saveMesh(name, vertices)
local im = image(#vertices, 1)
local max = vec3(-math.huge, -math.huge, -math.huge)
local min = vec3(math.huge, math.huge, math.huge)
for i,v in ipairs(vertices) do
max = vec3(math.max(v.x,max.x),
math.max(v.y,max.y),
math.max(v.z,max.z))
min = vec3(math.min(v.x,min.x),
math.min(v.y,min.y),
math.min(v.z,min.z))
end
local span = math.max(math.abs(max.x - min.x),
math.abs(max.y - min.y),
math.abs(max.z - min.z))

for i,v in ipairs(vertices) do
v = (v - min) / span * 255
im:set(i,1, v.x,v.y,v.z)
end
saveImage("Documents:" .. name, im)
end

local im = readImage("Documents:" .. name)
if not im then return nil end
local w,h = spriteSize(im)
local vertices = {}
local texs = {}

for i = 1,w do
local r,g,b = im:get(i,1)
local v = origin + (vec3(r,g,b) * scl) / 255
table.insert(vertices, v)
if (i-1)%3 == 0 then
table.insert(texs, vec2(0,0))
table.insert(texs, vec2(1,0))
table.insert(texs, vec2(0,1))
end
end

return vertices, texs
end
``````

Go with two bytes per value to get more space.