public void cant_add_two_confirmations_for_one_order_to_hashset()
        {
            ObservableHashSet <OrderDeliveryConfirmation> confirmations =
                new ObservableHashSet <OrderDeliveryConfirmation>(new OrderDeliveryConfirmationComparer());

            Order o1 = new Order(1,
                                 BrokerDateTime.Make(DateTime.Now),
                                 "BP12345-RF-01",
                                 "RTS-9.13_FT",
                                 TradeAction.Buy,
                                 OrderType.Limit,
                                 10,
                                 136000,
                                 0);

            OrderDeliveryConfirmation c1 =
                new OrderDeliveryConfirmation(o1, BrokerDateTime.Make(DateTime.Now));

            confirmations.Add(c1);
            Assert.AreEqual(1, confirmations.Count);

            OrderDeliveryConfirmation c2 =
                new OrderDeliveryConfirmation(o1, BrokerDateTime.Make(DateTime.Now));

            confirmations.Add(c2);
            Assert.AreEqual(1, confirmations.Count);
        }
        public void AddingItems_ThatAreReferences_ShouldTrackAddedItems()
        {
            var sourceHashSet = new ObservableHashSet <string>();

            var SourceSynchronizerRoot = new SourceSynchronizerRoot(sourceHashSet);

            sourceHashSet.Add("1");
            sourceHashSet.Add("2");

            Assert.Equal(3, SourceSynchronizerRoot.TrackedObjects.Count());
        }
 public void Add_RaisesCollectionChanged()
 {
     bool flag = false;
     var observableHash = new ObservableHashSet<int>();
     observableHash.CollectionChanged += (sender, args) => flag = true;
     observableHash.Add(1);
     Assert.True(flag);
 }
 public void Add_DoesNotRaisesCollectionChanged_WhenAlreadyAdded()
 {
     bool flag = false;
     var observableHash = new ObservableHashSet<int>() {1};
     observableHash.CollectionChanged += (sender, args) => flag = true;
     observableHash.Add(1);
     Assert.False(flag);
 }
        public void Can_add()
        {
            var hashSet           = new ObservableHashSet <string>();
            var countChanging     = 0;
            var countChanged      = 0;
            var collectionChanged = 0;
            var currentCount      = 0;
            var countChange       = 1;
            var adding            = new string[0];

            hashSet.PropertyChanging  += (s, a) => AssertCountChanging(hashSet, s, a, currentCount, ref countChanging);
            hashSet.PropertyChanged   += (s, a) => AssertCountChanged(hashSet, s, a, ref currentCount, countChange, ref countChanged);
            hashSet.CollectionChanged += (s, a) =>
            {
                Assert.Equal(NotifyCollectionChangedAction.Add, a.Action);
                Assert.Null(a.OldItems);
                Assert.Equal(adding, a.NewItems.OfType <string>());
                collectionChanged++;
            };

            adding = new[] { "Palmer" };
            Assert.True(hashSet.Add("Palmer"));

            Assert.Equal(1, countChanging);
            Assert.Equal(1, countChanged);
            Assert.Equal(1, collectionChanged);
            Assert.Equal(new[] { "Palmer" }, hashSet);

            adding = new[] { "Carmack" };
            Assert.True(hashSet.Add("Carmack"));

            Assert.Equal(2, countChanging);
            Assert.Equal(2, countChanged);
            Assert.Equal(2, collectionChanged);
            Assert.Equal(new[] { "Carmack", "Palmer" }, hashSet.OrderBy(i => i));

            Assert.False(hashSet.Add("Palmer"));

            Assert.Equal(2, countChanging);
            Assert.Equal(2, countChanged);
            Assert.Equal(2, collectionChanged);
            Assert.Equal(new[] { "Carmack", "Palmer" }, hashSet.OrderBy(i => i));
        }
Exemple #6
0
        private void FileHashes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (ignoreChanges)
            {
                return;
            }

            ignoreChanges = true;

            // If the collection was reset, then e.OldItems is empty. Just clear and reload.
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset)
            {
                FileHashes.Clear();

                foreach (var hash in index.Hashes)
                {
                    hashes.Add(new FileHashViewModel(hash));
                }
            }
            else
            {
                // Remove items from collection.
                var toRemove = new List <FileHashViewModel>();

                if (null != e.OldItems && e.OldItems.Count > 0)
                {
                    foreach (var item in e.OldItems)
                    {
                        foreach (var existingItem in FileHashes)
                        {
                            if (existingItem.IsViewFor((FileHash)item))
                            {
                                toRemove.Add(existingItem);
                            }
                        }
                    }
                }

                foreach (var item in toRemove)
                {
                    FileHashes.Remove(item);
                }

                // Add new items to the collection.
                if (null != e.NewItems && e.NewItems.Count > 0)
                {
                    foreach (var item in e.NewItems)
                    {
                        FileHashes.Add(new FileHashViewModel((FileHash)item));
                    }
                }
            }
            ignoreChanges = false;
            NotifyPropertyChanged("FileHashes");
        }
        public void Items_added_to_ObservableHashSet_are_added_to_binding_list()
        {
            var oc   = new ObservableHashSet <ListElement>();
            var obbl = new ObservableBackedBindingList <ListElement>(oc);

            var item = new ListElement(1);

            oc.Add(item);

            Assert.True(obbl.Contains(item));
        }
Exemple #8
0
        public void Collections_ObservableHashSet_test()
        {
            OrderHashSetObserver      o  = new OrderHashSetObserver();
            ObservableHashSet <Order> hs = new ObservableHashSet <Order>();

            hs.RegisterObserver(o);

            Assert.AreEqual(0, o.Count);
            hs.Add(new Order());

            Assert.AreEqual(1, o.Count);
        }
        public void WhenClear_ThenRaisesCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);

            bool wasEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Reset) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.Clear();

            // Assert
            Assert.IsTrue(wasEventRaised);
        }
        public void WhenAdd_ThenCountUpdated() {
            // Arrange
            var target = new ObservableHashSet<int>();

            // Act
            target.Add(5);

            var actual = target.Count;

            // Assert
            Assert.AreEqual(1, actual);
        }
        public void Adding_duplicate_item_to_the_ObservableHashSet_is_ignored()
        {
            var item = new ListElement(4);
            var oc   = new ObservableHashSet <ListElement> {
                3, 1, item, 1, 5, 9
            };
            var obbl = new ObservableBackedBindingList <ListElement>(oc);

            oc.Add(item);

            Assert.Equal(6, obbl.Count);
            Assert.Equal(1, obbl.Count(i => ReferenceEquals(i, item)));
        }
        public void RemoveWhereConcurrent() {
            var names = new ObservableHashSet<string>(_names);
            names.CollectionChanged += (sender, args) => Console.WriteLine(args.Action);
            for (int i = names.Count; i > 0; i--) {
                int length = i;
                var task = Task.Factory.StartNew(() => {
                    names.Add("Bob");
                    names.RemoveWhere(n => n.Equals("Bob"));
                });
                names.RemoveWhere(n => n.Length > length);
                task.WaitWithPumping();
            }

            Assert.AreEqual(0, names.Count);
        }
        public void WhenAdd_ThenRaisesCountPropertyChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            bool wasEventRaised = false;
            target.PropertyChanged += (s, e) => {
                if (e.PropertyName == ObservableHashSet<int>.PropertyNames.Count) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.Add(5);

            // Assert
            Assert.IsTrue(wasEventRaised);
        }
        public void WhenAdd_ThenRaisesCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            bool wasEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems.Contains(5)) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.Add(5);

            // Assert
            Assert.IsTrue(wasEventRaised);
        }
        public void RemoveWhereConcurrent()
        {
            var names = new ObservableHashSet <string>(_names);

            names.CollectionChanged += (sender, args) => Console.WriteLine(args.Action);
            for (int i = names.Count; i > 0; i--)
            {
                int length = i;
                var task   = Task.Factory.StartNew(() => {
                    names.Add("Bob");
                    names.RemoveWhere(n => n.Equals("Bob"));
                });
                names.RemoveWhere(n => n.Length > length);
                task.WaitWithPumping();
            }

            Assert.AreEqual(0, names.Count);
        }
Exemple #16
0
        /// <summary>
        /// Updates the versions of all entities that are currently marked as modified.
        /// </summary>
        internal void UpdateVersions()
        {
            var versionEntries = new ObservableHashSet <PropertyEntry>();

            foreach (EntityEntry entityEntry in ChangeTracker.Entries())
            {
                if (entityEntry.Entity is VersionedEntity versionedEntity)
                {
                    var propertyEntry  = entityEntry.Property(nameof(versionedEntity.Version));
                    var currentVersion = (long)propertyEntry.CurrentValue;
                    propertyEntry.CurrentValue = currentVersion + 1L;
                    versionEntries.Add(propertyEntry);
                }
            }
            // Mark the updated versions as not being modified. This prevents the entity from being
            // included in any subsequent SaveChanges call, unless one of its actual properties is
            // updated.
            foreach (PropertyEntry pe in versionEntries)
            {
                pe.IsModified = false;
            }
        }
        public void Synchronizing_RollsBackTargetChangesPriorToSourceTick()
        {
            var source = new ObservableHashSet <string>();
            var SourceSynchronizerRoot = new SourceSynchronizerRoot(source);

            byte[] writeFullAndDispose    = SourceSynchronizerRoot.WriteFullAndDispose();
            var    TargetSynchronizerRoot = new TargetSynchronizerRoot <ObservableHashSet <string> >(
                writeFullAndDispose);

            ObservableHashSet <string> target = TargetSynchronizerRoot.Reference;

            target.Add("2");

            TargetSynchronizerRoot.Clock.OwnTick = TimeSpan.FromMilliseconds(5);

            //Set tick older than client tick
            byte[] changes = SourceSynchronizerRoot.WriteChangesAndDispose().SetTick(TimeSpan.FromMilliseconds(6));
            TargetSynchronizerRoot.Read(changes);

            // Recently added item should be rolled back
            Assert.Empty(target);
        }
Exemple #18
0
        public bool AddOrModify(GameObjectMetadata metadata)
        {
            if (_collection.FirstOrDefault(or => or.Equals(metadata)) is GameObjectMetadata existing)
            {
                bool modified = false;
                if (existing.Name != metadata.Name)
                {
                    existing.Name = metadata.Name;
                    modified      = true;
                }
                if (existing.Keywords.SequenceEqual(metadata.Keywords))
                {
                    existing.UpdateKeywords(metadata.Keywords);
                    modified = true;
                }

                return(modified);
            }
            else
            {
                _collection.Add(metadata);
                return(true);
            }
        }
        public void WhenUnionWithAndOtherEqual_ThenDoesNotRaiseCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            var other = new int[] { 1, 2, 3, 4 };

            bool wasEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Add) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.UnionWith(other);

            // Assert            
            Assert.IsFalse(wasEventRaised);
        }
        public void WhenUnionWithAndOtherEqual_ThenDoesNotRaiseCountPropertyChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            var other = new int[] { 1, 2, 3, 4 };

            bool wasEventRaised = false;
            target.PropertyChanged += (s, e) => {
                if (e.PropertyName == ObservableHashSet<int>.PropertyNames.Count) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.UnionWith(other);

            // Assert
            Assert.IsFalse(wasEventRaised);
        }
        public void OldTests()
        {
            //////////////////////////////////////////////////////////////////////////////////////
            List<int> ints = new List<int> { 1, 2, 3 };
            ints.ForEach(delegate(int i) { if (i == 2) ints.Remove(i); }); //COOL: NO ENUMERATION WAS MODIFIED ERROR
            ints.ForEach(delegate(int i) { Console.WriteLine(i); });

            MethodInfo testmethod = room.GetType().GetMethod("test");
            Action<Room, int, float, string> del = (Action<Room, int, float, string>)Delegate.CreateDelegate(typeof(Action<Room, int, float, string>), testmethod);
            del(room, 1, 0.3f, "Action worked.");

            Action<int, float, string> del2 = (Action<int, float, string>)Delegate.CreateDelegate(typeof(Action<int, float, string>), room, testmethod);
            //target is bound to 'room' in this example due to the overload of CreateDelegate used.
            del2(2, 3.3f, "Action worked again.");

            PropertyInfo pinfo = typeof(Component).GetProperty("active");
            MethodInfo minfo = pinfo.GetGetMethod();
            Console.WriteLine("{0}", minfo.ReturnType);

            Movement tester = new Movement();
            tester.active = true;

            bool ret = (bool)minfo.Invoke(tester, new object[] { }); //VERY expensive (slow)
            Console.WriteLine("{0}", ret);

            Func<Component, bool> delGet = (Func<Component, bool>)Delegate.CreateDelegate(typeof(Func<Component, bool>), minfo);
            Console.WriteLine("{0}", delGet(tester)); //very fast, and no cast or creation of empty args array required

            minfo = pinfo.GetSetMethod();
            //Console.WriteLine("{0} {1}", minfo.ReturnType, minfo.GetParameters()[0].ParameterType);

            Action<Component, bool> delSet = (Action<Component, bool>)Delegate.CreateDelegate(typeof(Action<Component, bool>), minfo);
            delSet(tester, false);
            Console.WriteLine("Here we go: {0}", delGet(tester));
            delSet(tester, true);
            /////////////////////////////////////////////////////////////////////////////////////////
            /*
            //gets all types that are a subclass of Component
            List<Type> types = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(assembly => assembly.GetTypes())
                       .Where(type => type.IsSubclassOf(typeof(Component))).ToList();
            foreach (Type t in types) Console.WriteLine(t);
            */

            //room.defaultNode.Update(new GameTime()); //for testing

            //MODIFIER ADDITION
            /*
            room.defaultNode.addComponent(comp.modifier, true); //room.defaultNode.comps[comp.modifier].active = false;
            ModifierInfo modinfo = new ModifierInfo();
            modinfo.AddFPInfoFromString("o1", "scale", room.defaultNode);
            modinfo.AddFPInfoFromString("m1", "position", room.defaultNode);
            modinfo.AddFPInfoFromString("v1", "position", room.defaultNode);

            modinfo.args.Add("mod", 4.0f);
            modinfo.args.Add("times", 3.0f);
            modinfo.args.Add("test", 3.0f);

            //modinfo.delegateName = "Mod";
            //modinfo.delegateName = "Triangle";
            //modinfo.delegateName = "VelocityToOutput";
            //modinfo.delegateName = "VectorSine";
            modinfo.delegateName = "VectorSineComposite";

            room.defaultNode.comps[comp.modifier].modifierInfos["sinecomposite"] = modinfo;
            */

            ObservableHashSet<int> obints = new ObservableHashSet<int>();
            obints.CollectionChanged += (s, e) =>
            {
                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {
                    foreach (int i in e.NewItems)
                    {
                        Console.WriteLine("Added:" + i);
                    }
                }
            };
            obints.Add(6);
        }
        public void WhenUnionWith_ThenRaisesCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            var other = new int[] { 1, 4, 5, 6 };

            bool wasEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Add &&
                    e.NewItems.Count == 2 &&
                    e.NewItems.Contains(5) &&
                    e.NewItems.Contains(6)) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.UnionWith(other);

            // Assert            
            Assert.IsTrue(wasEventRaised);
        }
        public void WhenSymmetricExceptWithAndOtherEquals_ThenRaisesCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            var other = new int[] { 1, 2, 3, 4 };

            bool wasRemoveEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Remove &&
                    e.OldItems.Count == 4 &&
                    e.OldItems.Contains(1) &&
                    e.OldItems.Contains(2) &&
                    e.OldItems.Contains(3) &&
                    e.OldItems.Contains(4)) {
                    wasRemoveEventRaised = true;
                }
            };

            bool wasAddEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Add) {
                    wasAddEventRaised = true;
                }
            };

            // Act
            target.SymmetricExceptWith(other);

            // Assert
            Assert.IsTrue(wasRemoveEventRaised);
            Assert.IsFalse(wasAddEventRaised);
        }
        public void WhenSymmetricExceptWithAndOtherEmpty_ThenDoesNotRaiseCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            var other = new int[] { };

            bool wasRemoveEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Remove) {
                    wasRemoveEventRaised = true;
                }
            };

            bool wasAddEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Add) {
                    wasAddEventRaised = true;
                }
            };

            // Act
            target.SymmetricExceptWith(other);

            // Assert
            Assert.IsFalse(wasRemoveEventRaised);
            Assert.IsFalse(wasAddEventRaised);
        }
        public void WhenSymmetricExceptWith_ThenRaisesCountPropertyChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            var other = new int[] { 1, 4, 5, 6 };

            bool wasEventRaised = false;
            target.PropertyChanged += (s, e) => {
                if (e.PropertyName == ObservableHashSet<int>.PropertyNames.Count) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.SymmetricExceptWith(other);

            // Assert
            Assert.IsTrue(wasEventRaised);
        }
Exemple #26
0
        public void DoesSupportObservableHashSet()
        {
            List <string> expected;
            List <int>    expectedForked;

            ObservableHashSet <int> source1 = new ObservableHashSet <int>();
            ObservableHashSet <int> source2 = new ObservableHashSet <int>();
            ObservableHashSet <int> source3 = new ObservableHashSet <int>();

            List <string> projection1 = new List <string>();
            List <string> projection2 = new List <string>();
            List <int>    projection3 = new List <int>();

            Func <int, string> transformation  = i => i.ToString();
            Func <int, bool>   filterPredicate = i => i <= 2;

            ListBinding <string> binding = new ListBinding <string>()
                                           .AddSource(source1, convert: transformation, filter: filterPredicate)
                                           .AddSource(source2, convert: transformation, filter: filterPredicate)
                                           .AddSource(source3, convert: transformation, filter: filterPredicate);

            source1.Add(0);
            source2.Add(1);
            source3.Add(2);
            source3.Add(3);
            source2.Add(4);

            binding.AddTarget(projection1);

            source1.Add(5);
            source2.Add(6);

            binding.AddTarget(projection2);

            source1.Add(7);
            source3.Add(8);

            expected = source1.Concat(source2).Concat(source3).Where(filterPredicate).Select(transformation).ToList();
            expected.Sort();
            Assert.Equal(expected, projection1);
            Assert.Equal(expected, projection2);

            var bindingForked = binding.Select <int>(item => int.Parse(item));

            source2.Remove(4);
            source1.Remove(5);
            source2.Remove(6);

            expected = source1.Concat(source2).Concat(source3).Where(filterPredicate).Select(transformation).ToList();
            expected.Sort();
            Assert.Equal(expected, projection1);
            Assert.Equal(expected, projection2);

            source1.Add(4);
            source3.Add(5);
            source1.Add(6);

            expected = source1.Concat(source2).Concat(source3).Where(filterPredicate).Select(transformation).ToList();
            expected.Sort();
            Assert.Equal(expected, projection1);
            Assert.Equal(expected, projection2);

            source1.Clear();

            expected = source1.Concat(source2).Concat(source3).Where(filterPredicate).Select(transformation).ToList();
            expected.Sort();
            Assert.Equal(expected, projection1);
            Assert.Equal(expected, projection2);

            source3.Clear();
            source2.Clear();

            expected = source1.Concat(source2).Concat(source3).Where(filterPredicate).Select(transformation).ToList();
            expected.Sort();
            Assert.Equal(expected, projection1);
            Assert.Equal(expected, projection2);

            expectedForked = source1.Concat(source2).Concat(source3).Where(filterPredicate).ToList();
            expectedForked.Sort();
            Assert.Equal(expectedForked, projection3);
        }
        public void LoadLevel(LevelSave levelSave)
        {
            Room room = OrbIt.game.room;
            //room.worldWidth = levelSave.levelWidth;
            //room.worldHeight = levelSave.levelHeight;
            v = new Vector2(levelSave.levelWidth, levelSave.levelHeight);
            room.resize(v, true);
            room.waitTimeCounter = 0;
            if (!levelSaves.ContainsKey(levelSave))
            {
                ObservableHashSet<Node> nodes = new ObservableHashSet<Node>();
                for (int i = 0; i < levelSave.polygonVertices.Count; i++)
                {
                    Node newNode = new Node(sidebar.ui.game.room, ShapeType.Polygon);
                    Polygon poly = (Polygon)newNode.body.shape;
                    //poly.SetCenterOfMass(vertices);
                    float[] list = levelSave.polygonVertices[i];
                    for (int j = 0; j < list.Length / 2; j++)
                    {
                        poly.vertices[j] = new Vector2(list[j * 2], list[(j * 2) + 1]);
                    }
                    poly.vertexCount = list.Length / 2;
                    newNode.body.pos = new Vector2(levelSave.polygonPositions[i][0], levelSave.polygonPositions[i][1]);
                    newNode.body.SetStatic();
                    newNode.body.orient = 0;
                    newNode.movement.mode = movemode.free;
                    newNode.body.restitution = 1f;
                    newNode.body.texture = textures.rock1;
                    newNode.meta.maxHealth.enabled = false;
                    poly.ComputeNormals();
                    poly.CalibrateTexture();
                    nodes.Add(newNode);
                }
                levelSaves[levelSave] = nodes;
            }
            ObservableHashSet<Node> incomingNodes = levelSaves[levelSave];
            foreach (Node n in wallGroup.entities.ToList())
            {
                wallGroup.DiscludeEntity(n);
            }

            foreach (Node n in incomingNodes)
            {
                wallGroup.IncludeEntity(n);
            }
        }
        public static void LoadLevelSpider(LevelSave levelSave)
        {
            Room room = OrbIt.game.room;
            //room.worldWidth = levelSave.levelWidth;
            //room.worldHeight = levelSave.levelHeight;
            Vector2 v = new Vector2(levelSave.levelWidth, levelSave.levelHeight);
            room.resize(v, true);
            room.waitTimeCounter = 0;
            ObservableHashSet<Node> nodes = new ObservableHashSet<Node>();
            for (int i = 0; i < levelSave.polygonVertices.Count; i++)
            {
                Node newNode = new Node(OrbIt.ui.game.room, ShapeType.Polygon);
                Polygon poly = (Polygon)newNode.body.shape;
                //poly.SetCenterOfMass(vertices);
                float[] list = levelSave.polygonVertices[i];
                for (int j = 0; j < list.Length / 2; j++)
                {
                    poly.vertices[j] = new Vector2(list[j * 2], list[(j * 2) + 1]);
                }
                poly.vertexCount = list.Length / 2;
                newNode.body.pos = new Vector2(levelSave.polygonPositions[i][0], levelSave.polygonPositions[i][1]);
                newNode.body.SetStatic();
                newNode.body.orient = 0;
                newNode.movement.mode = movemode.free;
                newNode.body.restitution = 1f;
                newNode.body.texture = textures.rock1;
                newNode.meta.maxHealth.enabled = false;
                poly.ComputeNormals();
                poly.CalibrateTexture();
                nodes.Add(newNode);
            }
                foreach (var dd in levelSave.Diodes)
                {
                    var dict = new Dictionary<dynamic, dynamic>() { { typeof(Diode), true }, { nodeE.texture, textures.gradient1 } };
                    Node lastSpawnedDiode = Node.ContructLineWall(room, new Vector2(dd.start[0], dd.start[1]), new Vector2(dd.end[0], dd.end[1]), DiodeSpawner.diodeThickness, dict, false);
                    lastSpawnedDiode.SetColor(new Color(255, 255, 255, 255));
                    lastSpawnedDiode.Comp<Diode>().start = new Vector2(dd.start[0], dd.start[1]);
                    lastSpawnedDiode.Comp<Diode>().end = new Vector2(dd.end[0], dd.end[1]);
                    lastSpawnedDiode.Comp<Diode>().semaphore = dd.isSemaphore;
                    lastSpawnedDiode.Comp<Diode>().maxTickets = dd.tickets;
                    lastSpawnedDiode.body.orient = dd.orientation;

                    room.masterGroup.IncludeEntity(lastSpawnedDiode);
                    lastSpawnedDiode.OnSpawn();
                }

            ObservableHashSet<Node> incomingNodes = nodes;
            foreach (Node n in room.groups.walls.entities.ToList())
            {
                room.groups.walls.DiscludeEntity(n);
            }

            foreach (Node n in incomingNodes)
            {
                room.groups.walls.IncludeEntity(n);
            }
            foreach (Node n in room.groups.walls.entities)
            {
                n.collision.UpdateCollisionSet();
            }
            finalizeLevelLoad(v);
        }
Exemple #29
0
        public override ProblemCollection Check(TypeNode type)
        {
            Debug.WriteLine("Checking type:" + type.FullName);
            var initializer = type.Members.OfType<Method>().FirstOrDefault(x => x.FullName == type.FullName + ".InitializeComponent");

            if (initializer == null)
                return null;
            Debug.WriteLine(initializer.FullName);
            var constructorsWithNoInitCall = type.Members.OfType<Method>().Where(m => m.NodeType == NodeType.InstanceInitializer).ToList();
            var visitedMethods = new HashSet<string>();
            var foundMethods = new ObservableHashSet<Method>();


            var whenMethodsFound = Observable.FromEvent<NotifyCollectionChangedEventArgs>(foundMethods, "CollectionChanged")
                .Where(e => e.EventArgs.Action == NotifyCollectionChangedAction.Add
                    && constructorsWithNoInitCall.Any());


           

            whenMethodsFound.Subscribe(e => Parallel.ForEach(e.EventArgs.NewItems.OfType<Method>()
                                     .Where(m => !visitedMethods.Any(v => v == m.FullName)),
                                        i =>
                                        {
                                            lock (visitedMethods)
                                            {
                                                if (visitedMethods.Contains(i.FullName))
                                                    return;
                                                visitedMethods.Add(i.FullName);
                                            }
                                            Debug.WriteLine("Visiting:" + i.FullName);
                                            var callers = (CallGraph.CallersFor(i));
                                            constructorsWithNoInitCall.RemoveAll(x => callers.Any(c => x.FullName == c.FullName));
                                            if (constructorsWithNoInitCall.Any())
                                                foreach (var item in callers.Where(c => visitedMethods.Any(v => v == c.FullName) == false))
                                                {
                                                    foundMethods.Add(item);
                                                }
                                        }));


            //e =>
            //{
            //                Parallel.ForEach(e.EventArgs.NewItems.OfType<Method>()
            //                                    .Where(m => !visitedMethods.Any(v => v == m.FullName) ),
            //                    i =>
            //                    {

            //                        lock (visitedMethods)
            //                        {
            //                            if (visitedMethods.Contains(i.FullName))
            //                                return;
            //                            visitedMethods.Add(i.FullName);

            //                        }
            //                        Debug.WriteLine("Visiting:" + i.FullName);
            //                        var callers = (CallGraph.CallersFor(i));
            //                        constructorsWithNoInitCall.RemoveAll(x => callers.Any(c => x.FullName == c.FullName));
            //                        if (constructorsWithNoInitCall.Any())
            //                            foreach (var item in callers.Where(c => visitedMethods.Any(v => v == c.FullName) == false))
            //                            {
            //                                foundMethods.Add(item);
            //                            }
            //                    });
            //));



            foundMethods.Add(initializer);

            //whenMethodsFound.Run();

            //_currentType=type;
            ReportProblem(constructorsWithNoInitCall, type);

            return Problems;
        }
        public void WhenRemove_ThenCountUpdated() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            // Act
            target.Remove(3);

            var actual = target.Count;

            // Assert
            Assert.AreEqual(3, actual);
        }
Exemple #31
0
        public override ProblemCollection Check(TypeNode type)
        {
            Debug.WriteLine("Checking type:" + type.FullName);
            var initializer = type.Members.OfType <Method>().FirstOrDefault(x => x.FullName == type.FullName + ".InitializeComponent");

            if (initializer == null)
            {
                return(null);
            }
            Debug.WriteLine(initializer.FullName);
            var constructorsWithNoInitCall = type.Members.OfType <Method>().Where(m => m.NodeType == NodeType.InstanceInitializer).ToList();
            var visitedMethods             = new HashSet <string>();
            var foundMethods = new ObservableHashSet <Method>();


            var whenMethodsFound = Observable.FromEvent <NotifyCollectionChangedEventArgs>(foundMethods, "CollectionChanged")
                                   .Where(e => e.EventArgs.Action == NotifyCollectionChangedAction.Add &&
                                          constructorsWithNoInitCall.Any());



            whenMethodsFound.Subscribe(e => Parallel.ForEach(e.EventArgs.NewItems.OfType <Method>()
                                                             .Where(m => !visitedMethods.Any(v => v == m.FullName)),
                                                             i =>
            {
                lock (visitedMethods)
                {
                    if (visitedMethods.Contains(i.FullName))
                    {
                        return;
                    }
                    visitedMethods.Add(i.FullName);
                }
                Debug.WriteLine("Visiting:" + i.FullName);
                var callers = (CallGraph.CallersFor(i));
                constructorsWithNoInitCall.RemoveAll(x => callers.Any(c => x.FullName == c.FullName));
                if (constructorsWithNoInitCall.Any())
                {
                    foreach (var item in callers.Where(c => visitedMethods.Any(v => v == c.FullName) == false))
                    {
                        foundMethods.Add(item);
                    }
                }
            }));


            //e =>
            //{
            //                Parallel.ForEach(e.EventArgs.NewItems.OfType<Method>()
            //                                    .Where(m => !visitedMethods.Any(v => v == m.FullName) ),
            //                    i =>
            //                    {

            //                        lock (visitedMethods)
            //                        {
            //                            if (visitedMethods.Contains(i.FullName))
            //                                return;
            //                            visitedMethods.Add(i.FullName);

            //                        }
            //                        Debug.WriteLine("Visiting:" + i.FullName);
            //                        var callers = (CallGraph.CallersFor(i));
            //                        constructorsWithNoInitCall.RemoveAll(x => callers.Any(c => x.FullName == c.FullName));
            //                        if (constructorsWithNoInitCall.Any())
            //                            foreach (var item in callers.Where(c => visitedMethods.Any(v => v == c.FullName) == false))
            //                            {
            //                                foundMethods.Add(item);
            //                            }
            //                    });
            //));



            foundMethods.Add(initializer);

            //whenMethodsFound.Run();

            //_currentType=type;
            ReportProblem(constructorsWithNoInitCall, type);

            return(Problems);
        }
        public override void PlayerControl(Input input)
        {
            Vector2 newstickpos = input.GetRightStick(shovelReach, true);//input.GetRightStick();
            Vector2 pos = newstickpos * shovelReach;
            Vector2 worldStickPos = parent.body.pos + pos;
            Vector2 diff = worldStickPos - shovelNode.body.pos;
            //float angle = Utils.VectorToAngle(shovelNode.body.pos - parent.body.pos) + VMath.PIbyTwo % VMath.twoPI;
            Vector2 shovelDir = shovelNode.body.pos - parent.body.pos;
            shovelDir = new Vector2(shovelDir.Y, -shovelDir.X);
            shovelNode.body.SetOrientV2(shovelDir);

            if (modeShovelPosition == ModeShovelPosition.AbsoluteStickPos)
            {
                shovelNode.body.pos = worldStickPos;
            }
            else if (modeShovelPosition == ModeShovelPosition.PhysicsBased)
            {
                float len = diff.Length();
                if (len < 1)
                {
                    shovelNode.body.velocity = Vector2.Zero;
                }
                else
                {
                    float velLen = shovelNode.body.velocity.Length();

                    Vector2 diffcopy = diff;
                    VMath.NormalizeSafe(ref diffcopy);

                    Vector2 normalizedVel = shovelNode.body.velocity;
                    VMath.NormalizeSafe(ref normalizedVel);

                    float result = 0;
                    Vector2.Dot(ref diffcopy, ref normalizedVel, out result);

                    diffcopy *= result;
                    Vector2 force = (diff / physicsDivisor);
                    if (shovelling && compoundedMass >= 1) force /= compoundedMass * 1;
                    shovelNode.body.velocity = diffcopy + force;
                    //shovelNode.body.ApplyForce(force);
                }
            }

            if (shovelling)
            {
                //if (fc.newGamePadState.Triggers.Right < deadzone && fc.oldGamePadState.Triggers.Right > deadzone)
                if (input.BtnReleased(InputButtons.RightTrigger_Mouse1))
                {
                    shovelling = false;
                    foreach(Node n in shovelLink.targets.ToList())
                    {
                        if (physicsThrow)
                        {
                            n.body.velocity = n.body.effvelocity;
                        }
                        else
                        {
                            Vector2 stickdirection = newstickpos;
                            VMath.NormalizeSafe(ref stickdirection);

                            n.body.velocity = stickdirection * throwSpeed;
                        }
                        n.collision.active = true;
                        shovelLink.targets.Remove(n);
                        n.body.ClearExclusionChecks();
                        n.body.color = n.body.permaColor;
                    }
                    shovelLink.formation.UpdateFormation();
                    shovelLink.active = false;
                    shovelNode.room.AllActiveLinks.Remove(shovelLink);
                    compoundedMass = 0f;
                }
            }
            else
            {
                if (input.BtnClicked(InputButtons.RightTrigger_Mouse1))
                {
                    shovelling = true;
                    ObservableHashSet<Node> capturedNodes = new ObservableHashSet<Node>();
                    int count = 0;
                    Action<Collider, Collider> del = delegate(Collider c1, Collider c2){
                        if (count >= maxShovelCapacity) return;
                        if (c2.parent.dataStore.ContainsKey("shovelnodeparent"))return;
                        if (c2.parent.HasComp<Diode>()) return;
                        if (modePlayers != ModePlayers.GrabBoth && c2.parent.IsPlayer)
                        {
                            if (modePlayers == ModePlayers.GrabNone) return;
                            if (modePlayers == ModePlayers.GrabSelf && c2.parent != parent) return;
                            if (modePlayers == ModePlayers.GrabOtherPlayers && c2.parent == parent) return;
                        }
                        float dist = Vector2.Distance(c1.pos, c2.pos);
                        if (dist <= scoopReach)
                        {
                            count++;
                            capturedNodes.Add(c2.parent);
                            c2.parent.body.color = parent.body.color;
                        }
                    };
                    shovelNode.room.gridsystemAffect.retrieveOffsetArraysAffect(shovelNode.body, del, scoopReach * 2);
                    shovelLink.targets = capturedNodes;
                    shovelLink.formation.UpdateFormation();
                    shovelLink.active = true;
                    shovelNode.room.AllActiveLinks.Add(shovelLink);
                    compoundedMass = 0f;
                    foreach(Node n in capturedNodes)
                    {
                        n.collision.active = false;
                        compoundedMass += n.body.mass;
                    }
                }
            }
        }
        public void WhenRemove_ThenRaisesCollectionChanged() {
            // Arrange
            var target = new ObservableHashSet<int>();

            target.Add(1);
            target.Add(2);
            target.Add(3);
            target.Add(4);

            bool wasEventRaised = false;
            target.CollectionChanged += (s, e) => {
                if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems.Contains(3)) {
                    wasEventRaised = true;
                }
            };

            // Act
            target.Remove(3);

            // Assert
            Assert.IsTrue(wasEventRaised);
        }
Exemple #34
0
        public override void PlayerControl(Input input)
        {
            Vector2R newstickpos   = input.GetRightStick(shovelReach, true).toV2R(); //input.GetRightStick();
            Vector2R pos           = newstickpos * shovelReach;
            Vector2R worldStickPos = parent.body.pos + pos;
            Vector2R diff          = worldStickPos - shovelNode.body.pos;
            //float angle = Utils.VectorToAngle(shovelNode.body.pos - parent.body.pos) + VMath.PIbyTwo % VMath.twoPI;
            Vector2R shovelDir = shovelNode.body.pos - parent.body.pos;

            shovelDir = new Vector2R(shovelDir.Y, -shovelDir.X);
            shovelNode.body.SetOrientV2(shovelDir);

            if (modeShovelPosition == ModeShovelPosition.AbsoluteStickPos)
            {
                shovelNode.body.pos = worldStickPos;
            }
            else if (modeShovelPosition == ModeShovelPosition.PhysicsBased)
            {
                float len = diff.Length();
                if (len < 1)
                {
                    shovelNode.body.velocity = Vector2R.Zero;
                }
                else
                {
                    float velLen = shovelNode.body.velocity.Length();

                    Vector2R diffcopy = diff;
                    VMath.NormalizeSafe(ref diffcopy);

                    Vector2R normalizedVel = shovelNode.body.velocity;
                    VMath.NormalizeSafe(ref normalizedVel);

                    float result = 0;
                    Vector2R.Dot(ref diffcopy, ref normalizedVel, out result);

                    diffcopy *= result;
                    Vector2R force = (diff / physicsDivisor);
                    if (shovelling && compoundedMass >= 1)
                    {
                        force /= compoundedMass * 1;
                    }
                    shovelNode.body.velocity = diffcopy + force;
                    //shovelNode.body.ApplyForce(force);
                }
            }

            if (shovelling)
            {
                //if (fc.newGamePadState.Triggers.Right < deadzone && fc.oldGamePadState.Triggers.Right > deadzone)
                if (input.BtnReleased(InputButtons.RightTrigger_Mouse1))
                {
                    shovelling = false;
                    foreach (Node n in shovelLink.targets.ToList())
                    {
                        if (physicsThrow)
                        {
                            n.body.velocity = n.body.effvelocity;
                        }
                        else
                        {
                            Vector2R stickdirection = newstickpos;
                            VMath.NormalizeSafe(ref stickdirection);

                            n.body.velocity = stickdirection * throwSpeed;
                        }
                        n.collision.active = true;
                        shovelLink.targets.Remove(n);
                        n.body.ClearExclusionChecks();
                        n.body.color = n.body.permaColor;
                    }
                    shovelLink.formation.UpdateFormation();
                    shovelLink.active = false;
                    shovelNode.room.AllActiveLinks.Remove(shovelLink);
                    compoundedMass = 0f;
                }
            }
            else
            {
                if (input.BtnClicked(InputButtons.RightTrigger_Mouse1))
                {
                    shovelling = true;
                    ObservableHashSet <Node> capturedNodes = new ObservableHashSet <Node>();
                    int count = 0;
                    Action <Collider, Collider> del = delegate(Collider c1, Collider c2) {
                        if (count >= maxShovelCapacity)
                        {
                            return;
                        }
                        if (c2.parent.dataStore.ContainsKey("shovelnodeparent"))
                        {
                            return;
                        }
                        if (c2.parent.HasComp <Diode>())
                        {
                            return;
                        }
                        if (modePlayers != ModePlayers.GrabBoth && c2.parent.IsPlayer)
                        {
                            if (modePlayers == ModePlayers.GrabNone)
                            {
                                return;
                            }
                            if (modePlayers == ModePlayers.GrabSelf && c2.parent != parent)
                            {
                                return;
                            }
                            if (modePlayers == ModePlayers.GrabOtherPlayers && c2.parent == parent)
                            {
                                return;
                            }
                        }
                        float dist = Vector2R.Distance(c1.pos, c2.pos);
                        if (dist <= scoopReach)
                        {
                            count++;
                            capturedNodes.Add(c2.parent);
                            c2.parent.body.color = parent.body.color;
                        }
                    };
                    shovelNode.room.GridsystemAffect.retrieveOffsetArraysAffect(shovelNode.body, del, scoopReach * 2);
                    shovelLink.targets = capturedNodes;
                    shovelLink.formation.UpdateFormation();
                    shovelLink.active = true;
                    shovelNode.room.AllActiveLinks.Add(shovelLink);
                    compoundedMass = 0f;
                    foreach (Node n in capturedNodes)
                    {
                        n.collision.active = false;
                        compoundedMass    += n.body.mass;
                    }
                }
            }
        }
 public void Add_ShouldAddAnItem()
 {
     var observableHash = new ObservableHashSet<int>();
     observableHash.Add(1);
     Assert.Contains(1, observableHash);
 }