Isometric reveal mechanism wip

A short demo of the mechanism of revealing the Player behind certain elements in the scene. Still rather rough; some adjustments are needed, but the principle seems to work.


The image below illustrates the implementation.

The mechanism consists of 3 colliders, and elements that have a reveal attribute that can either be always, back, front, top.

The 3 colliders are:

  • frontface_reveal_collider
  • backface_reveal_collider
  • top_reveal_collider

The procedure is:

  • When the frontface_reveal_collider overlaps a reveal=front element, then that element becomes semi-transparent.
  • When the backface_reveal_collider overlaps a reveal=back element, then that element becomes semi-transparent.
  • When the top_reveal_collider overlaps a reveal=top element, then that element becomes invisible.
Advertisements

G.M.A.C. – Give-Me-A-Chance™ Hit System

When I started to think about the hit-chance system for combat, I wanted to address the ‘consecutive hit/miss’ issue that pops up in turn-based games. Even some of my own favourites games, like X-COM have players complaining of their questionable bad luck (naturally, no one complains of good luck).

Citizen is a real-time game. The random-hit issue presents itself differently from a turn-based game. I think the issue is more glaring in a turn-based game because every shot is felt. Nevertheless, as my iterative test showed, this issue is still relevantly noticeable in real-time game.

Luck vs skill

I think that the root of the issue with this game design is the distinction between luck vs skill. If we say that I have a 25% chance of hitting, and then proceed to roll a d8, and hope to get <= 2, then, that’s the concept of luck as all dice rolls are.

But in combat, it’s not all about luck; rather, it’s more about skill. When we say that we can hit a bulls-eye 25% of the time — contingent on factors affecting accuracy — we are likely referring to a fact, not a chance. To say that I can hit so-and-so 25% of the time means that I would have gone to a firing range, shot some rounds, and observed how many rounds have gone in the #1 ring and how many have landed outside. Then I would repeat this process until I get an average percentage, which becomes a quantitative representation of my skill level. This is the principle of skill, which I wished to represent in the Give-Me-A-Chance (GMAC) system.

Randomness

Some folks think that the problem with pseudo-random numbers (also referred to RNG — random number generation) is that they are ‘pseudo’, rather than ‘true’ random numbers. For the purposes of rolling for a hit that technical distinction is irrelevant. The important aspect about RNG is that whether they are ‘pseudo’ or ‘true’, they they depict luck rather than skill.

When you view a graphical representation of random numbers, they do not form any coherent shape, making them suitable for unpredictability.

But in a combat system some unpredictability is necessary. But the unpredictability needs to be felt in the details of combat to give it an organic touch. But unpredictability shouldn’t be felt on the wider scope of the whole combat system, which is the complaint of most players.

Give-Me-A-Chance

Enter GMAC, which tries to balance the hit-chance based on previous hits/misses. This means that the hit-chance (i.e. the skill level) is being modified based on the success rate of hits. In short, GMAC is intended to make hit-chance feel like the percentage it is depicting.

As an example of why RNG without modifications feels like luck, we run a random number generator for 100 iterations. For each iteration, it compares a random number to 75%; if the random number falls below 75%, then that’s considered a hit. Then the average percentage for those 100 iterations is shown.  Then we run it 10 more times (10 cycles). This is an example of the results:

Each line represents a single cycle. Remember that the percentages are averages of 100 comparisons per single cycle. This means that for cycle # 3, the average percentage was 7% higher than the target. And at cycle #9 it was 5% lower, giving a total range of 12% difference, which is rather a big deal.

Success rate

The principle behind GMAC is counting the success rate of shots. The basic principle is this: when you shoot the first round, you roll against your hit-chance, which is your basic skill level, which we’ll set as 50%. If you hit the target, you would have had a 100% success rate (1 out of 1 shot). Because you are 100% successful so far, and your skill level is 50%, your next hit-chance would be penalised to, say, 1%.  If you make the second shot (roll below 1% — yes it’s actually possible!), then you would continue to have a 100% success rate, and your hit-chance continues to be penalised to 1%, which you will likely not keep on hitting for long.

On the flip-side, if you missed the first shot, your success rate is 0%, and your hit-chance is given a slight bonus so as to make you more likely to hit.

Like a true socialist system, it helps you when you’re down, and when you’re getting too successful, it shuts you down.

Compared to the previous random hit-chance test, the above image shows GMAC modifying the hit-chance. hit_chance is incremented, and average is the result of the GMAC operation. The closer average is to hit_chance means that it is working.

However, you can see that in the hit_chance:12 there is a large 3% discrepancy. This occurs in the lower percentages (< 20%). GMAC represents higher percentages far more accurately than low ones.

Shot count

I had to decide how many shots I wanted to track in order to compute the percentages accurately. As I’m tracking each shot that fires, I have to know when to ‘give up’ and reset the counter. The primary reason for this is the assumption that the hit-chance changes over time. For example, if the Player is moving towards the enemy, the hit-chance increases. If I track too many shots, then I would potentially be comparing the success rate of another hit-chance that is drastically different from the current one.

Of course, the downside of tracking too little is that I won’t be able to represent the accuracy of certain the percentages  because there wouldn’t be enough ‘resolution’ for the math to compute.

In the actual GMAC v1 algorithm, however, once properly tweaked, it seemed like 10 shots satisfied all requirements; resolution was good especially when I simulated the shot series over a thousand times.

Low percentage

There was a peculiarity with the algorithm, which I think was related to the fact that I decided on counting 10 shots.

The lowest percentage I could track was 10%, which is logical, since any hit-chance above 0% is going to be adjusted to have at least once in 10 shots, giving it always a minimum of 10%. Thus, combat skills should always resolve to anything above 10%.

 

Hit-chance and GMAC

Note that GMAC is a modifier. The actual hit-chance is calculated by the factors governing the combat mechanics; weapon accuracy, weapon range, Player skills, etc. Then that ‘base’ hit-chance is passed onto GMAC which takes care of the balancing for success rate.

I think the GMAC modifier is a good RPG combat concept. It allows randomisation on a shot-by-shot basis, but will endeavour to reflect your actual skill level by increasing or decreasing likelihood of hitting based on on your success rate. Hopefully, this replaces the feeling of being unlucky with the feeling of being unskilled.

 

 

Inventory

One of Citizen’s gameplay themes is the limitation of what weapons you can use. As a citizen of a dystopian, Robot-controlled city, you couldn’t freely carry dangerous goods and not expect to be accosted by Robot patrollers.

It was in the INV system that I first wanted to express that game concept. The INV system was originally conceived so that the Player can carry only a few weapons. So I delineated certain types of items can only be placed in certain ‘slots’. I also limited the number of slots for a particular category.

However, in time, I came to think that the limitation was a bit too extreme. It was complicated from the point of view of mechanism, but it also had logical game problems.


Nearly 3 years ago I was working on an RnD game project (dubbed Henry) which was supposed to feature multiple characters. The system allowed the viewing of different inventories within the same interface, and allowed trading between characters through a drag-and-drop mechanism. It featured multiple pages and a categorisation of items; weapons and armour were automatically put into the upper slots, and other adventure items were put underneath.

The Inventory system from the RnD project called ‘Henry’. I think there’s a bit of Jagged Alliance in the graphic design decisions…

It was Henry‘s Inventory system that gave me my first experience in the in the difficulty in doing inventories, from the organisation of items, to the behaviours of drag-and-drop and how the logic of how things are arranged and displayed.

Also from Henry I took the idea of categorisation, which is the exclusive placement of items of a certain type into a section of slots in the interface.

But categorisation, I later decided, was not necessary if I was just simply gunning for weapon limitations. There were other ways of discouraging the Player from carrying too many, from the increased likelihood of getting checked by Robots, or simply the inability to use them effectively once the shooting started.

Because there were hundreds of ways to skin the limitation cat, I eased my rigid rules in the INV system. However, unlike Henry I had two other Inventory-related concepts that I had to address to introduced their own complexity: Readyslot, and Trade.

The Citizen INV (right), Trade( left) and Readyslot (bottom-right) interfaces.

Readyslot

Without going into too much details about the the Readyslot’s mechanics, it is simply the place where weapons that will be used immediately for combat are put.

Switching weapons that are already in the Readyslot are done immediately. However, there’s a time-delay when you try equipping weapons from the INV, which may be akin to taking something from your backpack. This is how the game discourages the Player from swapping weapons from the INV which may potentially contain a lot of different weapons in the game.

There are other characteristics: there are only 3 slots in the Readyslot area, and that is significant. Pistols are 1-slot weapons, subguns (i.e. SMG) are 2-slot weapons, and rifles are 3-slot weapons. You can mix and match any weapon configuration that the number of slots numerically allows.

But there are special considerations for pistols, too: you can dual-wield pistols.

If you choose to equip a subgun, you can carry another pistol as ‘backup’.

If you choose a rifle, the most powerful weapons in the game, you are limited to that weapon only, and if you try to change weapons from the backpack, there’s a time-delay to get it.

The technical challenged associated with the Readyslot is how that in itself is an extension of the INV system even though it may not look like it visually. The Readyslot is a categorisation, so only weapons can be placed in there.

Trade

The Trade system is essentially the INV system, but using a different source for the contents of the INV. For example, NPCs have their own INV database, and even scene elements, like a rubbish bin that can potentially hold items, have their own INV system.

The Trade system is a little different from INV in that there is a variable slot designation that is dictated by some database (in this case it’s specified in Tiled). For example, a rubbish bin will have 2×2 Trade INV (a.k.a. TINV). A dead robot will have 1×1. Some may have 3×1, or 4×2, etc. And thus there were many considerations about how the system will respond if there was an attempt to populate the TINV with more slots that it could hold, or items that wouldn’t fit the dimension of the slots. For example, a 3-slot rifle cannot fit in a 2×2 TINV.

Slot size, width and height

In games like Diablo, items occupy ‘slots’ in the inventory. But Diablo’s system is very elaborate, as items have both width and height. For Citizen, I decided only to consider how many slots a certain item will occupy. For the most part, only rifles and subguns occupy more than one slot. This greatly simplified the system.

The reason why this is a big deal is because one of the challenges of making an INV is the correct display of items in their proper slots. When dragging a rifle (3-slots) at the right-most slot of the INV, you expect the system to compensate for the size; it must not place it the right-most slot, but 3-slots to the left in order to the rifle to fit the intended placement location.

Also, you have to consider if there are items currently in place in those slots. Will you allow items to be displaced? If so, how do you logically re-position them that makes intuitive sense?

If dragging a rifle from the INV to the Readyslot that is already full of weapons, will you make a swap? Or disallow it?

It’s questions like that, and every conceivable permutation of how one item is dragged from one place or another, dropped onto itself, or another dropped onto it, or something else entirely, all those things filled the 2 weeks I spent designing and iterating through the INV and Readyslot systems

The multi-page function isn’t yet implemented, but I have to make sure to what extent I implement it. How many items will I end up implementing in the game’s narrative and combat? How many pages will it fill? Should I have unlimited pages? Or is one page a good simply limit?

Lots of questions. But it’s all part of the fun, right?

 

AI and dialogue using node graphs and custom language

One of the significant progress milestones I’ve done since the beginning of March was the implementation of a system I call Convo and a rudimentary NPC AI that allows NPCs to move/wander and do things randomly, if their base purpose allows it.

To achieve the implementation, two fundamental concepts had to be developed. The first is SNTX, and the second is the usage of the TGF to express nodal networks that are are interpreted at runtime.

SNTX

SNTX is a procedural markup language designed to be injected into dicts. The resulting dict keys are procedurally looked-up to get to a resulting value.

SNTX is a significant upgrade to the TalkDialogue system that I developed in 2015.  The difference lies in the robustness of handling Conditions, as well as clarity. The idea behind the TalkDialogue and SNTX markups was the ability to author a dialogue tree using a text file. By and large this has been possible, but the branching nature of dialogue trees makes writing everything down in one linear text file still confusing. It was this reason that I looked to yEd in order to visualise the dialogue tree .

Conditions

One of the important aspects of SNTX is the concept of Conditions. Conditions are simply asking: is this node valid? If a node has a Condition, the Condition must be True in order for the node to be processed by the system.

Conditions check 3 things:

  • Accomps – a global dict that represent arbitrary ‘accomplishments’.
  • State – the NPC’s ‘state’ variable which is essentially a CSV string, and can comprise any number string tokens describing its state
  • INV – the Player’s Inventory can be searched for a particular item, for a particular quantity.

Doers

The other side of Conditions are Doers. Doers set Accomps or an NPC’s State. Within the Convo (and Astrip) systems, a node is capable of executing a command telling to either add/remove/modify a key in the Accomps, or amend an NPC’s State. It also allows transferring of items from NPC to Player, and vice-versa.

With Doers and Conditions combined, it allows me to script an interactive storyline.

In fact, I have completed a sample quest using all these systems as an early-stage trial for the prototype. I’m happy to say that it also involves having to kill a Robot.

yEd and TGF

yEd is a very capable diagramming application. It has become my weapon of choice because it is one of the very few programs that allow TGF export. TGF (Trivial Graph Format) is a super-lightweight nodal graph format that, when coupled with a well-thought-out markup, can solve a large number of data relationship issues.

My usage of yEd and TGFs began with simply creating nodes that were labeled as SNTX keys. I drew edges that served as annotations to their relationships, though they didn’t actually define the relationship. That is, except for Choices: for every Topic a line can be drawn to a Choice, which will then be recognised by the TGF2Convo converter tool (explained later).

A Convo graph. ‘choice’-labelled edges are the only edges that are processed in the TGF.

The above image shows Topics (yellow), Choices (green), Doers (cyan), ChoiceGroups (pink), Entry (white).

The labels in the nodes reflect directly as it is written in SNTX. When it is written in TGF it looks something like:

4 ==intro -1 ~text:: [The man seems to be so worried that he hardly notices you when you come up to talk.]\nWha? Oh, hi. You must be the new recruit. My name's Zak.
5 ->::intro
6 ++worried ~text:: Worried
7 ~dostate::+met_player
8 -> ?@met_player,$!zak_quest_rejected::intro_hi_again
9 ==intro_hi_again -1 ~text::Hi, again. 
10 ==worried -1 ~text:: I've lost the Sub- Rail pass that I was issued with. My team leader is going to kill me.
11 ++subrailpass ~text:: Sub-Rail Pass
12 ==subrailpass -1 ~text:: I don't know where I might have dropped it. I swear it was in my pocket.
13 ++quest ?@!questaccepted ~text:: [...]

This is translated using a Python script called TGF2Convo, and the output looks like this:

# EntryTopic: Entry for cond -----
->::intro

# EntryTopic: Entry for cond ?@met_player,$!zak_quest_rejected -----
-> ?@met_player,$!zak_quest_rejected::intro_hi_again
# Topic: intro -----------------------

# ~text
==intro -1 ~text::[The man seems to be so worried that he hardly notices you when you come up to talk.]\nWha? Oh, hi. You must be the new recruit. My name's Zak.

# ~choices
==intro -1 ~choices::worried

# ~dostate
==intro -1 ~dostate::+met_player
> Choice
```yml
# Choice: worried -----------------------
# ~text
++worried ~text:: Worried

# Choice: subrailpass -----------------------
# ~text
++subrailpass ~text:: Sub-Rail Pass

The TGF2Convo tool uses Markdown syntax so that when a Markdown viewer is used, it is easier to understand.

Ultimately, the dict is populated with these values, and the runtime uses the dict to determine the path of the dialogue.

However, this is not my ideal way. I had developed SNTX ahead of using TGF. Since using TGF with AI, I realised that utilising TGF fully would be a better way to go for dialogues, but this requires a re-working of the Convo system. This might be done at the end of the prototype phase.

AI and TGF

After the Convo system and SNTX were developed, I had to jump into AI. At that point I had two choices: I could go and write the AI in C2 as events, or I could attempt something much harder, ultimately more flexible, and platform-agnostic. I chose the latter.

When looking at what I wanted to do with the AI, I decided that I just needed a very simple system of controlling the actions and movements of NPCs (not the enemy NPCs). I outlined the requirements of what it would take for an NPC (Zak) who has lost something and is wandering around a given area.

First, there is the point of movement. The NPC should be able to use waypoints. Second, the NPC should have some random ability to use waypoints. Third, the NPC should have some random wait times. Fourth, the NPC should have random animation.

With all that in mind I went into the specifics of what components need to exist to make that happen. I needed:

  • ability to set NPC variables
  • ability to query NPC variables from within the AI graph
  • ability to initiate a ‘move’ (pathfinding) command from the AI graph to the runtime
  • likewise, the ability to ‘wait’
  • the ability to stop
  • the ability to have AI graph randomly choose between named choices
  • the ability to receive event handlers from the runtime
A portion of Zak’s AI graph
The AI at work. Zak is the guy with red pants. 🙂

Event handlers

When I started developing the AI, I would click on Zak to talk to him. A ‘Talk’ icon would appear, but Zak kept on moving. Though I could have effectively paused the game so that I could properly select the icon before Zak walked away, I thought it would be better to tell the AI to stop Zak.

That’s when event handlers came into the picture, which also brought forth a host of different possibilities. For example, I created an event handler called onastrip, which is called when you try to initiate an interaction. In the AI graph, this event handler is connected to make Zak stop. If the icons are ‘aborted’, the event onastripend is fired, and the AI graph is wired to make Zak resume where he left off. When a Convo is initiatedonconvo is fired, and this stops him, too. When Convo is ended, onconvoend is fired.

If a waypoint is missing, there is a wpmissing event that fires, which allows the AI to adjust itself in order to get a proper waypoint index.

The idea of ‘events handlers’ also gradually slid into the other aspects of the AI graph, where ‘events’ are triggered as a result of an operation (a Doer). For example, a choose node chooses between one of any number of events to fire. As long as that event handler is present, then it is a valid event.

Example of a `choose` node. `0`, `1`, and `2` are not really numbers; they are event names and when `choose` chooses an event the handler should be named `onchosen <event_name>`.

There is an immense satisfaction in working this way. There’s definitely a lot more work involved, but it brings the systems I’m working on at a higher level of flexibility, while at the same time, it’s still within the realm of my understanding since I’m the one developing it.

Although I don’t know how much of the AI, in particular, will make it through the Unity alpha, it is undoubtedly a very useful  piece of development because it informs me of the kinds of behaviours I may need to do; which aspects to simplify, and which aspects need more complex behaviours.

 

Why not C2?

(This is a follow-up post to my other one which explained the reasons for choosing to remain working in C2).

When I review this whole venture, it stems from the desire to create a game on my own.  I want to create the graphics, the logic, the story, the words, the music — everything — like how those guy did it back in the day when I was a wee child playing their games.

I came to use C2 because of its simplicity, and the quickness in which I can throw something together and get results. There’s nothing like instant gratification that hooks you in.

But as project size increases, so do doubts about working in C2. Lots of niggles, lots of creaks and groans give me doubts as to appropriateness of the engine/framework for Citizen. A framework is a convenience. But everything out there is a convenience except C++. I could have approached Corona or Phaser, I could have used Godot or Unity, and some of them might have been more suited to the task.

When you turn to an established game engine like Unity, you don’t tend to have that many doubts that your main goal is achievable if you were clever enough to code/design your game well. That’s because you see the sort of games that have already been developed and you can’t really argue with the fact that Unity is established for a reason.

Then you take a gander to notice the sort of games that C2 is generally used for, which is not the sort of thing Citizen is. There are plenty of developmental previews and tutorials of isometric games, — none of them are serious enough to take umbrage — but no finished product as far as the Search Engine can see.

Then one day, you come upon some kind of undesirable behaviour that you have no control over (because Construct is a very blackbox environment). You start weighing in the facts: that C2 isn’t being developed any more; that critical bugs appear in the latest builds; that downgrading is the only recourse because the developers will likely not fix it because they are committed to C3, an app whose design philosophy doesn’t nearly tick enough of your own boxes for you to use with dignity.

These leave you imagining the sort of adventures you’ll have with this little boat, which will receive no more refits, as it takes you across the pond. What awaits you, who knows? But there are tales of show-stopping, insanity-inducing odds, and some are journalistic facts as the asset obfuscation that you won’t get.

 

 


At the end of the day, it’s a ‘use the right tool for the job’ situation. And as the days go by, C2 (and C3) are becoming less of the ‘right’ tool to actually publish a game. But as many C2 users know, C2 is great at prototyping. And so at prototyping it will be relegated to.

Even if from some miracle I complete the prototype and I am able to scale it to encompass the scope of the game I want to make, it will still be a hard-sell for me to publish the game in C2 because of the absence of even a rudimentary obfuscation method: another design philosophy that didn’t get ticked.

We shall see…

Another method for z-sorting

Z-sorting has been, in my experiments, been based on the Y value of a given Sprite object. It’s the sorting mechanisms have been specifically explored rather than the logic that they were arranged.

In this post I want to describe an alternate method to sort using collisions.

This method was developed to solve the issue of complex graphical elements. By ‘complex’, this refers to images that are possibly concave, or elongated. In previous z-sorting implementations, the Sprites being sorted needed to remain within a given Tile area in order for the Y position to be specifically determined for that graphic element to be properly sorted. So what I aimed to do is to overcome/get rid of the limitation that forced discrete graphical elements to remain within one Tile.

Consider the image below.

Note the elongated ‘wall’ and the L-shaped wall, both of which implicitly extend beyond one Tile area. The goal here is this: given these irregularly-sized/shaped elements, find a way to determine whether the character Sprite should be sorted behind/above the ‘walls’.

First I considered finding intersections of 2d vectors in which to construct a depth stack, but then thought it was too computationally cumbersome as an initial approach. Furthermore, this required multiple definitions of 2d vectors if, for example, the shape of the ‘wall’ was L-shaped. Note that the bottom edges were the 2d vectors that were being checked against the character’s position and vector which was, in turn, based on the isometric tile ratio, which determined the vector direction to check with. Again, very cumbersome.

So I came upon an idea of using collisions for a check. The logic is simple. If the character’s base position touches (collides into) a wall, it will be set to be behind the wall. This is the starting point and main principle of the method.

The image below describes it in C2’s event sheet.

The main Sprite being sorted is pc, and mover is the collision line. pc is pinned to mover.

The offsets shown in the image above are somewhat arbitrary. What’s important is the principle of the collisions, which are explained below.

The first issue is that the base of the character (a.k.a mover’) must actually be a volume or area, not a single point because the Sprite needs to check for a hit on the full base width of the Sprite.

The red line is the ‘mover’, and is tailor fitted to the width extent of the Sprite that is being sorted. In fact it should encompass the widest width of the Sprite animation. The ‘mover’ is collision-aware, of course.

Second, we have to consider the Y position of the mover in relation to the Sprite being sorted. Ideally, the position should be the bottom vertex of the virtual Tile diamond.  When the ‘mover’ is too high, the collision will occur ahead of time and will seem too premature. This offset doesn’t need to be precise as it is based on the specifics of the graphics, and the parameters of the game’s aesthetics.

Third, the ‘wall’ Sprites must have accurate collision polygons; as accurate as you need them to have.

Fourth, since we are dealing with 2d layers, we need to design our ‘sortable’ graphical elements so that they can split up so that can be sorted at all.

So if we were designing a four-sided room, you can encompass it with 2 elements. The first element is the bottom L-shaped wall, and the second element is the upper L-shaped wall. In this way, it possible for the character to appear either in front, or behind, either of these two elements.

 

Importing into the C2 /Files folder

Auto-importing

The C2 manual references the project file folder which contains other files other than its default.

Even though files and subfolders can be created in this folder, it doesn’t automatically become part of the caproj unless it is actually specified/registered inside the caproj. Inside C2, it is possible to ‘auto-import’ files, but this only works at the root level of /Files; directories aren’t traversed, making this mechanism suitable for single files, like configuration files.

However, when using the Files folder in other ways, such as replacing animation using Rex’s Animation Loader, it would be a monumental task to get all these files in. So I’ve written a Python function that traverses any given folder and writes out a block that can be copied and pasted into the caproj, which is near the end of the caproj. Perhaps in future, I will make the procedure more seamless; right now, the manual copy-paste is for security reasons.

The code below is very unpolished, but gets the idea across.

def make_xml_c2_file_folder():
    ''' Create a folder structure in caproj/xml format with a given directory
        The intention is to create a sprite animation folder in the /Files
        project folder, and have that referenced as imported files in the caproj.
        The output of this function is to be copied and pasted into the caproj.
    '''
    gb = glob_buffer()
    ext = '.png'
    filesdir = 'X:/GAME_PROJECTS/c2/Files/'
    unitdir = 'hero_w'
    rootdir_name = '%s%s' % (filesdir, unitdir)


    rootfolder = CaprojFileFolder(rootdir_name, ext, filesdir)
    gb.buffer += '\n%s' %rootfolder.xml
    process_folder(rootfolder,gb)


    fn = 'c:/outputcaproj.txt'
    f = open(fn,'w')
    for b in gb.buffer:
        f.write(b)


def process_folder(folder,gb):
    for c in folder.content:        
        # print(c)
        if isinstance(c,CaprojFileFolder) == True:
            # print('hi')
            gb.buffer += '\n%s' %c.xml
            process_folder(c,gb)
        else:
            gb.buffer += '\n\t%s' %c
    gb.buffer += '\n</file-folder>'
class CaprojFileFolder:
    ''' The folder class contains info about the folder, eg content, name '''
    def __init__(self, path, ext, rootdir):
        # code below considers trailing / separator like c:/test/folder/
        # where the last -1 index will contain ''. code below doesn't allow that ''
        self.rootdir = rootdir # root for relative path
        self.ext = ext # allowed file extension
        self.name = [x for x in path.split('/') if x != ''][-1]
        self.xml = '<file-folder name="%s">' % self.name
        self.path = path
        self.content = []
        self.get_folder_content()
    def get_folder_content(self):
        mf = matchfiles_full(self.path,'*')
        for m in mf:
            if os.path.isfile(m) == False: # folder
                newfolder = self.__class__(m,self.ext, self.rootdir)
                self.content.append(newfolder)
            else:

                fl = [x for x in m.split('/') if x != ''][-1]
                # check if extension is allowed
                relpath = self.path[len(self.rootdir):]

                if fl.endswith(self.ext) == True:
                    fls = '<file name="%s/%s" />' % (relpath,fl)
                    self.content.append(fls)

The class CaprojFolder represents a folder and the contents of the folder (stored in the content list). An element in content may either be another CaprojFolder object, or may be a path to a file. The caproj code snippet is written in a text file in the C: drive (!).

Once this snippet is pasted over to the caproj new folders and subfolders would be created in the /Files folder the matches the one found in the file system. The only major difference is the name of the actual files, which I explain below.

Referencing the files

Though the script mimicks the file system folder structure, C2 does not use these folders as a path to the file. In other words, C2’s folders structure is purely for visual organisation within the C2 editor. The files themselves are treated as though they were in the root directory. Therefore, I opted to name the files to represent their full relative path.

For example, say the script references a file: hero_w/run/000.png

This file is put under /Files/hero_w/run. But it is also named, literally: hero_w/run/000.png, and not just 000.png as you would normally expect. If I had named the file 000.png, there would be no way to distinguish this 000.png with other files in other C2 File subfolders. So a unique name was necessary.