Example #1
0
 public void StructTest()
 {
     Guid id = Guid.NewGuid();
     StructValue s = StructValue.Create(id, "Name1");
     StructValue s1 = new StructValue().PopulateWith(s);
     Assert.AreEqual(Guid.Empty, s1.Id);
     Assert.AreEqual(null, s1.Name);
     var nameProperty = s1.GetType().GetProperty("Name");
     nameProperty.SetValue(s1, "Name1");
     Assert.AreEqual(null, s1.Name);
     s1.Name = "Name1";
     Assert.AreEqual("Name1", s1.Name);
 }
Example #2
0
        public override Object ImportValue(StructValue sv)
        {
            //      Dictionary<object,object> map = new Dictionary<object,object>();
            Hashtable map = new Hashtable();

            Object[] keysAndValues = ( Object[] )sv.Get(field);
            int      n             = keysAndValues.Length;
            int      index         = 0;

            while (index < n)
            {
                object key   = ( object )keysAndValues[index++];
                object value = ( object )keysAndValues[index++];
                map.Add(key, value);
            }

            return(map);
        }
        public void test_S2_import()
        {
            StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S2, vf);

            sv.Add(ValueFactoryTest1._mf_a, new S1(21, 22, 23));
            sv.Add(ValueFactoryTest1._mf_b, new S1(31, 32, 33));
            sv.Add(ValueFactoryTest1._mf_c, E1.A);

            S2 s = ( S2 )vf.ImportCustomValue(sv);

            Assert.AreEqual(21, s.a.x);
            Assert.AreEqual(22, s.a.y);
            Assert.AreEqual(23, s.a.z);
            Assert.AreEqual(31, s.b.x);
            Assert.AreEqual(32, s.b.y);
            Assert.AreEqual(33, s.b.z);
            Assert.AreEqual(E1.A, s.c);
        }
Example #4
0
        private void TestDate(DateTime date)
        {
            XType type = new XType("date");

            Class2TypeMap class2type =
                new Class2TypeMap();

            DateSerializer.Init(type, class2type);

            ImportExportHelper helper = type.GetImportExportHelper();
            StructValue        sv     = helper.ExportValue(vf, date);

            Assert.AreEqual(sv.GetXType, type);

            DateTime date2 = ( DateTime )helper.ImportValue(sv);

            Assert.AreEqual(date, date2);
        }
Example #5
0
        public override StructValue ExportValue(ValueFactory vf, Object value)
        {
            //       List<object> list = (List<object>)value;
            ArrayList list = (ArrayList)value;

            Object[] values = new Object[list.Count];
            int      index  = 0;

            foreach (object me in list)
            {
                values[index++] = me;
            }

            StructValue sv = new StructValue(type, vf);

            sv.Add(field, values);
            return(sv);
        }
Example #6
0
        public override StructValue ExportValue(ValueFactory vf, Object value)
        {
            StrStrHashMap map = ( StrStrHashMap )value;

            Object[] keysAndValues = new Object[map.Count * 2];
            int      index         = 0;

            foreach (KeyValuePair <String, String> me in map)
            {
                keysAndValues[index++] = me.Key;
                keysAndValues[index++] = me.Value;
            }

            StructValue sv = new StructValue(type, vf);

            sv.Add(field, keysAndValues);
            return(sv);
        }
Example #7
0
        public void TestNegativePlan1()
        {
            var planner    = GetPlanner();
            var gameObject = new GameObject();

            ReGoapTestsHelper.GetCustomAction(gameObject, "CollectRes",
                                              new Dictionary <string, object> {
            },
                                              new Dictionary <string, object> {
                { "NFloatRisk", 10f }, { "IntGold", 10 }
            },
                                              3);
            ReGoapTestsHelper.GetCustomAction(gameObject, "ReduceRisk",
                                              new Dictionary <string, object> {
                { "IntGold", -10 }
            },
                                              new Dictionary <string, object> {
                { "NFloatRisk", -20f }, { "IntGold", -10 }
            },
                                              5);

            var goal = ReGoapTestsHelper.GetCustomGoal(gameObject, "GetGold",
                                                       new Dictionary <string, object> {
                { "NFloatRisk", 10f }
            });

            var memory = gameObject.AddComponent <ReGoapTestMemory>();

            memory.Init();
            memory.SetStructValue("NFloatRisk", StructValue.CreateFloatArithmetic(50f));
            memory.SetStructValue("IntGold", StructValue.CreateFloatArithmetic(10));

            var agent = gameObject.AddComponent <ReGoapTestAgent>();

            agent.Init();
            agent.debugPlan = true;

            var plan = planner.Plan(agent, null, null, null);

            Assert.That(plan, Is.EqualTo(goal));
            Assert.That(plan.GetPlan().Count, Is.EqualTo(5));
            // validate plan actions
            ReGoapTestsHelper.ApplyAndValidatePlan(plan, memory);
        }
Example #8
0
        public void MergeFrom(Value other)
        {
            if (other == null)
            {
                return;
            }
            switch (other.KindCase)
            {
            case KindOneofCase.NullValue:
                NullValue = other.NullValue;
                break;

            case KindOneofCase.NumberValue:
                NumberValue = other.NumberValue;
                break;

            case KindOneofCase.StringValue:
                StringValue = other.StringValue;
                break;

            case KindOneofCase.BoolValue:
                BoolValue = other.BoolValue;
                break;

            case KindOneofCase.StructValue:
                if (StructValue == null)
                {
                    StructValue = new global::Google.Protobuf.WellKnownTypes.Struct();
                }
                StructValue.MergeFrom(other.StructValue);
                break;

            case KindOneofCase.ListValue:
                if (ListValue == null)
                {
                    ListValue = new global::Google.Protobuf.WellKnownTypes.ListValue();
                }
                ListValue.MergeFrom(other.ListValue);
                break;
            }

            _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
        }
Example #9
0
        public void TestPlan3()
        {
            var planner    = GetPlanner();
            var gameObject = new GameObject();

            ReGoapTestsHelper.GetCustomAction(gameObject, "BuyFood",
                                              new Dictionary <string, object> {
                { "IntGold", 5 }
            },
                                              new Dictionary <string, object> {
                { "IntGold", -5 }, { "IntFood", 2 }
            },
                                              3);
            ReGoapTestsHelper.GetCustomAction(gameObject, "GoMine",
                                              new Dictionary <string, object> {
                { "IntFood", 2 }
            },
                                              new Dictionary <string, object> {
                { "IntFood", -2 }, { "IntGold", 20 }
            },
                                              5);

            var miningGoal = ReGoapTestsHelper.GetCustomGoal(gameObject, "Mine",
                                                             new Dictionary <string, object> {
                { "IntGold", 40 }
            });

            var memory = gameObject.AddComponent <ReGoapTestMemory>();

            memory.Init();
            memory.SetStructValue("IntGold", StructValue.CreateIntArithmetic(20));
            memory.SetStructValue("IntFood", StructValue.CreateIntArithmetic(20));

            var agent = gameObject.AddComponent <ReGoapTestAgent>();

            agent.Init();

            var plan = planner.Plan(agent, null, null, null);

            Assert.That(plan, Is.EqualTo(miningGoal));
            // validate plan actions
            ReGoapTestsHelper.ApplyAndValidatePlan(plan, memory);
        }
Example #10
0
        protected override void VisitNewArray(NewArray downNode, object o)
        {
            PointerToNode        ptrUpNode = (o as Data).PointerToNode;
            StructValue          idx       = this.state.Stack.Pop() as StructValue;
            Array                arr       = Array.CreateInstance(downNode.Type, SpecializingVisitor.toInt(idx));
            ObjectReferenceValue obj       = new ObjectReferenceValue(arr);

            if (Annotation.GetArrayElementsBTType(downNode) == BTType.Dynamic)
            {
                for (int i = 0; i < SpecializingVisitor.toInt(idx); i++)
                {
                    Variable varUp = this.mbbUp.Variables.CreateVar(downNode.Type, VariableKind.Local);
                    this.varsHash[new PointerToElementValue(arr, i)] = varUp;
                    ptrUpNode = SpecializingVisitor.initVariable(varUp, ptrUpNode);
                }
            }

            this.state.Stack.Push(obj);
            this.AddTask(downNode.Next, ptrUpNode);
        }
        private StructValue ConvertObjectToStructValue(object data)
        {
            if (!data.GetType().IsClass)
            {
                throw new InvalidOperationException($"Value of type '{data.GetType().Name}' cannot be converted");
            }

            var structValue = new StructValue();

            var properties = data.GetType().GetProperties();

            var memberProperties = from property in properties
                                   let memberAttribute = property.GetCustomAttribute <XmlRpcStructMemberAttribute>()
                                                         where memberAttribute != null
                                                         select(property, memberAttribute);

            memberProperties.ForEach(v => SetMemberValue(data, v.property, v.memberAttribute, structValue));

            return(structValue);
        }
Example #12
0
        public override StructValue ExportValue(ValueFactory vf, Object value)
        {
            //     Dictionary<object, object> map = (Dictionary<object, object>)value;

            Hashtable map = (Hashtable)value;

            Object[] keysAndValues = new Object[map.Count * 2];
            int      index         = 0;

            foreach (DictionaryEntry me in map)
            {
                keysAndValues[index++] = me.Key;
                keysAndValues[index++] = me.Value;
            }

            StructValue sv = new StructValue(type, vf);

            sv.Add(field, keysAndValues);
            return(sv);
        }
Example #13
0
        public void TestReGoapStateAddOperator()
        {
            var state = ReGoapState <string, object> .Instantiate();

            state.Set("var0", true);
            state.SetStructValue("var1", StructValue.CreateIntArithmetic(10));
            state.SetStructValue("var2", StructValue.CreateFloatArithmetic(100f));
            var otherState = ReGoapState <string, object> .Instantiate();

            otherState.SetStructValue("var1", StructValue.CreateIntArithmetic(20)); // 2nd one replaces the first
            otherState.SetStructValue("var2", StructValue.CreateFloatArithmetic(-20f));
            otherState.Set("var3", 10.1f);
            Assert.That(state.Count, Is.EqualTo(3));
            state.AddFromState(otherState);
            Assert.That(otherState.Count, Is.EqualTo(3));
            Assert.That(state.Count, Is.EqualTo(4));
            Assert.That(state.Get("var0"), Is.EqualTo(true));
            Assert.That(state.Get("var1"), Is.EqualTo(30));
            Assert.That(state.Get("var2"), Is.EqualTo(80f));
            Assert.That(state.Get("var3"), Is.EqualTo(10.1f));
        }
Example #14
0
        public void Convert_DictionaryWithString_ReturnsCorrectValue()
        {
            var converter = new XmlRpcValueToDataConverter();

            var xmlRpcValue = new StructValue(new Dictionary <string, XmlRpcValue>
            {
                { "TestProp1", new StringValue("1234") },
                { "TestProp2", new StringValue("abcd") }
            });

            var value = converter.Convert(xmlRpcValue, typeof(Dictionary <string, string>)) as IDictionary <string, string>;

            Assert.NotNull(value);

            Assert.Equal(2, value.Keys.Count);

            var firstValue  = value["TestProp1"];
            var secondValue = value["TestProp2"];

            Assert.Equal("1234", firstValue);
            Assert.Equal("abcd", secondValue);
        }
        private void SetMemberValue(object obj, PropertyInfo property, XmlRpcStructMemberAttribute memberAttribute,
                                    StructValue xmlRpcStruct)
        {
            var memberName = string.IsNullOrEmpty(memberAttribute.Name)
                ? property.Name
                : memberAttribute.Name;

            var propertyValue = property.GetValue(obj);

            var memberConverter = memberAttribute.GetConverter();

            var value = memberConverter != null
                ? memberConverter.ConvertFromObject(propertyValue)
                : Convert(propertyValue);

            if (value == null)
            {
                return;
            }

            xmlRpcStruct.Value[memberName] = value;
        }
Example #16
0
        private float _CalculateH()
        {
            float h = 0;

            foreach (var pr in goal.GetValues())
            {
                var pairValue = pr.Value;
                if (pairValue.tp == StructValue.EValueType.Other)
                {
                    ++h;
                }
                else if (pairValue.tp == StructValue.EValueType.Arithmetic)
                {
                    float goalValue = Convert.ToSingle(pairValue.v);
                    var   defValue  = StructValue.CopyCreate(ref pairValue, 0);
                    if (!pairValue.IsFulfilledBy(defValue))
                    {
                        h += Math.Abs(goalValue);
                    }
                }
            }
            return(h);
        }
Example #17
0
 private static void _AddIntoReGoapState(ReGoapState <string, object> st, string key, object v)
 {
     if (key.StartsWith("Int"))
     {
         st.SetStructValue(key, StructValue.CreateIntArithmetic((int)v));
     }
     else if (key.StartsWith("Float"))
     {
         st.SetStructValue(key, StructValue.CreateFloatArithmetic((float)v));
     }
     else if (key.StartsWith("NInt"))
     {
         st.SetStructValue(key, StructValue.CreateIntArithmetic((int)v, neg: true));
     }
     else if (key.StartsWith("NFloat"))
     {
         st.SetStructValue(key, StructValue.CreateFloatArithmetic((float)v, neg: true));
     }
     else
     {
         st.Set(key, v);
     }
 }
Example #18
0
        public override void Interpret()
        {
            var structElemento = new StructValue();

            foreach (var elementos in bloqueStruct)
            {
                if (elementos is GeneralDeclarationNode)
                {
                    var elementoDeclaration = (elementos as GeneralDeclarationNode);
                    structElemento.Value.Add(elementoDeclaration.identificador, obtenerTipo(elementoDeclaration.tipo).GetDefaultValue());
                }
                else
                {
                    var elementoDeclaration = (elementos as IdentificadorArrayNode);
                    structElemento.Value.Add((elementoDeclaration.identificador as GeneralDeclarationNode).identificador, obtenerTipo((elementoDeclaration.identificador as GeneralDeclarationNode).tipo).GetDefaultValue());
                }
            }

            if (asignacion != null)
            {
                int i = 0;
                foreach (var elemento in asignacion)
                {
                    if (elemento.Interpret().GetType() == structElemento.Value.ToList()[i].Value.GetType())
                    {
                        structElemento.Value[structElemento.Value.ToList()[i].Key] = elemento.Interpret();
                    }
                    else
                    {
                        throw new Semantico.SemanticoException("el orden de inicializacion no es el correcto en el struct fila" + _TOKEN.Fila + " columna" + _TOKEN.Columna);
                    }
                    i++;
                }
            }
            ContenidoStack.InstanceStack.Stack.Peek()._values.Add(variableNombre, structElemento);
            var stack = ContenidoStack.InstanceStack.Stack;
        }
Example #19
0
        private void ReadKeysAndValues(StructValue sv)
        {
            XType t = sv.GetXType;

            while (true)
            {
                Field key = ReadField(t);
                if (key == null)
                {
                    break;
                }

                //Object obj = ReadValue( intValidator, true );
                //if ( obj == NONE )
                //    break;

                //int id = ( int ) obj;
                //Field key = t.GetField( id );
                //if (key == null)
                //    key = new Field(id, id.ToString());

                Validator v = t.GetValidator(key);
                if (v != null)
                {
                    sv.Add(key, ReadValue(v));
                }
                else
                {
                    // read the value but ignore it.
                    Object obj = ReadValue(Validator_object.Get(0));
                    if (false)
                    {
                        sv.Add(key, obj);
                    }
                }
            }
        }
Example #20
0
        public override Object ImportValue(StructValue sv)
        {
            long ms = (long)sv.Get(field);

            return(new DateTime(epoch + ms * TICKS_PER_MS, DateTimeKind.Utc).ToLocalTime());
        }
Example #21
0
 private void WriteStruct(StructValue sv)
 {
     StartStruct(sv);
     WriteKeysAndValues(sv);
     EndStruct(sv);
 }
Example #22
0
            /**
             * Handle messages from peer.
             * @param sender
             * @param msg
             * @throws Exception
             */
            public void dispatch(Who sender, Message msg)
            {
                Console.WriteLine("msg = " + msg);
                if (msg.IsType(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_CuaeServer_doit))
                {
                    StructValue req = (StructValue)msg.Get(MyValueFactoryCuae._mf_req);
                    MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_Request.CheckIsAssignableFrom(req.GetXType);
                    int?code = (int?)req.Get(MyValueFactoryCuae._mf_code);

                    // String m;
                    StructValue resp;
                    switch (code.GetValueOrDefault())
                    {
                    case 23:
                        resp = new StructValue(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_Response, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "foo");
                        delayDoit2a(7);
                        break;

                    case 19:
                        resp =
                            new StructValue(
                                MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_RespWithCode, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "bar");
                        resp.Add(MyValueFactoryCuae._mf_code, 54);
                        delayDoit2b(11, "heaven");
                        break;

                    case 13:
                        resp = new StructValue(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_Response, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "baz");
                        delayDoit2a(99);
                        break;

                    default:
                        resp =
                            new StructValue(
                                MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_RespWithCode, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, " unknown code " + code);
                        resp.Add(MyValueFactoryCuae._mf_code, 63);
                        delayDoit2b(23, "killer bee");
                        break;
                    }



                    Message rmsg = msg.Reply();
                    Console.WriteLine("rmsg = " + rmsg);
                    Console.WriteLine("resp = " + resp);
                    rmsg.Add(MyValueFactoryCuae._mf_result, resp);
                    svc.TransportMessage(sender, rmsg);
                    return;
                }

                if (msg.IsType(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_CuaeServer_doit3))
                {
                    StructValue[] reqs = (StructValue[])msg.Get(MyValueFactoryCuae._mf_req);
                    StructValue   req  = reqs[0];
                    MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_Request.CheckIsAssignableFrom(
                        req.GetXType);
                    int?code = (int?)req.Get(MyValueFactoryCuae._mf_code);

                    StructValue resp;
                    switch (code.GetValueOrDefault())
                    {
                    case 23:
                        resp =
                            new StructValue(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_Response, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "foo");
                        delayDoit2a(7);
                        break;

                    case 19:
                        resp = new StructValue(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_RespWithCode, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "bar");
                        resp.Add(MyValueFactoryCuae._mf_code, 54);
                        delayDoit2b(11, "heaven");
                        break;

                    case 13:
                        resp =
                            new StructValue(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_Response, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "baz");
                        delayDoit2a(99);
                        break;

                    default:
                        resp = new StructValue(MyValueFactoryCuae._mt_etch_bindings_csharp_examples_cuae_Cuae_RespWithCode, vf);
                        resp.Add(MyValueFactoryCuae._mf_msg, "unknown code " + code);
                        resp.Add(MyValueFactoryCuae._mf_code, 63);
                        delayDoit2b(23, "killer bee");
                        break;
                    }

                    Message rmsg = msg.Reply();
                    Console.WriteLine("rmsg = " + rmsg);
                    Console.WriteLine("resp = " + resp);
                    rmsg.Add(MyValueFactoryCuae._mf_result, new StructValue[] { resp });
                    svc.TransportMessage(sender, rmsg);
                    return;
                }


                throw new Exception("unknown msg type " + msg);
            }
Example #23
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sv"></param>
 /// Exception:
 ///     throws Exception
 private void EndStruct(StructValue sv)
 {
     WriteNoneValue();
 }
Example #24
0
        ///////////////////////////
        // LOCAL UTILITY METHODS //
        ///////////////////////////

        #region Local Utility Methods

        /// <summary>
        ///
        /// </summary>
        /// <param name="v">the validator for this value, or none if there
        /// isn't one</param>
        /// <param name="value"></param>
        /// Exception:
        ///     throws Exception
        private void WriteValue(Validator v, Object value)
        {
            sbyte typeCode = CheckValue(value);

            if (level != Validator.Level.NONE && value != null)
            {
                if (level == Validator.Level.FULL && v == null)
                {
                    throw new ArgumentException("validator missing");
                }

                if (v != null && !v.Validate(value))
                {
                    throw new ArgumentException(String.Format(
                                                    "validator {0} failed for value {1}", v, value));
                }
            }

            buf.PutByte(typeCode);

            switch (typeCode)
            {
            case TypeCode.NULL:
            case TypeCode.BOOLEAN_FALSE:
            case TypeCode.BOOLEAN_TRUE:
            case TypeCode.EMPTY_STRING:
            case TypeCode.NONE:
                return;

            case TypeCode.BYTE:
                buf.PutByte((Convert.ToSByte(value)));
                return;

            case TypeCode.SHORT:
                buf.PutShort(Convert.ToInt16(value));
                return;

            case TypeCode.INT:
                buf.PutInt(Convert.ToInt32(value));
                return;

            case TypeCode.LONG:
                buf.PutLong(Convert.ToInt64(value));
                return;

            case TypeCode.FLOAT:
                buf.PutFloat(Convert.ToSingle(value));
                return;

            case TypeCode.DOUBLE:
                buf.PutDouble(Convert.ToDouble(value));
                return;

            case TypeCode.BYTES:
                WriteBytes((sbyte[])value);
                return;

            // reserved for future use
            //case TypeCode.BOOLS:
            //case TypeCode.SHORTS:
            //case TypeCode.INTS:
            //case TypeCode.LONGS:
            //case TypeCode.FLOATS:
            //case TypeCode.DOUBLES:
            case TypeCode.ARRAY:
                WriteArray(ToArrayValue(value, v), v);
                return;

            case TypeCode.STRING:
                WriteBytes(Encoding.UTF8.GetBytes((String)value));
                return;

            case TypeCode.CUSTOM:
            {
                StructValue sv = vf.ExportCustomValue(value);
                if (sv == null)
                {
                    throw new Exception("unsupported type " + value.GetType());
                }

                WriteStruct(sv);
                return;
            }

            default:
                // type is either "tiny" integer or unused...
                if (typeCode >= TypeCode.MIN_TINY_INT && typeCode <= TypeCode.MAX_TINY_INT)
                {
                    return;
                }

                throw new Exception("unsupported typecode " + typeCode);
            }
        }
Example #25
0
 public void Visit(StructValue sv)
 {
     var st = sv.Type as StructType;
     Debug.Assert(st != null);
     foreach (var v in sv.Values) {
         v.Accept(this);
     }
     _instructions.Add(Instruction.Create(OpCodes.Newobj, st.Ctor));
 }
Example #26
0
 public object ImportCustomValue(StructValue sv)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Example #27
0
 private void _GetValueType(ref StructValue goalValue, ref StructValue effectValue, ref StructValue precondValue, ref StructValue stateValue,
                            out StructValue.EValueType valueType,
                            out StructValue protoValue)
 {
     if (goalValue.Inited)
     {
         valueType  = goalValue.tp;
         protoValue = goalValue;
     }
     else if (effectValue.Inited)
     {
         valueType  = effectValue.tp;
         protoValue = effectValue;
     }
     else if (precondValue.Inited)
     {
         valueType  = precondValue.tp;
         protoValue = precondValue;
     }
     else if (stateValue.Inited)
     {
         valueType  = stateValue.tp;
         protoValue = stateValue;
     }
     else
     {
         UnityEngine.Debug.LogError("ReGoapNode._GetValueType: failed to find inited value");
         valueType  = StructValue.EValueType.Other;
         protoValue = StructValue.Create(null);
     }
 }
Example #28
0
        private void Init(IGoapPlanner <T, W> planner, ReGoapState <T, W> newGoal, ReGoapNode <T, W> parent, IReGoapAction <T, W> action)
        {
            expandList.Clear();
            tmpKeys.Clear();

            this.planner = planner;
            this.parent  = parent;
            this.action  = action;
            if (action != null)
            {
                actionSettings = action.GetSettings(planner.GetCurrentAgent(), newGoal);
            }

            if (parent != null)
            {
                state = parent.GetState().Clone();
                // g(node)
                g = parent.GetPathCost();
            }
            else
            {
                state = planner.GetCurrentAgent().GetMemory().GetWorldState().Clone();
            }

            var nextAction = parent == null ? null : parent.action;

            if (action != null)
            {
                // create a new instance of the goal based on the paren't goal
                goal = ReGoapState <T, W> .Instantiate();

                var tmpGoal = ReGoapState <T, W> .Instantiate(newGoal);

                var preconditions = action.GetPreconditions(tmpGoal, nextAction);
                var effects       = action.GetEffects(tmpGoal, nextAction);
                // adding the action's effects to the current node's state
                state.AddFromState(effects);
                // addding the action's cost to the node's total cost
                g += action.GetCost(tmpGoal, nextAction);

                //// add all preconditions of the current action to the goal
                //tmpGoal.AddFromState(preconditions);
                //// removes from goal all the conditions that are now fulfilled in the node's state
                //tmpGoal.ReplaceWithMissingDifference(state);
                ////goal.ReplaceWithMissingDifference(effects);

                // collect all keys from goal & precondition, unique-ed
                foreach (var pr in tmpGoal.GetValues())
                {
                    var k = pr.Key;
                    if (!tmpKeys.Contains(k))
                    {
                        tmpKeys.Add(k);
                    }
                }
                foreach (var pr in preconditions.GetValues())
                {
                    var k = pr.Key;
                    if (!tmpKeys.Contains(k))
                    {
                        tmpKeys.Add(k);
                    }
                }

                // process each keys
                foreach (var k in tmpKeys)
                {
                    StructValue goalValue, effectValue, precondValue, stateValue, protoValue;
                    tmpGoal.GetValues().TryGetValue(k, out goalValue);
                    effects.GetValues().TryGetValue(k, out effectValue);
                    preconditions.GetValues().TryGetValue(k, out precondValue);
                    state.GetValues().TryGetValue(k, out stateValue);

                    StructValue.EValueType valueType;
                    _GetValueType(ref goalValue, ref effectValue, ref precondValue, ref stateValue, out valueType, out protoValue);
                    if (valueType == StructValue.EValueType.Arithmetic)
                    {
                        //_EnsureArithStructValueInited(ref goalValue, ref protoValue);
                        _EnsureArithStructValueInited(ref effectValue, ref protoValue);
                        _EnsureArithStructValueInited(ref precondValue, ref protoValue);
                        _EnsureArithStructValueInited(ref stateValue, ref protoValue);
                        if (!goalValue.Inited)
                        {
                            goalValue = StructValue.CopyCreate(ref stateValue, -(Convert.ToSingle(stateValue.v) - Convert.ToSingle(effectValue.v)));
                        }

                        float fGoal    = Convert.ToSingle(goalValue.v);
                        float fEffect  = Convert.ToSingle(effectValue.v);
                        float fPrecond = Convert.ToSingle(precondValue.v);
                        float fState   = Convert.ToSingle(stateValue.v);

                        float finalV = Math.Max(
                            fGoal - fEffect,
                            Math.Min(fPrecond, fPrecond - fState)
                            );

                        var sv = StructValue.CopyCreate(ref protoValue, finalV);

                        goal.SetStructValue(k, sv);
                    }
                    else if (valueType == StructValue.EValueType.Other)
                    {
                        //ReplaceWithMissingDifference
                        if (stateValue.Inited && goalValue.Inited && goalValue.IsFulfilledBy(stateValue))
                        {
                            goalValue.Invalidate();
                        }

                        // AddFromPrecond
                        // 1. if the precond is satisfied by the memory start state, then discard
                        // 2. else this newly added goal from precond, should not be removed due to fulfilled by curStateValue
                        if (precondValue.Inited)
                        {
                            bool        preCondfulfilledByMem = false;
                            var         startMemoryState      = planner.GetCurrentAgent().GetMemory().GetWorldState();
                            StructValue startMemoryValue;
                            if (startMemoryState.GetValues().TryGetValue(k, out startMemoryValue))
                            {
                                if (startMemoryValue.Inited && precondValue.IsFulfilledBy(startMemoryValue))
                                {
                                    preCondfulfilledByMem = true;
                                }
                            }

                            if (!preCondfulfilledByMem)
                            {
                                if (goalValue.Inited)
                                {
                                    goalValue = goalValue.MergeWith(precondValue);
                                }
                                else
                                {
                                    goalValue = precondValue;
                                }
                            }
                        }

                        if (goalValue.Inited)
                        {
                            goal.SetStructValue(k, goalValue);
                        }
                    }
                    else
                    {
                        UnityEngine.Debug.LogError("Unexpected StructValue type: " + valueType);
                    }
                }// foreach (var k in tmpKeys)

                tmpGoal.Recycle();
            }
            else
            {
                var diff = ReGoapState <T, W> .Instantiate();

                newGoal.MissingDifference(state, ref diff);
                goal = diff;
            }

            h = _CalculateH();

            // f(node) = g(node) + h(node)
            cost = g + h * planner.GetSettings().HeuristicMultiplier;
        }
Example #29
0
 public void Visit(StructValue sv)
 {
     _sb.AppendFormat("struct {0} {{", sv.Name);
     int i = 0;
     for (; i < sv.Values.Count - 1; ++i) {
         sv.Values[i].Accept(this);
         _sb.Append(", ");
     }
     sv.Values[i].Accept(this);
     _sb.Append("}");
 }
Example #30
0
        // TODO: RBSONG
        public static RBSong.RBSong MakeRBSong(DataArray array)
        {
            var drumBank = array.Array("drum_bank")?.Any(1)
                           .Replace("sfx", "fusion/patches")
                           .Replace("_bank.milo", ".fusion")
                           ?? "fusion/patches/kit01.fusion";
            var editorComponent = new Component
            {
                ClassName = "Editor",
                Name      = "Editor",
                Unknown1  = 3,
                Unknown2  = 2,
                Props     = new[]
                {
                    new Property("capabilities", new FlagValue(50))
                }
            };
            var vec3     = StructType.FromData(DTX.FromDtaString("define vec3 (props (x float) (y float) (z float))"));
            var xfm_type = StructType.FromData(DTX.FromDtaString(
                                                   @"define xfm
            (props
              (basis_x vec3)
              (basis_y vec3)
              (basis_z vec3)
              (translate vec3))"));
            var entityHeaderComponent = new Component
            {
                ClassName = "EntityHeader",
                Name      = "EntityHeader",
                Unknown1  = 3,
                Unknown2  = 1,
                Props     = new[]
                {
                    new Property("copy_on_instance", new BoolValue(true)),
                    new Property("drives_parent", new BoolValue(false)),
                    new Property("static", new BoolValue(false)),
                    new Property("instance_polling_mode", new IntValue(0)),
                    new Property("num_instances", new IntValue(0)),
                    new Property("num_meshes", new IntValue(0)),
                    new Property("num_particles", new IntValue(0)),
                    new Property("num_propanims", new IntValue(0)),
                    new Property("num_lights", new IntValue(0)),
                    new Property("num_verts", new IntValue(0)),
                    new Property("num_faces", new IntValue(0)),
                    new Property("changelist", new IntValue(0)),
                    new Property("icon_cam_initialized", new BoolValue(false)),
                    new Property("icon_cam_near", new FloatValue(0.1f)),
                    new Property("icon_cam_far", new FloatValue(1000f)),
                    new Property("icon_cam_xfm", StructValue.FromData(xfm_type, DTX.FromDtaString(
                                                                          @"(basis_x ((x 1.0) (y 0.0) (z 0.0)))
              (basis_y ((x 0.0) (y 1.0) (z 0.0)))
              (basis_z ((x 0.0) (y 0.0) (z 1.0)))
              (translate ((x 0.0) (y 0.0) (z 0.0)))"))),
                    new Property("icon_data",
                                 new ArrayValue(new ArrayType {
                        ElementType = PrimitiveType.Byte, InternalType = RBSong.DataType.Uint8 | RBSong.DataType.Array
                    }, new Value[] { }))
                }
            };

            return(new RBSong.RBSong
            {
                Version = 0xE,
                Object1 = new ObjectContainer
                {
                    Unknown1 = 20,
                    Unknown2 = 1,
                    Unknown3 = 20,
                    Unknown4 = 0,
                    Unknown5 = 1,
                    Entities = new[] {
                        new Entity
                        {
                            Index0 = 0,
                            Index1 = 0,
                            Name = "root",
                            Coms = new Component[] {
                                editorComponent,
                                entityHeaderComponent,
                                new Component
                                {
                                    ClassName = "RBSongMetadata",
                                    Name = "RBSongMetadata",
                                    Unknown1 = 3,
                                    Unknown2 = 4,
                                    Props = new[]
                                    {
                                        new Property("tempo", new SymbolValue("medium")),
                                        new Property("vocal_tonic_note", new LongValue(array.Array("vocal_tonic_note")?.Int(1) ?? 0)),
                                        new Property("vocal_track_scroll_duration_ms", new LongValue(array.Array("song_scroll_speed")?.Int(1) ?? 2300)),
                                        new Property("global_tuning_offset", new FloatValue(array.Array("tuning_offset_cents")?.Number(1) ?? 0)),
                                        new Property("band_fail_sound_event", new SymbolValue("", true)),
                                        new Property("vocal_percussion_patch", new ResourcePathValue("fusion/patches/vox_perc_tambourine.fusion", true)),
                                        new Property("drum_kit_patch", new ResourcePathValue(drumBank)),
                                        new Property("improv_solo_patch", new SymbolValue("gtrsolo_amer_03")),
                                        new Property("dynamic_drum_fill_override", new IntValue(10)),
                                        new Property("improv_solo_volume_db", new FloatValue(-9))
                                    }
                                },
                                new Component
                                {
                                    ClassName = "RBVenueAuthoring",
                                    Name = "RBVenueAuthoring",
                                    Unknown1 = 3,
                                    Unknown2 = 0,
                                    Props = new[]
                                    {
                                        new Property("part2_instrument", new IntValue(2)),
                                        new Property("part3_instrument", new IntValue(0)),
                                        new Property("part4_instrument", new IntValue(1))
                                    }
                                }
                            }
                        }
                    }
                },
                KV = new KeyValue
                {
                    Str1 = "PropAnimResource",
                    Str2 = "venue_authoring_data"
                },
                Object2 = new ObjectContainer
                {
                    Unknown1 = 20,
                    Unknown2 = 1,
                    Unknown3 = 20,
                    Unknown4 = 0,
                    Unknown5 = 1,
                    Entities = new[] {
                        new Entity
                        {
                            Index0 = 0,
                            Index1 = 0,
                            Name = "root",
                            Coms = new[]
                            {
                                editorComponent,
                                entityHeaderComponent,
                                new Component
                                {
                                    ClassName = "PropAnim",
                                    Name = "PropAnim",
                                    Unknown1 = 3,
                                    Unknown2 = 0,
                                    Props = StructValue.FromData(
                                        StructType.FromData(DTX.FromDtaString(
                                                                @"(props 
                                  (frame_range_start float)
                                  (frame_range_end float)
                                  (time_units int)
                                  (is_looping bool))")),
                                        DTX.FromDtaString(
                                            @"(frame_range_start 3.402823E+38)
                                (frame_range_end -3.402823E+38)
                                (time_units 0)
                                (is_looping 0)")).Props
                                }
                            }
                        }
                    }
                }
            });
        }
Example #31
0
 public void Visit(StructValue sv)
 {
     // Nothing to do here...
 }
Example #32
0
        static Protocol()
        {
            ushort Company = 0;

            StructBlock   Block   = new StructBlock();
            StructReceipt Receipt = new StructReceipt();
            StructValue   Value;

            string GroupElement = "";

            XmlReader xmlReader = XmlReader.Create(Properties.Settings.Default.Protocol);

            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Whitespace)
                {
                    // пропускаем
                }
                else if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Company") && xmlReader.HasAttributes)
                {
                    Company = Convert.ToUInt16(xmlReader.GetAttribute("Code"));
                }
                else if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Block") && xmlReader.HasAttributes)
                {
                    Block = new StructBlock();

                    try { Block.Name = xmlReader.GetAttribute("Name").Trim(); }
                    catch { Block.Name = ""; }

                    try { Block.Table = xmlReader.GetAttribute("Table").Trim(); }
                    catch { Block.Table = ""; }

                    Block.Code = Convert.ToUInt16(xmlReader.GetAttribute("Code"));
                    Block.Size = Convert.ToUInt16(xmlReader.GetAttribute("Size"));

                    Block.Company = Company;

                    BlockList.Add(Block);

                    GroupElement = "Block";
                }
                else if ((xmlReader.NodeType == XmlNodeType.EndElement) && (xmlReader.Name == "Block"))
                {
                    GroupElement = "";
                }
                else if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Receipt") && xmlReader.HasAttributes)
                {
                    Receipt = new StructReceipt();

                    try { Receipt.Name = xmlReader.GetAttribute("Name").Trim(); }
                    catch { Receipt.Name = ""; }

                    try { Receipt.Table = xmlReader.GetAttribute("Table").Trim(); }
                    catch { Receipt.Table = ""; }

                    Receipt.Code = Convert.ToUInt16(xmlReader.GetAttribute("Code"));
                    Receipt.Size = Convert.ToUInt16(xmlReader.GetAttribute("Size"));

                    Receipt.Company = Company;

                    ReceiptList.Add(Receipt);

                    GroupElement = "Receipt";
                }
                else if ((xmlReader.NodeType == XmlNodeType.EndElement) && (xmlReader.Name == "Receipt"))
                {
                    GroupElement = "";
                }
                else if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Value") && xmlReader.HasAttributes)
                {
                    Value = new StructValue();

                    try { Value.Name = xmlReader.GetAttribute("Name").Trim(); }
                    catch { Value.Name = ""; }

                    try { Value.Type = xmlReader.GetAttribute("Type").Trim(); }
                    catch { Value.Type = ""; }

                    try { Value.Base = Convert.ToByte(xmlReader.GetAttribute("Base")); }
                    catch { Value.Base = 10; }

                    try { Value.Field = xmlReader.GetAttribute("Field").Trim(); }
                    catch { Value.Field = ""; }

                    try { Value.Parameter = xmlReader.GetAttribute("Parameter").Trim(); }
                    catch { Value.Parameter = ""; }

                    Value.Offset = Convert.ToUInt16(xmlReader.GetAttribute("Offset"));
                    Value.Size   = Convert.ToUInt16(xmlReader.GetAttribute("Size"));

                    Value.AddFlag(xmlReader.GetAttribute("Flag"));

                    if (GroupElement == "Block")
                    {
                        Block.ValueList.Add(Value);
                    }
                    else if (GroupElement == "Receipt")
                    {
                        Receipt.ValueList.Add(Value);
                    }
                    else
                    {
                        throw new Exception("Error in protocol file");
                    }
                }
            }
        }
Example #33
0
 public void Visit(StructValue sv)
 {
     var st = GetStructType(sv.Name);
     Raise<TypeCheckException>.IfAreNotEqual(st.Fields.Count, sv.Values.Count, "Wrong field count");
     for (var i = 0; i < st.Fields.Count; ++i) {
         sv.Values[i].Accept(this);
         Raise<TypeCheckException>.IfAreNotSame(st.Fields[i].Type, sv.Values[i].Type, "Wrong field type");
     }
     sv.Type = _result = st;
     sv.Temp = _currFunc.AddVariable("$" + _tempCounter++, st);
 }
Example #34
0
 public override Object ImportValue(StructValue sv)
 {
     return(new URL((String)sv.Get(field)));
 }
 public void Visit(StructValue sv)
 {
     // Nothing to do here...
 }