This is Bananattack.

Tag: vx

Anonymous Functions, and Textshmup: A retrospect

Posted by Overkill on April 8, 2009 at 8:53 pm under Uncategorized

Some of you may have recently played my 24h game textshmup. As expected, it wasn’t that well received. It was a bad concept to begin with, after all! :D

It was too hard to read quickly and type responses. Audio cues and colored text were added to make the game slightly easier to react to, but even then, it was just too tedious. It was just a randomly generated endurance test, with no goal, and no intermediate tasks.

That said, I had fun making it! I mentioned last time that I made it in LuaVerge. I never mentioned why it was so quick to write.

Well let’s go!

For one, I used the vx library I had written. It came with the spiffy nifty object-oriented class system that I made.

I had my entire game use a single well-divided render/update loop, which boiled down to this:

while true do
    Render()
    Update()
end

I declare two lists which contain all the callbacks done by the render and update events:

render_list = {}
update_list = {}

Here is Render(), in its entirety:

function Render()
    vx.screen:RectFill(0, 0, vx.screen.width, vx.screen.height, 0)
    for i, f in ipairs(render_list) do
        f()
    end
    vx.ShowPage()
end

The Render() function starts by clearing the screen, then it iterates over all entries in the render list, and calls them all. At the end, it shows the changes on the screen. This was ridiculously nice to hook in new rendering events.

Similarly, here was my Update() code, which used frame-throttling so each update callback could be written in per-tick logic:

function Update()
    frame_limiter:Update()
    
    local i = 0
    while i < frame_limiter.gap do
        for _, f in ipairs(update_list) do
            f()
        end
        i = i + 1
    end
    vx.SetAppName(TITLE .. ' ' .. frame_limiter.frame_rate)
end

Both of these worked great for global functions and static methods.

There was one issue with the way they were designed though. Which wasn't immediately apparent, but here goes.

Say I made a class named BlueBox, which has an x, y, x2 and y2. I declare a method for it like this.

function BlueBox:Draw()
    vx.screen:RectFill(self.x, self.y, self.x2, self.y2, vx.RGB(0, 0, 255))
end

In Lua, the colon : in that function is syntax sugar for the following:

function BlueBox.Draw(self)
    vx.screen:RectFill(self.x, self.y, self.x2, self.y2, vx.RGB(0, 0, 255))
end

Which is syntax sugar for:

BlueBox.Draw = function(self)
    vx.screen:RectFill(self.x, self.y, self.x2, self.y2, vx.RGB(0, 0, 255))
end

See that 'self' parameter? Well, earlier when I'm calling the functions, I go like this:

f()

That's a call with no arguments. If we try and add the method pointer for a particular blue box's render, it will call it without passing self, so 'self' is nil:

-- Won't pass the self parameter!
table.insert(render_list, self.Render)
-- Similarly, won't pass the self parameter!
table.insert(render_list, self:Render)

Thus object instances aren't passed around. Not good!

So how do you pass around the 'self' parameter to this list? Well, fortunately, Lua allows you to create anonymous functions, wherever you want because functions are first-class values. And these anonymous functions can be passed "upvalues", which are local values defined in a scope outside the function.

Using these facts, I wrote a trivial fix to bind method pointers to their objects, and leave Render unchanged! I made a function that did the method wrapping for me:

function MethodPointer(self, meth)
    return function(...)
        return self[meth](self, ...)
    end
end

The function is passed the 'self' parameter and the method pointer to bind together, and it returns an anonymous function which will take care of calling, with 'self' being passed automatically.

Then I can go add to the render_list and update list:

table.insert(render_list, MethodPointer(self, 'Render'))
table.insert(update_list, MethodPointer(self, 'Update'))

This is actually pretty close to how Javascript gets around similar problems, but with its definition of 'this'.

This little tidbit allowed my various components of my game to plugged and unplugged from the main loop as it progressed.

For my text input, I used a callback to process commands when enter was pressed, using the same method pointer stuff. The callback passed around the piece of text, and would return true or false on whether or not the command was permissible. It was very nice.

Lua is just awesome. I love it.

Anyways. As you might see, coding isn't really a colossal obstacle, with Lua around. Instead, the new obstacle is coming up with good ideas!

Something to remember for the next time I try and make a 24h game, and what I always need to consider, while making Resonance.

Catch you later, everyone!

Tags: , , , , , , ,

No comments (make one!)


It is never too late to be great.

Posted by Overkill on February 2, 2009 at 10:19 pm under Uncategorized

Early on during the last week, me and Toen were having a nice talk about how so many of our projects fell apart due to lack of interest and direction. This led to a bunch of talk about planning, collaboration, and organization, something I’ve always lacked. After some disccusion, he decided to make an entry about how planning is urgent and so often overlooked (especially when working in groups), and specifically in the Verge community,

This inspired me to take a new approach to planning, and begin to write ideas down in detail before actual implementation. I decided, clarity is essential if I ever want to do something longterm. I think this will prevent feature creep, and keep myself from losing focus.

I started outlining general things that I want out of the gameplay, as well as making some level designs for shmuptroidvania. It will be a mix of bullet-heavy shmup action, and platforming with exploration, and the transition between the two modes of will be relatively painless.
 
 
 
But, then for a while during the past week, I just became too stressed out. I couldn’t really deal with the crappy weather, and the monotony of school and responsibilities. Started sleeping in and missing classes, and generally did nothing. It wasn’t until near the end of the weekend that I started to recover from this stress-induced aversion to work.

But I recovered! When I did, I started to piece together some of the final steps for LuaVerge. Got cracking, and finally put in a system for garbage collected resources.

To request a Verge resource be garbage collected automatically, you call a function v3.GCHandle(handle, destructor_name), which returns a reference that will manage this handle’s scoping. When that reference is no longer used, the destructor is called, and the variable is freed. I made this fairly low-level though, so v3.GCHandle have no public variables or any methods on them. They are a simply a mechanism for gc scoping internals. Here is an quick and extremely dirty example of it being used

function LoadImageGC(filename)
    local t = {}
    -- The resource handle, which is accessed from
    t.image = v3.LoadImage(filename)
    -- The returned table has a gc_handle that
    -- manages the garbage collection of this resource
    -- If this escapes scope, the image handle held will become invalidated.
    t.gc_handle = v3.GCHandle(self.image, "FreeImage")
    return t
end

-- A small scope block, allocates an image, and the image
-- will escape scope directly after.
-- Collection will occur on next Lua collectgarbage() event.
do
    local img = v3.LoadImageGC("hero.png")
end

I mainly put this in for OO wrappers, like the vx library, which of course uses it. All handle-style references use it, with the exception of vx.File, since files must be closed by the user anyway (especially if writing), and Verge reuses handles so defered collection could result in some bad issues.

vx.File was something I added today to the work-in-progress build. It basically wraps the Verge File library, which is surprisingly powerful, alongside the string tokenizing functions.

LuaVerge is essentially ready, but I’m withholding release until more tests are done, and vx is successfully updated. We’re getting there really quick! Then shmuptroidvania is back in the foreground.

Anyway, I’m back, and ready to rock through school and game making.

Tags: , , , ,

No comments (make one!)


Minty chewing gum.

Posted by Overkill on January 25, 2009 at 2:10 am under Uncategorized

This week, I poured over some more scripting language stuff in LuaVerge. Monotonous work really, but it needed to be done!

As a result, LuaVerge is nearly done. I’m convinced it’s at about the point where it’s usable again.
 
 
 
I added a way to load from .vpk packfiles with Lua scripts. So now require statements will also examine packfiles for source code, meaning that things like vx, and peoples’ games can be packed away in a single file.

I might add override loadfile and dofile too, if it’s actually required, but I figure those are mainly lowlevel things, and most work can USUALLY be done by require. I guess if someone were using Lua as a file format for game data (like a database of items or something) as well, then you’d need to worry about this. I’ll take peoples’ input here, for those Lua users out there.
 
 
 
One of the biger things I spent time scratching my head over was binding Verge’s builtin variables. You see, Lua shoves in getters and setters for variables as functions. So at the lower level, to get the backend variable VC-style entity.x[ent], it calls v3.get_entity_x(ent).

However forcing people to call raw functions rather than assign variables, I’m told is annoying. So, I added support, through Lua’s crazy voodoo magic with metatables.

Since ‘variable’-style accesses to builtins are more expensive than their raw function calls, a bit of optimization had to be considered, to at least lower these costs. After all, the older LuaVerge had issues with speedy access.

This was a bit of a surprise to me at first, but also really neat, local variables have a much faster access time than global ones. Storing local copies of global variables gives a significant efficiency boost. Some report about a 10% lookup for globals, so imagine if it were a nested table of some sort. Caching variable lookups as much as possible would very much improve performance.

So using this knowledge and a few tricks, I think I’ve constructed a way to make fast lookups to LuaVerge builtins. I won’t bore or scare you with the details.

But if you insist, and are curious, all the work is in the source repository for Verge at http://www.verge-rpg.com/svn/verge3/ with username “anonymous” and password “anonymous”.

Particular files to look at are:

 
 
 
So after all this, I started to repair the vx library so it’d work after the giant rewrite. Surprisingly, it wasn’t too hard to repair.

Why? Because vx enclosed all its source in a custom class system. Object oriented code made things compartmentalized and simple enough to refactor.

I made a simple vergeclass function that declares a class, and basically allows you to declare objects of that class after it’s been made.

You declare classes like this:

vergeclass "Thing"

(Whoa! no brackets around the function call? Lua lets you omit them for literals like quoted strings or tables). Anyway, after that point, there’s a globally named class called “Thing” which can be instantiated.

Constructors are declared like

function Thing:__init(a, b, c)
    self.a = a
    self.b = b
    self.c = c
end

And methods inside the class are sort like

function Thing:method()
    print "Hody2!"
end

Objects can be instantiated like this:

mything = Thing(5, 3, "tacos")

Their methods can be invoked fairly simply:

mything:method()

The downside, was the original system I had (before LuaVerge was rewritten) was horrendously inefficient, but it worked somehow. Lua is magical and allows you to horrendously hack things that just work.

Anyway, I revisited this code not because of this but for another reason. None of classes could be ‘extended’ or ‘inherited’ from, making the OOP limited. Granted, for vx, inheritance wasn’t necessary, and I didn’t really desire people extending the core objects because I’d much prefer composition.

Basically objects should as much as possible use “has-a” relations instead, and avoid “is-a” whenever possible, however tempting it is. It decreases coupling somewhat that way.
 
 
 
But I had other code, with Resonance’s sidescroller engine that I wanted to salvage. It used a moderate degree of inheritance, which given for free by luabind. Luabind being the thing that glued LuaVerge behind the scenes before we tossed it, and it came with a class system with inheritance… Anyway.

So I added a single-inheritance system to vx’s vergeclass so I could eliminate this old dependency and have working code again. This involved entirely rewriting the old system now that I understand the Lua library, Lua-based optimizations and metatables a lot better.

It was actually pretty enjoyable to overhaul the whole thing, and… weird. Metatables have some godly power to them. Anyway I finished, and even gave two methods of setting up inheritance.

I supply a temporary global function super(...) which must be invoked in a child class’s initializer to ensure the object inherits all the attributes that its parent class has. Later, I might enforce the call be made on every subclass just to ensure undefined behaviour won’t happen.

Now any time a method is called, it’ll look in its own class first, and failing that it’ll look in it’s parent’s class. If a class needs to explicitly call a method of its parent, it can index self.parent and use self.parent.method(self, ...).

So using the Thing example from earlier, the calls to create a child class are either this…

vergeclass("SuperThing", Thing) do
    SuperThing:__init(a, b, c, x, y, z)
        super(a, b, c)
        self.x = x
        self.y = y
        self.z = z
    end
end

…or this, which I prefer because it looks like Python kind of:

vergeclass "SuperThing"(Thing) do
    SuperThing:__init(a, b, c, x, y, z)
        super(a, b, c)
        self.x = x
        self.y = y
        self.z = z
    end
end

Either one of them reads “The class SuperThing is a child of Thing”. And there you go! Inheritance! Nifty! Sexy!

I even added one other thing! Properties. Other languages provide properties to declare pseudovariables with functions that are called when their values are accessed or mutated. I do similarly, through a bit of metatable magic.

Let’s take an example of a typical RPG player for a second, who has an HP attribute. To declare a property, you can go something like this:

Player._property('alive', function(self) return self.hp ~= 0 end)

You can then use the ‘alive property like a readonly variable, for instance on a player object named bob:

if bob.alive then print("We're still kicking!") end

I might expand this class system to allow multiple inheritance or mixins at some point. Not a high priority, but it’d be nifty!
 
 
 
So yeah, this has been my week. I’d love to hear about yours too! :D

Tags: , , , , ,

No comments (make one!)


Composting misspelled off-colour vegetables.

Posted by Overkill on November 16, 2008 at 9:40 pm under Uncategorized

People were right. I was pointlessly reinventing the wheel in an attempt to make something that nobody would’ve used anyway.

I discontinued Brockoly.

I was hitting major roadblocks, and redoing code that I didn’t really want to rewrite from the bottom up. I would never finish by myself in this lifetime.

However, I still assert that I learned a fair deal while suffering of Not-Invented-Here Syndrome. I learned how to write C++ code better, and how to do slightly-complicated software image blitting techniques. I also took a heavy inspection of ways to structure internal file formats like sprites, tilesets, and maps (which I am actually interested in — and what threw me into making my own engine to begin with).

But this madness stops.

Now.
 
 
 
From now on, this engine know-how should be invested smartly. I should be fixing things that are already out there. Things that just need improvement. Fix the wheel, don’t make a new one.

Verge is a great candidate for this. It’s already enough-to-make-games-with, just needs a push to make the whole ordeal of making a fully-fledged game a less tedious experience.

I think the internal engine stuff should be improved. And now let me go on about how.

Entities must have custom animation strands.

The .chr file format itself should allow animations to be scripted. This way you don’t need to write a custom animation system on top of Verge’s. This means that you can tell your hero to strike a victory pose without having to hardcode “F10W10F11W10B” and such in your engine — and it allows sprite editor to handle all sprite animation instead of HAVING to write out code for it.

Entities and Layers should be referrable by name.

So you don’t need to memorize index numbers. So now you can say in your script something like “Move Bob” instead of “Move Entity 34″, or “Change the rooftop transparency” instead of “Change the transparency of Layer 23″. It keeps you a lot more sane, and prevents scripting mistakes from creeping in.

Obstructions, Entities and Zones should be on each Layer.

Allow every layer on the map to have an obstruction channel, zone channel and entity channel. Instead of ONE obstruction layer, ONE zones layer, and so on. This, in turn, allows you to have bridges that you walk both above and below, without hacky tricks.

Maps need Waypoints.

Waypoints would be for a single spot on a map that have a name (constant lookup by name) and allow you to work it into your scripts quite easily. It would allow tile regions on a Layer to be referred to by name.

This is different from a zone, because Zones are for many spots on the map that all share the same events (constant lookup by (x, y) position).

Additionally, this single name to single position mapping means it’s ideal for pathfinding!
 
 
 
So say you have a water fountain, and you want your player to walk towards it. Currently, you need specify an exact path to walk to the fountain through a series of EntityMove(player, "X10Y11U10L10") like commands probably with a bunch of if statements and stuff.

Contrast this with just saying something like EntityMoveTo(player, "fountain"), which could pathfind automatically. It could be pretty quick about its search, and maybe have a restraint on distance to pathfind from, after which you could chain a bunch of Waypoints together and move from point to point.
 
 
 
Perhaps more interesting is, say, when you have a bunch of treasure chests on a map.

You can use zones for their activation on map, and waypoints for actually telling where the chest IS on the map, so you don’t hardcode positions.

So when you return to the map later, and need to set tiles for all the chests again, you can change the tiles at the waypoints! As opposed to needing to write coordinates in your map startup event, which gets messy quickly.

LuaVerge needs to be faster.

LuaVerge, the new twist on Verge, which has Lua instead of VergeC for scripting. Lua’s a language that I figure could replace VC at some point, because it’s much more expressive, and less restricted. LuaVerge has a lot of potential.

Sadly the potential that has gone sour by the fact that the LuaVerge is several magnitudes slower than the VC version right now. Surprisingly, the problem isn’t Lua, or its helper LuaBind. It’s our code that glues Lua into Verge. It was supposed to be fixed a long time ago, but I never figured out how to represent array-of-structure like things through LuaBind directly.

LuaVerge needs to play nice with packfiles.

Right now Lua scripts need to be outside of .vpk files, because otherwise they can’t be included by Lua. In short, this means people who release demos have to include source, which could be fun-ruining. Also I respect peoples’ desire to have their code stay private, just so nobody outright steals stuff.

This is probably a fairly easy fix, just make the Lua code use verge’s I/O stuff instead of the <stdio.h> library that comes with C. Kind of hairy though, since you need modify Lua itself.

I need write tutorials for vx.

So, vx (Verge eXtension) is my little code library that makes LuaVerge even nicer to use. The problem is, I need to write a tutorial on how to use it. Unexplained code means very few people are going to jump on it.

This brings me to my next point…

I need to entice people to switch over to LuaVerge.

Right now almost nobody uses LuaVerge, and I know that’s mostly because nobody has been encouraged or taught how to use it. So we need to get people interested in the newer Verge and to demonstrate how it’s better. Ey, ain’t that right, Kildorf, ustor?
 
 
 
Anyway, that’s a lot to think about. Hopefully I can redeem myself of my grand suckitude. School is murdering me, so I want my dev time to be useful and rewarding. That is all.

Tags: , , , , ,

4 comments


Gruedorf: New Years Resolution?

Posted by Overkill on October 20, 2008 at 6:00 pm under Uncategorized

So this is the second year into McGrue and Kildorf’s fearsome competition known as Gruedorf.

What did I do in a year? This list summarizes it pretty well:

  • I lost Gruedorf several several times.
  • I added new features to Verge 3, and fixed the new Lua side of the scripting
  • I was one of the first people to use LuaVerge in a project, though Kildorf was the first to post
  • I made a scripting improvement for LuaVerge called vx (which you can read about here). Basically like Verge with OOP and awesome. Ustor uses it in his space game!
  • I made a data language called Mungo, which was basically a human-readable replacement for plain-text file formats. Better than XML in some ways, because it doesn’t have annoying tags, it just has bulleted lists with colons. I use it in my own projects at any rate.
  • I worked on a sidescrolling Metroidvania game idea I had for a while, called Resonance, which you can view the work-in-progress for with an SVN client from: http://www.verge-rpg.com/svn/resonance/
  • I attempted to create my own file formats for maps, tilesets, and sprites. And also thought about a container format known as a “world” that basically joins up a bunch of maps seamlessly. Unfortunately the results of this were…
  • …I got frustrated with existing game engines to an extent, and decided to make my own game engine from scratch which I’ve called Brockoly for the time being. I’ve been developing it under both Windows and Linux. You can view the intermediate C++ source and current crappy demo from: http://www.verge-rpg.com/svn/resonance/branches/Brockoly
  • This website was formed (thanks to Grue and Zeromus for hosting). I updated this website a tad, with a few different layouts. It’s been through varying degrees of eyesore. I think it looks better, but it’s still got a while to go. Plus it looks pretty damn broken in older low res browsers. I need to rehost all my games here :/
  • I drew a bunch of random pixel art. I think I finally am starting to get the hang of spriting in ways I never did before!

Speaking of art, I never posted this here, but I’ve been making changes to Resonance’s protagonist sprite with the help of Pixelation (a site dedicated to learning and critiquing Pixel artwork):

Anyway, most recently, I’ve put in my sprite system. It can do all sorts of funky things so far, like custom frame dimension stuff, hotspot setting, custom animation strands, transparency, and sprite rotation. And it uses Mungo! Really, not especially impressive, but it’s a start.

Anyway, seeing as it’s a new year of Gruedorf, maybe some resolutions are in order. If they’re anything like typical resolutions made on New Year’s, they probably won’t be kept. But like New Years, I can sure try!

My resolution: To lose 450099030984534095 pounds to actually post more on Gruedorf. And to be less lame.

Sadly, with school my attention gets diverted a lot, and I am typically pretty busy. So I’d appreciate nagging and support to keep me posting more!

In fact, it was McGrue who was nagging me to post this week. You should nag me too!

Anyway, maybe year two of Gruedorf will fare a little nicer!

Tags: , , , , , ,

1 comment


My Big Throbbing Love Organ

Posted by Overkill on February 24, 2008 at 2:21 am under Uncategorized

Yeah, that’s right, I drew a cutesy heart icon. Why, what did you think the title was referring to? Sicko.

Using it, I added a animating health meter to Resonance!

Get it here.

I’m not sure if this is this the sort of health gauge I’m going to stay with, just need something for now. I might switch to a percentage-style meter system which Megaman, Cave Story, Kirby Superstar, Castlevania, and a ton of games use. It’s a little more nice than a tick-style system, in that you get in-between health amounts, but slightly less fun to look at, because there’s less artistic representation usually with these sorts of gauges. Then there’s Metroid, which has several energy tanks and an active tank which has a health rating out of 100 (plus reserve tank which effectively doubles the tanks you get).

Oh, and then I need to think! How will underwater breathing work? Lots of games just let you breathe without penalty (NES/SNES age Marios on levels where water isn’t a deathtrap, Metroid, Kirby), or somehow keep you from going in water until you get a proper ability (Link to the Past), or keep you from going underwater but you can still swim until you get an ability (Aria of Sorrow). Then there’s Ocarina of Time, which had it so you’d just float back up after 3 seconds of diving (unless you get stuck underneath something, then I think you got hit with damage until you surface). Then there’s lots of games where you have limited air supply and start taking damage after air supply runs out. Cave Story took this too far, and just had you die instantly after about 15 seconds (100 air) elapsed without surfacing, which I didn’t like. Then I remember Mario 64 (and Sunshine, and maybe Galaxy, too?) had this wacked out health system for breathing underwater that overlayed your current health. Oh, the dilemma of water handling in video games!

Moving on, you can take a deep breath again, I find thinking about water levels a lot affects my breathing slightly!

I recently cleaned up a lot of unused files, and renamed the ‘chr’ folder to ‘sprites’, because none of the sprites use Verge’s CHR system (instead they use Mungo, a simple associative data language!). I might eventually move all my resource files into a folder called ‘resources’ or ‘res’, just to tidy up things and give my data a bit more hierarchy!

Oh, and I renamed my ‘v3′ namespace to ‘vx’ after Kildorf and I decided to rename the ‘LuaVergeRaw’ (internal v3 binding) package to ‘v3′, which was a better name. vx stands for Verge eXtension!

Since I don’t know how much I mentioned it before, vx is a slightly object-oriented approach to wrapping the v3 library, addressing some personal gripes with the classic library and making it nicer to compose with OOP. Kildorf seems to be doing the same thing, but I’ve did it first! I made my library before anyone actually knew LuaVerge existed! Zeromus and I meant it to be the official middleware wrapper to LuaVerge, but unfortunately there were a few things holding it back, and I’ve since decided that the ‘classic’ verge library should still be accessible to those that aren’t comfortable adapting to a new API.

Nonetheless, vx is kickass. Some people might appreciate its slight similarity to ika’s library, but it’s nicer to use in some aspects. For instance, a vx.Image is more powerful than ika.Image and ika.Canvas combined (in terms of how easily it can be manipulated — not so much render speed sadly). I think this could definitely be useful for those ika users who are on the fence but like Lua. Additionally, it can be intermixed nicely with the raw, classic bindings of Verge3 (which are also pretty solid) when this alternative API seems to be too much of a stretch. So if you were interested in LuaVerge, but wanted an alternative library that caters to your Lua script-kiddie OOP-seasoned mind, you might want to use vx! If you have questions about using this library, feel free to post on the regular Verge help forums, since I endorse this, and I want to make a usable game making interface.

I would NOT, however, recommend jumping to a new language midproject. If you’re actually getting somewhere using VergeC, why waste more time to learn a new language, and then rewrite your code? LuaVerge is certainly easier to pick up than VergeC, if you’re starting something NEW though!

Oh yeah, and I have an SVN for Resonance now, for those that are interested: http://www.verge-rpg.com/svn/resonance/ (username: anonymous password: anonymous). The latest version of vx is always included in this SVN (for now, and hopefully forever). And here’s the vx documentation for those who want to see: http://www.verge-rpg.com/svn/resonance/vx/docs/vx_readme.txt (once again, you’ll need that SVN password). (Update: Things changed a bit. Please see http://www.bananattack.com/vx/ for the latest information about vx!)

In other news, Thrasher, the metric unit for failure, has returned. Now I’ll have somebody else to make fun of again!

Now I depart. Look forward to more meaningful progress again on Resonance soon!

Love,

Overkill.

Tags: , , , , ,

2 comments