Archive for category Paradigm 2D World Builder

Developing a simple plugin architecture in C#

Once my editor officially began being used for two different, completely unrelated games, I had a few decisions to make.  The main problem was the fact that an RPG needs very specific helper functions (NPC editing, scripting, etc) whereas a platformer would need things like event scripting.  Rather than make additional tools to handle these functions, having them combined would be ideal.  However, I didn’t want to combine functions into an editor that would be useless for the other game.

The solution: a very simple plugin architecture.  By very simple, I mean that the actual Map classes would not be changed at all, in fact the XML map that the editor exported would not be changed in the slightest.  The plugin would not so much be given access to the Map in any way, but more so it would be given a place to run.  Essentially (at this point anyway) the plugin would be aesthetic.  It would allow level designers to use additional functionality within the level editor, which would already be running on the system.

But enough about that, the reason for this post is that I wanted to share a bit of code that let this happen.  After doing some research, I came across an old post by Shawn Walcheske called “Implementing a Plug-In Architecture in C#” (located here: http://www.ddj.com/cpp/184403942).  My implementation is, basically, identical, however the source download on that page is down, and he doesn’t really explain the System.Activator class which leaves the reader hanging. Update from a reader. Apparently the source is still available here: ftp://ftp.cuj.com/sourcecode/cuj/2003/cujjan2003.zip. Thanks!

So with that, I thought I’d show how I went about doing things, and basically explain the few loose ends that Shawn leaves out.  I think it goes without saying that if you really want to understand this entire concept, read his article as well.

The first thing we need to do is create a simple interface for our plugin.  This interface needs to be in it’s own assembly, for example I created ParadigmCommon.dll for plugins to reference in order to have access to this interface.  As the plugin system I am developing is very simple, the interface only provides an ActivatePlugin() method, as all we want to do is be able to launch new plugins from the main editor.

    public interface IParadigmPlugin
    {
        /// <summary>
        /// Activates the plugin, showing it's main form
        /// </summary>
        void ActivatePlugin();
    }

Next we need to define some custom attributes.  These attributes will hold some metadata for our class, this way our main application can reference that data.  We are, for this example, going to create a custom DisplayName attribute, and a custom Description attribute.  They are fairly self explanatory.

    /// <summary>
    /// This class defines the custom attribute for plugin display names
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class ParadigmPluginDisplayNameAttribute : System.Attribute
    {
        private string displayName;
 
        public ParadigmPluginDisplayNameAttribute(string displayName)
            : base()
        {
            this.displayName = displayName;
        }
 
        public override string ToString()
        {
            return displayName;
        }
    }
    /// <summary>
    /// This class defines the custom attribute for plugin descriptions
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class ParadigmPluginDescriptionAttribute : System.Attribute
    {
        private string description;
 
        public ParadigmPluginDescriptionAttribute(string description)
            : base()
        {
            this.description = description;
        }
 
        public override string ToString()
        {
            return description;
        }
    }

Here we have an actual plugin.  As you can see, we need to use the ParadigmCommon namespace, as well as reference the DLL from the project.  The plugin itself merely implements the IParadigmPlugin interface and as such implements the ActivatePlugin() method, which only serves to open a new form for the plugin.  Simple enough.  Similar in implementation to the way Program.cs would launch the main form in a Windows application.  As you can see, we are also using our custom attributes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; // referencing System.Windows.Forms is obviously needed for form usage, make sure to reference it in the project as well
using ParadigmCommon; // you must reference the ParadigmCommon namespace to access the needed attributes and interface
 
namespace TestPlugin
{
    /// <summary>
    /// This is an example of a paradigm plugin
    /// </summary>
    [ParadigmPluginDisplayName("Test Plugin")] // you must provice a display name
    [ParadigmPluginDescription("Test Plugin")] // as well as a description
    public class TestPlugin : IParadigmPlugin  // Your main class must implement the IParadigmPlugin interface
    {
        public void ActivatePlugin() // by implementing the interface, you must implement an ActivatePlugin method
        {
            TestPluginMainForm mainForm = new TestPluginMainForm();
            mainForm.Show();
            mainForm.Activate();
        }
    }
}

In our host applciation, we need to define a few things.  First, we need a wrapper class. This class will hold a reference to an object implementing our IParagidmPlugin interface (ie: any plugin we create), as well as the metadata for the plugin (in our case, name and description). In this case we also implement an Activate() method that will call the actual plugin’s ActivatePlugin() method.

    /// <summary>
    /// This class wraps our plugins
    /// </summary>
    public class ParadigmPlugin
    {
        #region Fields
        private IParadigmPlugin plugin;
        private string name;
        private string description;
        #endregion
 
        #region Attributees
        public string Name
        {
            get { return name; }
        }
 
        public string Description
        {
            get { return description; }
        }
        #endregion
 
        /// <summary>
        /// Constructs a plugin wrapper
        /// </summary>
        public ParadigmPlugin(IParadigmPlugin plugin, string name, string description)
        {
            this.plugin = plugin;
            this.name = name;
            this.description = description;
        }
 
        /// <summary>
        /// Activate Plugin
        /// </summary>
        public void Activate()
        {
            plugin.ActivatePlugin();
        }

We also need to define a quick custom exception, which we will use later on. There is really no implementation here in the example, but you can handle the exception however you wish.

    class PluginNotValidException : ApplicationException
    {
        public PluginNotValidException(Type type, string param1)
        {
        }
    }

First, we need to define a list to contain all of the plugins we load at runtime.  Next, we need a LoadPlugins() method.  This method uses reflection to handle plugin loading.  Essentially, it steps through our plugin directory looking for any file that matches the *.dll file name mask.  When it finds a DLL, it attempts to load the assembly.  If it fails, it will throw an exception and alert the user.

If it succeeds in loading the assembly, and looks for our IParadigmInterface.  If it finds it, it then gets our custom attributes.

Next, the System.Activator class comes into play.  This wasn’t mentioned in Shawn’s article as I said before.  Basically, we are going to create an object of a specific type, which in this case our type is going to be pulled from the loaded assembly, this way we create the correct type of object.

Next, we create an instance of our wrapper class.  Upon constructing, we are going to make sure to cast the object returned by System.Activator as IParadigmPlugin.  We will then add it to our list of loaded plugins.  Thats it.

The last part of this function is optional, but pretty cool and may be helpful.  Basically, we want our loaded plugins to show up dynamically on a menu strip.  So, we will iterate through our list of loaded plugins, and for each one we will add a new item to a toolstrip menu dropdown list.  We will set the name and text to the plugin display name, and the tool tip to the plugin description (see, we used the metadata for something afterall).  Then, we will set the new items Click event to be a delegate referencing the plugin’s Activate() method.  Simple right?  When this method executes, our tool strip will be dynamically populated by the plugins, and clicking them will launch them.

private List<ParadigmPlugin> loadedPlugins = new List<ParadigmPlugin>();
        private void LoadPlugins()
        {
            // search plugin directory for dlls
            string[] files = Directory.GetFiles("Plugins", "*.dll");
 
            // check each file in plugin direction
            foreach (string file in files)
            {
                try
                {
                    // load the assembly and get types
                    Assembly assembly = Assembly.LoadFrom(file);
                    System.Type[] types = assembly.GetTypes();
 
                    // look for our interface in the assembly
                    foreach (System.Type type in types)
                    {
                        // if we found our interface, verify attributes
                        if (type.GetInterface("IParadigmPlugin") != null)
                        {
 
                            if (type.GetCustomAttributes(typeof(ParadigmPluginDisplayNameAttribute), false).Length != 1)
                                throw new PluginNotValidException(type, "Plugin display name is not supported!");
 
                            if (type.GetCustomAttributes(typeof(ParadigmPluginDescriptionAttribute), false).Length != 1)
                                throw new PluginNotValidException(type, "Plugin description is not supported");
 
                            // get custom attributes from plugin
                            string name = type.GetCustomAttributes(typeof(ParadigmPluginDisplayNameAttribute), false)[0].ToString();
                            string description = type.GetCustomAttributes(typeof(ParadigmPluginDescriptionAttribute), false)[0].ToString();
 
                            // create the plugin using reflection
                            Object o = Activator.CreateInstance(type);
 
                            ParadigmPlugin plugin = new ParadigmPlugin(o as IParadigmPlugin, name, description);                                                               
 
                            loadedPlugins.Add(plugin);
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Plugin Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
 
            // iterate through list and add them to our form control
            for (int i = 0; i < loadedPlugins.Count; i++)
            {
                ParadigmPlugin plugin = loadedPlugins[i];
 
                pluginsToolStripMenuItem.DropDownItems.Add(plugin.Name);
                pluginsToolStripMenuItem.DropDownItems[i].Click += delegate { plugin.Activate(); };
                pluginsToolStripMenuItem.DropDownItems[i].Text = plugin.Name;
                pluginsToolStripMenuItem.DropDownItems[i].ToolTipText = plugin.Description;
            }
        }

You could easily expose much more via the interface and make some complicated plugins, but that isn’t needed in this scenario.  However, I hope this helps to illuminate the basics of plugin architecture in C#.

, ,

3 Comments

Upcoming level editor updates

After switching gears and looking at my editor from an RPG standpoint instead of a sidescrolling standpoint, I’ve noticed a few shortcomings in my editor and engine design.

As such, a few changes are planned.

  1. Shadow mapping.  I have a few different ideas on to how create shadows with a decent degree of alpha transparency.  More than likely I will go with a separate B&W image that stores that shadow textures and have the engine draw them as needed with alpha transparency.
  2. Layers, layers, LAYERS.  Three layers, simply, is not enough.  As such, I’m going to transition from the current 3 layer system to an unlimited layer system.
  3. Zooming.  RPG maps are going to be somewhat large.  I think zooming in and out of the editor will be a very helpful addition.
  4. Advanced entity spawning system.  I’m on the fence with this one.  I may or may not implement this in the editor.  Part of me thinks creating an NPC editor would be smarter.  We’ll see how this pans out though.

That is all for now.

, ,

No Comments

Tile Based Level Editor Progress

Well it’s about time isn’t it?  I finally got around to writing this blog post regarding my tile editor.  I recently joined a team to produce an RPG in C# using XNA Studio 3.1, so I figured now would be a good time to put some more work into the tile engine / editor and showcase what is working so far.

As it stands, the editor is pretty robust.  Currently it supports three tile layers, a rear, mid, and foreground layer.  The rear layer is self explanatory.  The mid layer renders over the rear layer to add details, and the foreground layer renders over NPCs, the player, particles, etc (as long as your engine supports it).  The foreground layer is currently tinted yellow so it can be distinguished.

Tiles can be drawn in as single tiles and regions.  You can also choose to fill an entire layer with a single tile if you so choose.

The editor supports multiple collision types such as impassible, platform, slopes, etc.  These are basically just flags that your engine needs to interpret correctly.

The editor also supports spawn points.  Any entity your engine supports can be dumped into a plain text file and the editor will parse it.  The spawn points can be added dynamically to the map.

It also supports a portal layer which allows for areas of the map to be flagged as a portal.  This allows for your engine to do a check against those regions and load a new map as needed.

We also support terrain effects which are regions of the map that will be processed with some sort of effect.  My demo shows this being used with a simple water shader I wrote.

You can set the background color of the map to any of the predefined .NET colors, as well as a custom color using the color wheel.  You can resize the map dynamically as well as specify the tile size to match your tile set.

The next iteration of this editor will support more layers, likely unlimited using just a list of layers.  In addition I plan to implement a sort of multilayer occlusion so that the foreground layer is more or less dynamic.  Different layers will occlude other layers, so on and so forth.  This is not really needed for a platformer, but will be pretty useful in RPG world building.

Videos:

(My apologies as the audio goes out of sync near the end of part 1 and into part 2, blame Camstudio.)

, ,

No Comments

Level Editor Progress

I’ve been hard at work on the level editor for my game engine and I figured I’d get something up here showing current progress. It is currently near completion actually. It allows for editing of 3 tile layers, background, midground, and foreground. It also allows for world hazards, spawn points, portals, and multiple collision types. The editor renders using the XNA framework within a normal WinForms application. Output is serialized using the XNA intermediate serializer into an XML file that can be directly loaded into the game itself.

Basically, pretty sweet.

Here is a screenshot for the time being.

Level Editor Alpha

Level Editor Alpha

, ,

No Comments