Terraria Mod: CheatHotkeys (tModLoader v0.8.3.1)

I recently downloaded tModLoader for Terraria because there were a few things I wanted, such as an easy way to cheat in-game (I admit it, I’m a cheater). I found some pretty good solutions, but none of them had in-game keybindings for cheat functions like refilling health and mana. So I wrote my own!

CheatHotkeys is a tModLoader mod that adds some hotkeys for various cheat functions, such as refilling life and mana, removing debuffs, god mode, and unlimited ammo.

You can download the mod through the in-game Mod Browser or via the GitHub page. Enjoy!

Import URL as Background

Blender Plugin: Import URL as Background

I’m not really a Python developer, but I recently wrote a Blender plugin that allows you to import an image URL as a background in your scene. Note that the URL has to have an image extension: picture.jpg will work, but picture.jpg?attach=981 will not work. You can download that plugin on the GitHub page.

Recursively Combine a File Path in Java

I was looking for a built-in way to combine file paths in Java like the Path.Combine() function in C#; none exist, so I decided to write my own. It’s not hard, but I thought I’d share it since it seems to be a popular question online.

public static String combinePath(String ... paths) {
    String fullPath = "";
    
    for(String path : paths) {
        fullPath = combinePathRecursive(fullPath, path);
    }
    
    return fullPath;
}
    
private static String combinePathRecursive(String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

That’s it! The function will recursively combine the strings until you get the full path.

Example:

System.out.println(combinePath("foo", "bar", "foobar.txt"));
// Will print "foo/bar/foobar.txt".

[Game Maker] Bettering 4-Direction Player Movement

Game Maker 6 by YoYo Games was the first game creation engine I ever used, and it’s only gotten more powerful in the years since it became GameMaker: Studio. One of the hardest things to figure out is how to make a smooth 4-way or 8-way movement system.

Stephen Loney of 8-Bit Warrior addresses this issue with a surprisingly simple solution: booleans store when a movement key is pressed and released.

You can read his article Bettering 4-Direction Player Movement to learn how to create the movement system.

Implementing the Singleton Pattern in C#

Singletons are a very debated topic in the programming world, most people saying that they are just glorified global variable holders. However, in some circumstances (such as game development) having a single instance of an important class can be exceptionally useful.

Table of contents (for linking purposes…)

Introduction

The singleton pattern is one of the best-known patterns in software engineering.
Essentially, a singleton is a class which only allows a single instance of itself
to be created, and usually gives simple access to that instance. Most commonly,
singletons don’t allow any parameters to be specified when creating the instance –
as otherwise a second request for an instance but with a different parameter could
be problematic! (If the same instance should be accessed for all requests with the
same parameter, the factory pattern is more appropriate.) This article deals only with
the situation where no parameters are required. Typically a requirement of singletons
is that they are created lazily – i.e. that the instance isn’t created until it is
first needed.

There are various different ways of implementing the singleton pattern in C#. I shall
present them here in reverse order of elegance, starting with the most commonly seen,
which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple
and highly performant version.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless.
    This prevents other classes from instantiating it (which would be a violation of the pattern).
    Note that it also prevents subclassing – if a singleton can be subclassed once, it can be
    subclassed twice, and if each of those subclasses can create an instance, the pattern is
    violated. The factory pattern can be used if you need a single instance of a base type,
    but the exact type isn’t known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point,
    but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating
    one if necessary.

Note that all of these implementations also use a public static property Instance
as the means of accessing the instance. In all cases, the property could easily be converted
to a method, with no impact on thread-safety or performance.

First version – not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

As hinted at before, the above is not thread-safe. Two different threads could both
have evaluated the test if (instance==null) and found it to be true,
then both create instances, which violates the singleton pattern. Note that in fact
the instance may already have been created before the expression is evaluated, but
the memory model doesn’t guarantee that the new value of instance will be seen by
other threads unless suitable memory barriers have been passed.

Second version – simple thread-safety

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared
object, and then checks whether or not the instance has been created before creating the instance.
This takes care of the memory barrier issue (as locking makes sure that
all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur
logically before the lock release) and ensures that only one thread will create an instance
(as only one thread can be in that part of the code at a time – by the time the second thread
enters it,the first thread will have created the instance, so the expression will evaluate to false).
Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this
implementation do, I lock on the value of a static variable which is private to the class.
Locking on objects which other classes can access and lock on (such as the type) risks
performance issues and even deadlocks. This is a general style preference of mine – wherever
possible, only lock on objects specifically created for the purpose of locking, or which
document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue).
Usually such objects should be private to the class they are used in. This helps to make
writing thread-safe applications significantly easier.

Third version – attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time.
Unfortunately, there are four downsides to the pattern:

  • It doesn’t work in Java. This may seem an odd thing to comment on, but it’s worth knowing
    if you ever need the singleton pattern in Java, and C# programmers may well also be Java
    programmers. The Java memory model doesn’t ensure that the constructor completes before
    the reference to the new object is assigned to instance. The Java memory model underwent
    a reworking for version 1.5, but double-check locking is still broken after this without a volatile
    variable (as in C#).
  • Without any memory barriers, it’s broken in the ECMA CLI specification too. It’s possible that under the .NET 2.0
    memory model (which is stronger than the ECMA spec) it’s safe, but I’d rather not rely on those stronger
    semantics, especially if there’s any doubt as to the safety.
    Making the instance variable volatile can make it work, as would explicit memory barrier calls,
    although in the latter case even experts can’t agree exactly which barriers are required. I tend to try to avoid situations where
    experts don’t agree what’s right and what’s wrong!
  • It’s easy to get wrong. The pattern needs to be pretty much exactly as above – any
    significant changes are likely to impact either performance or correctness.
  • It still doesn’t perform as well as the later implementations.

Fourth version – not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

As you can see, this is really is extremely simple – but why is it thread-safe and how lazy is it?
Well, static constructors in C# are specified to execute only when an instance of the class is
created or a static member is referenced, and to execute only once per AppDomain. Given that
this check for the type being newly constructed needs to be executed whatever else happens, it
will be faster than adding extra checking as in the previous examples. There are a couple of
wrinkles, however:

  • It’s not as lazy as the other implementations. In particular, if you have static members
    other than Instance, the first reference to those members will involve
    creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the
    first again. Look in the .NET specifications (currently section 9.5.3 of partition II)
    for more details about the exact nature of type initializers – they’re unlikely to bite you,
    but it’s worth being aware of the consequences of static constructors which refer to each
    other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn’t
    marked with a special flag called beforefieldinit. Unfortunately,
    the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types
    which don’t have a static constructor (i.e. a block which looks
    like a constructor but is marked static) as beforefieldinit. I now
    have an article with more details about
    this issue
    . Also note that it affects performance, as discussed near the bottom
    of the page.

One shortcut you can take with this implementation (and only this one) is to just make
instance a public static readonly variable, and get rid of the property entirely.
This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a
property in case further action is needed in future, and JIT inlining is likely to make
the performance identical. (Note that the static constructor itself is still required
if you require laziness.)

Fifth version – fully lazy instantiation

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }
        
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested
class, which only occurs in Instance. This means the implementation is fully
lazy, but has all the performance benefits of the previous ones. Note that although nested
classes have access to the enclosing class’s private members, the reverse is not true, hence
the need for instance to be internal here. That doesn’t raise any other problems,
though, as the class itself is private. The code is a bit more complicated in order to make
the instantiation lazy, however.

Sixth version – using .NET 4’s Lazy<T> type

If you’re using .NET 4 (or higher), you can use the System.Lazy<T>
type to make the laziness really simple. All you need to do is pass a delegate to the constructor
which calls the Singleton constructor – which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

It’s simple and performs well. It also allows you to check whether or not the instance
has been created yet with the IsValueCreated
property, if you need that.

Performance vs laziness

In many cases, you won’t actually require full laziness – unless your class initialization
does something particularly time-consuming, or has some side-effect elsewhere, it’s probably
fine to leave out the explicit static constructor shown above. This can increase performance
as it allows the JIT compiler to make a single check (for instance at the start of a method)
to ensure that the type has been initialized, and then assume it from then on. If your
singleton instance is referenced within a relatively tight loop, this can make a (relatively)
significant performance difference. You should decide whether or not fully lazy instantiation
is required, and document this decision appropriately within the class.

A lot of the reason for this page’s existence is people trying to be clever, and thus coming
up with the double-checked locking algorithm. There is an attitude of locking being expensive
which is common and misguided. I’ve written a very quick benchmark
which just acquires singleton instances in a loop a billion ways, trying different variants.
It’s not terribly scientific, because in real life you may want to know how fast it is if each
iteration actually involved a call into a method fetching the singleton, etc. However, it does
show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking
one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to
acquire the singleton a billion times in under 40 seconds. (Note: this article was originally written
quite a while ago now – I’d expect better performance now.) That means that if you’re “only”
acquiring the singleton four hundred thousand times per second, the cost of the acquisition
is going to be 1% of the performance – so improving it isn’t going to do a lot. Now, if you are
acquiring the singleton that often – isn’t it likely you’re using it within a loop? If you care
that much about improving the performance a little bit, why not declare a local variable outside the loop,
acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily
adequate.

I would be very interested to see a real world application where the difference between using
simple locking and using one of the faster solutions actually made a significant performance difference.

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but
might not be fatal to the whole application. Potentially, your application may be able to
fix the problem and want to try again. Using type initializers to construct the singleton
becomes problematic at this stage. Different runtimes handle this case differently,
but I don’t know of any which do the desired thing (running the type initializer again), and
even if one did, your code would be broken on other runtimes. To avoid these problems, I’d
suggest using the second pattern listed on the page – just use a simple lock, and go through
the check each time, building the instance in the method/property if it hasn’t already been
successfully built.

Thanks to Andriy Tereshchenko for raising this issue.

Conclusion (modified slightly on January 7th 2006; updated Feb 12th 2011)

There are various different ways of implementing the singleton pattern in C#.
A reader has written to me detailing a way he has encapsulated the synchronization aspect,
which while I acknowledge may be useful in a few very particular situations
(specifically where you want very high performance, and the ability to determine whether or not
the singleton has been created, and full laziness regardless of other static
members being called). I don’t personally see that situation coming up often enough
to merit going further with on this page, but please mail
me
if you’re in that situation.

My personal preference is for solution 4: the only time I would normally go away from it
is if I needed to be able to call other static methods without triggering initialization, or
if I needed to know whether or not the singleton has already been instantiated. I don’t remember
the last time I was in that situation, assuming I even have. In that case, I’d probably go
for solution 2, which is still nice and easy to get right.

Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides
seem to only be rarely useful. Solution 6 is a simpler way to achieve laziness, if you’re using .NET 4.
It also has the advantage that it’s obviously lazy. I currently tend to still use solution 4,
simply through habit – but if I were working with inexperienced developers I’d quite possibly
go for solution 6 to start with as an easy and universally applicable pattern.

(I wouldn’t use solution 1 because it’s broken, and I wouldn’t use solution 3 because it has no
benefits over 5.)

source: Jon Skeet, C# In Depth. February 12, 2011.

KeepTime

Hello, everyone!

I've been working hard for the past few days on the successor to Simple Alarm: KeepTime. KeepTime has all the same features as Simple Alarm (12- or 24-hour format; month/day/year or day/month/year date format; a custom message; etc.) but also includes a timer and stopwatch.

For now, there's no released version, as I intend to include an update feature soon so users don't have to keep an eye on the repository for new features. That's not to say there will be many updates, but I like to include it just in case.

The lack of a release version unfortunately means you have to build the project yourself in Visual Studio. You can clone the repository on GitHub.

Visual Studio 2013 Dark Theme for MonoDevelop

Being a long-time Visual Studio user, I’m extremely comfortable with VS themes, especially the dark theme that’s been present in both VS2012 and VS2013. I was dissatisfied with the theme choices in the Unity-bundled version of MonoDevelop and decided to make my own version of the VS2013 dark theme. It won’t look the same in every way, as Visual Studio had a lot more color choices than MonoDevelop, but it should be familiar enough that Visual Studio users will feel comfortable.

The theme is available at the GitHub repository. To install it, just follow the instructions on the repo’s main page.

The Truth: How Much You Should Pay for a Website

When people contact me for help with a blog or website, they have one main question.

How much is this going to cost?

It’s a logical thing to ask, really. Those of us who aren’t rich or famous have a finite amount of money, and we always want to feel like that money is being used in the smartest way possible. We are especially cautious when it comes to paying for something intangible like a website – you can’t hold it in your hand, so how much can it really be worth?

The cost of web design work varies wildly. You could ask for quotes from 10 different designers and receive 10 completely different dollar amounts, ranging from a few hundred dollars to several thousand. How do you decide what amount you’re willing to pay?

Factors That Affect the Price of Website Design

1. The components and features you need.

Never assume that your needs are “simple” or should be cheaper than a designer’s standard rate. Some things look easy but are very complicated, while others seem like a big deal but are very easy to implement. Your site may only consist of a single page, yet that doesn’t mean it’s automatically cheaper than one with 5 or even 100 pages.

The thing is, designers don’t always price by the amount of time something takes. Your doctor can stitch a cut in 10 minutes, but that doesn’t mean it doesn’t require knowledge, skill, and precision. Likewise, we have spent considerable time learning to do what we do. If anyone could do it, we wouldn’t have jobs. Adding things like forums, ecommerce, opt-ins, memberships, and other custom functionality is simply going to cost more money.

2. Your designer’s skill level.

Yes, you can get a website for $150. No, it won’t be the same quality as a website that costs $1500. It’s like the difference between a bicycle and a Lexus. Both will get you where you need to go, but one is decidedly better than the other. Designers who charge more are providing you with expertise you won’t find at a bargain rate – and in most cases, the benefits will definitely outweigh the added costs. If you automatically choose the cheapest option, you risk hiring a designer who sucks. Don’t say I didn’t warn you!

3. How demanding you are as a client.

Oops, I mentioned one of those things no one is supposed to talk about! But in the interest of being honest, I’ll just tell you: If you email or call me 50 times a day, expect a billion tiny revisions, cut into my time with my family, and/or request things outside the scope of our working relationship, it’s going to cost you. Over time, designers learn how to sniff out “difficult” clients pretty easily, but if one sneaks through the gates, we are going to make absolutely sure we are compensated for the extra work. Please remember that designers are people and we (sometimes) have lives away from our computers.

So How Much Should I Pay?

Here are a few questions to ask yourself before deciding on a budget for website design.

For Blogs:

What is the point of my blog? If you blog to share photos and memories with your family and don’t make any money from it, I wouldn’t spend more than a few hundred dollars for a design at the most. Actually I’d probably just grab a free theme and leave it at that. If, however, you make thousands of dollars a year from your blog and need it to do specific things for your visitors, it’s time to increase the budget.

What will I gain from a professional design? Whether you want to attract better advertisers or get featured on big name websites, a professionally designed blog will always outperform a generic one. If you knew that spending $2000 now would earn you 5-6 times that in the next year alone, wouldn’t it make sense to spend the money?

Should I outsource this? Many, many bloggers ask me for a quote, then tell me they’re going to design their own sites to save money. When that happens I usually see one of four results:

  • They waste hours and hours trying to figure out what to do, then the end result still looks awful.
  • They waste hours and hours trying to figure out what to do, then get frustrated and hire someone anyway.
  • They immediately go hire a cheaper designer, then end up hiring me to fix what the designer broke.
  • They pay for another design within a year of the DIY job because it wasn’t what they wanted.

In those situations, all I see is wasted time, money, and/or effort. If you’re a blogger, focus on blogging, especially if that’s how you earn your living. There’s no shame in outsourcing the things that aren’t a good use of your time.

WHAT YOU SHOULD SPEND: Anywhere from a few hundred to a few thousand dollars, depending on the value you would get from a better design. In general, I wouldn’t spend more than $5000 on a blog design unless you have a huge audience and very specialized needs.

For Business Websites:

How important is it to have a website for my business? It’s the 21st century, and over 60% of internet users research products and services online before they make a purchase. If your company doesn’t have a website, regardless of what you do or how many employees you have, you are totally missing out. That said, having an ugly, outdated website isn’t going to help you much in the reputation department. It’s easy to tell yourself that any web presence is better than none, but you can certainly lose potential clients or customers if they perceive your brand as “cheap” or out of touch.

What does my website actually do for my business? Do people use your website to learn about what you offer? Make appointments? Purchase products? Find your phone number? Two important points about this: (1) If your website doesn’t lead to more business, that’s a problem. And it’s not because the web doesn’t work – it’s because your site doesn’t. (2) If your website does lead to more business, it’s time to ask yourself what could help improve conversion rates or make things easier for clients and customers.

What does my business really need? I’ve talked to business owners who are obsessed with things that simply don’t matter. They absolutely must have a menu that pops out a certain way, or they want to push content lower on the page just to make the logo bigger. And while they’re worrying about all those nitpicky details, they’re missing the fact that half their visitors never click beyond the homepage. If you aren’t sure what your business site needs, it’s time to consult with someone who does. Immediately.

WHAT YOU SHOULD SPEND: Website designs for businesses are more difficult to price because there are so many factors involved. I would say you should always expect at least several thousand dollars, if not much more than that. Don’t like that answer? Try thinking of your website as an employee (click that link – it’s worth it) and I think you’ll see why you’re getting a bargain no matter what you spend.

What do you think? How much should a website design cost? What factors do you use to come up with that amount?

source: Andrea Whitmer, nuts and bolts media. December 5, 2013.

New Website!

Hello, folks, and welcome to the website! It’s brand-spanking new and ready for use! There’s all the same content, but in fancy WordPress-wrapped packages.

Got any suggestions? Email me at the Contact page right up there.

Enjoy the site!

ListBoxTabs

Hello, everyone!

I just released a C# UserControl called “ListBoxTabs”. It acts as an alternative to the TabControl and allows you to customize a ListBox for use in menus.

You can check that out here!