My favorites | Sign in
Project Logo
                
Search
for
Updated Jun 18, 2008 by Ichitaro.Masuda
DevNoteJP  

更新履歴


rbofについて

swigの使い方がよく分からなかった作者が、この際だからRubyの拡張ライブラリの勉強を、とはじめてのC++を駆使して見よう見まねで書いたopenFrameworksの愚直なラッパーです。以下、留意点になります。

  • より高速なaction-codingを目標にしていますが、Processingにはライブラリの豊富さという利点があるため、別なプロジェクトとしました。
  • APIを極力揃えるために、悪い部分もそのまま踏襲しています。今後、よりRubyらしいラッパーにしていくかもしれません。
  • 例外はおろかエラーコードすら返さずに、stdoutにエラーを吐くことがありますが、この点についてはopenFrameworks側の問題です。
  • Mac OSXしかサポートしていません。コンパイルにはXCodeが必要です。どなたか他のOSでもコンパイルできるようextconf.rbを書いて下さい><
  • バグレポートや要望があればIssuesにお願いします。

導入

現在アルファ版のため、バイナリをダウンロードできるようにはなっていません。お手数ですがチェックアウトして下さい:

$ svn checkout http://rbof.googlecode.com/svn/trunk/ rbof-read-only

ライブラリを利用するには、あなたが作成するRubyコードで以下のようにします。

require 'rbof'

その際、ロードパスにあらかじめ以下の3つのファイルを設置しておいて下さい。


コード例

openFrameworksをRubyから使ったときの雰囲気をお伝えします。実行してみたい方は是非チェックアウトして下さい!

フォントの使用:

require 'rbof'

class App < OF::SimpleApp
  include OF
  
  def setup
    noFill
    background 0, 0, 0
    setVerticalSync true
    
    @font = TrueTypeFont.new
    font_size = 32
    @font.loadFont "verdana.ttf", font_size
    @font.setLineHeight font_size * 1.25
  end

  def draw
    setColor 0xffffff
    drawBitmapString "click to view the bounding box", 20, 40
    
    str = millis_to_print
    @font.drawString str, 20, 100
    
    # draw the bounding box
    if @pressed
      setColor 0xff0000
      box = @font.getStringBoundingBox str, 20, 100
      rect box.x, box.y, box.width, box.height
    end
  end
  
  def millis_to_print
    result = getElapsedTimeMillis.to_s
    %w[
      zero one two three four
      five six seven eight nine
    ].each_with_index do |s, i|
      result.gsub!(/#{i}/) {"#{s}\n"}
    end
    result
  end
  
  def mousePressed(x, y, button)
    @pressed = true
  end
  
  def mouseReleased  
    @pressed = false
  end
end

OF.setupOpenGL 400, 400, OF::WINDOW
OF.runApp App.new

画像ファイルのロード、表示、保存:

require 'rbof'

class App < OF::SimpleApp
  include OF
  
  def setup
    setVerticalSync true
    
    @trans_img = Image.new
    @trans_img.loadImage "transparency.png"

    @noise_img = Image.new
    @noise_w, @noise_h = 100, 100
    @noise_img.allocate @noise_w, @noise_h, IMAGE_GRAYSCALE
    @pixels = Array.new @noise_w * @noise_h
    
    @msg = "click to capture screen"
  end
  
  def update
    @pixels.map! {rand 255}
    @noise_img.setFromPixels @pixels, @noise_w, @noise_h, IMAGE_GRAYSCALE
  end

  def draw
    w, h = getWidth, getHeight
    @noise_img.draw 0, 0, w, h
    
    drawBitmapString @msg, 20, 40
    
    translate 0.5 * w, 0.5 * h, 0
    pushMatrix
      rotate getFrameNum * 2, 0, 1, 0
      enableAlphaBlending
        @trans_img.draw(
          -0.5 * @trans_img.width + 50, 
          -0.5 * @trans_img.height
        )
      disableAlphaBlending
    popMatrix
  end
  
  def mousePressed(x, y, button)
    save_img = Image.new
    save_img.grabScreen 0, 0, getWidth, getHeight
    file_name = "snapshot.png"
    save_img.saveImage file_name
    
    @msg = "done! see #{toDataPath file_name}"
  end
end

OF.setupOpenGL 400, 400, OF::WINDOW
OF.runApp App.new

サウンドファイルの再生:

require 'rbof'

class App < OF::SimpleApp
  include OF
  
  def setup
    background 0, 0, 0
    setVerticalSync true
    
    @sound = SoundPlayer.new
    @sound.loadSound "1085.mp3"
    @sound.setLoop true
    @sound.play
  end
  
  def update
    @sound.setSpeed 2 * (1 - mouseY.to_f / getHeight)
    @sound.setPan mouseX.to_f / getWidth
  end
  
  def draw
    setColor 0xffffff
    drawBitmapString "move your mouse", 20, 40
    
    setColor 0xffff00
    w = 5
    soundGetSpectrum(81).each_with_index do |v, i|
      rect i * w, 200, w, -v * 800
      rect i * w, 200, w, v * 800
    end
  end
end

OF.setupOpenGL 400, 400, OF::WINDOW
OF.runApp App.new

カメラ入力からピクセルを取得:

require 'rbof'

class App < OF::SimpleApp
  include OF
  
  def setup
    setBackgroundAuto false
    setVerticalSync true
    @cam = VideoGrabber.new
    @cam.initGrabber 320, 240
    @pixels = Array.new 320 * 240 * 3
  end
  
  def update
    @cam.grabFrame
  end
  
  def draw
    if @cam.isFrameNew
      background 255, 255, 255
      draw_dots
      draw_src
    end
  end
  
  def draw_dots
    setColor 0
    pushMatrix
      translate 320, 0, 0
      pixels = @cam.getPixels
      4.step 320, 8 do |i|
        4.step 240, 8 do |j|
          v = pixels[(j * 320 + i) * 3]
          v = 1 - v / 255.0
          circle i, j, 10 * v
        end
      end 
    popMatrix
  end
  
  def draw_src
    setColor 0xffffff
    @cam.draw 0, 0
  end
  
  def keyPressed(key)
    @cam.videoSettings if key.chr == 's'
  end
end

OF.setupOpenGL 640, 240, OF::WINDOW
OF.runApp App.new

ダイナミックサウンド:

require 'rbof'

class App < OF::SimpleApp
  include OF
  
  def setup
    background 0, 0, 0
    setColor 0xFFFFFF
    
    @phase = 0
    @phase_adder = 0
    @phase_adder_target = 0
  	
    buff_size = 1024
    @audio = Array.new buff_size, 0
    soundStreamSetup 1, 0, self, 44100, buff_size, 4
  end
  
  def draw
    drawBitmapString "move your mouse or click to make a noise", 20, 40
    400.times do |i|
      line i, 200, i, 200 + @audio[i] * 500.0
    end
  end
  
  def mouseMoved(x, y)
    height = 1 - y.to_f / getHeight
  	freq = 2000.0 * height
  	@phase_adder_target = (freq / 44100) * TWO_PI
  end
  
  def mousePressed(x, y, button)
    @pressed = true
  end
  
  def mouseReleased 
    @pressed = false
  end
  
  def audioRequested(buff, size, channels)
    volume = 0.1
    
    if @pressed
      buff.map! {randomf * volume}
    else
      @phase_adder = 0.95 * @phase_adder + 0.05 * @phase_adder_target
      buff.length.times do |i|
        @phase += @phase_adder
        buff[i] = Math.sin(@phase) * volume
      end
    end
    @audio = buff
  end
end

OF.setupOpenGL 400, 400, OF::WINDOW
OF.runApp App.new

openFrameworksとの命名の違い

OFというモジュールの中に全て定義されているので、名前に接頭辞 "of" や "OF" を付けていません。 本家のドキュメントと以下の一覧から対応を探して下さい。

Constants:
	CLOSE
	FOUR_PI
	FULLSCREEN
	GAME_MODE
	GL_ALPHA
	GL_BLUE
	GL_COLOR_INDEX
	GL_DEPTH_COMPONENT
	GL_GREEN
	GL_LUMINANCE
	GL_LUMINANCE_ALPHA
	GL_RED
	GL_RGB
	GL_RGBA
	GL_STENCIL_INDEX
	HALF_PI
	IMAGE_COLOR
	IMAGE_COLOR_ALPHA
	IMAGE_GRAYSCALE
	IMAGE_UNDEFINED
	KEY_BACKSPACE
	KEY_DEL
	KEY_DOWN
	KEY_END
	KEY_F1
	KEY_F10
	KEY_F11
	KEY_F12
	KEY_F2
	KEY_F3
	KEY_F4
	KEY_F5
	KEY_F6
	KEY_F7
	KEY_F8
	KEY_F9
	KEY_HOME
	KEY_INSERT
	KEY_LEFT
	KEY_MODIFIER
	KEY_PAGE_DOWN
	KEY_PAGE_UP
	KEY_RETURN
	KEY_RIGHT
	KEY_UP
	LOOP_NONE
	LOOP_NORMAL
	LOOP_PALINDROME
	M_TWO_PI
	PI
	POLY_WINDING_ABS_GEQ_TWO
	POLY_WINDING_NEGATIVE
	POLY_WINDING_NONZERO
	POLY_WINDING_ODD
	POLY_WINDING_POSITIVE
	RECTMODE_CENTER
	RECTMODE_CORNER
	TWO_PI
	WINDOW

Module functions:
	bClearBg
	background
	beginShape
	bezier
	bezierVertex
	bgColor
	circle
	curve
	curveVertex
	disableAlphaBlending
	disableSmoothing
	drawBitmapString
	ellipse
	enableAlphaBlending
	enableSmoothing
	endShape
	fill
	getDay
	getElapsedTimeMillis
	getElapsedTimef
	getFrameNum
	getFrameRate
	getHeight
	getHours
	getMinutes
	getMonth
	getRectMode
	getScreenHeight
	getScreenWidth
	getSeconds
	getVersionInfo
	getWeekDay
	getWidth
	getWindowMode
	getWindowPositionX
	getWindowPositionY
	getYear
	hideCursor
	launchBrowser
	line
	nextContour
	nextPow2
	noFill
	popMatrix
	pushMatrix
	random
	randomf
	randomuf
	rect
	rotate
	runApp
	scale
	seedRandom
	setBackgroundAuto
	setCircleResolution
	setColor
	setFrameRate
	setFullscreen
	setPolyMode
	setRectMode
	setVerticalSync
	setWindowPosition
	setWindowShape
	setWindowTitle
	setupOpenGL
	setupScreen
	showCursor
	sleepMillis
	soundGetSpectrum
	soundSetVolume
	soundStopAll
	soundStreamClose
	soundStreamListDevices
	soundStreamSetup
	soundStreamStart
	soundStreamStop
	toDataPath
	toString
	toggleFullscreen
	translate
	triangle
	vertex

Image methods:
	allocate
	bpp
	clear
	draw
	getPixels
	grabScreen
	height
	loadImage
	resize
	saveImage
	setFromPixels
	setImageType
	setUseTexture
	type
	width

Rectangle methods:
	height
	width
	x
	y

Serial methods:
	bVerbose
	close
	enumerateDevices
	readByte
	readBytes
	setVerbose
	setup
	writeByte
	writeBytes

SimpleApp methods:
	audioReceived
	audioRequested
	draw
	exit
	keyPressed
	keyReleased
	mouseDragged
	mouseMoved
	mousePressed
	mouseReleased
	mouseX
	mouseY
	setup
	update

SoundPlayer methods:
	getIsPlaying
	getPan
	getPosition
	getSpeed
	loadSound
	play
	setLoop
	setMultiPlay
	setPan
	setPaused
	setPosition
	setSpeed
	setVolume
	stop
	unloadSound

Texture methods:
	allocate
	clear
	draw
	loadData
	loadScreenData

TrueTypeFont methods:
	bAntiAlised
	bFullCharacterSet
	bLoadedOk
	drawString
	getLineHeight
	getStringBoundingBox
	loadFont
	nCharacters
	setLineHeight
	stringHeight
	stringWidth

VideoGrabber methods:
	close
	draw
	getPixels
	grabFrame
	height
	initGrabber
	isFrameNew
	listDevices
	setDeviceID
	setUseTexture
	setVerbose
	videoSettings
	width

VideoPlayer methods:
	bLoaded
	closeMovie
	draw
	getDuration
	getPixels
	getPosition
	getSpeed
	height
	idleMovie
	isFrameNew
	loadMovie
	play
	setLoopState
	setPaused
	setPosition
	setSpeed
	setUseTexture
	setVolume
	speed
	stop
	width

ruby_caseを有効にする

以下のようにrequireするファイルを切り替えることで、Rubyらしいメソッド名に変更できます。ruby_caseとcamelCaseの併用はできませんので、ご注意下さい。

# to use method names like ruby, do this:
require 'rbof_rubycase'

# for example:
#   getFrameRate => frame_rate
#   bLoaded => loaded?
#   setVerticalSync => vertical_sync=

class App < OF::SimpleApp
  include OF
  
  def setup
    no_fill
    background 0, 0, 0
    self.vertical_sync = true
  end

  def draw
    color 0xffffff
    draw_bitmap_string "click to see all ruby_case", 20, 40
  end
  
  def mouse_pressed(x, y, button)
    load 'runme.rb'
  end
end

OF.setup_open_gl 400, 400, OF::WINDOW
OF.run_app App.new

あくまで予定


Sign in to add a comment
Hosted by Google Code