Tilemap script for open source RMXP re-implimentation

Script Title:
Tilemap.rb

Engine: RMXP

Detailed Description:
Hello guys! I'm working on reimplimenting RMXP. For those of you wondering why I'd want to do that, I'll explain later on down this page. For now, let me describe what I need to make this possible.

For my clone of RMXP (http://github.com/cstrahan/open-rpg-maker), I need to implement the Tilemap class. Unfortunetly, I'm not very familiar with the behavior of this class, so doing this myself would take for ever. If someone could write this for me, I'll be able to make much more progress on the rest of the codebase. The code is already rendering sprites successfully, which means that we can render the Tilemap by creating a sprite for each layer.

I tried looking through GlitchFinder's edit of SephirothSpawn's Tilemap script here:
viewtopic.php?p=494360#p494360

Unfortunately, it requires modification to RMXP's standard scripts, which won't work in my scenario. The reason why that isn't an acceptable solution is due to the fact that I want my implementation of RMXP to work with existing games without modifying their scripts.

So, if someone can rewrite Tilemap without any requirement of modifying/inserting scripts, I'll be that much closer to getting my open source version of RMXP finished!

Why rewrite RMXP?
I have many reasons!
    1) Cross platform support (Mac, Linux & Windows)
    2) Run games in the browser via Silverlight
    3) Using a full distribution of Ruby 1.8.7 or 1.9 (which would run much faster, and allow for advanced scripting)
    4) Using the Rubygame gem for OpenGL/SDL rendering
    5) Playing games on the PSP with Joyau

Screen shots:
N/A

Other Scripts I am using (in order):
N/A
Alright! So I've managed to refactor Glitchfinder's script. I still need to clean up a bit, and remove all the other modules (other than Tilemap).

Please give it a test and let me know if there's anything wrong! I'm hoping I'll have a decent replica of the Tilemap functionality pretty soon... then I can move on to an alpha release of my project.

Content Hidden Spoiler
  1.  
  2. #==============================================================================
  3. # ** RPG::Cache
  4. #==============================================================================
  5.  
  6. module RPG::Cache
  7.   #--------------------------------------------------------------------------
  8.   # * Auto-Tiles
  9.   #--------------------------------------------------------------------------
  10.   Autotiles = [
  11.     [[27, 28, 33, 34], [ 5, 28, 33, 34], [27,  6, 33, 34], [ 5,  6, 33, 34],
  12.      [27, 28, 33, 12], [ 5, 28, 33, 12], [27,  6, 33, 12], [ 5,  6, 33, 12]],
  13.     [[27, 28, 11, 34], [ 5, 28, 11, 34], [27,  6, 11, 34], [ 5,  6, 11, 34],
  14.      [27, 28, 11, 12], [ 5, 28, 11, 12], [27,  6, 11, 12], [ 5,  6, 11, 12]],
  15.     [[25, 26, 31, 32], [25,  6, 31, 32], [25, 26, 31, 12], [25,  6, 31, 12],
  16.      [15, 16, 21, 22], [15, 16, 21, 12], [15, 16, 11, 22], [15, 16, 11, 12]],
  17.     [[29, 30, 35, 36], [29, 30, 11, 36], [ 5, 30, 35, 36], [ 5, 30, 11, 36],
  18.      [39, 40, 45, 46], [ 5, 40, 45, 46], [39,  6, 45, 46], [ 5,  6, 45, 46]],
  19.     [[25, 30, 31, 36], [15, 16, 45, 46], [13, 14, 19, 20], [13, 14, 19, 12],
  20.      [17, 18, 23, 24], [17, 18, 11, 24], [41, 42, 47, 48], [ 5, 42, 47, 48]],
  21.     [[37, 38, 43, 44], [37,  6, 43, 44], [13, 18, 19, 24], [13, 14, 43, 44],
  22.      [37, 42, 43, 48], [17, 18, 47, 48], [13, 18, 43, 48], [ 1,  2,  7,  8]]
  23.   ]
  24.   #--------------------------------------------------------------------------
  25.   # * Autotile Cache
  26.   #
  27.   #   @autotile_cache = {
  28.   #     filename => { [autotile_id, frame_id, hue] => bitmap, ... },
  29.   #     ...
  30.   #    }
  31.   #--------------------------------------------------------------------------
  32.   @autotile_cache = {}
  33.   #--------------------------------------------------------------------------
  34.   # * Autotile Tile
  35.   #--------------------------------------------------------------------------
  36.   def self.autotile_tile(autotile, tile_id, hue = 0, frame_id = nil)
  37.     # Configures Frame ID if not specified
  38.     if frame_id.nil?
  39.       # Animated Tiles
  40.       frames = autotile.width / 96
  41.       # Configures Animation Offset
  42.       fc = Graphics.frame_count / Animated_Autotiles_Frames
  43.       frame_id = (fc) % frames * 96
  44.     end
  45.  
  46.     # Reconfigure Tile ID
  47.     tile_id %= 48
  48.     # Creates Bitmap
  49.     bitmap = Bitmap.new(32, 32)
  50.     # Collects Auto-Tile Tile Layout
  51.     tiles = Autotiles[tile_id / 8][tile_id % 8]
  52.     # Draws Auto-Tile Rects
  53.     for i in 0...4
  54.       tile_position = tiles[i] - 1
  55.       src_rect = Rect.new(tile_position % 6 * 16 + frame_id,
  56.         tile_position / 6 * 16, 16, 16)
  57.       bitmap.blt(i % 2 * 16, i / 2 * 16, autotile, src_rect)
  58.     end    
  59.     # Set hue
  60.     bitmap.hue_change(hue)
  61.     # Return Auto-Tile
  62.     bitmap
  63.   end
  64.  
  65. end
  66. RPG::Cache::Animated_Autotiles_Frames = 16
  67.  
  68.  
  69. module Tilemap_Options
  70.   #--------------------------------------------------------------------------
  71.   # * Tilemap Options
  72.   #
  73.   #
  74.   #   Print Error Reports when not enough information set to tilemap
  75.   #    - Print_Error_Logs          = true or false
  76.   #
  77.   #   Number of autotiles to refresh at edge of viewport
  78.   #    - Viewport_Padding          = n
  79.   #
  80.   #   When maps are switch, automatically set
  81.   #   $game_map.tileset_settings.flash_data (Recommended : False unless using
  82.   #   flash_data)
  83.   #    - Autoset_Flash_data        = true or false
  84.   #
  85.   #   Duration Between Flash Data Flashes
  86.   #    - Flash_Duration            = n
  87.   #
  88.   #   Color of bitmap (Recommended to use low opacity value)
  89.   #    - Flash_Bitmap_C            = Color.new(255, 255, 255, 50)
  90.   #
  91.   #   Update Flashtiles Default Setting
  92.   #   Explanation : In the Flash Data Addition, because of lag, you may wish
  93.   #   to toggle whether flash tiles flash or not. This is the default state.
  94.   #    - Default_Update_Flashtiles = false
  95.   #--------------------------------------------------------------------------
  96.   Print_Error_Logs          = true
  97.   Autoset_Flash_data        = true
  98.   Viewport_Padding          = 2
  99.   Flash_Duration            = 40
  100.   Flash_Bitmap_C            = Color.new(255, 255, 255, 50)
  101.   Default_Update_Flashtiles = false
  102. end
  103.  
  104. #==============================================================================
  105. # ** Tilemap
  106. #==============================================================================
  107.  
  108. class Tilemap
  109.   #--------------------------------------------------------------------------
  110.   # * Public Instance Variables
  111.   #--------------------------------------------------------------------------
  112.   attr_reader   :layers
  113.   attr_accessor :tileset
  114.   attr_accessor :autotiles
  115.   attr_reader   :map_data
  116.   attr_accessor :flash_data
  117.   attr_accessor :priorities
  118.   attr_accessor :visible
  119.   attr_accessor :ox
  120.   attr_accessor :oy
  121.   attr_accessor :refresh_autotiles
  122.   #--------------------------------------------------------------------------
  123.   # * Object Initialization
  124.   #--------------------------------------------------------------------------
  125.   def initialize(viewport)
  126.     # Saves Viewport
  127.     @viewport = viewport
  128.     # Creates Blank Instance Variables
  129.     @layers            = []    # Refers to Array of Sprites or Planes
  130.     @tileset           = nil   # Refers to Tileset Bitmap
  131.     @autotiles         = []    # Refers to Array of Autotile Bitmaps
  132.     @map_data          = nil   # Refers to 3D Array Of Tile Settings
  133.     @flash_data        = nil   # Refers to 3D Array of Tile Flashdata
  134.     @priorities        = nil   # Refers to Tileset Priorities
  135.     @visible           = true  # Refers to Tilest Visibleness
  136.     @ox                = 0     # Bitmap Offsets        
  137.     @oy                = 0     # Bitmap Offsets
  138.     @dispose           = false # Disposed Flag
  139.     @refresh_autotiles = true  # Refresh Autotile Flag
  140.   end
  141.   #--------------------------------------------------------------------------
  142.   # * Setup
  143.   #--------------------------------------------------------------------------
  144.   def setup
  145.     # Creates Layers
  146.     @layers = []
  147.     for l in 0...3
  148.       layer = Sprite.new(@viewport)
  149.       layer.bitmap = Bitmap.new(@map_data.xsize * 32, @map_data.ysize * 32)
  150.       layer.z = l * 150
  151.       layer.zoom_x = 1.0
  152.       layer.zoom_y = 1.0
  153.       @layers << layer
  154.     end
  155.     # Update Flags
  156.     @refresh_data = nil
  157.     @zoom_x   = 1.0
  158.     @zoom_y   = 1.0
  159.     @tone     = nil
  160.     @hue      = 0
  161.     @tilesize = 32
  162.   end
  163.  
  164.   #--------------------------------------------------------------------------
  165.   # * Map Data=
  166.   #--------------------------------------------------------------------------
  167.   def map_data=(map_data)
  168.     # Save Map Data
  169.     @map_data = map_data
  170.    
  171.     setup
  172.    
  173.     # Refresh if able
  174.     begin ; refresh ; rescue ; end
  175.   end
  176.   #--------------------------------------------------------------------------
  177.   # * Dispose
  178.   #--------------------------------------------------------------------------
  179.   def dispose
  180.     # Dispose Layers (Sprites)
  181.     @layers.each { |layer| layer.dispose }
  182.     # Set Disposed Flag to True
  183.     @disposed = true
  184.   end
  185.   #--------------------------------------------------------------------------
  186.   # * Disposed?
  187.   #--------------------------------------------------------------------------
  188.   def disposed?
  189.     return @disposed
  190.   end
  191.   #--------------------------------------------------------------------------
  192.   # * Viewport
  193.   #--------------------------------------------------------------------------
  194.   def viewport
  195.     return @viewport
  196.   end
  197.   #--------------------------------------------------------------------------
  198.   # * Frame Update
  199.   #--------------------------------------------------------------------------
  200.   def update
  201.     # Set Refreshed Flag to On
  202.     needs_refresh = true
  203.     # If Map Data, Tilesize or HueChanges
  204.     if @map_data != @refresh_data
  205.       # Refresh Bitmaps
  206.       refresh
  207.       # Turns Refresh Flag to OFF
  208.       needs_refresh = false
  209.     end
  210.     # Update layer Position offsets
  211.     for layer in @layers
  212.       layer.ox = @ox
  213.       layer.oy = @oy
  214.     end
  215.     # If Refresh Autotiles, Needs Refreshed & Autotile Reset Frame
  216.     if @refresh_autotiles && needs_refresh &&
  217.        Graphics.frame_count % RPG::Cache::Animated_Autotiles_Frames == 0
  218.       # Refresh Autotiles
  219.       refresh_autotiles
  220.     end
  221.   end
  222.   #--------------------------------------------------------------------------
  223.   # * Refresh
  224.   #--------------------------------------------------------------------------
  225.   def refresh
  226.     unless priorities.nil?
  227.       # Saves Map Data & Tilesize
  228.       @refresh_data = @map_data
  229.       @hue      = 0
  230.       @tilesize = 32
  231.       # Passes Through Layers
  232.       for z in 0...@map_data.zsize
  233.         # Passes Through X Coordinates
  234.         for x in 0...@map_data.xsize
  235.           # Passes Through Z Coordinates
  236.           for y in 0...@map_data.ysize
  237.             # Collects Tile ID
  238.             id = @map_data[x, y, z]
  239.             # Skip if 0 tile
  240.             next if id == 0
  241.             # Passes Through All Priorities
  242.             for p in 0..5
  243.               # Skip If Priority Doesn't Match
  244.               next unless p == @priorities[id]
  245.               # Cap Priority to Layer 3
  246.               p = 2 if p > 2
  247.               # Draw Tile
  248.               id < 384 ? draw_autotile(x, y, p, id) : draw_tile(x, y, p, id)
  249.             end
  250.           end
  251.         end
  252.       end
  253.     end
  254.   end  
  255.   #--------------------------------------------------------------------------
  256.   # * Refresh Auto-Tiles
  257.   #--------------------------------------------------------------------------
  258.   def refresh_autotiles
  259.     # Auto-Tile Locations
  260.     autotile_locations = Table.new(@map_data.xsize, @map_data.ysize,
  261.       @map_data.zsize)
  262.     # Get X Tiles
  263.     x1 = [@ox / @tilesize - Tilemap_Options::Viewport_Padding, 0].max
  264.     x2 = [@viewport.rect.width / @tilesize +
  265.           Tilemap_Options::Viewport_Padding, @map_data.xsize].min
  266.     # Get Y Tiles
  267.     y1 = [@oy / @tilesize - Tilemap_Options::Viewport_Padding, 0].max
  268.     y2 = [@viewport.rect.height / @tilesize +
  269.           Tilemap_Options::Viewport_Padding, @map_data.ysize].min
  270.     # Passes Through Layers
  271.     for z in 0...@map_data.zsize
  272.       # Passes Through X Coordinates
  273.       for x in x1...x2
  274.         # Passes Through Y Coordinates
  275.         for y in y1...y2
  276.           # Collects Tile ID
  277.           id = @map_data[x, y, z]
  278.           # Skip if 0 tile
  279.           next if id == 0
  280.           # Skip If Non-Animated Tile
  281.           next unless @autotiles[id / 48 - 1].width / 96 > 1 if id < 384
  282.           # Get Priority
  283.           p = @priorities[id]
  284.           # Cap Priority to Layer 3
  285.           p = 2 if p > 2
  286.           # If Autotile
  287.           if id < 384
  288.             # Draw Auto-Tile
  289.             draw_autotile(x, y, p, id)
  290.             for l in (p+1)...@map_data.zsize
  291.               id_l = @map_data[x, y, l]
  292.               draw_tile(x, y, p, id_l)
  293.             end
  294.             # Save Autotile Location
  295.             autotile_locations[x, y, z] = 1
  296.           # If Normal Tile
  297.           else
  298.             # If Autotile Drawn
  299.             if autotile_locations[x, y, z] == 1
  300.               # Redraw Normal Tile
  301.               draw_tile(x, y, p, id)
  302.               # Draw Higher Tiles
  303.               for l in (p+1)...@map_data.zsize
  304.                 id_l = @map_data[x, y, l]
  305.                 draw_tile(x, y, p, id_l)
  306.               end
  307.             end
  308.           end
  309.         end
  310.       end
  311.     end
  312.   end    
  313.   #--------------------------------------------------------------------------
  314.   # * Draw Tile
  315.   #--------------------------------------------------------------------------
  316.   def draw_tile(x, y, z, id)
  317.     rect = Rect.new((id - 384) % 8 * 32, (id - 384) / 8 * 32, 32, 32)
  318.     x *= @tilesize
  319.     y *= @tilesize
  320.     if @tile_width == 32 && @tile_height == 32
  321.       @layers[z].bitmap.blt(x, y, @tileset, rect)
  322.     else
  323.       dest_rect = Rect.new(x, y, @tilesize, @tilesize)
  324.       @layers[z].bitmap.stretch_blt(dest_rect, @tileset, rect)
  325.     end
  326.   end
  327.   #--------------------------------------------------------------------------
  328.   # * Draw Auto-Tile
  329.   #--------------------------------------------------------------------------
  330.   def draw_autotile(x, y, z, tile_id)
  331.     # Gets Autotile Filename
  332.     autotile_num = tile_id / 48 - 1
  333.     # Reconfigure Tile ID
  334.     tile_id %= 48
  335.     # Gets Generated Autotile Bitmap Section
  336.     bitmap = RPG::Cache.autotile_tile(autotiles[autotile_num], tile_id, @hue)
  337.    
  338.     # Calculates Tile Coordinates
  339.     x *= @tilesize
  340.     y *= @tilesize
  341.     @layers[z].bitmap.blt(x, y, bitmap, Rect.new(0, 0, 32, 32))
  342.   end
  343.   #--------------------------------------------------------------------------
  344.   # * Collect Bitmap
  345.   #--------------------------------------------------------------------------
  346.   def bitmap
  347.     # Creates New Blank Bitmap
  348.     bitmap = Bitmap.new(@layers[0].bitmap.width, @layers[0].bitmap.height)
  349.     # Passes Through All Layers
  350.     for layer in @layers
  351.       bitmap.blt(0, 0, layer.bitmap,
  352.         Rect.new(0, 0, bitmap.width, bitmap.height))
  353.     end
  354.     # Return Bitmap
  355.     return bitmap
  356.   end
  357. end
  358.  
Expand to see the code.


Cheers,
-Charles
That's not really Glitch's script. It is almost identical to the one I did, just a slight mod of mine. Not that I really care...
SephirothSpawn wrote:
That's not really Glitch's script. It is almost identical to the one I did, just a slight mod of mine. Not that I really care...


He sent me a PM about it, and I pointed him your way. You had been working on another version of your rewrite last I had checked, and it might prove useful in this case. As a side note, he's going to have quite a bit of trouble with his goals when it comes to input, because he has two real choices: either change things, or severely limit the keys it reads from the keyboard. Not to mention the issues of reading from a game controller or mouse.

Also, it might be worth noting that Enterbrain would not like an open source clone of their copyrighted material being made, no matter what the intentions were. Differences between American and Japanese copyright law can only hold a major corporation back for so long once they take notice.
SephirothSpawn wrote:
That's not really Glitch's script. It is almost identical to the one I did, just a slight mod of mine. Not that I really care...

True. That's why I mentioned that it was an edit of yours (or at least I meant to).

Glitchfinder wrote:
Also, it might be worth noting that Enterbrain would not like an open source clone of their copyrighted material being made, no matter what the intentions were. Differences between American and Japanese copyright law can only hold a major corporation back for so long once they take notice.


I suppose Enterbrain may not like it, but that would be sorta strange. I'm not planning on rewriting the part that makes the games - just the part that plays them. And, considering that I don't intend to use any copyrighted material, I don't see what they could complain about. The end result is that people will purchase RMXP and build their games on Windows, but they'll be able to deploy them wherever they see fit - Linux, Windows, Mac, whatever. I suppose I share the same goals as vgvgf's ARGSS:
http://argss.com.ar/forums/showthread.php?tid=10

Glitchfinder wrote:
... he's going to have quite a bit of trouble with his goals when it comes to input, because he has two real choices: either change things, or severely limit the keys it reads from the keyboard. Not to mention the issues of reading from a game controller or mouse.


As for the Input module, I'll just make the extra keys available as an option. I don't want to break compatibility with existing games right from the start, so I'll do something creative... Although that might not be necessary. If the game is running on the "official" Ruby interpreter (MRI, or YARV), calls into the Windows API and dlls should work just fine - on Windows, of course. To make such games work cross platform would require taking out any scripts depending on the dll, and replace them with something that plays nicely with my version of the game engine. I'll probably just make full support for mouse and keyboard inherent with my engine, and distribute a script that switches it on.


Back to the topic of Tilemaps. I just finished rewriting Seph's script without any dependency on changing the rest of the game scripts. I'm now trying to find out why it is that the character's sprite renders on top of layer 2 and 3 when the character is below the middle of the map (on the y-axis). I think I'll sit down at some point and actually figure out how the Tilemap needs to be rendered and do a complete rewrite... but for now, this should work for testing purposes. I'm really not looking forward to it though - I've spent well over 25 hours working on this project just this weekend, and I really want to get it to a solid alpha or beta point here pretty soon. :huh:

Hopefully I'll have some good news here in little while. I have all of the data structures, Sprite/Bitmap finished, the main game loop successfully runs through a simple game, etc.

-Charles
cstrahan wrote:
Back to the topic of Tilemaps. I just finished rewriting Seph's script without any dependency on changing the rest of the game scripts. I'm now trying to find out why it is that the character's sprite renders on top of layer 2 and 3 when the character is below the middle of the map (on the y-axis). I think I'll sit down at some point and actually figure out how the Tilemap needs to be rendered and do a complete rewrite... but for now, this should work for testing purposes. I'm really not looking forward to it though - I've spent well over 25 hours working on this project just this weekend, and I really want to get it to a solid alpha or beta point here pretty soon. :huh:


Actually, that's because the player's z position changes with its y position. Check out the z-related method in Game_Character.
I need to change resolution and this tileset helps a lot!
i suggest you to join to vgvg argss http://sourceforge.net/projects/argss/ thats very advanced, is better to join forces no?.

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