Skip to content

Instantly share code, notes, and snippets.

@pushmatrix
Last active June 10, 2020 16:57
Show Gist options
  • Save pushmatrix/c8f18cc97e63b2cc17c2891c6433d79d to your computer and use it in GitHub Desktop.
Save pushmatrix/c8f18cc97e63b2cc17c2891c6433d79d to your computer and use it in GitHub Desktop.
Create a usdz box in ruby land
USDZ_TEMPLATE = File.open('cube.usdz', 'rb').read
def generate_usdz(length, width, height)
usdz = USDZ_TEMPLATE.dup
# This is the block of bytes in the buffer that represent the vertex positions
# They are stored as 32-bit floats
buffer = usdz[1168,624].unpack("F*")
buffer = resize_box_buffer(buffer, length, width, height)
usdz[1168, 624] = buffer.pack("F*")
usdz
end
# This function can be used by both the .glb and .usdz generation for modifying buffers.
# It takes in a buffer representing vertex data, and resizes the vertices based on specified dimensions
def resize_box_buffer(buffer, length, width, height)
# Divide by two because of the symmetry of the cube. Ex: if the width is 3, then one side will be -1.5 and the other will be 1.5
length *= 0.5
width *= 0.5
height *= 0.5
thickness = 0.01
buffer.map { |element|
sign = element<=>0
if element.abs == 51
sign * length
elsif element.abs == 52
sign * height
elsif element.abs == 53
sign * width
elsif element.abs == 41
sign * (length - thickness)
elsif element.abs == 42
sign * (height - thickness)
elsif element.abs == 43
sign * (width - thickness)
else
element
end
}
end
# Example usage. You can use the output of this to save as a file or serve as a file
generate_usdz(1, 1, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment