Exemplo n.º 1
0
    public static ActionNetwork AreSkillNamesUnique(ActionLibrary library)
    {
        for (int i = 0; i < library.networks.Length; ++i)
        {
            string[] names = new string[library.networks[i].skills.Count];

            for (int j = 0; j < library.networks[i].skills.Count; ++j)
            {
                names[j] = library.networks[i].skills[j].Name.RemoveSpecialCharacters();
            }

            for (int j = 0; j < library.networks[i].skills.Count; ++j)
            {
                for (int k = j + 1; k < library.networks[i].skills.Count; ++k)
                {
                    if (names[j].Equals(names[k]))
                    {
                        return(library.networks[i]);
                    }
                }
            }
        }

        return(null);
    }
Exemplo n.º 2
0
    /// <summary>
    /// Step this instance.
    /// </summary>
    public override void Step()
    {
        // Do a certain number of actions based loosely on the population,
        // the frequency of the reference action, the overall sum of action
        // frequencies, and the target number of iterations...
        // target_iterations and reference_action (as well as all action frequencies)
        // asre set in ActionLibrary
        float fib_factor = PersonTown.Singleton.aliveResidents.Count / 10.0f;

        for (int i = 0; i < (ActionLibrary.ActualIterations * fib_factor); i++)
        {
            ActionType randAction = ActionLibrary.FrequencyFilteredRandomSelection();
            if (randAction != null)
            {
                randAction.InstantiateAndExecute();
            }
            else
            {
                continue;
            }
        }

        if (PersonTown.Singleton.aliveResidents.Count == 0) // Town is dead
        {
            return;
        }
    }
Exemplo n.º 3
0
 public ActionDefinition(ActionLibrary parent, string name, int id)
 {
     Library = parent;
     GameMakerVersion = 520;
     Name = name;
     ActionID = id;
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     Properties.Resources.DefaultAction.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
     OriginalImage = ms.ToArray();
     ms.Close();
     Image = new System.Drawing.Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     System.Drawing.Graphics.FromImage(Image).DrawImage(Properties.Resources.DefaultAction, new System.Drawing.Rectangle(0, 0, 24, 24), new System.Drawing.Rectangle(0, 0, 24, 24), System.Drawing.GraphicsUnit.Pixel);
     (Image as System.Drawing.Bitmap).MakeTransparent(Properties.Resources.DefaultAction.GetPixel(0, Properties.Resources.DefaultAction.Height - 1));
     Hidden = false;
     Advanced = false;
     RegisteredOnly = false;
     Description = string.Empty;
     ListText = string.Empty;
     HintText = string.Empty;
     Kind = ActionKind.Normal;
     InterfaceKind = ActionInferfaceKind.Normal;
     IsQuestion = false;
     ShowApplyTo = true;
     ShowRelative = true;
     ArgumentCount = 0;
     Arguments = new ActionArgument[8];
     for (int i = 0; i < 8; i++) Arguments[i] = new ActionArgument();
     ExecutionType = ActionExecutionType.None;
     FunctionName = string.Empty;
     Code = string.Empty;
 }
Exemplo n.º 4
0
    public static byte[] GetData(ActionLibrary library)
    {
        CoAdjointProjectAsset projectAsset = new CoAdjointProjectAsset();

        MemoryStream    memoryStream    = new MemoryStream();
        BinaryFormatter binaryFormatter = new BinaryFormatter();

        //Serialise library to memoryStream
        binaryFormatter.Serialize(memoryStream, library);
        memoryStream.Close();

        //Store memory stream as byte array
        projectAsset.data = memoryStream.ToArray();

        memoryStream    = new MemoryStream();
        binaryFormatter = new BinaryFormatter();

        //Seralise projectAsset to memoryStream (useful if project asset contains other data)
        binaryFormatter.Serialize(memoryStream, projectAsset);

        memoryStream.Close();

        //Return it
        return(memoryStream.ToArray());
    }
Exemplo n.º 5
0
    static public void SerializeToBin(ActionLibrary library)
    {
        IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        Stream     stream    = new FileStream(Application.dataPath + @"/coAdjoint/Action/Exports/" + Selection.activeObject.name + ".ActLib", FileMode.Create, FileAccess.Write, FileShare.None);

        formatter.Serialize(stream, library);
        stream.Close();
    }
Exemplo n.º 6
0
    public override void OnInspectorGUI()
    {
        GUILayout.TextArea("This asset contains your Action Library. The library contains one or more" +
                           " networks for use in your Unity3D project. To edit the library, press the 'Edit Library' button below.");
        EditorGUILayout.Separator();

        ActionAsset highlightedAsset = Selection.activeObject as ActionAsset;

        try
        {
            currentLibrary = ActionLibrary.LoadData(highlightedAsset.libraryData);
        }
        catch {}

        GUILayout.Label("This library contains " + currentLibrary.networks.Length + " networks.");
        EditorGUILayout.Separator();

        GUILayout.BeginHorizontal();
        {
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Edit Library", GUILayout.MaxWidth(100f)))
            {
                ActionMenu.EditLibraryAsset();
            }
            GUILayout.FlexibleSpace();
        }
        GUILayout.EndHorizontal();

        GUILayout.Space(10f);

        GUILayout.BeginHorizontal();
        {
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Generate Runtime Library from Asset"))
            {
                //ActionClassGenerator.CreateNetworkClass(Selection.activeObject as ActionAsset);
                ActionCompiler.GenerateRTLibrary(Selection.activeObject as ActionAsset);
            }
            GUILayout.FlexibleSpace();
        }
        GUILayout.EndHorizontal();

        GUILayout.Space(10f);

        GUILayout.BeginHorizontal();
        {
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Export Library"))
            {
                SerializeToXML(currentLibrary);
                //SerializeToBin(currentLibrary);
            }
            GUILayout.FlexibleSpace();
        }
        GUILayout.EndHorizontal();
    }
Exemplo n.º 7
0
 public StandardLibrary(GameContext context)
 {
     Context = context;
     D3d     = new D3dFunctions(context);
     Drawing = new DrawingFunctions(context);
     Main    = new MainFunctions(context);
     Move    = new MoveFunctions(context);
     Real    = new RealFunctions(context);
     Actions = new ActionLibrary(context);
 }
Exemplo n.º 8
0
        private void LoadActionLibraries()
        {
            m_actionLibs.Clear();

            if (Settings.Default.DontUseLibs)
            {
                return;
            }

            var path = Settings.Default.LibPath;

            if (!Directory.Exists(path))
            {
                LogLine("The specified action library directory doesn't exist.", MessageType.Warning, false);
                return;
            }

            var filePaths = Directory.GetFiles(path, "*.lib");

            LogLine("Loading action libraries...", MessageType.Information, true);
            SetStatus("Loading action libraries...");

            foreach (var filePath in filePaths)
            {
                var fileName = Path.GetFileName(filePath);

                try {
                    using (var file = File.OpenRead(filePath)) {
                        var lib = new ActionLibrary();
                        lib.ReadFrom(file);

                        m_actionLibs.Add(lib);
                        LogLine(fileName + " loaded successfully", MessageType.Success, true);
                    }
                }
                catch (GameMaker.Format.Exceptions.FileCorrupted) {
                    LogLine("Failed to load " + fileName + " action library: file is corrupted", MessageType.Error, true);
                }
                catch (GameMaker.Format.Exceptions.UnsupportedVersion) {
                    LogLine("Failed to load " + fileName + " action library: unsupported version", MessageType.Error, true);
                }
                catch (IOException) {
                    LogLine("Error occurred while trying to read " + fileName + " action library.", MessageType.Error, true);
                }
            }

            LogLine("Finished loading action libraries.", MessageType.Success, true);
            SetStatus("Finished loading action libraries.");
        }
Exemplo n.º 9
0
    public static void GenerateRTLibrary(ActionAsset asset)
    {
        ActionLibrary library = ActionLibrary.LoadData(asset.libraryData);

        ActionNetwork illegalNetwork = AreSkillNamesUnique(library);

        StringBuilder text = new StringBuilder();

        if (illegalNetwork != null)
        {
            EditorUtility.DisplayDialog("Error", "At least two skills in the network " + illegalNetwork.name + " contained in the currently " +
                                        "selected asset have the same name after special characters have been removed from their names. Please change their names to ensure " +
                                        "they will be unique when special characters are removed.", "Ok");

            return;
        }
        else
        {
            for (int i = 0; i < library.networks.Length; ++i)
            {
                if (library.networks[i].skills.Count > 0)
                {
                    text.Append(ActionClassGenerator.ClassString(library.networks[i]) + "\n\n");
                }
            }

            string TEMPADDRESS = string.Empty;

            if (Application.platform != RuntimePlatform.WindowsEditor)
            {
                TEMPADDRESS = Path.Combine(Path.Combine(Path.Combine(EditorApplication.applicationContentsPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar), "Frameworks"), "Managed")
                                           , "UnityEngine.dll");
            }
            else
            {
                TEMPADDRESS = Path.Combine(Path.Combine(EditorApplication.applicationContentsPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar), "Managed")
                                           , "UnityEngine.dll");
            }

            using (StreamWriter writer = new StreamWriter("output.txt", false))
            {
                writer.WriteLine(text);
            }

            CompilerParameters compilerParameters = new CompilerParameters();
            compilerParameters.ReferencedAssemblies.Add(TEMPADDRESS);
            compilerParameters.ReferencedAssemblies.Add("system.dll");
            compilerParameters.ReferencedAssemblies.Add(Application.dataPath + @"/coAdjoint/Action/ACE.dll");
            compilerParameters.OutputAssembly = Application.dataPath + "/coAdjoint/Action/Builds/" + asset.name + "Build.dll";

            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp");

            CompilerResults cr = codeDomProvider.CompileAssemblyFromSource(compilerParameters, new string[]
            {
                text.ToString()
            });

            if (cr.Errors.Count > 0)
            {
                foreach (CompilerError ce in cr.Errors)
                {
                    throw new ApplicationException(ce.ToString());
                }
            }

            AssetDatabase.Refresh();
        }
    }
Exemplo n.º 10
0
    public static void ImportActionLibrary()
    {
        string file = EditorUtility.OpenFilePanel("Select Action Library to import", "", "xml");

        if (file == null || file.Length == 0)
        {
            return;
        }

        XDocument doc = XDocument.Load(file);

        try
        {
            ActionLibrary importedLibrary = new ActionLibrary();

            foreach (var network in doc.Root.Elements("Network"))
            {
                ActionNetwork actN = new ActionNetwork(network.Attribute("Name").Value);

                importedLibrary.Add(actN);

                foreach (var skill in network.Elements("Skills").Elements("Skill"))
                {
                    string[] position = skill.Element("Position").Value.Replace("(", "").Replace(")", "").Split(',');

                    EditorTwoVector pos = new EditorTwoVector(float.Parse(position[0]), float.Parse(position[1]));

                    actN.AddSkill(skill.Attribute("Name").Value, double.Parse(skill.Element("Q").Value), double.Parse(skill.Element("B").Value),
                                  double.Parse(skill.Element("v").Value), pos);
                }

                foreach (var connection in network.Elements("Connections").Elements("Connection"))
                {
                    actN.AddConnection(actN.Get(connection.Element("ToSkill").Value), actN.Get(connection.Element("FromSkill").Value),
                                       double.Parse(connection.Element("ToValue").Value), double.Parse(connection.Element("FromValue").Value));
                }
            }

            string fileName = Path.GetFileNameWithoutExtension(file);

            string nameCopy = fileName.Clone().ToString();

            int index = 0;

            if (System.IO.File.Exists(Application.dataPath + "/coAdjoint/Action/Libraries/" + fileName + ".asset"))
            {
                ++index;

                while (System.IO.File.Exists(Application.dataPath + "/coAdjoint/Action/Libraries/" + fileName + index + ".asset"))
                {
                    ++index;
                }

                nameCopy += index.ToString();
            }

            var asset = ScriptableObject.CreateInstance <ActionAsset>();

            asset.libraryData = importedLibrary.GetData();

            AssetDatabase.CreateAsset(asset, "Assets/coAdjoint/Action/Libraries/" + nameCopy + ".asset");

            Selection.activeObject = asset;

            ActionMenu.EditLibraryAsset();
        }
        catch (Exception e)
        {
            Debug.LogError("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
    }
Exemplo n.º 11
0
 public ActionDefinition(ActionLibrary reference)
     : this(reference, string.Format("Action {0}", ++reference.ActionNumberIncremental), reference.ActionNumberIncremental)
 {
 }
Exemplo n.º 12
0
 public ActionLibraryWriter(ActionLibrary library, string filename)
     : this(library, new FileStream(filename, FileMode.Create))
 {
 }
Exemplo n.º 13
0
 public ActionLibraryWriter(ActionLibrary library, Stream outputStream)
 {
     Library      = library;
     OutputStream = outputStream;
 }
Exemplo n.º 14
0
 public static ActionLibrary Load(System.IO.Stream s)
 {
     ActionLibrary lib = new ActionLibrary();
     System.IO.BinaryReader br = new System.IO.BinaryReader(s, Encoding.ASCII);
     lib.GameMakerVersion = br.ReadInt32();
     bool gm5 = lib.GameMakerVersion == 500;
     lib.TabCaption = new string(br.ReadChars(br.ReadInt32()));
     lib.LibraryID = br.ReadInt32();
     lib.Author = new string(br.ReadChars(br.ReadInt32()));
     lib.Version = br.ReadInt32();
     lib.LastChanged = new DateTime(1899, 12, 30).AddDays(br.ReadDouble());
     lib.Info = new string(br.ReadChars(br.ReadInt32()));
     lib.InitializationCode = new string(br.ReadChars(br.ReadInt32()));
     lib.AdvancedModeOnly = br.ReadInt32() == 0 ? false : true;
     lib.ActionNumberIncremental = br.ReadInt32();
     for (int i = br.ReadInt32(); i > 0; i--)
     {
         int ver = br.ReadInt32();
         ActionDefinition a = new ActionDefinition(lib, new string(br.ReadChars(br.ReadInt32())), br.ReadInt32());
         a.GameMakerVersion = ver;
         int size = br.ReadInt32();
         a.OriginalImage = new byte[size];
         br.Read(a.OriginalImage, 0, size);
         System.IO.MemoryStream ms = new System.IO.MemoryStream(a.OriginalImage);
         System.Drawing.Bitmap b = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(ms);
         a.Image = new System.Drawing.Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
         using (var g = System.Drawing.Graphics.FromImage(a.Image))
         {
             g.DrawImage(b, new System.Drawing.Rectangle(0, 0, b.Width, b.Height));
         }
         if (b.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
             ((System.Drawing.Bitmap)a.Image).MakeTransparent(b.GetPixel(0, b.Height - 1));
         ms.Close();
         b.Dispose();
         a.Hidden = br.ReadInt32() == 0 ? false : true;
         a.Advanced = br.ReadInt32() == 0 ? false : true;
         a.RegisteredOnly = ver == 500 || (br.ReadInt32() == 0) ? false : true;
         a.Description = new string(br.ReadChars(br.ReadInt32()));
         a.ListText = new string(br.ReadChars(br.ReadInt32()));
         a.HintText = new string(br.ReadChars(br.ReadInt32()));
         a.Kind = (ActionKind)br.ReadInt32();
         a.InterfaceKind = (ActionInferfaceKind)br.ReadInt32();
         a.IsQuestion = br.ReadInt32() == 0 ? false : true;
         a.ShowApplyTo = br.ReadInt32() == 0 ? false : true;
         a.ShowRelative = br.ReadInt32() == 0 ? false : true;
         a.ArgumentCount = br.ReadInt32();
         int count = br.ReadInt32();
         if (a.Arguments.Length != count)
             a.Arguments = new ActionArgument[count];
         for (int j = 0; j < count; j++)
         {
             a.Arguments[j] = new ActionArgument();
             a.Arguments[j].Caption = new string(br.ReadChars(br.ReadInt32()));
             a.Arguments[j].Type = (ActionArgumentType)br.ReadInt32();
             a.Arguments[j].DefaultValue = new string(br.ReadChars(br.ReadInt32()));
             a.Arguments[j].Menu = new string(br.ReadChars(br.ReadInt32()));
         }
         a.ExecutionType = (ActionExecutionType)br.ReadInt32();
         a.FunctionName = new string(br.ReadChars(br.ReadInt32()));
         a.Code = new string(br.ReadChars(br.ReadInt32()));
         lib.Actions.Add(a);
     }
     //Hmm...
     //ActionDefinition d = new ActionDefinition(lib);
     //d.Description = "Font...";
     //d.ArgumentCount = 1;
     //d.Arguments[0] = new ActionArgument();
     //d.Arguments[0].Type = ActionArgumentType.FontString;
     //d.ListText = "@0";
     //lib.Actions.Add(d);
     //d.Arguments[0].DefaultValue = "\"Times New Roman\",10,0,0,0,0,0";
     return lib;
 }
Exemplo n.º 15
0
    static public void SerializeToXML(ActionLibrary library)
    {
        XmlWriterSettings settings = new XmlWriterSettings()
        {
            Indent              = true,
            IndentChars         = "\t",
            NewLineOnAttributes = true
        };

        using (XmlWriter writer = XmlWriter.Create(Application.dataPath + @"/coAdjoint/Action/Exports/" + Selection.activeObject.name + ".xml", settings))
        {
            writer.WriteStartDocument();
            {
                writer.WriteStartElement("ActionLibrary");
                {
                    writer.WriteAttributeString("Name", Selection.activeObject.name);

                    foreach (ActionNetwork actN in library.networks)
                    {
                        writer.WriteStartElement("Network");
                        {
                            writer.WriteAttributeString("Name", actN.name);

                            writer.WriteStartElement("Skills");
                            {
                                foreach (ActionSkill actS in actN.skills)
                                {
                                    writer.WriteStartElement("Skill");
                                    {
                                        writer.WriteAttributeString("Name", actS.Name);

                                        writer.WriteElementString("Q", actS.Q.ToString());
                                        writer.WriteElementString("B", actS.B.ToString());
                                        writer.WriteElementString("v", actS.v.ToString());
                                        writer.WriteElementString("Position", "(" + actS.Position.X.ToString() + "," + actS.Position.Y.ToString() + ")");
                                    }
                                    writer.WriteEndElement();
                                }
                            }
                            writer.WriteEndElement();

                            writer.WriteStartElement("Connections");
                            {
                                foreach (ActionConnection actC in actN.connections)
                                {
                                    writer.WriteStartElement("Connection");
                                    {
                                        writer.WriteElementString("ToSkill", actC.To.Name);
                                        writer.WriteElementString("FromSkill", actC.From.Name);
                                        writer.WriteElementString("ToValue", actC.toValue.ToString());
                                        writer.WriteElementString("FromValue", actC.fromValue.ToString());
                                    }
                                    writer.WriteEndElement();
                                }
                            }
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                    }
                }
                writer.WriteEndElement();
            }
            writer.WriteEndDocument();
        }
    }