Пример #1
0
        void SerializePrimitive(BitStreamWriter writer, object value, PrimitiveContract contract, DsdlType derivedDsdlType, bool tailArrayOptimization)
        {
            if (contract.TypeCode == PrimitiveTypeCode.String &&
                derivedDsdlType is ArrayDsdlType adt &&
                adt.IsStringLike)
            {
                byte[] stringBytes;
                if (value == null)
                {
                    stringBytes = _emptyByteArray;
                }
                else
                {
                    if (!(value is string stringValue))
                    {
                        throw new ArgumentException("Cannot cast value to string.", nameof(value));
                    }
                    stringBytes = _encoding.GetBytes(stringValue);
                }

                SerializeList(writer, stringBytes, contract, null, adt, tailArrayOptimization);
                return;
            }

            if (!(derivedDsdlType is PrimitiveDsdlType t))
            {
                throw new InvalidOperationException($"Primitive DSDL type expected for type '{contract.UnderlyingType.FullName}'.");
            }

            switch (t)
            {
            case BooleanDsdlType _:
                var boolValue = (bool)ConvertUtils.ConvertOrCast(value, CultureInfo.CurrentCulture, typeof(bool));
                BitSerializer.Write(writer, boolValue, t.MaxBitlen);
                break;

            case IntDsdlType idt:
                var longValue = (long)ConvertUtils.ConvertOrCast(value, CultureInfo.CurrentCulture, typeof(long));
                longValue = ApplyIntegerCastMode(longValue, idt);
                BitSerializer.Write(writer, longValue, t.MaxBitlen);
                break;

            case UIntDsdlType uidt:
                var ulongValue = (ulong)ConvertUtils.ConvertOrCast(value, CultureInfo.CurrentCulture, typeof(ulong));
                ulongValue = ApplyIntegerCastMode(ulongValue, uidt);
                BitSerializer.Write(writer, ulongValue, t.MaxBitlen);
                break;

            case FloatDsdlType fdt:
                var doubleValue = (double)ConvertUtils.ConvertOrCast(value, CultureInfo.CurrentCulture, typeof(double));
                WriteFloatPrimitive(writer, doubleValue, fdt);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(t));
            }
        }
Пример #2
0
        public void ExpressionSerializationDeserialization()
        {
            ExpressionInfo expression = new ExpressionInfo();

            expression.Code     = ExpressionCode.And;
            expression.Children = new[]
            {
                new ExpressionInfo
                {
                    Code     = ExpressionCode.Eq,
                    Children = new[]
                    {
                        new ExpressionInfo
                        {
                            Code  = ExpressionCode.Value,
                            Value = PrimitiveContract.Create(new Coordinate(1, 1, 1, 1))
                        },
                        new ExpressionInfo
                        {
                            Code  = ExpressionCode.Value,
                            Value = PrimitiveContract.Create(new Coordinate(1, 1, 1, 1))
                        },
                    }
                },
                new ExpressionInfo
                {
                    Code  = ExpressionCode.Value,
                    Value = PrimitiveContract.Create(true),
                }
            };

            ExpressionInfo clone = null;

            Assert.DoesNotThrow(() =>
            {
                TaskInfo task = new TaskInfo {
                    Expression = expression
                };
                clone = SerializedTask.ToTaskInfo(m_protobufSerializer.DeepClone(SerializedTask.FromTaskInfo(task))).Expression;
            });

            Assert.IsNotNull(clone);
            Assert.AreEqual(expression.Code, clone.Code);
            Assert.IsNotNull(clone.Children);
            Assert.AreNotSame(expression.Children, clone.Children);
            Assert.AreEqual(expression.Children.Length, clone.Children.Length);
            Assert.IsNotNull(clone.Children[0].Children);
            Assert.AreEqual(expression.Children[0].Children.Length, clone.Children[0].Children.Length);
            Assert.AreEqual(expression.Children[0].Children[0].Code, clone.Children[0].Children[0].Code);
            Assert.AreEqual(expression.Children[0].Children[0].Value, clone.Children[0].Children[0].Value);
            Assert.AreEqual(expression.Children[1].Code, clone.Children[1].Code);
            Assert.AreEqual(expression.Children[1].Value, clone.Children[1].Value);
        }
Пример #3
0
        private object EnsureType(BitStreamReader reader, object value, CultureInfo culture, IContract contract, Type targetType)
        {
            if (targetType == null)
            {
                return(value);
            }

            Type valueType = value?.GetType();

            // type of value and type of target don't match
            // attempt to convert value's type to target's type
            if (valueType != targetType)
            {
                if (value == null && contract.IsNullable)
                {
                    return(null);
                }

                if (contract.IsConvertable)
                {
                    PrimitiveContract primitiveContract = (PrimitiveContract)contract;

                    if (contract.IsEnum)
                    {
                        if (value is string s)
                        {
                            return(EnumUtils.ParseEnum(contract.NonNullableUnderlyingType, s, false));
                        }
                        if (ConvertUtils.IsInteger(primitiveContract.TypeCode))
                        {
                            return(Enum.ToObject(contract.NonNullableUnderlyingType, value));
                        }
                    }

                    // this won't work when converting to a custom IConvertible
                    return(Convert.ChangeType(value, contract.NonNullableUnderlyingType, culture));
                }

                return(ConvertUtils.ConvertOrCast(value, culture, contract.NonNullableUnderlyingType));
            }

            return(value);
        }
Пример #4
0
        public void ContinueInSequenceTest()
        {
            Assert.DoesNotThrow(() =>
            {
                BeginTest(TestEnv0, 4);
            });

            const int playerId = 2;

            ExpressionInfo expr = ExpressionInfo.PrimitiveVal(true);
            TaskInfo       task = TaskInfo.Repeat(expr);

            task.Children = new[]
            {
                new TaskInfo(TaskType.TEST_Mock),
                new TaskInfo(TaskType.TEST_Mock),
                TaskInfo.Sequence
                (
                    new TaskInfo(TaskType.TEST_MockImmediate),
                    TaskInfo.Assert((tb, ti) =>
                {
                    expr       = TaskInfo.FindById(task.TaskId, ti.Root).Expression;
                    expr.Value = PrimitiveContract.Create(false);
                    return(TaskState.Completed);
                }),
                    TaskInfo.Continue(),
                    new TaskInfo(TaskType.TEST_Fail)
                ),
                new TaskInfo(TaskType.TEST_MockImmediate),
                new TaskInfo(TaskType.TEST_MockImmediate)
            };


            BeginCleanupCheck(playerId);
            FinializeTest(playerId, task, result =>
            {
                Assert.AreEqual(TaskState.Completed, result.State);
                Assert.IsFalse(result.IsFailed);
                CleanupCheck(playerId);
                Assert.Pass();
            });
        }
Пример #5
0
        public void RepeatContinueTaskTest()
        {
            TaskInputInfo input = new TaskInputInfo {
                OutputIndex = 0
            };
            ExpressionInfo isTrue       = ExpressionInfo.Val(PrimitiveContract.Create(true));
            TaskInfo       continueTask = new TaskInfo
            {
                TaskType = TaskType.Continue,
            };
            TaskInfo branchTask = new TaskInfo
            {
                TaskType   = TaskType.Branch,
                Expression = isTrue,
                Children   = new[]
                {
                    continueTask,
                    null
                }
            };

            int continueCounter = 0;

            RepeatTaskTest(branchTask, input, 2, 2, childTask =>
            {
                if (continueTask.TaskId == childTask.TaskId && childTask.State == TaskState.Active)
                {
                    continueCounter++;
                    if (continueCounter == 1)
                    {
                        isTrue       = TaskInfo.FindById(branchTask.TaskId, childTask.Root).Expression;
                        isTrue.Value = false;
                    }
                }
            },
                           () =>
            {
                Assert.AreEqual(1, continueCounter);
            });
        }
Пример #6
0
        /// <summary>
        /// Get or create a read contract for <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to get or create a read contract for.</param>
        /// <returns>The read contract corresponding to <paramref name="type"/>.</returns>
        public IReadContract GetOrAddReadContract(Type type)
        {
            if (type == typeof(Empty))
            {
                return(Intern(new EmptyContract()));
            }
            if (PrimitiveContract.CanProcess(type))
            {
                return(Intern(new PrimitiveContract(type)));
            }
            if (EnumContract.CanProcess(type))
            {
                return(Intern(new EnumContract(type)));
            }
            if (TupleReadContract.CanProcess(type))
            {
                return(Intern(new TupleReadContract(type, this)));
            }
            if (NullableReadContract.CanProcess(type))
            {
                return(Intern(new NullableReadContract(type, this)));
            }
            if (ListReadContract.CanProcess(type))
            {
                return(Intern(new ListReadContract(type, this)));
            }
            if (DictionaryReadContract.CanProcess(type))
            {
                return(Intern(new DictionaryReadContract(type, this)));
            }
            if (UnionReadContract.CanProcess(type))
            {
                return(Intern(new UnionReadContract(type, this)));
            }

            return(Intern(new ComplexReadContract(type, this)));
        }
Пример #7
0
        public void RepeatBreakTaskTest()
        {
            TaskInputInfo input = new TaskInputInfo {
                OutputIndex = 0
            };
            ExpressionInfo eqTo5 = ExpressionInfo.Eq(
                ExpressionInfo.Val(input),
                ExpressionInfo.Val(PrimitiveContract.Create(5)));
            TaskInfo branchTask = new TaskInfo
            {
                TaskType   = TaskType.Branch,
                Expression = eqTo5,
                Children   = new[]
                {
                    new TaskInfo
                    {
                        TaskType = TaskType.Break,
                    },
                    null
                }
            };

            RepeatTaskTest(branchTask, input, 10, 5);
        }
Пример #8
0
        public override void ReadFrom(object obj)
        {
            base.ReadFrom(obj);
            if (obj == null)
            {
                return;
            }

            Material o = (Material)obj;

            if (o.HasProperty("_MainTex"))
            {
                mainTextureOffset = o.mainTextureOffset;
                mainTextureScale  = o.mainTextureScale;
            }

            if (o.shader == null)
            {
                shader       = m_assetDB.NullID;
                m_shaderName = null;
                return;
            }

            shader       = m_assetDB.ToID(o.shader);
            m_shaderName = o.shader.name;

            RuntimeShaderInfo  shaderInfo = null;
            IRuntimeShaderUtil shaderUtil = IOC.Resolve <IRuntimeShaderUtil>();

            if (shaderUtil != null)
            {
                shaderInfo = shaderUtil.GetShaderInfo(o.shader);
            }
            if (shaderInfo == null)
            {
                return;
            }

            m_propertyNames  = new string[shaderInfo.PropertyCount];
            m_propertyTypes  = new RTShaderPropertyType[shaderInfo.PropertyCount];
            m_propertyValues = new PrimitiveContract[shaderInfo.PropertyCount];

            for (int i = 0; i < shaderInfo.PropertyCount; ++i)
            {
                string name = shaderInfo.PropertyNames[i];
                RTShaderPropertyType type = shaderInfo.PropertyTypes[i];
                m_propertyNames[i] = name;
                m_propertyTypes[i] = type;
                switch (type)
                {
                case RTShaderPropertyType.Color:
                    m_propertyValues[i] = PrimitiveContract.Create((PersistentColor)o.GetColor(name));
                    break;

                case RTShaderPropertyType.Float:
                    m_propertyValues[i] = PrimitiveContract.Create(o.GetFloat(name));
                    break;

                case RTShaderPropertyType.Range:
                    m_propertyValues[i] = PrimitiveContract.Create(o.GetFloat(name));
                    break;

                case RTShaderPropertyType.TexEnv:
                    Texture2D texture = (Texture2D)o.GetTexture(name);
                    if (texture == null)
                    {
                        m_propertyValues[i] = PrimitiveContract.Create(m_assetDB.NullID);
                    }
                    else
                    {
                        m_propertyValues[i] = PrimitiveContract.Create(m_assetDB.ToID(texture));
                    }
                    break;

                case RTShaderPropertyType.Vector:
                    m_propertyValues[i] = PrimitiveContract.Create((PersistentVector4)o.GetVector(name));
                    break;

                case RTShaderPropertyType.Unknown:
                    m_propertyValues[i] = null;
                    break;
                }
            }

            m_keywords = o.shaderKeywords;
        }
Пример #9
0
        public void IterateRepeatTest()
        {
            Assert.DoesNotThrow(() =>
            {
                BeginTest(TestEnv0, 4);
            });

            List <int> integers = new List <int>()
            {
                1, 2, 3, 4, 5
            };
            TaskInfo iterateTask = new TaskInfo
            {
                TaskType     = TaskType.EvalExpression,
                Expression   = ExpressionInfo.Iterate(integers),
                OutputsCount = 1,
            };

            TaskInputInfo input = new TaskInputInfo
            {
                OutputIndex = 0,
                OutputTask  = iterateTask,
            };

            ExpressionInfo isTrue = ExpressionInfo.Eq(
                ExpressionInfo.Val(PrimitiveContract.Create(true)),
                ExpressionInfo.Get(
                    ExpressionInfo.Val(input),
                    ExpressionInfo.PrimitiveVal("IsLast")));

            TaskInfo breakIfCompleted = new TaskInfo
            {
                TaskType   = TaskType.Branch,
                Expression = isTrue,
                Children   = new[]
                {
                    new TaskInfo
                    {
                        TaskType = TaskType.Break,
                    },
                    null
                }
            };

            TaskInfo repeat = new TaskInfo
            {
                TaskType   = TaskType.Repeat,
                Expression = ExpressionInfo.PrimitiveVal(true),
                Children   = new[]
                {
                    iterateTask,
                    breakIfCompleted,
                }
            };

            repeat.SetParents();
            input.SetScope();

            const int playerId   = 1;
            bool      isIterated = false;
            int       counter    = 0;

            BeginCleanupCheck(playerId);

            FinializeTest(playerId, repeat, result =>
            {
                Assert.IsTrue(isIterated);

                Assert.AreEqual(TaskState.Completed, result.State);
                Assert.IsFalse(result.IsFailed);
                CleanupCheck(playerId);

                Assert.Pass();
            },
                          childTask =>
            {
                if (childTask.TaskId == iterateTask.TaskId && childTask.State == TaskState.Completed)
                {
                    counter++;
                    ITaskMemory memory         = m_engine.GetTaskEngine(playerId).Memory;
                    IterationResult iterResult = (IterationResult)memory.ReadOutput(iterateTask.Parent.TaskId, iterateTask.TaskId, 0);
                    if (iterResult.IsLast)
                    {
                        isIterated = true;
                        Assert.IsNull(iterResult.Object);
                    }
                    else
                    {
                        Assert.AreEqual(counter, (int)iterResult.Object);
                    }
                }
            });
        }
Пример #10
0
        public void RepeatTaskTest(TaskInfo repeatChildTask, TaskInputInfo input, int iterations, int expectedIterations, TaskEngineEvent <TaskInfo> childTaskCallback = null, Action pass = null)
        {
            Assert.DoesNotThrow(() =>
            {
                BeginTest(TestEnv0, 4);
            });

            ExpressionInfo setToZero = ExpressionInfo.Val(PrimitiveContract.Create(0));
            ExpressionInfo add       = ExpressionInfo.Add(
                ExpressionInfo.Val(input),
                ExpressionInfo.Val(PrimitiveContract.Create(1)));
            ExpressionInfo lessThanValue = ExpressionInfo.Lt(
                ExpressionInfo.Val(input),
                ExpressionInfo.Val(PrimitiveContract.Create(iterations)));

            TaskInfo setToZeroTask = new TaskInfo
            {
                TaskType     = TaskType.EvalExpression,
                OutputsCount = 1,
                Expression   = setToZero,
            };

            input.OutputTask = setToZeroTask;

            ExpressionInfo increment     = ExpressionInfo.Assign(setToZeroTask, add);
            TaskInfo       incrementTask = new TaskInfo
            {
                TaskType     = TaskType.EvalExpression,
                Expression   = increment,
                OutputsCount = 1,
                Inputs       = new[] { input },
            };

            TaskInfo repeatTask = new TaskInfo();

            repeatTask.TaskType   = TaskType.Repeat;
            repeatTask.Expression = lessThanValue;

            repeatTask.Children = new[]
            {
                repeatChildTask,
                incrementTask
            };

            TaskInfo task = new TaskInfo
            {
                TaskType = TaskType.Sequence,
                Children = new[]
                {
                    setToZeroTask,
                    repeatTask
                }
            };

            task.SetParents();
            const int playerId = 1;

            task.Initialize(playerId);

            //
            //input.SetScope();

            bool isIncremented = false;

            BeginCleanupCheck(playerId);
            FinializeTest(playerId, task, result =>
            {
                Assert.IsTrue(isIncremented);
                Assert.AreEqual(TaskState.Completed, result.State);
                Assert.IsFalse(result.IsFailed);
                CleanupCheck(playerId);
                if (pass != null)
                {
                    pass();
                }
                Assert.Pass();
            },
                          childTask =>
            {
                if (childTask.TaskId == repeatTask.TaskId && childTask.State == TaskState.Completed)
                {
                    ITaskMemory memory = m_engine.GetTaskEngine(playerId).Memory;
                    Assert.AreEqual(expectedIterations, memory.ReadOutput(setToZeroTask.Parent.TaskId, setToZeroTask.TaskId, 0));
                    isIncremented = true;
                }
                else
                {
                    if (childTaskCallback != null)
                    {
                        childTaskCallback(childTask);
                    }
                }
            });
        }
Пример #11
0
        public void IncrementTaskTest()
        {
            Assert.DoesNotThrow(() =>
            {
                BeginTest(TestEnv0, 4);
            });

            TaskInputInfo input = new TaskInputInfo
            {
                OutputIndex = 0
            };

            ExpressionInfo setToZero = ExpressionInfo.Val(PrimitiveContract.Create(0));
            ExpressionInfo add       = ExpressionInfo.Add(
                ExpressionInfo.Val(input),
                ExpressionInfo.Val(PrimitiveContract.Create(1)));

            TaskInfo setToZeroTask = new TaskInfo
            {
                TaskType     = TaskType.EvalExpression,
                OutputsCount = 1,
                Expression   = setToZero,
            };

            ExpressionInfo increment     = ExpressionInfo.Assign(setToZeroTask, add);
            TaskInfo       incrementTask = new TaskInfo
            {
                TaskType     = TaskType.EvalExpression,
                Expression   = increment,
                OutputsCount = 1,
                Inputs       = new[] { input },
            };

            TaskInfo task = new TaskInfo
            {
                TaskType = TaskType.Sequence,
                Children = new[]
                {
                    setToZeroTask,
                    incrementTask
                }
            };

            task.SetParents();

            input.OutputTask = setToZeroTask;
            input.SetScope();

            bool      isIncremented = false;
            const int playerId      = 1;

            BeginCleanupCheck(playerId);
            FinializeTest(playerId, task, result =>
            {
                Assert.IsTrue(isIncremented);
                Assert.AreEqual(TaskState.Completed, result.State);
                Assert.IsFalse(result.IsFailed);
                CleanupCheck(playerId);
                Assert.Pass();
            },
                          childTask =>
            {
                if (childTask.TaskId == incrementTask.TaskId && childTask.State == TaskState.Completed)
                {
                    ITaskMemory memory = m_engine.GetTaskEngine(playerId).Memory;
                    Assert.AreEqual(1, memory.ReadOutput(setToZeroTask.Parent.TaskId, setToZeroTask.TaskId, 0));
                    isIncremented = true;
                }
            });
        }