Virtual Machine/Scripting/Console in XNA using C#

Started by
11 comments, last by greedygoblins 11 years, 8 months ago
Hi I've been creating a 3D engine in C# and XNA, with the hopes of deploying on PC and XBL. One tool I've wanted to make (for the sake of development and education) is a Quake/Half-Life style console that I could use to run commands and scripts. I'm aware having a console is pointless on the XBOX but its useful in the dev cycle. I've created a "Virtual Machine" that is basically a dictionary of all the functions i want to make accessible to the console and the script manager. Different classes can register their Functions with the VM with a meta tag so that it can be called by the user or script.

My next step is to add support for scripting. But I have a few questions....

1. Am i taking the most efficient approach to implementing this type of functionality?

2. And if i place a script in my content and Build the solution is my script being compiled as well? (From what I've read parsing text is very slow and doesnt scale well - but the Xbox doesn't support the compiler class!)

Here is the start of my VM and Console:

VirtualMachine.cs

namespace AnoeTech
{
public class VirtualMachine
{
#region Structs
private struct FunctionHeader
{
public Func<object[], object> Function;
public int NumberOfParameters;
public Type[] ParameterType;
}
#endregion
#region Variables
VMConsole _console;
Game1 _engine;
Dictionary<string, FunctionHeader> FunctionDictionary = new Dictionary<string, FunctionHeader>();

#endregion
#region Accessors
public VMConsole Console{ get{ return _console;} }
public Game1 Engine{ get{ return _engine;} }
#endregion
#region Functions
public void Initiate( Game1 engine )
{
_engine = engine; // Link the VM to the engine - this gives the VM access to the entire scope of the game
// so you can make calls to any class within the game.
_console = new VMConsole(); // Create a new console
_console.Initiate(this); // and Initiate it
}
public void RegisterFunction<T>(string command, int numberOfArguments, Type[] parameterTypes, Func<object[], T> function)
{
FunctionHeader functionHeader = new FunctionHeader(); // Create a new Function Header
functionHeader.Function = args => function(args); // Pass the Function into the Header
functionHeader.NumberOfParameters = numberOfArguments; // Set the number of parameters the function takes
functionHeader.ParameterType = parameterTypes; // Set the array of parameter types
FunctionDictionary.Add(command, functionHeader); // Add the Meta Tag and Function Header to the Dictionary
Console.Output("Function " + command + " has been registered with the VM.");
}
public void RegisterFunction(string command, int numberOfArguments, Type[] parameterTypes, Action<object[]> function)
{
FunctionHeader functionHeader = new FunctionHeader(); // This code does the same as above
functionHeader.Function = args => { function.Invoke(args); return null; }; // but is responsible for handling
functionHeader.NumberOfParameters = numberOfArguments; // functions that have no return value.
functionHeader.ParameterType = parameterTypes;
FunctionDictionary.Add(command, functionHeader);
Console.Output("Function " + command + " has been registered with the VM.");
}
public object Execute(string command, object[] args)
{
return FunctionDictionary[command].Function.Invoke(args); // Execute a command and pass the result to the caller
}
public void ExecuteFromConsole( string command, object[] args)
{
if (FunctionDictionary.ContainsKey(command)) // If the Command is registered
{
if (args.Length == FunctionDictionary[command].NumberOfParameters) // And the correct number of parameters were used
{
bool allIsGood = true;
for (int counter = 0; counter < FunctionDictionary[command].NumberOfParameters; counter++)
if (args[counter].GetType() == FunctionDictionary[command].ParameterType[counter]) // And the parameters are all the correct type
continue;
else
allIsGood = false;
if (allIsGood)
{
FunctionDictionary[command].Function.Invoke(args); //Then execute the command
Console.Output("Executed: " + Console.Command);
}
else
Console.Output("=Command " + command + " takes different type for parameter=");
}
else
Console.Output("=Command " + command + " takes " + FunctionDictionary[command].NumberOfParameters + " parameters=");
}
else
Console.Output("=Command " + command + " not recognized=");
}
public void Update()
{
}
#endregion
}
}


VMConsole.cs


namespace AnoeTech
{
public class VMConsole
{
#region Variables
private Texture2D _consolePanel;
private string[] _consoleData;
private string _command;
private Vector2 _consoleTextPosition;
private char[] _delimiterChars = { ' ', '(', ',', ')' };
private int _maxLines = 8;
private Vector2 _position, _targetPosition;
private bool _slidingIn = false;
private bool _slidingOut = false;
private bool _visible = false;
private VirtualMachine _vm;
private int _width, _height;
#endregion
#region Accessors
public bool IsVisible { get { return _visible; } private set { _visible = value; } }
public string Command { get { return _command; } private set { _command = value; } }
#endregion
#region Public Functions
public void Draw()
{
if (IsVisible)
{
// Draw the console panel graphic
_vm.Engine.spriteBatch.Draw(_consolePanel, new Rectangle((int)_position.X, (int)_position.Y, _width, _height), Color.White);
// Draw the current command
_vm.Engine.spriteBatch.DrawString(_vm.Engine.Font, _command, _consoleTextPosition, Color.White, 0, new Vector2(0, 0), 0.7f, SpriteEffects.None, 0.5f);

// Draw the command/debug history
if (_consoleData != null) // If there is prior data
{
Vector2 originalPosition = _consoleTextPosition; // Save the original start position
for( int counter = 0; counter < _consoleData.Length; counter++ ) // Go through all the lines of debug info
{
_consoleTextPosition.Y -= 14; // Move up to print the next line of debug info
_vm.Engine.spriteBatch.DrawString(_vm.Engine.Font, // Write the info onto the console
_consoleData[counter], _consoleTextPosition, Color.White,
0, new Vector2(0, 0), 0.7f, SpriteEffects.None, 0.5f);
if (counter == _maxLines) break; // If we are at the max # of visible lines then break
}
_consoleTextPosition = originalPosition; // Reset the console text position back to the original
}
}
}
public void Hide()
{
_slidingOut = true;
}
public void Initiate(VirtualMachine vm)
{
_vm = vm;
_consolePanel = vm.Engine.Content.Load<Texture2D>("HUD/consolePanel");
_position = new Vector2(0, vm.Engine.Resolution.Y);
_targetPosition = new Vector2(0, (int)Math.Ceiling(vm.Engine.Resolution.Y - vm.Engine.Resolution.Y * 0.2f));
_consoleTextPosition = new Vector2(10, _position.Y + vm.Engine.Resolution.Y * 0.2f - 26);
_width = (int)vm.Engine.Resolution.X;
_height = (int)(vm.Engine.Resolution.Y * 0.2);
// Register console based functions with the VM
Type[] y = new Type[1]; y[0] = typeof(string);
vm.RegisterFunction("CONSOLE2FILE", 1, y, arg => SaveToFile((string)arg[0])); // Saves the console to a txt file
}
public void Output(string line)
{
_command = line;
UpdateText();
}
public void Show()
{
IsVisible = true;
_slidingIn = true;
_vm.Engine.Pause(true);
}
public void Update(KeyboardState keyState, KeyboardState oldkeyState)
{
if (_slidingIn) // If sliding in
{
_position.Y -= 0.1f * (_position.Y - _targetPosition.Y); // Move 10% of the total distance to target
_consoleTextPosition.Y -= 0.1f * (_position.Y - _targetPosition.Y); // Move the text 10% of the totale distance too
if (Math.Abs(_position.Y - _targetPosition.Y) < 0.1f) // If we are within .1 of the target
{
_position.Y = _targetPosition.Y; // Snap to the target
_consoleTextPosition.Y = _position.Y + _vm.Engine.Resolution.Y * 0.2f - 14; // Snap the text to the target
_targetPosition = new Vector2(0, _vm.Engine.Resolution.Y); // Set the target to the original starting pos
_slidingIn = false; // Set liding in to false
}
}
else if (_slidingOut) // If sliding out
{
_position.Y -= 0.1f * (_position.Y - _targetPosition.Y); // Opposite code of sliding in
_consoleTextPosition.Y -= 0.1f * (_position.Y - _targetPosition.Y);
if (Math.Abs(_position.Y - _targetPosition.Y) < 0.1f)
{
_position.Y = _targetPosition.Y;
_consoleTextPosition.Y = _position.Y + _vm.Engine.Resolution.Y * 0.2f - 26;
_targetPosition = new Vector2(0, (int)(_vm.Engine.Resolution.Y - _vm.Engine.Resolution.Y * 0.2f));
_slidingOut = false;
IsVisible = false;
_vm.Engine.Pause(false); // Unpause the engine
}
}
else // If not sliding in or out
{
Keys[] keys = keyState.GetPressedKeys(); // Make an array of all the pressed keys
foreach (Keys key in keys) // For each key
{
if (oldkeyState.IsKeyUp(key)) // If not pressed last iteration ( done to avoid registering a key press twice or more )
if (key == Keys.Back) // If user pressed BackSpace
{
if (_command.Length > 0) // If there is text
_command = _command.Remove(_command.Length - 1, 1); // Remove the last character in the string
}
else if (key == Keys.Space) // If user presses SPACE
_command = _command.Insert(_command.Length, " "); // Add a space
else if (key == Keys.Enter) // If user presses ENTER
BuildCommand(); // Build and attempt to execute the command
else if ((int)key >= 48 && (int)key <= 57) // If the users presses 0-9
_command += ((int)key - 48); // Add "0" - "9" (as a char)
else if ((int)key >= 96 && (int)key <= 105) //..
_command += ((int)key - 96);
else if (key == Keys.OemPeriod) // If user presses period
_command += "."; // Add "."
else // If any other entry
_command += key.ToString(); // Add the entry as a string
}
}
}
#endregion
#region Private Functions
private void BuildCommand()
{
string[] words = _command.Split(_delimiterChars); // Create an array of all the words entered
string command = words[0]; // Assign the first word as the command
object[] args = new object[words.Length-1]; // Create an array to hold all the arguements in the command
bool tmpBool;
float tmpFloat;
int tmpInt;
for (int counter = 1; counter < words.Length; counter++ ) // Build the list of arguements from the command string
{
if(int.TryParse(words[counter], out tmpInt)) // If the string is an Integer convert it
args[counter - 1] = tmpInt;
else if (float.TryParse(words[counter], out tmpFloat)) // If the string is a Float convert it
args[counter - 1] = tmpFloat;
else if (bool.TryParse(words[counter], out tmpBool)) // If the string is a Bool convert it
args[counter - 1] = tmpBool;
else // Otherwise its a string
args[counter - 1] = words[counter];
}
_vm.ExecuteFromConsole(command, args); // Execute the command
}
public void SaveToFile( string filename )
{
System.IO.File.WriteAllLines(System.IO.Directory.GetCurrentDirectory() + "'\'" + filename, _consoleData);
}
private void UpdateText()
{
int length = 0; // Assume there are no lines of text in the console cache
if (_consoleData != null) // But if there is lines of data in the console cache
length = _consoleData.Length; // Set length to the number of lines there are
string[] consoleData = new string[length + 1]; // Make a new string array with space for the new line
for (int x = length; x > 0; x--) // Go through each line in the console starting from the back
{
consoleData[x] = _consoleData[x - 1]; // Place them in the new array, filling from the end of the array towards the front
}
consoleData[0] = _command.ToString(); // Put the newest command in the the first slot of the array
_consoleData = consoleData; // Assign the new array to _consoleData
_command = ""; // Clear the command line for the next command
}
#endregion
}
}
Advertisement
*BUMP*

I want to have compiled scripts but be able to deploy on XBOX. Will simply including them in the Content make them compiled???
Out of curiousity, why are you writing your own? There are existing tools like Lua that are already well-written, debugged, and have tool chains written for them.

What do you hope to gain by writing yet another scripting engine when so many others are out there? What do you need that they cannot already do?
A few things:

- Namely just knowledge. I'm interested in knowing how to create and implement my own solutions into my software so that i understand how it works. Its how I learn, I cant afford school so I geek out. Just me and my IDE.
- The other problem is that Lua can be used in XNA and C# through LuaInterace, but its unmanaged code, so cannot be executed on the Xbox360 (which is a requirement for my game). Do you know of a library that would work?
So I have a new question haha


I have a function that returns the angle between two objects. It takes two arguments position1 and position2. In my VM i have registered the function GET_ANGLE_BETWEEN with 2 vector3's as parameters. In my HUD class I made a widget in my game, called a Variable Tracker. It displays results returned from a function registered in the VM.

My problem specifically is that I register the Variable Tracker with the camera's position and the camera's target position in the beginning of the game. however as the camera moves and targets move the values that are passed to the function aren't changing. In c# aren't all variables passed by reference? In my c++ engine I would pass pointers of the camera position, but I thought c# automatically passes a reference???

Heres the VariableTracker:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace AnoeTech
{
class HUDVarWatcher : HUDObject
{
private float _fontSize;
private string[] _VMCommands;
private object[][] _args;
public override void Destroy()
{
throw new NotImplementedException();
}
public override void Draw()
{
_engine.spriteBatch.Draw(_bgTexture, new Rectangle((int)_position.X, (int)_position.Y, (int)_size.X, (int)_size.Y), new Color(255,255,255, 100));
for (int x = 0; x < _VMCommands.Length; x++)
{
if(_args != null)
_engine.spriteBatch.DrawString(_engine.font, _engine.virtualMachine.Execute(_VMCommands[x], _args[x]).ToString(), _position, Color.White, 0, new Vector2(0, 0), _fontSize, SpriteEffects.None, 0.5f);
else
_engine.spriteBatch.DrawString(_engine.font, _engine.virtualMachine.Execute(_VMCommands[x], null).ToString(), _position, Color.White, 0, new Vector2(0, 0), _fontSize, SpriteEffects.None, 0.5f);
}
}
public override void Initiate(Game1 engine, Vector2 position, Vector2 size)
{
_engine = engine;
_position = position;
_size = size;
_bgTexture = engine.Content.Load<Texture2D>("HUD/hudPanelGeneric");
}
public void LockToVariable(string[] VMCommands, object[][] args, float fontSize)
{
_args = args;
_VMCommands = VMCommands;
_fontSize = fontSize;
}
public override void Update()
{
if (_transitioningIn) TransitionIn();
if (_transitioningOut) TransitionOut();
}
}
}


and the creation of the object in my main file:


/// Angle tracker widget
HUDVarWatcher tester2 = new HUDVarWatcher();
tester2.Initiate(this, new Vector2(100, 200), new Vector2(75, 25));
String[] str2 = new String[1];
str2[0] = "GET_ANGLE_BETWEEN";
Object[][] args = new object[1][]{ new object[2] {camera.position, camera.Target.position}};
tester2.LockToVariable(str2, args, 0.7f);

hud.Add(tester2);


When the HUD is updated it executes the command used by the VarWatcher - GET_ANGLE_BETWEEN - but the values arent changing...

Any suggestions on how i can make sure the widget is always displaying the current angle between the two?
I think you are confusing reference types with pass-by-reference. Rather than try and explain (since I'm bad at explanations), you may want to look here for some info: http://www.yoda.arachsys.com/csharp/parameters.html

In particular, note that XNA Vectors are value types, and that by default all objects (either structs or classes) are passed by value (not by reference).

Also, if you are coming from a strong C++ background to C#, in general this may be of value: http://www.andymcm.com/csharpfaq.htm
Thanks for the links, my C# is pretty good though. Ive been porting my engine from OpenGL to C# and XNA. And lemme say, C# and XNA = half the lines of code to get the same stuff done.

However I think i'm not describing my problem properly. My virtual machine can be passed any set of variables as a parameter. The problem is that they're not being referenced. and i think the problem is here:

Object[][] args2 = new object[1][] { new object[2] { camera.Position, camera.Target.Position } };

i have to pass the arguements as an array of objects. How would I create this array with the reference to the camera's position?

Object[][] args2 = new object[1][] { new object[2] { ref camera.Position, ref camera.Target.Position } }; <----doesnt work.

Whats happening is the position isnt updating to match the true position of the camera. Its staying at whatever the position is at the time of creating the widget....

Object[][] args2 = new object[1][] { new object[2] { ref camera.Position, ref camera.Target.Position } }; <----doesnt work.

Whats happening is the position isnt updating to match the true position of the camera. Its staying at whatever the position is at the time of creating the widget....


It's possible I'm still misunderstanding, but here is how I see it:

You want to reference the two Position values - however, Vectors are structs, thus value types, so they are being copied into your new object (just like any other value, such as an int).

What you need to do is copy a reference type that contains and exposes those values. In the above case, "camera" is (probably) a reference, so couldn't you just have your object keep a copy of the camera reference?

In general, when you want to hold on to a reference to a value type, you need to put it inside of a reference type.
I see what you're saying. While that would work I dont want to have to hardcode in a reference for every new object type i make in my game, it defeats the purpose of having the console/VM. I want to be able to create a widget to watch any variable and pass it at runtime....

thanks for the help ill have to think of a different solution though methinks
In C#, you can never store references to structs/value types, you can only pass them as references to methods. If you are not planning on obfuscating your code then I highly recommend you to use Reflection for stuff like this. The first version of my console used some regex magic in combination with alot of reflection to achieve what you are probably trying to do here.

For the record, my current console also supports C# commands (statements) and IronPython commands/statements which may only work on Windows, but I'm not really sure a console like that would be particularly useful on an xbox anyway with the differences in input devices etc. For me it's mostly a debug tool.

This topic is closed to new replies.

Advertisement