xrforge/manyfold/root/hook.d/experience_updated/1050-compile-textures.rb

80 lines
2.2 KiB
Ruby
Executable file

#!/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'
begin
# Change the directory
dir = File.dirname(filename)
Dir.chdir( dir )
# Read and parse the JSON file
data = JSON.parse( File.read( "datapackage.json" ) )
logfile = File.join( File.dirname(filename), ".xrforge/log.txt" )
update = false
data['resources'].each do |resource|
ext = File.extname(resource['path'])
filenameWithoutExt = File.basename(resource['path'], ext)
if ! XRForge::MODEL_EXT.any?( ext )
next # skip unknown 3d files
end
if ! resource['path'].match(/^[a-zA-Z0-9]/)
next # skip filenames like '_generated.glb' e.g. (produced by hooks)
end
XRForge.log("✅ compiling textures", logfile)
gltf_path = ".xrforge/#{filenameWithoutExt}.gltf"
# 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)
XRForge.log("✅ No 'images' array found in #{gltf_path}",logfile)
next
end
# Iterate through the images array
gltf['images'].each_with_index do |img, i|
name = img['name']
next unless name && !name.empty?
new_filename = "#{dir}/#{name}.png"
# move file to modeldirectory (but dont overwrite if user overwrite it)
XRForge.log("🤔 checking #{new_filename}",logfile)
if File.exist?(new_filename)
XRForge.log("✅ importing #{new_filename} -> #{resource['path']}",logfile)
img['uri'] = "#{name}.png"
update = true
end
end
if update
File.write( gltf_path, JSON.pretty_generate(gltf) )
XRForge.log("✅ writing #{resource['path']}",logfile)
system("assimp export #{gltf_path} #{resource['path']} --embed-textures")
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