RMVXA-GL - 3D graphics in RPG Maker!

RMVXA-GL
RPG Maker VX Ace OpenGL


This is a re-approach to my last attempt with using GLSL shaders in RMVXA.
The GLSL project had a number of flaws, most of it coming from that it was produced when I had little experience with desktop GL and I had very little experience with Ruby and I was more interested in hacking the Game runtime than creating a usable API.

If you are unfamiliar with my previous attempts; this project is a 3D rendering API so you can call OpenGL rendering commands and write the result to an RPG Maker bitmap.

This also supports loading an RPG Maker bitmap into an OpenGL texture, so you can load bitmaps from RPG Maker and render them in 3D.

In theory this will work with XP and VX, but VXA is what I am developing this on so it's the primary target for now.

System Requirements
Read this!
OpenGL 2.1 support is currently untested. It works with OpenGL 3.1 on NVidia, Intel and AMD GPUs, but 2.1 support is untested (However, it is implemented as best as I could without a 2.1 GPU).
These are the minimum supported GPUs:
  • AMD Radeon HD 6350 or later
  • ATI Radeon HD 2350 or later
  • NVidia GeForce 6100 or later
  • First-generation Intel Core graphics or later
Frame buffer object extension is required.

Download Alpha 2

Screen-shots
Image
Super Simple Bur!

Image
Gameboy Pixelation and Palette!

Image
3 colours per component + 1.5x zoom!

Image
Refraction shader!

Image
Spinning cube!

This is more of a try-for-your-self thing, so download the demo and have a walk around.

Demo runs slow!
The post-processing effect is choked by the snap_to_bitmap method, which is slow and is not intended for real-time (This method is usually called once for static image processing such as opening a menu or similar, this demo calls it every frame).

The character on the left will advise you to turn off "reduce screen flickering" (Basically turn of the runtime's vsync), doing that for me gives me a solid 60 FPS on my 2011 gaming PC, with it turned on gives me a solid 59 FPS. My 2012 mid-range laptop gets 15 to 45 FPS in this demo.

The actual 3D rendering is very fast; all GPU memory is allocated/destroyed at initialise/terminate so the slowest part of the rendering is uploading and downloading the texture to and from the GPU, which I actually performance tested against on-GPU memory and had very little performance difference.

TLDR: RPG Maker's snap_to_bitmap is slow, someone make me a new map rendering class so I can directly grab the bitmap as it is rendered (Or better yet, a map rendering class that renders directly to OpenGL!).

So what is this?
This will be an API for rendering 3D polygons within RPG Maker, it comes with my DLL which deals with all the OpenGL stuff and I am writing an API for using it.
It's intended for scripters who want to write 3D graphics, so if you don't script then this isn't for you.

What does this actually mean?
This API set will hopefully let us do cool stuff in RPG Maker;
  • 3D battle animations
  • 3D maps
  • 3D battlers and enemies
  • 3D battle-scenes (Like Playstation Final Fantasy titles)
  • Even faster, even cooler "Mode 7" (3D maps, again)
  • Screen-space shaders (Like in this post-processing demo)
  • Map special effects (Per-pixel lighting, bump mapping, water refraction)
  • Weather effects (Pixel shader rain, snow, heat-waves)
  • 3D menu systems (Even stuff like 3D rotating weapon icons)
  • Awesome battle transitions (FFX or FFXIII style)
The possibilities are limited only by your system requirements, so any graphical effect you can imagine is now possible.

Demo is cool, now what?
Open up the shaders folder, open the "fragment.fsh" file in a text editor like Notepad++ and perhaps modify the pixel shader to make some new post-processing effects.
To enable the debug console (Which will log your shader compile errors) uncomment line 408 in RMVXA-GL (#Lib.Console_Show) to enable the console when testing your game.
There is a crash if you output too much stuff to the console, I am working on this.



Give me feedback please.
I tried even if I knew it wouldn't work, make sure you don't call a null function. (Make a GL Version test before launching OpenGL because some people will probably redistribute this without saying it won't work with Intel Chipset x))

Image

  1. >   00000000()  Unknown
  2.     [Frames below may be incorrect and/or missing] 
  3.     RMVXA-GL.dll!67625063() Unknown
  4.     RMVXA-GL.dll!67624716() Unknown
  5.     RGSS301.dll!100faf3d()  Unknown
  6.     RGSS301.dll!10088e7a()  Unknown
  7.     RGSS301.dll!10088f08()  Unknown
  8.     RGSS301.dll!10089011()  Unknown
  9.     RGSS301.dll!1002cb45()  Unknown
  10.     RGSS301.dll!10027cc9()  Unknown
  11.     RGSS301.dll!10028049()  Unknown
  12.     RGSS301.dll!1002d01a()  Unknown
  13.     RGSS301.dll!1002e10b()  Unknown
  14.     RGSS301.dll!1002fd7b()  Unknown
  15.     RGSS301.dll!100308c0()  Unknown
  16.     RGSS301.dll!10030d10()  Unknown
  17.     RGSS301.dll!10030d3d()  Unknown
  18.     RGSS301.dll!1006a534()  Unknown
  19.     RGSS301.dll!10033e7d()  Unknown
  20.     RGSS301.dll!10027cc9()  Unknown
  21.     RGSS301.dll!10028049()  Unknown
  22.     RGSS301.dll!1002d01a()  Unknown
  23.     RGSS301.dll!1002e10b()  Unknown
  24.     RGSS301.dll!1002fd7b()  Unknown
  25.     RGSS301.dll!100300d9()  Unknown
  26.     RGSS301.dll!100303f7()  Unknown
  27.     RGSS301.dll!10027cc9()  Unknown
  28.     RGSS301.dll!10030962()  Unknown
  29.     RGSS301.dll!10030d10()  Unknown
  30.     RGSS301.dll!10030d3d()  Unknown
  31.     RGSS301.dll!1000c573()  Unknown
  32.     RGSS301.dll!1006a2d9()  Unknown
  33.     RGSS301.dll!10087c13()  Unknown
  34.     RGSS301.dll!1000c52e()  Unknown
  35.     RGSS301.dll!1000c5ee()  Unknown
  36.     RGSS301.dll!1000edc9()  Unknown
  37.     KernelBase.dll!_GetVersionExW@4()  Unknown
  38.     propsys.dll!_NdrClientCall2()  Unknown
  39.     001c48cc()  Unknown
  40.     ntdll.dll!_RegisterGuidsApiCallback@8()    Unknown
  41.     rpcrt4.dll!FreeWrapper(void *)  Unknown
  42.     00000048()  Unknown
  43.     rpcrt4.dll!LRPC_BASE_BINDING_HANDLE::FreeCallToCache(enum _LrpcCachedCallTypes,class LRPC_BASE_CCALL *) Unknown
  44.     rpcrt4.dll!LRPC_BASE_CCALL::FreeObject(void)    Unknown
  45.     rpcrt4.dll!_I_RpcFreeBuffer@4()    Unknown
  46.     rpcrt4.dll!_NdrFreeBuffer@4()  Unknown
  47.     ole32.dll!InternalVerifyStackAvailable(unsigned long Size) Line 317 C
  48.     rpcrt4.dll!_NdrClientCall2()   Unknown
  49.     KernelBase.dll!_WaitForMultipleObjectsEx@20()  Unknown
  50.     kernel32.dll!_WaitForMultipleObjectsExImplementation@20()  Unknown
  51.  
Expand to see the code.
Nuri Yuri wrote:
I tried even if I knew it wouldn't work, make sure you don't call a null function. (Make a GL Version test before launching OpenGL because some people will probably redistribute this without saying it won't work with Intel Chipset x))

http://puu.sh/cYKfJ/8f7e714631.png

  1. >   00000000()  Unknown
  2.     [Frames below may be incorrect and/or missing] 
  3.     RMVXA-GL.dll!67625063() Unknown
  4.     RMVXA-GL.dll!67624716() Unknown
  5.     RGSS301.dll!100faf3d()  Unknown
  6.     RGSS301.dll!10088e7a()  Unknown
  7.     RGSS301.dll!10088f08()  Unknown
  8.     RGSS301.dll!10089011()  Unknown
  9.     RGSS301.dll!1002cb45()  Unknown
  10.     RGSS301.dll!10027cc9()  Unknown
  11.     RGSS301.dll!10028049()  Unknown
  12.     RGSS301.dll!1002d01a()  Unknown
  13.     RGSS301.dll!1002e10b()  Unknown
  14.     RGSS301.dll!1002fd7b()  Unknown
  15.     RGSS301.dll!100308c0()  Unknown
  16.     RGSS301.dll!10030d10()  Unknown
  17.     RGSS301.dll!10030d3d()  Unknown
  18.     RGSS301.dll!1006a534()  Unknown
  19.     RGSS301.dll!10033e7d()  Unknown
  20.     RGSS301.dll!10027cc9()  Unknown
  21.     RGSS301.dll!10028049()  Unknown
  22.     RGSS301.dll!1002d01a()  Unknown
  23.     RGSS301.dll!1002e10b()  Unknown
  24.     RGSS301.dll!1002fd7b()  Unknown
  25.     RGSS301.dll!100300d9()  Unknown
  26.     RGSS301.dll!100303f7()  Unknown
  27.     RGSS301.dll!10027cc9()  Unknown
  28.     RGSS301.dll!10030962()  Unknown
  29.     RGSS301.dll!10030d10()  Unknown
  30.     RGSS301.dll!10030d3d()  Unknown
  31.     RGSS301.dll!1000c573()  Unknown
  32.     RGSS301.dll!1006a2d9()  Unknown
  33.     RGSS301.dll!10087c13()  Unknown
  34.     RGSS301.dll!1000c52e()  Unknown
  35.     RGSS301.dll!1000c5ee()  Unknown
  36.     RGSS301.dll!1000edc9()  Unknown
  37.     KernelBase.dll!_GetVersionExW@4()  Unknown
  38.     propsys.dll!_NdrClientCall2()  Unknown
  39.     001c48cc()  Unknown
  40.     ntdll.dll!_RegisterGuidsApiCallback@8()    Unknown
  41.     rpcrt4.dll!FreeWrapper(void *)  Unknown
  42.     00000048()  Unknown
  43.     rpcrt4.dll!LRPC_BASE_BINDING_HANDLE::FreeCallToCache(enum _LrpcCachedCallTypes,class LRPC_BASE_CCALL *) Unknown
  44.     rpcrt4.dll!LRPC_BASE_CCALL::FreeObject(void)    Unknown
  45.     rpcrt4.dll!_I_RpcFreeBuffer@4()    Unknown
  46.     rpcrt4.dll!_NdrFreeBuffer@4()  Unknown
  47.     ole32.dll!InternalVerifyStackAvailable(unsigned long Size) Line 317 C
  48.     rpcrt4.dll!_NdrClientCall2()   Unknown
  49.     KernelBase.dll!_WaitForMultipleObjectsEx@20()  Unknown
  50.     kernel32.dll!_WaitForMultipleObjectsExImplementation@20()  Unknown
  51.  
Expand to see the code.

Lol you scared me! I see you tried on a GL version below 3.3 (So it would have called a null function)

Testing for GL version is exactly what I'm going to do and then reporting upward to RGSS that the device cannot be supported; I don't want to introduce checks everywhere so I'm going to do a check at context creation and report with a visible error, from there it's up to the scripter to avoid calling any of the API rather than up to the API.

There's no error checking at all right now :L

EDIT: I quickly updated the demo, DL link has been replaced in first post with demo 3
  • Now errors and closes when unsupported GL version found (Thanks for the heads up Nuri)
  • RM Bitmaps are now copied by the int32, rather than int8, this means a theoretical 4x faster texture copying on the GPU (But you won't notice any speed improvements, that snap_to_bitmap is still the #1 killer)
  • Activated the SceneManager finalization modification, so the GL context will now be cleaned up properly
The demo 3 doesn't seem to detect I'm using a old OpenGL version :/
Probably you should test if the library exists and if the function exists (in the context initialization).
(Or it came from the RGSS that continued to load the other functions but didn't display me anything ^^')
Nuri Yuri wrote:
The demo 3 doesn't seem to detect I'm using a old OpenGL version :/
Probably you should test if the library exists and if the function exists (in the context initialization).
(Or it came from the RGSS that continued to load the other functions but didn't display me anything ^^')

The way GL works on windows is you have to make an old 1.4 context before making a new context, when it is 1.4 I grab the major/minor version numbers.
I tested on an old Intel and by requesting versions that don't exist yet, it was all fine this end.

I'll test if the functions I use to get version number is a nullptr too, perhaps you're on a really old GL version that doesn't even support querying the hardware??

Edit: yeah I am an idiot, the version check is gl30+! I'll change to the string test
I'm on the Intel OpenGL 2.1 but Intel is making a lot of shit with that so it has a lot of problem ^^'

I'll test the next demo if you want :3 (The verification step :d)
Wow, dude, your work is marvellous. Please don't stop it. Always wanted to link OpenGL to RM window but I never knew how.
I'll try to play with what you've released here... since my gpu can handle it very well.
My job is a bit crazy right now as I am releasing an app this week and spending 2 weeks doing R&D, so I can only work on this during weekends (of which I've had very few free).

So progress will be slow.

The next things I'll be doing:
  • Setting shader uniforms <- easy
  • Uploading meshes to GPU <- need to think about how to do a Ruby class for this, I don't want to limit the functionality
  • Drawing meshes to bitmap <- easy

Once that is done I will pull in my matrix research that I am doing for my job right now so we can transform meshes, which at that point this little project is feature complete for what I had planned, it would be then working on GL2.1 compatibility and adding bells and whistles.

EDIT: Because uniforms were easy I made a new demo that uses uniforms to animate a refraction shader;
GL33 Shaders 4
Same requirements as before, needs OpenGL 3.3 for now.
Please give this a test if you have a spare few minutes. If it works you should see this;
Image

The system requirements as as followed;
  • AMD Radeon HD 6350 or later
  • ATI Radeon HD 2350 or later
  • NVidia GeForce 6100 or later
  • First-generation Intel Core graphics or later

OpenGL 2.1 is the minimum supported version! I do not have an OpenGL 2.1 GPU on hand right now, I only have a 3.1 GPU so 3.1 is the recommended OpenGL version if you don't want anything crashing.

Your GPU must support the Frame Buffer Objects extension.
Update to your latest GPU driver, on some 2.1 systems the FBO extension will run in software mode, you will get a significant performance drop if this is the case!


This Demo uses snap_to_bitmap every-frame, this function performs horribly and requires a powerful PC if you want to maintain 60 FPS with this function!
If you want to see how this performs without snap_to_bitmap (It performs very well!) then implement the Hello Triangle tutorial below.
snap_to_bitmap is definitely the current bottleneck in this, the actual 3D rendering is blazing fast.

The Script
This script requires RMVXA-GL.dll which you can get from the demo download above.
  1. #==============================================================================
  2. # ** GL
  3. #------------------------------------------------------------------------------
  4. #  Graphics API interface.
  5. # All functions here should be used to deal with 3D rendering.
  6. # By Felix "Xilefian" Jones [Version a.1]
  7. #==============================================================================
  8. module GL
  9.   DEBUG_CONSOLE = 0 # Set to 1 to show console when debugging
  10.   #==============================================================================
  11.   # ** Texture
  12.   #------------------------------------------------------------------------------
  13.   #  GPU texture class.
  14.   #==============================================================================
  15.   class Texture
  16.     attr_reader :name, :width, :height
  17.     #--------------------------------------------------------------------------
  18.     # * Colour components
  19.     #--------------------------------------------------------------------------
  20.     R = 1
  21.     RG = 2
  22.     RGB = 3
  23.     RGBA = 4
  24.     #--------------------------------------------------------------------------
  25.     # * Allocates a texture with a given component count
  26.     #--------------------------------------------------------------------------
  27.     def self.Alloc( components, width, height )
  28.       Console::Print( "Allocating texture [#{width}, #{height}]" )
  29.       tex = new( OpenGL::GenTexture( components, width, height, 0 ) )
  30.       tex.send( :SetSize, width, height )
  31.       return tex
  32.     end
  33.     #--------------------------------------------------------------------------
  34.     # * Allocates a texture with a given bitmap
  35.     #--------------------------------------------------------------------------
  36.     def self.AllocWithBitmap( bitmap )
  37.       width = bitmap.width
  38.       height = bitmap.height
  39.       handle = bitmap.__id__
  40.      
  41.       Console::Print( "Allocating texture from Bitmap [#{width}, #{height}]" )
  42.       tex = new( OpenGL::GenTexture( 0, 0, 0, handle ) )
  43.       tex.send( :SetSize, width, height )
  44.       return tex
  45.     end
  46.     #--------------------------------------------------------------------------
  47.     # * Destroys the texture
  48.     #--------------------------------------------------------------------------
  49.     def Dealloc
  50.       if @name != 0
  51.         Console::Print( "Deallocating texture" )
  52.         OpenGL::DestroyTex( @name )
  53.         @name = 0
  54.         @width = 0
  55.         @height = 0
  56.       end
  57.     end
  58.     #--------------------------------------------------------------------------
  59.     # * Copies a bitmap into glTexture
  60.     #--------------------------------------------------------------------------
  61.     def LoadBitmap( bitmap )
  62.       OpenGL::TexSubBitmap( @name, bitmap.__id__ )
  63.     end
  64.     #--------------------------------------------------------------------------
  65.     # * Sets texture to GPU unit
  66.     #--------------------------------------------------------------------------
  67.     def BindToUnit( unit )
  68.       OpenGL::BindTextureToUnit( @name, unit )
  69.     end
  70.     #--------------------------------------------------------------------------
  71.     # * Sets the texture size (!PRIVATE!)
  72.     #--------------------------------------------------------------------------
  73.     def SetSize( width, height )
  74.       @width = width
  75.       @height = height
  76.     end
  77.     private :SetSize
  78.     #--------------------------------------------------------------------------
  79.     # * Initialize (!PRIVATE!)
  80.     #--------------------------------------------------------------------------
  81.     private_class_method :new
  82.     def initialize( name )
  83.       @name = name
  84.       @width = 0
  85.       @height = 0
  86.     end
  87.   end
  88.   #==============================================================================
  89.   # ** Shader
  90.   #------------------------------------------------------------------------------
  91.   #  Class for compiling shaders.
  92.   #==============================================================================
  93.   class Shader
  94.     attr_reader :name, :type
  95.     #--------------------------------------------------------------------------
  96.     # * Shader types
  97.     #--------------------------------------------------------------------------
  98.     VERTEX = 1
  99.     GEOMETRY = 2
  100.     FRAGMENT = 3
  101.     #--------------------------------------------------------------------------
  102.     # * Creates vertex shader
  103.     #--------------------------------------------------------------------------
  104.     def self.CreateVertex( src )
  105.       Console::Print( "Creating Vertex shader" )
  106.       shader = new( OpenGL::CreateShader( VERTEX ), VERTEX )
  107.       status = shader.send( :Compile, src )
  108.       if status != 0
  109.         shader.Dealloc
  110.         return nil
  111.       else
  112.         return shader
  113.       end
  114.     end
  115.     #--------------------------------------------------------------------------
  116.     # * Creates geometry shader
  117.     #--------------------------------------------------------------------------
  118.     def self.CreateGeometry( src )
  119.       Console::Print( "Creating Geometry shader" )
  120.       shader = new( OpenGL::CreateShader( GEOMETRY ), GEOMETRY )
  121.       status = shader.send( :Compile, src )
  122.       if status != 0
  123.         shader.Dealloc
  124.         return nil
  125.       else
  126.         return shader
  127.       end
  128.     end
  129.     #--------------------------------------------------------------------------
  130.     # * Creates fragment shader
  131.     #--------------------------------------------------------------------------
  132.     def self.CreateFragment( src )
  133.       Console::Print( "Creating Fragment shader" )
  134.       shader = new( OpenGL::CreateShader( FRAGMENT ), FRAGMENT )
  135.       status = shader.send( :Compile, src )
  136.       if status != 0
  137.         shader.Dealloc
  138.         return nil
  139.       else
  140.         return shader
  141.       end
  142.     end
  143.     #--------------------------------------------------------------------------
  144.     # * Deletes shader
  145.     #--------------------------------------------------------------------------
  146.     def Dealloc
  147.       Console::Print( "Deallocating shader" )
  148.       OpenGL::DestroyShader( @name )
  149.       @name = 0
  150.       @type = 0
  151.     end
  152.     #--------------------------------------------------------------------------
  153.     # * Compiles the shader source (!PRIVATE!)
  154.     #--------------------------------------------------------------------------
  155.     def Compile( src )
  156.       return OpenGL::ShaderCompile( @name, src )
  157.     end
  158.     private :Compile
  159.     #--------------------------------------------------------------------------
  160.     # * Initialize (!PRIVATE!)
  161.     #--------------------------------------------------------------------------
  162.     private_class_method :new
  163.     def initialize( name, type )
  164.       @name = name
  165.       @type = type
  166.     end
  167.   end
  168.   #==============================================================================
  169.   # ** ShaderMaterial
  170.   #------------------------------------------------------------------------------
  171.   #  Class for managing shader programs.
  172.   #==============================================================================
  173.   class ShaderMaterial
  174.     @@current_shader = nil
  175.     #--------------------------------------------------------------------------
  176.     # * Current bound shader handle
  177.     #--------------------------------------------------------------------------
  178.     def self.GetCurrentShader
  179.       return @@current_shader
  180.     end
  181.     #--------------------------------------------------------------------------
  182.     # * Current bound shader handle
  183.     #--------------------------------------------------------------------------
  184.     def self.SetCurrentShader( shader )
  185.       @@current_shader = shader
  186.     end
  187.     #--------------------------------------------------------------------------
  188.     # * Creates a shader program
  189.     #--------------------------------------------------------------------------
  190.     def self.Create( vertex, fragment )
  191.       Console::Print( "Creating vertex/fragment program" )
  192.       material = new( OpenGL::CreateProgam() )
  193.      
  194.       material.send( :AttachShaders, vertex, fragment, nil )
  195.      
  196.       return material
  197.     end
  198.     #--------------------------------------------------------------------------
  199.     # * Creates a shader program with a geometry shader
  200.     #--------------------------------------------------------------------------
  201.     def self.CreateWithGeometry( vertex, geometry, fragment )
  202.       Console::Print( "Creating vertex/geometry/fragment program" )
  203.       material = new( OpenGL::CreateProgam() )
  204.      
  205.       material.send( :AttachShaders, vertex, fragment, geometry )
  206.      
  207.       return material
  208.     end
  209.     #--------------------------------------------------------------------------
  210.     # * Attach Shaders
  211.     #--------------------------------------------------------------------------
  212.     def AttachShaders( vsh, fsh, gsh )
  213.       @vsh = vsh
  214.       @fsh = fsh
  215.       @gsh = gsh
  216.     end
  217.     #--------------------------------------------------------------------------
  218.     # * Destroys this program
  219.     #--------------------------------------------------------------------------
  220.     def Dealloc
  221.       Console::Print( "Deallocating program" )
  222.       OpenGL::DestroyProg( @name )
  223.       @name = 0
  224.       @vsh = nil
  225.       @gsh = nil
  226.       @fsh = nil
  227.       @uniformMap = nil
  228.       @uniLocationMap = nil
  229.     end
  230.     #--------------------------------------------------------------------------
  231.     # * Activates this shader for rendering
  232.     #--------------------------------------------------------------------------
  233.     def UseProgram
  234.       ShaderMaterial.SetCurrentShader( self )
  235.      
  236.       if @isLinked == false
  237.         status = self.send( :Link )
  238.         if status != 0
  239.           self.Dealloc
  240.           return
  241.         end
  242.         @isLinked = true
  243.       end
  244.      
  245.       # Use program
  246.       OpenGL::UseProgram( @name )
  247.      
  248.       # Update uniforms
  249.       self.UploadUniforms
  250.     end
  251.     #--------------------------------------------------------------------------
  252.     # * Uploads Uniforms to current shader
  253.     #--------------------------------------------------------------------------
  254.     def UploadUniforms
  255.       @uniformMap.each do |uniformName, value|
  256.         case value
  257.           when Float
  258.             OpenGL::SetUniform1f( uniformName, [value] )
  259.           when Integer
  260.             OpenGL::SetUniform1i( uniformName, value )
  261.           when Array
  262.             # Check first value of array, assume that is what we are uploading
  263.             case value.count
  264.               when 1
  265.                 case value[0]
  266.                   when Float
  267.                     OpenGL::SetUniform1f( uniformName, value )
  268.                   when Integer
  269.                     OpenGL::SetUniform1i( uniformName, value )
  270.                 end
  271.               when 2
  272.                 case value[0]
  273.                   when Float
  274.                     OpenGL::SetUniform2f( uniformName, value )
  275.                   when Integer
  276.                     OpenGL::SetUniform2i( uniformName, value )
  277.                   when Matrix
  278.                     case value[1]
  279.                       when 2
  280.                         value[0].UploadMatrix2( uniformName )
  281.                       when 3
  282.                         value[0].UploadMatrix3( uniformName )
  283.                       when 4
  284.                         value[0].UploadMatrix4( uniformName )
  285.                     end
  286.                 end
  287.               when 3
  288.                 case value[0]
  289.                   when Float
  290.                     OpenGL::SetUniform3f( uniformName, value )
  291.                   when Integer
  292.                     OpenGL::SetUniform3i( uniformName, value )
  293.                 end
  294.               when 4
  295.                 case value[0]
  296.                   when Float
  297.                     OpenGL::SetUniform4f( uniformName, value )
  298.                   when Integer
  299.                     OpenGL::SetUniform4i( uniformName, value )
  300.                 end
  301.             end
  302.         end
  303.       end
  304.      
  305.       @uniformMap.clear
  306.     end
  307.     #--------------------------------------------------------------------------
  308.     # * Sets a program uniform to a value
  309.     #--------------------------------------------------------------------------
  310.     def SetUniform( uniformName, value )
  311.       if @isLinked == false
  312.         status = self.send( :Link )
  313.         if status != 0
  314.           self.Dealloc
  315.           return
  316.         end
  317.         @isLinked = true
  318.       end
  319.      
  320.       if @uniLocationMap[uniformName] == nil
  321.         intVal = OpenGL::GetUniformLocation( @name, uniformName )
  322.         Console::Print( "Found uniform #{uniformName} == #{intVal}" )
  323.        
  324.         @uniLocationMap[uniformName] = intVal
  325.       else
  326.         intVal = @uniLocationMap[uniformName]
  327.       end
  328.      
  329.       @uniformMap[intVal] = value
  330.      
  331.       if ShaderMaterial.GetCurrentShader() == self
  332.         self.UploadUniforms
  333.       end
  334.     end
  335.     #--------------------------------------------------------------------------
  336.     # * Sets a program uniform to a mat2
  337.     #--------------------------------------------------------------------------
  338.     def SetUniformMatrix2( uniformName, matrix )
  339.       if @uniLocationMap[uniformName] == nil
  340.         intVal = OpenGL::GetUniformLocation( @name, uniformName )
  341.        
  342.         @uniLocationMap[uniformName] = intVal
  343.       else
  344.         intVal = @uniLocationMap[uniformName]
  345.       end
  346.      
  347.       @uniformMap[intVal] = [matrix, 2]
  348.      
  349.       if ShaderMaterial.GetCurrentShader() == self
  350.         self.UploadUniforms
  351.       end
  352.     end
  353.     #--------------------------------------------------------------------------
  354.     # * Sets a program uniform to a mat3
  355.     #--------------------------------------------------------------------------
  356.     def SetUniformMatrix3( uniformName, matrix )
  357.       if @uniLocationMap[uniformName] == nil
  358.         intVal = OpenGL::GetUniformLocation( @name, uniformName )
  359.        
  360.         @uniLocationMap[uniformName] = intVal
  361.       else
  362.         intVal = @uniLocationMap[uniformName]
  363.       end
  364.      
  365.       @uniformMap[intVal] = [matrix, 3]
  366.      
  367.       if ShaderMaterial.GetCurrentShader() == self
  368.         self.UploadUniforms
  369.       end
  370.     end
  371.     #--------------------------------------------------------------------------
  372.     # * Sets a program uniform to a mat4
  373.     #--------------------------------------------------------------------------
  374.     def SetUniformMatrix4( uniformName, matrix )
  375.       if @uniLocationMap[uniformName] == nil
  376.         intVal = OpenGL::GetUniformLocation( @name, uniformName )
  377.        
  378.         @uniLocationMap[uniformName] = intVal
  379.       else
  380.         intVal = @uniLocationMap[uniformName]
  381.       end
  382.      
  383.       @uniformMap[intVal] = [matrix, 4]
  384.      
  385.       if ShaderMaterial.GetCurrentShader() == self
  386.         self.UploadUniforms
  387.       end
  388.     end
  389.     #--------------------------------------------------------------------------
  390.     # * Sets a program attribute to an index
  391.     #--------------------------------------------------------------------------
  392.     def SetAttributeIndex( attribStr, index )
  393.       if @isLinked == true
  394.         Console::Print( "ERROR - Tried to set attribute location of linked shader!" )
  395.         Console::Print( "- Call .SetAttributeIndex BEFORE linking program!" )
  396.         return
  397.       end
  398.      
  399.       Console::Print( "Setting attribute #{attribStr} to #{index}" )
  400.       OpenGL::BindAttribLocation( @name, index, attribStr )
  401.     end
  402.     #--------------------------------------------------------------------------
  403.     # * Links shaders to this program (!PRIVATE!)
  404.     #--------------------------------------------------------------------------
  405.     def Link
  406.       if @gsh
  407.         return OpenGL::ProgLink( @name, @vsh.name, @gsh.name, @fsh.name )
  408.       else
  409.         return OpenGL::ProgLink( @name, @vsh.name, 0, @fsh.name )
  410.       end
  411.     end
  412.     private :Link
  413.     private :AttachShaders
  414.     #--------------------------------------------------------------------------
  415.     # * Initialize (!PRIVATE!)
  416.     #--------------------------------------------------------------------------
  417.     private_class_method :new
  418.     def initialize( name )
  419.       @name = name
  420.       @vsh = nil
  421.       @gsh = nil
  422.       @fsh = nil
  423.       @isLinked = false
  424.       @uniformMap = Hash.new
  425.       @uniLocationMap = Hash.new
  426.     end
  427.   end
  428.   #==============================================================================
  429.   # ** VertexBuffer
  430.   #------------------------------------------------------------------------------
  431.   #  Class for uploading vertex data to the GPU.
  432.   #==============================================================================
  433.   class VertexBuffer
  434.     #--------------------------------------------------------------------------
  435.     # * Draw Modes
  436.     #--------------------------------------------------------------------------
  437.     DRAW_POINTS = 1 # Point cloud
  438.     DRAW_LINES = 2 # Pairs of verts = line
  439.     DRAW_LINE_STRIP = 3 # Verts = line path
  440.     DRAW_LINE_LOOP = 4 # Verts = line path, ending back at first
  441.     DRAW_TRIANGLES = 5 # 3 verts = triangle
  442.     DRAW_TRIANGLE_STRIP = 6 # Each new vert makes a triangle from the last two
  443.     DRAW_TRIANGLE_FAN = 7 # Each new vert makes a traingle from last + first
  444.     #--------------------------------------------------------------------------
  445.     # * Creates the GPU VBO
  446.     #--------------------------------------------------------------------------
  447.     def self.Alloc
  448.       Console::Print( "Allocating VertexBuffer" )
  449.       return new
  450.     end
  451.     #--------------------------------------------------------------------------
  452.     # * Deletes the GPU handles for this VBO
  453.     #--------------------------------------------------------------------------
  454.     def Dealloc
  455.       Console::Print( "Deallocating VertexBuffer" )
  456.       OpenGL::DestroyVBO( @name )
  457.     end
  458.     #--------------------------------------------------------------------------
  459.     # * Updates this VBO and then renders it
  460.     #--------------------------------------------------------------------------
  461.     def DrawArrays( drawMode )
  462.       OpenGL::BindVBO( @name )
  463.      
  464.       if @vertexArray
  465.         OpenGL::VBOData( @vertexArray );
  466.        
  467.         @vertexArray = nil
  468.       end
  469.            
  470.       index = 0
  471.       offset = 0
  472.       @description.each do |arg|
  473.         OpenGL::VBOAttrib( index, arg, @stride, offset )
  474.        
  475.         offset += arg
  476.         index += 1
  477.       end
  478.      
  479.       OpenGL::DrawVBO( drawMode, @vertexCount )
  480.     end
  481.     #--------------------------------------------------------------------------
  482.     # * Sets how the buffer should be read
  483.     # * eg: vbo.DescribeBuffer( 3, [3, 2, 4] ) # 3 verts = vec3, vec2, vec4
  484.     #--------------------------------------------------------------------------
  485.     def DescribeBuffer( vertexCount, args )
  486.       @stride = 0
  487.       args.each { |a| @stride += a }
  488.      
  489.       @vertexCount = vertexCount
  490.       @description = args
  491.     end
  492.     #--------------------------------------------------------------------------
  493.     # * Uploads a given vertex array to this buffer object
  494.     #--------------------------------------------------------------------------
  495.     def UploadVertexArray( vertexArray )
  496.       @vertexArray = vertexArray.flatten
  497.     end
  498.     #--------------------------------------------------------------------------
  499.     # * Initialize (!PRIVATE!)
  500.     #--------------------------------------------------------------------------
  501.     private_class_method :new
  502.     def initialize
  503.       @name = OpenGL::GenVBO()
  504.       @stride = 0
  505.       @vertexCount = 0
  506.       @vertexArray = nil
  507.       @description = nil
  508.     end
  509.   end
  510.   #==============================================================================
  511.   # ** FrameBuffer
  512.   #------------------------------------------------------------------------------
  513.   #  Class for creating frame buffers to render to.
  514.   #==============================================================================
  515.   class FrameBuffer
  516.     attr_reader :name, :width, :height
  517.     #--------------------------------------------------------------------------
  518.     # * Clear Modes
  519.     #--------------------------------------------------------------------------
  520.     Clear = 1
  521.     #--------------------------------------------------------------------------
  522.     # * Creates the GPU FB with no attachments
  523.     #--------------------------------------------------------------------------
  524.     def self.Alloc( width, height )
  525.       Console::Print( "Allocating FrameBuffer [#{width}, #{height}]" )
  526.       return new( width, height )
  527.     end
  528.     #--------------------------------------------------------------------------
  529.     # * Deletes the GPU handles for this FBO
  530.     #--------------------------------------------------------------------------
  531.     def Dealloc
  532.       Console::Print( "Deallocating FrameBuffer" )
  533.       OpenGL::DestroyFBO( @name )
  534.       @width = 0
  535.       @height = 0
  536.       @colourAttachment0 = nil
  537.       @name = 0
  538.     end
  539.     #--------------------------------------------------------------------------
  540.     # * Copies a frame buffer contents into bitmap
  541.     #--------------------------------------------------------------------------
  542.     def ToBitmap( bitmap )
  543.       OpenGL::GetTexImage( @name, bitmap.__id__ )
  544.     end
  545.     #--------------------------------------------------------------------------
  546.     # * Attaches a texture to this FBO
  547.     #--------------------------------------------------------------------------
  548.     def AttachTexture( texture )
  549.       if texture.width != @width || texture.height != @height
  550.         message = "Expected size [#{@width}, #{@height}] " <<
  551.         "given size [#{texture.width}, #{texture.height}]"
  552.        
  553.         Console::Print( "FrameBuffer attach failure!" )
  554.         Console::Print( message )
  555.       else
  556.         oldAttachment = @colourAttachment0
  557.         @colourAttachment0 = texture
  558.         Console::Print( "Attaching Texture to FrameBuffer" )
  559.         OpenGL::FBOTexure( @name, texture.name )
  560.         if oldAttachment != nil
  561.           return oldAttachment
  562.         end          
  563.       end
  564.     end
  565.     #--------------------------------------------------------------------------
  566.     # * Test method for rendering to FBO
  567.     #--------------------------------------------------------------------------
  568.     def DrawShader( shader )
  569.       shader.UseProgram
  570.       OpenGL::DrawToFBO( @name )
  571.     end
  572.     #--------------------------------------------------------------------------
  573.     # * Makes this FBO the render target
  574.     #--------------------------------------------------------------------------
  575.     def Bind( willClear = 0 )
  576.       OpenGL::BindFBO( @name )
  577.       if willClear == 1
  578.         OpenGL::Clear()
  579.       end
  580.     end
  581.     #--------------------------------------------------------------------------
  582.     # * Initialize (!PRIVATE!)
  583.     #--------------------------------------------------------------------------
  584.     private_class_method :new
  585.     def initialize( width, height )
  586.       @width = width
  587.       @height = height
  588.       @colourAttachment0 = nil
  589.       @name = OpenGL::GenFBO()
  590.     end
  591.   end
  592.   #==============================================================================
  593.   # ** OpenGL
  594.   #------------------------------------------------------------------------------
  595.   #  OpenGL management.
  596.   # Object life-time for 3D elements managed here.
  597.   #==============================================================================
  598.   class OpenGL
  599.     #--------------------------------------------------------------------------
  600.     # * Starts up the Graphics interface
  601.     #--------------------------------------------------------------------------
  602.     def initialize
  603.       initStatus = Lib.XGL_Init
  604.      
  605.       case initStatus
  606.         when 1
  607.           SceneManager.exit_error( "Unsupported GL version\nOpenGL 2.1 Required" )
  608.         when 2
  609.           SceneManager.exit_error( "Missing extension FrameBufferObject" )
  610.       end
  611.     end
  612.     #--------------------------------------------------------------------------
  613.     # * Clears current buffer
  614.     #--------------------------------------------------------------------------
  615.     def self.Clear
  616.       Lib.Graphics_Clear()
  617.     end
  618.     #--------------------------------------------------------------------------
  619.     # * Create a glTexImage
  620.     #--------------------------------------------------------------------------
  621.     def self.DestroyTex( texName )
  622.       Lib.Graphics_DestroyTex( texName )
  623.     end
  624.     #--------------------------------------------------------------------------
  625.     # * Create a glTexImage
  626.     #--------------------------------------------------------------------------
  627.     def self.GenTexture( components, width, height, bmpHandle )
  628.       return Lib.Graphics_GenTexture( components, width, height, bmpHandle )
  629.     end
  630.     #--------------------------------------------------------------------------
  631.     # * Loads a bitmap into a glTexImage
  632.     #--------------------------------------------------------------------------
  633.     def self.TexSubBitmap( texName, bmpHandle )
  634.       return Lib.Graphics_TexSubBitmap( texName, bmpHandle )
  635.     end
  636.     #--------------------------------------------------------------------------
  637.     # * Dumps a glTexImage into a bitmap
  638.     #--------------------------------------------------------------------------
  639.     def self.GetTexImage( texName, bmpHandle )
  640.       return Lib.Graphics_GetTexImage( texName, bmpHandle )
  641.     end
  642.     #--------------------------------------------------------------------------
  643.     # * Creates a new FBO
  644.     #--------------------------------------------------------------------------
  645.     def self.GenFBO
  646.       return Lib.Graphics_GenFBO
  647.     end
  648.     #--------------------------------------------------------------------------
  649.     # * Creates a new FBO
  650.     #--------------------------------------------------------------------------
  651.     def self.DestroyFBO( fboName )
  652.       Lib.Graphics_DestroyFBO( fboName )
  653.     end
  654.     #--------------------------------------------------------------------------
  655.     # * Attaches texture to FBO
  656.     #--------------------------------------------------------------------------
  657.     def self.FBOTexure( fboName, texName )
  658.       Lib.Graphics_FBOTexure( fboName, texName )
  659.     end
  660.     #--------------------------------------------------------------------------
  661.     # * Creates a new shader of given type
  662.     #--------------------------------------------------------------------------
  663.     def self.CreateShader( shaderType )
  664.       return Lib.Graphics_CreateShader( shaderType )
  665.     end
  666.     #--------------------------------------------------------------------------
  667.     # * Deletes glShader
  668.     #--------------------------------------------------------------------------
  669.     def self.DestroyShader( shaderName )
  670.       Lib.Graphics_DestroyShader( shaderName )
  671.     end
  672.     #--------------------------------------------------------------------------
  673.     # * Compiles shader source and returns the result
  674.     #--------------------------------------------------------------------------
  675.     def self.ShaderCompile( shaderName, src )
  676.       return Lib.Graphics_ShaderCompile( shaderName, src )
  677.     end
  678.     #--------------------------------------------------------------------------
  679.     # * Creates a shader program
  680.     #--------------------------------------------------------------------------
  681.     def self.CreateProgam
  682.       return Lib.Graphics_CreateProgam
  683.     end
  684.     #--------------------------------------------------------------------------
  685.     # * Links shaders to this program
  686.     #--------------------------------------------------------------------------
  687.     def self.ProgLink( progName, vsh, gsh, fsh )
  688.       return Lib.Graphics_ProgLink( progName, vsh, gsh, fsh )
  689.     end
  690.     #--------------------------------------------------------------------------
  691.     # * Deletes a shader program
  692.     #--------------------------------------------------------------------------
  693.     def self.DestroyProg( progName )
  694.       return Lib.Graphics_DestroyProg( progName )
  695.     end
  696.     #--------------------------------------------------------------------------
  697.     # * Deletes a shader program
  698.     #--------------------------------------------------------------------------
  699.     def self.GetUniformLocation( progName, uniString )
  700.       return Lib.Graphics_UniformLocation( progName,  uniString )
  701.     end
  702.     #--------------------------------------------------------------------------
  703.     # * Draws texName to fboName using progName
  704.     #--------------------------------------------------------------------------
  705.     def self.DrawToFBO( fboName )
  706.       Lib.Graphics_DrawToFBO( fboName )
  707.     end
  708.     #--------------------------------------------------------------------------
  709.     # * Sets program uniform value at location
  710.     #--------------------------------------------------------------------------
  711.     def self.SetUniform1f( name, args )
  712.       larr = args.pack("f").unpack("l")
  713.       Lib.Graphics_Uniform1f( name, larr[0] )
  714.     end
  715.     #--------------------------------------------------------------------------
  716.     # * Sets program uniform value at location
  717.     #--------------------------------------------------------------------------
  718.     def self.SetUniform2f( name, args )
  719.       larr = args.pack( "ff" ).unpack( "ll" )
  720.       Lib.Graphics_Uniform2f( name, larr[0], larr[1] )
  721.     end
  722.     #--------------------------------------------------------------------------
  723.     # * Sets program uniform value at location
  724.     #--------------------------------------------------------------------------
  725.     def self.SetUniform3f( name, args )
  726.       larr = args.pack( "fff" ).unpack( "lll" )
  727.       Lib.Graphics_Uniform3f( name, larr[0], larr[1], larr[2] )
  728.     end
  729.     #--------------------------------------------------------------------------
  730.     # * Sets program uniform value at location
  731.     #--------------------------------------------------------------------------
  732.     def self.SetUniform4f( name, args )
  733.       larr = args.pack( "ffff" ).unpack( "llll" )
  734.       Lib.Graphics_Uniform4f( name, larr [0], larr [1], larr[2], larr[3] )
  735.     end
  736.     #--------------------------------------------------------------------------
  737.     # * Sets program uniform value at location
  738.     #--------------------------------------------------------------------------
  739.     def self.SetUniform1i( name, args )
  740.       Lib.Graphics_Uniform1i( name, args )
  741.     end
  742.     #--------------------------------------------------------------------------
  743.     # * Sets program uniform value at location
  744.     #--------------------------------------------------------------------------
  745.     def self.SetUniform2i( name, args )
  746.       Lib.Graphics_Uniform2i( name, args[0], args[1] )
  747.     end
  748.     #--------------------------------------------------------------------------
  749.     # * Sets program uniform value at location
  750.     #--------------------------------------------------------------------------
  751.     def self.SetUniform3i( name, args )
  752.       Lib.Graphics_Uniform3i( name, args[0], args[1], args[2] )
  753.     end
  754.     #--------------------------------------------------------------------------
  755.     # * Sets program uniform value at location
  756.     #--------------------------------------------------------------------------
  757.     def self.SetUniform4i( name, args )
  758.       Lib.Graphics_Uniform4i( name, args[0], args[1], args[2], args[3])
  759.     end
  760.     #--------------------------------------------------------------------------
  761.     # * Activates a shader program for usage (And modifying)
  762.     #--------------------------------------------------------------------------
  763.     def self.UseProgram( shaderName )
  764.       Lib.Graphics_UseProgram( shaderName )
  765.     end
  766.     #--------------------------------------------------------------------------
  767.     # * Binds (and activates) a texture to a given unit
  768.     #--------------------------------------------------------------------------
  769.     def self.BindTextureToUnit( textureName, unitIndex )
  770.       Lib.Graphics_BindTexUnit( textureName, unitIndex )
  771.     end
  772.     #--------------------------------------------------------------------------
  773.     # * Creats a new VBO (Must be destroyed!)
  774.     #--------------------------------------------------------------------------
  775.     def self.GenVBO
  776.       return Lib.Graphics_GenVBO
  777.     end
  778.     #--------------------------------------------------------------------------
  779.     # * Destroys a VBO
  780.     #--------------------------------------------------------------------------
  781.     def self.DestroyVBO( vboName )
  782.       Lib.Graphics_DestroyVBO( vboName )
  783.     end
  784.     #--------------------------------------------------------------------------
  785.     # * Binds a VBO (Making it current)
  786.     #--------------------------------------------------------------------------
  787.     def self.BindVBO( vboName )
  788.       Lib.Graphics_BindVBO( vboName )
  789.     end
  790.     #--------------------------------------------------------------------------
  791.     # * Uploads the vertex data for current VBO
  792.     #--------------------------------------------------------------------------
  793.     def self.VBOData( floatArray )
  794.       stringPacker = "f" * floatArray.length
  795.       floatString = floatArray.pack( stringPacker )
  796.  
  797.       Lib.Graphics_VBOData( floatString, floatArray.length )
  798.     end
  799.     #--------------------------------------------------------------------------
  800.     # * Applies the attribute data for current VBO
  801.     #--------------------------------------------------------------------------
  802.     def self.VBOAttrib( index, components, stride, offset )
  803.       Lib.Graphics_VBOAttrib( index, components, stride, offset )
  804.     end
  805.     #--------------------------------------------------------------------------
  806.     # * Draws the current VBO
  807.     #--------------------------------------------------------------------------
  808.     def self.DrawVBO( mode, count )
  809.       Lib.Graphics_DrawVBO( mode, count )
  810.     end
  811.     #--------------------------------------------------------------------------
  812.     # * Draws the current VBO
  813.     #--------------------------------------------------------------------------
  814.     def self.BindAttribLocation( shaderName, index, attribStr )
  815.       Lib.Graphics_BindAttribLocation( shaderName, index, attribStr )
  816.     end
  817.     #--------------------------------------------------------------------------
  818.     # * Binds a FBO (Target render buffer)
  819.     #--------------------------------------------------------------------------
  820.     def self.BindFBO( fboName )
  821.       Lib.Graphics_BindFBO( fboName )
  822.     end
  823.   end
  824.   #==============================================================================
  825.   # ** Matrix
  826.   #------------------------------------------------------------------------------
  827.   #  Manipulates and uploads matrices
  828.   #==============================================================================
  829.   class Matrix
  830.     #--------------------------------------------------------------------------
  831.     # * Wrapper for Matrix.new
  832.     #--------------------------------------------------------------------------
  833.     def self.Alloc
  834.       matrix = new()
  835.       matrix.Push
  836.       return matrix
  837.     end
  838.     #--------------------------------------------------------------------------
  839.     # * Pushes an identity matrix to the top
  840.     #--------------------------------------------------------------------------
  841.     def Push
  842.       Lib.Matrix_Push( @name )
  843.     end
  844.     #--------------------------------------------------------------------------
  845.     # * Removes the top matrix
  846.     #--------------------------------------------------------------------------
  847.     def Pop
  848.       Lib.Matrix_Pop( @name )
  849.     end
  850.     #--------------------------------------------------------------------------
  851.     # * Uploads the top matrix to the current shader's mat2 at location
  852.     #--------------------------------------------------------------------------
  853.     def UploadMatrix2( location )
  854.       Lib.Matrix_UploadMatrix2( @name, location )
  855.     end
  856.     #--------------------------------------------------------------------------
  857.     # * Uploads the top matrix to the current shader's mat3 at location
  858.     #--------------------------------------------------------------------------
  859.     def UploadMatrix3( location )
  860.       Lib.Matrix_UploadMatrix3( @name, location )
  861.     end
  862.     #--------------------------------------------------------------------------
  863.     # * Uploads the top matrix to the current shader's mat4 at location
  864.     #--------------------------------------------------------------------------
  865.     def UploadMatrix4( location )
  866.       Lib.Matrix_UploadMatrix4( @name, location )
  867.     end
  868.     #--------------------------------------------------------------------------
  869.     # * Translates the matrix
  870.     #--------------------------------------------------------------------------
  871.     def Translate( x, y, z )
  872.       larr = [x, y, z].pack("fff").unpack("lll")
  873.       Lib.Matrix_Translate( @name, larr[0], larr[1], larr[2] )
  874.     end
  875.     #--------------------------------------------------------------------------
  876.     # * Scales the matrix
  877.     #--------------------------------------------------------------------------
  878.     def Scale( x, y, z )
  879.       larr = [x, y, z].pack("fff").unpack("lll")
  880.       Lib.Matrix_Scale( @name, larr[0], larr[1], larr[2] )
  881.     end
  882.     #--------------------------------------------------------------------------
  883.     # * Rotates the matrix in the X axis by radian
  884.     #--------------------------------------------------------------------------
  885.     def RotateX( radian )
  886.       larr = [radian].pack("f").unpack("l")
  887.       Lib.Matrix_RotateX( @name, larr[0] )
  888.     end
  889.     #--------------------------------------------------------------------------
  890.     # * Rotates the matrix in the Y axis by radian
  891.     #--------------------------------------------------------------------------
  892.     def RotateY( radian )
  893.       larr = [radian].pack("f").unpack("l")
  894.       Lib.Matrix_RotateY( @name, larr[0] )
  895.     end
  896.     #--------------------------------------------------------------------------
  897.     # * Rotates the matrix in the Z axis by radian
  898.     #--------------------------------------------------------------------------
  899.     def RotateZ( radian )
  900.       larr = [radian].pack("f").unpack("l")
  901.       Lib.Matrix_RotateZ( @name, larr[0] )
  902.     end
  903.     #--------------------------------------------------------------------------
  904.     # * Destroys the matrix
  905.     #--------------------------------------------------------------------------
  906.     def Dealloc
  907.       Lib.Matrix_Destroy( @name )
  908.     end
  909.     #--------------------------------------------------------------------------
  910.     # * Creates the matrix handle
  911.     #--------------------------------------------------------------------------
  912.     private_class_method :new
  913.     def initialize
  914.       @name = Lib.Matrix_Create()
  915.     end
  916.   end
  917.   #==============================================================================
  918.   # ** Console
  919.   #------------------------------------------------------------------------------
  920.   #  Debug console, feel free to ignore.
  921.   #==============================================================================
  922.   class Console
  923.     #--------------------------------------------------------------------------
  924.     # * When in test mode this will show the console
  925.     #--------------------------------------------------------------------------
  926.     def initialize
  927.       if $TEST && DEBUG_CONSOLE == 1
  928.         Lib.Console_Show
  929.       end
  930.     end
  931.     #--------------------------------------------------------------------------
  932.     # * Prints debug text
  933.     #--------------------------------------------------------------------------
  934.     def self.Print( str )
  935.       return Lib.Console_Print( "[RMVXA-GL] #{str}" )
  936.     end
  937.   end
  938.   #==============================================================================
  939.   # ** Lib
  940.   #------------------------------------------------------------------------------
  941.   #  DLL library interface here.
  942.   # This should generally be considered private.
  943.   #==============================================================================
  944.   module Lib
  945.     #--------------------------------------------------------------------------
  946.     # * Library API methods
  947.     #--------------------------------------------------------------------------
  948.     def self.XGL_Init( *args );return @@XGL_Init.call( *args );end
  949.     def self.XGL_Terminate( *args );return @@XGL_Terminate.call( *args );end
  950.      
  951.     def self.Console_Show( *args );return @@Console_Show.call( *args );end
  952.     def self.Console_Hide( *args );return @@Console_Hide.call( *args );end
  953.     def self.Console_Print( *args );return @@Console_Print.call( *args );end
  954.    
  955.     def self.Graphics_Clear( *args );return @@Graphics_Clear.call( *args );end
  956.      
  957.     def self.Graphics_GenTexture( *args );return @@Graphics_GenTexture.call( *args );end
  958.     def self.Graphics_TexSubBitmap( *args );return @@Graphics_TexSubBitmap.call( *args );end
  959.     def self.Graphics_DestroyTex( *args );return @@Graphics_DestroyTex.call( *args );end
  960.     def self.Graphics_BindTexUnit( *args );return @@Graphics_BindTexUnit.call( *args );end
  961.      
  962.     def self.Graphics_GenFBO( *args );return @@Graphics_GenFBO.call( *args );end
  963.     def self.Graphics_FBOTexure( *args );return @@Graphics_FBOTexure.call( *args );end
  964.     def self.Graphics_GetTexImage( *args );return @@Graphics_GetTexImage.call( *args );end
  965.     def self.Graphics_DestroyFBO( *args );return @@Graphics_DestroyFBO.call( *args );end
  966.     def self.Graphics_BindFBO( *args );return @@Graphics_BindFBO.call( *args );end
  967.      
  968.     def self.Graphics_CreateShader( *args );return @@Graphics_CreateShader.call( *args );end
  969.     def self.Graphics_DestroyShader( *args );return @@Graphics_DestroyShader.call( *args );end
  970.     def self.Graphics_ShaderCompile( *args );return @@Graphics_ShaderCompile.call( *args );end
  971.      
  972.     def self.Graphics_CreateProgam( *args );return @@Graphics_CreateProgam.call( *args );end
  973.     def self.Graphics_ProgLink( *args );return @@Graphics_ProgLink.call( *args );end
  974.     def self.Graphics_DestroyProg( *args );return @@Graphics_DestroyProg.call( *args );end
  975.     def self.Graphics_UniformLocation( *args );return @@Graphics_UniformLocation.call( *args );end
  976.    
  977.     def self.Graphics_Uniform1f( *args );return @@Graphics_Uniform1f.call( *args );end
  978.     def self.Graphics_Uniform2f( *args );return @@Graphics_Uniform2f.call( *args );end
  979.     def self.Graphics_Uniform3f( *args );return @@Graphics_Uniform3f.call( *args );end
  980.     def self.Graphics_Uniform4f( *args );return @@Graphics_Uniform4f.call( *args );end
  981.    
  982.     def self.Graphics_Uniform1i( *args );return @@Graphics_Uniform1i.call( *args );end
  983.     def self.Graphics_Uniform2i( *args );return @@Graphics_Uniform2i.call( *args );end
  984.     def self.Graphics_Uniform3i( *args );return @@Graphics_Uniform3i.call( *args );end
  985.     def self.Graphics_Uniform4i( *args );return @@Graphics_Uniform4i.call( *args );end
  986.    
  987.     def self.Graphics_Uniform1ui( *args );return @@Graphics_Uniform1ui.call( *args );end
  988.     def self.Graphics_Uniform2ui( *args );return @@Graphics_Uniform2ui.call( *args );end
  989.     def self.Graphics_Uniform3ui( *args );return @@Graphics_Uniform3ui.call( *args );end
  990.     def self.Graphics_Uniform4ui( *args );return @@Graphics_Uniform4ui.call( *args );end
  991.      
  992.     def self.Graphics_UseProgram( *args );return @@Graphics_UseProgram.call( *args );end
  993.     def self.Graphics_BindAttribLocation( *args );return @@Graphics_BindAttribLocation.call( *args );end
  994.      
  995.     def self.Graphics_GenVBO( *args );return @@Graphics_GenVBO.call( *args );end
  996.     def self.Graphics_DestroyVBO( *args );return @@Graphics_DestroyVBO.call( *args );end
  997.     def self.Graphics_BindVBO( *args );return @@Graphics_BindVBO.call( *args );end
  998.     def self.Graphics_VBOData( *args );return @@Graphics_VBOData.call( *args );end
  999.     def self.Graphics_VBOAttrib( *args );return @@Graphics_VBOAttrib.call( *args );end
  1000.     def self.Graphics_DrawVBO( *args );return @@Graphics_DrawVBO.call( *args );end
  1001.      
  1002.     def self.Matrix_Create( *args );return @@Matrix_Create.call( *args );end
  1003.     def self.Matrix_Destroy( *args );return @@Matrix_Destroy.call( *args );end
  1004.      
  1005.     def self.Matrix_Pop( *args );return @@Matrix_Pop.call( *args );end
  1006.     def self.Matrix_Push( *args );return @@Matrix_Push.call( *args );end
  1007.     def self.Matrix_Size( *args );return @@Matrix_Size.call( *args );end
  1008.      
  1009.     def self.Matrix_UploadMatrix2( *args );return @@Matrix_UploadMatrix2.call( *args );end
  1010.     def self.Matrix_UploadMatrix3( *args );return @@Matrix_UploadMatrix3.call( *args );end
  1011.     def self.Matrix_UploadMatrix4( *args );return @@Matrix_UploadMatrix4.call( *args );end
  1012.      
  1013.     def self.Matrix_LoadMatrix4( *args );return @@Matrix_LoadMatrix4.call( *args );end
  1014.     def self.Matrix_MultiplyMatrix4( *args );return @@Matrix_MultiplyMatrix4.call( *args );end
  1015.     def self.Matrix_MultiplyMatrixStack( *args );return @@Matrix_MultiplyMatrixStack.call( *args );end
  1016.     def self.Matrix_Rotate( *args );return @@Matrix_Rotate.call( *args );end
  1017.     def self.Matrix_RotateX( *args );return @@Matrix_RotateX.call( *args );end
  1018.     def self.Matrix_RotateY( *args );return @@Matrix_RotateY.call( *args );end
  1019.     def self.Matrix_RotateZ( *args );return @@Matrix_RotateZ.call( *args );end
  1020.     def self.Matrix_Scale( *args );return @@Matrix_Scale.call( *args );end
  1021.     def self.Matrix_Translate( *args );return @@Matrix_Translate.call( *args );end
  1022.     #--------------------------------------------------------------------------
  1023.     # * Library name, read as LIB_NAME.dll
  1024.     #--------------------------------------------------------------------------
  1025.     LIB_NAME = "RMVXA-GL"
  1026.     #--------------------------------------------------------------------------
  1027.     # * Win32API function pointer bindings
  1028.     #--------------------------------------------------------------------------
  1029.     @@XGL_Init = Win32API.new( LIB_NAME, "XGL_Init", "v", "i" )
  1030.     @@XGL_Terminate = Win32API.new( LIB_NAME, "XGL_Terminate", "v", "v" )
  1031.    
  1032.     @@Console_Show = Win32API.new( LIB_NAME, "Console_Show", "v", "v" )
  1033.     @@Console_Hide = Win32API.new( LIB_NAME, "Console_Hide", "v", "v" )
  1034.     @@Console_Print = Win32API.new( LIB_NAME, "Console_Print", "p", "v" )
  1035.    
  1036.     @@Graphics_Clear = Win32API.new( LIB_NAME, "Graphics_Clear", "v", "v" )
  1037.    
  1038.     @@Graphics_GenTexture = Win32API.new( LIB_NAME, "Graphics_GenTexture", "iiip", "i" )
  1039.     @@Graphics_TexSubBitmap = Win32API.new( LIB_NAME, "Graphics_TexSubBitmap", "ip", "v" )
  1040.     @@Graphics_DestroyTex = Win32API.new( LIB_NAME, "Graphics_DestroyTex", "i", "v" )
  1041.     @@Graphics_BindTexUnit = Win32API.new( LIB_NAME, "Graphics_BindTexUnit", "ii", "v" )
  1042.    
  1043.     @@Graphics_GenFBO = Win32API.new( LIB_NAME, "Graphics_GenFBO", "v", "i" )
  1044.     @@Graphics_FBOTexure = Win32API.new( LIB_NAME, "Graphics_FBOTexure", "ii", "v" )
  1045.     @@Graphics_GetTexImage = Win32API.new( LIB_NAME, "Graphics_GetTexImage", "ip", "v" )
  1046.     @@Graphics_DestroyFBO = Win32API.new( LIB_NAME, "Graphics_DestroyFBO", "i", "v" )
  1047.     @@Graphics_BindFBO = Win32API.new( LIB_NAME, "Graphics_BindFBO", "i", "v" )
  1048.    
  1049.     @@Graphics_CreateShader = Win32API.new( LIB_NAME, "Graphics_CreateShader", "i", "i" )
  1050.     @@Graphics_DestroyShader = Win32API.new( LIB_NAME, "Graphics_DestroyShader", "i", "v" )
  1051.     @@Graphics_ShaderCompile = Win32API.new( LIB_NAME, "Graphics_ShaderCompile", "ip", "i" )
  1052.    
  1053.     @@Graphics_CreateProgam = Win32API.new( LIB_NAME, "Graphics_CreateProgam", "v", "i" )
  1054.     @@Graphics_ProgLink = Win32API.new( LIB_NAME, "Graphics_ProgLink", "iiii", "i" )
  1055.     @@Graphics_DestroyProg = Win32API.new( LIB_NAME, "Graphics_DestroyProg", "i", "v" )
  1056.     @@Graphics_UniformLocation = Win32API.new( LIB_NAME, "Graphics_UniformLocation", "ip", "i" )
  1057.    
  1058.     @@Graphics_Uniform1f = Win32API.new( LIB_NAME, "Graphics_Uniform1f", "ii", "v" )
  1059.     @@Graphics_Uniform2f = Win32API.new( LIB_NAME, "Graphics_Uniform2f", "iii", "v" )
  1060.     @@Graphics_Uniform3f = Win32API.new( LIB_NAME, "Graphics_Uniform3f", "iiii", "v" )
  1061.     @@Graphics_Uniform4f = Win32API.new( LIB_NAME, "Graphics_Uniform4f", "iiiii", "v" )
  1062.    
  1063.     @@Graphics_Uniform1i = Win32API.new( LIB_NAME, "Graphics_Uniform1i", "ii", "v" )
  1064.     @@Graphics_Uniform2i = Win32API.new( LIB_NAME, "Graphics_Uniform2i", "iii", "v" )
  1065.     @@Graphics_Uniform3i = Win32API.new( LIB_NAME, "Graphics_Uniform3i", "iiii", "v" )
  1066.     @@Graphics_Uniform4i = Win32API.new( LIB_NAME, "Graphics_Uniform4i", "iiiii", "v" )
  1067.    
  1068.     @@Graphics_UseProgram = Win32API.new( LIB_NAME, "Graphics_UseProgram", "i", "v" )
  1069.     @@Graphics_BindAttribLocation = Win32API.new( LIB_NAME, "Graphics_BindAttribLocation", "iip", "v" )
  1070.    
  1071.     @@Graphics_GenVBO = Win32API.new( LIB_NAME, "Graphics_GenVBO", "v", "i" )
  1072.     @@Graphics_DestroyVBO = Win32API.new( LIB_NAME, "Graphics_DestroyVBO", "i", "v" )
  1073.     @@Graphics_BindVBO = Win32API.new( LIB_NAME, "Graphics_BindVBO", "i", "v" )
  1074.     @@Graphics_VBOData = Win32API.new( LIB_NAME, "Graphics_VBOData", "pi", "v" )
  1075.     @@Graphics_VBOAttrib = Win32API.new( LIB_NAME, "Graphics_VBOAttrib", "iiii", "v" )
  1076.     @@Graphics_DrawVBO = Win32API.new( LIB_NAME, "Graphics_DrawVBO", "ii", "v" )
  1077.    
  1078.     @@Matrix_Create = Win32API.new( LIB_NAME, "Matrix_Create", "v", "i" )
  1079.     @@Matrix_Destroy = Win32API.new( LIB_NAME, "Matrix_Destroy", "i", "v" )
  1080.    
  1081.     @@Matrix_Pop = Win32API.new( LIB_NAME, "Matrix_Pop", "i", "v" )
  1082.     @@Matrix_Push = Win32API.new( LIB_NAME, "Matrix_Push", "i", "v" )
  1083.     @@Matrix_Size = Win32API.new( LIB_NAME, "Matrix_Size", "i", "i" )
  1084.    
  1085.     @@Matrix_Pop = Win32API.new( LIB_NAME, "Matrix_Pop", "i", "v" )
  1086.     @@Matrix_Push = Win32API.new( LIB_NAME, "Matrix_Push", "i", "v" )
  1087.     @@Matrix_UploadMatrix2 = Win32API.new( LIB_NAME, "Matrix_UploadMatrix2", "ii", "v" )
  1088.     @@Matrix_UploadMatrix3 = Win32API.new( LIB_NAME, "Matrix_UploadMatrix3", "ii", "v" )
  1089.     @@Matrix_UploadMatrix4 = Win32API.new( LIB_NAME, "Matrix_UploadMatrix4", "ii", "v" )
  1090.    
  1091.     @@Matrix_LoadMatrix4 = Win32API.new( LIB_NAME, "Matrix_LoadMatrix4", "ip", "v" )
  1092.     @@Matrix_MultiplyMatrix4 = Win32API.new( LIB_NAME, "Matrix_MultiplyMatrix4", "ip", "v" )
  1093.     @@Matrix_MultiplyMatrixStack = Win32API.new( LIB_NAME, "Matrix_MultiplyMatrixStack", "ii", "v" )
  1094.     @@Matrix_Rotate = Win32API.new( LIB_NAME, "Matrix_Rotate", "iiiii", "v" )
  1095.     @@Matrix_RotateX = Win32API.new( LIB_NAME, "Matrix_RotateX", "ii", "v" )
  1096.     @@Matrix_RotateY = Win32API.new( LIB_NAME, "Matrix_RotateY", "ii", "v" )
  1097.     @@Matrix_RotateZ = Win32API.new( LIB_NAME, "Matrix_RotateZ", "ii", "v" )
  1098.     @@Matrix_Scale = Win32API.new( LIB_NAME, "Matrix_Scale", "iiii", "v" )
  1099.     @@Matrix_Translate = Win32API.new( LIB_NAME, "Matrix_Translate", "iiii", "v" )
  1100.    
  1101.     @@Matrix_DownloadMatrix2 = Win32API.new( LIB_NAME, "Matrix_DownloadMatrix2", "i", "p" )
  1102.     @@Matrix_DownloadMatrix3 = Win32API.new( LIB_NAME, "Matrix_DownloadMatrix3", "i", "p" )
  1103.     @@Matrix_DownloadMatrix4 = Win32API.new( LIB_NAME, "Matrix_DownloadMatrix4", "i", "p" )
  1104.   end
  1105. end
  1106. #==============================================================================
  1107. # ** SceneManager
  1108. #------------------------------------------------------------------------------
  1109. #  Adds a finalisation stage to SceneManager.
  1110. # Used by XGL to cleanup the OpenGL context.
  1111. #==============================================================================
  1112. module SceneManager
  1113.   @@error = nil
  1114.   #--------------------------------------------------------------------------
  1115.   # * Override SceneManager
  1116.   #--------------------------------------------------------------------------
  1117.   class << self
  1118.     alias super_exit exit
  1119.     alias super_run run
  1120.     def run
  1121.       GL::Console.new
  1122.       GL::OpenGL.new
  1123.       if @@error != nil
  1124.         messageBox = Win32API.new( "User32", "MessageBox", "lppl", "l" )
  1125.         messageBox.call( 0, @@error, "SceneManager Error", 0 )
  1126.       else
  1127.         super_run
  1128.       end
  1129.     end
  1130.     #--------------------------------------------------------------------------
  1131.     # * Pre-Termination Processing
  1132.     #--------------------------------------------------------------------------
  1133.     def exit
  1134.       GL::Lib.XGL_Terminate
  1135.       super_exit
  1136.     end
  1137.   end
  1138.   #--------------------------------------------------------------------------
  1139.   # * Sets the scene manager to exit with an error message
  1140.   #--------------------------------------------------------------------------
  1141.   def self.exit_error( str )
  1142.     @@error = str
  1143.   end
  1144. end
Expand to see the code.


Hello Triangle Tutorial
Tutorial for scripters Spoiler
This little tutorial will modifying Spriteset_Map to draw a colourful triangle on the field.

Underneath the RMVXA-GL add a script section and call it "Hello Triangle".
Copy in this framework for overloading the default Spriteset_Map class:

  1. class Spriteset_Map
  2.   include GL
  3.  
  4.   alias super_update update
  5.   alias super_dispose dispose
  6.  
  7.   def initialize
  8.     create_viewports
  9.     create_tilemap
  10.     create_parallax
  11.     create_characters
  12.     create_shadow
  13.     create_weather
  14.     create_pictures
  15.     create_timer
  16.    
  17.    
  18.    
  19.     update
  20.   end
  21.  
  22.   def dispose
  23.  
  24.     super_dispose
  25.   end
  26.  
  27.   def update
  28.     super_update
  29.    
  30.   end
  31.    
  32. end
Expand to see the code.


Notice the include GL, this is so we can use the RMVXA-GL classes without needing GL:: infront of everything.

First we want to load in some shaders to render out our triangle, so add in these two methods:
  1. def create_shader
  2.  
  3. end
  4.  
  5. def destroy_shader
  6.  
  7. end
Expand to see the code.

We will have 3 instance variables for handling the shader; the vertex shader, the fragment shader and the shader program.
(The OpenGL shader system was inspired by C/C++ compilers; the shader is made up of vertex and fragment objects that are linked into the final program)

To create the vertex and fragment shaders we need to write some shader code.
Here's a vertex shader;
  1. vertex_source = "#version 120
  2.  attribute vec2  vertex_position;
  3.  attribute vec3  vertex_colour;
  4.  varying vec3  fragment_colour;
  5.  void main() {
  6.       fragment_colour = vertex_colour;
  7.       gl_Position = vec4( vertex_position, 0.0, 1.0 );
  8.  }"
Expand to see the code.

And here's a fragment shader;
  1. fragment_source = "#version 120
  2.  varying vec3  fragment_colour;
  3.  void main() {
  4.       gl_FragColor = vec4( fragment_colour, 1.0 );
  5.  }"
Expand to see the code.


You can copy those into the create_shader method as we can use these sources directly.

To create each shader we use the Shader.Create* methods with out shader source;
  1. @vertex_shader = Shader.CreateVertex( vertex_source )
  2. @fragment_shader = Shader.CreateVertex( vertex_source )
Expand to see the code.

These can then be linked into the final program and the vertex attributes can be set;
  1. @shader_program = ShaderMaterial.Create( @vertex_shader, @fragment_shader )
  2. @shader_program.SetAttributeIndex( "vertex_position", 0 )
  3. @shader_program.SetAttributeIndex( "vertex_colour", 1 )
Expand to see the code.

The vertex_position attribute is the first attribute in our vertex shader, so we set the index to 0 (Like an array)
The vertex_colour attribute is the second attribute in our vertex shader, so we set that index to 1

The shader program is not yet linked, RMVXA-GL will link the program when it is next bound (When setting uniforms or when activating the program itself).

To clean-up the shader memory (On both the GPU memory and CPU memory) call the Dealloc method;
  1. @shader_program.Dealloc
  2.  
  3. @fragment_shader.Dealloc
  4. @vertex_shader.Dealloc
Expand to see the code.

That can go into the destroy_shader method.


Next is the most important part; setting up the frame buffer for rendering. This is a page in GPU memory that OpenGL will draw to.
Let's make some RGSS bitmaps to draw to;
  1. def create_display_buffer
  2.     @display_sprite = Sprite.new( @viewport3 )
  3.     @display_sprite.bitmap = Bitmap.new( 544, 416 )
  4.    
  5.    
  6. end
Expand to see the code.

RGSS bitmaps require cleaning up, so add that into a destroy method;
  1. def destroy_display_buffer
  2.  
  3.  
  4.     @display_sprite.bitmap.dispose
  5. end
Expand to see the code.


There are 2 parts to a frame buffer;
  • GPU Target
  • GPU Textures
The target is the point where all the textures are collected, the textures are the actual bytes where we will render our image.

To create our texture in GPU memory we use the Texure.Alloc method and parse in the details of our texture.
We want a texture that has red, blue, green and alpha components that is 544x416.
Alpha is needed if we want to see the map underneath our image and the 544x416 is to match the size of the game screen.

So after creating our RGSS bitmap, allocate the GPU memory for our texture, allocate the frame-buffer's target size (This is the size that all frame-buffer textures need to be) and then attach the texture to our frame buffer.
  1. @render_texture = Texture.Alloc( Texture::RGBA, 544, 416 )
  2.  
  3. @frame_buffer = FrameBuffer.Alloc( 544, 416 )
  4. @frame_buffer.AttachTexture( @render_texture )
Expand to see the code.


The cleanup is once again Dealloc for both;
  1. def destroy_display_buffer
  2.     @frame_buffer.Dealloc
  3.  
  4.     @render_texture.Dealloc
  5.  
  6.     @display_sprite.bitmap.dispose
  7. end
Expand to see the code.


The final piece is the triangle that we want to draw.
We want to draw a 2D triangle with each point being a red, green or blue colour.

For this we need: x, y, r, g, b information for each point.
A float array can describe this for us:
  1. def create_vertex_buffer
  2.     triangle_mesh = [ [  0.0,  0.5, 1.0, 0.0, 0.0 ],
  3.                       [  0.5, -0.5, 0.0, 1.0, 0.0 ],
  4.                       [ -0.5, -0.5, 0.0, 0.0, 1.0 ] ]
  5.  
  6.    
  7. end
Expand to see the code.


The vertices need to be allocated memory on the GPU and uploaded, we also need to describe our triangle to OpenGL.
  1. @vertex_buffer = VertexBuffer.Alloc # Allocate GPU space for vertices
  2. @vertex_buffer.DescribeBuffer( 3, [2, 3] ) # Describe that we have 3 vertices, split into 2 floats then 3 floats [xy,rgb]
  3. @vertex_buffer.UploadVertexArray( triangle_mesh ) # Upload our triangle to the GPU memory
Expand to see the code.


And then we have the cleanup;
  1. def destroy_vertex_buffer
  2.     @vertex_buffer.Dealloc
  3. end
Expand to see the code.


Make one more method called draw_triagle then set up all the calls for our create and destroy methods;
  1. def initialize
  2.     create_viewports
  3.     create_tilemap
  4.     create_parallax
  5.     create_characters
  6.     create_shadow
  7.     create_weather
  8.     create_pictures
  9.     create_timer
  10.  
  11.     create_shader # +@shader_program
  12.     create_display_buffer # +@frame_buffer
  13.     create_vertex_buffer # +@vertex_buffer
  14.  
  15.     update
  16. end
  17.  
  18. def dispose
  19.     destroy_vertex_buffer # -@vertex_buffer
  20.     destroy_display_buffer # -@frame_buffer
  21.     destroy_shader # -@shader_program
  22.  
  23.     super_dispose
  24. end
  25.  
  26. def update
  27.     super_update
  28.  
  29.     draw_triangle # Do the actual rendering
  30. end
  31.  
  32. def draw_triangle
  33.    
  34. end
  35.  
  36. ...
Expand to see the code.


Now that we have all the memory allocated and sorted out, drawing the triangle is easy;
  1. def draw_triangle
  2.     @frame_buffer.Bind( FrameBuffer::Clear ) # Bind our frame_buffer and clear any textures on it
  3.  
  4.     @shader_program.UseProgram # Select our shader_program (This will also link it if it is not already linked)
  5.  
  6.     @vertex_buffer.DrawArrays( VertexBuffer::DRAW_TRIANGLES ) # Draw our vertex_buffer, telling OpenGL that we are drawing Triangles
  7.  
  8.     @frame_buffer.ToBitmap( @display_sprite.bitmap ) # Copy the frame_buffer contents to our displayed bitmap
  9. end
Expand to see the code.


And that's it, you should now have a triangle slapped on top of the map.


Next tutorial will be setting textures to a cube and animating it.

Known Problems
  • OpenGL 2.1 support is not tested! - Please test it someone!
  • Some Matrix functions are broken - I don't know which, please report the ones that aren't working

Missing Features
  • Matrix cameras - Not hooked up yet
  • Setting render flags - Backface modes, blend modes, etc cannot be set
  • Depth Buffers and Textures - No depth buffer at all right now
The missing features are planned for the next version (After bug fixing).
Ran your demo. I was surprised it stayed at 60fps. I have Nvidia Geforce GT 300m on my laptop so I wasn't sure I'd meet the requirements.
It dropped the 30fps when I turned on the weather effect. Not bad.
Here's a screenshot of the spinning cube demo that's coming up next:
Image

I'll be uploading the demo (Which will be called alpha 2) in a moment.

EDIT:
And here it is;
Alpha 2

This demo does not do screen post-processing, so it will be significantly faster than the other demos. I get full 60 FPS on all my machines with the cube spinning demo.

New features:
  • Camera matrix functions
  • Functions for setting depth IO, culling and blending
  • ViewPort is now set to the frame-buffer's width/height
  • Depth texture can now be attached to frame buffers for depth buffering

Bug fixes:
  • Cross product X/Y were switched
  • Pushing to the matrix stack wasn't copying the top matrix
  • Setting matrix uniforms no longer crashes if shader program hasn't yet been linked (Program is linked when a uniform is set)
Holy. Shit.

You are pushing the limits of a platform meant for a very specific commercial target: The masses who are without coding capability and prowess...So you have tread upon unknown territory. I'd like to thing this opens up some more mode7 for me with a designated zoom script so I can make Fractus Stellarum the way it should be...but I doubt that in the same mindset: You have a lot to do, and it doesn't involve us at hbg.

PS: I'd completely remake FS if you made a zoom script and whatnot in regards to what I originally wanted in FS. <3 u felix
To do 3D maps I'd need to rewrite the Tilemap class to render with OpenGL instead of bitmap blitting and I don't know anything about the Tilemap class to be able to rewrite it.

I'll need help setting that up, but once that's done you get fast mode 7, zooming, spinning, etc for free.

If you can get someone to make a Tilemapper framework then I can do it
That's rather impressive, just downloaded the demo and it ran at a perfect 60fps with no drops... then again it should do with my computer anyways lol, and I don't have any low end computers to try it on sadly, since we're all upgraded in this house, lol. It's quite an interesting idea though, to have OpenGL working within VXAce, but I think it's something for the more advanced RM* users, right?
Quote:
OpenGL 2.1 support is not tested! - Please test it someone!

Tested Alpha 2 : still doesn't work.
Nuri Yuri wrote:
Quote:
OpenGL 2.1 support is not tested! - Please test it someone!

Tested Alpha 2 : still doesn't work.

Do you have the FBO extension?
Can you enable the console in the script and tell me if any errors log or if you can which function call was a nullptr?
RMVXA-GL will support GL lighting commands?
Ryaryu wrote:
RMVXA-GL will support GL lightning commands?

I presume you mean lighting?

I am not using fixed-function GL, so you can do anything you want with it as long as you write the shader.

It doesn't support the old OpenGL lighting functions, everything is programmable pipeline here.

Basically, anything is possible as long as you have the computing power to do it.
The console displays absolutely nothing :\
I don't know if I have the FBO and I don't know where I can download it... It's the jungle :x
Nuri Yuri wrote:
The console displays absolutely nothing :\
I don't know if I have the FBO and I don't know where I can download it... It's the jungle :x

You need a tool to check your GL support, one that lists extensions.
If you are 2.1 and missing the extension then perhaps a driver update will add it.

I'll add some real checks for the extension. I miss have missed something for a crash to happen
I've been playing with it (and learning new OpenGL programing style haha), and was able to create normal mapping.
Next I'll try to expand it to every sprite in-screen...

Image

I haven't cared for GL 2.1 so it probably won't work there.
Ryaryu wrote:
I've been playing with it (and learning new OpenGL programing style haha), and was able to create normal mapping.
Next I'll try to expand it to every sprite in-screen...

http://i814.photobucket.com/albums/zz68/Arashin_Sieg/CapturadeTela2.png

I haven't cared for GL 2.1 so it probably won't work there.

You just made my day.

2.1 support still isn't figured out, so I might lock it to 3.0 frankly (Which opens up a lot of options).
看起来是个非常厉害的系统呢,连远在地球另一边的立华揍都跑过来了。
Seems to be a very powerful system, even as far as the other side of the globe Tachibana Kanade ran all over.
Thank you Allen2014.

Allen2014 wrote:
连远在地球另一边的立华揍都跑过来了。
even as far as the other side of the globe Tachibana Kanade ran all over.

你的句子的最后一部分是混乱的。你能解释一下这句话?

The last part of your sentence is confusing. Can you explain this statement?
Xilef wrote:
Thank you Allen2014.

Allen2014 wrote:
连远在地球另一边的立华揍都跑过来了。
even as far as the other side of the globe Tachibana Kanade ran all over.

你的句子的最后一部分是混乱的。你能解释一下这句话?

The last part of your sentence is confusing. Can you explain this statement?


我来自中国 我是通过一个传送门抵达这里的,我这里有一个彪悍的天使她两只手都装备了长刀……【不要在意这些细节
I come from China I is through a portal arrived here, here I have a tough Angel her two hands are equipped with long knives...... [don't care about these details
Xilef wrote:
Thank you Allen2014.

Allen2014 wrote:
连远在地球另一边的立华揍都跑过来了。
even as far as the other side of the globe Tachibana Kanade ran all over.

你的句子的最后一部分是混乱的。你能解释一下这句话?

The last part of your sentence is confusing. Can you explain this statement?


Just call me Allen
BTW:
I have been and princess Amy for help, I want to HB the forum released a game about 400MB in size, but not SkyDrive, can you help me?
Allen2014 wrote:
Just call me Allen
BTW:
I have been and princess Amy for help, I want to HB the forum released a game about 400MB in size, but not SkyDrive, can you help me?

I would suggest DropBox where you get 2GB free file hosting https://www.dropbox.com/plans
It is similar to SkyDrive.

There is also MediaFire which is more like a traditional file host where you have 10GB free https://www.mediafire.com/upgrade/

But please keep within the thread topic.
Xilef wrote:
Allen2014 wrote:
Just call me Allen
BTW:
I have been and princess Amy for help, I want to HB the forum released a game about 400MB in size, but not SkyDrive, can you help me?

I would suggest DropBox where you get 2GB free file hosting https://www.dropbox.com/plans
It is similar to SkyDrive.

There is also MediaFire which is more like a traditional file host where you have 10GB free https://www.mediafire.com/upgrade/

But please keep within the thread topic.


Oh sorry I digress, this is called the slanting floor in our...... Your system is tough, I can only use some simple scripts, the word is a very good very good very good
I've been struggling with the Tileset. It's draw methods are hidden, and I can't figure out how it draws the scene, hence I can't apply bump mapping to the map right now... has anyone found some Tileset implementation so far?
Tileset! I've got an RMXP implementation for you right here. Well...it will probably take some modification, because the viewport code uses other systems I wrote and it is designed for GOSU rather than plain OpenGL. You probably don't want to split the images into individual textures like this, you want to load it as one texture (if you can) and draw with UVs. But you can do this I think. The only part that needs explaining is that `Gosu::Image.load_tiles` creates an array of textures, in this case all 32x32 pixel tiles, row-by-row (so the first row would be tiles 0-7, the next 8-15, etc).

Every time I come back to this I am again disappointed that I did not do the GL calls myself in this way. Oh well. This should help you get started though.

  1. # RMXP Tilemap (gosu)
  2. #
  3. # Readable/Writable Attributes :
  4. #  - viewport         : Viewport used for sprites
  5. #  - map_data         : 3D Table of Tile ID Data
  6. #  - flash_data       : 3D Table of Tile Color Data
  7. #  - priorities       : 3D Table of Tile Priorities
  8. #  - ox, oy           : Tilemap layer offsets
  9. #  - zoom             : Zoom value as fraction
  10. #  - tilesize         : Zoom value as size of individual tile (normal is 32.0)
  11. #  - visible          : Tilemap Visible Flag
  12. #  - is_a_plane       : Behaves like a Plane (loops around edges)
  13. #  - tileset          : Name of Bitmap
  14. #  - autotiles        : Array of Autotile Filenames
  15. class Tilemap
  16.   include Disposable
  17.   VP                = 2    # Number of tiles beyond viewport to refresh
  18.   FA                = 64   # Alpha value of the color of flash data
  19.   Autotile_Speed    = 20   # Number of frames between autotile animations
  20.   Autotiles = [
  21.     [416,432,512,528], [ 64,432,512,528], [416, 80,512,528], [ 64, 80,512,528],
  22.     [416,432,512,176], [ 64,432,512,176], [416, 80,512,176], [ 64, 80,512,176],
  23.     [416,432,160,528], [ 64,432,160,528], [416, 80,160,528], [ 64, 80,160,528],
  24.     [416,432,160,176], [ 64,432,160,176], [416, 80,160,176], [ 64, 80,160,176],
  25.     [384,400,480,496], [384, 80,480,496], [384,400,480,176], [384, 80,480,176],
  26.     [224,240,320,336], [224,240,320,176], [224,240,160,336], [224,240,160,176],
  27.     [448,464,544,560], [448,464,160,560], [ 64,464,544,560], [ 64,464,160,560],
  28.     [608,624,704,720], [ 64,624,704,720], [608, 80,704,720], [ 64, 80,704,720],
  29.     [384,464,480,560], [224,240,704,720], [192,208,288,304], [192,208,288,176],
  30.     [256,272,352,368], [256,272,160,368], [640,656,736,752], [ 64,656,736,752],
  31.     [576,592,672,688], [576, 80,672,688], [192,272,288,368], [192,208,672,688],
  32.     [576,656,672,752], [256,272,736,752], [192,272,672,752], [  0, 16, 96,112]
  33.   ]
  34.   DEFAULTS = {:tileset => nil, :autotiles => [], :map_data => nil,
  35.               :flash_data => nil, :priorities => nil, :visible => true,
  36.               :ox => 0, :oy => 0, :zoom => 1.0, :is_a_plane => true,
  37.               :manager => nil}
  38.  
  39.   # Public Instance Variables
  40.   attr_reader   :gosuwindow     # Instance of Gosu::Window it's drawing to
  41.   attr_reader   :tileset        # Tileset Image
  42.   attr_reader   :autotiles      # Array of Autotile Images
  43.   attr_accessor :map_data       # 3D Table of Tile Settings
  44.   attr_reader   :flash_data     # 3D Table of Sprite Flash Colors
  45.   attr_accessor :priorities     # 3D Table of Tileset Priorities
  46.   attr_accessor :visible        # Tilemap Visibility
  47.   attr_accessor :ox             # Bitmap Offsets
  48.   attr_accessor :oy             # Bitmap Offsets
  49.   attr_accessor :zoom           # Zoom Fraction
  50.   attr_accessor :is_a_plane     # Loops around edges
  51.  
  52.   # Object Initialization
  53.   def initialize(manager = nil, opts = {})
  54.     @gosuwindow = $GameWindow
  55.     DEFAULTS.merge!(opts).each do |sym, val|
  56.       instance_variable_set("@#{sym}", val)
  57.     end
  58.     @manager           = manager unless manager.nil?
  59.     @autotiles_cache   = @autotiles
  60.     self.flash_data    = @flash_data
  61.     @tiles             = []
  62.     @frame             = 0
  63.     (@manager.nil? ? @gosuwindow.draw_manager : @manager).manage(self)
  64.   end
  65.  
  66.   # Get "viewport"
  67.   def viewport
  68.     @manager
  69.   end
  70.  
  71.   # Set "viewport"
  72.   def viewport=(manager)
  73.     (@manager.nil? ? @gosuwindow.draw_manager : @manager).unmanage(self)
  74.     (manager.nil? ? @gosuwindow.draw_manager : manager).manage(self)
  75.     @manager = manager
  76.   end
  77.  
  78.   # Get Tile Size
  79.   def tilesize
  80.     (zoom * 32).to_i
  81.   end
  82.  
  83.   # Set Tile Size
  84.   def tilesize=(tilesize)
  85.     self.zoom = tilesize / 32.0
  86.   end
  87.  
  88.   # Set tileset graphic. Recaches the internal tileset.
  89.   def tileset=(tileset)
  90.     @tiles[384..-1] = Gosu::Image.load_tiles(@gosuwindow, tileset, 32, 32, true)
  91.     @tileset = tileset
  92.   end
  93.  
  94.   # Set list of autotiles. Recaches the internal tileset.
  95.   def autotiles=(autotiles)
  96.     autotiles.each_with_index do |autotile, i|
  97.       Autotiles.each_with_index do |tiles, j|
  98.         key = (i + 1) * 48 + j
  99.         @tiles[key] = []
  100.         # Draws Auto-Tile Rects
  101.         for f in 0..(autotile.width / 96)
  102.           bmp = Gosu::Image.new(@gosuwindow,
  103.                                 TexPlay::EmptyImageStub.new(32, 32), true)
  104.           tiles.each_with_index do |pos, k|
  105.             opts = {:crop => [x1 = pos%96+f*96, x2=pos / 96, x1 + 16, x2 + 16]}
  106.             bmp.splice(k % 2 * 16, k / 2 * 16, autotile, opts)
  107.           end
  108.           @tiles[key][f] = bmp
  109.         end
  110.       end
  111.     end
  112.     @autotiles = @autotiles_cache = autotiles
  113.   end
  114.  
  115.   # Set flash data. For speed we maintain a separate list of GOSU::Color
  116.   # object for actual display.
  117.   def flash_data=(flash_data)
  118.     @flash_data = flash_data
  119.     if flash_data.nil?
  120.       @flash_data_colors = nil
  121.     else
  122.       @flash_data_colors = Hash.new
  123.       for y in 0...flash_data.ysize
  124.         for x in 0...flash_data.xsize
  125.           hex = @flash_data[x, y]
  126.           @flash_data_colors[[x, y]] =
  127.             Gosu::Color.rgba((hex<<8)*16, ((hex<<4)%16)*16, (hex%16)*16, FA))
  128.         end
  129.       end
  130.     end
  131.   end
  132.  
  133.   # Dispose
  134.   def dispose
  135.     @visible = false
  136.     super
  137.   end
  138.  
  139.   # Update autotile animation
  140.   def update
  141.     @frame += 1
  142.   end
  143.  
  144.   # Per-frame draw function
  145.   def draw
  146.     return if @map_data.nil? or @priorities.nil? or !@visible
  147.    
  148.     self.autotiles = @autotiles if @autotiles != @autotiles_cache
  149.     ts = tilesize
  150.     frame = @frame / Autotile_Speed
  151.     xmax = (((@viewport.nil? ? @gosuwindow : @viewport.rect).width + @ox) / ts)
  152.     ymax = (((@viewport.nil? ? @gosuwindow : @viewport.rect).height + @oy) / ts)
  153.     ydts = @oy / ts
  154.     yrange = ydts - VP...ymax + VP
  155.     xrange = (@ox / ts) - VP...xmax + VP
  156.    
  157.     for y in yrange
  158.       ytop = y - ydts
  159.       if y < 0 or y >= @map_data.ysize
  160.         next unless @is_a_plane
  161.         y %= @map_data.ysize
  162.         y += @map_data.ysize if y < 0
  163.       end
  164.       draw_y = y * ts - @oy
  165.      
  166.       for x in xrange
  167.         if x < 0 or x >= @map_data.xsize
  168.           next unless @is_a_plane
  169.           x %= @map_data.xsize
  170.           x += @map_data.xsize if x < 0
  171.         end
  172.         draw_x = x * ts - @ox
  173.        
  174.         for layer in 0...@map_data.zsize
  175.           id = @map_data[x, y, layer]
  176.           next if id == 0
  177.           z = (ytop + z) * 32 + 64 unless (z = @priorities[id]) == 0
  178.           tile = @tiles[id]
  179.           tile = @tiles[id][frame % tile.size] if tile.is_a?(Array)
  180.           tile.draw(draw_x, draw_y, z, @zoom, @zoom)
  181.         end
  182.         unless @flash_data.nil?
  183.           c = @flash_data_colors[[x, y]]
  184.           @gosuwindow.draw_quad(draw_x, draw_y,    c, draw_x+ts, draw_y,    c,
  185.                                 draw_x, draw_y+ts, c, draw_x+ts, draw_y+ts, c)
  186.         end
  187.       end # for x
  188.     end # for y
  189.   end
  190. end
  191.  
Expand to see the code.

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