Class: Rgltf::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/rgltf/writer.rb,
lib/rgltf/writer/buffer_merger.rb,
lib/rgltf/writer/default_omitter.rb,
lib/rgltf/writer/extension_serializer.rb

Defined Under Namespace

Classes: BufferMerger, DefaultOmitter, ExtensionSerializer

Instance Method Summary collapse

Constructor Details

#initialize(document, validate: true) ⇒ Writer

Returns a new instance of Writer.

Raises:



5
6
7
8
9
10
11
12
13
14
# File 'lib/rgltf/writer.rb', line 5

def initialize(document, validate: true)
  @document = document
  @validate = validate
  return unless validate

  result = Validator.validate(document)
  return if result.errors.empty?

  raise ValidationError, result.errors.map { |issue| "#{issue.path}: #{issue.message}" }.join('; ')
end

Instance Method Details

#to_glbObject



16
17
18
19
20
# File 'lib/rgltf/writer.rb', line 16

def to_glb
  json, binary = serialized_payload
  json.fetch('buffers', []).each { |buffer| buffer.delete('uri') }
  GLB.write(JSON.generate(json), binary.empty? ? nil : binary)
end

#write_glb(path) ⇒ Object



22
23
24
25
26
27
# File 'lib/rgltf/writer.rb', line 22

def write_glb(path)
  File.binwrite(path, to_glb)
  path
rescue Errno::EACCES, Errno::ENOENT => e
  raise MissingResourceError, e.message
end

#write_gltf(path, embed: false) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rgltf/writer.rb', line 29

def write_gltf(path, embed: false)
  json, binary = serialized_payload
  unless binary.empty?
    if embed
      json.fetch('buffers').first['uri'] = data_uri(binary)
    else
      extension = File.extname(path)
      basename = File.basename(path, extension)
      bin_path = File.join(File.dirname(path), "#{basename}.bin")
      File.binwrite(bin_path, binary)
      json.fetch('buffers').first['uri'] = File.basename(bin_path)
    end
  end
  File.write(path, JSON.pretty_generate(json) << "\n")
  path
rescue Errno::EACCES, Errno::ENOENT => e
  raise MissingResourceError, e.message
end