Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, March 18, 2015

On Programming Languages and Complexity

It's been awhile since I ranted a bit on programming methods. I've had some thoughts on languages recently that I want to write down to help solidify. Bear with me or skip this if languages aren't your thing.

In college I was taught in Java, with a bit of C, and even less of other languages like Python, ML, Prolog. I and Tristan learned C++ to write our first game. Later I took more software engineering courses and learned some new patterns for complicated projects. I wrote a pile of libraries in C++ and got a pretty good handle on it. At Bunkspeed I continued with C++ but we pretty quickly replaced that with C#, which I worked with from version 1.1 until I left. World has been almost entirely C# since its inception in 2007. Now for work I'm working with C++ again, now for approaching 2 years.

So I have a pretty good comparison now of C++ and C#, both used for larger codebases. Bunkspeed's main product was pushing 600k, my current work is around 1M, and the World project is around 150k. I admit I do have better experience in C#; I try to keep that in mind.

I firmly believe that what you can do in one you can do in the other. The limitations of both can be circumvented to achieve the same ends.

 C# has the reputation of being slow, and the problem of being single platform and having a harder time interacting with 3rd party libraries (which are usually native). The slowness problem I think is a red herring; optimizing is usually done at the algorithmic level, which is indifferent to language. The GC and memory management can be controlled if you desperately need to, but honestly you do not. .NET Native coming out soon should alleviate the rest of whatever performance issues exist.  The single-platform issue is improving with Mono and recent C# changes announced by Microsoft. The third party library issue is more complicated and I don't know of a good solution. P/Invoke is not a good solution, nor is C++/CLI.

C++ has the reputation of being fast and powerful, but complex, low-level and imprecise. The low-level issue can be resolved by writing code within C++ to add high-level features. C++ code MUST manage memory, and so large C++ codebases MUST write something to track pointers and allocations. In the end these systems approximate garbage collection, and they work. By 'imprecise', I mean that there are often unanswerable questions, the answers for which are not apparent immediately in the code. The size of pointers and integers, the nature of strings, how 'out' parameters are passed, naming conventions, includes ordering, namespace management, smart-pointer management, etc. All of these things have to be handled in some way by the programmer. And they can be with great grace and power, but they must be handled.

Herein lies my point. C#'s failings are fixed by external structure. C++'s failings are fixed by internal structure.

The upper limit of manageable complexity in C++ is lower, because some of that manageable complexity is ubiquitous and cannot be ignored. When writing in a large C++ codebase, you cannot forget about the internal structures that handle C++'s limitations. Every last line needs additional consideration as you ponder string encodings and which of 6 ways to declare your pointers (smart, shared, dumb, reference, constness, etc...).

The upper limit of manageable complexity is higher in C# than in C++, because when the structure becomes more complicated, the code does not. The complexity is managed in a parallel way, a way that does not impact the programmer when trying to read and understand a lone function.

Maybe with time I'll be able to background the necessary considerations in C++ and be able to acheive similar productivity. Or maybe I'm just spoiled by the cleanliness of C# lambdas, extensions, and continuations. The only thing to do is to try and see if I can get there. Tsuyoku Naritai indeed.




Wednesday, September 17, 2014

New panels, Web UI development

Hi :)

So the last week or so has been taken up by rebuilding the formation editting panel. Since we've been moving our UI frontend code to web tech through Awesomium, this means learning a whole bunch of new technologies to manage it. And since I'm new at these sorts of languages, it also means constant retuning and rebuilding of the code. Now that's it's a little more stable I wanted to talk about it some.

First, one of the big advantages of using the web-style frontend, is that you can use it in a browser! So, here's the new panel! Go take a look!

Commander Formation Panel Tester

This thing here is built using a pile of stuff a learned recently:

  • Javascript, of course, since the web runs on javascript. I don't have all that much javascript experience in the past, so there was certainly some learning. The first set of UIs, which have been in the game's main menus for a year or so, use JS of course, but there's good JS, and bad JS, and those menus are... bad JS...
  • TypeScript: I admit it, I'm only comfortable programming in primarily statically typed languages. Typescript is a nice balance between typing and javascript. While it took a bit to learn how to use it properly, since you have to compile it into JS, it's been a noticable improvement for me personally.
  • Handlebars: Handlebars is a templating system to build HTML docs (or JS I suppose) from JS data. My standard coding methodology is to break things down into pieces, yes? HTML/JS/CSS don't really let you do that. Using handlebars to break the HTML bits into pieces gets me some of the way there. Most of the pages I build now use a few templates. Recently I started keeping them in separate files, loaded dynamically when needed.
  • HTML5 Canvas: The main interactive area of the formation panel is displayed with canvas. Turns out that coding to canvas is a lot like using a super-primitive 2D version of OpenGL. Piece of cake :)
  • JQuery / JQuery UI: JQuery of course is largely requisite for some kinds of JS development. I know it's not truly necessary and that there are other options, but I don't have a personally compelling reason to switch. JQuery UI is a bit of a different beast. We use it mostly to set up buttons with consistent styles, tabs, sliders, checkboxes, and other core UI elements. I'm not sold on it, but it does seem to work well enough so far. 
So mercifully the frontend code is becoming less of a mess. With other bugs getting fixed in the game's UI management, we may actually be getting somewhere on having a reasonable UI toolkit. 

Took long enough, eh?

Next task is the commander panel; skills and classes and customization. It used to sound like an impossible task, but I'm beginning to think it won't be so terrible. Will find out soon :)

Wednesday, January 5, 2011

Breaking everything!

This is partially another progress update, but I might go into a bit more detail this time. (Turns out after writing it is mostly prose, not so much an update. :p )

First off, I spent the week before christmas on a big big change to a fairly low level in the codebase. It took the better part of 3 days (with probably 5 to 6 hours of work each day) to just get the system compiling again, let alone fully functional! We're talking a low level change here. The full system isn't fully functional again yet, even though the core is working correctly, so you know it's a pretty fundamental change.

Here's the skinny. We've got a good 4 sizable and separate layers of the server side implementation. The lowest level manages definitions of game data (the game database). The next implements that data (the zone implementation). There is another layer to construct that data from a more user-friendly format (stored in google documents, actually). Lastly there are various communication layers built on top of the zone implementation that provide specific functionality that can be consumed by the lower layers.

Most of the layers have very few concerns. (As an aside, it's odd to many people to anthropomorphize code, assigning it thoughts or concerns. To me it's important to constrain sections of code by their concerns, so that no section internalizes too much complexity. It makes a large system possible and maintainable when done correctly, even if it sounds silly and doesn't belong in master's theses).

Ahem; Most of the layers have very few concerns. The bottom 2 don't even know what kind of game we're running! In fact, the server and communications modules don't know either, so half of the 3rd major layer doesn't even know it is running an RTS. The obvious boon for this is that we have a game-agnostic engine. We could use this to make another game! But, er, why? Are we actually going to do that? I can't finish 1 game let alone multiple. No, the real benefit is that the code is simplified when it uses fewer assumptions. The foundation of this engine is simplicity; an entity in the game consists of only 3 concepts; data, states, and actions. Everything can be broken down to these 3, which keeps the zone implementation and game database layers very focused.

Now all that's all good, but it makes elementary interaction with the system complicated. For example, imagine some very very high level code that operates the formation system. This system is extremely dependant on knowledge of the skirmish game. But, since it operates on the skirmish-agnostic data, it has to contain a great deal of additional code to translate the low level data into the higher level data. That makes things crazy hard to work with at the top level!

Relatedly, it turns out that building a scenario is extremely complicated. The nature of spawning enemies, teams, groups, formations, scenario organization, respawns, etc etc, is very complicated! The editor for the zone implementation, since it doesn't 'know' anything about a skirmish, is incapable of making these operations clear. Of course, we could just break our rule and make it aware, but that just makes that one layer extremely complicated, since it has to now know the full details about both layers.

Anyone who's played the game within the last 2 years knows we only have one level. Perhaps that's clear why now. Even I really, really didn't want to have to make another.

So it's time to fix that. I'm building a scenario editor. This is a higher level layer that represents data specifically in skirmish-level constructs, and is then compiled into a zone implementation. The compilation process is the only small bit that needs to understand both layers, and is segregated away from the data manipulation. It loses some power in the process, but it gains orders of magnitude in simplicity and usability.

But just building the same kinds of scenarios is boring. There are a pile of necessary, low level features we've been lacking for too long, and its time to figure out how to include them. The first obvious one is to have terrain and obstacles, rather than an infinite empty plane. This, is what took those 4 days.

So. Originally the world system was built without movement constraints. There was no collision, no intersection prevention, no pathing. Everything could move anywhere. But, when we started implementing the RTS mechanics, we found that horribly lacking, and needed to control space better. We opted for a hex-grid based system, which works well for RTS games. The zone implementation was given a higher layer for managing separate spaces. Some objects used the free mover system (non-game entities, spawners, some ground effects), and units used a hex system.

But this then colluded the hex system away from the core assumptions of the zone implementation. The hex system couldn't be assumed, so a great deal of code had to be written to translate between those layers. Complicated! Hacky! It also means that any collisions have to be done on all layers, and between layers, which is just way complicated. Adding navigation, obstacles, and heights to the combination of systems would be largely impossible.

So I settled on implementing the hex map as a core assumption of the engine. It would no longer be implemented 'on top of' the free mover system. Position of entities would no longer be given in 3d coordinates, it would be strictly in hex-space. Everything from proximity detection, range checks, and basic movement would be done directly on the hex-graph. This meant, well, rewriting everything.

But it means that the graph is the de-facto declaration of the world space. Removing cells from the map or adding new ones controls space. So, if I want a bridge, instead of doing some intersection test or complicated movement logic, I just remove the cells around teh bridge, and everything works. The graph is the world.

But yes, changing over the system was difficult. First, the old scenario no longer even makes sense. It doesn't have a grid, and all the positions are in the old system. The old zone is dead! A new way of building zones needs to be built. So then, obviously the next step is the scenario editor. It's started now, but can't do most of what is necessary. I can create a flat network of hex for the map, but that's just to get us back where we were. I cannot place units yet, nor setup start positions. I can setup the scenario type, btu that's about it.

So we have no scenario. :p But we have a kickass new nav and motion engine! That we can't see.

Back to work with me.

That was kind of rambly, wasn't it...

Saturday, December 5, 2009

A programming aside: SRP in World's code

It's a bit different than most recent posts, but I felt like talking about about good code, bad code, and some of the World's code design that has paid off, in theory.

Divide-and-conquer is a pretty well known strategy, in any field. Any task which is sufficiently complicated has to be broken into pieces to be completed. Needless to say, almost all programming tasks are beyond the mental capacity of an individual to solve. Breaking the problem into pieces is a fundamental task in programming, and most advances in programming, historically, have been to make this break easier.

Now, there are many ways to divide things up. Or rather, there are many ways to combine the pieces together. Some of them are bad. For example, introductory object oriented programming teaches us to split things up by classes, and further by their respective nouns (data) and verbs (functions). This is bad! Very bad. In the long run, you end up with a class with a dizzying variety of tasks, data, and code, none of which may be terribly related to each other. Furthermore, the noun/verb class abstraction often breaks down in terrible ways. They say a square is a rectangle, but try and implement a square and a rectangle class with that relationship embedded and you'll have trouble, I promise you.

Anyway. We all agree that dividing the work up is a necessity. However, as soon as we did the work, we assumedly integrate it back together to form the whole. But, and here's the point, if we have to go back to it, how to we redivide it? We broke up the work, but only once, and then we threw the division away! That seems silly. Why not retain the division somehow, so that if we have to go back to code a year later, it is already divided into understandable components?

This has been codified into a programming principle called SRP, the Single Responsibility Principle. When following this principle, the rule is that any given piece of code must only 'care' about a single aspect of the program. Defining 'care' is tricky of course, but I define it to mean anything I can understand without reference. If the code brings two complicated systems together, and each is too complicated to keep in my brain, that's too much responsibility, and the offending code must be further divided (and conquered).

An anecdotal example. In Twilight 1, each potential action a unit could perform was a discrete class. Each individual class had a large set of knowledge required to perform its job. A 'rob that building' task action needed to know how to move, how to respond to danger, how to rob, and how to return with the results. Not only was each action very difficult to get working, but they inevitably had bugs. The code was too complicated, because it knew too much.

To fix this, in Twilight 2 I implemented an action sequencing system. Robbery was defined as 'Move to Building', 'Rob', and 'Return', and these were reusable pieces. How could this single element, the sequence, possibly be incorrect? It can't. There are no possible bugs. The sub-components can be wrong, but that's not the worry of this action, so it MUST work. I never had to touch the sequences again. (Actually, since I implemented my own scripting language to build these sequences, I overdid it greatly and suffered from second-system-syndrome, but that's a talk for another post).

So yes, Single-Responsibility is good. It makes for a HUGE number of classes, but each one is individually understandable, debug-able, and iterate-able. Ironically, the only good way to get SRP out of traditional Object-Oriented Programming, is to invert the traditional approach. Classes are no longer nouns with function verbs. Classes are now verbs, that operate on classes that are nouns. This separates data storage and activity. Each potentially complicated verb is split into its own responsibility, and life is good.

World's design, entirely on accident, absolutely enforces this paradigm. I didn't even realize it till a year past I had been working with it.

When working with the game entities in World, there are only 3 concepts available for use: Attributes (just data), States (usually implemented as a State Machine), and Actions (which are just functions, but with some attached metadata). When constructing a new action, there is a set of action classes already implemented, which can be used, or a new one can be implemented. An action implementation has a known definition and limited data availability. It cannot possibly do more than an Action is supposed to do. Each action definition, therefore, is extremely easy to understand, debug, or copy.

States are slightly more complicated, since state machines are not a simple construct. A state machine is a set of states (just a number, really), each of which has a set of transitions (conditions for moving to a new state), and behaviors (just some operation again, like an Action). If new code is needed, the only places to hook in are at these two types. Either you make a new transition, or a new behavior. And, like actions, these consist of a very small set of functions and responsibilities. They are simple. There are a lot of them, but each one is simple.

So as it turns out, actions can only act, and transitions can only transit. But perhaps more importantly, only actions can act, and only transitions can transit. This means that nothing else can possibly care about acting or transiting, and that, in effect, simplifies everything else.

Perhaps I should redefine SRP. Single Responsibility Principle: Any given piece of code must only 'care' about a single aspect of the program, and ONLY that piece of code is allowed to 'care' about it. Divided and Conquered.

Wednesday, December 2, 2009

Laziness

Some have said that laziness is a virtue of a good programmer. Perhaps this because a lazy programmer will often do a bit of extra work to be sure he doesn't have to work hard later. We'd rather write an automatic solution than exert manual effort.

Now, I think that's kind of a fallacy really. A really lazy programmer won't bother with the efficient solution, and just plods along doing whatever works. Perhaps there is a Ballmer-peak-esque point where laziness yields maximal efficiency, however. Indulge me in a brief allegory from the engagement implementation.

In Skirmish, there are two tables of hostile-entity information retained. First is engagement, which is a constant value, and is recalculated every 2 seconds. Second is damage-threat, which is additive, but decays at a rate of 5% per second. The only important yield from all this data is knowing which entity is on top of each table, and then combining the two tables to know which entity is the overall 'winner'. Remember, the entire system is event based, so we won't be asking who is on top and reacting. Rather, we need the system to tell us when the top entity changes. Furthermore, we apply a threshold, and define this threshold to be 10%. Only when a new entity reaches 110% of the current maximal entity, will the event fire.

So there are three cases. First, a newly applied engagement value trumps the current top. This is extremely easy. We are informed when engagement changes, so we can easily fire the event if the math is correct. The damage-decay is easy to manage, since at any given time we can compute the new value correctly and easily. Equally easy, is when a newly applied engagement value is the previous top, and is now no longer top. Very easy to implement.

Second, a newly incoming damage-threat rises above. Also easy for the same reason.

The only tricky case is handling transitions due to damage-threat decay. Herein there are several cases as well. First, one damage-threat drops below another due to decay. But HA! This is easy. Each threat decays the same exponential rate, so they are guaranteed to never cross, however long time passes! Piece of cake, unless someone decides they want damage-threat to decay at different rates per class. We'll just pretend that'll never happen for now.

And now the point. What if damage-threat decays below 90.9% of the top engagement threat, so that engagement is now 10% greater than damage-threat? Since the decay is implicit (that is, it is never calculated and assigned a new value), we would have to compute the future time where the decay reaches 90.9% of max engagement, set a timer, and wait till then. While the scheduling system World is written on makes that sort of thing easy, I think you can guess my reaction. I decided that that was too much effort, got lazy, and forgot about it.

Later I grumbled a bit and decided I polish the implementation off and get it right. But I realized a curious thing. The timer will NEVER FIRE. That's right. If I implemented the delayed decay transit system, it would never be relevant.

Two simple facts combine to put a constraint on the time the decay would require. First, know we have a 10% threshold for the top damage-threat to be relevant. Then know that there is a 5% decay per second on damage-threat, and then note the 2 second recalculation of engagement.
In the 2 seconds before engagement is reassigned, there is only marginally more than 10% of decay possible. So it'll never transit, or if it did, it'd only be minutely before the engagement ping would fire anyway. Horray for laziness!

Actually, all that is wrong.

The 10% threshold is for overcoming threat. It could be that at the 2 second mark, entity A has 100 damage threat, and entity B has 109 engagement, and entity A is currently the 'top' entity, since B has not crossed the threshold. In this case the transit would need to fire in about .2 seconds, in order to be correct.

But you know what? It doesn't matter. The end effect is that in extremely rare cases, damage-threat will not be overcome by engagement immediately, and instead will need to wait a very rare worst case of 2 seconds. If that becomes a gameplay disaster, then you can call me wrong and make me write the bloody algorithm.

Guess I'm Lazy.