Tag Archives: Code

Dev Log 1/11/2013

This evening I worked on basic boiler plate stuff. I put some stuff up on github including Futile QuickStart I even made a pull request for Futile.
I pretty much spent the rest of evening fighting my font code. Fonts took way too long because I though I was running the latest version of Futile, but it turned out I wasn’t. I got confused about my github pull and which package I imported. Exactly, one of those things that bugs me about the way github’s and Unity’s idiosyncrasies interact. Anyway, once I figuring that out, Futile gave me a useful error that nicely explained what the problem was, oh hum.

Unity3D #pragma strict Gotch

I was working with some code in a book today and could not figure out why a variable was giving me problems.

Unknown idenifier: ‘mesh’. (BCE0005)

I don’t usually program using JavaScript much less with MonoDevlop, so it took me a while.  Turns out, it’s a little thing:

#pragma strict

I was using it, and the book wasn’t.  They didn’t declare the variable in the example unlike ALL the other ones! That’s why it is unknown, it IS unknown.  The sample code that came with the book compiled because it doesn’t have the #pragma strict.

XNA SpriteFonts

While working on Iron Roads today, I tried to use the custom font Radius (a free font from Urban Fonts.)   I like how the letters look like curving tracks you might see on a draftsman’s drawing or surveying map.  It has potential for the Iron Roads logo.  Anyway, I ran into a tricky problem that stumped me for a long while.

Iron Roads with Radius Font

I followed the normal procedure as Microsoft describes in Drawing Text with a Sprite:

  1. Right-click your Content project in Solution Explorer, click Add, and then click New Item.
  2. In the Add New Item dialog box, click Sprite Font. You may find it convenient at this point to change the name of the new file from “SpriteFont1” to the friendly name of the font you intend to load (keeping the .spritefont file extension).  The friendly name identifies the font once it is installed on your computer, for example, “Courier New” or “Times New Roman.” When you reference the font in your code, you must use the friendly name you have assigned it. XNA Game Studio creates a new .spritefont file for your font and opens it.

At this point I had what I needed, but alas, it wouldn’t compile, complaining:

The font family “Radius” could not be found. Please ensure the requested font is installed, and is a TrueType or OpenType font.

Took me a long while to figure it out, but it’s actually quite simple. Install new fonts before starting up Visual Studio! So, all I had to do was shut VS2010 down and start her up again, an Voila! New beautiful font displaying in my game!!!

Iron Roads Title Screen Draft Peek

Please note, this is a concept piece, not art assets are my original and I don’t claim copyright to them.

Tom Miller’s render loop, a revision

Tom Miller, Managed DirectX’s father figure, has made several posts on the game loop or render loop for the managed environment. His lastest post on the subject was back in May 2005. I’m writing the render loop for Alien Sovereign using GDI+, so I needed to tweak his code a little to make it work for a non-DirectX renderer. Here is my version source:

#region Source
/* This code is an adaptation by Philip Ludington (of Mr.
* Phil Games) from the DirectX SDK file DXMUTMisc.cs, and
* Tom Miller’s blog post “My last post on render loops
* (hopefully)..” * http://blogs.msdn.com/tmiller/archive/2005/05/05/415008.aspx*/#endregionusing System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Company.Program
{
#region Enum, deligates, struct etc.
public enum WindowMessage : uint { // Misc messages Destroy = 0x0002, Close = 0x0010, Quit = 0x0012, Paint = 0x000F, SetCursor = 0x0020, ActivateApplication = 0x001C, EnterMenuLoop = 0x0211, ExitMenuLoop = 0x0212, NonClientHitTest = 0x0084, PowerBroadcast = 0x0218, SystemCommand = 0x0112, GetMinMax = 0x0024, // Keyboard messages KeyDown = 0x0100, KeyUp = 0x0101, Character = 0x0102, SystemKeyDown = 0x0104, SystemKeyUp = 0x0105, SystemCharacter = 0x0106, // Mouse messages MouseMove = 0x0200, LeftButtonDown = 0x0201, LeftButtonUp = 0x0202, LeftButtonDoubleClick = 0x0203, RightButtonDown = 0x0204, RightButtonUp = 0x0205, RightButtonDoubleClick = 0x0206, MiddleButtonDown = 0x0207, MiddleButtonUp = 0x0208, MiddleButtonDoubleClick = 0x0209, MouseWheel = 0x020a, XButtonDown = 0x020B, XButtonUp = 0x020c, XButtonDoubleClick = 0x020d, MouseFirst = LeftButtonDown, // Skip mouse move,
// it happens a lot and there is another
// message for that MouseLast = XButtonDoubleClick, // Sizing EnterSizeMove = 0x0231, ExitSizeMove = 0x0232, Size = 0x0005, } [StructLayout( LayoutKind.Sequential )] public struct Message
{
public IntPtr hWnd;
public WindowMessage msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public System.Drawing.Point p;
}
#endregion /// /// Program /// static class Program
{
#region Member Variables
private static Form1 form1;
#endregion #region Properties
#endregion #region Constructors (including static)
#endregion #region Public members
/// /// The main entry point for the application. /// [STAThread] static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(
false );

form1 = new Form1();

// Hook the application’s idle event Application.Idle += new EventHandler(
OnApplicationIdle );

Application.Run( form1 );
}

// We won’t use this maliciously
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport( “User32.dll”, CharSet
= CharSet.Auto )]
public static extern bool PeekMessage(
out Message msg,
IntPtr hWnd, uint messageFilterMin,
uint messageFilterMax,
uint flags );
#endregion #region Private (helper) methods
static private void OnApplicationIdle( object sender,
EventArgs e )
{
while( AppStillIdle )
{
// Render a frame during idle time
// (no messages are waiting) Update(); Render(); } } private static void Render()
{
throw new Exception(
“The method or operation is not implemented.” );
}
private static void Update()
{
throw new Exception(
“The method or operation is not implemented.” );
}
static private bool AppStillIdle
{
get
{
Message msg;
return !PeekMessage( out msg,
IntPtr.Zero, 0, 0, 0 );
}
}
#endregion }}

Visual Studio 2005 Keyboard Cheat Sheet

Lately I have been having pain in my arm and wrist from using the mouse so much.  So I went looking for a keyboard cheat sheet for Visual Studio 2005.  I am hoping this will allow me to use the mouse less and give my wrist a rest.  Sadly, the best thing I could find was this video at Channel 9 (I can’t get a lot of these to work with C#).  So using tips from the video and my own sleuth like skills I created my own cheat sheet which I share here for you future Google travelers.

Visual Studio 2005 Key Board Cheat Sheet

Build = Shift+F6
Jump to Find Window = Ctrl + /
Toggle Region = Ctrl+M, M
Next Error = Ctrl+Shif+F12
Comment Line = Ctrl+C,C
UnComment Line = Ctrl+C,C
Open a file = Ctrl+O
Error W. = Ctrl+W, E
Class W. = Ctrl+W, C
Code = F7

DOH!, Pause = Thread.Sleep(42)

So I’ve been working with .Net for years and today I put something together that made me feel foolish for not already realizing. Especially since I’ve used Threads before and even timed them out. I just never had the concept of needing to pause my code bump up next to the fact that my “normal” code is in a thread too.  I’ve gotten so used to only dealing with threading stuff in special situations I guess I forget that my everyday code is threading too. So if you want to pause your code for a certain number of milliseconds do this

     System.Threading.Thread.Sleep( milliseconds );

Not:

    DateTime stop = DateTime.Now.AddMilliseconds( milliseconds );
    while( DateTime.Now < stop );

Or some other machination with DateTimes and loops.

Oh well, it not really my fault it is simply a side affect of global warming.

Strategy Pattern

Taking Alastair Patrick’s example of applying patterns to game making I present the strategy pattern. The strategy pattern encapsulates behavior allowing flexibility and object composition. This means a group of classes (as ships) can have some behavior in common, but also room for different flavors without having a lot of overrides and duplicate code. Here’s an example in code. Note, I’ve even written it so the behavior can be changed at runtime!

public interface AttackBehavior

{

void Attack();

}

public class AttackWithNoWeapon : AttackBehavior

{

public AttackWithNoWeapon()

{

//

// TODO: Add constructor logic here

//

}

public void Attack()

{

Console.Out.WriteLine( “No weapon to attack with.” );

}

}

public class AttackWithRedLaser : AttackBehavior

{

public AttackWithRedLaser()

{

//

// TODO: Add constructor logic here

//

}

public void Attack()

{

Console.Out.WriteLine( “Firing red lasers.” );

}

}

public class AttackWithReinforcedIceProjectile : AttackBehavior

{

public AttackWithReinforcedIceProjectile()

{

//

// TODO: Add constructor logic here

//

}

public void Attack()

{

Console.Out.WriteLine( “Firing Reinforced Ice Projectiles ” );

}

}

public interface FlyBehavior

{

void Fly();

}

public class FlyWithIonEngines : FlyBehavior

{

public FlyWithIonEngines()

{

//

// TODO: Add constructor logic here

//

}

public void Fly()

{

Console.Out.WriteLine( “Moved 4 parsecs.” );

}

}

public class FlyWithNoEngines : FlyBehavior

{

public FlyWithNoEngines()

{

//

// TODO: Add constructor logic here

//

}

public void Fly()

{

Console.Out.WriteLine( “Movement determined by gravity and inertia.” );

}

}

public class FlyWithSolarSails : FlyBehavior

{

public FlyWithSolarSails()

{

//

// TODO: Add constructor logic here

//

}

public void Fly()

{

Console.Out.WriteLine( “Low Solar Wind, move .5 parsecs.” );

}

}

public abstract class Ship

{

protected FlyBehavior flyBehavior = null;

protected AttackBehavior attackBehavior = null;

public Ship()

{

}

public abstract void Display();

public void PerformFly()

{

flyBehavior.Fly();

}

public void PerformAttack()

{

attackBehavior.Attack();

}

public void Repair()

{

Console.Out.WriteLine( “Repair teams dispatched, 10% improvement.” );

}

public void SetFlyBehavior( FlyBehavior fb )

{

flyBehavior = fb;

}

public void SetAttackBehavior( AttackBehavior ab )

{

attackBehavior = ab;

}

}

public class TerranMarkI : Ship

{

public TerranMarkI()

{

flyBehavior = new FlyWithIonEngines();

attackBehavior = new AttackWithRedLaser();

}

public override void Display()

{

Console.Out.WriteLine( “This is a Terran Mark I ship.” );

}

}

public class NeiwckronMkI : Ship

{

public NeiwckronMkI()

{

SetAttackBehavior( new AttackWithNoWeapon() );

SetFlyBehavior( new FlyWithIonEngines() );

}

public override void Display()

{

Console.Out.WriteLine( “A Neiwckron Mark I ship.” );

}

}

public class TheMain

{

///

/// The main entry point for the application.

///

[STAThread]

static void Main()

{

Ship s1 = new TerranMarkI();

s1.PerformAttack();

s1.PerformFly();

Ship s2 = new NeiwckronMkI();

s2.PerformFly();

s2.SetFlyBehavior( new FlyWithSolarSails() );

s2.PerformFly();

}

}

When I am not writing about making games, procrastinating or watching movies I’m working on a science fiction strategy game (sometimes called 4X or empire builder.) Email me questions, ideas and jokes at mrphil (at) mrphilgames . com

Object Cloning Using Reflection

Today on Alastair Patrick’s blog he shared a way to use reflection to clone objects which I found really interesting. I took the liberty of expanding the example a little so I could better understand the effects deep and shallow cloning had. I also replaced his main() with a NUnit test.

using System;

using System.Reflection;

using NUnit.Framework;

public class DeepCopyAttribute : Attribute

{

}

public class PrototypeCloner

{

public object Clone( object prototype )

{

object clone = CreateNewInstance( prototype.GetType() );

CopyPropertyValuesFromPrototype( clone, prototype );

return clone;

}

private object CreateNewInstance(Type type)

{

ConstructorInfo defaultConstructor = type.GetConstructor( new Type[0] );

return defaultConstructor.Invoke(new object[0]);

}

private bool IsPropertyDeepCopied( PropertyInfo property )

{

if( property.GetCustomAttributes( typeof(DeepCopyAttribute), true).Length

!= 0 )

{

return true;

}

else

{

return false;

}

}

private void CopyPropertyValuesFromPrototype(object clone, object prototype)

{

foreach (PropertyInfo property in prototype.GetType().GetProperties())

{

if (IsPropertyDeepCopied(property))

{

object prototypeProperty = property.GetValue(prototype, null);

object cloneProperty = Clone(prototypeProperty);

property.SetValue(clone, cloneProperty, null);

}

else

{

property.SetValue(clone, property.GetValue(prototype, null), null);

}

}

}

}

public abstract class Weapon

{

}

public class LaserDisruptor: Weapon

{

public float RateOfFire

{

get

{

return rateOfFire;

}

set

{

rateOfFire = value;

}

}

private float rateOfFire = 1000;

}

public abstract class Entity {}

public class SpaceMonkey: Entity

{

public float Speed

{

get

{

return speed;

}

set

{

speed = value;

}

}

private float speed = 5;

private Weapon deepCopyWeapon = new LaserDisruptor();

[DeepCopyAttribute()]

public Weapon DeepCopyWeapon

{

get

{

return deepCopyWeapon;

}

set

{

deepCopyWeapon = value;

}

}

private Weapon shallowCopyWeapon = new LaserDisruptor();

public Weapon ShallowCopyWeapon

{

get

{

return shallowCopyWeapon;

}

set

{

shallowCopyWeapon = value;

}

}

}

[TestFixture]

public class PrototypeClonerTests

{

[Test]

public void Clone()

{

SpaceMonkey prototypeObject = new SpaceMonkey();

PrototypeCloner cloner = new PrototypeCloner();

Entity clonedObject = null;

clonedObject = (Entity)cloner.Clone(prototypeObject);

SpaceMonkey clonedMonkey = (SpaceMonkey)clonedObject;

// Testing for Equality

Assert.AreEqual( prototypeObject.Speed, clonedMonkey.Speed, “Fail1” );

// — This is false because it is a Deep Copy property and this class

// doesn’t override the Equals or == operator so the Assert’s

// AreSame and AreEqual tests have the identical result

Assert.IsFalse(

prototypeObject.DeepCopyWeapon == clonedMonkey.DeepCopyWeapon,

“Fail2” );

Assert.AreEqual(

((LaserDisruptor)prototypeObject.DeepCopyWeapon).RateOfFire,

((LaserDisruptor)clonedMonkey.DeepCopyWeapon).RateOfFire, “Fail3” );

// — Are equal, as in the same object because it is the Shallow Copy

Assert.AreEqual( prototypeObject.ShallowCopyWeapon,

clonedMonkey.ShallowCopyWeapon,

“Fail4” );

Assert.AreEqual(

((LaserDisruptor)prototypeObject.ShallowCopyWeapon).RateOfFire,

((LaserDisruptor)clonedMonkey.ShallowCopyWeapon).RateOfFire, “Fail5” );

// Testing for Same

// — Only the DeepCopyAttribute properties should be the same

// — Not same because it is not a referance object (float)

Assert.IsFalse(

object.ReferenceEquals( prototypeObject.Speed, clonedMonkey.Speed ),

“Fail6” );

// — Not same because it is a DeepCopyAttribute

Assert.IsFalse(

object.ReferenceEquals( prototypeObject.DeepCopyWeapon,

clonedMonkey.DeepCopyWeapon),

“Fail7” );

// — Not same because it is not a referance object (float)

Assert.IsFalse( object.ReferenceEquals(

((LaserDisruptor)prototypeObject.DeepCopyWeapon).RateOfFire,

((LaserDisruptor)clonedMonkey.DeepCopyWeapon).RateOfFire), “Fail8” );

// — The only referance object that isn’t a deep copy Are Same

Assert.AreSame( prototypeObject.ShallowCopyWeapon,

clonedMonkey.ShallowCopyWeapon,

“Fail9” );

// — Not same because it is not a referance object (float)

Assert.IsFalse( object.ReferenceEquals(

((LaserDisruptor)prototypeObject.ShallowCopyWeapon).RateOfFire,

((LaserDisruptor)clonedMonkey.ShallowCopyWeapon).RateOfFire),

“Fail10” );

}

}

Your Own “Servlet” or HTML Spew Machine

So you want a quick way to spew your own html?

Create an aspx page and remove all the html and then in the code behind replace the Page_Load procedure with:

private void Page_Load(object sender, System.EventArgs e)
{
Response.Clear();
Response.ClearHeaders();
Response.ContentType = “Text/HTML”;
Response.AppendHeader( “your header”, “your value” );
Response.Write( “Your spew” );
}

Of course you don’t have to spew html.

-Mr.Phil

When I am not writing about making games, procrastinating or watching movies I’m working on a science fiction strategy game (sometimes called 4X or empire builder.) Email me questions, ideas and jokes at mrphil (at) mrphilgames . com

June 8th, 2004

Feeling pretty sick today, must have caught some bug, but I finished the code reorganizing I started yesterday. It may seem like just procrastination, but I wanted all the engine code in one assembly (was two). I also realized that I have another category of code I want to keep in it’s own namespace. I am calling this new namespace Library. So my engine now has three parts Graphics, Framework, and Library. I also took all the NUnit tests out of the class’ they test and put them into their own project. It makes the engine more portable and I can access all the namespaces in the testing area without opening up a backdoor in the engine. Next I need to break the bindings between a couple classes that are in the Framework but access the directx device. The whole idea of a Graphics namespace was to keep display specific stuff out of the Framework!!! I also started a new solution I’m calling the Sandbox. Every time I run into trouble understanding how some class works I’m going to create a project in which to experiment with it. Hopefully this will increase my understanding and build a sort of “snippet” library.