You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
455 lines
17 KiB
455 lines
17 KiB
8 years ago
|
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
|
||
|
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
|
||
9 years ago
|
|
||
9 years ago
|
using UnityEngine;
|
||
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using System;
|
||
|
using System.Linq;
|
||
9 years ago
|
using System.Text;
|
||
9 years ago
|
using System.Text.RegularExpressions;
|
||
|
using MoonSharp.Interpreter;
|
||
|
|
||
|
namespace Fungus
|
||
|
{
|
||
8 years ago
|
/// <summary>
|
||
|
/// A collection of utilites to use in Lua for common Unity / Fungus tasks.
|
||
|
/// </summary>
|
||
8 years ago
|
public class LuaUtils : LuaEnvironment.Initializer, ISubstitutionHandler, ILuaUtils
|
||
9 years ago
|
{
|
||
8 years ago
|
public enum FungusModuleOptions
|
||
|
{
|
||
|
UseGlobalVariables, // Fungus helper items will be available as global variables.
|
||
|
UseFungusVariable, // Fungus helper items will be available in the 'fungus' global variable.
|
||
|
NoFungusModule // The fungus helper module will not be loaded.
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// Controls if the fungus utilities are accessed from globals (e.g. say) or via a fungus variable (e.g. fungus.say)"
|
||
|
/// You can also choose to disable loading the fungus module if it's not required by your script.
|
||
|
/// </summary>
|
||
|
[Tooltip("Controls if the fungus utilities are accessed from globals (e.g. say) or via a fungus variable (e.g. fungus.say)")]
|
||
8 years ago
|
[SerializeField] protected FungusModuleOptions fungusModule = FungusModuleOptions.UseGlobalVariables;
|
||
9 years ago
|
|
||
9 years ago
|
/// <summary>
|
||
|
/// The currently selected language in the string table. Affects variable substitution.
|
||
|
/// </summary>
|
||
|
[Tooltip("The currently selected language in the string table. Affects variable substitution.")]
|
||
8 years ago
|
[SerializeField] protected string activeLanguage = "en";
|
||
8 years ago
|
public virtual string ActiveLanguage { get { return activeLanguage; } set { activeLanguage = value; } }
|
||
8 years ago
|
|
||
9 years ago
|
/// <summary>
|
||
|
/// Lua script file which defines the global string table used for localisation.
|
||
|
/// </summary>
|
||
|
[HideInInspector]
|
||
|
[Tooltip("List of JSON text files which contain localized strings. These strings are added to the 'stringTable' table in the Lua environment at startup.")]
|
||
8 years ago
|
[SerializeField] protected List<TextAsset> stringTables = new List<TextAsset>();
|
||
9 years ago
|
|
||
8 years ago
|
/// <summary>
|
||
|
/// JSON text files listing the c# types that can be accessed from Lua.
|
||
|
/// </summary>
|
||
|
[HideInInspector]
|
||
9 years ago
|
[Tooltip("JSON text files listing the c# types that can be accessed from Lua.")]
|
||
8 years ago
|
[SerializeField] protected List<TextAsset> registerTypes = new List<TextAsset>();
|
||
9 years ago
|
|
||
|
/// <summary>
|
||
|
/// Flag used to avoid startup dependency issues.
|
||
|
/// </summary>
|
||
|
protected bool initialised = false;
|
||
|
|
||
|
/// <summary>
|
||
|
/// Cached reference to the string table (if loaded).
|
||
|
/// </summary>
|
||
9 years ago
|
protected Table stringTable;
|
||
9 years ago
|
|
||
8 years ago
|
/// <summary>
|
||
|
/// Cached reference to the Lua Environment component.
|
||
|
/// </summary>
|
||
8 years ago
|
protected ILuaEnvironment LuaEnv { get; set; }
|
||
9 years ago
|
|
||
8 years ago
|
protected StringSubstituter stringSubstituter;
|
||
9 years ago
|
|
||
8 years ago
|
protected ConversationManager conversationManager;
|
||
|
|
||
|
/// <summary>
|
||
|
/// Registers all listed c# types for interop with Lua.
|
||
|
/// You can also register types directly in the Awake method of any
|
||
|
/// monobehavior in your scene using UserData.RegisterType().
|
||
|
/// </summary>
|
||
|
protected virtual void InitTypes()
|
||
|
{
|
||
|
bool isFungusInstalled = (Type.GetType("Fungus.Flowchart") != null);
|
||
|
|
||
|
foreach (TextAsset textFile in registerTypes)
|
||
|
{
|
||
|
if (textFile == null)
|
||
|
{
|
||
|
continue;
|
||
|
}
|
||
9 years ago
|
|
||
9 years ago
|
// Parse JSON file
|
||
|
JSONObject jsonObject = new JSONObject(textFile.text);
|
||
|
if (jsonObject == null ||
|
||
|
jsonObject.type != JSONObject.Type.OBJECT)
|
||
|
{
|
||
|
UnityEngine.Debug.LogError("Error parsing JSON file " + textFile.name);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
// Register types with MoonSharp
|
||
|
JSONObject registerTypesArray = jsonObject.GetField("registerTypes");
|
||
|
if (registerTypesArray != null &&
|
||
|
registerTypesArray.type == JSONObject.Type.ARRAY)
|
||
|
{
|
||
|
foreach (JSONObject entry in registerTypesArray.list)
|
||
|
{
|
||
|
if (entry != null &&
|
||
|
entry.type == JSONObject.Type.STRING)
|
||
|
{
|
||
|
string typeName = entry.str.Trim();
|
||
|
|
||
|
// Don't register fungus types if the Fungus library is not present
|
||
|
if (!isFungusInstalled &&
|
||
|
typeName.StartsWith("Fungus."))
|
||
|
{
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
LuaEnvironment.RegisterType(typeName);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Register extension types with MoonSharp
|
||
|
JSONObject extensionTypesArray = jsonObject.GetField("extensionTypes");
|
||
|
if (extensionTypesArray != null &&
|
||
|
extensionTypesArray.type == JSONObject.Type.ARRAY)
|
||
|
{
|
||
|
foreach (JSONObject entry in extensionTypesArray.list)
|
||
|
{
|
||
|
if (entry != null &&
|
||
|
entry.type == JSONObject.Type.STRING)
|
||
|
{
|
||
|
string typeName = entry.str.Trim();
|
||
|
|
||
|
// Don't register fungus types if the Fungus library is not present
|
||
|
if (!isFungusInstalled &&
|
||
|
typeName.StartsWith("Fungus."))
|
||
|
{
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
LuaEnvironment.RegisterType(typeName, true);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
8 years ago
|
}
|
||
|
}
|
||
9 years ago
|
|
||
|
/// <summary>
|
||
9 years ago
|
/// Binds all gameobjects and components defined in LuaBindings components to LuaEnvironments.
|
||
9 years ago
|
/// </summary>
|
||
|
protected virtual void InitBindings()
|
||
|
{
|
||
8 years ago
|
LuaBindingsBase[] bindings = GameObject.FindObjectsOfType<LuaBindingsBase>();
|
||
|
foreach (LuaBindingsBase binding in bindings)
|
||
9 years ago
|
{
|
||
8 years ago
|
binding.AddBindings(LuaEnv);
|
||
9 years ago
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
/// <summary>
|
||
|
/// Register some commonly used Unity classes and objects for Lua interop.
|
||
|
/// To register more class objects externally to this class, register them in the Awake method of any
|
||
|
/// monobehavior in your scene.
|
||
|
/// </summary>
|
||
|
protected virtual void InitFungusModule()
|
||
|
{
|
||
|
if (fungusModule == FungusModuleOptions.NoFungusModule)
|
||
|
{
|
||
|
return;
|
||
|
}
|
||
|
|
||
8 years ago
|
MoonSharp.Interpreter.Script interpreter = LuaEnv.Interpreter;
|
||
8 years ago
|
|
||
|
// Require the Fungus module and assign it to the global 'fungus'
|
||
|
Table fungusTable = null;
|
||
|
MoonSharp.Interpreter.DynValue value = interpreter.RequireModule("fungus");
|
||
|
if (value != null &&
|
||
|
value.Type == DataType.Function)
|
||
|
{
|
||
|
fungusTable = value.Function.Call().Table;
|
||
|
}
|
||
|
if (fungusTable == null)
|
||
|
{
|
||
|
UnityEngine.Debug.LogError("Failed to create Fungus table");
|
||
|
return;
|
||
|
}
|
||
|
interpreter.Globals["fungus"] = fungusTable;
|
||
|
|
||
|
// Static classes
|
||
|
fungusTable["time"] = UserData.CreateStatic(typeof(Time));
|
||
9 years ago
|
fungusTable["playerprefs"] = UserData.CreateStatic(typeof(PlayerPrefs));
|
||
8 years ago
|
fungusTable["prefs"] = UserData.CreateStatic(typeof(FungusPrefs));
|
||
|
fungusTable["factory"] = UserData.CreateStatic(typeof(PODTypeFactory));
|
||
|
|
||
|
// Lua Environment and Lua Utils components
|
||
8 years ago
|
fungusTable["luaenvironment"] = LuaEnv;
|
||
8 years ago
|
fungusTable["luautils"] = this;
|
||
|
|
||
|
// Provide access to the Unity Test Tools (if available).
|
||
|
Type testType = Type.GetType("IntegrationTest");
|
||
|
if (testType != null)
|
||
|
{
|
||
|
UserData.RegisterType(testType);
|
||
|
fungusTable["test"] = UserData.CreateStatic(testType);
|
||
|
}
|
||
|
|
||
|
// Populate the string table by parsing the string table JSON files
|
||
9 years ago
|
stringTable = new Table(interpreter);
|
||
|
fungusTable["stringtable"] = stringTable;
|
||
|
foreach (TextAsset stringFile in stringTables)
|
||
|
{
|
||
|
if (stringFile.text == "")
|
||
|
{
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
JSONObject stringsJSON = new JSONObject(stringFile.text);
|
||
|
if (stringsJSON == null ||
|
||
|
stringsJSON.type != JSONObject.Type.OBJECT)
|
||
|
{
|
||
|
UnityEngine.Debug.LogError("String table JSON format is not correct " + stringFile.name);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
foreach (string stringKey in stringsJSON.keys)
|
||
|
{
|
||
|
if (stringKey == "")
|
||
|
{
|
||
|
UnityEngine.Debug.LogError("String table JSON format is not correct " + stringFile.name);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
Table entriesTable = new Table(interpreter);
|
||
|
stringTable[stringKey] = entriesTable;
|
||
|
|
||
|
JSONObject entries = stringsJSON.GetField(stringKey);
|
||
|
if (entries.type != JSONObject.Type.OBJECT)
|
||
|
{
|
||
|
UnityEngine.Debug.LogError("String table JSON format is not correct " + stringFile.name);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
foreach (string language in entries.keys)
|
||
|
{
|
||
|
string translation = entries.GetField(language).str;
|
||
|
entriesTable[language] = translation;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
9 years ago
|
|
||
8 years ago
|
stringSubstituter = new StringSubstituter();
|
||
8 years ago
|
stringSubstituter.CacheSubstitutionHandlers();
|
||
9 years ago
|
|
||
8 years ago
|
conversationManager = new ConversationManager();
|
||
8 years ago
|
conversationManager.PopulateCharacterCache();
|
||
9 years ago
|
|
||
8 years ago
|
if (fungusModule == FungusModuleOptions.UseGlobalVariables)
|
||
|
{
|
||
|
// Copy all items from the Fungus table to global variables
|
||
|
foreach (TablePair p in fungusTable.Pairs)
|
||
|
{
|
||
|
if (interpreter.Globals.Keys.Contains(p.Key))
|
||
|
{
|
||
|
UnityEngine.Debug.LogError("Lua globals already contains a variable " + p.Key);
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
interpreter.Globals[p.Key] = p.Value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
interpreter.Globals["fungus"] = DynValue.Nil;
|
||
|
|
||
|
// Note: We can't remove the fungus table itself because of dependencies between functions
|
||
|
}
|
||
|
}
|
||
9 years ago
|
|
||
8 years ago
|
#region LuaEnvironment.Initializer implementation
|
||
|
|
||
|
public override void Initialize()
|
||
|
{
|
||
|
LuaEnv = GetComponent<ILuaEnvironment>();
|
||
|
if (LuaEnv == null)
|
||
|
{
|
||
|
Debug.LogError("No Lua Environment found");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
if (LuaEnv.Interpreter == null)
|
||
|
{
|
||
|
Debug.LogError("No Lua interpreter found");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
InitTypes();
|
||
|
InitFungusModule();
|
||
|
InitBindings();
|
||
|
}
|
||
|
|
||
9 years ago
|
/// <summary>
|
||
8 years ago
|
/// Called by LuaEnvironment prior to executing a script.
|
||
9 years ago
|
/// </summary>
|
||
8 years ago
|
public override string PreprocessScript(string input)
|
||
|
{
|
||
|
return input;
|
||
|
}
|
||
|
|
||
|
#endregion
|
||
|
|
||
|
#region ILuaUtils implementation
|
||
|
|
||
9 years ago
|
public virtual string GetString(string key)
|
||
|
{
|
||
9 years ago
|
if (stringTable != null)
|
||
9 years ago
|
{
|
||
|
// Match against string table and active language
|
||
9 years ago
|
DynValue stringTableVar = stringTable.Get(key);
|
||
9 years ago
|
if (stringTableVar.Type == DataType.Table)
|
||
|
{
|
||
|
DynValue languageEntry = stringTableVar.Table.Get(activeLanguage);
|
||
|
if (languageEntry.Type == DataType.String)
|
||
|
{
|
||
|
return languageEntry.String;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return "";
|
||
|
}
|
||
|
|
||
8 years ago
|
[MoonSharpHidden]
|
||
|
public virtual bool SubstituteStrings(StringBuilder input)
|
||
9 years ago
|
{
|
||
8 years ago
|
// This method could be called from the Start of another component, so
|
||
|
// we need to ensure that the LuaEnvironment has been initialized.
|
||
8 years ago
|
if (LuaEnv == null)
|
||
8 years ago
|
{
|
||
8 years ago
|
LuaEnv = GetComponent<ILuaEnvironment>();
|
||
|
if (LuaEnv != null)
|
||
8 years ago
|
{
|
||
8 years ago
|
LuaEnv.InitEnvironment();
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
if (LuaEnv == null)
|
||
8 years ago
|
{
|
||
|
UnityEngine.Debug.LogError("No Lua Environment found");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
8 years ago
|
if (LuaEnv.Interpreter == null)
|
||
8 years ago
|
{
|
||
|
UnityEngine.Debug.LogError("No Lua interpreter found");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
8 years ago
|
MoonSharp.Interpreter.Script interpreter = LuaEnv.Interpreter;
|
||
9 years ago
|
|
||
|
// Instantiate the regular expression object.
|
||
8 years ago
|
Regex r = new Regex("\\{\\$.*?\\}");
|
||
9 years ago
|
|
||
9 years ago
|
bool modified = false;
|
||
|
|
||
9 years ago
|
// Match the regular expression pattern against a text string.
|
||
9 years ago
|
var results = r.Matches(input.ToString());
|
||
9 years ago
|
foreach (Match match in results)
|
||
|
{
|
||
|
string key = match.Value.Substring(2, match.Value.Length - 3);
|
||
|
|
||
8 years ago
|
// Match against string table and active language (if specified)
|
||
|
if (stringTable != null)
|
||
|
{
|
||
|
DynValue stringTableVar = stringTable.Get(key);
|
||
|
if (stringTableVar.Type == DataType.Table)
|
||
|
{
|
||
|
DynValue languageEntry = stringTableVar.Table.Get(activeLanguage);
|
||
|
if (languageEntry.Type == DataType.String)
|
||
|
{
|
||
|
input.Replace(match.Value, languageEntry.String);
|
||
9 years ago
|
modified = true;
|
||
8 years ago
|
}
|
||
|
continue;
|
||
|
}
|
||
|
}
|
||
9 years ago
|
|
||
|
// Match against global variables
|
||
|
DynValue globalVar = interpreter.Globals.Get(key);
|
||
|
if (globalVar.Type != DataType.Nil)
|
||
|
{
|
||
9 years ago
|
input.Replace(match.Value, globalVar.ToPrintString());
|
||
|
modified = true;
|
||
9 years ago
|
continue;
|
||
|
}
|
||
|
}
|
||
|
|
||
9 years ago
|
return modified;
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
public virtual string Substitute(string input)
|
||
|
{
|
||
9 years ago
|
return stringSubstituter.SubstituteStrings(input);
|
||
8 years ago
|
}
|
||
|
|
||
|
public virtual GameObject Find(string name)
|
||
|
{
|
||
|
return GameObject.Find(name);
|
||
|
}
|
||
|
|
||
|
public virtual GameObject FindWithTag(string tag)
|
||
|
{
|
||
|
return GameObject.FindGameObjectWithTag(tag);
|
||
|
}
|
||
|
|
||
|
public virtual GameObject[] FindGameObjectsWithTag(string tag)
|
||
|
{
|
||
|
return GameObject.FindGameObjectsWithTag(tag);
|
||
|
}
|
||
9 years ago
|
|
||
8 years ago
|
public virtual GameObject Instantiate(GameObject go)
|
||
|
{
|
||
|
return GameObject.Instantiate(go);
|
||
|
}
|
||
|
|
||
|
public virtual void Destroy(GameObject go)
|
||
|
{
|
||
|
GameObject.Destroy(go);
|
||
|
}
|
||
|
|
||
|
public virtual GameObject Spawn(string resourceName)
|
||
|
{
|
||
|
// Auto spawn a say dialog object from the prefab
|
||
|
GameObject prefab = Resources.Load<GameObject>(resourceName);
|
||
|
if (prefab != null)
|
||
|
{
|
||
|
GameObject go = Instantiate(prefab) as GameObject;
|
||
8 years ago
|
go.name = resourceName.Replace("Prefabs/", "");
|
||
8 years ago
|
return go;
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
public virtual IEnumerator DoConversation(string conv)
|
||
|
{
|
||
|
return conversationManager.DoConversation(conv);
|
||
|
}
|
||
|
|
||
8 years ago
|
public void SetSayDialog(ISayDialog sayDialog)
|
||
8 years ago
|
{
|
||
|
SayDialog.activeSayDialog = sayDialog;
|
||
|
}
|
||
8 years ago
|
|
||
|
#endregion
|
||
9 years ago
|
}
|
||
|
}
|