Beispiel #1
0
        // Token: 0x060041D2 RID: 16850 RVA: 0x0014E7E0 File Offset: 0x0014CBE0
        public void Inverse()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            CSG.CSG csg = new CSG.CSG();
            csg.Construct(this.A.GetComponent <MeshFilter>().sharedMesh, this.A.transform, 0);
            CSG.CSG csg2       = csg.Inverse();
            Mesh    sharedMesh = csg2.ToMesh();

            this.Result = new GameObject("Inverse");
            DefaultObject defaultObject = this.Result.AddComponent <DefaultObject>();
            MeshFilter    meshFilter    = this.Result.AddComponent <MeshFilter>();

            meshFilter.sharedMesh = sharedMesh;
            MeshRenderer meshRenderer = this.Result.AddComponent <MeshRenderer>();

            meshRenderer.sharedMaterial = new Material(this.A.GetComponent <MeshRenderer>().sharedMaterial);
            if (this.DeleteOriginal)
            {
                UnityEngine.Object.DestroyImmediate(this.A);
            }
            stopwatch.Stop();
            defaultObject.GenerationTimeMS = (float)stopwatch.ElapsedMilliseconds;
        }
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type.GetGenericTypeDefinition() != typeof(List <>))
            {
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
            }

            Type itemType = type.GetGenericArguments()[0];

            if (!itemType.IsEnum)
            {
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
            }

            System.Collections.IList enumArray = (System.Collections.IList)Plugin.CreateInstance(type);

            if (!string.IsNullOrEmpty(str))
            {
                int index = str.IndexOf(':');

                if (index >= 0)
                {
                    str = str.Substring(index + 1);
                }

                string[] tokens = str.Split('|');
                foreach (string s in tokens)
                {
                    enumArray.Add(Enum.Parse(itemType, s, true));
                }
            }

            return(enumArray);
        }
Beispiel #3
0
        public static string GetProperty(DefaultObject defaultObj, Behaviac.Design.PropertyDef property, MethodDef.Param arrayIndexElement, StreamWriter stream, string indent, string var, string caller)
        {
            string agentName = GetGenerateAgentName(property, var, caller);

            if (property.Owner != Behaviac.Design.VariableDef.kSelf)
            {
                bool        isGlobal      = Plugin.IsInstanceName(property.Owner, null);
                PropertyDef ownerProperty = null;

                if (!isGlobal)
                {
                    Debug.Check(defaultObj != null && defaultObj.Behavior != null && defaultObj.Behavior.AgentType != null);
                    ownerProperty = defaultObj.Behavior.AgentType.GetPropertyByName(property.Owner);
                }

                if (isGlobal || ownerProperty == null || ownerProperty.IsCustomized) // global or customized instance
                {
                    stream.WriteLine("{0}Agent* {1} = Agent::GetInstance(pAgent, \"{2}\");", indent, agentName, property.Owner);
                }
                else // member instance
                {
                    string propName   = ownerProperty.Name.Replace("::", "_");
                    string nativeType = DataCppExporter.GetGeneratedNativeType(ownerProperty.NativeType);
                    string prop       = string.Format("(({0}*)pAgent)->_Get_Property_<{1}PROPERTY_TYPE_{2}, {3} >()", ownerProperty.ClassName, getNamespace(ownerProperty.ClassName), propName, nativeType);

                    stream.WriteLine("{0}Agent* {1} = {2};", indent, agentName, prop);
                }
                stream.WriteLine("{0}BEHAVIAC_ASSERT({1});", indent, agentName);
            }

            return(getProperty(property, arrayIndexElement, agentName, stream, indent));
        }
Beispiel #4
0
        public static void GenerateClassConstructor(DefaultObject defaultObj, Behaviac.Design.VariableDef variable, StreamWriter stream, string indent, string var)
        {
            if (variable.ValueClass == Behaviac.Design.VariableDef.kConst)
            {
                Type type = variable.Value.GetType();
                if (Plugin.IsRefType(type))
                {
                    string nativeType = DataCppExporter.GetBasicGeneratedNativeType(variable.NativeType);
                    stream.WriteLine("{0}\t\t\t{1} = NULL;", indent, var);
                }
                else if (Plugin.IsArrayType(type) || Plugin.IsCustomClassType(type) || (Plugin.IsStringType(type) && !variable.IsConst))
                {
                    if (Plugin.IsArrayType(type))
                    {
                        string nativeType = DataCppExporter.GetGeneratedNativeType(variable.NativeType);
                        int    startIndex = nativeType.IndexOf('<');
                        int    endIndex   = nativeType.LastIndexOf('>');
                        string itemType   = nativeType.Substring(startIndex + 1, endIndex - startIndex - 1);

                        ArrayCppExporter.GenerateCode(variable.Value, defaultObj, stream, indent + "\t\t\t", itemType, var);
                    }
                    else if (Plugin.IsCustomClassType(type))
                    {
                        StructCppExporter.GenerateCode(variable.Value, defaultObj, stream, indent + "\t\t\t", var, null, "");
                    }
                    else if ((Plugin.IsStringType(type) && !variable.IsConst))
                    {
                        string nativeType = DataCppExporter.GetBasicGeneratedNativeType(variable.NativeType);
                        string retStr     = DataCppExporter.GenerateCode(variable.Value, defaultObj, stream, indent + "\t\t\t", nativeType, string.Empty, string.Empty);
                        stream.WriteLine("{0}\t\t\t{1} = {2};", indent, var, retStr);
                    }
                }
            }
        }
Beispiel #5
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }

            foreach (Plugin.InstanceName_t t in Plugin.InstanceNames)
            {
                if (str == t.AgentType.Name
#if BEHAVIAC_NAMESPACE_FIX
                    || t.AgentType.Name.EndsWith(str)
#endif
                    )
                {
                    return(t.AgentType);
                }
            }

            foreach (AgentType t in Plugin.AgentTypes)
            {
                if (str == t.Name || str == t.OldName
#if BEHAVIAC_NAMESPACE_FIX
                    || t.Name.EndsWith(str) || t.OldName.EndsWith(str)
#endif
                    )
                {
                    return(t);
                }
            }

            return(null);
        }
Beispiel #6
0
        public static string GenerateCode(DefaultObject defaultObj, PropertyDef property, MethodDef.Param arrayIndexElement, bool isRefParam, StringWriter stream, string indent, string typename, string var, string caller, string setValue = null)
        {
            if (property.IsPar || property.IsCustomized)
            {
                return(ParInfoCsExporter.GenerateCode(property, isRefParam, stream, indent, typename, var, caller));
            }

            string agentName = GetGenerateAgentName(property, var, caller);
            string prop      = GetProperty(defaultObj, property, arrayIndexElement, stream, indent, var, caller);

            if (setValue == null)
            {
                if (!string.IsNullOrEmpty(var))
                {
                    if (string.IsNullOrEmpty(typename))
                    {
                        stream.WriteLine("{0}{1} = {2};", indent, var, prop);
                    }
                    else
                    {
                        string nativeType = DataCsExporter.GetPropertyNativeType(property, arrayIndexElement);

                        stream.WriteLine("{0}{1} {2} = {3};", indent, nativeType, var, prop);
                    }
                }
            }
            else
            {
                string propBasicName = property.BasicName.Replace("[]", "");
                stream.WriteLine("{0}AgentMetaVisitor.SetProperty({1}, \"{2}\", {3});", indent, agentName, propBasicName, setValue);
            }

            return(prop);
        }
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type.GetGenericTypeDefinition() != typeof(List<>))
            { throw new Exception(Resources.ExceptionDesignerAttributeInvalidType); }

            Type itemType = type.GetGenericArguments()[0];

            if (!itemType.IsEnum)
            { throw new Exception(Resources.ExceptionDesignerAttributeInvalidType); }

            System.Collections.IList enumArray = (System.Collections.IList)Plugin.CreateInstance(type);

            if (!string.IsNullOrEmpty(str)) {
                int index = str.IndexOf(':');

                if (index >= 0)
                { str = str.Substring(index + 1); }

                string[] tokens = str.Split('|');
                foreach(string s in tokens) {
                    enumArray.Add(Enum.Parse(itemType, s, true));
                }
            }

            return enumArray;
        }
Beispiel #8
0
        public static string GenerateCode(DefaultObject defaultObj, Behaviac.Design.VariableDef variable, bool isRefParam, StreamWriter stream, string indent, string typename, string var, string caller)
        {
            string retStr = string.Empty;

            if (variable.ValueClass == Behaviac.Design.VariableDef.kConst)
            {
                bool shouldGenerate = true;
                Type type           = variable.Value.GetType();

                if (Plugin.IsArrayType(type) || Plugin.IsCustomClassType(type) || (Plugin.IsStringType(type) && !variable.IsConst))
                {
                    shouldGenerate = false;
                }

                if (shouldGenerate)
                {
                    retStr = DataCppExporter.GenerateCode(variable.Value, defaultObj, stream, indent, typename, var, caller);
                }
            }
            else if (variable.Property != null)
            {
                retStr = PropertyCppExporter.GenerateCode(defaultObj, variable.Property, variable.ArrayIndexElement, isRefParam, stream, indent, typename, var, caller);
            }

            return(retStr);
        }
Beispiel #9
0
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (Plugin.IsCustomClassType(type))
            { return ParseStringValue(result, type, null, str, node); }

            throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
        }
Beispiel #10
0
        /// <summary>
        /// Used to replace the default object with a behaviour once loaded.
        /// </summary>
        /// <param name="behavior">The behaviour we have loaded.</param>
        public void AssignLoadedBehavior(BehaviorNode behavior)
        {
            Debug.Check(_type == NodeTagType.Behavior);
            Debug.Check(_filename == behavior.FileManager.Filename);

            _defaults = (DefaultObject)behavior;
        }
        public new static object ParseStringValue(List<Nodes.Node.ErrorCheck> result, Type type, string str, DefaultObject node)
        {
            Debug.Check(type != null && Plugin.IsArrayType(type));

            object obj = Plugin.CreateInstance(type);
            Debug.Check(obj != null);

            if (!string.IsNullOrEmpty(str)) {
                System.Collections.IList list = (System.Collections.IList)obj;
                Type itemType = type.GetGenericArguments()[0];

                int index = str.IndexOf(':');

                if (index >= 0)
                { str = str.Substring(index + 1); }

                if (!string.IsNullOrEmpty(str)) {
                    System.Collections.IList structArray = (System.Collections.IList)Plugin.CreateInstance(type);
                    parseStringValue(result, node, structArray, itemType, str, 0, str.Length - 1);

                    return structArray;
                }
            }

            return obj;
        }
Beispiel #12
0
        /// <summary>
        /// Creates a new NodeTag and an instance of the node for the defaults.
        /// </summary>
        /// <param name="type">The type of the node in the node explorer.</param>
        /// <param name="nodetype">The type of the node which will be added to the behaviour tree.</param>
        /// <param name="filename">The filename of the behaviour we want to load. Use string.Empty if the node is not a behaviour.</param>
        public NodeTag(NodeTagType type, Type nodetype, string filename)
        {
            if ((type == NodeTagType.BehaviorFolder || type == NodeTagType.NodeFolder) && nodetype != null)
            {
                throw new Exception(Resources.ExceptionWrongNodeTagType);
            }

            _type     = type;
            _nodetype = nodetype;
            _filename = filename;

            if (nodetype == null)
            {
                _defaults = null;
            }
            else
            {
                //if(!nodetype.IsSubclassOf(typeof(DefaultObject)))
                //	throw new Exception(Resources.ExceptionNotImplementDefaultObject);

                if (nodetype.IsSubclassOf(typeof(Events.Event)) && type != NodeTagType.Event)
                {
                    throw new Exception(Resources.ExceptionWrongNodeTagType);
                }

                if (nodetype.IsSubclassOf(typeof(Nodes.Node)) && type != NodeTagType.Node && type != NodeTagType.Behavior)
                {
                    throw new Exception(Resources.ExceptionWrongNodeTagType);
                }

                _defaults = type == NodeTagType.Event ? (DefaultObject)Brainiac.Design.Events.Event.Create(nodetype, null) : (DefaultObject)Nodes.Node.Create(nodetype);
            }
        }
Beispiel #13
0
        public static void GenerateCode(object obj, DefaultObject defaultObj, StringWriter stream, string indent, string itemTypename, string var)
        {
            if (obj != null)
            {
                Type type = obj.GetType();

                if (Plugin.IsArrayType(type))
                {
                    System.Collections.IList list = (System.Collections.IList)obj;

                    if (list.Count > 0)
                    {
                        stream.WriteLine("{0}{1}.reserve({2});", indent, var, list.Count);

                        for (int i = 0; i < list.Count; ++i)
                        {
                            string itemName = string.Format("{0}_item{1}", var.Replace(".", "_"), i);

                            DataCppExporter.GenerateCode(list[i], defaultObj, stream, indent, itemTypename, itemName, string.Empty);

                            stream.WriteLine("{0}{1}.push_back({2});", indent, var, itemName);
                        }
                    }
                }
            }
        }
Beispiel #14
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(float) && type != typeof(double))
            {
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
            }


            if (type == typeof(float))
            {
                float resultValue;
                if (float.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out resultValue))
                {
                    return(resultValue);
                }
            }
            else if (type == typeof(double))
            {
                double resultValue;
                if (double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out resultValue))
                {
                    return(resultValue);
                }
            }

            throw new Exception(string.Format(Resources.ExceptionDesignerAttributeIllegalFloatValue, str));
        }
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(RightValueDef))
            {
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
            }

            if (str.Length == 0 ||
                str.Length == 2 && str == "\"\"")
            {
                return(null);
            }

            if (!str.StartsWith("const"))
            {
                int pos = str.IndexOf('(');

                if (pos < 0)
                {
                    VariableDef var = DesignerPropertyEnum.parsePropertyVar(result, node, str);

                    return(new RightValueDef(var));
                }
                else
                {
                    Nodes.Behavior behavior  = node.Behavior as Nodes.Behavior;
                    AgentType      agentType = (behavior != null) ? behavior.AgentType : null;

                    string    valueClass = VariableDef.kSelfMethod;
                    MethodDef method     = DesignerMethodEnum.parseMethodString(result, node, agentType, this.MethodType, str);

                    if (method == null)
                    {
                        string className = Plugin.GetClassName(str);
                        method     = DesignerMethodEnum.parseMethodString(result, node, Plugin.GetInstanceAgentType(className, behavior, null), this.MethodType, str);
                        valueClass = className + VariableDef.kMethod;
                    }

                    string instanceName = Plugin.GetInstanceName(str);

                    if (!string.IsNullOrEmpty(instanceName))
                    {
                        valueClass = instanceName + VariableDef.kMethod;
                    }

                    return(new RightValueDef(method, valueClass));
                }
            }
            else
            {
                VariableDef var = this.parseConstVar(result, node, parentObject, str);

                if (var != null)
                {
                    return(new RightValueDef(var));
                }
            }

            return(null);
        }
Beispiel #16
0
        public static void GenerateCode(object obj, DefaultObject defaultObj, StreamWriter stream, string indent, string var, object parent, string paramName)
        {
            Debug.Check(obj != null);

            Type type = obj.GetType();

            Debug.Check(Plugin.IsCustomClassType(type));

            MethodDef method = parent as MethodDef;
            IList <DesignerPropertyInfo> properties = DesignerProperty.GetDesignerProperties(type);

            foreach (DesignerPropertyInfo property in properties)
            {
                if (!property.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
                {
                    object member = property.GetValue(obj);

                    Type memberType = member.GetType();

                    if (Plugin.IsArrayType(memberType))
                    {
                        string memberNativeType = Plugin.GetNativeTypeName(memberType);
                        string nativeTypeStr    = DataCppExporter.GetGeneratedNativeType(memberNativeType);
                        int    startIndex       = nativeTypeStr.IndexOf('<');
                        int    endIndex         = nativeTypeStr.LastIndexOf('>');
                        string itemType         = nativeTypeStr.Substring(startIndex + 1, endIndex - startIndex - 1);

                        ArrayCppExporter.GenerateCode(member, defaultObj, stream, indent, itemType, var + "." + property.Property.Name);
                    }
                    else
                    {
                        if (property.Attribute is DesignerStruct)
                        {
                            GenerateCode(member, defaultObj, stream, indent, var + "." + property.Property.Name, parent, paramName);
                        }
                        else
                        {
                            bool bStructProperty = false;
                            if (method != null)
                            {
                                MethodDef.Param param = method.GetParam(paramName, property);
                                if (param != null)
                                {
                                    bStructProperty = true;
                                    ParameterCppExporter.GenerateCode(defaultObj, param, stream, indent, string.Empty, var + "." + property.Property.Name, string.Empty);
                                }
                            }

                            if (!bStructProperty)
                            {
                                DataCppExporter.GenerateCode(member, defaultObj, stream, indent, string.Empty, var + "." + property.Property.Name, string.Empty);
                            }
                        }
                    }
                }
            }
        }
Beispiel #17
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (Plugin.IsCustomClassType(type))
            {
                return(ParseStringValue(result, type, null, str, node));
            }

            throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
        }
Beispiel #18
0
        public override bool AcceptsAttachment(DefaultObject obj)
        {
            Type type = (obj != null) ? obj.GetType() : null;

            return(type != null && ((this.IsFSM && Plugin.IsClassDerived(type, typeof(Behaviac.Design.Attachments.AttachAction))) ||  //if fsm, only accept effectors
                                    (!Plugin.IsClassDerived(type, typeof(Behaviac.Design.Attachments.AttachAction)) &&
                                     !Plugin.IsClassDerived(type, typeof(Behaviac.Design.Attachments.Event)) &&
                                     !Plugin.IsClassDerived(type, typeof(Behaviac.Design.Nodes.Behavior)))));
        }
Beispiel #19
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(string))
            {
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
            }

            return(str);
        }
 public static void GenerateClassConstructor(DefaultObject defaultObj, RightValueDef rightValue, StringWriter stream, string indent, string var)
 {
     if (rightValue.IsMethod)
     {
         MethodCsExporter.GenerateClassConstructor(defaultObj, rightValue.Method, stream, indent, var);
     }
     else
     {
         VariableCsExporter.GenerateClassConstructor(defaultObj, rightValue.Var, stream, indent, var);
     }
 }
Beispiel #21
0
        public static string GetProperty(DefaultObject defaultObj, Behaviac.Design.PropertyDef property, MethodDef.Param arrayIndexElement, StringWriter stream, string indent, string var, string caller)
        {
            string agentName = GetGenerateAgentName(property, var, caller);

            if (property.Owner != Behaviac.Design.VariableDef.kSelf)
            {
                string      instanceName  = property.Owner.Replace("::", ".");
                bool        isGlobal      = Plugin.IsInstanceName(instanceName, null);
                PropertyDef ownerProperty = null;

                if (!isGlobal)
                {
                    Debug.Check(defaultObj != null && defaultObj.Behavior != null && defaultObj.Behavior.AgentType != null);
                    if (defaultObj != null && defaultObj.Behavior != null)
                    {
                        ownerProperty = defaultObj.Behavior.AgentType.GetPropertyByName(instanceName);
                    }
                }

                if (isGlobal || ownerProperty == null || ownerProperty.IsCustomized || ownerProperty.IsPar) // global or customized instance
                {
                    stream.WriteLine("{0}behaviac.Agent {1} = behaviac.Utils.GetParentAgent(pAgent, \"{2}\");", indent, agentName, instanceName);
                }
                else // member instance
                {
                    string prop = "";

                    if (ownerProperty.IsPublic)
                    {
                        string className = ownerProperty.ClassName.Replace("::", ".");

                        if (ownerProperty.IsStatic)
                        {
                            prop = string.Format("{0}.{1}", className, instanceName);
                        }
                        else
                        {
                            prop = string.Format("(({0})pAgent).{1}", className, instanceName);
                        }
                    }
                    else
                    {
                        string nativeType = DataCsExporter.GetGeneratedNativeType(ownerProperty.NativeType);
                        prop = string.Format("({0})AgentMetaVisitor.GetProperty(pAgent, \"{1}\")", nativeType, instanceName);
                    }

                    stream.WriteLine("{0}behaviac.Agent {1} = {2};", indent, agentName, prop);
                }

                //stream.WriteLine("{0}Debug.Check(!System.Object.ReferenceEquals({1}, null) || Utils.IsStaticClass(\"{2}\"));", indent, agentName, instanceName);
            }

            return(getProperty(property, arrayIndexElement, agentName, stream, indent));
        }
Beispiel #22
0
        public static VariableDef setParameter(List <Nodes.Node.ErrorCheck> result, DefaultObject node, string propertyName)
        {
            Behaviac.Design.Nodes.Behavior behavior = node.Behavior as Behaviac.Design.Nodes.Behavior;

            // Convert the Par to the Property
            if (!propertyName.Contains(".") && !propertyName.Contains(":"))
            {
                propertyName = "Self." + behavior.AgentType.AgentTypeName + "::" + propertyName;
            }

            VariableDef var      = null;
            string      instance = Plugin.GetInstanceName(propertyName);

            if (!string.IsNullOrEmpty(instance))
            {
                propertyName = propertyName.Substring(instance.Length + 1, propertyName.Length - instance.Length - 1);

                var = createVariable(result, node, behavior.AgentType, instance, propertyName);

                if (var != null)
                {
                    return(var);
                }
            }

            // Try to find the Agent property with the name.
            if (behavior != null && behavior.AgentType != null)
            {
                instance = "Self";
                var      = createVariable(result, node, behavior.AgentType, instance, propertyName);

                if (var != null)
                {
                    return(var);
                }
            }

            // Try to find the global property with the name.
            string instacneName = Plugin.GetClassName(propertyName);

            if (!string.IsNullOrEmpty(instacneName) && Plugin.GetInstanceAgentType(instacneName) != null)
            {
                var = createVariable(result, node, behavior.AgentType, instacneName, propertyName);

                if (var != null)
                {
                    return(var);
                }
            }

            return(null);
        }
Beispiel #23
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (!Plugin.IsIntergerNumberType(type))
            {
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
            }

            int resultValue = 0;

            if (int.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out resultValue))
            {
                if (type == typeof(uint))
                {
                    return((uint)resultValue);
                }

                if (type == typeof(short))
                {
                    return((short)resultValue);
                }

                if (type == typeof(ushort))
                {
                    return((ushort)resultValue);
                }

                if (type == typeof(sbyte))
                {
                    return((sbyte)resultValue);
                }

                if (type == typeof(byte))
                {
                    return((byte)resultValue);
                }

                if (type == typeof(long))
                {
                    return((long)resultValue);
                }

                if (type == typeof(ulong))
                {
                    return((ulong)resultValue);
                }

                return(resultValue);
            }

            throw new Exception(string.Format(Resources.ExceptionDesignerAttributeIllegalIntegerValue, str));
        }
        public static bool parseParam(List <Nodes.Node.ErrorCheck> result, DefaultObject node, MethodDef method, MethodDef.Param par, string param)
        {
            string propName = null;

            if (param[0] == '\"')
            {
                param = param.Substring(1, param.Length - 2);
            }
            else if (param[0] == '{')     //struct
            {
                //to set it as action.Method is used in the following parsing
                Nodes.Action action = node as Nodes.Action;

                if (action != null && action.Method == null)
                {
                    action.Method = method;
                }
            }
            else
            {
                string noStaticParam = param.Replace("static ", "");
                int    index         = noStaticParam.IndexOf(" ");

                if (index >= 0)
                {
                    propName = noStaticParam.Substring(index + 1);
                }
            }

            bool bOk = false;

            if (propName != null)
            {
                VariableDef var = setParameter(result, node, propName);

                if (var != null)
                {
                    par.Value = var;
                    bOk       = true;
                }
            }
            else
            {
                bOk = Plugin.InvokeTypeParser(result, par.Type, param,
                                              (object value) => par.Value = value,
                                              node, par.Name);
            }

            return(bOk);
        }
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(RightValueDef))
            { throw new Exception(Resources.ExceptionDesignerAttributeInvalidType); }

            if (str.Length == 0 ||
                str.Length == 2 && str == "\"\"") {
                return null;
            }

            if (!str.StartsWith("const")) {
                int pos = str.IndexOf('(');

                if (pos < 0) {
                    VariableDef var = DesignerPropertyEnum.parsePropertyVar(result, node, str);

                    return new RightValueDef(var);

                } else {
                    Nodes.Behavior behavior = node.Behavior as Nodes.Behavior;
                    AgentType agentType = (behavior != null) ? behavior.AgentType : null;

                    string valueClass = VariableDef.kSelfMethod;
                    MethodDef method = DesignerMethodEnum.parseMethodString(result, node, agentType, this.MethodType, str);

                    if (method == null) {
                        string className = Plugin.GetClassName(str);
                        method = DesignerMethodEnum.parseMethodString(result, node, Plugin.GetInstanceAgentType(className, behavior, null), this.MethodType, str);
                        valueClass = className + VariableDef.kMethod;
                    }

                    string instanceName = Plugin.GetInstanceName(str);

                    if (!string.IsNullOrEmpty(instanceName)) {
                        valueClass = instanceName + VariableDef.kMethod;
                    }

                    return new RightValueDef(method, valueClass);
                }

            } else {
                VariableDef var = this.parseConstVar(result, node, parentObject, str);

                if (var != null) {
                    return new RightValueDef(var);
                }
            }

            return null;
        }
Beispiel #26
0
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(bool))
            { throw new Exception(Resources.ExceptionDesignerAttributeInvalidType); }

            str = str.ToLowerInvariant();

            if (str == "true")
            { return true; }

            if (str == "false")
            { return false; }

            throw new Exception(string.Format(Resources.ExceptionDesignerAttributeIllegalBooleanValue, str));
        }
        public static string GenerateCode(DefaultObject defaultObj, RightValueDef rightValue, StringWriter stream, string indent, string typename, string var, string caller)
        {
            string retStr = string.Empty;

            if (rightValue.IsMethod)
            {
                retStr = MethodCsExporter.GenerateCode(defaultObj, rightValue.Method, stream, indent, rightValue.Method.NativeReturnType, var, caller);
            }
            else
            {
                retStr = VariableCsExporter.GenerateCode(defaultObj, rightValue.Var, false, stream, indent, typename, var, caller);
            }

            return(retStr);
        }
        private static void parseStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, System.Collections.IList structArray, Type itemType, string str, int startIndex, int endIndex)
        {
            string propertyName  = string.Empty;
            string propertyValue = string.Empty;

            int nextIndex = getItemStr(str, startIndex, endIndex, out propertyName, out propertyValue);

            if (nextIndex > 0)
            {
                object item = DesignerStruct.ParseStringValue(result, itemType, null, propertyValue, node);
                structArray.Add(item);

                parseStringValue(result, node, structArray, itemType, str, nextIndex, endIndex);
            }
        }
Beispiel #29
0
        public static string GenerateCode(DefaultObject defaultObj, Behaviac.Design.MethodDef.Param param, StreamWriter stream, string indent, string typename, string var, string caller)
        {
            Behaviac.Design.ParInfo par = param.Value as Behaviac.Design.ParInfo;
            if (par != null)
            {
                return(ParInfoCppExporter.GenerateCode(par, param.IsRef, stream, indent, typename, var, caller));
            }

            Behaviac.Design.VariableDef v = param.Value as Behaviac.Design.VariableDef;
            if (v != null)
            {
                return(VariableCppExporter.GenerateCode(defaultObj, v, param.IsRef, stream, indent, typename, var, caller));
            }

            return(DataCppExporter.GenerateCode(param.Value, defaultObj, stream, indent, typename, var, caller));
        }
Beispiel #30
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (!type.IsEnum)
            {
                //throw new Exception(string.Format(Resources.ExceptionDesignerAttributeExpectedEnum, type));
                Debug.Check(false);
                return(null);
            }

            string[] parts = str.Split(':');

            if (parts.Length != 2)
            {
                // keep compatibility with version 1
                //throw new Exception( string.Format(Resources.ExceptionDesignerAttributeEnumCouldNotReadValue, str) );
                parts = new string[] { str, "-1" };
            }

            string enumname = parts[0];

            int enumval;

            try
            {
                // try to get the enum value by name
                enumval = (int)Enum.Parse(type, enumname, true);
            }
            catch
            {
                // try to read the stored enum value index
                if (!int.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out enumval))
                {
                    throw new Exception(string.Format(Resources.ExceptionDesignerAttributeEnumCouldNotParseValue, str));
                }

                // try to get the enum value by index
                if (Enum.ToObject(type, enumval) == null)
                {
                    throw new Exception(string.Format(Resources.ExceptionDesignerAttributeEnumIllegalEnumIndex, enumval));
                }

                enumval = (int)Plugin.DefaultValue(type);
            }

            return(enumval);
        }
Beispiel #31
0
        public static bool parseParam(List <Nodes.Node.ErrorCheck> result, DefaultObject node, MethodDef method, MethodDef.Param par, string param)
        {
            string[] tokens = null;

            if (param[0] == '\"')
            {
                param = param.Substring(1, param.Length - 2);
            }
            else if (param[0] == '{')
            {
                //struct

                //to set it as action.Method is used in the following parsing
                Nodes.Action action = node as Nodes.Action;

                if (action != null)
                {
                    action.Method = method;
                }
            }
            else
            {
                tokens = param.Split(' ');
            }


            bool bOk = false;

            if (tokens != null && tokens.Length > 1)
            {
                //par
                VariableDef var = setParameter(result, node, tokens[tokens.Length - 1]);

                if (var != null)
                {
                    par.Value = var;
                    bOk       = true;
                }
            }
            else
            {
                bOk = Plugin.InvokeTypeParser(result, par.Type, param, (object value) => par.Value = value, node, par.Name);
            }

            return(bOk);
        }
Beispiel #32
0
        public static void GenerateClassConstructor(DefaultObject defaultObj, Behaviac.Design.MethodDef method, StringWriter stream, string indent, string var)
        {
            for (int i = 0; i < method.Params.Count; ++i)
            {
                // const value
                if (!method.Params[i].IsProperty && !method.Params[i].IsLocalVar)
                {
                    object obj = method.Params[i].Value;

                    if (obj != null)
                    {
                        string param = var + "_p" + i;
                        Type   type  = obj.GetType();

                        if (Plugin.IsArrayType(type))
                        {
                            string nativeType = DataCppExporter.GetGeneratedNativeType(method.Params[i].NativeType);
                            int    startIndex = nativeType.IndexOf('<');
                            int    endIndex   = nativeType.LastIndexOf('>');
                            string itemType   = nativeType.Substring(startIndex + 1, endIndex - startIndex - 1);

                            ArrayCppExporter.GenerateCode(obj, defaultObj, stream, indent + "\t\t\t", itemType, param);
                        }
                        else if (Plugin.IsCustomClassType(type))
                        {
                            if (Plugin.IsRefType(type))
                            {
                                stream.WriteLine("{0}\t\t\t{1} = NULL;", indent, param);
                            }
                            else if (DesignerStruct.IsPureConstDatum(obj, method, method.Params[i].Name))
                            {
                                StructCppExporter.GenerateCode(obj, defaultObj, stream, indent + "\t\t\t", param, null, "");
                            }
                        }
                        else
                        {
                            string nativeType = DataCppExporter.GetBasicGeneratedNativeType(method.Params[i].NativeType);
                            string retStr     = DataCppExporter.GenerateCode(obj, defaultObj, stream, string.Empty, nativeType, string.Empty, string.Empty);
                            stream.WriteLine("{0}\t\t\t{1} = {2};", indent, param, retStr);
                        }
                    }
                }
            }
        }
Beispiel #33
0
        public static void GenerateOperand(DefaultObject defaultObj, StringWriter stream, string indent, RightValueDef operand, string operandName, string nodeName)
        {
            if (operand != null)
            {
                string typeName = DataCsExporter.GetGeneratedNativeType(operand.ValueType);
                typeName = typeName.Replace("::", ".");

                if (operand.IsMethod) // method
                {
                    RightValueCsExporter.GenerateCode(defaultObj, operand, stream, indent, typeName, operandName, string.Empty);
                    RightValueCsExporter.PostGenerateCode(operand, stream, indent, typeName, operandName, string.Empty);
                }
                else
                {
                    VariableDef var = operand.Var;

                    if (var != null)
                    {
                        if (var.IsProperty) // property
                        {
                            PropertyDef prop = var.Property;

                            if (prop != null)
                            {
                                string property = PropertyCsExporter.GetProperty(defaultObj, prop, var.ArrayIndexElement, stream, indent, operandName, nodeName);
                                string propName = prop.BasicName.Replace("[]", "");

                                if (prop.IsArrayElement && var.ArrayIndexElement != null)
                                {
                                    ParameterCsExporter.GenerateCode(defaultObj, var.ArrayIndexElement, stream, indent, "int", operandName + "_index", nodeName + "_opl");
                                    property = string.Format("({0})[{1}_index]", property, operandName);
                                }

                                stream.WriteLine("{0}{1} {2} = {3};", indent, typeName, operandName, property);
                            }
                        }
                        else if (var.IsConst) // const
                        {
                            RightValueCsExporter.GenerateCode(defaultObj, operand, stream, indent, typeName, operandName, string.Empty);
                        }
                    }
                }
            }
        }
Beispiel #34
0
        public void ResetId()
        {
            bool bReset = (this.Id < 0);

            if (!bReset)
            {
                DefaultObject obj = Plugin.GetObjectById((Nodes.Node)Node.Behavior, this.Id);

                if (obj != null && obj != this)
                {
                    bReset = true;
                }
            }

            if (bReset)
            {
                this.Id = Plugin.NewNodeId((Nodes.Node)Node.Behavior);
            }
        }
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(MethodDef))
            { throw new Exception(Resources.ExceptionDesignerAttributeInvalidType); }

            Nodes.Behavior behavior = node.Behavior as Nodes.Behavior;

            if (behavior != null && behavior.AgentType != null) {
                MethodDef method = parseMethodString(result, node, behavior.AgentType, this.MethodType, str);

                if (method == null) {
                    string className = Plugin.GetClassName(str);
                    method = parseMethodString(result, node, Plugin.GetInstanceAgentType(className, behavior, null), this.MethodType, str);
                }

                return method;
            }

            return null;
        }
Beispiel #36
0
        public override object FromStringValue(List <Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type == typeof(string))
            {
                return(trimQuotes(str));
            }
            else if (Plugin.IsCharType(type))
            {
                if (str.Length >= 1)
                {
                    char r = str[0];
                    return(r);
                }

                //return "";
                return('A');
            }

            throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);
        }
Beispiel #37
0
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            foreach(Plugin.InstanceName_t t in Plugin.InstanceNames) {
                if (str == t.agentType_.AgentTypeName
#if BEHAVIAC_NAMESPACE_FIX
                    || t.agentType_.AgentTypeName.EndsWith(str)
#endif
                   ) {
                    return t.agentType_;
                }
            }

            foreach(AgentType t in Plugin.AgentTypes) {
                if (str == t.ToString()
#if BEHAVIAC_NAMESPACE_FIX
                    || t.AgentTypeName.EndsWith(str)
#endif
                   ) {
                    return t;
                }
            }

            return null;
        }
        public static bool parseParam(List<Nodes.Node.ErrorCheck> result, DefaultObject node, MethodDef method, MethodDef.Param par, string param)
        {
            string[] tokens = null;

            if (param[0] == '\"') {
                param = param.Substring(1, param.Length - 2);

            } else if (param[0] == '{') {
                //struct

                //to set it as action.Method is used in the following parsing
                Nodes.Action action = node as Nodes.Action;

                if (action != null) {
                    action.Method = method;
                }

            } else {
                tokens = param.Split(' ');
            }


            bool bOk = false;

            if (tokens != null && tokens.Length > 1) {
                //par
                VariableDef var = setParameter(result, node, tokens[tokens.Length - 1]);

                if (var != null) {
                    par.Value = var;
                    bOk = true;
                }

            } else {
                bOk = Plugin.InvokeTypeParser(result, par.Type, param, (object value) => par.Value = value, node, par.Name);
            }

            return bOk;
        }
        private static VariableDef createVariable(List<Nodes.Node.ErrorCheck> result, DefaultObject node, AgentType agentType, string instacneName, string propertyName)
        {
            List<string> tokens = DesignerPropertyEnum.SplitTokens(propertyName);
            Debug.Check(tokens.Count > 0);
            string arrayIndexStr = null;

            if (tokens.Count > 1) {
                propertyName = tokens[0] + "[]";
                arrayIndexStr = tokens[1];
            }

            Nodes.Behavior behavior = node.Behavior as Nodes.Behavior;
            agentType = Plugin.GetInstanceAgentType(instacneName, behavior, agentType);

            if (agentType != null) {
                IList<PropertyDef> properties = agentType.GetProperties();
                foreach(PropertyDef p in properties) {
                    if (p.Name == propertyName
#if BEHAVIAC_NAMESPACE_FIX
                        || p.Name.EndsWith(propertyName)
#endif
                       ) {
                        VariableDef v = new VariableDef(p, instacneName);

                        if (v != null && !string.IsNullOrEmpty(arrayIndexStr)) {
                            v.ArrayIndexElement = new MethodDef.Param("ArrayIndex", typeof(int), "int", "ArrayIndex", "ArrayIndex");
                            v.ArrayIndexElement.IsArrayIndex = true;
                            DesignerMethodEnum.parseParam(result, node, null, v.ArrayIndexElement, arrayIndexStr);
                        }

                        return v;
                    }
                }
            }

            return null;
        }
Beispiel #40
0
 public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
 {
     return ParseStringValue(result, type, str, node);
 }
Beispiel #41
0
 /// <summary>
 /// Determines if an attachment of a certain type is aceepted by this node or not.
 /// </summary>
 /// <param name="type">The type of the attachment we want to add.</param>
 /// <returns>Returns if the attachment may be added or not</returns>
 public virtual bool AcceptsAttachment(DefaultObject obj) {
     return (obj != null) && !obj.IsFSM && obj.CanBeAttached;
 }
Beispiel #42
0
 public override bool AcceptsAttachment(DefaultObject obj)
 {
     return (obj != null) && (obj is WaitTransition);
 }
        protected VariableDef parseConstVar(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, string str)
        {
            Debug.Check(str.StartsWith("const"));

            //const Int32 1
            object propertyMemberDepended = null;
            Type objType = node.GetType();

            if (this.DependedProperty != "") {
                System.Reflection.PropertyInfo pi = objType.GetProperty(this.DependedProperty);

                if (pi != null) {
                    propertyMemberDepended = pi.GetValue(node, null);

                } else if (pi == null && parentObject != null) {
                    Type parentType = parentObject.GetType();
                    pi = parentType.GetProperty(this.DependedProperty);
                    propertyMemberDepended = pi.GetValue(parentObject, null);
                }
            }

            Type valueType = null;
            VariableDef variableDepended = propertyMemberDepended as VariableDef;

            if (variableDepended != null) {
                valueType = variableDepended.GetValueType();

            } else if (propertyMemberDepended != null) {
                MethodDef methodDepended = propertyMemberDepended as MethodDef;

                if (methodDepended != null) {
                    valueType = methodDepended.ReturnType;

                } else {
                    RightValueDef varRV = propertyMemberDepended as RightValueDef;

                    if (varRV != null) {
                        valueType = varRV.ValueType;
                    }
                }

            } else {
                string[] tokens = str.Split(' ');
                Debug.Check(tokens.Length >= 3);

                valueType = Plugin.GetTypeFromName(tokens[1]);
            }

            if (valueType != null) {
                VariableDef variable = new VariableDef(null);

                //string[] tokens = str.Split(' ');
                //Debug.Check(tokens.Length == 3);
                Debug.Check(str.StartsWith("const"));
                //skip 'const '
                int pos = str.IndexOf(' ');
                Debug.Check(pos != -1);
                pos = str.IndexOf(' ', pos + 1);
                string token = str.Substring(pos + 1);

                Plugin.InvokeTypeParser(result, valueType, token,
                                        (object value) => variable.Value = value,
                                        node);

                return variable;
            }

            return null;
        }
Beispiel #44
0
        /// <summary>
        /// Handles when a key is pressed.
        /// </summary>
        protected override void OnKeyDown(KeyEventArgs e) {
            switch (e.KeyCode) {
                    // store when the control key is pressed
                case (Keys.ControlKey):
                    if (_copiedNode == null && _movedNode == null) {
                        Cursor = Cursors.Default;
                    }

                    break;

                    // store when the shift key is pressed
                case (Keys.ShiftKey):

                    // update the drawn graph for dragging and duplicating
                    if (_movedNodeGraph != null) {
                        _movedNodeGraph.RenderDepth = int.MaxValue;
                        Invalidate();
                    }

                    break;

                    // cut to clipboard
                case (Keys.X):
                    if (KeyCtrlIsDown) {
                        CutSelectedNode(KeyShiftIsDown);
                    }

                    break;

                    // copy to clipboard
                case (Keys.C):
                    if (KeyCtrlIsDown) {
                        CopySelectedNode(KeyShiftIsDown);
                    }

                    break;

                    // paste from clipboard
                case (Keys.V):
                    if (!_clipboardPasteMode) {
                        _clipboardPasteMode = KeyCtrlIsDown && _clipboardNode != null;

                        if (_clipboardPasteMode) {
                            // create the layout manager used to draw the graph
                            _movedNodeGraph = new NodeLayoutManager(_clipboardNode.CloneBranch().CreateNodeViewData(null, _rootNodeView.RootBehavior), _nodeLayoutManager.EdgePen, _nodeLayoutManager.EdgePenSelected, _nodeLayoutManager.EdgePenHighlighted, _nodeLayoutManager.EdgePenUpdate, _nodeLayoutManager.EdgePenReadOnly, true);
                            _movedNodeGraph.Scale = 0.3f;
                            //_movedNodeGraph.RenderDepth = KeyShiftIsDown ? int.MaxValue : 0;
                            _movedNodeGraph.RenderDepth = int.MaxValue;

                            // use the existing node as the node defaults
                            _dragNodeDefaults = _clipboardNode;

                            Invalidate();
                        }
                    }

                    break;

                    // handle when the delete key is pressed
                case (Keys.Delete):
                    DeleteSelectedNode(KeyShiftIsDown);
                    break;

                case (Keys.E):
                    if (e.Control) {
                        CenterNode(_rootNodeView);
                    }

                    break;

                case (Keys.Oemplus):
                    if (e.Control) {
                        scaleGraph(0.1f * _nodeLayoutManager.Scale, false);
                    }

                    break;

                case (Keys.OemMinus):
                    if (e.Control) {
                        scaleGraph(-0.1f * _nodeLayoutManager.Scale, false);
                    }

                    break;

                case (Keys.K):
                    if (e.Control) {
                        CheckErrors(_rootNodeView.RootBehavior, false);
                    }

                    break;

                case (Keys.F9):
                    if (SelectedNode != null) {
                        if (e.Shift) {
                            SelectedNode.SetBreakpoint(HighlightBreakPoint.kExit);

                        } else if (e.Control) {
                            SelectedNode.SetBreakpoint(HighlightBreakPoint.kPlanning);

                        } else {
                            SelectedNode.SetBreakpoint(HighlightBreakPoint.kEnter);
                        }

                        LayoutChanged();
                    }

                    break;

                case (Keys.F8):
                    toggleEnableNode();
                    break;

                case (Keys.F1):
                    openDoc();
                    break;

                case (Keys.Left):
                case (Keys.Right):
                case (Keys.Up):
                case (Keys.Down):
                    if (e.Control)
                    {
                        switch (e.KeyCode)
                        {
                            case (Keys.Left):
                                _nodeLayoutManager.Offset = new PointF(_nodeLayoutManager.Offset.X - 10, _nodeLayoutManager.Offset.Y);
                                Invalidate();
                                break;

                            case (Keys.Right):
                                _nodeLayoutManager.Offset = new PointF(_nodeLayoutManager.Offset.X + 10, _nodeLayoutManager.Offset.Y);
                                Invalidate();
                                break;

                            case (Keys.Up):
                                _nodeLayoutManager.Offset = new PointF(_nodeLayoutManager.Offset.X, _nodeLayoutManager.Offset.Y - 10);
                                Invalidate();
                                break;

                            case (Keys.Down):
                                _nodeLayoutManager.Offset = new PointF(_nodeLayoutManager.Offset.X, _nodeLayoutManager.Offset.Y + 10);
                                Invalidate();
                                break;
                        }
                        break;
                    }
                    break;

                default:
                    base.OnKeyDown(e);
                    break;
            }
        }
        public static MethodDef parseMethodString(List<Nodes.Node.ErrorCheck> result, DefaultObject node, AgentType agentType, MethodType methodType, string str)
        {
            try {
                if (agentType != null) {
                    int pos = str.IndexOf('(');

                    if (pos < 0)
                    { return null; }

                    string ownerName = agentType.ToString();
                    int pointIndex = str.IndexOf('.');

                    if (pointIndex > -1 && pointIndex < pos) {
                        ownerName = str.Substring(0, pointIndex);
                        Nodes.Behavior behavior = node.Behavior as Nodes.Behavior;

                        if (ownerName != VariableDef.kSelf && !Plugin.IsInstanceName(ownerName, behavior))
                        {
                            throw new Exception("The instance does not exist.");
                        }

                        str = str.Substring(pointIndex + 1, str.Length - pointIndex - 1);
                        agentType = Plugin.GetInstanceAgentType(ownerName, behavior, agentType);
                        //if (agentType == node.Behavior.AgentType)
                        //    ownerName = VariableDef.kSelf;
                        pos = str.IndexOf('(');
                    }

                    IList<MethodDef> actions = agentType.GetMethods(methodType);
                    string actionName = str.Substring(0, pos);
                    foreach(MethodDef actionTypeIt in actions) {
                        if (actionTypeIt.Name == actionName
#if BEHAVIAC_NAMESPACE_FIX
                            || actionTypeIt.Name.EndsWith(actionName)
#endif
                           ) {
                            MethodDef method = new MethodDef(actionTypeIt);
                            method.Owner = ownerName;

                            List<string> paras = parseParams(str.Substring(pos + 1, str.Length - pos - 2));
                            //Debug.Check((paras.Count == actionTypeIt.Params.Count));

                            //if (paras.Count == actionTypeIt.Params.Count)
                            {
                                for (int i = 0; i < paras.Count; ++i) {
                                    if (i >= method.Params.Count) {
                                        break;
                                    }

                                    string param = paras[i];
                                    MethodDef.Param par = method.Params[i];
                                    bool bOk = parseParam(result, node, method, par, param);

                                    if (!bOk) {
                                        throw new Exception(string.Format(Resources.ExceptionDesignerAttributeIllegalFloatValue, str));
                                    }
                                }
                            }

                            return method;
                        }
                    }
                }

            } catch (Exception) {
                //System.Windows.Forms.MessageBox.Show(str, Resources.LoadError, System.Windows.Forms.MessageBoxButtons.OK);
                if (result != null)
                {
                    Nodes.Node n = node as Nodes.Node;
                    string label = "";
                    if (n == null)
                    {
                        Attachments.Attachment a = node as Attachments.Attachment;
                        if (a != null)
                        {
                            n = a.Node;
                            label = a.Label;
                        }
                    }
                    else
                    {
                        label = n.Label;
                    }

                    Nodes.Node.ErrorCheck error = new Nodes.Node.ErrorCheck(n, node.Id, label, Nodes.ErrorCheckLevel.Error, str);
                    result.Add(error);
                }
            }

            return null;
        }
Beispiel #46
0
        /// <summary>
        /// Handles when a mouse button is let go of.
        /// </summary>
        protected override void OnMouseUp(MouseEventArgs e)
        {
            _movedSubItem = null;

            // check if we were dragging a transition for the FSM.
            if (e.Button == MouseButtons.Left && _currentNode != null && ((_objectDragType == ObjectDragTypes.kNode) && _currentNode.IsFSM || _fsmSubItem != null && _fsmDragMode != FSMDragModes.kNone)) {
                if (Plugin.EditMode == EditModes.Design && _startMousePosition != e.Location) {
                    // drag and move the fsm node
                    if ((_objectDragType == ObjectDragTypes.kNode) && _currentNode.IsFSM) {
                        UndoManager.Save(this.RootNode);

                        LayoutChanged();
                    }

                    // drag and connector the target node
                    else {
                        NodeViewData targetNvd = _rootNodeView.GetInsideNode(e.Location);

                        if (targetNvd != null && targetNvd.IsFSM && (targetNvd.Parent != null) && _fsmSubItem is NodeViewData.SubItemAttachment) {
                            NodeViewData.SubItemAttachment subItemAttachment = _fsmSubItem as NodeViewData.SubItemAttachment;

                            if (subItemAttachment.Attachment != null && subItemAttachment.Attachment.TargetFSMNodeId != targetNvd.Node.Id) {
                                subItemAttachment.Attachment.TargetFSMNodeId = targetNvd.Node.Id;

                                UndoManager.Save(this.RootNode);

                                LayoutChanged();
                            }
                        }
                    }
                }
            }

            // check if we were dragging an existing sub item.
            else if (e.Button == MouseButtons.Left && _currentNode != null && _dragTargetNode != null && _dragAttachment != null) {
                NodeViewData.SubItem targetSubItem = _dragTargetNode.GetSubItem(_dragTargetNode, _nodeLayoutManager.ViewToGraph(e.Location));

                if (KeyCtrlIsDown || targetSubItem != _dragAttachment) {
                    NodeViewData.SubItemAttachment targetAttachment = targetSubItem as NodeViewData.SubItemAttachment;

                    if ((_currentNode != _dragTargetNode || targetAttachment != null) &&
                        this.MoveSubItem(_currentNode, _dragTargetNode, _dragAttachment, targetAttachment, _dragAttachMode == NodeAttachMode.Top, KeyCtrlIsDown)) {
                        _currentNode.ClickEvent(_currentNode, _nodeLayoutManager.ViewToGraph(e.Location));

                        LayoutChanged();
                    }
                }

                _dragAttachment = null;
                _dragTargetAttachment = null;
                _dragAttachMode = NodeAttachMode.None;
            }

            // check if we were dragging or copying an existing node.
            else if (e.Button == MouseButtons.Left && (_movedNode != null || _copiedNode != null || _clipboardPasteMode)) {
                // if we have a valid target node continue
                if (_dragTargetNode != null) {
                    Node sourceNode = null;

                    if (_copiedNode != null) {
                        bool cloneBranch = !(_copiedNode is ReferencedBehavior);
                        sourceNode = (KeyShiftIsDown && cloneBranch) ? (Nodes.Node)_copiedNode.CloneBranch() : (Nodes.Node)_copiedNode.Clone();

                    } else if (_clipboardPasteMode) {
                        bool cloneBranch = !(_clipboardNode is ReferencedBehavior);
                        sourceNode = (/*KeyShiftIsDown && */cloneBranch) ? (Nodes.Node)_clipboardNode.CloneBranch() : (Nodes.Node)_clipboardNode.Clone();

                    } else if (_movedNode != null) {
                        sourceNode = _movedNode;
                    }

                    Debug.Check(sourceNode != null);
                    Node sourceParent = (Node)sourceNode.Parent;
                    BehaviorNode sourceBehavior = sourceNode.Behavior;

                    if (_dragTargetNode.Node == sourceNode) {
                        _dragAttachMode = NodeAttachMode.None;
                    }

                    if (_dragAttachMode == NodeAttachMode.Top ||
                        _dragAttachMode == NodeAttachMode.Bottom ||
                        _dragAttachMode == NodeAttachMode.Left ||
                        _dragAttachMode == NodeAttachMode.Right ||
                        _dragAttachMode == NodeAttachMode.Center) {
                        // set the prefab dirty for its previous parent
                        if (sourceParent != null && !string.IsNullOrEmpty(sourceParent.PrefabName)) {
                            sourceParent.HasOwnPrefabData = true;
                        }

                        if (KeyShiftIsDown) {
                            if (sourceParent != null) {
                                sourceParent.RemoveChild(sourceNode.ParentConnector, sourceNode);
                            }

                        } else {
                            sourceNode.ExtractNode();
                        }
                    }

                    // move the dragged node to the target node, according to the attach mode
                    switch (_dragAttachMode) {
                            // the node will be placed above the target node
                        case (NodeAttachMode.Top):
                            int n = _dragTargetNode.Node.ParentConnector.GetChildIndex(_dragTargetNode.Node);
                            ((Node)_dragTargetNode.Node.Parent).AddChild(_dragTargetNode.Node.ParentConnector, sourceNode, n);

                            _selectedNodePending = sourceNode;
                            _selectedNodePendingParent = _dragTargetNode.Parent;

                            LayoutChanged();
                            break;

                            // the node will be placed below the target node
                        case (NodeAttachMode.Bottom):
                            int m = _dragTargetNode.Node.ParentConnector.GetChildIndex(_dragTargetNode.Node);
                            ((Node)_dragTargetNode.Node.Parent).AddChild(_dragTargetNode.Node.ParentConnector, sourceNode, m + 1);

                            _selectedNodePending = sourceNode;
                            _selectedNodePendingParent = _dragTargetNode.Parent;

                            LayoutChanged();
                            break;

                            // the node will be placed in front of the target node
                        case (NodeAttachMode.Left):
                            Node parent = (Node)_dragTargetNode.Node.Parent;
                            Node.Connector conn = _dragTargetNode.Node.ParentConnector;

                            int o = conn.GetChildIndex(_dragTargetNode.Node);

                            parent.RemoveChild(conn, _dragTargetNode.Node);
                            parent.AddChild(conn, sourceNode, o);

                            BaseNode.Connector sourceConn = sourceNode.GetConnector(conn.Identifier);
                            Debug.Check(sourceConn != null);

                            sourceNode.AddChild(sourceConn, _dragTargetNode.Node);

                            _selectedNodePending = sourceNode;
                            _selectedNodePendingParent = _dragTargetNode.Parent;

                            LayoutChanged();
                            break;

                            // the node will simply attached to the target node
                        case (NodeAttachMode.Right):
                            _dragTargetNode.Node.AddChild(_dragTargetConnector, sourceNode);

                            _selectedNodePending = sourceNode;
                            _selectedNodePendingParent = _dragTargetNode;

                            LayoutChanged();
                            break;

                            // the node will replace the target node
                        case (NodeAttachMode.Center):
                            if (replaceNode(_dragTargetNode.Node, sourceNode)) {
                                LayoutChanged();
                            }

                            break;
                    }

                    if (_dragAttachMode != NodeAttachMode.None) {
                        // If cloning a node, its Id should be reset.
                        if (_copiedNode != null || _clipboardPasteMode) {
                            // Cross two different behavior files
                            if (_clipboardPasteMode && _clipboardRootNode != this.RootNodeView) {
                                try {
                                    // Copy the used Pars from the current behavior to the new one.
                                    if (_clipboardNode != null && _clipboardRootNode != null && _clipboardRootNode.Node is Behavior) {
                                        foreach(ParInfo par in((Behavior)(_clipboardRootNode.Node)).LocalVars) {
                                            List<Node.ErrorCheck> result = new List<Node.ErrorCheck>();
                                            Plugin.CheckPar(_clipboardNode, par, ref result);

                                            if (result.Count > 0) {
                                                bool bExist = false;
                                                foreach(ParInfo p in((Behavior)this.RootNode).LocalVars) {
                                                    if (p.Name == par.Name) {
                                                        bExist = true;
                                                        break;
                                                    }
                                                }

                                                if (!bExist) {
                                                    ((Behavior)this.RootNode).LocalVars.Add(par);
                                                }
                                            }
                                        }
                                    }

                                    // reset its properties and methods
                                    sourceNode.ResetMembers(false, this.RootNode.AgentType, true);

                                } catch {
                                }
                            }

                            // reset its Id
                            sourceNode.ResetId(true);
                        }

                        // update the node's label
                        sourceNode.OnPropertyValueChanged(false);

                        // set the prefab dirty for its current parent
                        if (sourceNode.Parent != null) {
                            Node parent = (Node)sourceNode.Parent;

                            if (!string.IsNullOrEmpty(parent.PrefabName)) {
                                parent.HasOwnPrefabData = true;
                                sourceNode.SetPrefab(parent.PrefabName, true);
                            }
                        }

                        UndoManager.Save(this.RootNode);
                    }
                }

                // reset all the drag data
                if (!_clipboardPasteMode) {
                    _copiedNode = null;
                    _movedNode = null;
                    _dragTargetNode = null;
                    _dragNodeDefaults = null;
                    _movedNodeGraph = null;
                }

                // redraw the graph
                Invalidate();
            }

            // popup the menu for the current hit node
            else if (e.Button == MouseButtons.Right && !KeyAltIsDown && !KeyCtrlIsDown && !KeyShiftIsDown) {
                bool itemEnabled = (SelectedNode != null && SelectedNode.Node.Parent != null);
                itemEnabled &= (Plugin.EditMode == EditModes.Design);

                deleteMenuItem.ShortcutKeys = Keys.Delete;
                deleteTreeMenuItem.ShortcutKeys = Keys.Shift | Keys.Delete;

                cutMenuItem.Enabled = SelectedNodeCanBeCut();
                cutTreeMenuItem.Enabled = (SelectedNode != null) && !SelectedNode.IsFSM && SelectedTreeCanBeCut();
                copyMenuItem.Enabled = itemEnabled;
                copySubtreeMenuItem.Enabled = (SelectedNode != null) && !SelectedNode.IsFSM;
                pasteMenuItem.Enabled = SelectedNodeCanBePasted();
                deleteMenuItem.Enabled = SelectedNodeCanBeDeleted();
                deleteTreeMenuItem.Enabled = (SelectedNode != null) && !SelectedNode.IsFSM && SelectedTreeCanBeDeleted();

                bool isReferencedBehavior = SelectedNode != null && SelectedNode.Node is ReferencedBehavior;
                bool isEvent = SelectedNode != null && SelectedNode.SelectedSubItem != null && SelectedNode.SelectedSubItem.SelectableObject is Attachments.Event;
                referenceMenuItem.Enabled = itemEnabled || isReferencedBehavior || isEvent;
                referenceMenuItem.Text = (isReferencedBehavior || isEvent) ? Resources.OpenReference : Resources.SaveReference;

                disableMenuItem.Enabled = false;
                if (itemEnabled)
                {
                    if (SelectedNode.SelectedSubItem != null && SelectedNode.SelectedSubItem.SelectableObject is Attachments.Attachment)
                    {
                        Attachments.Attachment attach = SelectedNode.SelectedSubItem.SelectableObject as Attachments.Attachment;
                        disableMenuItem.Enabled = attach.CanBeDisabled();
                        disableMenuItem.Text = attach.Enable ? Resources.DisableNode : Resources.EnableNode;
                    }
                    else
                    {
                        disableMenuItem.Enabled = SelectedNode.Node.CanBeDisabled();
                        disableMenuItem.Text = SelectedNode.Node.Enable ? Resources.DisableNode : Resources.EnableNode;
                    }
                }

                expandMenuItem.Enabled = (SelectedNode != null && SelectedNode.CanBeExpanded());
                collapseMenuItem.Enabled = expandMenuItem.Enabled;
                expandAllMenuItem.Enabled = expandMenuItem.Enabled;
                collapseAllMenuItem.Enabled = expandMenuItem.Enabled;

                bool isPrefabInstance = SelectedNode != null && !string.IsNullOrEmpty(SelectedNode.Node.PrefabName);
                breakPrefabMenuItem.Enabled = itemEnabled && isPrefabInstance;

                if (isPrefabInstance) {
                    string fullpath = FileManagers.FileManager.GetFullPath(SelectedNode.Node.PrefabName);
                    isPrefabInstance = File.Exists(fullpath);
                }

                savePrefabMenuItem.Enabled = itemEnabled;
                savePrefabMenuItem.Text = isPrefabInstance ? Resources.OpenPrefab : Resources.SavePrefab;

                if (SelectedNode != null) {
                    Node prefabRoot = SelectedNode.Node.GetPrefabRoot();
                    string relativeFilename = FileManagers.FileManager.GetRelativePath(this.RootNode.Filename);
                    applyMenuItem.Enabled = itemEnabled && isPrefabInstance && SelectedNode.Node.PrefabName != relativeFilename && prefabRoot.IsPrefabDataDirty();
                }

                breakpointMenuItem.Enabled = SelectedNode != null && SelectedNode.Parent != null;

                if (SelectedNode != null) {
                    enterBreakpointMenuItem.Text = SelectedNode.GetBreakpointOperation(HighlightBreakPoint.kEnter);
                    exitBreakpointMenuItem.Text = SelectedNode.GetBreakpointOperation(HighlightBreakPoint.kExit);

                    this.beakpointPlanning.Visible = false;

                    if (SelectedNode.Node is Task) {
                        this.beakpointPlanning.Visible = true;
                        beakpointPlanning.Text = SelectedNode.GetBreakpointOperation(HighlightBreakPoint.kPlanning);
                    }
                }

                contextMenu.Show(this, new Point(e.X, e.Y));
            }

            Cursor = Cursors.Default;
            _fsmDragMode = FSMDragModes.kNone;

            // redraw the graph
            Invalidate();

            base.OnMouseUp(e);
        }
Beispiel #47
0
        /// <summary>
        /// Handles when a key is released.
        /// </summary>
        protected override void OnKeyUp(KeyEventArgs e) {
            switch (e.KeyCode) {
                case (Keys.Enter):
                    if (SelectedNode != null) {
                        if (KeyCtrlIsDown) {
                            SelectedNode.ExpandAll(!SelectedNode.IsExpanded);
                        }

                        else {
                            SelectedNode.IsExpanded = !SelectedNode.IsExpanded;
                        }

                        LayoutChanged();

                        e.Handled = true;
                    }

                    break;

                    // store when the shift key is released
                case (Keys.ShiftKey):

                    // update the drawn graph for dragging and duplicating
                    if (_movedNodeGraph != null) {
                        _movedNodeGraph.RenderDepth = 0;
                        Invalidate();
                    }

                    break;

                    // paste from clipboard
                case (Keys.V):
                    PasteSelectedNode();

                    _clipboardPasteMode = false;

                    // reset all the drag data
                    _copiedNode = null;
                    _movedNode = null;
                    _dragTargetNode = null;
                    _dragNodeDefaults = null;
                    _movedNodeGraph = null;

                    // redraw the graph
                    Invalidate();
                    break;

                case (Keys.Left):
                case (Keys.Right):
                case (Keys.Up):
                case (Keys.Down):
                    if (e.Control)
                    {
                        break;
                    }

                    if (SelectedNode == null) {
                        SelectedNode = this.RootNodeView;

                        if (ClickNode != null) {
                            ClickNode(SelectedNode);
                        }

                        LayoutChanged();
                        break;
                    }

                    switch (e.KeyCode) {
                        case (Keys.Left):
                            if (SelectedNode != null && SelectedNode.Parent != null) {
                                SelectedNode = SelectedNode.Parent;

                                if (ClickNode != null) {
                                    ClickNode(SelectedNode);
                                }

                                LayoutChanged();
                            }

                            break;

                        case (Keys.Right):
                            if (SelectedNode != null && SelectedNode.Children.Count > 0) {
                                SelectedNode = SelectedNode.Children[0] as NodeViewData;

                                if (ClickNode != null) {
                                    ClickNode(SelectedNode);
                                }

                                LayoutChanged();
                            }

                            break;

                        case (Keys.Up):
                            if (SelectedNode != null) {
                                if (!KeyShiftIsDown || !SwitchSelection()) {
                                    // Node
                                    if (SelectedNode.SelectedSubItem == null) {
                                        if (SelectedNode.PreviousNode != null) {
                                            if (KeyCtrlIsDown) { // Move
                                                MoveNode(true);

                                            } else { // Select
                                                SelectedNode = SelectedNode.PreviousNode as NodeViewData;

                                                if (ClickNode != null) {
                                                    ClickNode(SelectedNode);
                                                }
                                            }
                                        }
                                    }

                                    // Attachment
                                    else {
                                        NodeViewData.SubItem previousItem = SelectedNode.PreviousSelectedSubItem;

                                        if (previousItem != null) {
                                            if (KeyCtrlIsDown) { // Move
                                                NodeViewData.SubItemAttachment sourceItem = SelectedNode.SelectedSubItem as NodeViewData.SubItemAttachment;
                                                NodeViewData.SubItemAttachment targetItem = previousItem as NodeViewData.SubItemAttachment;
                                                MoveSubItem(SelectedNode, SelectedNode, sourceItem, targetItem, true, false);
                                                SelectedNode.SelectedSubItem = sourceItem;

                                            } else { // Select
                                                SelectedNode.SelectedSubItem = previousItem;

                                                if (ClickEvent != null) {
                                                    ClickEvent(SelectedNode);
                                                }
                                            }
                                        }
                                    }
                                }

                                LayoutChanged();
                            }

                            break;

                        case (Keys.Down):
                            if (SelectedNode != null) {
                                if (!KeyShiftIsDown || !SwitchSelection()) {
                                    // Node
                                    if (SelectedNode.SelectedSubItem == null) {
                                        if (SelectedNode.NextNode != null) {
                                            if (KeyCtrlIsDown) { // Move
                                                MoveNode(false);

                                            } else { // Select
                                                SelectedNode = SelectedNode.NextNode as NodeViewData;

                                                if (ClickNode != null) {
                                                    ClickNode(SelectedNode);
                                                }
                                            }
                                        }
                                    }

                                    // Attachment
                                    else {
                                        NodeViewData.SubItem nextItem = SelectedNode.NextSelectedSubItem;

                                        if (nextItem != null) {
                                            if (KeyCtrlIsDown) { // Move
                                                NodeViewData.SubItemAttachment sourceItem = SelectedNode.SelectedSubItem as NodeViewData.SubItemAttachment;
                                                NodeViewData.SubItemAttachment targetItem = nextItem as NodeViewData.SubItemAttachment;
                                                MoveSubItem(SelectedNode, SelectedNode, sourceItem, targetItem, false, false);
                                                SelectedNode.SelectedSubItem = sourceItem;

                                            } else { // Select
                                                SelectedNode.SelectedSubItem = nextItem;

                                                if (ClickEvent != null) {
                                                    ClickEvent(SelectedNode);
                                                }
                                            }
                                        }
                                    }
                                }

                                LayoutChanged();
                            }

                            break;
                    }

                    break;

                default:
                    base.OnKeyUp(e);
                    break;
            }
        }
Beispiel #48
0
        /// <summary>
        /// Handles when the mouse is moved.
        /// </summary>
        protected override void OnMouseMove(MouseEventArgs e) {
            if (_lostFocus) {
                _lostFocus = false;

                // update the last ouse position
                _lastMousePosition = e.Location;

                base.OnMouseMove(e);

                return;
            }

            // returns the mouse under the mouse cursor
            NodeViewData nodeFound = _rootNodeView.GetInsideNode(e.Location);
            NodeViewData.SubItem subItemFound = null;

            if (nodeFound != null) {
                subItemFound = nodeFound.GetSubItem(nodeFound, _nodeLayoutManager.ViewToGraph(e.Location));

            } else {
                this.toolTip.Hide(this);
            }

            // clear previously stored node which can cause problems when dragging to another view
            //_dragTargetNode = null;

            if (nodeFound != null || _currentExpandNode != null || subItemFound != null) {
                if (_dragAttachment == null) {
                    _currentNode = nodeFound;
                }

                if (Settings.Default.ShowNodeToolTips) {
                    if (nodeFound != null) {
                        _nodeToolTip = (subItemFound != null) ? subItemFound.ToolTip : nodeFound.ToolTip;
                    }

                    if (!string.IsNullOrEmpty(_nodeToolTip)) {
                        this.toolTipTimer.Start();
                    }
                }

                Invalidate();
            }

            // check if we are currently dragging the graph
            if ((e.Button == MouseButtons.Middle || (e.Button == MouseButtons.Left && _objectDragType == ObjectDragTypes.kGraph)) && _lastMousePosition != e.Location && !this.contextMenu.Visible) {
                Cursor = Cursors.SizeAll;

                // move the graph according to the last mouse position
                _nodeLayoutManager.Offset = new PointF(_nodeLayoutManager.Offset.X - (_lastMousePosition.X - e.X), _nodeLayoutManager.Offset.Y - (_lastMousePosition.Y - e.Y));

                Invalidate();
            }

            // check if we start duplicating an existing node step 1
            else if (e.Button == MouseButtons.Left && KeyCtrlIsDown && _lastMousePosition != e.Location && _dragNodeDefaults == null && _copiedNode == null && _currentNode != null && !(_currentNode.Node is BehaviorNode)) {
                if (_objectDragType == ObjectDragTypes.kNode) { // node
                    _movedNode = null;
                    _copiedNode = _currentNode.Node;

                    // create the layout manager used to draw the graph
                    _movedNodeGraph = new NodeLayoutManager(_copiedNode.CloneBranch().CreateNodeViewData(null, _rootNodeView.RootBehavior), _nodeLayoutManager.EdgePen, _nodeLayoutManager.EdgePenSelected, _nodeLayoutManager.EdgePenHighlighted, _nodeLayoutManager.EdgePenUpdate, _nodeLayoutManager.EdgePenReadOnly, true);
                    _movedNodeGraph.Scale = 0.3f;
                    _movedNodeGraph.RenderDepth = KeyShiftIsDown ? int.MaxValue : 0;

                    // use the existing node as the node defaults
                    _dragNodeDefaults = _copiedNode;

                } else if (_objectDragType == ObjectDragTypes.kAttachment) { // attachment
                    if (_dragAttachment == null) {
                        NodeViewData.SubItem subItem = _currentNode.GetSubItem(_currentNode, _nodeLayoutManager.ViewToGraph(e.Location));
                        _dragAttachment = subItem as NodeViewData.SubItemAttachment;
                    }
                }

                Invalidate();
            }

            // check if we are duplicating an existing node step 2
            else if (e.Button == MouseButtons.Left && KeyCtrlIsDown && (_copiedNode != null || _dragAttachment != null)) {
                if (_objectDragType == ObjectDragTypes.kNode) { // node
                    _movedNodeGraph.RenderDepth = KeyShiftIsDown ? int.MaxValue : 0;

                    _dragTargetNode = _currentNode;

                    Cursor = _currentNode == null ? Cursors.No : Cursors.Default;

                    //Point movedGraphGraphPos= new Point(e.Location.X + _movedNodeGraph.Offset.X, e.Location.Y + _movedNodeGraph.Offset.Y /-2);
                    //_movedNodeGraph.Location= movedGraphGraphPos;

                } else if (_objectDragType == ObjectDragTypes.kAttachment) { // attachment
                    _dragTargetNode = nodeFound;

                    if (_dragTargetNode != null) {
                        NodeViewData.SubItem subItem = _dragTargetNode.GetSubItem(_dragTargetNode, _nodeLayoutManager.ViewToGraph(e.Location));
                        _dragTargetAttachment = subItem as NodeViewData.SubItemAttachment;
                    }
                }

                Invalidate();
            }

            // check if we start dragging an existing node step 1
            else if (e.Button == MouseButtons.Left && _lastMousePosition != e.Location && !KeyCtrlIsDown && _movedNode == null && _currentNode != null) {
                if (_objectDragType == ObjectDragTypes.kNode) { // node
                    if (_currentNode.CanBeDragged())
                    {
                        if (_currentNode.IsFSM)
                        {
                            PointF currentGraphMousePos = _nodeLayoutManager.ViewToGraph(e.Location);
                            PointF lastGraphMousePos = _nodeLayoutManager.ViewToGraph(_lastMousePosition);

                            _currentNode.ScreenLocation = new PointF(_currentNode.ScreenLocation.X + currentGraphMousePos.X - lastGraphMousePos.X,
                                                                     _currentNode.ScreenLocation.Y + currentGraphMousePos.Y - lastGraphMousePos.Y);

                            LayoutChanged();

                        }
                        else if ((KeyShiftIsDown || _currentNode.Node.ParentCanAdoptChildren))
                        {
                            _movedNode = _currentNode.Node;

                            // create the layout manager used to draw the graph
                            if (_movedNodeGraph == null)
                            {
                                _movedNodeGraph = new NodeLayoutManager(_movedNode.CloneBranch().CreateNodeViewData(null, _rootNodeView.RootBehavior), _nodeLayoutManager.EdgePen, _nodeLayoutManager.EdgePenSelected, _nodeLayoutManager.EdgePenHighlighted, _nodeLayoutManager.EdgePenUpdate, _nodeLayoutManager.EdgePenReadOnly, true);
                            }

                            _movedNodeGraph.Scale = 0.3f;
                            //_movedNodeGraph.RenderDepth = KeyShiftIsDown ? int.MaxValue : 0;
                            _movedNodeGraph.RenderDepth = int.MaxValue;
                        }
                    }

                } else if (_objectDragType == ObjectDragTypes.kAttachment) { // attachment
                    if (_fsmDragMode == FSMDragModes.kNone && Plugin.EditMode == EditModes.Design) {
                        _movedNodeGraph = null;
                        _dragTargetNode = nodeFound;

                        if (_dragAttachment == null) {
                            NodeViewData.SubItem subItem = _currentNode.GetSubItem(_currentNode, _nodeLayoutManager.ViewToGraph(e.Location));
                            _dragAttachment = subItem as NodeViewData.SubItemAttachment;

                            if (_dragAttachment != null) {
                                _movedSubItem = _dragAttachment.Clone(_currentNode.Node);
                            }

                        } else if (_dragTargetNode != null) {
                            NodeViewData.SubItem subItem = _dragTargetNode.GetSubItem(_dragTargetNode, _nodeLayoutManager.ViewToGraph(e.Location));
                            _dragTargetAttachment = subItem as NodeViewData.SubItemAttachment;
                        }
                    }
                }

                Invalidate();
            }

            // check if we start dragging an existing node step 2
            else if (e.Button == MouseButtons.Left && _movedNode != null && !_clipboardPasteMode) {
                // create the layout manager used to draw the graph
                if (_movedNodeGraph == null) {
                    _movedNodeGraph = new NodeLayoutManager(_movedNode.CloneBranch().CreateNodeViewData(null, _rootNodeView.RootBehavior), _nodeLayoutManager.EdgePen, _nodeLayoutManager.EdgePenSelected, _nodeLayoutManager.EdgePenHighlighted, _nodeLayoutManager.EdgePenUpdate, _nodeLayoutManager.EdgePenReadOnly, true);
                }

                _movedNodeGraph.Scale = 0.3f;
                _movedNodeGraph.RenderDepth = KeyShiftIsDown ? int.MaxValue : 0;

                _dragNodeDefaults = _movedNode;
                _dragTargetNode = _currentNode;

                Cursor = _currentNode == null ? Cursors.No : Cursors.Default;

                Invalidate();

            } else if (_clipboardPasteMode) {
                if (_movedNodeGraph != null) {
                    //_movedNodeGraph.RenderDepth = KeyShiftIsDown ? int.MaxValue : 0;
                    _movedNodeGraph.RenderDepth = int.MaxValue;
                }

                _dragTargetNode = _currentNode;

                Cursor = _currentNode == null ? Cursors.No : Cursors.Default;

                Invalidate();

            } else if (_currentNode != null && _dragAttachment == null) {
                // Highlight the expand/collapse flag
                PointF graphMousePos = _nodeLayoutManager.ViewToGraph(e.Location);
                bool isInExandRange = _currentNode.IsInExpandRange(graphMousePos);
                bool isInExandConnectorRange = _currentNode.IsInExpandConnectorRange(graphMousePos);

                if (isInExandRange || isInExandConnectorRange) {
                    _currentExpandNode = _currentNode;
                    _nodeToolTip = isInExandRange ? Resources.ExpandAllInfo : Resources.ExpandConnectorInfo;
                    Invalidate();

                } else if (_currentExpandNode != null) {
                    _currentExpandNode = null;
                    Invalidate();
                }
            }

            // update the last ouse position
            _lastMousePosition = e.Location;

            base.OnMouseMove(e);
        }
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (type != typeof(string))
            { throw new Exception(Resources.ExceptionDesignerAttributeInvalidType); }

            return str;
        }
Beispiel #50
0
 public override bool AcceptsAttachment(DefaultObject obj)
 {
     return false;
 }
        public static VariableDef setParameter(List<Nodes.Node.ErrorCheck> result, DefaultObject node, string propertyName)
        {
            Nodes.Behavior behavior = node.Behavior as Nodes.Behavior;

            // Convert the Par to the Property
            if (!propertyName.Contains(".") && !propertyName.Contains(":"))
            { propertyName = "Self." + behavior.AgentType.AgentTypeName + "::" + propertyName; }

            VariableDef var = null;
            string instance = Plugin.GetInstanceName(propertyName);

            if (!string.IsNullOrEmpty(instance)) {
                propertyName = propertyName.Substring(instance.Length + 1, propertyName.Length - instance.Length - 1);

                var = createVariable(result, node, behavior.AgentType, instance, propertyName);

                if (var != null) {
                    return var;
                }
            }

            // Try to find the Agent property with the name.
            if (behavior != null && behavior.AgentType != null) {
                instance = "Self";
                var = createVariable(result, node, behavior.AgentType, instance, propertyName);

                if (var != null) {
                    return var;
                }
            }

            // Try to find the global property with the name.
            string instacneName = Plugin.GetClassName(propertyName);

            if (!string.IsNullOrEmpty(instacneName) && Plugin.GetInstanceAgentType(instacneName, behavior, null) != null) {
                var = createVariable(result, node, behavior.AgentType, instacneName, propertyName);

                if (var != null) {
                    return var;
                }
            }

            return null;
        }
Beispiel #52
0
        /// <summary>
        /// Handles when dropping a tree node on the view.
        /// </summary>
        private void BehaviorTreeView_DragDrop(object sender, DragEventArgs e) {
            // make sure the view is focused
            Focus();

            // drag the property or method into the node
            string dragItem = (string)e.Data.GetData(DataFormats.Text);

            if (!string.IsNullOrEmpty(dragItem) && _dragTargetNode != null && _dragTargetNode.Node != null) {
                if (_dragTargetNode.Node.SetDefaultPropertyByDragAndDrop(dragItem)) {
                    if (ClickNode != null) {
                        ClickNode(_dragTargetNode);
                    }

                    UndoManager.Save(this.RootNode);

                    LayoutChanged();
                }

                return;
            }

            // get source node
            TreeNode sourceNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

            if (sourceNode == null) {
                return;
            }

            NodeTag sourceNodeTag = (NodeTag)sourceNode.Tag;

            // keep the current node position
            //KeepNodePosition(_dragTargetNode);

            bool bDragBTOverNode = !((Node)this.RootNode).IsFSM && sourceNodeTag.Type == NodeTagType.Behavior && _dragTargetNode is Behaviac.Design.NodeViewData;

            // check if we are dropping an attach
            // or if we are dropping a bt to a node and the indicator is not left/right/up/bottom/center
            if (_dragAttachMode == NodeAttachMode.Attachment ||
                (bDragBTOverNode && (_dragAttachMode == NodeAttachMode.None || _dragAttachMode == NodeAttachMode.Attachment))) {
                Attachments.Attachment attach = null;

                // when we attach a behaviour we must create a special referenced behaviour node
                if (bDragBTOverNode) {
                    //drag an event(a bt) to a node
                    if (!File.Exists(sourceNodeTag.Filename))
                    {
                        MainWindow.Instance.SaveBehavior(sourceNodeTag.Defaults as Nodes.BehaviorNode, false);
                    }

                    if (File.Exists(sourceNodeTag.Filename)) {
                        // get the behavior we want to reference
                        BehaviorNode behavior = _behaviorTreeList.LoadBehavior(sourceNodeTag.Filename);
                        Behavior rootB = _rootNodeView.RootBehavior as Behavior;
                        Behavior b = behavior as Behavior;

                        if (!b.CanBeAttached || !IsCompatibleAgentType(rootB, b))
                            return;

                        attach = Behaviac.Design.Attachments.Attachment.Create(typeof(Behaviac.Design.Attachments.Event), _dragTargetNode.Node);
                        Behaviac.Design.Attachments.Event evt = (Behaviac.Design.Attachments.Event)attach;
                        evt.ReferencedBehavior = behavior;
                    }

                } else if (_dragTargetNode != null) {
                    Debug.Check(_dragAttachMode == NodeAttachMode.Attachment);

                    // add the attach to the target node
                    attach = Behaviac.Design.Attachments.Attachment.Create(sourceNodeTag.NodeType, _dragTargetNode.Node);
                }

                if (_dragTargetNode != null && attach != null && _dragTargetNode.Node.AcceptsAttachment(attach))
                {
                    attach.OnPropertyValueChanged(false);

                    attach.ResetId();
                    _dragTargetNode.Node.AddAttachment(attach);

                    NodeViewData.SubItemAttachment sub = attach.CreateSubItem();
                    _dragTargetNode.AddSubItem(sub);

                    SelectedNode = _dragTargetNode;
                    SelectedNode.SelectedSubItem = sub;

                    // call the ClickEvent event handler
                    if (ClickEvent != null) {
                        ClickEvent(SelectedNode);
                    }

                    UndoManager.Save(this.RootNode);

                    LayoutChanged();
                }
            }

            //else if (_dragAttachMode != NodeAttachMode.None)
            else {
                // attach a new node to the target node
                InsertNewNode(_dragTargetNode, _dragAttachMode, sourceNodeTag, this.PointToClient(new Point(e.X, e.Y)));
            }

            // reset drag stuff
            _dragTargetNode = null;
            _dragNodeDefaults = null;
            _dragAttachMode = NodeAttachMode.None;

            Invalidate();
        }
Beispiel #53
0
        public static bool parseParam(List<Nodes.Node.ErrorCheck> result, DefaultObject node, MethodDef method, MethodDef.Param par, string param)
        {
            string propName = null;

            if (param[0] == '\"')
            {
                param = param.Substring(1, param.Length - 2);
            }
            else if (param[0] == '{') //struct
            {
                //to set it as action.Method is used in the following parsing
                Nodes.Action action = node as Nodes.Action;

                if (action != null)
                {
                    action.Method = method;
                }
            }
            else
            {
                string noStaticParam = param.Replace("static ", "");
                int index = noStaticParam.IndexOf(" ");
                if (index >= 0)
                    propName = noStaticParam.Substring(index + 1);
            }

            bool bOk = false;

            if (propName != null)
            {
                VariableDef var = setParameter(result, node, propName);

                if (var != null)
                {
                    par.Value = var;
                    bOk = true;
                }
            }
            else
            {
                bOk = Plugin.InvokeTypeParser(result, par.Type, param, 
                    (object value) => par.Value = value, 
                    node, par.Name);
            }

            return bOk;
        }
Beispiel #54
0
        /// <summary>
        /// Handles when a tree node is dragged into the view.
        /// </summary>
        private void BehaviorTreeView_DragEnter(object sender, DragEventArgs e) {
            TreeNode sourceNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

            if (sourceNode != null) {
                NodeTag sourceNodeTag = sourceNode.Tag as NodeTag;

                if (sourceNodeTag == null) {
                    return;
                }

                // store the tree node's defaults
                _dragNodeDefaults = sourceNodeTag.Defaults;
            }
        }
Beispiel #55
0
        public override object FromStringValue(List<Nodes.Node.ErrorCheck> result, DefaultObject node, object parentObject, Type type, string str)
        {
            if (!Plugin.IsIntergerNumberType(type))
                throw new Exception(Resources.ExceptionDesignerAttributeInvalidType);

            int resultValue = 0;

            if (int.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out resultValue))
                return resultValue;

            throw new Exception(string.Format(Resources.ExceptionDesignerAttributeIllegalIntegerValue, str));
        }
Beispiel #56
0
        /// <summary>
        /// Used to replace the default object with a behaviour once loaded.
        /// </summary>
        /// <param name="behavior">The behaviour we have loaded.</param>
        public void AssignLoadedBehavior(BehaviorNode behavior)
        {
            Debug.Check(_type ==NodeTagType.Behavior);
            Debug.Check(_filename ==behavior.FileManager.Filename);

            _defaults= (DefaultObject)behavior;
        }
        protected static VariableDef setProperty(List<Nodes.Node.ErrorCheck> result, DefaultObject node, AgentType agentType, string propertyName, string arrayIndexStr, string valueType)
        {
            if (agentType != null)
            {
                IList<PropertyDef> properties = agentType.GetProperties();
                foreach (PropertyDef p in properties)
                {
                    if (p.Name == propertyName
#if BEHAVIAC_NAMESPACE_FIX
                        || p.Name.EndsWith(propertyName)
#endif
                        )
                    {
                        PropertyDef prop = p.Clone();
                        prop.Owner = valueType;

                        VariableDef v = new VariableDef(prop, valueType);

                        if (v != null && !string.IsNullOrEmpty(arrayIndexStr))
                        {
                            v.ArrayIndexElement = new MethodDef.Param("ArrayIndex", typeof(int), "int", "ArrayIndex", "ArrayIndex");
                            v.ArrayIndexElement.IsArrayIndex = true;
                            DesignerMethodEnum.parseParam(result, node, null, v.ArrayIndexElement, arrayIndexStr);
                        }

                        return v;
                    }
                }
            }

            return null;
        }
Beispiel #58
0
        /// <summary>
        /// Creates a new NodeTag and an instance of the node for the defaults.
        /// </summary>
        /// <param name="type">The type of the node in the node explorer.</param>
        /// <param name="nodetype">The type of the node which will be added to the behaviour tree.</param>
        /// <param name="filename">The filename of the behaviour we want to load. Use string.Empty if the node is not a behaviour.</param>
        public NodeTag(NodeTagType type, Type nodetype, string filename)
        {
            if((type ==NodeTagType.BehaviorFolder || type ==NodeTagType.NodeFolder) && nodetype !=null)
                throw new Exception(Resources.ExceptionWrongNodeTagType);

            _type= type;
            _nodetype= nodetype;
            _filename= filename;

            if(nodetype ==null)
            {
                _defaults= null;
            }
            else
            {
                //if(!nodetype.IsSubclassOf(typeof(DefaultObject)))
                //	throw new Exception(Resources.ExceptionNotImplementDefaultObject);

                if(nodetype.IsSubclassOf(typeof(Events.Event)) && type !=NodeTagType.Event)
                    throw new Exception(Resources.ExceptionWrongNodeTagType);

                if(nodetype.IsSubclassOf(typeof(Nodes.Node)) && type !=NodeTagType.Node && type !=NodeTagType.Behavior)
                    throw new Exception(Resources.ExceptionWrongNodeTagType);

                _defaults=type ==NodeTagType.Event ? (DefaultObject)Brainiac.Design.Events.Event.Create(nodetype, null) : (DefaultObject)Nodes.Node.Create(nodetype);
            }
        }
        /// <summary>
        /// Parse the string value to create an object.
        /// </summary>
        /// <param name="type">The type of the created object.</param>
        /// <param name="str">The string value of the created object.</param>
        /// <param name="node">The owner node of the created object.</param>
        /// <returns>Returns the created object.</returns>
        public static object ParseStringValue(List<Nodes.Node.ErrorCheck> result, Type type, string str, DefaultObject node)
        {
            object obj = null;
            Plugin.InvokeTypeParser(result, type, str, (object value) => obj = value, node);

            return obj;
        }
Beispiel #60
0
        public static object ParseStringValue(List<Nodes.Node.ErrorCheck> result, Type type, string str, DefaultObject node)
        {
            Debug.Check(Plugin.IsArrayType(type));

            Type itemType = type.GetGenericArguments()[0];

            if (Plugin.IsCustomClassType(itemType))
            { return DesignerArrayStruct.ParseStringValue(result, type, str, node); }

            object obj = Plugin.CreateInstance(type);
            Debug.Check(obj != null);

            if (!string.IsNullOrEmpty(str)) {
                System.Collections.IList list = (System.Collections.IList)obj;

                int index = str.IndexOf(':');

                if (index >= 0)
                { str = str.Substring(index + 1); }

                if (!string.IsNullOrEmpty(str)) {
                    string[] tokens = str.Split('|');
                    foreach(string s in tokens) {
                        if (!string.IsNullOrEmpty(s))
                        {
                            Plugin.InvokeTypeParser(result, itemType, s, (object value) => { list.Add(value); }, node);
                        }
                    }
                }
            }

            return obj;
        }