Ruby Sketchup 中的 onSaveModel 观察器导致无限循环

onSaveModel observer in Ruby Sketchup causes infinite loop

我正在尝试使用 Sketchup 中的内置 ModelObserver class 在用户保存当前模型时触发文件导出。出于某种原因,我的代码触发了一个无限循环——文本 'onSaveModel' 只输出一次,但 exportModel() 陷入循环。

我的 Ruby 技能很低,但我也听说过 SketchUp Ruby API 时不时出现故障。有人以前遇到过这个问题吗?

代码:

def protohypeEntry
    Sketchup.active_model.add_observer(ProtohypeModelObserver.new)
end

class ProtohypeModelObserver < Sketchup::ModelObserver
    def onSaveModel(model)
        puts "onSaveModel" + model.to_s
        exportModel()
    end
end

def exportModel()
    puts "exportModel()"
    model = Sketchup.active_model

    options_hash = { :triangulated_faces   => true,
     :doublesided_faces    => true,
     :edges                => false,
     :author_attribution   => true,
     :texture_maps         => true,
     :selectionset_only    => false,
     :preserve_instancing  => true }

     status = model.export 'C:\Users\Pelle\Test\test.dae', options_hash

 end

 protohypeEntry() 

导出也会触发 onSaveModel(API 文档对此不明确,我会在内部添加一个问题),因此您在观察者事件中的导出将触发无限循环.

设置一个内部标志来指示脚本的状态,并在导出过程中提前中断。

module Example

  def self.protohypeEntry
    Sketchup.active_model.add_observer(ProtohypeModelObserver.new)
  end

  class ProtohypeModelObserver < Sketchup::ModelObserver
    def onSaveModel(model)
      puts "onSaveModel" + model.to_s
      Example.exportModel()
    end
  end

  def self.exportModel()
    return if @exporting

    puts "exportModel()"
    model = Sketchup.active_model

    options_hash = { :triangulated_faces   => true,
      :doublesided_faces    => true,
      :edges                => false,
      :author_attribution   => true,
      :texture_maps         => true,
      :selectionset_only    => false,
      :preserve_instancing  => true
    }

    @exporting = true
    status = model.export 'C:/test.dae', options_hash
  ensure
    # Just in case model.export should raise an exception we guarranty the flag
    # is reset.
    @exporting = false
  end

end

Example.protohypeEntry()