Class: Engine::Texture

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Serializable

allowed_class?, get_class, included, register_class, #uuid

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



7
8
9
# File 'lib/engine/texture.rb', line 7

def source
  @source
end

#textureObject (readonly)

Returns the value of attribute texture.



7
8
9
# File 'lib/engine/texture.rb', line 7

def texture
  @texture
end

Class Method Details

.for(path, source: :game) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/engine/texture.rb', line 22

def self.for(path, source: :game)
  full_path = if source == :engine
    File.expand_path(File.join(ENGINE_DIR, "assets", path))
  else
    File.expand_path(File.join(GAME_DIR, path))
  end
  texture_cache[[path, source]] ||= create(relative_path: path, file_path: full_path, source: source)
end

.from_serializable_data(data) ⇒ Object



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

def self.from_serializable_data(data)
  self.for(data[:path], source: (data[:source] || :game).to_sym)
end

.texture_cacheObject



31
32
33
# File 'lib/engine/texture.rb', line 31

def self.texture_cache
  @texture_cache ||= {}
end

Instance Method Details

#awakeObject



17
18
19
20
# File 'lib/engine/texture.rb', line 17

def awake
  @texture = ' ' * 4
  load_texture
end

#load_textureObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/engine/texture.rb', line 35

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

  image = ChunkyPNG::Image.from_file(@file_path)
  image_data = image.to_rgba_stream
  image_width = image.width
  image_height = image.height

  # Flip rows vertically so textures follow OpenGL convention (V=0 at bottom)
  row_size = image_width * 4
  flipped = String.new(capacity: image_data.bytesize)
  (image_height - 1).downto(0) do |row|
    flipped << image_data.byteslice(row * row_size, row_size)
  end

  Engine::GL.TexImage2D(Engine::GL::TEXTURE_2D, 0, Engine::GL::RGBA32F, image_width, image_height, 0, Engine::GL::RGBA, Engine::GL::UNSIGNED_BYTE, flipped)
  Engine::GL.GenerateMipmap(Engine::GL::TEXTURE_2D)
end

#serializable_dataObject



13
14
15
# File 'lib/engine/texture.rb', line 13

def serializable_data
  { path: @relative_path, source: @source }
end