Module: SFML::Assets

Defined in:
lib/sfml/assets.rb

Overview

Cached, search-path-driven asset loader. Use it to avoid repeating file paths and to load each asset exactly once.

font  = SFML::Assets.font("DejaVuSans")
tex   = SFML::Assets.texture("hero")           # finds hero.png/.jpg/.bmp
blip  = SFML::Assets.sound("blip")             # finds blip.wav/.ogg/...
music = SFML::Assets.music("track")            # NOT cached (stateful)

By default the search root is ‘<dir of $0>/assets/`. Override:

SFML::Assets.root = File.expand_path("data", __dir__)
SFML::Assets.add_search_path("/usr/local/share/mygame")

Cache survives until you call .clear or the process exits.

Defined Under Namespace

Classes: NotFound

Constant Summary collapse

TEXTURE_EXTS =
%w[.png .jpg .jpeg .bmp .gif .tga].freeze
SOUND_EXTS =
%w[.wav .ogg .flac .mp3].freeze
MUSIC_EXTS =
SOUND_EXTS
FONT_EXTS =
%w[.ttf .otf].freeze

Class Method Summary collapse

Class Method Details

.add_search_path(path) ⇒ Object



38
39
40
# File 'lib/sfml/assets.rb', line 38

def add_search_path(path)
  search_paths << File.expand_path(path) unless search_paths.include?(File.expand_path(path))
end

.clearObject

Drop everything from the in-memory cache. New loads will re-read from disk and recreate textures, fonts, sound buffers.



44
45
46
47
# File 'lib/sfml/assets.rb', line 44

def clear
  @cache&.clear
  self
end

.font(name) ⇒ Object



49
50
51
# File 'lib/sfml/assets.rb', line 49

def font(name)
  cache[[:font, name]] ||= load_font(name)
end

.music(name) ⇒ Object

Music is intentionally NOT cached — it owns a streaming position and play state, so each caller wants its own instance.



63
64
65
66
67
# File 'lib/sfml/assets.rb', line 63

def music(name)
  path = locate(name, MUSIC_EXTS) or raise NotFound,
    "Music #{name.inspect} not found. Searched: #{search_paths.inspect}"
  Music.load(path)
end

.root=(path) ⇒ Object



34
35
36
# File 'lib/sfml/assets.rb', line 34

def root=(path)
  self.search_paths = [path]
end

.search_pathsObject



25
26
27
# File 'lib/sfml/assets.rb', line 25

def search_paths
  @search_paths ||= [default_root]
end

.search_paths=(paths) ⇒ Object



29
30
31
32
# File 'lib/sfml/assets.rb', line 29

def search_paths=(paths)
  @search_paths = Array(paths).map { |p| File.expand_path(p) }
  @cache&.clear
end

.sound(name) ⇒ Object



57
58
59
# File 'lib/sfml/assets.rb', line 57

def sound(name)
  cache[[:sound, name]] ||= load_sound_buffer(name)
end

.texture(name) ⇒ Object



53
54
55
# File 'lib/sfml/assets.rb', line 53

def texture(name)
  cache[[:texture, name]] ||= load_texture(name)
end