Class: Engine::Texture

Inherits:
Object
  • Object
show all
Defined in:
lib/engine/texture.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path, flip) ⇒ Texture

Returns a new instance of Texture.



8
9
10
11
12
13
# File 'lib/engine/texture.rb', line 8

def initialize(file_path, flip)
  @file_path = file_path
  @flip = flip
  @texture = ' ' * 4
  load_texture
end

Instance Attribute Details

#textureObject (readonly)

Returns the value of attribute texture.



5
6
7
# File 'lib/engine/texture.rb', line 5

def texture
  @texture
end

Class Method Details

.for(path, flip: false) ⇒ Object



15
16
17
18
# File 'lib/engine/texture.rb', line 15

def self.for(path, flip: false)
  full_path = File.expand_path(File.join(GAME_DIR, path))
  texture_cache[[full_path, flip]]
end

.texture_cacheObject



20
21
22
23
24
# File 'lib/engine/texture.rb', line 20

def self.texture_cache
  @texture_cache ||= Hash.new do |hash, key|
    hash[key] = new(key[0], key[1])
  end
end

Instance Method Details

#load_textureObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/engine/texture.rb', line 26

def load_texture
  tex = ' ' * 4
  GL.GenTextures(1, tex)
  @texture = tex.unpack('L')[0]
  GL.BindTexture(GL::TEXTURE_2D, @texture)
  GL.TexParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_S, GL::REPEAT)
  GL.TexParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_T, GL::REPEAT)
  GL.TexParameteri(GL::TEXTURE_2D, GL::TEXTURE_MIN_FILTER, GL::LINEAR)
  GL.TexParameteri(GL::TEXTURE_2D, GL::TEXTURE_MAG_FILTER, GL::LINEAR)

  image = read_image
  image_data = image.to_rgba_stream
  image_width = image.width
  image_height = image.height

  GL.TexImage2D(GL::TEXTURE_2D, 0, GL::RGBA, image_width, image_height, 0, GL::RGBA, GL::UNSIGNED_BYTE, image_data)
  GL.GenerateMipmap(GL::TEXTURE_2D)
end

#read_imageObject



45
46
47
48
49
50
51
# File 'lib/engine/texture.rb', line 45

def read_image
  if @flip
    ChunkyPNG::Image.from_file(@file_path).flip_horizontally
  else
    ChunkyPNG::Image.from_file(@file_path)
  end
end