Archive for the tag: programming

The Trouble with Interfaces

Developer's Cave 2 Comments »
Java interfaces are a wonderful thing; don't get me wrong. However, many interface contracts make assumptions about how the implementation will behave. What is more, Java offers no way to programmatically enforce such an interface contract. This article discusses a particular example of interface behavioral assumption and how to (partially) enforce the behavior programmatically. Read the rest of this entry »

To Enum or Not to Enum

Developer's Cave, Island Forge 3 Comments »
Java's enum feature offers a powerful language capability: compile-time type checking of constants. In addition, enum constants make code much easier to read and debug. However, an enum represents hard-coded values, requiring application recompilation/redeployment to alter. This conflicts with the mantra of code design taught to me: "Abstraction, abstraction, abstraction." That is, a piece of software should be as general-purpose as possible. Take, for example, the Potential RPG game engine. I've designed it to abstractly support MMORPGs, allowing game-specific content to be defined in external data files. This often precludes defining enum constants where they would otherwise make good programmatic sense. For example, my game supports a variety of shop types (weaponsmith, alchemist, healer, etc.). Currently, these are loaded from a definition file, rather than being hard-coded in the software. Adding a new shop type can be done without modifying the code... almost (read on). What I've discovered is that new content still requires logic and GUI code to be written against it. Therefore, the game must be recompiled/redeployed anyway, so why not just simplify things and hard-code enum constants? Ideally, I'd love to make the game engine 100% abstracted from content. For example, all content-related code should be isolated into dynamically loaded classes, referenced by the content definitions. While it's just me at the keyboard, simplification seems in order. (Unless someone is looking to invest in such a game engine...) In summary, depending on the requirements of your project, just use enum constants unless the level of effort is worth the design/implementation/maintenance overhead. (Hmmm ... now I'm talking like a software project manager.)

JFreeChart for SLOC History

Developer's Cave, Island Forge No Comments »
While in grad school, I learned to use gnuplot to create line/bar charts. It works well for command-line scripted data processing, so long as you're good at discerning arcane commands. Looking for Java-based charting, I found JFreeChart. I've only spent a couple hours with it, but it looks to be an impressive library. It's not simple, but appears to be well designed. I hope to become more adept at JFreeChart. So far, I've only redeveloped my Potential RPG Source Lines of Code (SLOC) chart (originally processed by gnuplot):

Can anyone offer other Java-based charting library suggestions? Any opinions of JFreeChart? Read the rest of this entry »

Swing Invocation Helper

Developer's Cave, Island Forge No Comments »
This article presents a simple programming technique for ensuring Java Swing tasks are executed on the proper thread, while avoiding unnecessary delayed invocation. Read the rest of this entry »

Developer Question: External Content in Software Repository?

Developer's Cave, Island Forge 4 Comments »
Here's a question for software developers out there (independent game developers and otherwise):

Is it best to keep external content in the software repository?

Read the rest of this entry »

World Rendering: Graphics Engine

Developer's Cave, Island Forge No Comments »
The previous article describes features of my world rendering engine. This article describes graphics engine techniques used to render the world. I highlight two competing approaches with which I've experimented. The goal is to paint a picture of the world. This includes layers of terrain, characters, creatures, and other surface features, as well as special effects graphics. See the previous article for a small sample of the rendered world. Under the hood, I've employed two approaches: (a) Off-screen, background-thread, pre-rendering vs. (b) On-demand, in-line rendering. This represents a classic memory-versus-speed tradeoff. Allocating the world image in memory, to be rendered by a background thread, should improve the speed of screen painting and overall client responsiveness. This is a theoretically reasonable approach, which is actually rather common (often used for double-buffering). However, the devil is in the details. Due to Java's painting architecture, my background rendering thread must be synchronized with Java's painting thread. Ultimately, my background rendering thread becomes a tripwire to Java's painting. (Tripple-buffering might overcome this, but would be memory prohibitive and even more complicated.) The second approach embraces Java's painting architecture, rendering the world on demand. Since all the painting calculations are now performed in Java's painting thread, more careful optimization is needed to avoid stalling the application. Optimization adds complexity, but in this case I consider in-line rendering to be more straight-forward than off-screen rendering. In my usual manner of over-analyzing and over-engineering, I've experimented with a hybrid approach. Terrain is pre-rendered off-screen, while characters, surface features, and effects are drawn on-demand. In this case, the Java painting thread still synchronizes with my background rendering thread, but is only grabbing part of the terrain layer, which rarely changes once drawn, thus avoiding the tripwire effect described above. This approach may provide the best of both worlds. During alpha testing, I've tried all three techniques. The first technique is too cumbersome. The second technique is performance sensitive, but seems promising. The hybrid approach provides the best and worst of both worlds, at the same time solving and creating more subtle issues. From a software standpoint, I'd love to perfect the hybrid engine. Someday I will, but the on-demand drawing system is the simplest to pursue for my immediate needs. From a performance standpoint, I do not have any hard statistics yet, but on-demand rendering seems to perform well on 5-year-old hardware, in Linux, in windowed mode (not full screen exclusive mode), with no accelerated hardware drivers. With further rendering optimizations and improvements promised for Java, my graphics engine should support Potential RPG and future projects. Having never built a graphics engine before, I've found this to be one of the most challenging and interesting components of this project.

Java Graphic Performance

Developer's Cave, Island Forge No Comments »
I'm often amazed how much processing can be performed in a few milliseconds, even in the face of sloppy algorithms. Graphic processing, on the other hand, seems to be another story. Any excess painting can be significantly detrimental. For the record, I'm developing this game in Linux (Debian) with no accelerated graphics drivers, and I am determined for it to run well on my platform of preference. Sun promises a vastly improved graphic pipeline with its upcoming Java update release, but this only helps with DirectX in Windows. It's easy to unjustly blame sluggish graphics on Java or Linux. So far in my burgeoning graphics experience, I've found that performance problems invariably indicate that I've done something horribly wrong. Reading an article on Swing animation last week inspired me to vastly improve my graphic processing. Without getting into the technical details (unless there's an interest), the conclusion is that Java on Linux can certainly drive graphic content, as long as you're meticulous in your implementation. While Java's general software performance is exceptional, only so much graphic excess can be swept under the rug.

Swing Hangs on Thread, Old Timers to Blame, Factory Fixes

Island Forge 2 Comments »
Elderly swing-set factory employees using thread instead of chains forces product recall? No. Why would you think that? This article describes how the javax.swing.Timer utility can cause your Swing application to hang at shutdown, and how to fix it. The Timer utility is useful for repeating tasks on the Swing/AWT thread. They're handy enough to create in many places throughout GUI code. However, each one that remains active keeps the AWT thread alive, which prevents clean application shutdown (without resorting to System.exit()). Lacing the code with Timer instances makes it difficult to track them all down and stop them when the application is supposed to exit. To correct the situation for the MMORPG client, I created a simple factory class with a create(..) method for producing Timer instances. The factory maintains a reference to every Timer created. At application shutdown, the factory's stop() method is called, which tells each Timer to stop(). After replacing all Timer constructor calls with the factory's create(..) method, the MMORPG client exits cleanly. There are a few caveats. For one, you must be certain it is safe to stop Timers in this way (a Timer may be carrying out some critical pre-shutdown operation). In general, I only use Timers for GUI-related activities, and not to drive application logic. Another weakness is that the factory cannot guarantee the Timers will not be restarted, or that more timers will not be created, after stopping the factory. This could be guarded with a more sophisticated design, such as a TimerProxy class to prevent post-shutdown starting, refusing to create new timers after shutdown, or an isStopped() method for GUI code to query. For the MMORPG client, this simple factory pattern is sufficient to untie Timers from the AWT thread, allowing clean shutdown without resorting to System.exit().

ProxyIcon

Developer's Cave, Island Forge No Comments »
For those who enjoy design patterns, I've written a ProxyIcon for the MMORPG client. The reason is to decrease memory allocation in the client, which is due in large part to graphic images, under the theory that most are not needed most of the time. This article describes the ProxyIcon (implementation details are left as an exercise for the reader). First, there is already a central factory of Icons. So, integrating a new proxy pattern only involved changing the factory. ProxyIcon implements the javax.swing.Icon interface, so users are none the wiser. ProxyIcon knows the source of the image to load. When any Icon methods are accessed, it makes sure the internal image is loaded. If not accessed for some timeout, the internal icon can be unloaded. The simplest implementation would have set the internal Icon reference to null, allowing the garbage collector to clean it up. Why the present perfect tense? Because there's an even better approach: ProxyIcon holds two references to the internal Icon: A hard reference and a soft reference. After the timeout, the hard reference is set null, but the soft reference is retained. Since the embedded icon is only referenced (never exposed) from the ProxyIcon object, this leaves only the soft reference. Java cleans up soft references (only) when memory is needed. If, however, the ProxyIcon is accessed before being cleaned up, the hard reference is reinstated. This provides the best of both worlds: Application logic can set policy on when to release resources but is backed up by the Java Virtual Machine's garbage collection logic to avoid unhelpful cleanup. The primary benefit, of course, is that unused icon resources can be deallocated. The software design benefit is that image users do not need to concern themselves with whether the icon is currently loaded or not. Notice that all ProxyIcon references stay in memory forever (in the factory). They could also be deallocated by using soft or weak references in the factory, but the objects themselves are (theoretically) miniscule compared to image memory consumption. Another minor benefit is lazy image loading. Instead of loading upon construction, the internal icon is loaded lazily upon first access. There are a number of icons that are requested in the code, but not always used. This feature has the benefit that the code can greedily ask for icons from the factory (e.g., as static variables) without impacting memory if not needed. One major gotcha is that Java itself may be holding cached references to the image data, which prevents garbage collection. I have not investigated this fully, but do not use Toolkit.getImage(), as it's API warns of just this problem. Also read the code for javax.swing.ImageIcon, which makes (undocumented) use of Toolkit.getImage(). Instead, use Toolkit.createImage() or ImageIO.read() with ImageIO.setUseCache(false). Further investigation is needed to determine exactly who has access to underlying image data depending on how it is loaded. For Alpha testers, look at $HOME/.potentialrpg/stat/IconFactory.stat, which shows:
timestamp, total, loaded, hard_referenced, average_ms_timeout, ms_stat_time