RGSS Table, Color & Tone Classes

I have made a Table class, equal to the RGSS one, which includes Marshal dump and load methods. You should be asking, why to use this, if it is equal to the RMXP/VX one, but this was designed for pure ruby, where the RGSS classes doens't exist. So with this script you will be able to load some .rxdata/.rvdata, which uses the Table class, with .rb programs, and also edit them and save them again.
  1. class Table
  2.   def initialize(x,y=1,z=1)
  3.      @xsize,@ysize,@zsize=x,y,z
  4.      @data=Array.new(x*y*z, 0)
  5.   end
  6.   def [](x,y=0,z=0)
  7.      @data[x+y*@xsize+z*@xsize*@ysize]
  8.   end
  9.   def []=(*args)
  10.      x=args[0]
  11.      y=args.size>2 ?args[1]:0
  12.      z=args.size>3 ?args[2]:0
  13.      v=args.pop
  14.      @data[x+y*@xsize+z*@xsize*@ysize]=v
  15.   end
  16.   def _dump(d=0)
  17.      s=[3].pack('L')
  18.      s+=[@xsize].pack('L')+[@ysize].pack('L')+[@zsize].pack('L')
  19.      s+=[@xsize*@ysize*@zsize].pack('L')
  20.      for z in 0...@zsize
  21.         for y in 0...@ysize
  22.            for x in 0...@xsize
  23.               s+=[@data[x+y*@xsize+z*@xsize*@ysize],0,0].pack('L')[0,2]
  24.            end
  25.         end
  26.      end
  27.      s
  28.   end
  29.   attr_reader(:xsize,:ysize,:zsize,:data)
  30.   class << self
  31.      def _load(s)
  32.         size=s[0,4].unpack('L')[0]
  33.         nx=s[4,4].unpack('L')[0]
  34.         ny=s[8,4].unpack('L')[0]
  35.         nz=s[12,4].unpack('L')[0]
  36.         data=[]
  37.         pointer=20
  38.         loop do
  39.            data.push((s[pointer,2]+"\000\000").unpack('L')[0])
  40.            pointer+=2
  41.            break if pointer > s.size-1
  42.         end
  43.         t=Table.new(nx,ny,nz)
  44.         n=0
  45.         for z in 0...nz
  46.            for y in 0...ny
  47.               for x in 0...nx
  48.                  t[x,y,z]=data[n]
  49.                  n+=1
  50.               end
  51.            end
  52.         end
  53.         t
  54.      end
  55.   end
  56. end
Expand to see the code.


And also I include here my BigTable class, which was designed for RPG Advanced Editor. This Table class allows to use upto 4294967296 numbers, insteand of the 65535 of the normal Table class.
  1. class BigTable
  2.   def initialize(x, y = 1, z = 1)
  3.      x = [x, 256 ** 4].min
  4.      y = [y, 256 ** 4].min
  5.      z = [z, 256 ** 4].min
  6.      @xsize, @ysize, @zsize = x, y, z
  7.      @data = Array.new(x * y * z, 0)
  8.   end
  9.   def [](x, y = 0, z = 0)
  10.      x = [x, @xsize].min
  11.      y = [y, @ysize].min
  12.      z = [z, @zsize].min
  13.      @data[x + y * @xsize + z * @xsize * @ysize]
  14.   end
  15.   def []=(*args)
  16.      x = [args[0], @xsize].min
  17.      y = [args.size>2 ?args[1] : 0, @ysize].min
  18.      z = [args.size>3 ?args[2] : 0, @zsize].min
  19.      v = [args.pop, 256 ** 4].min
  20.      @data[x + y * @xsize + z * @xsize * @ysize] = v
  21.   end
  22.   def _dump(d = 0)
  23.      s = [3].pack('L')
  24.      s += [@xsize].pack('L') + [@ysize].pack('L') + [@zsize].pack('L')
  25.      s += [@xsize * @ysize * @zsize].pack('L')
  26.      for z in 0...@zsize
  27.         for y in 0...@ysize
  28.            for x in 0...@xsize
  29.               s += [@data[x + y * @xsize + z * @xsize * @ysize]].pack('L')
  30.            end
  31.         end
  32.      end
  33.      s
  34.   end
  35.   attr_reader(:xsize, :ysize, :zsize, :data)
  36.   class << self
  37.      def _load(s)
  38.         nx = s[0, 4].unpack('L')[0]
  39.         ny = s[4, 4].unpack('L')[0]
  40.         nz = s[8, 4].unpack('L')[0]
  41.         size = s[12, 4].unpack('L')[0]
  42.         data = []
  43.         pointer = 16
  44.         loop do
  45.            data.push(s[pointer, 4].unpack('L')[0])
  46.            pointer += 4
  47.            break if pointer > s.size - 1
  48.         end
  49.         t = BigTable.new(nx, ny, nz)
  50.         n = 0
  51.         for z in 0...nz
  52.            for y in 0...ny
  53.               for x in 0...nx
  54.                  t[x, y, z] = data[n]
  55.                  n += 1
  56.               end
  57.            end
  58.         end
  59.         t
  60.      end
  61.   end
  62. end
Expand to see the code.


Update - 25/03/09
I have made time ago Color and Tone classes with their marshal methods, again for my project RPG Advanced Editor. Here are both classes, and also the last version of the Table class.

Color:
  1. class Color
  2.   def initialize(r, g, b, a = 255)
  3.      @red = r
  4.      @green = g
  5.      @blue = b
  6.      @alpha = a
  7.   end
  8.   def set(r, g, b, a = 255)
  9.      @red = r
  10.      @green = g
  11.      @blue = b
  12.      @alpha = a
  13.   end
  14.   def color
  15.      Color.new(@red, @green, @blue, @alpha)
  16.   end
  17.   def _dump(d = 0)
  18.      [@red, @green, @blue, @alpha].pack('d4')
  19.   end
  20.   def self._load(s)
  21.      Color.new(*s.unpack('d4'))
  22.   end
  23.   attr_accessor(:red, :green, :blue, :alpha)
  24. end
Expand to see the code.


Tone:
  1. class Tone
  2.   def initialize(r, g, b, a = 0)
  3.      @red = r
  4.      @green = g
  5.      @blue = b
  6.      @gray = a
  7.   end
  8.   def set(r, g, b, a = 0)
  9.      @red = r
  10.      @green = g
  11.      @blue = b
  12.      @gray = a
  13.   end
  14.   def color
  15.      Color.new(@red, @green, @blue, @gray)
  16.   end
  17.   def _dump(d = 0)
  18.      [@red, @green, @blue, @gray].pack('d4')
  19.   end
  20.   def self._load(s)
  21.      Tone.new(*s.unpack('d4'))
  22.   end
  23.   attr_accessor(:red, :green, :blue, :gray)
  24. end
Expand to see the code.


And my last version of Table:
  1. class Table
  2.   def initialize(x, y = 1, z = 1)
  3.      @xsize, @ysize, @zsize = x, y, z
  4.      @data = Array.new(x * y * z, 0)
  5.   end
  6.   def [](x, y = 0, z = 0)
  7.      @data[x + y * @xsize + z * @xsize * @ysize]
  8.   end
  9.   def []=(*args)
  10.      x = args[0]
  11.      y = args.size > 2 ? args[1] :0
  12.      z = args.size > 3 ? args[2] :0
  13.      v = args.pop
  14.      @data[x + y * @xsize + z * @xsize * @ysize] = v
  15.   end
  16.   def _dump(d = 0)
  17.      s = [3].pack('L')
  18.      s += [@xsize].pack('L') + [@ysize].pack('L') + [@zsize].pack('L')
  19.      s += [@xsize * @ysize * @zsize].pack('L')
  20.      for z in 0...@zsize
  21.         for y in 0...@ysize
  22.            for x in 0...@xsize
  23.               s += [@data[x + y * @xsize + z * @xsize * @ysize]].pack('S')
  24.            end
  25.         end
  26.      end
  27.      s
  28.   end
  29.   def self._load(s)
  30.      size = s[0, 4].unpack('L')[0]
  31.      nx = s[4, 4].unpack('L')[0]
  32.      ny = s[8, 4].unpack('L')[0]
  33.      nz = s[12, 4].unpack('L')[0]
  34.      data = []
  35.      pointer = 20
  36.      loop do
  37.         data.push(*s[pointer, 2].unpack('S'))
  38.         pointer += 2
  39.         break if pointer > s.size - 1
  40.      end
  41.      t = Table.new(nx, ny, nz)
  42.      n = 0
  43.      for z in 0...nz
  44.         for y in 0...ny
  45.            for x in 0...nx
  46.               t[x, y, z] = data[n]
  47.               n += 1
  48.            end
  49.         end
  50.      end
  51.      t
  52.   end
  53.   attr_reader(:xsize, :ysize, :zsize, :data)
  54. end
Expand to see the code.
So... what exactly is this for? Some kind osf scripting tool?
  -KRoP
It's for people who want to make things like Tilemaps in straight-up Ruby, right?

From what I can see, you'd be able to make a new map editor to work with an enhanced version of the Tilemap so that you could have more layers, autotiles, and whatever new features you could imagine, and be able to put those maps in your RMXP/VX game.

Pretty sweet. Good job, vgvgf.
Nice one, I especially like the BigTable class.
The only thing I don't quite understand is the .pack/.unpack methods... These are still mysterious to me.

Great job! :thumb:
-Dargor
Hey, here is Pack. It's about halfway down the page.
King Red Of Pancakes wrote:
So... what exactly is this for? Some kind osf scripting tool?
  -KRoP
OS wrote:
It's for people who want to make things like Tilemaps in straight-up Ruby, right?

From what I can see, you'd be able to make a new map editor to work with an enhanced version of the Tilemap so that you could have more layers, autotiles, and whatever new features you could imagine, and be able to put those maps in your RMXP/VX game.

Pretty sweet. Good job, vgvgf.
Well, I designed the Table class for allowing the load of Marshal data via .rb files. You can put the RPG module, with the definition of the RPG::#### classes in a .rb file, but some classes, like RPG::Actors, which uses the Table class for the paramaters, can't be loaded except you have the Table class defined, like my script.
And the BigTable class was designed for breaking the RMXP limits, like 9999 max stats, and so, which also can be used for making better tilesets, as you said OS.
Dargor wrote:
Nice one, I especially like the BigTable class.
The only thing I don't quite understand is the .pack/.unpack methods... These are still mysterious to me.

Great job! :thumb:
-Dargor
The pack/unpack methods are for compressing and decompressing data into and from bytes/numbers or strings. This methods are useful for some API calls, which gives or requires the data compressed, and in this case is useful, because compressed/packed numbers occupies less space when dumped than the normal numbers.
@vgvgf => You rock! This is going to be very helpful!! I'm writing an importer/exporter to plain text for all the rxdata files so that teams of people can work on RMXP games together and still version them with something like SVN or Mercurial.

By the way, how did you figure out the _load and _dump functions?!! I am working on the Color and Tone classes, but I am not sure how RGSS implemented the dump/load logic. Is there an easy/clever way to figure it out?

Thanks!
Interesting... and definately helpful for understanding that class. Also comes right when I'm working on Table-relying scripts :]

What are the chances you'll attempt a Tilemap class rewrite? ^^ (for VX, that is, since Seph already has the XP one covered...)
Very interesting. You must have worked excessively hard on this. Good work vgvgf. :shades:
Raku wrote:
@vgvgf => You rock! This is going to be very helpful!! I'm writing an importer/exporter to plain text for all the rxdata files so that teams of people can work on RMXP games together and still version them with something like SVN or Mercurial.

By the way, how did you figure out the _load and _dump functions?!! I am working on the Color and Tone classes, but I am not sure how RGSS implemented the dump/load logic. Is there an easy/clever way to figure it out?

Thanks!
I added Color and Tone classes to the first post. About how to figure how these classes are marshaled, well, I just analized the resultant strings lots of times until I encountered some patterns. That's all.

Quote:
What are the chances you'll attempt a Tilemap class rewrite? ^^ (for VX, that is, since Seph already has the XP one covered...)
100%, hehe, I have already made a Tilemap rewrite which wasnt very good, but now I am thinking on making it via dll with poccil's method, which would result in a really fast Tilemap script. But I am still learning C, so it will take me some time.
Thanks vgvgf! Using your classes I can now read all the rxdata files and dump their contents to YAML files! Now all I need to do is tidy up the scripting, test it out, then its ready to share. Thanks for sharing your work, I guess I need to improve my binary hacking skills. o(>_<)o

The version you provided here works great, but if we want to be 100% compliant with the RGSS documentation, here are revised Color and Tone classes with two minor changes:
  • The attributes are stored as Floats, not FixNums
  • Attribute setters limit the assigned values if they are outside the boundaries specified in the documentation.

  1. class Color
  2.   def initialize(r, g, b, a = 255.0)
  3.      self.red = r.to_f
  4.      self.green = g.to_f
  5.      self.blue = b.to_f
  6.      self.alpha = a.to_f
  7.   end
  8.   def set(r, g, b, a = 255.0)
  9.      self.red = r.to_f
  10.      self.green = g.to_f
  11.      self.blue = b.to_f
  12.      self.alpha = a.to_f
  13.   end
  14.   attr_reader(:red, :green, :blue, :alpha)
  15.   def red=(val)
  16.      @red    = [[val.to_f, 0.0].max, 255.0].min
  17.   end
  18.   def green=(val)
  19.      @green = [[val.to_f, 0.0].max, 255.0].min
  20.   end
  21.   def blue=(val)
  22.      @blue   = [[val.to_f, 0.0].max, 255.0].min
  23.   end
  24.   def alpha=(val)
  25.      @alpha = [[val.to_f, 0.0].max, 255.0].min
  26.   end
  27.   def color
  28.      Color.new(@red, @green, @blue, @alpha)
  29.   end
  30.   def _dump(d = 0)
  31.      [@red, @green, @blue, @alpha].pack('d4')
  32.   end
  33.   def self._load(s)
  34.      Color.new(*s.unpack('d4'))
  35.   end
  36. end
  37.  
  38. class Tone
  39.   def initialize(r, g, b, a = 0.0)
  40.      self.red = r.to_f
  41.      self.green = g.to_f
  42.      self.blue = b.to_f
  43.      self.gray = a.to_f
  44.   end
  45.   def set(r, g, b, a = 0.0)
  46.      self.red = r.to_f
  47.      self.green = g.to_f
  48.      self.blue = b.to_f
  49.      self.gray = a.to_f
  50.   end
  51.   def color
  52.      Color.new(@red, @green, @blue, @gray)
  53.   end
  54.   def _dump(d = 0)
  55.      [@red, @green, @blue, @gray].pack('d4')
  56.   end
  57.   def self._load(s)
  58.      Tone.new(*s.unpack('d4'))
  59.   end
  60.   attr_reader(:red, :green, :blue, :gray)
  61.   def red=(val)
  62.      @red    = [[val.to_f, -255.0].max, 255.0].min
  63.   end
  64.   def green=(val)
  65.      @green = [[val.to_f, -255.0].max, 255.0].min
  66.   end
  67.   def blue=(val)
  68.      @blue   = [[val.to_f, -255.0].max, 255.0].min
  69.   end
  70.   def gray=(val)
  71.      @gray   = [[val.to_f, 0.0].max, 255.0].min
  72.   end
  73. end
Expand to see the code.
I have updated your Table class so that RMXP can successfully read .rxdata files dumped by it. The two versions you wrote were loading the Table objects correctly from RMXP's .rxdata files, but your _dump logic always packed the constant 3 first. RMXP was choking when it tried to open an .rxdata file dumped using that logic because that first packed value represents the number of dimensions specified when creating the Table (1, 2, or 3). Not sure why the built-in Table class cares, maybe some optimization of the under-lying C/C++ implementation.

I've updated the Table class below with the correct dump logic so that dumped rxdata files can be correctly read by RMXP.

  1. class Table
  2.   def initialize(x, y = 0, z = 0)
  3.      @dim = 1 + (y > 0 ? 1 : 0) + (z > 0 ? 1 : 0)
  4.      @xsize, @ysize, @zsize = x, (y > 0 ? y : 1), (z > 0 ? z : 1)
  5.      @data = Array.new(x * y * z, 0)
  6.   end
  7.   def [](x = 0, y = 0, z = 0)
  8.      @data[x + y * @xsize + z * @xsize * @ysize]
  9.   end
  10.   def []=(*args)
  11.      x = args[0]
  12.      y = args.size > 2 ? args[1] :0
  13.      z = args.size > 3 ? args[2] :0
  14.      v = args.pop
  15.      @data[x + y * @xsize + z * @xsize * @ysize] = v
  16.   end
  17.   def _dump(d = 0)
  18.      # The number of required dimensions
  19.      s = [@dim].pack('L')
  20.      s += [@xsize].pack('L') + [@ysize].pack('L') + [@zsize].pack('L')
  21.      s += [@xsize * @ysize * @zsize].pack('L')
  22.      @zsize.times do |z|
  23.         @ysize.times do |y|
  24.            @xsize.times do |x|
  25.               s += [@data[x + y * @xsize + z * @xsize * @ysize]].pack('S')
  26.            end
  27.         end
  28.      end
  29.      s
  30.   end
  31.   def self._load(s)
  32.      size = s[0, 4].unpack('L')[0]
  33.      nx = s[4, 4].unpack('L')[0]
  34.      ny = s[8, 4].unpack('L')[0]
  35.      nz = s[12, 4].unpack('L')[0]
  36.      data = []
  37.      pointer = 20
  38.      loop do
  39.         data.push(*s[pointer, 2].unpack('S'))
  40.         pointer += 2
  41.         break if pointer > s.size - 1
  42.      end
  43.      t = Table.new(nx, ny, nz) if size == 3
  44.      t = Table.new(nx, ny)       if size == 2
  45.      t = Table.new(nx)             if size == 1
  46.      n = 0
  47.      for z in 0...nz
  48.         for y in 0...ny
  49.            for x in 0...nx
  50.               t[x, y, z] = data[n]
  51.               n += 1
  52.            end
  53.         end
  54.      end
  55.      t
  56.   end
  57.   attr_reader(:xsize, :ysize, :zsize)
  58. end
Expand to see the code.


Finally, I got my practice with reading the binary dumps! :thumb:
Thanks Raku, the first long of the table dump was a mistery to me, I didn't know that it was the number of dimesions. It was a unnecessary value for my table class, as it didn't depend on the dimension number, so I just put "3", as I saw in some RMXP Table dumps.
I have also updated the Table class, now it is cleaner:
  1. class Table
  2.   def initialize(x, y = 0, z = 0)
  3.      @dim = 1 + (y > 0 ? 1 : 0) + (z > 0 ? 1 : 0)
  4.      @xsize, @ysize, @zsize = x, [y, 1].max, [z, 1].max
  5.      @data = Array.new(x * y * z, 0)
  6.   end
  7.   def [](x, y = 0, z = 0)
  8.      @data[x + y * @xsize + z * @xsize * @ysize]
  9.   end
  10.   def []=(*args)
  11.      x = args[0]
  12.      y = args.size > 2 ? args[1] : 0
  13.      z = args.size > 3 ? args[2] : 0
  14.      v = args.pop
  15.      @data[x + y * @xsize + z * @xsize * @ysize] = v
  16.   end
  17.   def _dump(d = 0)
  18.      [@dim, @xsize, @ysize, @zsize, @xsize * @ysize * @zsize].pack('LLLLL') <<
  19.      @data.pack("S#{@xsize * @ysize * @zsize}")
  20.   end
  21.   def self._load(s)
  22.      size, nx, ny, nz, items = *s[0, 20].unpack('LLLLL')
  23.      case size
  24.      when 1; t = Table.new(nx)
  25.      when 2; t = Table.new(nx, ny)
  26.      when 3; t = Table.new(nx, ny, nz)
  27.      end
  28.      t.data = s[20, items * 2].unpack("S#{items}")
  29.      t
  30.   end
  31.   attr_accessor(:xsize, :ysize, :zsize, :data)
  32. end
Expand to see the code.


And also, you made a great work with the Color and Tone classes, now they are 100% RGSS compatible.

PD: Thanks to trebor777, who notified me that for strings the << method is faster than the + method.
  1. case size
  2. when 1; t = Table.new(nx)
  3. when 2; t = Table.new(nx, ny)
  4. when 3; t = Table.new(nx, ny, nz)
  5. end
Expand to see the code.


better this:
  1. t= Table.new(*[nx,ny,nz][0,size])
Expand to see the code.


its very shorter :P
I prefer the other way since it's easier to understand and most likely faster.
Nice clean-up of the Table class, vgvgf! I'll include it in my next release of the Rxdata Versioning Utility.

vgvgf wrote:
And also, you made a great work with the Color and Tone classes, now they are 100% RGSS compatible.

No problem! I was just "standing on the shoulders of giants" so to speak. ;)

hanmac wrote:
better this:
  1. t= Table.new(*[nx,ny,nz][0,size])
Expand to see the code.


its very shorter :P

hanmac, that is indeed compact! But I have no idea what the * in that Ruby code snippet does! :) Can someone enlighten me?
The * breaks up an array into arguments.
  1. my_method(*[nx,ny,nz])
  2. # Is basically the same as
  3. my_method(nx,ny,nz)
Expand to see the code.
Ahhh...thanks Zeriab! Got it.

I tend to agree with Zeriab that the case statement is probably faster and has the benefit of being easier to understand.

But, thanks to hanmac for his post regardless! I learned something new today. :)
i dont know how fast it is...
can someone test it?
Actually if we know how works the table we should be able to write directly

t = Table.new(nx, ny, nz)

for all the cases... as ny and nz, should be set to 0 by the unpack if the loaded tabled only used one or two dimensions.

Secondly you have a small bug that may happen if you try to dump a table which has just been created with only 1 or 2 dim
I think it's related to this; @data.pack('S#{size}') crashes "too few arguments".

I'll later tonight try to fix and improve that anyway.


EDIT^^
Al right Here is the fixed version:

Not Having a 2nd dimension is the same as having a 2nd dimension which only contains 1 item. (can be applied for a 3rd Dimension)
Therefore instead of increasing the dim size if the y or z are greater than 0, we do it if those are greater than 1
The default value for y and z also becomes 1.

  1.  
  2. class Table
  3.   def initialize(x, y = 1, z = 1)
  4.      y = [y.abs,1].max # Just in case the user types 0, or a negative value
  5.      z = [z.abs,1].max
  6.      @dim = 1 + (y <=> 1) + (z <=> 1)    # <=> returns 1 if greater, 0 if the same, -1 if smaller
  7.      @xsize, @ysize, @zsize = x, y, z # We don't need to set the 1 to 1 ;)
  8.      @data = Array.new(@xsize * @ysize * @zsize, 0)
  9.   end
  10.   def [](x, y = 0, z = 0)
  11.      @data[x + y * @xsize + z * @xsize * @ysize]
  12.   end
  13.   def []=(*args)
  14.      x = args[0]
  15.      y = args.size > 2 ? args[1] : 0
  16.      z = args.size > 3 ? args[2] : 0
  17.      v = args.pop
  18.      @data[x + y * @xsize + z * @xsize * @ysize] = v
  19.   end
  20.   def _dump(d = 0)
  21.      [@dim, @xsize, @ysize, @zsize, @xsize * @ysize * @zsize].pack('LLLLL') << @data.pack("S#{@xsize * @ysize * @zsize}")
  22.   end
  23.   def self._load(s)
  24.      size, nx, ny, nz, items = *s[0, 20].unpack('LLLLL')
  25.      t = Table.new(nx, ny, nz)
  26.      t.data = s[20, items * 2].unpack("S#{items}")
  27.      t
  28.   end
  29.   attr_accessor(:xsize, :ysize, :zsize, :data)
  30. end
  31.  
Expand to see the code.


PS... This hack transforms thhe into the ...great
trebor777 wrote:
Actually if we know how works the table we should be able to write directly

t = Table.new(nx, ny, nz)

for all the cases... as ny and nz, should be set to 0 by the unpack if the loaded tabled only used one or two dimensions.

Secondly you have a small bug that may happen if you try to dump a table which has just been created with only 1 or 2 dim
I think it's related to this; @data.pack('S#{size}') crashes "too few arguments".

I'll later tonight try to fix and improve that anyway.


EDIT^^
Al right Here is the fixed version:

Not Having a 2nd dimension is the same as having a 2nd dimension which only contains 1 item. (can be applied for a 3rd Dimension)
Therefore instead of increasing the dim size if the y or z are greater than 0, we do it if those are greater than 1
The default value for y and z also becomes 1.

  1. &nbsp;
  2. class Table
  3. &nbsp; def initialize(x, y = 1, z = 1)
  4. &nbsp; &nbsp; y = [y.abs,1].max # Just in case the user types 0, or a negative value
  5. &nbsp; &nbsp; z = [z.abs,1].max
  6. &nbsp; &nbsp; @dim = 1 + (y <=> 1) + (z <=> 1) &nbsp; # <=> returns 1 if greater, 0 if the same, -1 if smaller
  7. &nbsp; &nbsp; @xsize, @ysize, @zsize = x, y, z # We don't need to set the 1 to 1 ;)
  8. &nbsp; &nbsp; @data = Array.new(@xsize * @ysize * @zsize, 0)
  9. &nbsp; end
  10. &nbsp; def [](x, y = 0, z = 0)
  11. &nbsp; &nbsp; @data[x + y * @xsize + z * @xsize * @ysize]
  12. &nbsp; end
  13. &nbsp; def []=(*args)
  14. &nbsp; &nbsp; x = args[0]
  15. &nbsp; &nbsp; y = args.size > 2 ? args[1] : 0
  16. &nbsp; &nbsp; z = args.size > 3 ? args[2] : 0
  17. &nbsp; &nbsp; v = args.pop
  18. &nbsp; &nbsp; @data[x + y * @xsize + z * @xsize * @ysize] = v
  19. &nbsp; end
  20. &nbsp; def _dump(d = 0)
  21. &nbsp; &nbsp; [@dim, @xsize, @ysize, @zsize, @xsize * @ysize * @zsize].pack('LLLLL') << @data.pack("S#{@xsize * @ysize * @zsize}")
  22. &nbsp; end
  23. &nbsp; def self._load(s)
  24. &nbsp; &nbsp; size, nx, ny, nz, items = *s[0, 20].unpack('LLLLL')
  25. &nbsp; &nbsp; t = Table.new(nx, ny, nz)
  26. &nbsp; &nbsp; t.data = s[20, items * 2].unpack("S#{items}")
  27. &nbsp; &nbsp; t
  28. &nbsp; end
  29. &nbsp; attr_accessor(:xsize, :ysize, :zsize, :data)
  30. end
  31. &nbsp;
Expand to see the code.

trebor777, just a few comments from my end...

1) I did some "field research" on how the RMXP version of Table behaves for various inputs. Here are the results. The comments show what is packed into the dumped string:

  1.                                              # =>   [dim, x, y, z, size, data (# of bytes)]
  2. t = Table.new(2,4,2).dump      # =>   [   3, 2, 4, 2,    16,                        32]
  3. t = Table.new(1,1,1).dump      # =>   [   3, 1, 1, 1,      1,                         2]
  4. t = Table.new(1,1,-1).dump    # =>   [   3, 1, 1, 0,      0,                         0]
  5. t = Table.new(1,1).dump         # =>   [   2, 1, 1, 1,      1,                         2]
  6. t = Table.new(1).dump            # =>   [   1, 1, 1, 1,      1,                         2]
  7. t = Table.new(2,3,-4).dump    # =>   [   3, 2, 3, 0,      0,                         0]
  8. t = Table.new(2,-4,2).dump    # =>   [   3, 2, 0, 2,      0,                         0]
Expand to see the code.


It seems like RMXP doesn't crash when negative arguments are passed, but it also dumps a zero-sized array (which seems to be a bug). I recommend we copy RMXP's behavior, but NOT its bugs. ;)

2) I agree with your point that we should handle 0 and negative values in the initialize method, but should it really assume a dimension -x is x? I think 0 is more intuitive to the user. For example, a Table.new(1,-4,3) would create a 1 x 1 x 3 table instead of a 1 x 4 x 3 table. I think this is intuitive because usually when users give a negative array value, it is because some variable has accidentally gone negative, not because the dimension sign was reversed. What do you think?

If we want to replicate the dump behavior of RMXP exactly, here's what I propose, using a little from everyone. This one:
  1. class Table
  2.   def initialize(x, y = 0, z = 0)
  3.      @dim = 1 + (y > 0 ? 1 : 0) + (z > 0 ? 1 : 0)
  4.      @xsize, @ysize, @zsize = x, [y, 1].max, [z, 1].max
  5.      @data = Array.new(x * y * z, 0)
  6.   end
  7.   def [](x, y = 0, z = 0)
  8.      @data[x + y * @xsize + z * @xsize * @ysize]
  9.   end
  10.   def []=(*args)
  11.      x = args[0]
  12.      y = args.size > 2 ? args[1] : 0
  13.      z = args.size > 3 ? args[2] : 0
  14.      v = args.pop
  15.      @data[x + y * @xsize + z * @xsize * @ysize] = v
  16.   end
  17.   def _dump(d = 0)
  18.      [@dim, @xsize, @ysize, @zsize, @xsize * @ysize * @zsize].pack('LLLLL') <<
  19.      @data.pack("S#{@xsize * @ysize * @zsize}")
  20.   end
  21.   def self._load(s)
  22.      size, nx, ny, nz, items = *s[0, 20].unpack('LLLLL')
  23.      t = Table.new(*[nx, ny, nz][0,size])                # The * breaks apart an array into an argument list
  24.      t.data = s[20, items * 2].unpack("S#{items}")
  25.      t
  26.   end
  27.   attr_accessor(:xsize, :ysize, :zsize, :data)
  28. end
Expand to see the code.


I've tested it and I believe the dumped string matches the RMXP version 100% (except it doesn't have the negative dimension bug). Also, I settled on hanmac's the Table.new(*[...][...]) because, during some test over dumping many tables I didn't see a notable difference in speed. It's more succinct and with a comment it should be apparent what the syntax does.
hum I think you're right with the whole negative thing, that they should becomes 0values, but as i said: 0 means 1 ^^ so they should becomes ones instead 😀

So as ysize = 1, and zsize = 1 if y or z = 0, why not put y and z by default to 1 when they're not passed as arguments, or
when y or z are wrong values.
Also the dimension calculation just need to be adapted to work with ones instead of zeros(as in my version).
( and I quite like the use of <=> instead of ?: )

In the end in the load method, ny and nz will always have a value of 1 if we only have 1 dimension. (or nz will be 1 but not ny if 2 dimensions)( either with your's or my method ).

Therefore we can call simply Table.new(nx,ny,nz) all the time and don't have to worry about the number of argument needed.
trebor777 wrote:
hum I think you're right with the whole negative thing, that they should becomes 0values, but as i said: 0 means 1 ^^ so they should becomes ones instead 😀

So as ysize = 1, and zsize = 1 if y or z = 0, why not put y and z by default to 1 when they're not passed as arguments, or
when y or z are wrong values.
Also the dimension calculation just need to be adapted to work with ones instead of zeros(as in my version).
( and I quite like the use of <=> instead of ?: )

In the end in the load method, ny and nz will always have a value of 1 if we only have 1 dimension. (or nz will be 1 but not ny if 2 dimensions)( either with your's or my method ).

Therefore we can call simply Table.new(nx,ny,nz) all the time and don't have to worry about the number of argument needed.

Oh, sorry I don't think I explained well. The reason for making the y and z default parameters 0 is because we need to differentiate between the following two cases:

  1. t = Table.new(1)._dump          # @dim, @x, @y, @z = 1, 1, 1, 1
  2.  
  3. t = Table.new(1,1,1)._dump    # @dim, @x, @y, @z = 3, 1, 1, 1
Expand to see the code.

For some crazy reason, the RMXP Table class dumps 1 for the dimension in the first case and 3 for the dimension in the second case. The only thing I can think is that it is something about the underlying C/C++ implementation (since arrays aren't mutable there). Anyhow, If we make the defaults 1, we won't be able to differentiate between the above two cases and so the dumps won't be the same (indeed the code with defaults of 1 dumps 1 in both cases).

By the way, I completely agree with your style (defaulting to 1). 😀 The only issue is the compatibility with RMXP. :sad:
aaah well my bad then :p
Bad design from Enterbrain again.... they did a lot of stuff wrong lol...
I wonder if it's the same with RMVX actually?...
Quote:
PD: Thanks to trebor777, who notified me that for strings the << method is faster than the + method.

Spend a few time working on Benchmark, if you don't know it.
You can easily compare method1 to method2, and it's very usefull for optimizations.

________

About your code, I don't agree the way you've done it.
I read somewhere that Table was created because arrays with a lot of elements are bad managed within Ruby.
(and because the def [] (x,y,z) method is more intuitive)
So, that is why Table should be a multidimensionnal array.

But maybe I'm wrong, I'm not able to find the document I read this.
If you have some informations about that, I think I will change my mind. :)
well what do you mean by multi dim array..? lol, cause that's what is used here... :p
it's just that a multi dim array, is just simple array (instead of intricated ones( like [ [] ] ) with better indexing system. ( basically putting all the dimensions into one single dimensions)
handling 1 array is better than handling severals :p IMO.

It's written in the Help file, that the table class was created to handle large size arrays ( like 500*500*3 items = 750000 items ( largest map possible with all 3 layers used ))
Yeah, maybe I misunderstood this part of the Help file.
I was thinking that intricated arrays were better than super big simple array.

"IMO" ?
IMO = in my opinion

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=49838