Ran rubocop -a

This commit is contained in:
2020-12-14 16:04:31 -06:00
parent 2447dde1af
commit 26dd688124
59 changed files with 770 additions and 741 deletions

View File

@@ -1,6 +1,6 @@
source "https://rubygems.org" source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
# Specify your gem's dependencies in cyberarm_engine.gemspec # Specify your gem's dependencies in cyberarm_engine.gemspec
gemspec gemspec

View File

@@ -7,4 +7,4 @@ Rake::TestTask.new(:test) do |t|
t.test_files = FileList["test/**/*_test.rb"] t.test_files = FileList["test/**/*_test.rb"]
end end
task :default => :test task default: :test

View File

@@ -1,5 +1,4 @@
lib = File.expand_path("lib", __dir__)
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "cyberarm_engine/version" require "cyberarm_engine/version"
@@ -9,8 +8,8 @@ Gem::Specification.new do |spec|
spec.authors = ["Cyberarm"] spec.authors = ["Cyberarm"]
spec.email = ["matthewlikesrobots@gmail.com"] spec.email = ["matthewlikesrobots@gmail.com"]
spec.summary = %q{Make games quickly and easily with gosu} spec.summary = "Make games quickly and easily with gosu"
spec.description = %q{Yet another game making framework around gosu} spec.description = "Yet another game making framework around gosu"
spec.homepage = "https://github.com/cyberarm/cyberarm_engine" spec.homepage = "https://github.com/cyberarm/cyberarm_engine"
spec.license = "MIT" spec.license = "MIT"
@@ -21,20 +20,20 @@ Gem::Specification.new do |spec|
"public gem pushes." "public gem pushes."
end end
spec.files = `git ls-files -z`.split("\x0").reject do |f| spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/}) f.match(%r{^(test|spec|features)/})
end end
spec.bindir = "exe" spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib", "assets"] spec.require_paths = %w[lib assets]
spec.add_dependency "clipboard", "~> 1.3.4"
spec.add_dependency "excon", "~> 0.76.0" spec.add_dependency "excon", "~> 0.76.0"
spec.add_dependency "gosu", "~> 0.15.0" spec.add_dependency "gosu", "~> 0.15.0"
spec.add_dependency "gosu_more_drawables", "~> 0.3" spec.add_dependency "gosu_more_drawables", "~> 0.3"
spec.add_dependency "clipboard", "~> 1.3.4"
# spec.add_dependency "ffi", :platforms => [:mswin, :mingw] # Required by Clipboard on Windows # spec.add_dependency "ffi", :platforms => [:mswin, :mingw] # Required by Clipboard on Windows
spec.add_development_dependency "bundler", "~> 1.16" spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "minitest", "~> 5.0" spec.add_development_dependency "minitest", "~> 5.0"
spec.add_development_dependency "rake", "~> 13.0"
end end

View File

@@ -1,4 +1,4 @@
CYBERARM_ENGINE_ROOT_PATH = File.expand_path("../..", __FILE__) CYBERARM_ENGINE_ROOT_PATH = File.expand_path("..", __dir__)
begin begin
require File.expand_path("../../ffi-gosu/lib/gosu", File.dirname(__FILE__)) require File.expand_path("../../ffi-gosu/lib/gosu", File.dirname(__FILE__))

View File

@@ -2,8 +2,10 @@ module CyberarmEngine
class Animator class Animator
DEFAULT_TWEEN = :linear DEFAULT_TWEEN = :linear
def initialize(start_time:, duration:, from:, to:, &block) def initialize(start_time:, duration:, from:, to:, &block)
@start_time, @duration = start_time, duration @start_time = start_time
@from, @to = from.dup, to.dup @duration = duration
@from = from.dup
@to = to.dup
@block = block @block = block
end end
@@ -23,7 +25,7 @@ module CyberarmEngine
from + (to - from) * send("tween_#{tween}", progress) from + (to - from) * send("tween_#{tween}", progress)
end end
def color_transition(from, to, tween = DEFAULT_TWEEN) def color_transition(from, to, _tween = DEFAULT_TWEEN)
r = transition(from.red, to.red) r = transition(from.red, to.red)
g = transition(from.green, to.green) g = transition(from.green, to.green)
b = transition(from.blue, to.blue) b = transition(from.blue, to.blue)

View File

@@ -2,9 +2,13 @@ module CyberarmEngine
class Background class Background
attr_accessor :x, :y, :z, :width, :height, :angle, :debug attr_accessor :x, :y, :z, :width, :height, :angle, :debug
attr_reader :background attr_reader :background
def initialize(x: 0, y: 0, z: 0, width: 0, height: 0, background: Gosu::Color::BLACK, angle: 0, debug: false) def initialize(x: 0, y: 0, z: 0, width: 0, height: 0, background: Gosu::Color::BLACK, angle: 0, debug: false)
@x,@y,@z = x,y,z @x = x
@width,@height = width,height @y = y
@z = z
@width = width
@height = height
@debug = debug @debug = debug
@paint = Paint.new(background) @paint = Paint.new(background)
@@ -31,8 +35,8 @@ module CyberarmEngine
end end
def update def update
origin_x = (@x + (@width/2)) origin_x = (@x + (@width / 2))
origin_y = (@y + (@height/2)) origin_y = (@y + (@height / 2))
points = [ points = [
@top_left = Vector.new(@x, @y), @top_left = Vector.new(@x, @y),
@@ -47,8 +51,8 @@ module CyberarmEngine
# 90 is up here, while gosu uses 0 for up. # 90 is up here, while gosu uses 0 for up.
radians = (@angle + 90).gosu_to_radians radians = (@angle + 90).gosu_to_radians
vector.x = (@x + (@width/2)) + ((temp_x * Math.cos(radians)) - (temp_y * Math.sin(radians))) vector.x = (@x + (@width / 2)) + ((temp_x * Math.cos(radians)) - (temp_y * Math.sin(radians)))
vector.y = (@y + (@height/2)) + ((temp_x * Math.sin(radians)) + (temp_y * Math.cos(radians))) vector.y = (@y + (@height / 2)) + ((temp_x * Math.sin(radians)) + (temp_y * Math.cos(radians)))
end end
# [ # [
@@ -67,11 +71,11 @@ module CyberarmEngine
a = la.x - lb.x a = la.x - lb.x
b = la.y - lb.y b = la.y - lb.y
c = Gosu.distance(la.x, la.y, lb.x, lb.y) c = Gosu.distance(la.x, la.y, lb.x, lb.y)
p a,b,c p a, b, c
d = (a * point.x + b * point.y + c).abs / (Math.sqrt(a * a + b * b)) d = (a * point.x + b * point.y + c).abs / Math.sqrt(a * a + b * b)
puts "Distance: #{d}" puts "Distance: #{d}"
exit! exit!
return d d
end end
def debug_outline def debug_outline
@@ -117,6 +121,7 @@ module CyberarmEngine
class Paint class Paint
attr_accessor :top_left, :top_right, :bottom_left, :bottom_right attr_accessor :top_left, :top_right, :bottom_left, :bottom_right
def initialize(background) def initialize(background)
set(background) set(background)
end end
@@ -124,7 +129,6 @@ module CyberarmEngine
def set(background) def set(background)
@background = background @background = background
if background.is_a?(Numeric) if background.is_a?(Numeric)
@top_left = background @top_left = background
@top_right = background @top_right = background
@@ -167,9 +171,9 @@ end
# Add <=> method to support Range based gradients # Add <=> method to support Range based gradients
module Gosu module Gosu
class Color class Color
def <=>(other) def <=>(_other)
self self
end end
end end
end end

View File

@@ -23,7 +23,7 @@ module CyberarmEngine
def ==(other) def ==(other)
@min == other.min && @min == other.min &&
@max == other.max @max == other.max
end end
# returns a new bounding box that includes both bounding boxes # returns a new bounding box that includes both bounding boxes
@@ -37,7 +37,7 @@ module CyberarmEngine
temp.max.y = [@max.y, other.max.y].max temp.max.y = [@max.y, other.max.y].max
temp.max.z = [@max.z, other.max.z].max temp.max.z = [@max.z, other.max.z].max
return temp temp
end end
# returns the difference between both bounding boxes # returns the difference between both bounding boxes
@@ -46,7 +46,7 @@ module CyberarmEngine
temp.min = @min - other.min temp.min = @min - other.min
temp.max = @max - other.max temp.max = @max - other.max
return temp temp
end end
# returns whether bounding box intersects other # returns whether bounding box intersects other
@@ -55,8 +55,8 @@ module CyberarmEngine
other.intersect?(self) other.intersect?(self)
elsif other.is_a?(BoundingBox) elsif other.is_a?(BoundingBox)
(@min.x <= other.max.x && @max.x >= other.min.x) && (@min.x <= other.max.x && @max.x >= other.min.x) &&
(@min.y <= other.max.y && @max.y >= other.min.y) && (@min.y <= other.max.y && @max.y >= other.min.y) &&
(@min.z <= other.max.z && @max.z >= other.min.z) (@min.z <= other.max.z && @max.z >= other.min.z)
else else
raise "Unknown collider: #{other.class}" raise "Unknown collider: #{other.class}"
end end
@@ -65,20 +65,20 @@ module CyberarmEngine
# does this bounding box envelop other bounding box? (inclusive of border) # does this bounding box envelop other bounding box? (inclusive of border)
def contains?(other) def contains?(other)
other.min.x >= min.x && other.min.y >= min.y && other.min.z >= min.z && other.min.x >= min.x && other.min.y >= min.y && other.min.z >= min.z &&
other.max.x <= max.x && other.max.y <= max.y && other.max.z <= max.z other.max.x <= max.x && other.max.y <= max.y && other.max.z <= max.z
end end
# returns whether the 3D vector is inside of the bounding box # returns whether the 3D vector is inside of the bounding box
def inside?(vector) def inside?(vector)
(vector.x.between?(@min.x, @max.x) || vector.x.between?(@max.x, @min.x)) && (vector.x.between?(@min.x, @max.x) || vector.x.between?(@max.x, @min.x)) &&
(vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) && (vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) &&
(vector.z.between?(@min.z, @max.z) || vector.z.between?(@max.z, @min.z)) (vector.z.between?(@min.z, @max.z) || vector.z.between?(@max.z, @min.z))
end end
# returns whether the 2D vector is inside of the bounding box # returns whether the 2D vector is inside of the bounding box
def point?(vector) def point?(vector)
(vector.x.between?(@min.x, @max.x) || vector.x.between?(@max.x, @min.x)) && (vector.x.between?(@min.x, @max.x) || vector.x.between?(@max.x, @min.x)) &&
(vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y)) (vector.y.between?(@min.y, @max.y) || vector.y.between?(@max.y, @min.y))
end end
def volume def volume
@@ -107,7 +107,7 @@ module CyberarmEngine
temp.max.y = @max.y.to_f * entity.scale.y temp.max.y = @max.y.to_f * entity.scale.y
temp.max.z = @max.z.to_f * entity.scale.z temp.max.z = @max.z.to_f * entity.scale.z
return temp temp
end end
def normalize_with_offset(entity) def normalize_with_offset(entity)
@@ -120,23 +120,23 @@ module CyberarmEngine
temp.max.y = @max.y.to_f * entity.scale.y + entity.position.y temp.max.y = @max.y.to_f * entity.scale.y + entity.position.y
temp.max.z = @max.z.to_f * entity.scale.z + entity.position.z temp.max.z = @max.z.to_f * entity.scale.z + entity.position.z
return temp temp
end end
def +(other) def +(other)
box = BoundingBox.new box = BoundingBox.new
box.min = self.min + other.min box.min = min + other.min
box.min = self.max + other.max box.min = max + other.max
return box box
end end
def -(other) def -(other)
box = BoundingBox.new box = BoundingBox.new
box.min = self.min - other.min box.min = min - other.min
box.min = self.max - other.max box.min = max - other.max
return box box
end end
def sum def sum

View File

@@ -27,13 +27,14 @@ module CyberarmEngine
remaining_bytes = @downloads.map { |d| d.remaining_bytes }.sum remaining_bytes = @downloads.map { |d| d.remaining_bytes }.sum
total_bytes = @downloads.map { |d| d.total_bytes }.sum total_bytes = @downloads.map { |d| d.total_bytes }.sum
v = 1.0 - (remaining_bytes.to_f / total_bytes.to_f) v = 1.0 - (remaining_bytes.to_f / total_bytes)
return 0.0 if v.nan? return 0.0 if v.nan?
return v
v
end end
def active_downloads def active_downloads
@downloads.select { |d| [:pending, :downloading].include?(d.status) } @downloads.select { |d| %i[pending downloading].include?(d.status) }
end end
def update def update
@@ -53,6 +54,7 @@ module CyberarmEngine
attr_accessor :status attr_accessor :status
attr_reader :uri, :save_as, :callback, :remaining_bytes, :total_downloaded_bytes, :total_bytes, attr_reader :uri, :save_as, :callback, :remaining_bytes, :total_downloaded_bytes, :total_bytes,
:error_message, :started_at, :finished_at :error_message, :started_at, :finished_at
def initialize(uri:, save_as:, callback: nil) def initialize(uri:, save_as:, callback: nil)
@uri = uri @uri = uri
@save_as = save_as @save_as = save_as
@@ -68,9 +70,10 @@ module CyberarmEngine
end end
def progress def progress
v = 1.0 - (@remaining_bytes.to_f / total_bytes.to_f) v = 1.0 - (@remaining_bytes.to_f / total_bytes)
return 0.0 if v.nan? return 0.0 if v.nan?
return v
v
end end
def download def download
@@ -103,15 +106,14 @@ module CyberarmEngine
@finished_at = Time.now # TODO: monotonic time @finished_at = Time.now # TODO: monotonic time
@callback.call(self) if @callback @callback.call(self) if @callback
end end
rescue => e # TODO: cherrypick errors to cature rescue StandardError => e # TODO: cherrypick errors to cature
@status = :failed @status = :failed
@finished_at = Time.now # TODO: monotonic time @finished_at = Time.now # TODO: monotonic time
@error_message = e.message @error_message = e.message
@callback.call(self) if @callback @callback.call(self) if @callback
end end
ensure
ensure io.close if io
io.close if io
end end
end end
end end

View File

@@ -1,6 +1,6 @@
module CyberarmEngine module CyberarmEngine
module Common module Common
def push_state(klass, options={}) def push_state(klass, options = {})
window.push_state(klass, options) window.push_state(klass, options)
end end
@@ -20,7 +20,7 @@ module CyberarmEngine
window.show_cursor window.show_cursor
end end
def show_cursor=boolean def show_cursor=(boolean)
window.show_cursor = boolean window.show_cursor = boolean
end end
@@ -34,24 +34,24 @@ module CyberarmEngine
def lighten(color, amount = 25) def lighten(color, amount = 25)
if defined?(color.alpha) if defined?(color.alpha)
return Gosu::Color.rgba(color.red + amount, color.green + amount, color.blue + amount, color.alpha) Gosu::Color.rgba(color.red + amount, color.green + amount, color.blue + amount, color.alpha)
else else
return Gosu::Color.rgb(color.red + amount, color.green + amount, color.blue + amount) Gosu::Color.rgb(color.red + amount, color.green + amount, color.blue + amount)
end end
end end
def darken(color, amount = 25) def darken(color, amount = 25)
if defined?(color.alpha) if defined?(color.alpha)
return Gosu::Color.rgba(color.red - amount, color.green - amount, color.blue - amount, color.alpha) Gosu::Color.rgba(color.red - amount, color.green - amount, color.blue - amount, color.alpha)
else else
return Gosu::Color.rgb(color.red - amount, color.green - amount, color.blue - amount) Gosu::Color.rgb(color.red - amount, color.green - amount, color.blue - amount)
end end
end end
def opacity(color, ratio = 1.0) def opacity(color, ratio = 1.0)
alpha = 255 * ratio alpha = 255 * ratio
return Gosu::Color.rgba(color.red, color.green, color.blue, alpha) Gosu::Color.rgba(color.red, color.green, color.blue, alpha)
end end
def get_asset(path, hash, klass, retro = false, tileable = false) def get_asset(path, hash, klass, retro = false, tileable = false)
@@ -65,16 +65,16 @@ module CyberarmEngine
unless asset unless asset
instance = nil instance = nil
if klass == Gosu::Image instance = if klass == Gosu::Image
instance = klass.new(path, retro: retro, tileable: tileable) klass.new(path, retro: retro, tileable: tileable)
else else
instance = klass.new(path) klass.new(path)
end end
hash[path] = instance hash[path] = instance
asset = instance asset = instance
end end
return asset asset
end end
def get_image(path, retro: false, tileable: false) def get_image(path, retro: false, tileable: false)

View File

@@ -10,7 +10,7 @@ module CyberarmEngine
end end
end end
def []= *keys, value def []=(*keys, value)
last_key = keys.last last_key = keys.last
if keys.size == 1 if keys.size == 1

View File

@@ -5,55 +5,60 @@ module CyberarmEngine
attr_accessor :image, :angle, :position, :velocity, :center_x, :center_y, :scale_x, :scale_y, attr_accessor :image, :angle, :position, :velocity, :center_x, :center_y, :scale_x, :scale_y,
:color, :mode, :options, :paused, :radius, :last_position :color, :mode, :options, :paused, :radius, :last_position
attr_reader :alpha attr_reader :alpha
def initialize(options={})
if options[:auto_manage] || options[:auto_manage] == nil def initialize(options = {})
$window.current_state.add_game_object(self) $window.current_state.add_game_object(self) if options[:auto_manage] || options[:auto_manage].nil?
end
@options = options @options = options
@image = options[:image] ? image(options[:image]) : nil @image = options[:image] ? image(options[:image]) : nil
x = options[:x] ? options[:x] : 0 x = options[:x] || 0
y = options[:y] ? options[:y] : 0 y = options[:y] || 0
z = options[:z] ? options[:z] : 0 z = options[:z] || 0
@position = Vector.new(x, y, z) @position = Vector.new(x, y, z)
@velocity = Vector.new @velocity = Vector.new
@last_position = Vector.new @last_position = Vector.new
@angle = options[:angle] ? options[:angle] : 0 @angle = options[:angle] || 0
@center_x = options[:center_x] ? options[:center_x] : 0.5 @center_x = options[:center_x] || 0.5
@center_y = options[:center_y] ? options[:center_y] : 0.5 @center_y = options[:center_y] || 0.5
@scale_x = options[:scale_x] ? options[:scale_x] : 1 @scale_x = options[:scale_x] || 1
@scale_y = options[:scale_y] ? options[:scale_y] : 1 @scale_y = options[:scale_y] || 1
@color = options[:color] ? options[:color] : Gosu::Color.argb(0xff_ffffff) @color = options[:color] || Gosu::Color.argb(0xff_ffffff)
@alpha = options[:alpha] ? options[:alpha] : 255 @alpha = options[:alpha] || 255
@mode = options[:mode] ? options[:mode] : :default @mode = options[:mode] || :default
@paused = false @paused = false
@speed = 0 @speed = 0
@debug_color = Gosu::Color::GREEN @debug_color = Gosu::Color::GREEN
@world_center_point = Vector.new(0,0) @world_center_point = Vector.new(0, 0)
setup setup
@debug_text = Text.new("", color: @debug_color, y: @position.y-(self.height*self.scale), z: 9999) @debug_text = Text.new("", color: @debug_color, y: @position.y - (height * scale), z: 9999)
@debug_text.x = @position.x @debug_text.x = @position.x
if @radius == 0 || @radius == nil if @radius == 0 || @radius.nil?
@radius = options[:radius] ? options[:radius] : defined?(@image.width) ? ((@image.width+@image.height)/4)*scale : 1 @radius = if options[:radius]
options[:radius]
else
defined?(@image.width) ? ((@image.width + @image.height) / 4) * scale : 1
end
end end
end end
def draw def draw
if @image if @image
@image.draw_rot(@position.x, @position.y, @position.z, @angle, @center_x, @center_y, @scale_x, @scale_y, @color, @mode) @image.draw_rot(@position.x, @position.y, @position.z, @angle, @center_x, @center_y, @scale_x, @scale_y,
@color, @mode)
end end
if $debug if $debug
show_debug_heading show_debug_heading
$window.draw_circle(@position.x, @position.y, radius, 9999, @debug_color) $window.draw_circle(@position.x, @position.y, radius, 9999, @debug_color)
if @debug_text.text != "" if @debug_text.text != ""
$window.draw_rect(@debug_text.x-10, (@debug_text.y-10), @debug_text.width+20, @debug_text.height+20, Gosu::Color.rgba(0,0,0,200), 9999) $window.draw_rect(@debug_text.x - 10, (@debug_text.y - 10), @debug_text.width + 20, @debug_text.height + 20,
Gosu::Color.rgba(0, 0, 0, 200), 9999)
@debug_text.draw @debug_text.draw
end end
end end
@@ -64,13 +69,13 @@ module CyberarmEngine
def debug_text(text) def debug_text(text)
@debug_text.text = text @debug_text.text = text
@debug_text.x = @position.x-(@debug_text.width / 2) @debug_text.x = @position.x - (@debug_text.width / 2)
@debug_text.y = @position.y-(@debug_text.height + self.radius + self.height) @debug_text.y = @position.y - (@debug_text.height + radius + height)
end end
def scale def scale
if @scale_x == @scale_y if @scale_x == @scale_y
return @scale_x @scale_x
else else
false false
# maths? # maths?
@@ -80,7 +85,7 @@ module CyberarmEngine
def scale=(int) def scale=(int)
self.scale_x = int self.scale_x = int
self.scale_y = int self.scale_y = int
self.radius = ((@image.width+@image.height)/4)*self.scale self.radius = ((@image.width + @image.height) / 4) * scale
end end
def visible def visible
@@ -97,16 +102,16 @@ module CyberarmEngine
end end
def _x_visible def _x_visible
self.x.between?(($window.width/2)-(@world_center_point.x), ($window.width/2)+@world_center_point.x) || x.between?(($window.width / 2) - @world_center_point.x, ($window.width / 2) + @world_center_point.x) ||
self.x.between?(((@world_center_point.x)-$window.width/2), ($window.width/2)+@world_center_point.x) x.between?((@world_center_point.x - $window.width / 2), ($window.width / 2) + @world_center_point.x)
end end
def _y_visible def _y_visible
self.y.between?(($window.height/2)-(@world_center_point.y), ($window.height/2)+@world_center_point.y) || y.between?(($window.height / 2) - @world_center_point.y, ($window.height / 2) + @world_center_point.y) ||
self.y.between?((@world_center_point.y)-($window.height/2), ($window.height/2)+@world_center_point.y) y.between?(@world_center_point.y - ($window.height / 2), ($window.height / 2) + @world_center_point.y)
end end
def heading(ahead_by = 100, object = nil, angle_only = false) def heading(ahead_by = 100, _object = nil, angle_only = false)
direction = Gosu.angle(@last_position.x, @last_position.x, @position.x, position.y).gosu_to_radians direction = Gosu.angle(@last_position.x, @last_position.x, @position.x, position.y).gosu_to_radians
_x = @position.x + (ahead_by * Math.cos(direction)) _x = @position.x + (ahead_by * Math.cos(direction))
@@ -122,11 +127,11 @@ module CyberarmEngine
end end
def width def width
@image ? @image.width * self.scale : 0 @image ? @image.width * scale : 0
end end
def height def height
@image ? @image.height * self.scale : 0 @image ? @image.height * scale : 0
end end
def pause def pause
@@ -138,8 +143,8 @@ module CyberarmEngine
end end
def rotate(int) def rotate(int)
self.angle+=int self.angle += int
self.angle%=360 self.angle %= 360
end end
def alpha=(int) # 0-255 def alpha=(int) # 0-255
@@ -149,7 +154,7 @@ module CyberarmEngine
end end
def draw_rect(x, y, width, height, color, z = 0) def draw_rect(x, y, width, height, color, z = 0)
$window.draw_rect(x,y,width,height,color,z) $window.draw_rect(x, y, width, height, color, z)
end end
def button_up(id) def button_up(id)
@@ -163,14 +168,14 @@ module CyberarmEngine
best_distance = 100_000_000_000 # Huge default number best_distance = 100_000_000_000 # Huge default number
game_object_class.all.each do |object| game_object_class.all.each do |object|
distance = Gosu::distance(self.x, self.y, object.x, object.y) distance = Gosu.distance(x, y, object.x, object.y)
if distance <= best_distance if distance <= best_distance
best_object = object best_object = object
best_distance = distance best_distance = distance
end end
end end
return best_object best_object
end end
def look_at(object) def look_at(object)
@@ -178,31 +183,24 @@ module CyberarmEngine
end end
def circle_collision?(object) def circle_collision?(object)
distance = Gosu.distance(self.x, self.y, object.x, object.y) distance = Gosu.distance(x, y, object.x, object.y)
if distance <= self.radius+object.radius distance <= radius + object.radius
true
else
false
end
end end
# Duplication... so DRY. # Duplication... so DRY.
def each_circle_collision(object, resolve_with = :width, &block) def each_circle_collision(object, _resolve_with = :width, &block)
if object.class != Class && object.instance_of?(object.class) if object.class != Class && object.instance_of?(object.class)
$window.current_state.game_objects.select {|i| i.class == object.class}.each do |o| $window.current_state.game_objects.select { |i| i.instance_of?(object.class) }.each do |o|
distance = Gosu.distance(self.x, self.y, object.x, object.y) distance = Gosu.distance(x, y, object.x, object.y)
if distance <= self.radius+object.radius block.call(o, object) if distance <= radius + object.radius && block
block.call(o, object) if block
end
end end
else else
list = $window.current_state.game_objects.select {|i| i.class == object} list = $window.current_state.game_objects.select { |i| i.instance_of?(object) }
list.each do |o| list.each do |o|
next if self == o next if self == o
distance = Gosu.distance(self.x, self.y, o.x, o.y)
if distance <= self.radius+o.radius distance = Gosu.distance(x, y, o.x, o.y)
block.call(self, o) if block block.call(self, o) if distance <= radius + o.radius && block
end
end end
end end
end end
@@ -210,35 +208,30 @@ module CyberarmEngine
def destroy def destroy
if $window.current_state if $window.current_state
$window.current_state.game_objects.each do |o| $window.current_state.game_objects.each do |o|
if o.is_a?(self.class) && o == self $window.current_state.game_objects.delete(o) if o.is_a?(self.class) && o == self
$window.current_state.game_objects.delete(o)
end
end end
end end
end end
# NOTE: This could be implemented more reliably # NOTE: This could be implemented more reliably
def all def all
INSTANCES.select {|i| i.class == self} INSTANCES.select { |i| i.instance_of?(self) }
end end
def self.each_circle_collision(object, resolve_with = :width, &block) def self.each_circle_collision(object, _resolve_with = :width, &block)
if object.class != Class && object.instance_of?(object.class) if object.class != Class && object.instance_of?(object.class)
$window.current_state.game_objects.select {|i| i.class == self}.each do |o| $window.current_state.game_objects.select { |i| i.instance_of?(self) }.each do |o|
distance = Gosu.distance(o.x, o.y, object.x, object.y) distance = Gosu.distance(o.x, o.y, object.x, object.y)
if distance <= o.radius+object.radius block.call(o, object) if distance <= o.radius + object.radius && block
block.call(o, object) if block
end
end end
else else
lista = $window.current_state.game_objects.select {|i| i.class == self} lista = $window.current_state.game_objects.select { |i| i.instance_of?(self) }
listb = $window.current_state.game_objects.select {|i| i.class == object} listb = $window.current_state.game_objects.select { |i| i.instance_of?(object) }
lista.product(listb).each do |o, o2| lista.product(listb).each do |o, o2|
next if o == o2 next if o == o2
distance = Gosu.distance(o.x, o.y, o2.x, o2.y) distance = Gosu.distance(o.x, o.y, o2.x, o2.y)
if distance <= o.radius+o2.radius block.call(o, o2) if distance <= o.radius + o2.radius && block
block.call(o, o2) if block
end
end end
end end
end end
@@ -247,9 +240,7 @@ module CyberarmEngine
INSTANCES.clear INSTANCES.clear
if $window.current_state if $window.current_state
$window.current_state.game_objects.each do |o| $window.current_state.game_objects.each do |o|
if o.is_a?(self.class) $window.current_state.game_objects.delete(o) if o.is_a?(self.class)
$window.current_state.game_objects.delete(o)
end
end end
end end
end end

View File

@@ -5,7 +5,7 @@ module CyberarmEngine
attr_accessor :options, :global_pause attr_accessor :options, :global_pause
attr_reader :game_objects attr_reader :game_objects
def initialize(options={}) def initialize(options = {})
@options = options @options = options
@game_objects = [] @game_objects = []
@global_pause = false @global_pause = false
@@ -26,7 +26,10 @@ module CyberarmEngine
end end
def draw_bounding_box(box) def draw_bounding_box(box)
x,y, max_x, max_y = box.x, box.y, box.max_x, box.max_y x = box.x
y = box.y
max_x = box.max_x
max_y = box.max_y
color = Gosu::Color.rgba(255, 127, 64, 240) color = Gosu::Color.rgba(255, 127, 64, 240)

View File

@@ -1,55 +1,48 @@
module CyberarmEngine module CyberarmEngine
class Model class Model
attr_accessor :objects, :materials, :vertices, :uvs, :texures, :normals, :faces, :colors, :bones attr_accessor :objects, :materials, :vertices, :uvs, :texures, :normals, :faces, :colors, :bones, :material_file,
attr_accessor :material_file, :current_material, :current_object, :vertex_count, :smoothing :current_material, :current_object, :vertex_count, :smoothing
attr_reader :position, :bounding_box, :textured_material, :file_path attr_reader :position, :bounding_box, :textured_material, :file_path, :positions_buffer_id, :colors_buffer_id,
:normals_buffer_id, :uvs_buffer_id, :textures_buffer_id, :vertex_array_id, :aabb_tree
attr_reader :positions_buffer_id, :colors_buffer_id, :normals_buffer_id, :uvs_buffer_id, :textures_buffer_id
attr_reader :vertex_array_id
attr_reader :aabb_tree
def initialize(file_path:) def initialize(file_path:)
@file_path = file_path @file_path = file_path
@material_file = nil @material_file = nil
@current_object = nil @current_object = nil
@current_material=nil @current_material = nil
@vertex_count = 0 @vertex_count = 0
@objects = [] @objects = []
@materials= {} @materials = {}
@vertices = [] @vertices = []
@colors = [] @colors = []
@uvs = [] @uvs = []
@normals = [] @normals = []
@faces = [] @faces = []
@bones = [] @bones = []
@smoothing= 0 @smoothing = 0
@bounding_box = BoundingBox.new @bounding_box = BoundingBox.new
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
type = File.basename(file_path).split(".").last.to_sym type = File.basename(file_path).split(".").last.to_sym
parser = Model::Parser.find(type) parser = Model::Parser.find(type)
unless parser raise "Unsupported model type '.#{type}', supported models are: #{Model::Parser.supported_formats}" unless parser
raise "Unsupported model type '.#{type}', supported models are: #{Model::Parser.supported_formats}"
end
parse(parser) parse(parser)
@has_texture = false @has_texture = false
@materials.each do |key, material| @materials.each do |_key, material|
if material.texture_id @has_texture = true if material.texture_id
@has_texture = true
end
end end
allocate_gl_objects allocate_gl_objects
populate_vertex_buffer populate_vertex_buffer
configure_vao configure_vao
@objects.each {|o| @vertex_count+=o.vertices.size} @objects.each { |o| @vertex_count += o.vertices.size }
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
# build_collision_tree # build_collision_tree
@@ -87,28 +80,28 @@ module CyberarmEngine
@vertex_array_id = nil @vertex_array_id = nil
buffer = " " * 4 buffer = " " * 4
glGenVertexArrays(1, buffer) glGenVertexArrays(1, buffer)
@vertex_array_id = buffer.unpack('L2').first @vertex_array_id = buffer.unpack1("L2")
# Allocate buffers for future use # Allocate buffers for future use
@positions_buffer_id = nil @positions_buffer_id = nil
buffer = " " * 4 buffer = " " * 4
glGenBuffers(1, buffer) glGenBuffers(1, buffer)
@positions_buffer_id = buffer.unpack('L2').first @positions_buffer_id = buffer.unpack1("L2")
@colors_buffer_id = nil @colors_buffer_id = nil
buffer = " " * 4 buffer = " " * 4
glGenBuffers(1, buffer) glGenBuffers(1, buffer)
@colors_buffer_id = buffer.unpack('L2').first @colors_buffer_id = buffer.unpack1("L2")
@normals_buffer_id = nil @normals_buffer_id = nil
buffer = " " * 4 buffer = " " * 4
glGenBuffers(1, buffer) glGenBuffers(1, buffer)
@normals_buffer_id = buffer.unpack('L2').first @normals_buffer_id = buffer.unpack1("L2")
@uvs_buffer_id = nil @uvs_buffer_id = nil
buffer = " " * 4 buffer = " " * 4
glGenBuffers(1, buffer) glGenBuffers(1, buffer)
@uvs_buffer_id = buffer.unpack('L2').first @uvs_buffer_id = buffer.unpack1("L2")
end end
def populate_vertex_buffer def populate_vertex_buffer
@@ -122,16 +115,15 @@ module CyberarmEngine
colors << face.colors.map { |color| [color.red, color.green, color.blue] } colors << face.colors.map { |color| [color.red, color.green, color.blue] }
norms << face.normals.map { |vert| [vert.x, vert.y, vert.z, vert.weight] } norms << face.normals.map { |vert| [vert.x, vert.y, vert.z, vert.weight] }
if has_texture? uvs << face.uvs.map { |vert| [vert.x, vert.y, vert.z] } if has_texture?
uvs << face.uvs.map { |vert| [vert.x, vert.y, vert.z] }
end
end end
glBindBuffer(GL_ARRAY_BUFFER, @positions_buffer_id) glBindBuffer(GL_ARRAY_BUFFER, @positions_buffer_id)
glBufferData(GL_ARRAY_BUFFER, pos.flatten.size * Fiddle::SIZEOF_FLOAT, pos.flatten.pack("f*"), GL_STATIC_DRAW) glBufferData(GL_ARRAY_BUFFER, pos.flatten.size * Fiddle::SIZEOF_FLOAT, pos.flatten.pack("f*"), GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, @colors_buffer_id) glBindBuffer(GL_ARRAY_BUFFER, @colors_buffer_id)
glBufferData(GL_ARRAY_BUFFER, colors.flatten.size * Fiddle::SIZEOF_FLOAT, colors.flatten.pack("f*"), GL_STATIC_DRAW) glBufferData(GL_ARRAY_BUFFER, colors.flatten.size * Fiddle::SIZEOF_FLOAT, colors.flatten.pack("f*"),
GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, @normals_buffer_id) glBindBuffer(GL_ARRAY_BUFFER, @normals_buffer_id)
glBufferData(GL_ARRAY_BUFFER, norms.flatten.size * Fiddle::SIZEOF_FLOAT, norms.flatten.pack("f*"), GL_STATIC_DRAW) glBufferData(GL_ARRAY_BUFFER, norms.flatten.size * Fiddle::SIZEOF_FLOAT, norms.flatten.pack("f*"), GL_STATIC_DRAW)

View File

@@ -3,11 +3,12 @@ module CyberarmEngine
class Material class Material
attr_accessor :name, :ambient, :diffuse, :specular attr_accessor :name, :ambient, :diffuse, :specular
attr_reader :texture_id attr_reader :texture_id
def initialize(name) def initialize(name)
@name = name @name = name
@ambient = Color.new(1, 1, 1, 1) @ambient = Color.new(1, 1, 1, 1)
@diffuse = Color.new(1, 1, 1, 1) @diffuse = Color.new(1, 1, 1, 1)
@specular= Color.new(1, 1, 1, 1) @specular = Color.new(1, 1, 1, 1)
@texture = nil @texture = nil
@texture_id = nil @texture_id = nil
end end

View File

@@ -13,7 +13,7 @@ module CyberarmEngine
@faces = [] @faces = []
@materials = [] @materials = []
@bounding_box = BoundingBox.new @bounding_box = BoundingBox.new
@debug_color = Color.new(1.0,1.0,1.0) @debug_color = Color.new(1.0, 1.0, 1.0)
@scale = 1.0 @scale = 1.0
@@ -46,9 +46,10 @@ module CyberarmEngine
@faces.each do |face| @faces.each do |face|
face.vertices.each do |v| face.vertices.each do |v|
next unless v next unless v
list << v.x*@scale
list << v.y*@scale list << v.x * @scale
list << v.z*@scale list << v.y * @scale
list << v.z * @scale
list << v.weight list << v.weight
end end
end end
@@ -57,7 +58,7 @@ module CyberarmEngine
@vertices_list = list.pack("f*") @vertices_list = list.pack("f*")
end end
return @vertices_list @vertices_list
end end
def flattened_vertices_size def flattened_vertices_size
@@ -70,6 +71,7 @@ module CyberarmEngine
@faces.each do |face| @faces.each do |face|
face.uvs.each do |v| face.uvs.each do |v|
next unless v next unless v
list << v.x list << v.x
list << v.y list << v.y
list << v.z list << v.z
@@ -80,7 +82,7 @@ module CyberarmEngine
@uvs_list = list.pack("f*") @uvs_list = list.pack("f*")
end end
return @uvs_list @uvs_list
end end
def flattened_normals def flattened_normals
@@ -89,6 +91,7 @@ module CyberarmEngine
@faces.each do |face| @faces.each do |face|
face.normals.each do |n| face.normals.each do |n|
next unless n next unless n
list << n.x list << n.x
list << n.y list << n.y
list << n.z list << n.z
@@ -99,7 +102,7 @@ module CyberarmEngine
@normals_list = list.pack("f*") @normals_list = list.pack("f*")
end end
return @normals_list @normals_list
end end
def flattened_materials def flattened_materials
@@ -108,8 +111,8 @@ module CyberarmEngine
@faces.each do |face| @faces.each do |face|
material = face.material material = face.material
next unless material next unless material
face.vertices.each do # Add material to each vertex
face.vertices.each do # Add material to each vertex
list << material.diffuse.red list << material.diffuse.red
list << material.diffuse.green list << material.diffuse.green
list << material.diffuse.blue list << material.diffuse.blue
@@ -121,7 +124,7 @@ module CyberarmEngine
@materials_list = list.pack("f*") @materials_list = list.pack("f*")
end end
return @materials_list @materials_list
end end
end end
end end

View File

@@ -9,7 +9,8 @@ module CyberarmEngine
@@parsers = [] @@parsers = []
def self.handles def self.handles
raise NotImplementedError, "Model::Parser#handles must return an array of file extensions that this parser supports" raise NotImplementedError,
"Model::Parser#handles must return an array of file extensions that this parser supports"
end end
def self.inherited(parser) def self.inherited(parser)
@@ -17,11 +18,9 @@ module CyberarmEngine
end end
def self.find(file_type) def self.find(file_type)
found_parser = @@parsers.find do |parser| @@parsers.find do |parser|
parser.handles.include?(file_type) parser.handles.include?(file_type)
end end
return found_parser
end end
def self.supported_formats def self.supported_formats

View File

@@ -57,7 +57,7 @@ module CyberarmEngine
array = positions.at_css("[id=\"#{id}-positions-array\"]") array = positions.at_css("[id=\"#{id}-positions-array\"]")
stride = Integer(positions.at_css("[source=\"##{id}-positions-array\"]").attributes["stride"].value) stride = Integer(positions.at_css("[source=\"##{id}-positions-array\"]").attributes["stride"].value)
list = array.children.first.to_s.split(" ").map{ |f| Float(f) }.each_slice(stride).each do |slice| list = array.children.first.to_s.split(" ").map { |f| Float(f) }.each_slice(stride).each do |slice|
position = Vector.new(*slice) position = Vector.new(*slice)
@model.current_object.vertices << position @model.current_object.vertices << position
@model.vertices << position @model.vertices << position
@@ -69,7 +69,7 @@ module CyberarmEngine
array = normals.at_css("[id=\"#{id}-normals-array\"]") array = normals.at_css("[id=\"#{id}-normals-array\"]")
stride = Integer(normals.at_css("[source=\"##{id}-normals-array\"]").attributes["stride"].value) stride = Integer(normals.at_css("[source=\"##{id}-normals-array\"]").attributes["stride"].value)
list = array.children.first.to_s.split(" ").map{ |f| Float(f) }.each_slice(stride).each do |slice| list = array.children.first.to_s.split(" ").map { |f| Float(f) }.each_slice(stride).each do |slice|
normal = Vector.new(*slice) normal = Vector.new(*slice)
@model.current_object.normals << normal @model.current_object.normals << normal
@model.normals << normal @model.normals << normal
@@ -81,20 +81,23 @@ module CyberarmEngine
def project_node(name) def project_node(name)
@collada.css("library_visual_scenes visual_scene node").each do |node| @collada.css("library_visual_scenes visual_scene node").each do |node|
if node.attributes["name"].value == name next unless node.attributes["name"].value == name
transform = Transform.new( node.at_css("matrix").children.first.to_s.split(" ").map { |f| Float(f) } )
@model.current_object.vertices.each do |vert| transform = Transform.new(node.at_css("matrix").children.first.to_s.split(" ").map { |f| Float(f) })
v = vert.multiply_transform(transform)
vert.x, vert.y, vert.z, vert.w = v.x, v.y, v.z, v.w
end
break @model.current_object.vertices.each do |vert|
v = vert.multiply_transform(transform)
vert.x = v.x
vert.y = v.y
vert.z = v.z
vert.w = v.w
end end
break
end end
end end
def build_faces(id, mesh) def build_faces(_id, mesh)
material_name = mesh.at_css("triangles").attributes["material"].value material_name = mesh.at_css("triangles").attributes["material"].value
set_material(material_name) set_material(material_name)
@@ -116,7 +119,7 @@ module CyberarmEngine
face.normals = [] face.normals = []
face.colors = [] face.colors = []
face.material = current_material face.material = current_material
face.smoothing= @model.smoothing face.smoothing = @model.smoothing
slice.each do |index| slice.each do |index|
face.vertices << @model.vertices[index] face.vertices << @model.vertices[index]

View File

@@ -8,29 +8,29 @@ module CyberarmEngine
lines = 0 lines = 0
list = File.read(@model.file_path).split("\n") list = File.read(@model.file_path).split("\n")
list.each do |line| list.each do |line|
lines+=1 lines += 1
line = line.strip line = line.strip
array = line.split(' ') array = line.split(" ")
case array[0] case array[0]
when 'mtllib' when "mtllib"
@model.material_file = array[1] @model.material_file = array[1]
parse_mtllib parse_mtllib
when 'usemtl' when "usemtl"
set_material(array[1]) set_material(array[1])
when 'o' when "o"
change_object(nil, array[1]) change_object(nil, array[1])
when 's' when "s"
set_smoothing(array[1]) set_smoothing(array[1])
when 'v' when "v"
add_vertex(array) add_vertex(array)
when 'vt' when "vt"
add_texture_coordinate(array) add_texture_coordinate(array)
when 'vn' when "vn"
add_normal(array) add_normal(array)
when 'f' when "f"
verts = [] verts = []
uvs = [] uvs = []
norms = [] norms = []
@@ -46,22 +46,21 @@ module CyberarmEngine
face.normals = [] face.normals = []
face.colors = [] face.colors = []
face.material = current_material face.material = current_material
face.smoothing= @model.smoothing face.smoothing = @model.smoothing
mat = face.material.diffuse mat = face.material.diffuse
color = mat color = mat
verts.each_with_index do |v, index| verts.each_with_index do |v, index|
if uvs.first != "" if uvs.first != ""
face.vertices << @model.vertices[Integer(v)-1] face.vertices << @model.vertices[Integer(v) - 1]
face.uvs << @model.uvs[Integer(uvs[index])-1] face.uvs << @model.uvs[Integer(uvs[index]) - 1]
face.normals << @model.normals[Integer(norms[index])-1] face.normals << @model.normals[Integer(norms[index]) - 1]
face.colors << color face.colors << color
else else
face.vertices << @model.vertices[Integer(v)-1] face.vertices << @model.vertices[Integer(v) - 1]
face.uvs << nil face.uvs << nil
face.normals << @model.normals[Integer(norms[index])-1] face.normals << @model.normals[Integer(norms[index]) - 1]
face.colors << color face.colors << color
end end
end end
@@ -78,43 +77,42 @@ module CyberarmEngine
end end
def parse_mtllib def parse_mtllib
file = File.open(@model.file_path.sub(File.basename(@model.file_path), '')+@model.material_file, 'r') file = File.open(@model.file_path.sub(File.basename(@model.file_path), "") + @model.material_file, "r")
file.readlines.each do |line| file.readlines.each do |line|
array = line.strip.split(' ') array = line.strip.split(" ")
case array.first case array.first
when 'newmtl' when "newmtl"
material = Model::Material.new(array.last) material = Model::Material.new(array.last)
@model.current_material = array.last @model.current_material = array.last
@model.materials[array.last] = material @model.materials[array.last] = material
when 'Ns' # Specular Exponent when "Ns" # Specular Exponent
when 'Ka' # Ambient color when "Ka" # Ambient color
@model.materials[@model.current_material].ambient = Color.new(Float(array[1]), Float(array[2]), Float(array[3])) @model.materials[@model.current_material].ambient = Color.new(Float(array[1]), Float(array[2]),
when 'Kd' # Diffuse color Float(array[3]))
@model.materials[@model.current_material].diffuse = Color.new(Float(array[1]), Float(array[2]), Float(array[3])) when "Kd" # Diffuse color
when 'Ks' # Specular color @model.materials[@model.current_material].diffuse = Color.new(Float(array[1]), Float(array[2]),
@model.materials[@model.current_material].specular = Color.new(Float(array[1]), Float(array[2]), Float(array[3])) Float(array[3]))
when 'Ke' # Emissive when "Ks" # Specular color
when 'Ni' # Unknown (Blender Specific?) @model.materials[@model.current_material].specular = Color.new(Float(array[1]), Float(array[2]),
when 'd' # Dissolved (Transparency) Float(array[3]))
when 'illum' # Illumination model when "Ke" # Emissive
when 'map_Kd' # Diffuse texture when "Ni" # Unknown (Blender Specific?)
when "d" # Dissolved (Transparency)
when "illum" # Illumination model
when "map_Kd" # Diffuse texture
texture = File.basename(array[1]) texture = File.basename(array[1])
texture_path = "#{File.expand_path("../../", @model.file_path)}/textures/#{texture}" texture_path = "#{File.expand_path('../../', @model.file_path)}/textures/#{texture}"
@model.materials[@model.current_material].set_texture(texture_path) @model.materials[@model.current_material].set_texture(texture_path)
end end
end end
end end
def set_smoothing(value) def set_smoothing(value)
if value == "1" @model.smoothing = value == "1"
@model.smoothing = true
else
@model.smoothing = false
end
end end
def add_vertex(array) def add_vertex(array)
@model.vertex_count+=1 @model.vertex_count += 1
vert = nil vert = nil
if array.size == 5 if array.size == 5
vert = Vector.new(Float(array[1]), Float(array[2]), Float(array[3]), Float(array[4])) vert = Vector.new(Float(array[1]), Float(array[2]), Float(array[3]), Float(array[4]))
@@ -143,9 +141,9 @@ module CyberarmEngine
def add_texture_coordinate(array) def add_texture_coordinate(array)
texture = nil texture = nil
if array.size == 4 if array.size == 4
texture = Vector.new(Float(array[1]), 1-Float(array[2]), Float(array[3])) texture = Vector.new(Float(array[1]), 1 - Float(array[2]), Float(array[3]))
elsif array.size == 3 elsif array.size == 3
texture = Vector.new(Float(array[1]), 1-Float(array[2]), 1.0) texture = Vector.new(Float(array[1]), 1 - Float(array[2]), 1.0)
else else
raise raise
end end

View File

@@ -8,23 +8,19 @@ module CyberarmEngine
type = File.basename(model_file).split(".").last.to_sym type = File.basename(model_file).split(".").last.to_sym
if model = load_model_from_cache(type, model_file) if model = load_model_from_cache(type, model_file)
return model model
else else
model = CyberarmEngine::Model.new(file_path: model_file) model = CyberarmEngine::Model.new(file_path: model_file)
cache_model(type, model_file, model) cache_model(type, model_file, model)
return model model
end end
end end
def self.load_model_from_cache(type, model_file) def self.load_model_from_cache(type, model_file)
if CACHE[type].is_a?(Hash) return CACHE[type][model_file] if CACHE[type].is_a?(Hash) && (CACHE[type][model_file])
if CACHE[type][model_file]
return CACHE[type][model_file]
end
end
return false false
end end
def self.cache_model(type, model_file, model) def self.cache_model(type, model_file, model)

View File

@@ -7,10 +7,10 @@ end
module CyberarmEngine module CyberarmEngine
def gl_error? def gl_error?
e = glGetError() e = glGetError
if e != GL_NO_ERROR if e != GL_NO_ERROR
$stderr.puts "OpenGL error detected by handler at: #{caller[0]}" warn "OpenGL error detected by handler at: #{caller[0]}"
$stderr.puts " #{gluErrorString(e)} (#{e})\n" warn " #{gluErrorString(e)} (#{e})\n"
exit if window.exit_on_opengl_error? exit if window.exit_on_opengl_error?
end end
end end

View File

@@ -6,16 +6,17 @@ module CyberarmEngine
attr_reader :light_id attr_reader :light_id
attr_accessor :type, :ambient, :diffuse, :specular, :position, :direction, :intensity attr_accessor :type, :ambient, :diffuse, :specular, :position, :direction, :intensity
def initialize( def initialize(
id:, id:,
type: Light::POINT, type: Light::POINT,
ambient: Vector.new(0.5, 0.5, 0.5), ambient: Vector.new(0.5, 0.5, 0.5),
diffuse: Vector.new(1, 1, 1), diffuse: Vector.new(1, 1, 1),
specular: Vector.new(0.2, 0.2, 0.2), specular: Vector.new(0.2, 0.2, 0.2),
position: Vector.new(0, 0, 0), position: Vector.new(0, 0, 0),
direction: Vector.new(0, 0, 0), direction: Vector.new(0, 0, 0),
intensity: 1 intensity: 1
) )
@light_id = id @light_id = id
@type = type @type = type
@@ -40,9 +41,9 @@ module CyberarmEngine
def convert(struct, apply_intensity = false) def convert(struct, apply_intensity = false)
if apply_intensity if apply_intensity
return struct.to_a.compact.map{ |i| i * @intensity } struct.to_a.compact.map { |i| i * @intensity }
else else
return struct.to_a.compact struct.to_a.compact
end end
end end
end end

View File

@@ -2,17 +2,21 @@ module CyberarmEngine
class OrthographicCamera class OrthographicCamera
attr_accessor :position, :orientation, :zoom, :left, :right, :bottom, :top, attr_accessor :position, :orientation, :zoom, :left, :right, :bottom, :top,
:min_view_distance, :max_view_distance :min_view_distance, :max_view_distance
def initialize( def initialize(
position:, orientation: Vector.new(0, 0, 0), position:, right:, top:, orientation: Vector.new(0, 0, 0),
zoom: 1, left: 0, right:, bottom: 0, top:, zoom: 1, left: 0, bottom: 0,
min_view_distance: 0.1, max_view_distance: 200.0 min_view_distance: 0.1, max_view_distance: 200.0
) )
@position = position @position = position
@orientation = orientation @orientation = orientation
@zoom = zoom @zoom = zoom
@left, @right, @bottom, @top = left, right, bottom, top @left = left
@right = right
@bottom = bottom
@top = top
@min_view_distance = min_view_distance @min_view_distance = min_view_distance
@max_view_distance = max_view_distance @max_view_distance = max_view_distance

View File

@@ -2,7 +2,9 @@ module CyberarmEngine
class PerspectiveCamera class PerspectiveCamera
attr_accessor :position, :orientation, :aspect_ratio, :field_of_view, attr_accessor :position, :orientation, :aspect_ratio, :field_of_view,
:min_view_distance, :max_view_distance :min_view_distance, :max_view_distance
def initialize(position:, orientation: Vector.new(0, 0, 0), aspect_ratio:, field_of_view: 70.0, min_view_distance: 0.1, max_view_distance: 155.0)
def initialize(position:, aspect_ratio:, orientation: Vector.new(0, 0,
0), field_of_view: 70.0, min_view_distance: 0.1, max_view_distance: 155.0)
@position = position @position = position
@orientation = orientation @orientation = orientation

View File

@@ -1,6 +1,7 @@
module CyberarmEngine module CyberarmEngine
class BoundingBoxRenderer class BoundingBoxRenderer
attr_reader :bounding_boxes, :vertex_count attr_reader :bounding_boxes, :vertex_count
def initialize def initialize
@bounding_boxes = {} @bounding_boxes = {}
@vertex_count = 0 @vertex_count = 0
@@ -8,7 +9,7 @@ module CyberarmEngine
def render(entities) def render(entities)
entities.each do |entity| entities.each do |entity|
create_bounding_box(entity,color = nil) create_bounding_box(entity, color = nil)
draw_bounding_boxes draw_bounding_boxes
end end
@@ -43,7 +44,7 @@ module CyberarmEngine
colors = mesh_colors(color) colors = mesh_colors(color)
vertices = mesh_vertices(box) vertices = mesh_vertices(box)
@vertex_count+=vertices.size @vertex_count += vertices.size
@bounding_boxes[entity_id][:vertices_size] = vertices.size @bounding_boxes[entity_id][:vertices_size] = vertices.size
@bounding_boxes[entity_id][:vertices] = vertices.pack("f*") @bounding_boxes[entity_id][:vertices] = vertices.pack("f*")
@@ -58,7 +59,7 @@ module CyberarmEngine
colors = mesh_colors(mesh.debug_color) colors = mesh_colors(mesh.debug_color)
vertices = mesh_vertices(box) vertices = mesh_vertices(box)
@vertex_count+=vertices.size @vertex_count += vertices.size
data[:vertices_size] = vertices.size data[:vertices_size] = vertices.size
data[:vertices] = vertices.pack("f*") data[:vertices] = vertices.pack("f*")
@@ -71,48 +72,48 @@ module CyberarmEngine
def mesh_normals def mesh_normals
[ [
0,1,0, 0, 1, 0,
0,1,0, 0, 1, 0,
0,1,0, 0, 1, 0,
0,1,0, 0, 1, 0,
0,1,0, 0, 1, 0,
0,1,0, 0, 1, 0,
0,-1,0, 0, -1, 0,
0,-1,0, 0, -1, 0,
0,-1,0, 0, -1, 0,
0,-1,0, 0, -1, 0,
0,-1,0, 0, -1, 0,
0,-1,0, 0, -1, 0,
0,0,1, 0, 0, 1,
0,0,1, 0, 0, 1,
0,0,1, 0, 0, 1,
0,0,1, 0, 0, 1,
0,0,1, 0, 0, 1,
0,0,1, 0, 0, 1,
1,0,0, 1, 0, 0,
1,0,0, 1, 0, 0,
1,0,0, 1, 0, 0,
1,0,0, 1, 0, 0,
1,0,0, 1, 0, 0,
1,0,0, 1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0, -1, 0, 0,
-1,0,0 -1, 0, 0
] ]
end end
@@ -219,7 +220,7 @@ module CyberarmEngine
bounding_box[:entity].position.z bounding_box[:entity].position.z
) )
draw_bounding_box(bounding_box) draw_bounding_box(bounding_box)
@bounding_boxes[key][:objects].each {|o| draw_bounding_box(o)} @bounding_boxes[key][:objects].each { |o| draw_bounding_box(o) }
glPopMatrix glPopMatrix
end end

View File

@@ -1,11 +1,13 @@
module CyberarmEngine module CyberarmEngine
class GBuffer class GBuffer
attr_reader :screen_vbo, :vertices, :uvs attr_reader :screen_vbo, :vertices, :uvs
def initialize(width:, height:) def initialize(width:, height:)
@width, @height = width, height @width = width
@height = height
@framebuffer = nil @framebuffer = nil
@buffers = [:position, :diffuse, :normal, :texcoord] @buffers = %i[position diffuse normal texcoord]
@textures = {} @textures = {}
@screen_vbo = nil @screen_vbo = nil
@ready = false @ready = false
@@ -16,9 +18,9 @@ module CyberarmEngine
-1.0, 1.0, 0, -1.0, 1.0, 0,
-1.0, 1.0, 0, -1.0, 1.0, 0,
1.0, -1.0, 0, 1.0, -1.0, 0,
1.0, 1.0, 0, 1.0, 1.0, 0
].freeze ].freeze
@uvs = [ @uvs = [
0, 0, 0, 0,
@@ -35,9 +37,9 @@ module CyberarmEngine
end end
def create_framebuffer def create_framebuffer
buffer = ' ' * 4 buffer = " " * 4
glGenFramebuffers(1, buffer) glGenFramebuffers(1, buffer)
@framebuffer = buffer.unpack('L2').first @framebuffer = buffer.unpack1("L2")
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, @framebuffer) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, @framebuffer)
@@ -48,20 +50,20 @@ module CyberarmEngine
if status != GL_FRAMEBUFFER_COMPLETE if status != GL_FRAMEBUFFER_COMPLETE
message = "" message = ""
case status message = case status
when GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT when GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
message = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT" "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"
when GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT when GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
message = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT" "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"
when GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER when GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER
message = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER" "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"
when GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER when GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER
message = "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER" "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"
when GL_FRAMEBUFFER_UNSUPPORTED when GL_FRAMEBUFFER_UNSUPPORTED
message = "GL_FRAMEBUFFER_UNSUPPORTED" "GL_FRAMEBUFFER_UNSUPPORTED"
else else
message = "Unknown error!" "Unknown error!"
end end
puts "Incomplete framebuffer: #{status}\nError: #{message}" puts "Incomplete framebuffer: #{status}\nError: #{message}"
else else
@ready = true @ready = true
@@ -72,9 +74,9 @@ module CyberarmEngine
def create_textures def create_textures
@buffers.size.times do |i| @buffers.size.times do |i|
buffer = ' ' * 4 buffer = " " * 4
glGenTextures(1, buffer) glGenTextures(1, buffer)
texture_id = buffer.unpack('L2').first texture_id = buffer.unpack1("L2")
@textures[@buffers[i]] = texture_id @textures[@buffers[i]] = texture_id
glBindTexture(GL_TEXTURE_2D, texture_id) glBindTexture(GL_TEXTURE_2D, texture_id)
@@ -84,39 +86,39 @@ module CyberarmEngine
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, texture_id, 0) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, texture_id, 0)
end end
buffer = ' ' * 4 buffer = " " * 4
glGenTextures(1, buffer) glGenTextures(1, buffer)
texture_id = buffer.unpack('L2').first texture_id = buffer.unpack1("L2")
@textures[:depth] = texture_id @textures[:depth] = texture_id
glBindTexture(GL_TEXTURE_2D, texture_id) glBindTexture(GL_TEXTURE_2D, texture_id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, @width, @height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nil) glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, @width, @height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nil)
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture_id, 0) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture_id, 0)
draw_buffers = [ GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 ] draw_buffers = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3]
glDrawBuffers(draw_buffers.size, draw_buffers.pack("I*")) glDrawBuffers(draw_buffers.size, draw_buffers.pack("I*"))
end end
def create_screen_vbo def create_screen_vbo
buffer = ' ' * 4 buffer = " " * 4
glGenVertexArrays(1, buffer) glGenVertexArrays(1, buffer)
@screen_vbo = buffer.unpack('L2').first @screen_vbo = buffer.unpack1("L2")
buffer = " " * 4 buffer = " " * 4
glGenBuffers(1, buffer) glGenBuffers(1, buffer)
@positions_buffer_id = buffer.unpack('L2').first @positions_buffer_id = buffer.unpack1("L2")
buffer = " " * 4 buffer = " " * 4
glGenBuffers(1, buffer) glGenBuffers(1, buffer)
@uvs_buffer_id = buffer.unpack('L2').first @uvs_buffer_id = buffer.unpack1("L2")
glBindVertexArray(@screen_vbo) glBindVertexArray(@screen_vbo)
glBindBuffer(GL_ARRAY_BUFFER, @positions_buffer_id) glBindBuffer(GL_ARRAY_BUFFER, @positions_buffer_id)
glBufferData(GL_ARRAY_BUFFER, @vertices.size * Fiddle::SIZEOF_FLOAT, @vertices.pack("f*"), GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, @vertices.size * Fiddle::SIZEOF_FLOAT, @vertices.pack("f*"), GL_STATIC_DRAW)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nil) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nil)
glBindBuffer(GL_ARRAY_BUFFER, @uvs_buffer_id) glBindBuffer(GL_ARRAY_BUFFER, @uvs_buffer_id)
glBufferData(GL_ARRAY_BUFFER, @uvs.size * Fiddle::SIZEOF_FLOAT, @uvs.pack("f*"), GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, @uvs.size * Fiddle::SIZEOF_FLOAT, @uvs.pack("f*"), GL_STATIC_DRAW)
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nil) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nil)
glEnableVertexAttribArray(0) glEnableVertexAttribArray(0)

View File

@@ -3,8 +3,10 @@ module CyberarmEngine
@@immediate_mode_warning = false @@immediate_mode_warning = false
attr_accessor :show_wireframe attr_accessor :show_wireframe
def initialize(width:, height:, show_wireframe: false) def initialize(width:, height:, show_wireframe: false)
@width, @height = width, height @width = width
@height = height
@show_wireframe = show_wireframe @show_wireframe = show_wireframe
@g_buffer = GBuffer.new(width: @width, height: @height) @g_buffer = GBuffer.new(width: @width, height: @height)
@@ -63,7 +65,9 @@ module CyberarmEngine
@g_buffer.unbind_framebuffer @g_buffer.unbind_framebuffer
gl_error? gl_error?
else else
puts "Shaders are disabled or failed to compile, using immediate mode for rendering..." unless @@immediate_mode_warning unless @@immediate_mode_warning
puts "Shaders are disabled or failed to compile, using immediate mode for rendering..."
end
@@immediate_mode_warning = true @@immediate_mode_warning = true
gl_error? gl_error?
@@ -141,8 +145,8 @@ module CyberarmEngine
glBindTexture(GL_TEXTURE_2D, @g_buffer.texture(:depth)) glBindTexture(GL_TEXTURE_2D, @g_buffer.texture(:depth))
shader.uniform_integer("depth", 4) shader.uniform_integer("depth", 4)
lights.each_with_index do |light, i| lights.each_with_index do |light, _i|
shader.uniform_integer("light[0].type", light.type); shader.uniform_integer("light[0].type", light.type)
shader.uniform_vec3("light[0].direction", light.direction) shader.uniform_vec3("light[0].direction", light.direction)
shader.uniform_vec3("light[0].position", light.position) shader.uniform_vec3("light[0].position", light.position)
shader.uniform_vec3("light[0].diffuse", light.diffuse) shader.uniform_vec3("light[0].diffuse", light.diffuse)
@@ -229,7 +233,7 @@ module CyberarmEngine
end end
def draw_mesh(model) def draw_mesh(model)
model.objects.each_with_index do |o, i| model.objects.each_with_index do |o, _i|
glEnable(GL_COLOR_MATERIAL) glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glShadeModel(GL_FLAT) unless o.faces.first[4] glShadeModel(GL_FLAT) unless o.faces.first[4]
@@ -255,16 +259,16 @@ module CyberarmEngine
glPolygonOffset(2, 0.5) glPolygonOffset(2, 0.5)
glLineWidth(3) glLineWidth(3)
glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size/4) glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size / 4)
glLineWidth(1) glLineWidth(1)
glPolygonOffset(0, 0) glPolygonOffset(0, 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glEnable(GL_LIGHTING) glEnable(GL_LIGHTING)
glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size/4) glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size / 4)
else else
glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size/4) glDrawArrays(GL_TRIANGLES, 0, o.flattened_vertices_size / 4)
end end
# glBindBuffer(GL_ARRAY_BUFFER, 0) # glBindBuffer(GL_ARRAY_BUFFER, 0)

View File

@@ -22,9 +22,7 @@ module CyberarmEngine
if shader if shader
@@shaders.delete(name) @@shaders.delete(name)
if shader.compiled? glDeleteProgram(shader.program) if shader.compiled?
glDeleteProgram(shader.program)
end
end end
end end
@@ -68,15 +66,15 @@ module CyberarmEngine
# returns currently active {Shader}, if one is active # returns currently active {Shader}, if one is active
# #
# @return [Shader?] # @return [Shader?]
def self.active_shader class << self
@active_shader attr_reader :active_shader
end end
# sets currently active {Shader} # sets currently active {Shader}
# #
# @param instance [Shader] instance of {Shader} to set as active # @param instance [Shader] instance of {Shader} to set as active
def self.active_shader=(instance) class << self
@active_shader = instance attr_writer :active_shader
end end
# stops using currently active {Shader} # stops using currently active {Shader}
@@ -94,7 +92,8 @@ module CyberarmEngine
# #
# @param variable [String] # @param variable [String]
def self.attribute_location(variable) def self.attribute_location(variable)
raise RuntimeError, "No active shader!" unless Shader.active_shader raise "No active shader!" unless Shader.active_shader
Shader.active_shader.attribute_location(variable) Shader.active_shader.attribute_location(variable)
end end
@@ -103,12 +102,14 @@ module CyberarmEngine
# @param variable [String] # @param variable [String]
# @param value # @param value
def self.set_uniform(variable, value) def self.set_uniform(variable, value)
raise RuntimeError, "No active shader!" unless Shader.active_shader raise "No active shader!" unless Shader.active_shader
Shader.active_shader.set_uniform(variable, value) Shader.active_shader.set_uniform(variable, value)
end end
attr_reader :name, :program attr_reader :name, :program
def initialize(name:, includes_dir: nil, vertex: "shaders/default.vert", fragment:)
def initialize(name:, fragment:, includes_dir: nil, vertex: "shaders/default.vert")
raise "Shader name can not be blank" if name.length == 0 raise "Shader name can not be blank" if name.length == 0
@name = name @name = name
@@ -120,7 +121,7 @@ module CyberarmEngine
@error_buffer_size = 1024 * 8 @error_buffer_size = 1024 * 8
@variable_missing = {} @variable_missing = {}
@data = {shaders: {}} @data = { shaders: {} }
unless shader_files_exist?(vertex: vertex, fragment: fragment) unless shader_files_exist?(vertex: vertex, fragment: fragment)
raise ArgumentError, "Shader files not found: #{vertex} or #{fragment}" raise ArgumentError, "Shader files not found: #{vertex} or #{fragment}"
@@ -133,7 +134,7 @@ module CyberarmEngine
compile_shader(type: :fragment) compile_shader(type: :fragment)
link_shaders link_shaders
@data[:shaders].each { |key, id| glDeleteShader(id) } @data[:shaders].each { |_key, id| glDeleteShader(id) }
# Only add shader if it successfully compiles # Only add shader if it successfully compiles
if @compiled if @compiled
@@ -175,7 +176,7 @@ module CyberarmEngine
_size = [processed_source.length].pack("I") _size = [processed_source.length].pack("I")
glShaderSource(_shader, 1, _source, _size) glShaderSource(_shader, 1, _source, _size)
@data[:shaders][type] =_shader @data[:shaders][type] = _shader
end end
# evaluates shader preprocessors # evaluates shader preprocessors
@@ -199,22 +200,25 @@ module CyberarmEngine
lines = source.lines lines = source.lines
lines.each_with_index do |line, i| lines.each_with_index do |line, i|
if line.start_with?(PREPROCESSOR_CHARACTER) next unless line.start_with?(PREPROCESSOR_CHARACTER)
preprocessor = line.strip.split(" ")
lines.delete(line)
case preprocessor.first preprocessor = line.strip.split(" ")
when "@include" lines.delete(line)
raise ArgumentError, "Shader preprocessor include directory was not given for shader #{@name}" unless @includes_dir
preprocessor[1..preprocessor.length - 1].join.scan(/"([^"]*)"/).flatten.each do |file| case preprocessor.first
source = File.read("#{@includes_dir}/#{file}.glsl") when "@include"
unless @includes_dir
lines.insert(i, source) raise ArgumentError,
end "Shader preprocessor include directory was not given for shader #{@name}"
else
warn "Unsupported preprocessor #{preprocessor.first} for #{@name}"
end end
preprocessor[1..preprocessor.length - 1].join.scan(/"([^"]*)"/).flatten.each do |file|
source = File.read("#{@includes_dir}/#{file}.glsl")
lines.insert(i, source)
end
else
warn "Unsupported preprocessor #{preprocessor.first} for #{@name}"
end end
end end
@@ -230,12 +234,12 @@ module CyberarmEngine
raise ArgumentError, "No shader for #{type.inspect}" unless _shader raise ArgumentError, "No shader for #{type.inspect}" unless _shader
glCompileShader(_shader) glCompileShader(_shader)
buffer = ' ' buffer = " "
glGetShaderiv(_shader, GL_COMPILE_STATUS, buffer) glGetShaderiv(_shader, GL_COMPILE_STATUS, buffer)
compiled = buffer.unpack('L')[0] compiled = buffer.unpack1("L")
if compiled == 0 if compiled == 0
log = ' ' * @error_buffer_size log = " " * @error_buffer_size
glGetShaderInfoLog(_shader, @error_buffer_size, nil, log) glGetShaderInfoLog(_shader, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\"" puts "Shader Error: Program \"#{@name}\""
puts " #{type.to_s.capitalize} Shader InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n" puts " #{type.to_s.capitalize} Shader InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
@@ -246,7 +250,7 @@ module CyberarmEngine
_compiled = true _compiled = true
end end
return _compiled _compiled
end end
# link compiled OpenGL Shaders in to a OpenGL Program # link compiled OpenGL Shaders in to a OpenGL Program
@@ -261,18 +265,18 @@ module CyberarmEngine
end end
glLinkProgram(@program) glLinkProgram(@program)
buffer = ' ' buffer = " "
glGetProgramiv(@program, GL_LINK_STATUS, buffer) glGetProgramiv(@program, GL_LINK_STATUS, buffer)
linked = buffer.unpack('L')[0] linked = buffer.unpack1("L")
if linked == 0 if linked == 0
log = ' ' * @error_buffer_size log = " " * @error_buffer_size
glGetProgramInfoLog(@program, @error_buffer_size, nil, log) glGetProgramInfoLog(@program, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\"" puts "Shader Error: Program \"#{@name}\""
puts " Program InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n" puts " Program InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
end end
@compiled = linked == 0 ? false : true @compiled = !(linked == 0)
end end
# Returns the location of a uniform _variable_ # Returns the location of a uniform _variable_
@@ -281,18 +285,22 @@ module CyberarmEngine
# @return [Integer] location of uniform # @return [Integer] location of uniform
def variable(variable) def variable(variable)
loc = glGetUniformLocation(@program, variable) loc = glGetUniformLocation(@program, variable)
if (loc == -1) if loc == -1
puts "Shader Error: Program \"#{@name}\" has no such uniform named \"#{variable}\"", " Is it used in the shader? GLSL may have optimized it out.", " Is it miss spelled?" unless @variable_missing[variable] unless @variable_missing[variable]
puts "Shader Error: Program \"#{@name}\" has no such uniform named \"#{variable}\"",
" Is it used in the shader? GLSL may have optimized it out.", " Is it miss spelled?"
end
@variable_missing[variable] = true @variable_missing[variable] = true
end end
return loc loc
end end
# @see Shader.use Shader.use # @see Shader.use Shader.use
def use(&block) def use(&block)
return unless compiled? return unless compiled?
raise "Another shader is already in use! #{Shader.active_shader.name.inspect}" if Shader.active_shader raise "Another shader is already in use! #{Shader.active_shader.name.inspect}" if Shader.active_shader
Shader.active_shader=self
Shader.active_shader = self
glUseProgram(@program) glUseProgram(@program)
@@ -331,7 +339,7 @@ module CyberarmEngine
# @param location [Integer] # @param location [Integer]
# @return [void] # @return [void]
def uniform_transform(variable, value, location = nil) def uniform_transform(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable) attr_loc = location || attribute_location(variable)
glUniformMatrix4fv(attr_loc, 1, GL_FALSE, value.to_gl.pack("F16")) glUniformMatrix4fv(attr_loc, 1, GL_FALSE, value.to_gl.pack("F16"))
end end
@@ -343,7 +351,7 @@ module CyberarmEngine
# @param location [Integer] # @param location [Integer]
# @return [void] # @return [void]
def uniform_boolean(variable, value, location = nil) def uniform_boolean(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable) attr_loc = location || attribute_location(variable)
glUniform1i(attr_loc, value ? 1 : 0) glUniform1i(attr_loc, value ? 1 : 0)
end end
@@ -354,7 +362,7 @@ module CyberarmEngine
# @param location [Integer] # @param location [Integer]
# @return [void] # @return [void]
def uniform_integer(variable, value, location = nil) def uniform_integer(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable) attr_loc = location || attribute_location(variable)
glUniform1i(attr_loc, value) glUniform1i(attr_loc, value)
end end
@@ -366,7 +374,7 @@ module CyberarmEngine
# @param location [Integer] # @param location [Integer]
# @return [void] # @return [void]
def uniform_float(variable, value, location = nil) def uniform_float(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable) attr_loc = location || attribute_location(variable)
glUniform1f(attr_loc, value) glUniform1f(attr_loc, value)
end end
@@ -378,7 +386,7 @@ module CyberarmEngine
# @param location [Integer] # @param location [Integer]
# @return [void] # @return [void]
def uniform_vec3(variable, value, location = nil) def uniform_vec3(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable) attr_loc = location || attribute_location(variable)
glUniform3f(attr_loc, *value.to_a[0..2]) glUniform3f(attr_loc, *value.to_a[0..2])
end end
@@ -390,7 +398,7 @@ module CyberarmEngine
# @param location [Integer] # @param location [Integer]
# @return [void] # @return [void]
def uniform_vec4(variable, value, location = nil) def uniform_vec4(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable) attr_loc = location || attribute_location(variable)
glUniform4f(attr_loc, *value.to_a) glUniform4f(attr_loc, *value.to_a)
end end

View File

@@ -1,6 +1,6 @@
module CyberarmEngine module CyberarmEngine
class Texture class Texture
DEFAULT_TEXTURE = "#{CYBERARM_ENGINE_ROOT_PATH}/assets/textures/default.png" DEFAULT_TEXTURE = "#{CYBERARM_ENGINE_ROOT_PATH}/assets/textures/default.png".freeze
CACHE = {} CACHE = {}
@@ -11,12 +11,14 @@ module CyberarmEngine
end end
def self.from_cache(path, retro) def self.from_cache(path, retro)
return CACHE.dig("#{path}?retro=#{retro}") CACHE.dig("#{path}?retro=#{retro}")
end end
attr_reader :id attr_reader :id
def initialize(path: nil, image: nil, retro: false) def initialize(path: nil, image: nil, retro: false)
raise "keyword :path or :image must be provided!" if path.nil? && image.nil? raise "keyword :path or :image must be provided!" if path.nil? && image.nil?
@retro = retro @retro = retro
@path = path @path = path
@@ -47,9 +49,9 @@ module CyberarmEngine
def create_from_image(image) def create_from_image(image)
array_of_pixels = image.to_blob array_of_pixels = image.to_blob
tex_names_buf = ' ' * 4 tex_names_buf = " " * 4
glGenTextures(1, tex_names_buf) glGenTextures(1, tex_names_buf)
texture_id = tex_names_buf.unpack('L2').first texture_id = tex_names_buf.unpack1("L2")
glBindTexture(GL_TEXTURE_2D, texture_id) glBindTexture(GL_TEXTURE_2D, texture_id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, array_of_pixels) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, array_of_pixels)
@@ -61,7 +63,7 @@ module CyberarmEngine
glGenerateMipmap(GL_TEXTURE_2D) glGenerateMipmap(GL_TEXTURE_2D)
gl_error? gl_error?
return texture_id texture_id
end end
end end
end end

View File

@@ -4,7 +4,7 @@ module CyberarmEngine
raise "Origin must be a Vector!" unless origin.is_a?(Vector) raise "Origin must be a Vector!" unless origin.is_a?(Vector)
raise "Direction must be a Vector!" unless direction.is_a?(Vector) raise "Direction must be a Vector!" unless direction.is_a?(Vector)
@origin = origin @origin = origin
@direction = direction @direction = direction
@range = range @range = range
@@ -42,15 +42,15 @@ module CyberarmEngine
tmin = max(tmin, min(tz1, tz2)) tmin = max(tmin, min(tz1, tz2))
tmax = min(tmax, max(tz1, tz2)) tmax = min(tmax, max(tz1, tz2))
return tmax >= max(tmin, 0.0); tmax >= max(tmin, 0.0)
end end
def min(x, y) def min(x, y)
((x) < (y) ? (x) : (y)) ((x) < (y) ? x : y)
end end
def max(x, y) def max(x, y)
((x) > (y) ? (x) : (y)) ((x) > (y) ? x : y)
end end
end end
end end

View File

@@ -13,7 +13,7 @@ module CyberarmEngine
end end
def self.clear def self.clear
@@hash.each do |key, value| @@hash.each do |key, _value|
@@hash[key] = 0 @@hash[key] = 0
end end
end end

View File

@@ -5,7 +5,7 @@ module CyberarmEngine
attr_accessor :x, :y, :z, :size, :options attr_accessor :x, :y, :z, :size, :options
attr_reader :text, :textobject, :factor_x, :factor_y, :color, :shadow, :shadow_size, :shadow_alpha, :shadow_color attr_reader :text, :textobject, :factor_x, :factor_y, :color, :shadow, :shadow_size, :shadow_alpha, :shadow_color
def initialize(text, options={}) def initialize(text, options = {})
@text = text.to_s || "" @text = text.to_s || ""
@options = options @options = options
@size = options[:size] || 18 @size = options[:size] || 18
@@ -17,28 +17,28 @@ module CyberarmEngine
@factor_y = options[:factor_y] || 1 @factor_y = options[:factor_y] || 1
@color = options[:color] || Gosu::Color::WHITE @color = options[:color] || Gosu::Color::WHITE
@mode = options[:mode] || :default @mode = options[:mode] || :default
@alignment= options[:alignment] || nil @alignment = options[:alignment] || nil
@shadow = true if options[:shadow] == true @shadow = true if options[:shadow] == true
@shadow = false if options[:shadow] == false @shadow = false if options[:shadow] == false
@shadow = true if options[:shadow] == nil @shadow = true if options[:shadow].nil?
@shadow_size = options[:shadow_size] ? options[:shadow_size] : 1 @shadow_size = options[:shadow_size] || 1
@shadow_alpha= options[:shadow_alpha] ? options[:shadow_alpha] : 30 @shadow_alpha = options[:shadow_alpha] || 30
@shadow_alpha= options[:shadow_alpha] ? options[:shadow_alpha] : 30 @shadow_alpha = options[:shadow_alpha] || 30
@shadow_color= options[:shadow_color] @shadow_color = options[:shadow_color]
@textobject = check_cache(@size, @font) @textobject = check_cache(@size, @font)
if @alignment if @alignment
case @alignment case @alignment
when :left when :left
@x = 0+BUTTON_PADDING @x = 0 + BUTTON_PADDING
when :center when :center
@x = ($window.width/2)-(@textobject.text_width(@text)/2) @x = ($window.width / 2) - (@textobject.text_width(@text) / 2)
when :right when :right
@x = $window.width-BUTTON_PADDING-@textobject.text_width(@text) @x = $window.width - BUTTON_PADDING - @textobject.text_width(@text)
end end
end end
return self self
end end
def check_cache(size, font_name) def check_cache(size, font_name)
@@ -62,7 +62,7 @@ module CyberarmEngine
CACHE[@size][@font] = font CACHE[@size][@font] = font
end end
return font font
end end
def text=(string) def text=(string)
@@ -74,26 +74,32 @@ module CyberarmEngine
@rendered_shadow = nil @rendered_shadow = nil
@factor_x = n @factor_x = n
end end
def factor_y=(n) def factor_y=(n)
@rendered_shadow = nil @rendered_shadow = nil
@factor_y = n @factor_y = n
end end
def color=(color) def color=(color)
@rendered_shadow = nil @rendered_shadow = nil
@color = color @color = color
end end
def shadow=(boolean) def shadow=(boolean)
@rendered_shadow = nil @rendered_shadow = nil
@shadow = boolean @shadow = boolean
end end
def shadow_size=(n) def shadow_size=(n)
@rendered_shadow = nil @rendered_shadow = nil
@shadow_size = n @shadow_size = n
end end
def shadow_alpha=(n) def shadow_alpha=(n)
@rendered_shadow = nil @rendered_shadow = nil
@shadow_alpha = n @shadow_alpha = n
end end
def shadow_color=(n) def shadow_color=(n)
@rendered_shadow = nil @rendered_shadow = nil
@shadow_color = n @shadow_color = n
@@ -108,32 +114,33 @@ module CyberarmEngine
end end
def height(text = @text) def height(text = @text)
text.lines.count > 0 ? (text.lines.count) * textobject.height : @textobject.height text.lines.count > 0 ? text.lines.count * textobject.height : @textobject.height
end end
def draw(method = :draw_markup) def draw(method = :draw_markup)
if @shadow && !ARGV.join.include?("--no-shadow") if @shadow && !ARGV.join.include?("--no-shadow")
shadow_alpha = @color.alpha <= 30 ? @color.alpha : @shadow_alpha shadow_alpha = @color.alpha <= 30 ? @color.alpha : @shadow_alpha
shadow_color = @shadow_color ? @shadow_color : Gosu::Color.rgba(@color.red, @color.green, @color.blue, shadow_alpha) shadow_color = @shadow_color || Gosu::Color.rgba(@color.red, @color.green, @color.blue,
white = Gosu::Color::WHITE shadow_alpha)
white = Gosu::Color::WHITE
_x = @shadow_size _x = @shadow_size
_y = @shadow_size _y = @shadow_size
@rendered_shadow ||= Gosu.render((self.width+(shadow_size*2)).ceil, (self.height+(@shadow_size*2)).ceil) do @rendered_shadow ||= Gosu.render((width + (shadow_size * 2)).ceil, (height + (@shadow_size * 2)).ceil) do
@textobject.send(method, @text, _x-@shadow_size, _y, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x - @shadow_size, _y, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x-@shadow_size, _y-@shadow_size, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x - @shadow_size, _y - @shadow_size, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x, _y-@shadow_size, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x, _y - @shadow_size, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x+@shadow_size, _y-@shadow_size, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x + @shadow_size, _y - @shadow_size, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x, _y+@shadow_size, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x, _y + @shadow_size, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x-@shadow_size, _y+@shadow_size, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x - @shadow_size, _y + @shadow_size, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x+@shadow_size, _y, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x + @shadow_size, _y, @z, @factor_x, @factor_y, white, :add)
@textobject.send(method, @text, _x+@shadow_size, _y+@shadow_size, @z, @factor_x, @factor_y, white, :add) @textobject.send(method, @text, _x + @shadow_size, _y + @shadow_size, @z, @factor_x, @factor_y, white, :add)
end end
@rendered_shadow.draw(@x-@shadow_size, @y-@shadow_size, @z, @factor_x, @factor_y, shadow_color) @rendered_shadow.draw(@x - @shadow_size, @y - @shadow_size, @z, @factor_x, @factor_y, shadow_color)
end end
@textobject.send(method, @text, @x, @y, @z, @factor_x, @factor_y, @color, @mode) @textobject.send(method, @text, @x, @y, @z, @factor_x, @factor_y, @color, @mode)
@@ -147,6 +154,7 @@ module CyberarmEngine
@color.alpha @color.alpha
end end
def update; end def update
end
end end
end end

View File

@@ -2,11 +2,12 @@ module CyberarmEngine
# Basic 4x4 matrix operations # Basic 4x4 matrix operations
class Transform class Transform
attr_reader :elements attr_reader :elements
def initialize(matrix) def initialize(matrix)
@elements = matrix @elements = matrix
raise "Transform is wrong size! Got #{@elements.size}, expected 16" if 16 != @elements.size raise "Transform is wrong size! Got #{@elements.size}, expected 16" if 16 != @elements.size
raise "Invalid value for matrix, must all be numeric!" if @elements.any? { |e| e.nil? || !e.is_a?(Numeric)} raise "Invalid value for matrix, must all be numeric!" if @elements.any? { |e| e.nil? || !e.is_a?(Numeric) }
end end
def self.identity def self.identity
@@ -27,10 +28,10 @@ module CyberarmEngine
double c = Math.cos(angle).degrees_to_radians double c = Math.cos(angle).degrees_to_radians
double s = Math.sin(angle).degrees_to_radians double s = Math.sin(angle).degrees_to_radians
matrix = [ matrix = [
+c, +s, 0, 0, +c, +s, 0, 0,
-s, +c, 0, 0, -s, +c, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 1, 0, 0, 0, 1
] ]
rotate_matrix = Transform.new(matrix, rows: 4, columns: 4) rotate_matrix = Transform.new(matrix, rows: 4, columns: 4)
@@ -44,7 +45,7 @@ module CyberarmEngine
) )
end end
return rotate_matrix rotate_matrix
end end
# 2d translate operation, replicates Gosu's Gosu.translate function # 2d translate operation, replicates Gosu's Gosu.translate function
@@ -54,7 +55,7 @@ module CyberarmEngine
1, 0, 0, 0, 1, 0, 0, 0,
0, 1, 0, 0, 0, 1, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
x, y, z, 1, x, y, z, 1
] ]
Transform.new(matrix) Transform.new(matrix)
@@ -67,7 +68,7 @@ module CyberarmEngine
scale_x, 0, 0, 0, scale_x, 0, 0, 0,
0, scale_y, 0, 0, 0, scale_y, 0, 0,
0, 0, scale_z, 0, 0, 0, scale_z, 0,
0, 0, 0, 1, 0, 0, 0, 1
] ]
scale_matrix = Transform.new(matrix) scale_matrix = Transform.new(matrix)
@@ -81,7 +82,7 @@ module CyberarmEngine
) )
end end
return scale_matrix scale_matrix
end end
def self.concat(left, right) def self.concat(left, right)
@@ -107,13 +108,13 @@ module CyberarmEngine
1, 0, 0, x, 1, 0, 0, x,
0, 1, 0, y, 0, 1, 0, y,
0, 0, 1, z, 0, 0, 1, z,
0, 0, 0, 1, 0, 0, 0, 1
] ]
Transform.new(matrix) Transform.new(matrix)
end end
def self.rotate_3d(vector, order = "zyx") def self.rotate_3d(vector, _order = "zyx")
x, y, z = vector.to_a[0..2].map { |axis| axis * Math::PI / 180.0 } x, y, z = vector.to_a[0..2].map { |axis| axis * Math::PI / 180.0 }
rotation_x = Transform.new( rotation_x = Transform.new(
@@ -163,7 +164,7 @@ module CyberarmEngine
x * x * n + c, x * y * n - z * s, x * z * n + y * s, 0, x * x * n + c, x * y * n - z * s, x * z * n + y * s, 0,
y * x * n + z * s, y * y * n + c, y * z * n - x * s, 0, y * x * n + z * s, y * y * n + c, y * z * n - x * s, 0,
x * z * n - y * s, y * z * n + x * s, z * z * n + c, 0, x * z * n - y * s, y * z * n + x * s, z * z * n + c, 0,
0, 0, 0, 1.0 0, 0, 0, 1.0
] ]
) )
end end
@@ -190,7 +191,7 @@ module CyberarmEngine
[ [
f / aspect_ratio, 0.0, 0.0, 0.0, f / aspect_ratio, 0.0, 0.0, 0.0,
0.0, f, 0.0, 0.0, 0.0, f, 0.0, 0.0,
0.0, 0.0, zn, zf, 0.0, 0.0, zn, zf,
0.0, 0.0, -1.0, 0.0 0.0, 0.0, -1.0, 0.0
] ]
) )
@@ -200,13 +201,13 @@ module CyberarmEngine
s = Vector.new( s = Vector.new(
2 / (right - left.to_f), 2 / (right - left.to_f),
2 / (top - bottom.to_f), 2 / (top - bottom.to_f),
-2 / (far - near.to_f), -2 / (far - near.to_f)
) )
t = Vector.new( t = Vector.new(
(right + left.to_f) / (right - left.to_f), (right + left.to_f) / (right - left.to_f),
(top + bottom.to_f) / (top - bottom.to_f), (top + bottom.to_f) / (top - bottom.to_f),
(far + near.to_f) / (far - near.to_f), (far + near.to_f) / (far - near.to_f)
) )
Transform.new( Transform.new(
@@ -232,16 +233,15 @@ module CyberarmEngine
Transform.new( Transform.new(
[ [
x_axis.x, y_axis.y, z_axis.z, 0, x_axis.x, y_axis.y, z_axis.z, 0,
x_axis.x, y_axis.y, z_axis.z, 0, x_axis.x, y_axis.y, z_axis.z, 0,
x_axis.x, y_axis.y, z_axis.z, 0, x_axis.x, y_axis.y, z_axis.z, 0,
-x_axis.dot(eye), -y_axis.dot(eye), -z_axis.dot(eye), 1 -x_axis.dot(eye), -y_axis.dot(eye), -z_axis.dot(eye), 1
] ]
) )
end end
def *(other) def *(other)
case other case other
when CyberarmEngine::Vector when CyberarmEngine::Vector
matrix = @elements.clone matrix = @elements.clone
@@ -254,7 +254,7 @@ module CyberarmEngine
Transform.new(matrix) Transform.new(matrix)
when CyberarmEngine::Transform when CyberarmEngine::Transform
return multiply_matrices(other) multiply_matrices(other)
else else
p other.class p other.class
raise TypeError, "Expected CyberarmEngine::Vector or CyberarmEngine::Transform got #{other.class}" raise TypeError, "Expected CyberarmEngine::Vector or CyberarmEngine::Transform got #{other.class}"
@@ -279,7 +279,7 @@ module CyberarmEngine
end end
end end
return Transform.new(matrix) Transform.new(matrix)
end end
# arranges Matrix in column major form # arranges Matrix in column major form

View File

@@ -1,6 +1,7 @@
module CyberarmEngine module CyberarmEngine
class BorderCanvas class BorderCanvas
attr_reader :element, :top, :right, :bottom, :left attr_reader :element, :top, :right, :bottom, :left
def initialize(element:) def initialize(element:)
@element = element @element = element
@@ -25,7 +26,7 @@ module CyberarmEngine
elsif color.is_a?(Array) elsif color.is_a?(Array)
if color.size == 1 if color.size == 1
color=color.first color = color.first
elsif color.size == 2 elsif color.size == 2
@top.background = color.first @top.background = color.first
@@ -61,7 +62,7 @@ module CyberarmEngine
def update def update
# TOP # TOP
@top.x = @element.x# + @element.border_thickness_left @top.x = @element.x # + @element.border_thickness_left
@top.y = @element.y @top.y = @element.y
@top.z = @element.z @top.z = @element.z

View File

@@ -12,70 +12,70 @@ module CyberarmEngine
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::Label.new(text, options, block) ) add_element(Element::Label.new(text, options, block))
end end
def button(text, options = {}, &block) def button(text, options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::Button.new(text, options, block) { if block.is_a?(Proc); block.call; end } ) add_element(Element::Button.new(text, options, block) { block.call if block.is_a?(Proc) })
end end
def list_box(options = {}, &block) def list_box(options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::ListBox.new(options, block) { if block.is_a?(Proc); block.call; end } ) add_element(Element::ListBox.new(options, block) { block.call if block.is_a?(Proc) })
end end
def edit_line(text, options = {}, &block) def edit_line(text, options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::EditLine.new(text, options, block) ) add_element(Element::EditLine.new(text, options, block))
end end
def edit_box(text, options = {}, &block) def edit_box(text, options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::EditBox.new(text, options, block) ) add_element(Element::EditBox.new(text, options, block))
end end
def toggle_button(options = {}, &block) def toggle_button(options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::ToggleButton.new(options, block) ) add_element(Element::ToggleButton.new(options, block))
end end
def check_box(text, options = {}, &block) def check_box(text, options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::CheckBox.new(text, options, block) ) add_element(Element::CheckBox.new(text, options, block))
end end
def image(path, options = {}, &block) def image(path, options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::Image.new(path, options, block) ) add_element(Element::Image.new(path, options, block))
end end
def progress(options = {}, &block) def progress(options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::Progress.new(options, block) ) add_element(Element::Progress.new(options, block))
end end
def slider(options = {}, &block) def slider(options = {}, &block)
options[:parent] = element_parent options[:parent] = element_parent
options[:theme] = current_theme options[:theme] = current_theme
add_element( Element::Slider.new(options, block) ) add_element(Element::Slider.new(options, block))
end end
def background(color = Gosu::Color::NONE) def background(color = Gosu::Color::NONE)
@@ -93,7 +93,7 @@ module CyberarmEngine
private def add_element(element) private def add_element(element)
element_parent.add(element) element_parent.add(element)
return element element
end end
private def element_parent private def element_parent
@@ -114,7 +114,7 @@ module CyberarmEngine
$__current_container__ = old_parent $__current_container__ = old_parent
return _container _container
end end
end end
end end

View File

@@ -16,7 +16,7 @@ module CyberarmEngine
@focus = false @focus = false
@enabled = true @enabled = true
@visible = true @visible = true
@tip = @options[:tip] ? @options[:tip] : "" @tip = @options[:tip] || ""
@style = Style.new(options) @style = Style.new(options)
@@ -102,7 +102,7 @@ module CyberarmEngine
end end
def default_events def default_events
[:left, :middle, :right].each do |button| %i[left middle right].each do |button|
event(:"#{button}_mouse_button") event(:"#{button}_mouse_button")
event(:"released_#{button}_mouse_button") event(:"released_#{button}_mouse_button")
event(:"clicked_#{button}_mouse_button") event(:"clicked_#{button}_mouse_button")
@@ -152,7 +152,7 @@ module CyberarmEngine
@style.background_canvas.draw @style.background_canvas.draw
@style.border_canvas.draw @style.border_canvas.draw
Gosu.clip_to(@x,@y, width, height) do Gosu.clip_to(@x, @y, width, height) do
render render
end end
end end
@@ -166,7 +166,7 @@ module CyberarmEngine
def button_up(id) def button_up(id)
end end
def draggable?(button) def draggable?(_button)
false false
end end
@@ -175,7 +175,7 @@ module CyberarmEngine
def hit?(x, y) def hit?(x, y)
x.between?(@x, @x + width) && x.between?(@x, @x + width) &&
y.between?(@y, @y + height) y.between?(@y, @y + height)
end end
def width def width
@@ -227,11 +227,11 @@ module CyberarmEngine
end end
def dimensional_size(size, dimension) def dimensional_size(size, dimension)
raise "dimension must be either :width or :height" unless dimension == :width || dimension == :height raise "dimension must be either :width or :height" unless %i[width height].include?(dimension)
if size && size.is_a?(Numeric) if size && size.is_a?(Numeric)
if size.between?(0.0, 1.0) if size.between?(0.0, 1.0)
((@parent.send(:"content_#{dimension}") - self.send(:"noncontent_#{dimension}")) * size).round ((@parent.send(:"content_#{dimension}") - send(:"noncontent_#{dimension}")) * size).round
else else
size size
end end
@@ -239,7 +239,7 @@ module CyberarmEngine
end end
def background=(_background) def background=(_background)
@style.background_canvas.background=(_background) @style.background_canvas.background = (_background)
update_background update_background
end end
@@ -288,12 +288,12 @@ module CyberarmEngine
raise "#{self.class}#value was not overridden!" raise "#{self.class}#value was not overridden!"
end end
def value=(value) def value=(_value)
raise "#{self.class}#value= was not overridden!" raise "#{self.class}#value= was not overridden!"
end end
def to_s def to_s
"#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} value=#{ value.is_a?(String) ? "\"#{value}\"" : value }" "#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} value=#{value.is_a?(String) ? "\"#{value}\"" : value}"
end end
end end
end end

View File

@@ -2,11 +2,11 @@ module CyberarmEngine
class Element class Element
class Button < Label class Button < Label
def initialize(text_or_image, options = {}, block = nil) def initialize(text_or_image, options = {}, block = nil)
@image, @scale_x, @scale_y = nil, 1, 1 @image = nil
@scale_x = 1
@scale_y = 1
if text_or_image.is_a?(Gosu::Image) @image = text_or_image if text_or_image.is_a?(Gosu::Image)
@image = text_or_image
end
super(text_or_image, options, block) super(text_or_image, options, block)
@@ -26,14 +26,15 @@ module CyberarmEngine
@style.border_thickness_left + @style.padding_left + @x, @style.border_thickness_left + @style.padding_left + @x,
@style.border_thickness_top + @style.padding_top + @y, @style.border_thickness_top + @style.padding_top + @y,
@z + 2, @z + 2,
@scale_x, @scale_y, @text.color) @scale_x, @scale_y, @text.color
)
end end
def draw_text def draw_text
@text.draw @text.draw
end end
def enter(sender) def enter(_sender)
@focus = false unless window.button_down?(Gosu::MsLeft) @focus = false unless window.button_down?(Gosu::MsLeft)
if @focus if @focus
@@ -44,49 +45,50 @@ module CyberarmEngine
@text.color = default(:hover, :color) @text.color = default(:hover, :color)
end end
return :handled :handled
end end
def left_mouse_button(sender, x, y) def left_mouse_button(_sender, _x, _y)
@focus = true @focus = true
@style.background_canvas.background = default(:active, :background) @style.background_canvas.background = default(:active, :background)
window.current_state.focus = self window.current_state.focus = self
@text.color = default(:active, :color) @text.color = default(:active, :color)
return :handled :handled
end end
def released_left_mouse_button(sender,x, y) def released_left_mouse_button(sender, _x, _y)
enter(sender) enter(sender)
return :handled :handled
end end
def clicked_left_mouse_button(sender, x, y) def clicked_left_mouse_button(_sender, _x, _y)
@block.call(self) if @block @block.call(self) if @block
return :handled :handled
end end
def leave(sender) def leave(_sender)
@style.background_canvas.background = default(:background) @style.background_canvas.background = default(:background)
@text.color = default(:color) @text.color = default(:color)
return :handled :handled
end end
def blur(sender) def blur(_sender)
@focus = false @focus = false
return :handled :handled
end end
def recalculate def recalculate
if @image if @image
@width, @height = 0, 0 @width = 0
@height = 0
_width = dimensional_size(@style.image_width, :width) _width = dimensional_size(@style.image_width, :width)
_height= dimensional_size(@style.image_height,:height) _height = dimensional_size(@style.image_height, :height)
if _width && _height if _width && _height
@scale_x = _width.to_f / @image.width @scale_x = _width.to_f / @image.width
@@ -98,11 +100,12 @@ module CyberarmEngine
@scale_y = _height.to_f / @image.height @scale_y = _height.to_f / @image.height
@scale_x = @scale_y @scale_x = @scale_y
else else
@scale_x, @scale_y = 1, 1 @scale_x = 1
@scale_y = 1
end end
@width = _width ? _width : @image.width.round * @scale_x @width = _width || @image.width.round * @scale_x
@height= _height ? _height : @image.height.round * @scale_y @height = _height || @image.height.round * @scale_y
update_background update_background
else else
@@ -111,7 +114,7 @@ module CyberarmEngine
end end
def value def value
@image ? @image : super @image || super
end end
def value=(value) def value=(value)
@@ -121,7 +124,8 @@ module CyberarmEngine
super super
end end
old_width, old_height = width, height old_width = width
old_height = height
recalculate recalculate
root.gui_state.request_recalculate if old_width != width || old_height != height root.gui_state.request_recalculate if old_width != width || old_height != height

View File

@@ -4,14 +4,14 @@ module CyberarmEngine
include Common include Common
attr_accessor :stroke_color, :fill_color attr_accessor :stroke_color, :fill_color
attr_reader :children, :gui_state attr_reader :children, :gui_state, :scroll_x, :scroll_y
attr_reader :scroll_x, :scroll_y
def initialize(options = {}, block = nil) def initialize(options = {}, block = nil)
@gui_state = options.delete(:gui_state) @gui_state = options.delete(:gui_state)
super super
@scroll_x, @scroll_y = 0, 0 @scroll_x = 0
@scroll_y = 0
@scroll_speed = 10 @scroll_speed = 10
@text_color = options[:color] @text_color = options[:color]
@@ -49,27 +49,27 @@ module CyberarmEngine
@children.each(&:draw) @children.each(&:draw)
end end
if false#DEBUG if false # DEBUG
Gosu.flush Gosu.flush
Gosu.draw_line( Gosu.draw_line(
self.x, self.y, Gosu::Color::RED, x, y, Gosu::Color::RED,
self.x + outer_width, self.y, Gosu::Color::RED, x + outer_width, y, Gosu::Color::RED,
Float::INFINITY Float::INFINITY
) )
Gosu.draw_line( Gosu.draw_line(
self.x + outer_width, self.y, Gosu::Color::RED, x + outer_width, y, Gosu::Color::RED,
self.x + outer_width, self.y + outer_height, Gosu::Color::RED, x + outer_width, y + outer_height, Gosu::Color::RED,
Float::INFINITY Float::INFINITY
) )
Gosu.draw_line( Gosu.draw_line(
self.x + outer_width, self.y + outer_height, Gosu::Color::RED, x + outer_width, y + outer_height, Gosu::Color::RED,
self.x, self.y + outer_height, Gosu::Color::RED, x, y + outer_height, Gosu::Color::RED,
Float::INFINITY Float::INFINITY
) )
Gosu.draw_line( Gosu.draw_line(
self.x, outer_height, Gosu::Color::RED, x, outer_height, Gosu::Color::RED,
self.x, self.y, Gosu::Color::RED, x, y, Gosu::Color::RED,
Float::INFINITY Float::INFINITY
) )
end end
@@ -110,13 +110,14 @@ module CyberarmEngine
@width = @style.width = window.width @width = @style.width = window.width
@height = @style.height = window.height @height = @style.height = window.height
else else
@width, @height = 0, 0 @width = 0
@height = 0
_width = dimensional_size(@style.width, :width) _width = dimensional_size(@style.width, :width)
_height= dimensional_size(@style.height,:height) _height = dimensional_size(@style.height, :height)
@width = _width ? _width : (@children.map {|c| c.x + c.outer_width }.max || 0).round @width = _width || (@children.map { |c| c.x + c.outer_width }.max || 0).round
@height = _height ? _height : (@children.map {|c| c.y + c.outer_height}.max || 0).round @height = _height || (@children.map { |c| c.y + c.outer_height }.max || 0).round
end end
# Move child to parent after positioning # Move child to parent after positioning
@@ -140,13 +141,17 @@ module CyberarmEngine
def max_width def max_width
_width = dimensional_size(@style.width, :width) _width = dimensional_size(@style.width, :width)
_width ? outer_width : window.width - (@parent ? @parent.style.margin_right + @style.margin_right : @style.margin_right) if _width
outer_width
else
window.width - (@parent ? @parent.style.margin_right + @style.margin_right : @style.margin_right)
end
end end
def fits_on_line?(element) # Flow def fits_on_line?(element) # Flow
p [@options[:id], @width] if @options[:id] p [@options[:id], @width] if @options[:id]
@current_position.x + element.outer_width <= max_width && @current_position.x + element.outer_width <= max_width &&
@current_position.x + element.outer_width <= window.width @current_position.x + element.outer_width <= window.width
end end
def position_on_current_line(element) # Flow def position_on_current_line(element) # Flow
@@ -157,14 +162,14 @@ module CyberarmEngine
@current_position.x = @style.margin_left if @current_position.x >= max_width @current_position.x = @style.margin_left if @current_position.x >= max_width
end end
def tallest_neighbor(querier, y_position) # Flow def tallest_neighbor(querier, _y_position) # Flow
response = querier response = querier
@children.each do |child| @children.each do |child|
response = child if child.outer_height > response.outer_height response = child if child.outer_height > response.outer_height
break if child == querier break if child == querier
end end
return response response
end end
def position_on_next_line(child) # Flow def position_on_next_line(child) # Flow
@@ -195,17 +200,17 @@ module CyberarmEngine
# end # end
def value def value
@children.map {|c| c.class}.join(", ") @children.map { |c| c.class }.join(", ")
end end
def to_s def to_s
"#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} children=#{@children.size}" "#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} children=#{@children.size}"
end end
def write_tree(indent = "", index = 0) def write_tree(indent = "", _index = 0)
puts self puts self
indent = indent + " " indent += " "
@children.each_with_index do |child, i| @children.each_with_index do |child, i|
print "#{indent}#{i}: " print "#{indent}#{i}: "

View File

@@ -12,14 +12,14 @@ module CyberarmEngine
down: false, down: false,
repeat_delay: 50, repeat_delay: 50,
last_repeat: 0, last_repeat: 0,
action: proc {move(:up)} action: proc { move(:up) }
}, },
{ {
key: Gosu::KB_DOWN, key: Gosu::KB_DOWN,
down: false, down: false,
repeat_delay: 50, repeat_delay: 50,
last_repeat: 0, last_repeat: 0,
action: proc {move(:down)} action: proc { move(:down) }
} }
] ]
end end
@@ -31,26 +31,26 @@ module CyberarmEngine
calculate_active_line calculate_active_line
@repeatable_keys.each do |key| @repeatable_keys.each do |key|
if key[:down] if key[:down] && (Gosu.milliseconds > key[:last_repeat] + key[:repeat_delay])
if Gosu.milliseconds > key[:last_repeat] + key[:repeat_delay] key[:action].call
key[:action].call key[:last_repeat] = Gosu.milliseconds
key[:last_repeat] = Gosu.milliseconds
end
end end
end end
end end
def draw_caret def draw_caret
Gosu.draw_rect(caret_position, @text.y + @active_line * @text.textobject.height, @caret_width, @caret_height, @caret_color, @z) Gosu.draw_rect(caret_position, @text.y + @active_line * @text.textobject.height, @caret_width, @caret_height,
@caret_color, @z)
end end
def draw_selection def draw_selection
selection_width = caret_position - selection_start_position selection_width = caret_position - selection_start_position
Gosu.draw_rect(selection_start_position, @text.y, selection_width, @text.textobject.height, default(:selection_color), @z) Gosu.draw_rect(selection_start_position, @text.y, selection_width, @text.textobject.height,
default(:selection_color), @z)
end end
def text_input_position_for(method) def text_input_position_for(_method)
line = @text_input.text[0...@text_input.caret_pos].lines.last line = @text_input.text[0...@text_input.caret_pos].lines.last
_x = @text.x + @offset_x _x = @text.x + @offset_x
@@ -68,11 +68,11 @@ module CyberarmEngine
def calculate_active_line def calculate_active_line
sub_text = @text_input.text[0...@text_input.caret_pos] sub_text = @text_input.text[0...@text_input.caret_pos]
@active_line = sub_text.lines.size-1 @active_line = sub_text.lines.size - 1
end end
def caret_stay_left_of_last_newline def caret_stay_left_of_last_newline
@text_input.text+="\n" unless @text_input.text.end_with?("\n") @text_input.text += "\n" unless @text_input.text.end_with?("\n")
eof = @text_input.text.chomp.length eof = @text_input.text.chomp.length
set_position(eof) if @text_input.caret_pos > eof set_position(eof) if @text_input.caret_pos > eof
@@ -94,7 +94,7 @@ module CyberarmEngine
end end
def move_caret_to_mouse(mouse_x, mouse_y) def move_caret_to_mouse(mouse_x, mouse_y)
set_position( caret_position_under_mouse(mouse_x, mouse_y) ) set_position(caret_position_under_mouse(mouse_x, mouse_y))
end end
def row_at(y) def row_at(y)
@@ -108,27 +108,27 @@ module CyberarmEngine
buffer = @text_input.text.lines.first if row == 0 buffer = @text_input.text.lines.first if row == 0
line = @text_input.text.lines[row] line = @text_input.text.lines[row]
line = "" unless line line ||= ""
column = 0 column = 0
line.length.times do |i| line.length.times do |_i|
break if @text.textobject.text_width(line[0...column]) >= (x - @text.x).clamp(0.0, Float::INFINITY) break if @text.textobject.text_width(line[0...column]) >= (x - @text.x).clamp(0.0, Float::INFINITY)
column += 1 column += 1
end end
return column column
end end
def button_down(id) def button_down(id)
super super
@repeatable_keys.detect do |key| @repeatable_keys.detect do |key|
if key[:key] == id next unless key[:key] == id
key[:down] = true
key[:last_repeat] = Gosu.milliseconds + key[:repeat_delay] key[:down] = true
return true key[:last_repeat] = Gosu.milliseconds + key[:repeat_delay]
end return true
end end
case id case id
@@ -159,6 +159,7 @@ module CyberarmEngine
return if @active_line == 0 return if @active_line == 0
when :down when :down
return if @active_line == @text_input.text.chomp.lines return if @active_line == @text_input.text.chomp.lines
text = @text_input.text.chomp.lines[0..@active_line].join("\n") text = @text_input.text.chomp.lines[0..@active_line].join("\n")
pos = text.length pos = text.length
end end
@@ -166,7 +167,7 @@ module CyberarmEngine
set_position(pos) set_position(pos)
end end
def drag_update(sender, x, y, button) def drag_update(_sender, x, y, _button)
int = caret_position_under_mouse(x, y) int = caret_position_under_mouse(x, y)
int = 0 if int < 0 int = 0 if int < 0
@text_input.caret_pos = int @text_input.caret_pos = int

View File

@@ -8,11 +8,11 @@ module CyberarmEngine
@type = default(:type) @type = default(:type)
@caret_width = default(:caret_width) @caret_width = default(:caret_width)
@caret_height= @text.textobject.height @caret_height = @text.textobject.height
@caret_color = default(:caret_color) @caret_color = default(:caret_color)
@caret_interval = default(:caret_interval) @caret_interval = default(:caret_interval)
@caret_last_interval = Gosu.milliseconds @caret_last_interval = Gosu.milliseconds
@show_caret = true @show_caret = true
@text_input = Gosu::TextInput.new @text_input = Gosu::TextInput.new
@text_input.text = text @text_input.text = text
@@ -26,7 +26,8 @@ module CyberarmEngine
end end
end end
@offset_x, @offset_y = 0, 0 @offset_x = 0
@offset_y = 0
event(:begin_drag) event(:begin_drag)
event(:drag_update) event(:drag_update)
@@ -58,16 +59,16 @@ module CyberarmEngine
end end
def update def update
if @type == :password @text.text = if @type == :password
@text.text = default(:password_character) * @text_input.text.length default(:password_character) * @text_input.text.length
else else
@text.text = @text_input.text @text_input.text
end end
if @last_text_value != self.value if @last_text_value != value
@last_text_value = self.value @last_text_value = value
publish(:changed, self.value) publish(:changed, value)
end end
if Gosu.milliseconds >= @caret_last_interval + @caret_interval if Gosu.milliseconds >= @caret_last_interval + @caret_interval
@@ -85,7 +86,8 @@ module CyberarmEngine
def handle_keyboard_shortcuts(id) def handle_keyboard_shortcuts(id)
return unless @focus && @enabled return unless @focus && @enabled
if Gosu.button_down?(Gosu::KB_LEFT_CONTROL) or Gosu.button_down?(Gosu::KB_RIGHT_CONTROL)
if Gosu.button_down?(Gosu::KB_LEFT_CONTROL) || Gosu.button_down?(Gosu::KB_RIGHT_CONTROL)
case id case id
when Gosu::KB_A when Gosu::KB_A
@text_input.selection_start = 0 @text_input.selection_start = 0
@@ -113,7 +115,8 @@ module CyberarmEngine
when Gosu::KB_V when Gosu::KB_V
if instance_of?(EditLine) # EditLine assumes a single line of text if instance_of?(EditLine) # EditLine assumes a single line of text
@text_input.text = @text_input.text.insert(@text_input.caret_pos, Clipboard.paste.encode("UTF-8").gsub("\n", "")) @text_input.text = @text_input.text.insert(@text_input.caret_pos,
Clipboard.paste.encode("UTF-8").gsub("\n", ""))
else else
@text_input.text = @text_input.text.insert(@text_input.caret_pos, Clipboard.paste.encode("UTF-8")) @text_input.text = @text_input.text.insert(@text_input.caret_pos, Clipboard.paste.encode("UTF-8"))
end end
@@ -123,15 +126,13 @@ module CyberarmEngine
def caret_position_under_mouse(mouse_x) def caret_position_under_mouse(mouse_x)
1.upto(@text.text.length) do |i| 1.upto(@text.text.length) do |i|
if mouse_x < @text.x - @offset_x + @text.width(@text.text[0...i]) return i - 1 if mouse_x < @text.x - @offset_x + @text.width(@text.text[0...i])
return i - 1
end
end end
@text_input.text.length @text_input.text.length
end end
def move_caret_to_mouse(mouse_x, mouse_y) def move_caret_to_mouse(mouse_x, _mouse_y)
@text_input.caret_pos = @text_input.selection_start = caret_position_under_mouse(mouse_x) @text_input.caret_pos = @text_input.selection_start = caret_position_under_mouse(mouse_x)
end end
@@ -144,16 +145,15 @@ module CyberarmEngine
@last_text = @text.text @last_text = @text.text
@last_pos = caret_pos @last_pos = caret_pos
if caret_pos.between?(@offset_x, @width + @offset_x) if caret_pos.between?(@offset_x, @width + @offset_x)
# Do nothing # Do nothing
elsif caret_pos < @offset_x elsif caret_pos < @offset_x
if caret_pos > @width @offset_x = if caret_pos > @width
@offset_x = caret_pos + @width caret_pos + @width
else else
@offset_x = 0 0
end end
elsif caret_pos > @width elsif caret_pos > @width
@offset_x = caret_pos - @width @offset_x = caret_pos - @width
@@ -189,10 +189,10 @@ module CyberarmEngine
move_caret_to_mouse(x, y) move_caret_to_mouse(x, y)
return :handled :handled
end end
def enter(sender) def enter(_sender)
if @focus if @focus
@style.background_canvas.background = default(:active, :background) @style.background_canvas.background = default(:active, :background)
@text.color = default(:active, :color) @text.color = default(:active, :color)
@@ -201,31 +201,29 @@ module CyberarmEngine
@text.color = default(:hover, :color) @text.color = default(:hover, :color)
end end
return :handled :handled
end end
def leave(sender) def leave(sender)
unless @focus super unless @focus
super
end
return :handled :handled
end end
def blur(sender) def blur(_sender)
@focus = false @focus = false
@style.background_canvas.background = default(:background) @style.background_canvas.background = default(:background)
@text.color = default(:color) @text.color = default(:color)
window.text_input = nil window.text_input = nil
return :handled :handled
end end
def draggable?(button) def draggable?(button)
button == :left button == :left
end end
def begin_drag(sender, x, y, button) def begin_drag(_sender, x, _y, _button)
@drag_start = x @drag_start = x
@offset_drag_start = @offset_x @offset_drag_start = @offset_x
@drag_caret_position = @text_input.caret_pos @drag_caret_position = @text_input.caret_pos
@@ -233,14 +231,13 @@ module CyberarmEngine
:handled :handled
end end
def drag_update(sender, x, y, button) def drag_update(_sender, x, _y, _button)
@text_input.caret_pos = caret_position_under_mouse(x) @text_input.caret_pos = caret_position_under_mouse(x)
:handled :handled
end end
def end_drag(sender, x, y, button) def end_drag(_sender, _x, _y, _button)
:handled :handled
end end

View File

@@ -6,7 +6,8 @@ module CyberarmEngine
@path = path @path = path
@image = Gosu::Image.new(path, retro: @options[:image_retro]) @image = Gosu::Image.new(path, retro: @options[:image_retro])
@scale_x, @scale_y = 1, 1 @scale_x = 1
@scale_y = 1
end end
def render def render
@@ -14,18 +15,19 @@ module CyberarmEngine
@style.border_thickness_left + @style.padding_left + @x, @style.border_thickness_left + @style.padding_left + @x,
@style.border_thickness_top + @style.padding_top + @y, @style.border_thickness_top + @style.padding_top + @y,
@z + 2, @z + 2,
@scale_x, @scale_y, @style.color) @scale_x, @scale_y, @style.color
)
end end
def clicked_left_mouse_button(sender, x, y) def clicked_left_mouse_button(_sender, _x, _y)
@block.call(self) if @block @block.call(self) if @block
return :handled :handled
end end
def recalculate def recalculate
_width = dimensional_size(@style.width, :width) _width = dimensional_size(@style.width, :width)
_height= dimensional_size(@style.height,:height) _height = dimensional_size(@style.height, :height)
if _width && _height if _width && _height
@scale_x = _width.to_f / @image.width @scale_x = _width.to_f / @image.width
@@ -37,11 +39,12 @@ module CyberarmEngine
@scale_y = _height.to_f / @image.height @scale_y = _height.to_f / @image.height
@scale_x = @scale_y @scale_x = @scale_y
else else
@scale_x, @scale_y = 1, 1 @scale_x = 1
@scale_y = 1
end end
@width = _width ? _width : @image.width.round * @scale_x @width = _width || @image.width.round * @scale_x
@height= _height ? _height : @image.height.round * @scale_y @height = _height || @image.height.round * @scale_y
end end
def value def value

View File

@@ -5,11 +5,11 @@ module CyberarmEngine
super(options, block) super(options, block)
@text = Text.new( @text = Text.new(
text, font: @options[:font], z: @z, color: @options[:color], text, font: @options[:font], z: @z, color: @options[:color],
size: @options[:text_size], shadow: @options[:text_shadow], size: @options[:text_size], shadow: @options[:text_shadow],
shadow_size: @options[:text_shadow_size], shadow_size: @options[:text_shadow_size],
shadow_color: @options[:text_shadow_color] shadow_color: @options[:text_shadow_color]
) )
@raw_text = text @raw_text = text
end end
@@ -18,7 +18,7 @@ module CyberarmEngine
@text.draw @text.draw
end end
def clicked_left_mouse_button(sender, x, y) def clicked_left_mouse_button(_sender, _x, _y)
@block&.call(self) @block&.call(self)
# return :handled # return :handled
@@ -44,11 +44,11 @@ module CyberarmEngine
when :left when :left
@text.x = @style.border_thickness_left + @style.padding_left + @x @text.x = @style.border_thickness_left + @style.padding_left + @x
when :center when :center
if @text.width <= outer_width @text.x = if @text.width <= outer_width
@text.x = @x + outer_width / 2 - @text.width / 2 @x + outer_width / 2 - @text.width / 2
else # Act as left aligned else # Act as left aligned
@text.x = @style.border_thickness_left + @style.padding_left + @x @style.border_thickness_left + @style.padding_left + @x
end end
when :right when :right
@text.x = @x + outer_width - (@text.width + @style.border_thickness_right + @style.padding_right) @text.x = @x + outer_width - (@text.width + @style.border_thickness_right + @style.padding_right)
end end
@@ -84,7 +84,7 @@ module CyberarmEngine
if wrap_behavior == :word_wrap if wrap_behavior == :word_wrap
max_reach.times do |i| max_reach.times do |i|
reach = i reach = i
break if copy[line_end.floor - i].to_s.match(/[[:punct:]]|[ ]/) break if copy[line_end.floor - i].to_s.match(/[[:punct:]]| /)
end end
puts "Max width: #{max_width}/#{line_width(@raw_text)} Reach: {#{reach}/#{max_reach}} Line Start: #{line_start}/#{line_end.floor} (#{copy.length}|#{@raw_text.length}) [#{entering_line_end}] '#{copy}' {#{copy[line_start...line_end]}}" puts "Max width: #{max_width}/#{line_width(@raw_text)} Reach: {#{reach}/#{max_reach}} Line Start: #{line_start}/#{line_end.floor} (#{copy.length}|#{@raw_text.length}) [#{entering_line_end}] '#{copy}' {#{copy[line_start...line_end]}}"

View File

@@ -5,8 +5,8 @@ module CyberarmEngine
attr_reader :choose attr_reader :choose
def initialize(options = {}, block = nil) def initialize(options = {}, block = nil)
@items = options[:items] ? options[:items] : [] @items = options[:items] || []
@choose = options[:choose] ? options[:choose] : @items.first @choose = options[:choose] || @items.first
super(@choose, options, block) super(@choose, options, block)
@@ -29,6 +29,7 @@ module CyberarmEngine
def choose=(item) def choose=(item)
valid = @items.detect { |i| i == item } valid = @items.detect { |i| i == item }
return unless valid # TODO: Throw an error? return unless valid # TODO: Throw an error?
@choose = item @choose = item
self.value = item.to_s self.value = item.to_s
@@ -36,18 +37,19 @@ module CyberarmEngine
recalculate recalculate
end end
def released_left_mouse_button(sender, x, y) def released_left_mouse_button(_sender, _x, _y)
show_menu show_menu
return :handled :handled
end end
def show_menu def show_menu
@menu.clear @menu.clear
@items.each do |item| @items.each do |item|
[ @block] [@block]
block = proc { self.choose = item; @block.call(item) if @block } block = proc { self.choose = item; @block.call(item) if @block }
b = Button.new(item, { parent: @menu, width: 1.0, theme: @options[:theme], margin: 0, border_color: 0x00ffffff }, block) b = Button.new(item,
{ parent: @menu, width: 1.0, theme: @options[:theme], margin: 0, border_color: 0x00ffffff }, block)
@menu.add(b) @menu.add(b)
end end

View File

@@ -5,7 +5,7 @@ module CyberarmEngine
super(options, block) super(options, block)
@fraction_background = Background.new(background: @style.fraction_background) @fraction_background = Background.new(background: @style.fraction_background)
self.value = options[:fraction] ? options[:fraction] : 0.0 self.value = options[:fraction] || 0.0
end end
def render def render
@@ -14,9 +14,9 @@ module CyberarmEngine
def recalculate def recalculate
_width = dimensional_size(@style.width, :width) _width = dimensional_size(@style.width, :width)
_height= dimensional_size(@style.height,:height) _height = dimensional_size(@style.height, :height)
@width = _width @width = _width
@height= _height @height = _height
update_background update_background
end end
@@ -44,7 +44,7 @@ module CyberarmEngine
update_background update_background
publish(:changed, @fraction) publish(:changed, @fraction)
return @fraction @fraction
end end
end end
end end

View File

@@ -9,13 +9,13 @@ module CyberarmEngine
event(:drag_update) event(:drag_update)
event(:end_drag) event(:end_drag)
subscribe :begin_drag do |sender, x, y, button| subscribe :begin_drag do |_sender, x, y, _button|
@drag_start_pos = Vector.new(x, y) @drag_start_pos = Vector.new(x, y)
:handled :handled
end end
subscribe :drag_update do |sender, x, y, button| subscribe :drag_update do |_sender, x, y, _button|
@parent.handle_dragged_to(x, y) @parent.handle_dragged_to(x, y)
:handled :handled
@@ -33,21 +33,22 @@ module CyberarmEngine
end end
end end
attr_reader :range, :step_size attr_reader :range, :step_size, :value
def initialize(options = {}, block = nil) def initialize(options = {}, block = nil)
super(options, block) super(options, block)
@range = @options[:range] ? @options[:range] : 0.0..1.0 @range = @options[:range] || (0.0..1.0)
@step_size = @options[:step] ? @options[:step] : 0.1 @step_size = @options[:step] || 0.1
@value = @options[:value] ? @options[:value] : (@range.first + @range.last) / 2 @value = @options[:value] || (@range.first + @range.last) / 2
@handle = Handle.new("", parent: self, width: 8, height: 1.0) { close } @handle = Handle.new("", parent: self, width: 8, height: 1.0) { close }
self.add(@handle) add(@handle)
end end
def recalculate def recalculate
_width = dimensional_size(@style.width, :width) _width = dimensional_size(@style.width, :width)
_height= dimensional_size(@style.height,:height) _height = dimensional_size(@style.height, :height)
@width = _width @width = _width
@height = _height @height = _height
@@ -61,7 +62,7 @@ module CyberarmEngine
def position_handle def position_handle
@handle.x = @x + @style.padding_left + @style.border_thickness_left + @handle.x = @x + @style.padding_left + @style.border_thickness_left +
((content_width - @handle.outer_width) * (@value - @range.min) / (@range.max - @range.min).to_f) ((content_width - @handle.outer_width) * (@value - @range.min) / (@range.max - @range.min).to_f)
@handle.y = @y + @style.border_thickness_top + @style.padding_top @handle.y = @y + @style.border_thickness_top + @style.padding_top
end end
@@ -79,22 +80,18 @@ module CyberarmEngine
@handle.tip = @tip @handle.tip = @tip
end end
def holding_left_mouse_button(sender, x, y) def holding_left_mouse_button(_sender, x, y)
handle_dragged_to(x, y) handle_dragged_to(x, y)
:handled :handled
end end
def handle_dragged_to(x, y) def handle_dragged_to(x, _y)
@ratio = ((x - @handle.width / 2) - @x) / (content_width - @handle.outer_width) @ratio = ((x - @handle.width / 2) - @x) / (content_width - @handle.outer_width)
self.value = @ratio.clamp(0.0, 1.0) * (@range.max - @range.min) + @range.min self.value = @ratio.clamp(0.0, 1.0) * (@range.max - @range.min) + @range.min
end end
def value
@value
end
def value=(n) def value=(n)
@value = n @value = n
position_handle position_handle

View File

@@ -1,7 +1,7 @@
module CyberarmEngine module CyberarmEngine
class Element class Element
class ToggleButton < Button class ToggleButton < Button
attr_reader :toggled attr_reader :toggled, :value
def initialize(options, block = nil) def initialize(options, block = nil)
if options.dig(:theme, :ToggleButton, :checkmark_image) if options.dig(:theme, :ToggleButton, :checkmark_image)
@@ -24,12 +24,12 @@ module CyberarmEngine
end end
end end
def clicked_left_mouse_button(sender, x, y) def clicked_left_mouse_button(_sender, _x, _y)
self.value = !@value self.value = !@value
@block.call(self) if @block @block.call(self) if @block
return :handled :handled
end end
def recalculate def recalculate
@@ -45,10 +45,6 @@ module CyberarmEngine
update_background update_background
end end
def value
@value
end
def value=(boolean) def value=(boolean)
@value = boolean @value = boolean

View File

@@ -15,20 +15,18 @@ module CyberarmEngine
return unless enabled? return unless enabled?
if respond_to?(event) return :handled if respond_to?(event) && (send(event, self, *args) == :handled)
return :handled if send(event, self, *args) == :handled
end
@event_handler[event].reverse_each do |handler| @event_handler[event].reverse_each do |handler|
return :handled if handler.call(self, *args) == :handled return :handled if handler.call(self, *args) == :handled
end end
parent.publish(event, *args) if parent parent.publish(event, *args) if parent
return nil nil
end end
def event(event) def event(event)
@event_handler ||= Hash.new @event_handler ||= {}
@event_handler[event] ||= [] @event_handler[event] ||= []
end end
end end
@@ -37,7 +35,9 @@ module CyberarmEngine
attr_reader :publisher, :event, :handler attr_reader :publisher, :event, :handler
def initialize(publisher, event, handler) def initialize(publisher, event, handler)
@publisher, @event, @handler = publisher, event, handler @publisher = publisher
@event = event
@handler = handler
end end
def unsubscribe def unsubscribe

View File

@@ -35,7 +35,7 @@ module CyberarmEngine
# throws :blur event to focused element and sets GuiState focused element # throws :blur event to focused element and sets GuiState focused element
# Does NOT throw :focus event at element or set element as focused # Does NOT throw :focus event at element or set element as focused
def focus=(element) def focus=(element)
@focus.publish(:blur) if @focus and element && @focus != element @focus.publish(:blur) if @focus && element && @focus != element
@focus = element @focus = element
end end
@@ -88,7 +88,8 @@ module CyberarmEngine
if Vector.new(window.mouse_x, window.mouse_y) == @last_mouse_pos if Vector.new(window.mouse_x, window.mouse_y) == @last_mouse_pos
if @mouse_over && (Gosu.milliseconds - @mouse_moved_at) > tool_tip_delay if @mouse_over && (Gosu.milliseconds - @mouse_moved_at) > tool_tip_delay
@tip.text = @mouse_over.tip if @mouse_over @tip.text = @mouse_over.tip if @mouse_over
@tip.x, @tip.y = window.mouse_x - @tip.width / 2, window.mouse_y - @tip.height - 4 @tip.x = window.mouse_x - @tip.width / 2
@tip.y = window.mouse_y - @tip.height - 4
else else
@tip.text = "" @tip.text = ""
end end
@@ -146,7 +147,7 @@ module CyberarmEngine
end end
def redirect_mouse_button(button) def redirect_mouse_button(button)
hide_menu unless @menu and (@menu == @mouse_over) or (@mouse_over&.parent == @menu) hide_menu unless @menu && (@menu == @mouse_over) || (@mouse_over&.parent == @menu)
if @focus && @mouse_over != @focus if @focus && @mouse_over != @focus
@focus.publish(:blur) @focus.publish(:blur)
@@ -165,11 +166,14 @@ module CyberarmEngine
end end
def redirect_released_mouse_button(button) def redirect_released_mouse_button(button)
hide_menu if @menu and (@menu == @mouse_over) or (@mouse_over&.parent == @menu) hide_menu if @menu && (@menu == @mouse_over) || (@mouse_over&.parent == @menu)
if @mouse_over if @mouse_over
@mouse_over.publish(:"released_#{button}_mouse_button", window.mouse_x, window.mouse_y) @mouse_over.publish(:"released_#{button}_mouse_button", window.mouse_x, window.mouse_y)
@mouse_over.publish(:"clicked_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over == @mouse_down_on[button] if @mouse_over == @mouse_down_on[button]
@mouse_over.publish(:"clicked_#{button}_mouse_button", window.mouse_x,
window.mouse_y)
end
end end
if @dragging_element if @dragging_element
@@ -184,13 +188,13 @@ module CyberarmEngine
def redirect_holding_mouse_button(button) def redirect_holding_mouse_button(button)
if !@dragging_element && @mouse_down_on[button] && @mouse_down_on[button].draggable?(button) && @mouse_pos.distance(@mouse_down_position[button]) > @min_drag_distance if !@dragging_element && @mouse_down_on[button] && @mouse_down_on[button].draggable?(button) && @mouse_pos.distance(@mouse_down_position[button]) > @min_drag_distance
@dragging_element = @mouse_down_on[button] @dragging_element = @mouse_down_on[button]
@dragging_element.publish(:"begin_drag", window.mouse_x, window.mouse_y, button) @dragging_element.publish(:begin_drag, window.mouse_x, window.mouse_y, button)
end end
if @dragging_element if @dragging_element
@dragging_element.publish(:"drag_update", window.mouse_x, window.mouse_y, button) if @dragging_element @dragging_element.publish(:drag_update, window.mouse_x, window.mouse_y, button) if @dragging_element
else elsif @mouse_over
@mouse_over.publish(:"holding_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over @mouse_over.publish(:"holding_#{button}_mouse_button", window.mouse_x, window.mouse_y)
end end
end end

View File

@@ -1,11 +1,11 @@
module Gosu module Gosu
class Color class Color
def _dump(level) def _dump(_level)
[ [
"%02X" % self.alpha, "%02X" % alpha,
"%02X" % self.red, "%02X" % red,
"%02X" % self.green, "%02X" % green,
"%02X" % self.blue "%02X" % blue
].join ].join
end end
@@ -21,13 +21,14 @@ module CyberarmEngine
@hash = Marshal.load(Marshal.dump(hash)) @hash = Marshal.load(Marshal.dump(hash))
end end
def method_missing(method, *args, &block) def method_missing(method, *args)
if method.to_s.end_with?("=") if method.to_s.end_with?("=")
raise "Did not expect more than 1 argument" if args.size > 1 raise "Did not expect more than 1 argument" if args.size > 1
return @hash[method.to_s.sub("=", "").to_sym] = args.first
@hash[method.to_s.sub("=", "").to_sym] = args.first
elsif args.size == 0 elsif args.size == 0
return @hash[method] @hash[method]
else else
raise ArgumentError, "Did not expect arguments" raise ArgumentError, "Did not expect arguments"

View File

@@ -11,17 +11,21 @@ module CyberarmEngine
def theme_defaults(options) def theme_defaults(options)
raise "Error" unless self.class.ancestors.include?(CyberarmEngine::Element) raise "Error" unless self.class.ancestors.include?(CyberarmEngine::Element)
_theme = THEME _theme = THEME
_theme = deep_merge(_theme, options[:theme]) if options[:theme] _theme = deep_merge(_theme, options[:theme]) if options[:theme]
_theme.delete(:theme) if options[:theme] _theme.delete(:theme) if options[:theme]
hash = {} hash = {}
class_names = self.class.ancestors class_names = self.class.ancestors
class_names = class_names[0..class_names.index(CyberarmEngine::Element)].map! {|c| c.to_s.split("::").last.to_sym}.reverse! class_names = class_names[0..class_names.index(CyberarmEngine::Element)].map! do |c|
c.to_s.split("::").last.to_sym
end.reverse!
class_names.each do |klass| class_names.each do |klass|
next unless data = _theme.dig(klass) next unless data = _theme.dig(klass)
data.each do |key, value|
data.each do |_key, _value|
hash.merge!(data) hash.merge!(data)
end end
end end
@@ -32,7 +36,7 @@ module CyberarmEngine
# Derived from Rails Hash#deep_merge! # Derived from Rails Hash#deep_merge!
# Enables passing partial themes through Element options without issue # Enables passing partial themes through Element options without issue
def deep_merge(original, intergrate, &block) def deep_merge(original, intergrate, &block)
hash = original.merge(intergrate) do |key, this_val, other_val| original.merge(intergrate) do |key, this_val, other_val|
if this_val.is_a?(Hash) && other_val.is_a?(Hash) if this_val.is_a?(Hash) && other_val.is_a?(Hash)
deep_merge(this_val, other_val, &block) deep_merge(this_val, other_val, &block)
elsif block_given? elsif block_given?
@@ -41,8 +45,6 @@ module CyberarmEngine
other_val other_val
end end
end end
return hash
end end
THEME = { THEME = {
@@ -73,8 +75,8 @@ module CyberarmEngine
text_wrap: :none, text_wrap: :none,
hover: { hover: {
color: Gosu::Color.rgb(200,200,200), color: Gosu::Color.rgb(200, 200, 200),
background: ["ffB23E41".to_i(16), "ffFF7C00".to_i(16)] background: ["ffB23E41".to_i(16), "ffFF7C00".to_i(16)]
}, },
active: { active: {

View File

@@ -60,22 +60,15 @@ module CyberarmEngine
Vector.new(0, 0, -1) Vector.new(0, 0, -1)
end end
attr_accessor :x, :y, :z, :weight
def initialize(x = 0, y = 0, z = 0, weight = 0) def initialize(x = 0, y = 0, z = 0, weight = 0)
@x, @y, @z, @weight = x, y, z, weight @x = x
@y = y
@z = z
@weight = weight
end end
def x; @x; end
def x=(n); @x = n; end
def y; @y; end
def y=(n); @y = n; end
def z; @z; end
def z=(n); @z = n; end
def weight; @weight; end
def weight=(n); @weight = n; end
alias w weight alias w weight
alias w= weight= alias w= weight=
@@ -83,14 +76,14 @@ module CyberarmEngine
def ==(other) def ==(other)
if other.is_a?(Numeric) if other.is_a?(Numeric)
@x == other && @x == other &&
@y == other && @y == other &&
@z == other && @z == other &&
@weight == other @weight == other
elsif other.is_a?(Vector) elsif other.is_a?(Vector)
@x == other.x && @x == other.x &&
@y == other.y && @y == other.y &&
@z == other.z && @z == other.z &&
@weight == other.weight @weight == other.weight
else else
other == self other == self
end end
@@ -172,20 +165,20 @@ module CyberarmEngine
def dot(other) def dot(other)
product = 0 product = 0
a = self.to_a a = to_a
b = other.to_a b = other.to_a
3.times do |i| 3.times do |i|
product = product + (a[i] * b[i]) product += (a[i] * b[i])
end end
return product product
end end
# cross product of {Vector} # cross product of {Vector}
# @return [CyberarmEngine::Vector] # @return [CyberarmEngine::Vector]
def cross(other) def cross(other)
a = self.to_a a = to_a
b = other.to_a b = other.to_a
Vector.new( Vector.new(
@@ -198,7 +191,7 @@ module CyberarmEngine
# returns degrees # returns degrees
# @return [Float] # @return [Float]
def angle(other) def angle(other)
Math.acos( self.normalized.dot(other.normalized) ) * 180 / Math::PI Math.acos(normalized.dot(other.normalized)) * 180 / Math::PI
end end
# returns magnitude of Vector, ignoring #weight # returns magnitude of Vector, ignoring #weight
@@ -220,7 +213,6 @@ module CyberarmEngine
self / Vector.new(mag, mag, mag) self / Vector.new(mag, mag, mag)
end end
# returns a direction {Vector} # returns a direction {Vector}
# #
# z is pitch # z is pitch
@@ -265,19 +257,19 @@ module CyberarmEngine
# 2D distance using X and Y # 2D distance using X and Y
# @return [Float] # @return [Float]
def distance(other) def distance(other)
Math.sqrt((@x-other.x)**2 + (@y-other.y)**2) Math.sqrt((@x - other.x)**2 + (@y - other.y)**2)
end end
# 2D distance using X and Z # 2D distance using X and Z
# @return [Float] # @return [Float]
def gl_distance2d(other) def gl_distance2d(other)
Math.sqrt((@x-other.x)**2 + (@z-other.z)**2) Math.sqrt((@x - other.x)**2 + (@z - other.z)**2)
end end
# 3D distance using X, Y, and Z # 3D distance using X, Y, and Z
# @return [Float] # @return [Float]
def distance3d(other) def distance3d(other)
Math.sqrt((@x-other.x)**2 + (@y-other.y)**2 + (@z-other.z)**2) Math.sqrt((@x - other.x)**2 + (@y - other.y)**2 + (@z - other.z)**2)
end end
# Converts {Vector} to Array # Converts {Vector} to Array
@@ -295,7 +287,7 @@ module CyberarmEngine
# Converts {Vector} to Hash # Converts {Vector} to Hash
# @return [Hash] # @return [Hash]
def to_h def to_h
{x: @x, y: @y, z: @z, weight: @weight} { x: @x, y: @y, z: @z, weight: @weight }
end end
end end
end end

View File

@@ -1,4 +1,4 @@
module CyberarmEngine module CyberarmEngine
NAME = "InDev" NAME = "InDev".freeze
VERSION = "0.14.0" VERSION = "0.14.0".freeze
end end

View File

@@ -1,8 +1,8 @@
module CyberarmEngine module CyberarmEngine
class Window < Gosu::Window class Window < Gosu::Window
IMAGES = {} IMAGES = {}
SAMPLES= {} SAMPLES = {}
SONGS = {} SONGS = {}
attr_accessor :show_cursor attr_accessor :show_cursor
attr_writer :exit_on_opengl_error attr_writer :exit_on_opengl_error
@@ -13,15 +13,15 @@ module CyberarmEngine
end end
def self.dt def self.dt
$window.last_frame_time/1000.0 $window.last_frame_time / 1000.0
end end
def initialize(width: 800, height: 600, fullscreen: false, update_interval: 1000.0/60, resizable: false, borderless: false) def initialize(width: 800, height: 600, fullscreen: false, update_interval: 1000.0 / 60, resizable: false, borderless: false)
@show_cursor = false @show_cursor = false
super(width, height, fullscreen: fullscreen, update_interval: update_interval, resizable: resizable, borderless: borderless) super(width, height, fullscreen: fullscreen, update_interval: update_interval, resizable: resizable, borderless: borderless)
$window = self $window = self
@last_frame_time = Gosu.milliseconds-1 @last_frame_time = Gosu.milliseconds - 1
@current_frame_time = Gosu.milliseconds @current_frame_time = Gosu.milliseconds
self.caption = "CyberarmEngine #{CyberarmEngine::VERSION} #{Gosu.language}" self.caption = "CyberarmEngine #{CyberarmEngine::VERSION} #{Gosu.language}"
@@ -39,7 +39,7 @@ module CyberarmEngine
Stats.clear Stats.clear
current_state.update if current_state current_state.update if current_state
@last_frame_time = Gosu.milliseconds-@current_frame_time @last_frame_time = Gosu.milliseconds - @current_frame_time
@current_frame_time = Gosu.milliseconds @current_frame_time = Gosu.milliseconds
end end
@@ -48,7 +48,7 @@ module CyberarmEngine
end end
def dt def dt
@last_frame_time/1000.0 @last_frame_time / 1000.0
end end
def aspect_ratio def aspect_ratio
@@ -69,8 +69,8 @@ module CyberarmEngine
current_state.button_up(id) if current_state current_state.button_up(id) if current_state
end end
def push_state(klass, options={}) def push_state(klass, options = {})
options = {setup: true}.merge(options) options = { setup: true }.merge(options)
if klass.instance_of?(klass.class) && defined?(klass.options) if klass.instance_of?(klass.class) && defined?(klass.options)
@states << klass @states << klass
@@ -78,12 +78,12 @@ module CyberarmEngine
else else
@states << klass.new(options) if child_of?(klass, GameState) @states << klass.new(options) if child_of?(klass, GameState)
@states << klass.new if child_of?(klass, Element::Container) @states << klass.new if child_of?(klass, Element::Container)
current_state.setup if current_state.class == klass && options[:setup] current_state.setup if current_state.instance_of?(klass) && options[:setup]
end end
end end
private def child_of?(input, klass) private def child_of?(input, klass)
input.ancestors.detect {|c| c == klass} input.ancestors.detect { |c| c == klass }
end end
def current_state def current_state
@@ -91,10 +91,8 @@ module CyberarmEngine
end end
def previous_state def previous_state
if @states.size > 1 && state = @states[@states.size-2] if @states.size > 1 && state = @states[@states.size - 2]
return state state
else
return nil
end end
end end
@@ -103,10 +101,11 @@ module CyberarmEngine
end end
# Sourced from https://gist.github.com/ippa/662583 # Sourced from https://gist.github.com/ippa/662583
def draw_circle(cx,cy,r, z = 9999,color = Gosu::Color::GREEN, step = 10) def draw_circle(cx, cy, r, z = 9999, color = Gosu::Color::GREEN, step = 10)
0.step(360, step) do |a1| 0.step(360, step) do |a1|
a2 = a1 + step a2 = a1 + step
draw_line(cx + Gosu.offset_x(a1, r), cy + Gosu.offset_y(a1, r), color, cx + Gosu.offset_x(a2, r), cy + Gosu.offset_y(a2, r), color, z) draw_line(cx + Gosu.offset_x(a1, r), cy + Gosu.offset_y(a1, r), color, cx + Gosu.offset_x(a2, r),
cy + Gosu.offset_y(a2, r), color, z)
end end
end end
end end

View File

@@ -1,4 +1,4 @@
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "cyberarm_engine" require "cyberarm_engine"
require "minitest/autorun" require "minitest/autorun"