xrforge/manyfold/root/hook.d/experience_updated/200-to-gltf.rb

100 lines
2.5 KiB
Ruby
Raw Normal View History

#!/usr/bin/env ruby
require 'json'
require_relative './../../xrforge.rb'
# Check if a filename is provided
if ARGV.length != 1
puts "Usage: #{$0} <path/to/experience/somefile.xxx>"
exit 1
end
filename = ARGV[0]
require 'base64'
require 'json'
## Updates the 'uri' of an image in a GLTF hash when a matching PNG filename is found.
##
## gltf: a parsed JSON hash from a .gltf file
## png_path: path to the PNG file to embed
##
## returns: true if updated successfully, false if not found
#def update_gltf_image(gltf, png_path)
# # Get base name (without extension)
# name = File.basename(png_path, '.png')
#
# # Find image entry with the same name
# image_entry = gltf['images']&.find { |img| img['name'] == name }
#
# unless image_entry
# warn "No image named '#{name}' found in GLTF"
# return false
# end
#
# # Read and base64-encode the PNG file
# data = File.binread(png_path)
# encoded = Base64.strict_encode64(data)
#
# # Update the URI field with the base64-encoded PNG data URI
# image_entry['uri'] = "data:image/png;base64,#{encoded}"
#
# puts "Updated image '#{name}' in GLTF"
# true
#end
begin
# Change the directory
dir = File.dirname(filename)
Dir.chdir( File.dirname(filename) )
# Read and parse the JSON file
data = JSON.parse( File.read( "datapackage.json" ) )
ext = File.extname(filename)
filenameWithoutExt = File.basename(filename, ext)
if ! XRForge::MODEL_EXT.any?( ext )
exit(0) # not a 3d file
end
logfile = File.join( File.dirname(filename), ".xrforge/log.txt" )
XRForge.log("✅ generating gltf", logfile)
gltf_path = ".xrforge/#{filenameWithoutExt}.gltf"
system("assimp export #{filename} #{gltf_path}")
system("assimp extract #{filename} | sed 's|/.*/||g'")
# Read and parse the GLTF JSON
gltf = JSON.parse(File.read(gltf_path))
# Ensure images section exists
unless gltf['images'] && gltf['images'].is_a?(Array)
abort("No 'images' array found in #{gltf_path}")
end
# Iterate through the images array
gltf['images'].each_with_index do |img, i|
name = img['name']
next unless name && !name.empty?
old_filename = "website_img#{i}.png"
new_filename = "#{name}.png"
if File.exist?(old_filename)
XRForge.log("✅ Renaming #{old_filename} -> #{new_filename}", logfile)
File.rename(old_filename, new_filename)
end
end
XRForge.log(" ", logfile)
rescue Errno::ENOENT
puts "File #{filename} not found"
rescue JSON::ParserError
puts "Error parsing JSON from #{filename}"
rescue => e
puts "An error occurred: #{e.message}"
end