40 Commits

Author SHA1 Message Date
0850336e55 Bump version 2020-05-06 22:01:15 -05:00
8b6d7b6eb2 Fixed Slider default value was always 0.5 instead of middle of range 2020-05-06 12:54:52 -05:00
3226eb2bda Sliders work better, fixed CheckBox not passing along options hash, Text width/height now accept a string, changed EditLine text selection color, temporary back to back gui recalculations to fix positioning errors until Container#layout can safely be called after determining element width and height. 2020-05-06 12:08:20 -05:00
a98bb4ec82 Fixed hidden elements were interactable, added comments 2020-05-05 10:48:00 -05:00
da5d740c6e Sync: Renamed Engine to Window to be less confusing, elements are now supposed to throw a changed event if their value is changed 2020-05-04 11:17:11 -05:00
4055f645f3 Implemented Slider (still have some positioning issues to resolve but it works), added files for ListBox, Radio, and EditBox, implemented dragging support in GuiState. 2020-04-10 18:45:55 -05:00
185ab000d6 Updated rake 2020-04-06 09:40:41 -05:00
ed061c8408 Fixed incorrect element positioning when using margin 2020-04-06 09:38:30 -05:00
d8551c7428 Bump version 2020-03-24 10:34:14 -05:00
0017c841dd Added Shader.delete, shaders now clean up after themselves 2020-03-24 10:33:44 -05:00
8cedb40283 Increase shader error message buffer size 2020-03-22 17:28:03 -05:00
93a4e9a2b8 Fixed Vector#== erroring out with doing Vector == SomeObject 2020-01-30 20:08:17 -06:00
a0c0180411 Merge branch 'master' of https://github.com/cyberarm/cyberarm_engine 2020-01-29 18:22:33 -06:00
7f25cd49fe Added ConfigFile for persistent hash storage 2020-01-29 18:22:24 -06:00
7e6a17fe9f Updated README, added some docs for Shader 2020-01-29 11:52:51 -06:00
0ea1e5c2ff Add documentation for Vector 2020-01-29 10:55:51 -06:00
8c34293307 Updated required gosu to 0.15 series, bumped version 2020-01-28 10:53:58 -06:00
8172dafa8c Refactored Shader to duplicate code in shader compilation step, added support for @include preprocessor in shaders 2020-01-28 10:51:36 -06:00
9a3caabc7e Make UI events travel up parent hierarchy until event is either :handled or there is no parent to notify 2020-01-15 21:03:21 -06:00
4b25d724b5 Improved shoes-iness; no longer need to pass clear blocks an element to parent to, todo: replace global var with something else. 2020-01-13 20:13:03 -06:00
a267695b1c dry up DSL's flow/stack methods 2019-12-29 11:30:33 -06:00
d76da62ee1 Update animator pass in from and to objects 2019-12-19 16:54:33 -06:00
3a83e616d3 Added Animator for creating animations with various tweeners, supports Gosu::Color's and numbers 2019-12-19 13:08:29 -06:00
52940d1cfe Fixed element borders not always lining up when using dynamic width/height 2019-12-19 11:17:31 -06:00
e59771e412 Refactored Shader.set_uniform into multiple methods 2019-12-09 11:49:46 -06:00
b382bf6960 Fix passing Vector (as vec3) to Shader 2019-12-09 08:51:31 -06:00
a5ed650970 Got 3D rotations working as expected 2019-12-08 17:16:12 -06:00
935d6e9178 Added Transform.perspective and .view matrix helpers, fixed array index out of bounds for Transform * Vector 2019-12-07 09:59:47 -06:00
cc813c023f Added initial 3D support to Transform 2019-12-05 17:23:47 -06:00
5f359a8313 Fixed wrong method called in DSL.progress, removed unneed line, and made DSL.background use element_parent 2019-11-22 17:20:03 -06:00
c67d6f9d26 Trigger recalculate when Container#clear is called 2019-11-21 14:24:01 -06:00
7f97ec85dd Added Container#clear to remove child elements and optionally eval block, improvements to EditLine to show current selection. 2019-11-21 14:07:42 -06:00
89a54e90a1 Added Vector.xy 2019-10-25 13:57:23 -05:00
48d2924c9b Probably fixed Element dynamic width/height 2019-10-24 10:47:13 -05:00
7cc733dee4 Bumped version 2019-10-15 11:41:53 -05:00
28c4acdedf Added Gosu.draw_circle 2019-10-09 11:35:40 -05:00
57313a33a6 Bump version 2019-10-08 08:54:15 -05:00
5d16500edd Added support for passing flags to get_image, aliased Vector#weight/= to Vector#w/= 2019-10-08 08:53:37 -05:00
51dd3803fa Moved files around, renamed Matrix to Transform 2019-10-07 12:30:48 -05:00
c6beab3e99 Added Matrix, incomplete. 2019-10-06 21:35:10 -05:00
35 changed files with 1417 additions and 370 deletions

View File

@@ -1,8 +1,13 @@
# CyberarmEngine
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/cyberarm_engine`. To experiment with that code, run `bin/console` for an interactive prompt.
Yet Another Game Engine On Top Of Gosu
TODO: Delete this and the text above, and describe your gem
## Features
* [Shoes-like](http://shoesrb.com) GUI support
* OpenGL Shader support (requires [opengl-bindings](https://github.com/vaiorabbit/ruby-opengl) gem)
* Includes classes for handling Vectors, Rays, Bounding Boxes, and Transforms
* GameState system
* Monolithic GameObjects
## Installation
@@ -22,7 +27,32 @@ Or install it yourself as:
## Usage
TODO: Write usage instructions here
```ruby
require "cyberarm_engine"
class Hello < CyberarmEngine::GuiState
def setup
stack do
label "Hello World!"
button "close" do
window.close
end
end
end
end
class Window < CyberarmEngine::Window
def initialize
super
self.show_cursor = true
push_state(Hello)
end
end
Window.new.show
```
## Development

View File

@@ -28,9 +28,10 @@ Gem::Specification.new do |spec|
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "gosu", "~> 0.14.0"
spec.add_dependency "gosu", "~> 0.15.0"
spec.add_dependency "gosu_more_drawables", "~> 0.3"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "minitest", "~> 5.0"
end

View File

@@ -4,23 +4,30 @@ rescue LoadError => e
pp e
require "gosu"
end
require "json"
require "gosu_more_drawables"
require_relative "cyberarm_engine/version"
require_relative "cyberarm_engine/stats"
require_relative "cyberarm_engine/common"
require_relative "cyberarm_engine/game_object"
require_relative "cyberarm_engine/engine"
require_relative "cyberarm_engine/window"
require_relative "cyberarm_engine/lib/bounding_box"
require_relative "cyberarm_engine/lib/vector"
require_relative "cyberarm_engine/lib/ray"
require_relative "cyberarm_engine/lib/shader" if defined?(OpenGL)
require_relative "cyberarm_engine/bounding_box"
require_relative "cyberarm_engine/vector"
require_relative "cyberarm_engine/transform"
require_relative "cyberarm_engine/ray"
require_relative "cyberarm_engine/shader" if defined?(OpenGL)
require_relative "cyberarm_engine/background"
require_relative "cyberarm_engine/animator"
require_relative "cyberarm_engine/objects/text"
require_relative "cyberarm_engine/objects/timer"
require_relative "cyberarm_engine/text"
require_relative "cyberarm_engine/timer"
require_relative "cyberarm_engine/config_file"
require_relative "cyberarm_engine/ui/dsl"
require_relative "cyberarm_engine/ui/theme"
require_relative "cyberarm_engine/ui/event"
@@ -28,17 +35,19 @@ require_relative "cyberarm_engine/ui/style"
require_relative "cyberarm_engine/ui/border_canvas"
require_relative "cyberarm_engine/ui/element"
require_relative "cyberarm_engine/ui/elements/label"
require_relative "cyberarm_engine/ui/elements/list_box"
require_relative "cyberarm_engine/ui/elements/button"
require_relative "cyberarm_engine/ui/elements/toggle_button"
require_relative "cyberarm_engine/ui/elements/edit_line"
require_relative "cyberarm_engine/ui/elements/edit_box"
require_relative "cyberarm_engine/ui/elements/image"
require_relative "cyberarm_engine/ui/elements/container"
require_relative "cyberarm_engine/ui/elements/flow"
require_relative "cyberarm_engine/ui/elements/stack"
require_relative "cyberarm_engine/ui/elements/check_box"
require_relative "cyberarm_engine/ui/elements/radio"
require_relative "cyberarm_engine/ui/elements/progress"
require_relative "cyberarm_engine/ui/dsl"
require_relative "cyberarm_engine/ui/elements/slider"
require_relative "cyberarm_engine/game_state"
require_relative "cyberarm_engine/ui/gui_state"

View File

@@ -0,0 +1,54 @@
module CyberarmEngine
class Animator
DEFAULT_TWEEN = :linear
def initialize(start_time:, duration:, from:, to:, &block)
@start_time, @duration = start_time, duration
@from, @to = from.dup, to.dup
@block = block
end
def update
@block.call(self, @from, @to) if @block
end
def progress
(@start_time.to_f + (Gosu.milliseconds - @start_time)) / (@start_time + @duration.to_f)
end
def complete?
progress >= 1.0
end
def transition(from, to, tween = DEFAULT_TWEEN)
from + (to - from) * send("tween_#{tween}", progress)
end
def color_transition(from, to, tween = DEFAULT_TWEEN)
r = transition(from.red, to.red)
g = transition(from.green, to.green)
b = transition(from.blue, to.blue)
a = transition(from.alpha, to.alpha)
Gosu::Color.rgba(r, g, b, a)
end
def color_hsv_transition(from, to, tween = DEFAULT_TWEEN)
hue = transition(from.hue, to.hue, tween)
saturation = transition(from.saturation, to.saturation, tween)
value = transition(from.value, to.value, tween)
alpha = transition(from.alpha, to.alpha, tween)
Gosu::Color.from_ahsv(alpha, hue, saturation, value)
end
# NOTE: Use this for future reference? https://github.com/danro/easing-js/blob/master/easing.js
def tween_linear(t)
t
end
def tween_sine(t)
Math.sin(t) * t
end
end
end

View File

@@ -54,7 +54,7 @@ module CyberarmEngine
return Gosu::Color.rgba(color.red, color.green, color.blue, alpha)
end
def get_asset(path, hash, klass)
def get_asset(path, hash, klass, retro = false, tileable = false)
asset = nil
hash.detect do |_asset, instance|
if _asset == path
@@ -64,7 +64,12 @@ module CyberarmEngine
end
unless asset
instance = klass.new(path)
instance = nil
if klass == Gosu::Image
instance = klass.new(path, retro: retro, tileable: tileable)
else
instance = klass.new(path)
end
hash[path] = instance
asset = instance
end
@@ -72,16 +77,16 @@ module CyberarmEngine
return asset
end
def get_image(path)
get_asset(path, Engine::IMAGES, Gosu::Image)
def get_image(path, retro: false, tileable: false)
get_asset(path, Window::IMAGES, Gosu::Image, retro, tileable)
end
def get_sample(path)
get_asset(path, Engine::SAMPLES, Gosu::Sample)
get_asset(path, Window::SAMPLES, Gosu::Sample)
end
def get_song(path)
get_asset(path, Engine::SONGS, Gosu::Song)
get_asset(path, Window::SONGS, Gosu::Song)
end
def window

View File

@@ -0,0 +1,46 @@
module CyberarmEngine
class ConfigFile
def initialize(file:)
@file = file
if File.exist?(@file)
deserialize
else
@data = {}
end
end
def []= *keys, value
last_key = keys.last
if keys.size == 1
hash = @data
else
keys.pop
hash = @data[keys.shift] ||= {}
keys.each do |key|
hash[key] ||= {}
end
end
hash[last_key] = value
end
def get(*keys)
@data.dig(*keys)
end
def serialize
JSON.dump(@data)
end
def deserialize
@data = JSON.parse(File.read(@file), symbolize_names: true)
end
def save!
File.open(@file, "w") { |f| f.write(serialize) }
end
end
end

View File

@@ -3,7 +3,7 @@ module CyberarmEngine
include Common
attr_accessor :options, :global_pause
attr_reader :game_objects, :containers
attr_reader :game_objects
def initialize(options={})
@options = options

View File

@@ -1,205 +0,0 @@
module CyberarmEngine
# Ref: https://github.com/vaiorabbit/ruby-opengl/blob/master/sample/OrangeBook/brick.rb
class Shader
include OpenGL
@@shaders = {}
def self.add(name, instance)
@@shaders[name] = instance
end
def self.use(name, &block)
shader = @@shaders.dig(name)
if shader
shader.use(&block)
else
raise ArgumentError, "Shader '#{name}' not found!"
end
end
def self.available?(name)
@@shaders.dig(name).is_a?(Shader)
end
def self.get(name)
@@shaders.dig(name)
end
def self.active_shader
@active_shader
end
def self.active_shader=(instance)
@active_shader = instance
end
def self.stop
shader = Shader.active_shader
if shader
shader.stop
else
raise ArgumentError, "No active shader to stop!"
end
end
def self.attribute_location(variable)
raise RuntimeError, "No active shader!" unless Shader.active_shader
Shader.active_shader.attribute_location(variable)
end
def self.set_uniform(variable, value)
raise RuntimeError, "No active shader!" unless Shader.active_shader
Shader.active_shader.set_uniform(variable, value)
end
attr_reader :name, :program
def initialize(name:, vertex: "shaders/default.vert", fragment:)
@name = name
@vertex_file = vertex
@fragment_file = fragment
@compiled = false
@program = nil
@error_buffer_size = 1024
@variable_missing = {}
raise ArgumentError, "Shader files not found: #{@vertex_file} or #{@fragment_file}" unless shader_files_exist?
create_shaders
compile_shaders
# Only add shader if it successfully compiles
if @compiled
Shader.add(@name, self)
else
puts "FAILED to compile shader: #{@name}", ""
end
end
def shader_files_exist?
File.exist?(@vertex_file) && File.exist?(@fragment_file)
end
def create_shaders
@vertex = glCreateShader(GL_VERTEX_SHADER)
@fragment = glCreateShader(GL_FRAGMENT_SHADER)
source = [File.read(@vertex_file)].pack('p')
size = [File.size(@vertex_file)].pack('I')
glShaderSource(@vertex, 1, source, size)
source = [File.read(@fragment_file)].pack('p')
size = [File.size(@fragment_file)].pack('I')
glShaderSource(@fragment, 1, source, size)
end
def compile_shaders
return unless shader_files_exist?
glCompileShader(@vertex)
buffer = ' '
glGetShaderiv(@vertex, GL_COMPILE_STATUS, buffer)
compiled = buffer.unpack('L')[0]
if compiled == 0
log = ' ' * @error_buffer_size
glGetShaderInfoLog(@vertex, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\""
puts " Vectex Shader InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
puts " Shader Compiled status: #{compiled}"
puts " NOTE: assignment of uniforms in shaders is illegal!"
puts
return
end
glCompileShader(@fragment)
buffer = ' '
glGetShaderiv(@fragment, GL_COMPILE_STATUS, buffer)
compiled = buffer.unpack('L')[0]
if compiled == 0
log = ' ' * @error_buffer_size
glGetShaderInfoLog(@fragment, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\""
puts " Fragment Shader InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
puts " Shader Compiled status: #{compiled}"
puts " NOTE: assignment of uniforms in shader is illegal!"
puts
return
end
@program = glCreateProgram
glAttachShader(@program, @vertex)
glAttachShader(@program, @fragment)
glLinkProgram(@program)
buffer = ' '
glGetProgramiv(@program, GL_LINK_STATUS, buffer)
linked = buffer.unpack('L')[0]
if linked == 0
log = ' ' * @error_buffer_size
glGetProgramInfoLog(@program, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\""
puts " Program InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
end
@compiled = linked == 0 ? false : true
end
# Returns the location of a uniform variable
def variable(variable)
loc = glGetUniformLocation(@program, variable)
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]
@variable_missing[variable] = true
end
return loc
end
def use(&block)
return unless compiled?
raise "Another shader is already in use! #{Shader.active_shader.name.inspect}" if Shader.active_shader
Shader.active_shader=self
glUseProgram(@program)
if block
block.call(self)
stop
end
end
def stop
Shader.active_shader = nil if Shader.active_shader == self
glUseProgram(0)
end
def compiled?
@compiled
end
def attribute_location(variable)
glGetUniformLocation(@program, variable)
end
def set_uniform(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
case value.class.to_s.downcase.to_sym
when :integer
glUniform1i(attr_loc, value)
when :float
glUniform1f(attr_loc, value)
when :string
when :array
else
raise NotImplementedError, "Shader support for #{value.class.inspect} not implemented."
end
Window.handle_gl_error
end
end
end

View File

@@ -0,0 +1,398 @@
module CyberarmEngine
# Ref: https://github.com/vaiorabbit/ruby-opengl/blob/master/sample/OrangeBook/brick.rb
class Shader
include OpenGL
@@shaders = {} # Cache for {Shader} instances
PREPROCESSOR_CHARACTER = "@".freeze # magic character for preprocessor phase of {Shader} compilation
# add instance of {Shader} to cache
#
# @param name [String]
# @param instance [Shader]
def self.add(name, instance)
@@shaders[name] = instance
end
# removes {Shader} from cache and cleans up
#
# @param name [String]
def self.delete(name)
shader = @@shaders.dig(name)
if shader
@@shaders.delete(name)
if shader.compiled?
glDeleteProgram(shader.program)
end
end
end
##
# runs _block_ using {Shader} with _name_
#
# @example
#
# CyberarmEngine::Shader.use("blur") do |shader|
# shader.uniform_float("radius", 20.0)
# # OpenGL Code that uses shader
# end
#
# @param name [String] name of {Shader} to use
# @return [void]
def self.use(name, &block)
shader = @@shaders.dig(name)
if shader
shader.use(&block)
else
raise ArgumentError, "Shader '#{name}' not found!"
end
end
# returns whether {Shader} with _name_ is in cache
#
# @param name [String]
# @return [Boolean]
def self.available?(name)
@@shaders.dig(name).is_a?(Shader)
end
# returns instance of {Shader}, if it exists
#
# @param name [String]
# @return [Shader?]
def self.get(name)
@@shaders.dig(name)
end
# returns currently active {Shader}, if one is active
#
# @return [Shader?]
def self.active_shader
@active_shader
end
# sets currently active {Shader}
#
# @param instance [Shader] instance of {Shader} to set as active
def self.active_shader=(instance)
@active_shader = instance
end
# stops using currently active {Shader}
def self.stop
shader = Shader.active_shader
if shader
shader.stop
else
raise ArgumentError, "No active shader to stop!"
end
end
# returns location of OpenGL Shader uniform
#
# @param variable [String]
def self.attribute_location(variable)
raise RuntimeError, "No active shader!" unless Shader.active_shader
Shader.active_shader.attribute_location(variable)
end
# sets _variable_ to _value_
#
# @param variable [String]
# @param value
def self.set_uniform(variable, value)
raise RuntimeError, "No active shader!" unless Shader.active_shader
Shader.active_shader.set_uniform(variable, value)
end
attr_reader :name, :program
def initialize(name:, includes_dir: nil, vertex: "shaders/default.vert", fragment:)
raise "Shader name can not be blank" if name.length == 0
@name = name
@includes_dir = includes_dir
@compiled = false
@program = nil
@error_buffer_size = 1024 * 8
@variable_missing = {}
@data = {shaders: {}}
unless shader_files_exist?(vertex: vertex, fragment: fragment)
raise ArgumentError, "Shader files not found: #{vertex} or #{fragment}"
end
create_shader(type: :vertex, source: File.read(vertex))
create_shader(type: :fragment, source: File.read(fragment))
compile_shader(type: :vertex)
compile_shader(type: :fragment)
link_shaders
@data[:shaders].each { |key, id| glDeleteShader(id) }
# Only add shader if it successfully compiles
if @compiled
puts "compiled!"
puts "Compiled shader: #{@name}"
Shader.add(@name, self)
else
glDeleteProgram(@program)
warn "FAILED to compile shader: #{@name}", ""
end
end
# whether vertex and fragment files exist on disk
#
# @return [Boolean]
def shader_files_exist?(vertex:, fragment:)
File.exist?(vertex) && File.exist?(fragment)
end
# creates an OpenGL Shader of _type_ using _source_
#
# @param type [Symbol] valid values are: :vertex, :fragment
# @param source [String] source code for shader
def create_shader(type:, source:)
_shader = nil
case type
when :vertex
_shader = glCreateShader(GL_VERTEX_SHADER)
when :fragment
_shader = glCreateShader(GL_FRAGMENT_SHADER)
else
raise ArgumentError, "Unsupported shader type: #{type.inspect}"
end
processed_source = preprocess_source(source: source)
_source = [processed_source].pack("p")
_size = [processed_source.length].pack("I")
glShaderSource(_shader, 1, _source, _size)
@data[:shaders][type] =_shader
end
# evaluates shader preprocessors
#
# currently supported preprocessors:
#
# @include "file/path" "another/file/path" # => Replace line with contents of file; Shader includes_dir must be specified in constructor
#
# @example
# # Example Vertex Shader #
# # #version 330 core
# # @include "material_struct"
# # void main() {
# # gl_Position = vec4(1, 1, 1, 1);
# # }
#
# Shader.new(name: "model_renderer", includes_dir: "path/to/includes", vertex: "path/to/vertex_shader.glsl")
#
# @param source shader source code
def preprocess_source(source:)
lines = source.lines
lines.each_with_index do |line, i|
if line.start_with?(PREPROCESSOR_CHARACTER)
preprocessor = line.strip.split(" ")
lines.delete(line)
case preprocessor.first
when "@include"
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|
source = File.read("#{@includes_dir}/#{file}.glsl")
lines.insert(i, source)
end
else
warn "Unsupported preprocessor #{preprocessor.first} for #{@name}"
end
end
end
lines.join
end
# compile OpenGL Shader of _type_
#
# @return [Boolean] whether compilation succeeded
def compile_shader(type:)
_compiled = false
_shader = @data[:shaders][type]
raise ArgumentError, "No shader for #{type.inspect}" unless _shader
glCompileShader(_shader)
buffer = ' '
glGetShaderiv(_shader, GL_COMPILE_STATUS, buffer)
compiled = buffer.unpack('L')[0]
if compiled == 0
log = ' ' * @error_buffer_size
glGetShaderInfoLog(_shader, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\""
puts " #{type.to_s.capitalize} Shader InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
puts " Shader Compiled status: #{compiled}"
puts " NOTE: assignment of uniforms in shaders is illegal!"
puts
else
_compiled = true
end
return _compiled
end
# link compiled OpenGL Shaders in to a OpenGL Program
#
# @note linking must succeed or shader cannot be used
#
# @return [Boolean] whether linking succeeded
def link_shaders
@program = glCreateProgram
@data[:shaders].values.each do |_shader|
glAttachShader(@program, _shader)
end
glLinkProgram(@program)
buffer = ' '
glGetProgramiv(@program, GL_LINK_STATUS, buffer)
linked = buffer.unpack('L')[0]
if linked == 0
log = ' ' * @error_buffer_size
glGetProgramInfoLog(@program, @error_buffer_size, nil, log)
puts "Shader Error: Program \"#{@name}\""
puts " Program InfoLog:", " #{log.strip.split("\n").join("\n ")}\n\n"
end
@compiled = linked == 0 ? false : true
end
# Returns the location of a uniform _variable_
#
# @param variable [String]
# @return [Integer] location of uniform
def variable(variable)
loc = glGetUniformLocation(@program, variable)
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]
@variable_missing[variable] = true
end
return loc
end
# @see Shader.use Shader.use
def use(&block)
return unless compiled?
raise "Another shader is already in use! #{Shader.active_shader.name.inspect}" if Shader.active_shader
Shader.active_shader=self
glUseProgram(@program)
if block
block.call(self)
stop
end
end
# stop using shader, if shader is active
def stop
Shader.active_shader = nil if Shader.active_shader == self
glUseProgram(0)
end
# @return [Boolean] whether {Shader} successfully compiled
def compiled?
@compiled
end
# returns location of a uniform _variable_
#
# @note Use {#variable} for friendly error handling
# @see #variable Shader#variable
#
# @param variable [String]
# @return [Integer]
def attribute_location(variable)
glGetUniformLocation(@program, variable)
end
# send {Transform} to {Shader}
#
# @param variable [String]
# @param value [Transform]
# @param location [Integer]
# @return [void]
def uniform_transform(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
glUniformMatrix4fv(attr_loc, 1, GL_FALSE, value.to_gl.pack("F16"))
end
# send Boolean to {Shader}
#
# @param variable [String]
# @param value [Boolean]
# @param location [Integer]
# @return [void]
def uniform_boolean(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
glUniform1i(attr_loc, value ? 1 : 0)
end
# send Integer to {Shader}
# @param variable [String]
# @param value [Integer]
# @param location [Integer]
# @return [void]
def uniform_integer(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
glUniform1i(attr_loc, value)
end
# send Float to {Shader}
#
# @param variable [String]
# @param value [Float]
# @param location [Integer]
# @return [void]
def uniform_float(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
glUniform1f(attr_loc, value)
end
# send {Vector} (x, y, z) to {Shader}
#
# @param variable [String]
# @param value [Vector]
# @param location [Integer]
# @return [void]
def uniform_vec3(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
glUniform3f(attr_loc, *value.to_a[0..2])
end
# send {Vector} to {Shader}
#
# @param variable [String]
# @param value [Vector]
# @param location [Integer]
# @return [void]
def uniform_vec4(variable, value, location = nil)
attr_loc = location ? location : attribute_location(variable)
glUniform4f(attr_loc, *value.to_a)
end
end
end

View File

@@ -0,0 +1,21 @@
module CyberarmEngine
class Stats
@@hash = {
gui_recalculations_last_frame: 0
}
def self.get(key)
@@hash.dig(key)
end
def self.increment(key, n)
@@hash[key] += n
end
def self.clear
@@hash.each do |key, value|
@@hash[key] = 0
end
end
end
end

View File

@@ -9,7 +9,7 @@ module CyberarmEngine
@text = text.to_s || ""
@options = options
@size = options[:size] || 18
@font = options[:font] || "sans-serif"#Gosu.default_font_name
@font = options[:font] || Gosu.default_font_name
@x = options[:x] || 0
@y = options[:y] || 0
@z = options[:z] || 1025
@@ -98,12 +98,12 @@ module CyberarmEngine
@shadow_color = n
end
def width
textobject.text_width(@text)
def width(text = @text)
textobject.text_width(text)
end
def height
@text.lines.count > 0 ? (@text.lines.count) * textobject.height : @textobject.height
def height(text = @text)
text.lines.count > 0 ? (text.lines.count) * textobject.height : @textobject.height
end
def draw

View File

@@ -0,0 +1,273 @@
module CyberarmEngine
# Basic 4x4 matrix operations
class Transform
attr_reader :elements
def initialize(matrix)
@elements = matrix
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)}
end
def self.identity
Transform.new(
[
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
]
)
end
### 2D Operations meant for interacting with Gosu ###
# 2d rotate operation, replicates Gosu's Gosu.rotate function
def self.rotate(angle, rotate_around = nil)
double c = Math.cos(angle).degrees_to_radians
double s = Math.sin(angle).degrees_to_radians
matrix = [
+c, +s, 0, 0,
-s, +c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
]
rotate_matrix = Transform.new(matrix, rows: 4, columns: 4)
if rotate_around && (rotate_around.x != 0.0 || rotate_around.y != 0.0)
negative_rotate_around = Vector.new(-rotate_around.x, -rotate_around.y, -rotate_around.z)
rotate_matrix = concat(
concat(translate(negative_rotate_around), rotate_matrix),
translate(rotate_around)
)
end
return rotate_matrix
end
# 2d translate operation, replicates Gosu's Gosu.translate function
def self.translate(vector)
x, y, z = vector.to_a[0..2]
matrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x, y, z, 1,
]
Transform.new(matrix)
end
# 2d scale operation, replicates Gosu's Gosu.rotate function
def self.scale(vector, center_around = nil)
scale_x, scale_y, scale_z = vector.to_a[0..2]
matrix = [
scale_x, 0, 0, 0,
0, scale_y, 0, 0,
0, 0, scale_z, 0,
0, 0, 0, 1,
]
scale_matrix = Transform.new(matrix)
if center_around && (center_around.x != 0.0 || center_around.y != 0.0)
negative_center_around = Vector.new(-center_around.x, -center_around.y, -center_around.z)
scale_matrix = concat(
concat(translate(negative_center_around), scale_matrix),
translate(center_around)
)
end
return scale_matrix
end
def self.concat(left, right)
matrix = Array.new(left.elements.size)
rows = 4
matrix.size.times do |i|
matrix[i] = 0
rows.times do |j|
matrix[i] += left.elements[i / rows * rows + j] * right.elements[i % rows + j * rows]
end
end
Transform.new(matrix)
end
#### 3D Operations meant for OpenGL ###
def self.translate_3d(vector)
x, y, z = vector.to_a[0..2]
matrix = [
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1,
]
Transform.new(matrix)
end
def self.rotate_3d(vector, order = "zyx")
x, y, z = vector.to_a[0..2].map { |axis| axis * Math::PI / 180.0 }
rotation_x = Transform.new(
[
1, 0, 0, 0,
0, Math.cos(x), -Math.sin(x), 0,
0, Math.sin(x), Math.cos(x), 0,
0, 0, 0, 1
]
)
rotation_y = Transform.new(
[
Math.cos(y), 0, Math.sin(y), 0,
0, 1, 0, 0,
-Math.sin(y), 0, Math.cos(y), 0,
0, 0, 0, 1
]
)
rotation_z = Transform.new(
[
Math.cos(z), -Math.sin(z), 0, 0,
Math.sin(z), Math.cos(z), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
]
)
rotation_z * rotation_y * rotation_x
end
# Implements glRotatef
# https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glRotate.xml
def self.rotate_gl(angle, axis)
radians = angle * Math::PI / 180.0
s = Math.sin(radians)
c = Math.cos(radians)
axis = axis.normalized
x, y, z = axis.to_a[0..2]
n = (1.0 - c)
Transform.new(
[
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,
x * z * n - y * s, y * z * n + x * s, z * z * n + c, 0,
0, 0, 0, 1.0
]
)
end
def self.scale_3d(vector)
x, y, z = vector.to_a[0..2]
Transform.new(
[
x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
0, 0, 0, 1
]
)
end
def self.perspective(fov_y, aspect_ratio, near, far)
f = 1.0 / Math.tan(fov_y.degrees_to_radians / 2.0) # cotangent
zn = (far + near.to_f) / (near - far.to_f)
zf = (2.0 * far * near.to_f) / (near - far.to_f)
Transform.new(
[
f / aspect_ratio, 0.0, 0.0, 0.0,
0.0, f, 0.0, 0.0,
0.0, 0.0, zn, zf,
0.0, 0.0, -1.0, 0.0
]
)
end
def self.view(eye, orientation)
# https://www.3dgep.com/understanding-the-view-matrix/#The_View_Matrix
cosPitch = Math.cos(orientation.z * Math::PI / 180.0)
sinPitch = Math.sin(orientation.z * Math::PI / 180.0)
cosYaw = Math.cos(orientation.y * Math::PI / 180.0)
sinYaw = Math.sin(orientation.y * Math::PI / 180.0)
x_axis = Vector.new(cosYaw, 0, -sinYaw)
y_axis = Vector.new(sinYaw * sinPitch, cosPitch, cosYaw * sinPitch)
z_axis = Vector.new(sinYaw * cosPitch, -sinPitch, cosPitch * cosYaw)
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.dot(eye), -y_axis.dot(eye), -z_axis.dot(eye), 1
]
)
end
def *(other)
case other
when CyberarmEngine::Vector
matrix = @elements.clone
list = other.to_a
@elements.each_with_index do |e, i|
matrix[i] = e + list[i % 4]
end
Transform.new(matrix)
when CyberarmEngine::Transform
return multiply_matrices(other)
else
p other.class
raise TypeError, "Expected CyberarmEngine::Vector or CyberarmEngine::Transform got #{other.class}"
end
end
def get(x, y)
width = 4
# puts "Transform|#{self.object_id} -> #{@elements[width * y + x].inspect} (index: #{width * y + x})"
@elements[width * y + x]
end
def multiply_matrices(other)
matrix = Array.new(16, 0)
4.times do |x|
4.times do |y|
4.times do |k|
matrix[4 * y + x] += get(x, k) * other.get(k, y)
end
end
end
return Transform.new(matrix)
end
# arranges Matrix in column major form
def to_gl
e = @elements
[
e[0], e[4], e[8], e[12],
e[1], e[5], e[9], e[13],
e[2], e[6], e[10], e[14],
e[3], e[7], e[11], e[15]
]
end
end
end

View File

@@ -1,102 +1,106 @@
module CyberarmEngine
module DSL
def flow(options = {}, &block)
options[:parent] = @containers.last
options[:theme] = current_theme
_container = Element::Flow.new(options, block)
@containers << _container
_container.build
_container.parent.add(_container)
@containers.pop
return _container
container(CyberarmEngine::Element::Flow, options, &block)
end
def stack(options = {}, &block)
options[:parent] = @containers.last
options[:theme] = current_theme
_container = Element::Stack.new(options, block)
@containers << _container
_container.build
_container.parent.add(_container)
@containers.pop
return _container
container(CyberarmEngine::Element::Stack, options, &block)
end
def label(text, options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::Label.new(text, options, block)
@containers.last.add(_element)
return _element
add_element( Element::Label.new(text, options, block) )
end
def button(text, options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::Button.new(text, options, block) { if block.is_a?(Proc); block.call; end }
@containers.last.add(_element)
return _element
add_element( Element::Button.new(text, options, block) { if block.is_a?(Proc); block.call; end } )
end
def edit_line(text, options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::EditLine.new(text, options, block)
@containers.last.add(_element)
return _element
add_element( Element::EditLine.new(text, options, block) )
end
def toggle_button(options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::ToggleButton.new(options, block)
@containers.last.add(_element)
return _element
add_element( Element::ToggleButton.new(options, block) )
end
def check_box(text, options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::CheckBox.new(text, options, block)
@containers.last.add(_element)
return _element
add_element( Element::CheckBox.new(text, options, block) )
end
def image(path, options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::Image.new(path, options, block)
@containers.last.add(_element)
return _element
add_element( Element::Image.new(path, options, block) )
end
def progress(options = {}, &block)
options[:parent] = @containers.last
options[:parent] = element_parent
options[:theme] = current_theme
_element = Element::Progress.new(options, block)
@containers.last.add(_element)
return _element
add_element( Element::Progress.new(options, block) )
end
def slider(options = {}, &block)
options[:parent] = element_parent
options[:theme] = current_theme
add_element( Element::Slider.new(options, block) )
end
def background(color = Gosu::Color::NONE)
@containers.last.style.background = color
element_parent.style.background = color
end
def theme(theme)
@containers.last.options[:theme] = theme
element_parent.options[:theme] = theme
end
def current_theme
@containers.last.options[:theme]
element_parent.options[:theme]
end
private def add_element(element)
element_parent.add(element)
return element
end
private def element_parent
$__current_container__
end
private def container(klass, options = {}, &block)
options[:parent] = element_parent
options[:theme] = current_theme
_container = klass.new(options, block)
old_parent = element_parent
$__current_container__ = _container
_container.build
_container.parent.add(_container)
$__current_container__ = old_parent
return _container
end
end
end

View File

@@ -4,7 +4,7 @@ module CyberarmEngine
include Event
include Common
attr_accessor :x, :y, :z, :enabled
attr_accessor :x, :y, :z, :enabled, :tip
attr_reader :parent, :options, :style, :event_handler, :background_canvas, :border_canvas
def initialize(options = {}, block = nil)
@@ -16,6 +16,7 @@ module CyberarmEngine
@focus = false
@enabled = true
@visible = true
@tip = @options[:tip] ? @options[:tip] : ""
@style = Style.new(options)
@@ -110,6 +111,8 @@ module CyberarmEngine
event(:leave)
event(:blur)
event(:changed)
end
def enabled?
@@ -152,6 +155,10 @@ module CyberarmEngine
def button_up(id)
end
def draggable?(button)
false
end
def render
end
@@ -168,6 +175,14 @@ module CyberarmEngine
end
end
def content_width
@width
end
def noncontent_width
(inner_width + outer_width) - width
end
def outer_width
@style.margin_left + width + @style.margin_right
end
@@ -184,6 +199,14 @@ module CyberarmEngine
end
end
def content_height
@height
end
def noncontent_height
(inner_height + outer_height) - height
end
def outer_height
@style.margin_top + height + @style.margin_bottom
end
@@ -196,7 +219,7 @@ module CyberarmEngine
raise "dimension must be either :width or :height" unless dimension == :width || dimension == :height
if size && size.is_a?(Numeric)
if size.between?(0.0, 1.0)
@parent.send(:"#{dimension}") * size
((@parent.send(:"content_#{dimension}") - self.send(:"noncontent_#{dimension}")) * size).round
else
size
end
@@ -223,6 +246,8 @@ module CyberarmEngine
end
def root
return self if is_root?
unless @root && @root.parent.nil?
@root = parent
@@ -256,5 +281,9 @@ module CyberarmEngine
def value=(value)
raise "#{self.class}#value= was not overridden!"
end
def to_s
"#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} value=#{ value.is_a?(String) ? "\"#{value}\"" : value }"
end
end
end

View File

@@ -2,13 +2,32 @@ module CyberarmEngine
class Element
class CheckBox < Flow
def initialize(text, options, block = nil)
super({}, block = nil)
super(options, block)
options[:toggled] = options[:checked]
@toggle_button = ToggleButton.new(options)
@label = Label.new(text, options)
define_label_singletons
@label.subscribe(:holding_left_mouse_button) do |sender, x, y|
@toggle_button.left_mouse_button(sender, x, y)
end
@label.subscribe(:released_left_mouse_button) do |sender, x, y|
@toggle_button.released_left_mouse_button(sender, x, y)
end
@label.subscribe(:clicked_left_mouse_button) do |sender, x, y|
@toggle_button.clicked_left_mouse_button(sender, x, y)
publish(:changed, @toggle_button.value)
end
@label.subscribe(:enter) do |sender|
@toggle_button.enter(sender)
end
@label.subscribe(:leave) do |sender|
@toggle_button.leave(sender)
end
add(@toggle_button)
add(@label)
@@ -24,35 +43,8 @@ module CyberarmEngine
end
def value=(bool)
@toggle_button.vlaue = bool
end
def define_label_singletons
@label.define_singleton_method(:_toggle_button) do |button|
@_toggle_button = button
end
@label._toggle_button(@toggle_button)
@label.define_singleton_method(:holding_left_mouse_button) do |sender, x, y|
@_toggle_button.left_mouse_button(sender, x, y)
end
@label.define_singleton_method(:released_left_mouse_button) do |sender, x, y|
@_toggle_button.released_left_mouse_button(sender, x, y)
end
@label.define_singleton_method(:clicked_left_mouse_button) do |sender, x, y|
@_toggle_button.clicked_left_mouse_button(sender, x, y)
end
@label.define_singleton_method(:enter) do |sender|
@_toggle_button.enter(sender)
end
@label.define_singleton_method(:leave) do |sender|
@_toggle_button.leave(sender)
end
@toggle_button.value = bool
publish(:changed, @toggle_button.value)
end
end
end

View File

@@ -22,13 +22,26 @@ module CyberarmEngine
def build
@block.call(self) if @block
recalculate
root.gui_state.request_recalculate
end
def add(element)
@children << element
recalculate
root.gui_state.request_recalculate
end
def clear(&block)
@children.clear
old_container = $__current_container__
$__current_container__ = self
block.call(self) if block
$__current_container__ = old_container
root.gui_state.request_recalculate
end
def render
@@ -43,6 +56,8 @@ module CyberarmEngine
def hit_element?(x, y)
@children.reverse_each do |child|
next unless child.visible?
case child
when Container
if element = child.hit_element?(x, y)
@@ -59,6 +74,9 @@ module CyberarmEngine
def recalculate
@current_position = Vector.new(@style.margin_left + @style.padding_left, @style.margin_top + @style.padding_top)
return unless visible?
Stats.increment(:gui_recalculations_last_frame, 1)
stylize
layout
@@ -76,15 +94,16 @@ module CyberarmEngine
@height = _height ? _height : (@children.map {|c| c.y + c.outer_height}.max || 0).round
end
# Move child to parent after positioning
@children.each do |child|
child.x += @x
child.y += @y
child.x += (@x + @style.border_thickness_left) - style.margin_left
child.y += (@y + @style.border_thickness_top) - style.margin_top
child.stylize
child.recalculate
child.reposition # TODO: Implement top,bottom,left,center, and right positioning
Stats.increment(:gui_recalculations_last_frame, 1)
end
update_background
@@ -95,10 +114,12 @@ module CyberarmEngine
end
def max_width
@max_width ? @max_width : window.width - (@parent ? @parent.style.margin_right + @style.margin_right : @style.margin_right)
_width = dimensional_size(@style.width, :width)
_width ? outer_width : window.width - (@parent ? @parent.style.margin_right + @style.margin_right : @style.margin_right)
end
def fits_on_line?(element) # Flow
p [@options[:id], @width] if @options[:id]
@current_position.x + element.outer_width <= max_width &&
@current_position.x + element.outer_width <= window.width
end
@@ -157,6 +178,25 @@ module CyberarmEngine
def value
@children.map {|c| c.class}.join(", ")
end
def to_s
"#{self.class} x=#{x} y=#{y} width=#{width} height=#{height} children=#{@children.size}"
end
def write_tree(indent = "", index = 0)
puts self
indent = indent + " "
@children.each_with_index do |child, i|
print "#{indent}#{i}: "
if child.is_a?(Container)
child.write_tree(indent)
else
puts child
end
end
end
end
end
end
end

View File

@@ -0,0 +1,6 @@
module CyberarmEngine
class Element
class EditBox < Element
end
end
end

View File

@@ -16,16 +16,31 @@ module CyberarmEngine
@text_input = Gosu::TextInput.new
@text_input.text = text
@offset_x = 0
return self
end
def render
Gosu.clip_to(@text.x, @text.y, @style.width, @text.height) do
draw_text
Gosu.draw_rect(caret_position, @text.y, @caret_width, @caret_height, @caret_color, @z + 40) if @focus && @show_caret
Gosu.translate(-@offset_x, 0) do
draw_selection
draw_caret if @focus && @show_caret
draw_text
end
end
end
def draw_caret
Gosu.draw_rect(caret_position, @text.y, @caret_width, @caret_height, @caret_color, @z)
end
def draw_selection
selection_width = caret_position - selection_start_position
Gosu.draw_rect(selection_start_position, @text.y, selection_width, @text.height, default(:selection_color), @z)
end
def update
if @type == :password
@text.text = default(:password_character) * @text_input.text.length
@@ -38,6 +53,67 @@ module CyberarmEngine
@show_caret = !@show_caret
end
keep_caret_visible
end
def move_caret_to_mouse(mouse_x)
1.upto(@text.text.length) do |i|
if mouse_x < @text.x + @text.textobject.text_width(@text.text[0...i])
@text_input.caret_pos = @text_input.selection_start = i - 1;
return
end
end
@text_input.caret_pos = @text_input.selection_start = @text_input.text.length
end
def keep_caret_visible
caret_pos = (caret_position - @text.x) + @caret_width
@last_text ||= "/\\"
@last_pos ||= -1
puts "caret pos: #{caret_pos}, width: #{@width}, offset: #{@offset_x}" if (@last_text != @text.text) || (@last_pos != caret_pos)
@last_text = @text.text
@last_pos = caret_pos
if caret_pos.between?(@offset_x, @width + @offset_x)
# Do nothing
elsif caret_pos < @offset_x
if caret_pos > @width
@offset_x = caret_pos + @width
else
@offset_x = 0
end
elsif caret_pos > @width
@offset_x = caret_pos - @width
puts "triggered"
else
# Reset to Zero
@offset_x = 0
end
end
def caret_position
text_input_position_for(:caret_pos)
end
def selection_start_position
text_input_position_for(:selection_start)
end
def text_input_position_for(method)
if @type == :password
@text.x + @text.width(default(:password_character) * @text_input.text[0..@text_input.send(method)].length)
else
@text.x + @text.width(@text_input.text[0..@text_input.send(method)])
end
end
def left_mouse_button(sender, x, y)
@@ -47,6 +123,8 @@ module CyberarmEngine
@caret_last_interval = Gosu.milliseconds
@show_caret = true
move_caret_to_mouse(x)
return :handled
end
@@ -79,15 +157,6 @@ module CyberarmEngine
return :handled
end
# TODO: Fix caret rendering in wrong position unless caret_pos is at end of text
def caret_position
if @type == :password
@text.x + @text.textobject.text_width(default(:password_character) * @text_input.text[0..@text_input.caret_pos-1].length)
else
@text.x + @text.textobject.text_width(@text_input.text[0..@text_input.caret_pos-1])
end
end
def recalculate
super

View File

@@ -1,8 +1,6 @@
module CyberarmEngine
class Element
class Flow < Container
include Common
def layout
@children.each do |child|
if fits_on_line?(child)

View File

@@ -14,7 +14,7 @@ module CyberarmEngine
def clicked_left_mouse_button(sender, x, y)
@block.call(self) if @block
return :handled
# return :handled
end
def recalculate
@@ -44,6 +44,8 @@ module CyberarmEngine
recalculate
root.gui_state.request_recalculate if old_width != width || old_height != height
publish(:changed, self.value)
end
end
end

View File

@@ -0,0 +1,6 @@
module CyberarmEngine
class Element
class ListBox < Element
end
end
end

View File

@@ -43,6 +43,7 @@ module CyberarmEngine
@fraction = decimal.clamp(0.0, 1.0)
update_background
publish(:changed, @fraction)
return @fraction
end
end

View File

@@ -0,0 +1,6 @@
module CyberarmEngine
class Element
class Radio < Element
end
end
end

View File

@@ -0,0 +1,107 @@
module CyberarmEngine
class Element
class Slider < Container
class Handle < Button
def initialize(*args)
super(*args)
event(:begin_drag)
event(:drag_update)
event(:end_drag)
subscribe :begin_drag do |sender, x, y, button|
@drag_start_pos = Vector.new(x, y)
:handled
end
subscribe :drag_update do |sender, x, y, button|
@parent.handle_dragged_to(x, y)
:handled
end
subscribe :end_drag do
@drag_start_pos = nil
:handled
end
end
def draggable?(button)
button == :left
end
end
attr_reader :range, :step_size
def initialize(options = {}, block = nil)
super(options, block)
@range = @options[:range] ? @options[:range] : 0.0..1.0
@step_size = @options[:step] ? @options[:step] : 0.1
@value = @options[:value] ? @options[:value] : (@range.first + @range.last) / 2
@handle = Handle.new("", parent: self, width: 8, height: 1.0) { close }
self.add(@handle)
end
def recalculate
_width = dimensional_size(@style.width, :width)
_height= dimensional_size(@style.height,:height)
@width = _width
@height = _height
position_handle
@handle.recalculate
@handle.update_background
update_background
end
def position_handle
@handle.x = @x + @style.padding_left + @style.border_thickness_left +
((content_width - @handle.outer_width) * (@value - @range.min) / (@range.max - @range.min).to_f)
@handle.y = @y + @style.border_thickness_top + @style.padding_top
end
def draw
super
@handle.draw
end
def update
super
@tip = value.to_s
@handle.tip = @tip
end
def holding_left_mouse_button(sender, x, y)
handle_dragged_to(x, y)
:handled
end
def handle_dragged_to(x, y)
@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
end
def value
@value
end
def value=(n)
@value = n
position_handle
@handle.recalculate
publish(:changed, @value)
end
end
end
end

View File

@@ -1,8 +1,6 @@
module CyberarmEngine
class Element
class Stack < Container
include Common
def layout
@children.each do |child|
move_to_next_line(child)

View File

@@ -5,8 +5,8 @@ module CyberarmEngine
def initialize(options, block = nil)
super(options[:checkmark], options, block)
@toggled = options[:toggled] || false
if @toggled
@value = options[:checked] || false
if @value
@text.text = @options[:checkmark]
else
@text.text = ""
@@ -15,41 +15,42 @@ module CyberarmEngine
return self
end
def toggled=(boolean)
@toggled = !boolean
toggle
end
def clicked_left_mouse_button(sender, x, y)
toggle
self.value = !@value
@block.call(self) if @block
return :handled
end
def toggle
if @toggled
@toggled = false
@text.text = ""
else
@toggled = true
@text.text = @options[:checkmark]
end
end
def recalculate
super
_width = dimensional_size(@style.width, :width)
_height= dimensional_size(@style.height,:height)
@width = _width ? _width : @text.textobject.text_width(@options[:checkmark])
@height = _height ? _height : @text.height
update_background
end
def value
@toggled
@value
end
def value=(boolean)
@value = boolean
if boolean
@text.text = @options[:checkmark]
else
@text.text = ""
end
recalculate
publish(:changed, @value)
end
end
end

View File

@@ -23,6 +23,7 @@ module CyberarmEngine
return :handled if handler.call(self, *args) == :handled
end
parent.publish(event, *args) if parent
return nil
end

View File

@@ -12,7 +12,7 @@ module CyberarmEngine
@root_container = Element::Stack.new(gui_state: self)
@game_objects << @root_container
@containers = [@root_container]
$__current_container__ = @root_container
@active_width = window.width
@active_height = window.height
@@ -22,6 +22,11 @@ module CyberarmEngine
@mouse_down_on = {}
@mouse_down_position = {}
@pending_recalculate_request = false
@tip = CyberarmEngine::Text.new("", size: 22, z: Float::INFINITY)
@menu = nil
@min_drag_distance = 0
@mouse_pos = Vector.new
end
# throws :blur event to focused element and sets GuiState focused element
@@ -35,8 +40,18 @@ module CyberarmEngine
@focus
end
def draw
super
if @tip.text.length > 0
Gosu.draw_rect(@tip.x - 2, @tip.y - 2, @tip.width + 4, @tip.height + 4, 0xff020202, Float::INFINITY)
@tip.draw
end
end
def update
if @pending_recalculate_request
@root_container.recalculate
@root_container.recalculate
@pending_recalculate_request = false
end
@@ -56,12 +71,30 @@ module CyberarmEngine
redirect_holding_mouse_button(:middle) if @mouse_over && Gosu.button_down?(Gosu::MsMiddle)
redirect_holding_mouse_button(:right) if @mouse_over && Gosu.button_down?(Gosu::MsRight)
if Vector.new(window.mouse_x, window.mouse_y) == @last_mouse_pos
if @mouse_over && (Gosu.milliseconds - @mouse_moved_at) > tool_tip_delay
@tip.text = @mouse_over.tip if @mouse_over
@tip.x, @tip.y = window.mouse_x - @tip.width / 2, window.mouse_y - @tip.height - 4
else
@tip.text = ""
end
else
@mouse_moved_at = Gosu.milliseconds
end
@last_mouse_pos = Vector.new(window.mouse_x, window.mouse_y)
@mouse_pos = @last_mouse_pos.clone
request_recalculate if @active_width != window.width || @active_height != window.height
@active_width = window.width
@active_height = window.height
end
def tool_tip_delay
500 # ms
end
def button_down(id)
super
@@ -72,6 +105,8 @@ module CyberarmEngine
redirect_mouse_button(:middle)
when Gosu::MsRight
redirect_mouse_button(:right)
when Gosu::KbF5
request_recalculate
end
end
@@ -115,12 +150,26 @@ module CyberarmEngine
@mouse_over.publish(:"clicked_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over == @mouse_down_on[button]
end
if @dragging_element
@dragging_element.publish(:end_drag, window.mouse_x, window.mouse_y, button)
@dragging_element = nil
end
@mouse_down_position[button] = nil
@mouse_down_on[button] = nil
end
def redirect_holding_mouse_button(button)
@mouse_over.publish(:"holding_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over
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.publish(:"begin_drag", window.mouse_x, window.mouse_y, button)
end
if @dragging_element
@dragging_element.publish(:"drag_update", window.mouse_x, window.mouse_y, button) if @dragging_element
else
@mouse_over.publish(:"holding_#{button}_mouse_button", window.mouse_x, window.mouse_y) if @mouse_over
end
end
def redirect_mouse_wheel(button)

View File

@@ -88,6 +88,7 @@ module CyberarmEngine
caret_width: 2,
caret_color: Gosu::Color::WHITE,
caret_interval: 500,
selection_color: Gosu::Color.rgba(255, 128, 50, 200),
},
Image: { # < Element
@@ -111,7 +112,16 @@ module CyberarmEngine
height: 36,
background: 0xff111111,
fraction_background: [0xffc75e61, 0xffe26623],
border_thickness: 4,
border_thickness: 1,
border_color: [0xffd59674, 0xffff8746]
},
Slider: { # < Element
width: 250,
height: 36,
background: 0xff111111,
fraction_background: [0xffc75e61, 0xffe26623],
border_thickness: 1,
border_color: [0xffd59674, 0xffff8746]
}
}.freeze

View File

@@ -1,25 +1,61 @@
module CyberarmEngine
class Vector
##
# Creates a up vector
#
# Vector.new(0, 1, 0)
#
# @return [CyberarmEngine::Vector]
def self.up
Vector.new(0, 1, 0)
end
##
# Creates a down vector
#
# Vector.new(0, -1, 0)
#
# @return [CyberarmEngine::Vector]
def self.down
Vector.new(0, -1, 0)
end
##
# Creates a left vector
#
# Vector.new(-1, 0, 0)
#
# @return [CyberarmEngine::Vector]
def self.left
Vector.new(-1, 0, 0)
end
##
# Creates a right vector
#
# Vector.new(1, 0, 0)
#
# @return [CyberarmEngine::Vector]
def self.right
Vector.new(1, 0, 0)
end
##
# Creates a forward vector
#
# Vector.new(0, 0, 1)
#
# @return [CyberarmEngine::Vector]
def self.forward
Vector.new(0, 0, 1)
end
##
# Creates a backward vector
#
# Vector.new(0, 0, -1)
#
# @return [CyberarmEngine::Vector]
def self.backward
Vector.new(0, 0, -1)
end
@@ -40,21 +76,33 @@ module CyberarmEngine
def weight; @weight; end
def weight=(n); @weight = n; end
alias w weight
alias w= weight=
# @return [Boolean]
def ==(other)
if other.is_a?(Numeric)
@x == other &&
@y == other &&
@z == other &&
@weight == other
else
elsif other.is_a?(Vector)
@x == other.x &&
@y == other.y &&
@z == other.z &&
@weight == other.weight
else
other == self
end
end
# Performs math operation, excluding @weight
# Create a new vector using {x} and {y} values
# @return [CyberarmEngine::Vector]
def xy
Vector.new(@x, @y)
end
# Performs math operation, excluding {weight}
private def operator(function, other)
if other.is_a?(Numeric)
Vector.new(
@@ -71,22 +119,26 @@ module CyberarmEngine
end
end
# Adds Vector and Numberic or Vector and Vector, excluding @weight
# Adds Vector and Numeric or Vector and Vector, excluding {weight}
# @return [CyberarmEngine::Vector]
def +(other)
operator("+", other)
end
# Subtracts Vector and Numberic or Vector and Vector, excluding @weight
# Subtracts Vector and Numeric or Vector and Vector, excluding {weight}
# @return [CyberarmEngine::Vector]
def -(other)
operator("-", other)
end
# Multiplies Vector and Numberic or Vector and Vector, excluding @weight
# Multiplies Vector and Numeric or Vector and Vector, excluding {weight}
# @return [CyberarmEngine::Vector]
def *(other)
operator("*", other)
end
# Divides Vector and Numberic or Vector and Vector, excluding @weight
# Divides Vector and Numeric or Vector and Vector, excluding {weight}
# @return [CyberarmEngine::Vector]
def /(other)
# Duplicated to protect from DivideByZero
if other.is_a?(Numeric)
@@ -104,6 +156,8 @@ module CyberarmEngine
end
end
# dot product of {Vector}
# @return [Integer|Float]
def dot(other)
product = 0
@@ -117,6 +171,8 @@ module CyberarmEngine
return product
end
# cross product of {Vector}
# @return [CyberarmEngine::Vector]
def cross(other)
a = self.to_a
b = other.to_a
@@ -129,24 +185,40 @@ module CyberarmEngine
end
# returns degrees
# @return [Float]
def angle(other)
Math.acos( self.normalized.dot(other.normalized) ) * 180 / Math::PI
end
# returns magnitude of Vector, ignoring #weight
# @return [Float]
def magnitude
Math.sqrt((@x * @x) + (@y * @y) + (@z * @z))
end
##
# returns normalized {Vector}
#
# @example
# CyberarmEngine::Vector.new(50, 21.2, 45).normalized
# # => <CyberarmEngine::Vector:0x001 @x=0.7089... @y=0.3005... @z=0.6380... @weight=0>
#
# @return [CyberarmEngine::Vector]
def normalized
mag = magnitude
self / Vector.new(mag, mag, mag)
end
# returns a direction {Vector}
#
# z is pitch
#
# y is yaw
#
# x is roll
# @return [CyberarmEngine::Vector]
def direction
# z is pitch
# y is yaw
# x is roll
_x = -Math.sin(@y.degrees_to_radians) * Math.cos(@z.degrees_to_radians)
_y = Math.sin(@z.degrees_to_radians)
_z = Math.cos(@y.degrees_to_radians) * Math.cos(@z.degrees_to_radians)
@@ -154,41 +226,63 @@ module CyberarmEngine
Vector.new(_x, _y, _z)
end
# returns an inverse {Vector}
# @return [CyberarmEngine::Vector]
def inverse
Vector.new(1.0 / @x, 1.0 / @y, 1.0 / @z)
end
# Adds up values of {x}, {y}, and {z}
# @return [Integer|Float]
def sum
@x + @y + @z
end
##
# Linear interpolation: smoothly transition between two {Vector}
#
# CyberarmEngine::Vector.new(100, 100, 100).lerp( CyberarmEngine::Vector.new(0, 0, 0), 0.75 )
# # => <CyberarmEngine::Vector:0x0001 @x=75.0, @y=75.0, @z=75.0, @weight=0>
#
# @param other [CyberarmEngine::Vector | Integer | Float] value to subtract from
# @param factor [Float] how complete transition to _other_ is, in range [0.0..1.0]
# @return [CyberarmEngine::Vector]
def lerp(other, factor)
(self - other) * factor.clamp(0.0, 1.0)
end
# 2D distance using X and Y
# @return [Float]
def distance(other)
Math.sqrt((@x-other.x)**2 + (@y-other.y)**2)
end
# 2D distance using X and Z
# @return [Float]
def gl_distance2d(other)
Math.sqrt((@x-other.x)**2 + (@z-other.z)**2)
end
# 3D distance using X, Y, and Z
# @return [Float]
def distance3d(other)
Math.sqrt((@x-other.x)**2 + (@y-other.y)**2 + (@z-other.z)**2)
end
# Converts {Vector} to Array
# @return [Array]
def to_a
[@x, @y, @z, @weight]
end
# Converts {Vector} to String
# @return [String]
def to_s
"X: #{@x}, Y: #{@y}, Z: #{@z}, Weight: #{@weight}"
end
# Converts {Vector} to Hash
# @return [Hash]
def to_h
{x: @x, y: @y, z: @z, weight: @weight}
end

View File

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

View File

@@ -1,5 +1,5 @@
module CyberarmEngine
class Engine < Gosu::Window
class Window < Gosu::Window
IMAGES = {}
SAMPLES= {}
SONGS = {}
@@ -34,6 +34,8 @@ module CyberarmEngine
end
def update
Stats.clear
current_state.update if current_state
@last_frame_time = Gosu.milliseconds-@current_frame_time
@current_frame_time = Gosu.milliseconds