Пример #1
0
        public Nav2dNode(Vector3 worldPos)
        {
            this.worldPos  = worldPos;
            this.neighbors = new C5.HashSet <Nav2dNode>();

            zone = Random.ColorHSV();
        }
Пример #2
0
        protected void CheckEnums(string name, int expectedTypes, string[] expected, string[] notExpected)
        {
            C5.HashSet <string> valsToFind = new C5.HashSet <string>( );
            valsToFind.AddAll(expected);
            C5.HashSet <string> valsNotToFind = new C5.HashSet <string>( );
            valsNotToFind.AddAll(notExpected);

            AssemblyHelper.CheckAssembly(name, expectedTypes,
                                         delegate(TypeDefinition typeDef) { return(typeDef.BaseType.FullName == "System.Enum"); },
                                         delegate(TypeDefinition typeDef)
            {
                // num expected + num unexpected + field storage
                int totalValues = expected.Length + notExpected.Length + 1;
                Assert.AreEqual(totalValues, typeDef.Fields.Count,
                                String.Format("Type should have {0} values.", totalValues));

                foreach (FieldDefinition field in typeDef.Fields)
                {
                    Assert.IsFalse(valsNotToFind.Contains(field.Name), String.Format(
                                       "Did not expect to find event '{0}'.", field.Name));

                    valsToFind.Remove(field.Name);
                }

                Assert.IsFalse(valsToFind.Count > 0, "Failed to find all expected values.");
            });
        }
Пример #3
0
        public static void CheckAssembly(string name, int expectedTypes, string[] expectedMethods, string[] notExpectedMethods,
                                         Predicate <TypeDefinition> isType, Action <TypeDefinition> checkType)
        {
            C5.HashSet <string> methodsToFind = new C5.HashSet <string>( );
            methodsToFind.AddAll(expectedMethods);
            C5.HashSet <string> methodsNotToFind = new C5.HashSet <string>( );
            methodsNotToFind.AddAll(notExpectedMethods);

            CheckAssembly(name, expectedTypes, isType,
                          delegate(TypeDefinition typeDef)
            {
                // make sure we have enough methods...
                Assert.AreEqual(expectedMethods.Length + notExpectedMethods.Length, typeDef.Methods.Count,
                                "Some of the methods for the type are missing.");

                foreach (MethodDefinition method in typeDef.Methods)
                {
                    Assert.IsFalse(methodsNotToFind.Contains(method.Name), String.Format(
                                       "Did not expect to find method '{0}'.", method.Name));

                    methodsToFind.Remove(method.Name);
                }

                if (checkType != null)
                {
                    checkType(typeDef);
                }
            });

            Assert.IsFalse(methodsToFind.Count > 0, "Failed to find all expected methods.");
        }
Пример #4
0
 IEnumerable <MemberReference> getMemberReferences()
 {
     C5.HashSet <MemberReference> memberreferences = new C5.HashSet <MemberReference>();
     foreach (TypeDefinition type in this.GetAllTypeDefinitions())
     {
         foreach (MethodDefinition method in type.Methods)
         {
             if (method.Body != null)
             {
                 foreach (Instruction inst in method.Body.Instructions)
                 {
                     MemberReference memberref = inst.Operand as MemberReference;
                     if (memberref != null)
                     {
                         if (memberref is MethodReference && !(memberref is MethodDefinition || memberref is MethodSpecification || memberref is CallSite) ||
                             memberref is FieldReference && !(memberref is FieldDefinition))
                         {
                             int c = memberreferences.Count;
                             memberreferences.Add(memberref);
                         }
                     }
                 }
             }
         }
     }
     return(memberreferences);
 }
Пример #5
0
		public static void CheckAssembly( string name, int expectedTypes, string[] expectedMethods, string[] notExpectedMethods,
			Predicate<TypeDefinition> isType, Action<TypeDefinition> checkType )
		{
			C5.HashSet<string> methodsToFind = new C5.HashSet<string>( );
			methodsToFind.AddAll( expectedMethods );
			C5.HashSet<string> methodsNotToFind = new C5.HashSet<string>( );
			methodsNotToFind.AddAll( notExpectedMethods );

			CheckAssembly( name, expectedTypes, isType,
				delegate( TypeDefinition typeDef )
				{
					// make sure we have enough methods...
					Assert.AreEqual( expectedMethods.Length + notExpectedMethods.Length, typeDef.Methods.Count,
						"Some of the methods for the type are missing." );

					foreach ( MethodDefinition method in typeDef.Methods )
					{
						Assert.IsFalse( methodsNotToFind.Contains( method.Name ), String.Format(
							"Did not expect to find method '{0}'.", method.Name ) );

						methodsToFind.Remove( method.Name );
					}

					if ( checkType != null )
						checkType( typeDef );
				} );

			Assert.IsFalse( methodsToFind.Count > 0, "Failed to find all expected methods." );
		}
Пример #6
0
		public void CheckNestedTypes( )
		{
			string xml = String.Format(
				@"<?xml version='1.0'?>" +
				@"<Obfuscator>" +
				@"<Var name='InPath' value='{0}' />" +
				@"<Var name='OutPath' value='{1}' />" +
				@"<Module file='$(InPath)\AssemblyWithNestedTypes.dll'>" +
				@"<SkipType name='TestClasses.ClassA/NestedClassA' />" +
				@"</Module>" +
				@"</Obfuscator>", TestHelper.InputPath, TestHelper.OutputPath );

			TestHelper.BuildAndObfuscate( "AssemblyWithNestedTypes", string.Empty, xml );

			C5.HashSet<string> typesToFind = new C5.HashSet<string>( );
			typesToFind.Add( "A.A" );
			typesToFind.Add( "A.A/a" );
			typesToFind.Add( "A.A/NestedClassA" );

			AssemblyHelper.CheckAssembly( "AssemblyWithNestedTypes", 3,
				delegate( TypeDefinition typeDef ) { return true; },
				delegate( TypeDefinition typeDef )
				{
					Assert.IsTrue( typesToFind.Contains( typeDef.ToString( ) ), "Type {0} not expected.", typeDef.ToString( ) );
					typesToFind.Remove( typeDef.ToString( ) );
				} );
			Assert.IsTrue( typesToFind.Count == 0, "Not all types found." );
		}
Пример #7
0
		protected void CheckEnums( string name, int expectedTypes, string[] expected, string[] notExpected )
		{
			C5.HashSet<string> valsToFind = new C5.HashSet<string>( );
			valsToFind.AddAll( expected );
			C5.HashSet<string> valsNotToFind = new C5.HashSet<string>( );
			valsNotToFind.AddAll( notExpected );

			AssemblyHelper.CheckAssembly( name, expectedTypes,
				delegate( TypeDefinition typeDef ) { return typeDef.BaseType.FullName == "System.Enum"; },
				delegate( TypeDefinition typeDef )
				{
					// num expected + num unexpected + field storage
					int totalValues = expected.Length + notExpected.Length + 1;
					Assert.AreEqual( totalValues, typeDef.Fields.Count,
						String.Format( "Type should have {0} values.", totalValues ) );

					foreach ( FieldDefinition field in typeDef.Fields )
					{
						Assert.IsFalse( valsNotToFind.Contains( field.Name ), String.Format(
							"Did not expect to find event '{0}'.", field.Name ) );

						valsToFind.Remove( field.Name );
					}

					Assert.IsFalse( valsToFind.Count > 0, "Failed to find all expected values." );
				} );
		}
Пример #8
0
        public void CheckNestedTypes()
        {
            string xml = String.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Var name='InPath' value='{0}' />" +
                @"<Var name='OutPath' value='{1}' />" +
                @"<Module file='$(InPath)\AssemblyWithNestedTypes.dll'>" +
                @"<SkipType name='TestClasses.ClassA/NestedClassA' />" +
                @"</Module>" +
                @"</Obfuscator>", TestHelper.InputPath, TestHelper.OutputPath);

            TestHelper.BuildAndObfuscate("AssemblyWithNestedTypes", string.Empty, xml);

            C5.HashSet <string> typesToFind = new C5.HashSet <string> ();
            typesToFind.Add("A.A");
            typesToFind.Add("A.A/a");
            typesToFind.Add("A.A/NestedClassA");

            AssemblyHelper.CheckAssembly("AssemblyWithNestedTypes", 1,
                                         delegate(TypeDefinition typeDef) {
                return(true);
            },
                                         delegate(TypeDefinition typeDef) {
                Assert.IsTrue(typesToFind.Contains(typeDef.ToString()), "Type {0} not expected.", typeDef.ToString());
                typesToFind.Remove(typeDef.ToString());
            });
            Assert.IsTrue(typesToFind.Count == 0, "Not all types found.");
        }
Пример #9
0
 public void UnseqequalityComparerViaBuilder2()
 {
     SCG.IEqualityComparer <C5.HashSet <int> > h = EqualityComparer <C5.HashSet <int> > .Default;
     C5.HashSet <int> s = new C5.HashSet <int>();
     s.Add(1);
     s.Add(2);
     s.Add(3);
     Assert.AreEqual(CHC.unsequencedhashcode(1, 2, 3), h.GetHashCode(s));
 }
Пример #10
0
        public static IEnumerable <IPathNode <N> > GetReachableNodes <N>(N start, float maxCost) where N : INode <N>
        {
            C5.IDictionary <N, PathNode <N> > nodeDictionary = new C5.HashDictionary <N, PathNode <N> >();
            C5.IPriorityQueue <PathNode <N> > openSet        = new C5.IntervalHeap <PathNode <N> >(new PathNodeComparer <N>(), C5.MemoryType.Normal);
            C5.ICollection <N>            closedSet          = new C5.HashSet <N>();
            C5.ArrayList <IPathNode <N> > res = new C5.ArrayList <IPathNode <N> >(C5.MemoryType.Normal);


            PathNode <N> curNode = new PathNode <N>(start);

            curNode.g = 0;
            nodeDictionary.Add(start, curNode);
            while (true)
            {
                res.Add(curNode);
                foreach (IEdge <N> edge in curNode.node)
                {
                    N other = edge.GetEnd();
                    if (!closedSet.Contains(other))
                    {
                        PathNode <N> otherNode = null;
                        if (!nodeDictionary.Find(ref other, out otherNode))
                        {
                            otherNode = new PathNode <N>(other);
                            nodeDictionary.Add(other, otherNode);
                        }
                        float newG = edge.GetCost() + curNode.g;
                        if (otherNode.g > newG)
                        {
                            otherNode.g = newG;
                            if (otherNode.queueHandle != null)
                            {
                                openSet.Replace(otherNode.queueHandle, otherNode);
                            }
                            otherNode.prev = curNode;
                        }
                        if (otherNode.queueHandle == null)
                        {
                            C5.IPriorityQueueHandle <PathNode <N> > handle = null;
                            openSet.Add(ref handle, otherNode);
                            otherNode.queueHandle = handle;
                        }
                    }
                }
                if (openSet.IsEmpty)
                {
                    return(res);
                }
                closedSet.Add(curNode.node);
                curNode = openSet.DeleteMin();
                if (curNode.g > maxCost)
                {
                    return(res);
                }
            }
        }
Пример #11
0
        private C5.HashSet <UUID> CollectCreatedAssetIdsFromUserInventories()
        {
            C5.HashSet <UUID> retAssets = new C5.HashSet <UUID>();

            foreach (UUID creatorId in m_allowedCreatorIds)
            {
                this.CollectCreatedAssetIdsFromUserInventory(creatorId, retAssets);
            }

            return(retAssets);
        }
Пример #12
0
        public Mesh(ulong hashCode, int numVerticies, int numTriangles)
        {
            _meshHash = hashCode;

            m_vertices = new Dictionary <Vertex, int>();
            _triIndex  = new C5.HashSet <IndexedTriangle>();

            _meshData = meshCache.Lease(numTriangles);

            if (_meshData == null || _meshData.VertexCapacity < numVerticies || _meshData.TriangleCapacity < numTriangles)
            {
                _meshData = new MeshData(numVerticies, numTriangles);
            }
        }
Пример #13
0
        public Mesh(ulong hashCode, int numVerticies, int numTriangles)
        {
            _meshHash = hashCode;

            m_vertices = new Dictionary<Vertex, int>();
            _triIndex = new C5.HashSet<IndexedTriangle>();

            _meshData = meshCache.Lease(numTriangles);

            if (_meshData == null || _meshData.VertexCapacity < numVerticies || _meshData.TriangleCapacity < numTriangles)
            {
                _meshData = new MeshData(numVerticies, numTriangles);
            }
        }
        public static Dictionary <Point, List <LineSegment> > IntersectionsBentleyOttmann(List <LineSegment> segments)
        {
            var hsSegments = new C5.HashSet <LineSegmentFr>();

            hsSegments.AddAll(segments.Select(s => new LineSegmentFr(
                                                  new PointFr(new Fraction(s.StartPoint.X), new Fraction(s.StartPoint.Y)),
                                                  new PointFr(new Fraction(s.EndPoint.X), new Fraction(s.EndPoint.Y)), true)).ToList());

            Dictionary <PointFr, LineFr> sweepLinesFr;
            var result = IntersectionsBentleyOttmann(hsSegments, out sweepLinesFr);

            return(result.ToDictionary(kvp => new Point(kvp.Key.X.ToDouble(), kvp.Key.Y.ToDouble()),
                                       kvp => kvp.Value.Select(s => new LineSegment(
                                                                   new Point(s.StartPoint.X.ToDouble(), s.StartPoint.Y.ToDouble()),
                                                                   new Point(s.EndPoint.X.ToDouble(), s.EndPoint.Y.ToDouble()))).ToList()));
        }
Пример #15
0
        private void CollectCreatedAssetIdsFromUserInventory(UUID creatorId, C5.HashSet <UUID> retAssets)
        {
            IInventoryProviderSelector selector = ProviderRegistry.Instance.Get <IInventoryProviderSelector>();
            IInventoryStorage          provider = selector.GetProvider(creatorId);

            List <InventoryFolderBase> skel = provider.GetInventorySkeleton(creatorId);

            foreach (InventoryFolderBase folder in skel)
            {
                InventoryFolderBase fullFolder = provider.GetFolder(folder.ID);
                foreach (InventoryItemBase item in fullFolder.Items)
                {
                    if (m_allowedCreatorIds.Contains(item.CreatorIdAsUuid))
                    {
                        retAssets.Add(item.AssetID);
                    }
                }
            }
        }
Пример #16
0
        protected void CheckProperties(string name, int expectedTypes, string[] expected, string[] notExpected)
        {
            C5.HashSet <string> propsToFind = new C5.HashSet <string> ();
            propsToFind.AddAll(expected);
            C5.HashSet <string> propsNotToFind = new C5.HashSet <string> ();
            propsNotToFind.AddAll(notExpected);

            string[] expectedMethods = new string[expected.Length * 2];
            for (int i = 0; i < expected.Length; i++)
            {
                expectedMethods [i * 2 + 0] = "get_" + expected [i];
                expectedMethods [i * 2 + 1] = "set_" + expected [i];
            }

            string[] notExpectedMethods = new string[notExpected.Length * 2];
            for (int i = 0; i < notExpected.Length; i++)
            {
                notExpectedMethods [i * 2 + 0] = "get_" + notExpected [i];
                notExpectedMethods [i * 2 + 1] = "set_" + notExpected [i];
            }

            AssemblyHelper.CheckAssembly(name, expectedTypes, expectedMethods, notExpectedMethods,
                                         delegate(TypeDefinition typeDef) {
                return(true);
            },
                                         delegate(TypeDefinition typeDef) {
                Assert.AreEqual(expected.Length, typeDef.Properties.Count,
                                expected.Length == 1 ? "Type should have 1 property (others dropped by default)." :
                                String.Format("Type should have {0} properties (others dropped by default).", expected.Length));

                foreach (PropertyDefinition prop in typeDef.Properties)
                {
                    Assert.IsFalse(propsNotToFind.Contains(prop.Name), String.Format(
                                       "Did not expect to find property '{0}'.", prop.Name));

                    propsToFind.Remove(prop.Name);
                }

                Assert.IsFalse(propsToFind.Count > 0, "Failed to find all expected properties.");
            });
        }
Пример #17
0
		protected void CheckProperties( string name, int expectedTypes, string[] expected, string[] notExpected )
		{
			C5.HashSet<string> propsToFind = new C5.HashSet<string>( );
			propsToFind.AddAll( expected );
			C5.HashSet<string> propsNotToFind = new C5.HashSet<string>( );
			propsNotToFind.AddAll( notExpected );

			string[] expectedMethods = new string[expected.Length * 2];
			for ( int i = 0; i < expected.Length; i ++ )
			{
				expectedMethods[i * 2 + 0] = "get_" + expected[i];
				expectedMethods[i * 2 + 1] = "set_" + expected[i];
			}

			string[] notExpectedMethods = new string[notExpected.Length * 2];
			for ( int i = 0; i < notExpected.Length; i ++ )
			{
				notExpectedMethods[i * 2 + 0] = "get_" + notExpected[i];
				notExpectedMethods[i * 2 + 1] = "set_" + notExpected[i];
			}

			AssemblyHelper.CheckAssembly( name, expectedTypes, expectedMethods, notExpectedMethods,
				delegate( TypeDefinition typeDef ) { return true; },
				delegate( TypeDefinition typeDef )
				{
					Assert.AreEqual( expected.Length, typeDef.Properties.Count,
						expected.Length == 1 ? "Type should have 1 property (others dropped by default)." :
						String.Format( "Type should have {0} properties (others dropped by default).", expected.Length ) );

					foreach ( PropertyDefinition prop in typeDef.Properties )
					{
						Assert.IsFalse( propsNotToFind.Contains( prop.Name ), String.Format(
							"Did not expect to find property '{0}'.", prop.Name ) );

						propsToFind.Remove( prop.Name );
					}

					Assert.IsFalse( propsToFind.Count > 0, "Failed to find all expected properties." );
				} );
		}
Пример #18
0
        void GetBaseTypes(C5.HashSet <TypeKey> baseTypes, TypeDefinition type)
        {
            // check the interfaces
            foreach (TypeReference ifaceRef in type.Interfaces)
            {
                TypeDefinition iface = project.GetTypeDefinition(ifaceRef);
                if (iface != null)
                {
                    GetBaseTypes(baseTypes, iface);
                    baseTypes.Add(new TypeKey(iface));
                }
            }

            // check the base type unless it isn't in the project, or we don't have one
            TypeDefinition baseType = project.GetTypeDefinition(type.BaseType);

            if (baseType != null && baseType.FullName != "System.Object")
            {
                GetBaseTypes(baseTypes, baseType);
                baseTypes.Add(new TypeKey(baseType));
            }
        }
        public static Dictionary <Point, List <LineSegment> > IntersectionsBentleyOttmann(List <LineSegment> segments, out LineSegment[] sweepLines)
        {
            var hsSegments = new C5.HashSet <LineSegmentFr>();

            hsSegments.AddAll(segments.Select(s => new LineSegmentFr(
                                                  new PointFr(new Fraction(s.StartPoint.X), new Fraction(s.StartPoint.Y)),
                                                  new PointFr(new Fraction(s.EndPoint.X), new Fraction(s.EndPoint.Y)), true)).ToList());

            var result = IntersectionsBentleyOttmann(hsSegments, out var sweepLinesFr);

            var endpoints = result.Values.SelectMany(s => s).Select(s => new [] { s.StartPoint, s.EndPoint })
                            .SelectMany(p => p).ToList();
            var minY = endpoints.MinBy(p => p.Y).First().Y;
            var maxY = endpoints.MaxBy(p => p.Y).First().Y;

            sweepLines = sweepLinesFr.Keys.Select(key => new LineSegment(
                                                      new Point(key.X.ToDouble(), minY.ToDouble()),
                                                      new Point(key.X.ToDouble(), maxY.ToDouble()))).ToArray();

            return(result.ToDictionary(kvp => new Point(kvp.Key.X.ToDouble(), kvp.Key.Y.ToDouble()),
                                       kvp => kvp.Value.Select(s => new LineSegment(
                                                                   new Point(s.StartPoint.X.ToDouble(), s.StartPoint.Y.ToDouble()),
                                                                   new Point(s.EndPoint.X.ToDouble(), s.EndPoint.Y.ToDouble()))).ToList()));
        }
Пример #20
0
 public void Dispose()
 {
     _results.Clear();
     _results = null;
 }
Пример #21
0
        /// <summary>
        /// Archive the region requested.
        /// </summary>
        /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
        public void ArchiveRegion()
        {
            Dictionary <UUID, int> assetUuids = new Dictionary <UUID, int>();

            List <EntityBase>       entities     = m_scene.GetEntities();
            List <SceneObjectGroup> sceneObjects = new List <SceneObjectGroup>();

            // Filter entities so that we only have scene objects.
            // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
            // end up having to do this
            foreach (EntityBase entity in entities)
            {
                if (entity is SceneObjectGroup)
                {
                    SceneObjectGroup sceneObject = (SceneObjectGroup)entity;

                    if (MustCheckCreatorIds)
                    {
                        bool failedCreatorCheck = false;
                        foreach (SceneObjectPart part in sceneObject.GetParts())
                        {
                            if (!ExportIsAllowed(part.CreatorID))
                            {
                                failedCreatorCheck = true;
                                break;
                            }
                        }

                        if (failedCreatorCheck)
                        {
                            continue;
                        }
                    }

                    if (!sceneObject.IsDeleted && !sceneObject.IsAttachment)
                    {
                        sceneObjects.Add(sceneObject);
                    }
                }
            }

            if (m_storeAssets)
            {
                UuidGatherer assetGatherer = new UuidGatherer(m_scene.CommsManager.AssetCache);

                foreach (SceneObjectGroup sceneObject in sceneObjects)
                {
                    assetGatherer.GatherAssetUuids(sceneObject, assetUuids);
                }
            }

            // Make sure that we also request terrain texture assets
            RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings;

            if (m_storeAssets)
            {
                if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
                {
                    assetUuids[regionSettings.TerrainTexture1] = 1;
                }

                if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
                {
                    assetUuids[regionSettings.TerrainTexture2] = 1;
                }

                if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
                {
                    assetUuids[regionSettings.TerrainTexture3] = 1;
                }

                if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
                {
                    assetUuids[regionSettings.TerrainTexture4] = 1;
                }
            }

            if (MustCheckCreatorIds)
            {
                int originalCount = assetUuids.Count;

                m_log.DebugFormat(
                    "[ARCHIVER]: Filtering {0} asset IDs for {1} allowed creators",
                    originalCount, m_allowedCreatorIds.Count);

                C5.HashSet <UUID> assetsCreatedByAllowedUsers = this.CollectCreatedAssetIdsFromUserInventories();

                IEnumerable <UUID> uuids = new List <UUID>(assetUuids.Keys);
                assetUuids.Clear();

                foreach (UUID assetId in uuids)
                {
                    if (assetsCreatedByAllowedUsers.Contains(assetId))
                    {
                        assetUuids.Add(assetId, 1);
                    }
                }

                m_log.DebugFormat(
                    "[ARCHIVER]: Allowing export of {0} of {1} assets",
                    assetUuids.Count, originalCount);
            }

            m_log.DebugFormat(
                "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets",
                sceneObjects.Count, assetUuids.Count);

            TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream);

            // Asynchronously request all the assets required to perform this archive operation
            ArchiveWriteRequestExecution awre
                = new ArchiveWriteRequestExecution(
                      sceneObjects,
                      m_scene.RequestModuleInterface <ITerrainModule>(),
                      m_scene.RequestModuleInterface <IRegionSerializerModule>(),
                      m_scene,
                      archiveWriter,
                      m_requestId);

            new AssetsRequest(
                new AssetsArchiver(archiveWriter), assetUuids.Keys,
                m_scene.CommsManager.AssetCache, awre.ReceivedAllAssets).Execute();
        }
Пример #22
0
        protected void CheckEvents(string name, int expectedTypes, string[] expected, string[] notExpected)
        {
            C5.HashSet <string> eventsToFind = new C5.HashSet <string>( );
            eventsToFind.AddAll(expected);
            C5.HashSet <string> eventsNotToFind = new C5.HashSet <string>( );
            eventsNotToFind.AddAll(notExpected);

            C5.HashSet <string> methodsToFind = new C5.HashSet <string>( );
            for (int i = 0; i < expected.Length; i++)
            {
                methodsToFind.Add("add_" + expected[i]);
                methodsToFind.Add("remove_" + expected[i]);
            }

            C5.HashSet <string> methodsNotToFind = new C5.HashSet <string>( );
            for (int i = 0; i < notExpected.Length; i++)
            {
                methodsNotToFind.Add("add_" + notExpected[i]);
                methodsNotToFind.Add("remove_" + notExpected[i]);
            }

            bool foundDelType = false;

            AssemblyHelper.CheckAssembly(name, expectedTypes,
                                         delegate(TypeDefinition typeDef)
            {
                if (typeDef.BaseType.FullName == "System.MulticastDelegate")
                {
                    foundDelType = true;
                    return(false);
                }
                else
                {
                    return(true);
                }
            },
                                         delegate(TypeDefinition typeDef)
            {
                // make sure we have enough methods...
                // 2 methods / event + a method to fire them
                Assert.AreEqual(methodsToFind.Count + methodsNotToFind.Count + 1, typeDef.Methods.Count,
                                "Some of the methods for the type are missing.");

                foreach (MethodDefinition method in typeDef.Methods)
                {
                    Assert.IsFalse(methodsNotToFind.Contains(method.Name), String.Format(
                                       "Did not expect to find method '{0}'.", method.Name));

                    methodsToFind.Remove(method.Name);
                }

                Assert.AreEqual(expected.Length, typeDef.Events.Count,
                                expected.Length == 1 ? "Type should have 1 event (others dropped by default)." :
                                String.Format("Type should have {0} events (others dropped by default).", expected.Length));

                foreach (EventDefinition evt in typeDef.Events)
                {
                    Assert.IsFalse(eventsNotToFind.Contains(evt.Name), String.Format(
                                       "Did not expect to find event '{0}'.", evt.Name));

                    eventsToFind.Remove(evt.Name);
                }

                Assert.IsFalse(methodsToFind.Count > 0, "Failed to find all expected methods.");
                Assert.IsFalse(eventsToFind.Count > 0, "Failed to find all expected events.");
            });

            Assert.IsTrue(foundDelType, "Should have found the delegate type.");
        }
Пример #23
0
        static void Main(string[] args)
        {
            //string outputFileName = @"e:\\proj\\summary.tsv";
            //int minN = 100_000;
            //int maxN = 1_000_000;

            //int incrementNBy = 10_000;
            string errMsg = PerfUtil.GetCmdLineParams_OutputFileAndMinMaxIncN(args, out int minN, out int maxN, out int incrementNBy, out string outputFileName);

            int nCount = ((maxN - minN) / incrementNBy) + 1;

            int[] nArray = new int[nCount];

            int idx = 0;

            for (int n = minN; n <= maxN; n += incrementNBy, idx++)
            {
                nArray[idx] = n;
            }

            const int LoopUnrollCount       = 1;
            const int IterartionCount       = 512;
            const int IterartionWarmupCount = 16;

            long[] ticksH       = new long[nArray.Length * IterartionCount * LoopUnrollCount];
            int    ticksIdxForH = 0;

            long[] ticksF       = new long[nArray.Length * IterartionCount * LoopUnrollCount];
            int    ticksIdxForF = 0;

            long[] ticksC       = new long[nArray.Length * IterartionCount * LoopUnrollCount];
            int    ticksIdxForC = 0;

            long startTicks;

            double overheadTicks = PerfUtil.GetTimestampOverheadInNanoSeconds();

            int[] a;
            int[] c;

            SCG.HashSet <int> h = new HashSet <int>();
            FastHashSet <int> f = new FastHashSet <int>();

            C5.HashSet <int> c5 = new C5.HashSet <int>();

            HashSetBench.BenchUtil.PopulateCollections25_25_50PctUnique(maxN, out a, out c, h, f, c5);

            // not sure if we should run bechmark 1 and then benchmark 2 separately so that the presence of the one doesn't effect the other???
            // in practice they will probably not be run together one after the other

            PerfUtil.DoGCCollect();

            int N;

            for (int j = 0; j < nArray.Length; j++)
            {
                N = nArray[j];

                // not really sure what running the warmup really does - it can put things in the cache that maybe shouldn't be there because they won't be in a real application???
                // still, if we execute the same code with the same data in a loop alot of times, this will populate the cache unrealistically
                // also if we do a warmup, the jit times will be removed, but does this represent reality - jit times do happen in real running code???

                for (int iterationIdx = 0; iterationIdx < IterartionWarmupCount; iterationIdx++)
                {
                    // SCG_Contains
                    for (int i = 0; i < N; i++)
                    {
                        h.Contains(c[i]);
                    }

                    // Fast_Contains
                    for (int i = 0; i < N; i++)
                    {
                        f.Contains(c[i]);
                    }

                    for (int i = 0; i < N; i++)
                    {
                        c5.Contains(c[i]);
                    }
                }

                for (int iterationIdx = 0; iterationIdx < IterartionCount; iterationIdx++)
                {
                    // to minimize the effects of the loop code on the count, unroll each bechmark 2 times
                    // also alternate randomly between the order of these to minimize any effects of order
                    // not sure what effects loop unrolling has since that part isn't contained in the stopwatch time
                    // still there might be some residual effects on CPU registers? - not really sure

                    // 1

                    // there is some overhead that should be removed - it is returning from GetTimestamp and setting startTicks and afterwards calling GetTimestamp until the point where the return value is obtained
                    // we should determine this overhead by calling
                    startTicks = Stopwatch.GetTimestamp();
                    for (int i = 0; i < N; i++)
                    {
                        h.Contains(c[i]);
                    }
                    ticksH[ticksIdxForH++] = Stopwatch.GetTimestamp() - startTicks;

                    startTicks = Stopwatch.GetTimestamp();
                    for (int i = 0; i < N; i++)
                    {
                        f.Contains(c[i]);
                    }
                    ticksF[ticksIdxForF++] = Stopwatch.GetTimestamp() - startTicks;

                    startTicks = Stopwatch.GetTimestamp();
                    for (int i = 0; i < N; i++)
                    {
                        c5.Contains(c[i]);
                    }
                    ticksC[ticksIdxForC++] = Stopwatch.GetTimestamp() - startTicks;
                }
            }

            // summarize and output the data

            BenchmarkSummaries summaries = new BenchmarkSummaries();

            summaries.AddNSummaryList(NSummary.CreateNSummaryListForBenchmark(overheadTicks, nArray, IterartionCount * LoopUnrollCount, ticksH), "SCG_Contains");

            summaries.AddNSummaryList(NSummary.CreateNSummaryListForBenchmark(overheadTicks, nArray, IterartionCount * LoopUnrollCount, ticksF), "Fast_Contains");

            summaries.AddNSummaryList(NSummary.CreateNSummaryListForBenchmark(overheadTicks, nArray, IterartionCount * LoopUnrollCount, ticksC), "C5_Contains");

            summaries.OutputSummariesToFile(outputFileName, "SCG_Contains");
        }
Пример #24
0
 public UpdateQueue()
 {
     m_queue = new Queue <SceneObjectPart>();
     m_ids   = new C5.HashSet <uint>();
 }
Пример #25
0
        static void Main(string[] args)
        {
            // cmd line params variables
            string dbConnStr = null;
            int runID = 0;
            int benchmarkMethodID = 0;
            int n;
            int maxN;

            try
            {
                DateTime startTime = DateTime.Now;
                //Console.WriteLine($"Args Count:" + args.Length.ToString());
                //foreach (string s in args)
                //{
                //	Console.WriteLine(s);
                //}
                //Console.ReadKey();

                string errMsg = PerfUtil.GetCmdLineParams_DbNAndMaxN(args, out dbConnStr, out runID, out benchmarkMethodID, out n, out maxN);
                //if (errMsg != null)
                //{
                //	Console.WriteLine(errMsg);
                //}
                //Console.WriteLine($"Args: {dbConnStr}; {runID.ToString()}; {benchmarkMethodID.ToString()}; {n.ToString()}; {maxN.ToString()}");
                //Console.ReadKey();

                int[] a;
                int[] c;

                C5.HashSet<int> set = new C5.HashSet<int>();

                BenchUtil.PopulateArrays25_25_50PctUnique(maxN, out a, out c);

                // in a real world scenario, we will have probably have recently added the items into the set, so no need to try to clear the cache or anything
                for (int i = 0; i < maxN; i++)
                {
                    set.Add(a[i]);
                }

                double overheadNanoSecs = PerfUtil.GetTimestampOverheadInNanoSeconds();

                PerfUtil.DoGCCollect();

                int iterations = 1;
                long startTicks;
                long endTicks;
                double ticks;

                // this is enough to jit things and not put everything in the cache
                bool isContained = set.Contains(0);

                if (maxN <= 1000)
                {
                    iterations = 1;

                    // there amount of time taken for these is too small to measure just one iteration - so we measure multiple iterations in a loop and get the time for these
                    // the mean time is this total time / iterations

                    startTicks = Stopwatch.GetTimestamp();

                    for (int i = 0; i < maxN; i++)
                    {
                        set.Contains(c[i]);
                    }

                    endTicks = Stopwatch.GetTimestamp();

                    ticks = ((endTicks - startTicks) * n) / (double)maxN;
                }
                else
                {
                    iterations = 1;

                    startTicks = Stopwatch.GetTimestamp();
                    for (int i = 0; i < n; i++) // loop overhead is ok because we assume there will be some loop in real-world scenario
                    {
                        set.Contains(c[i]);
                    }
                    endTicks = Stopwatch.GetTimestamp();

                    ticks = (double)(endTicks - startTicks);
                }

                double nanoSecs = PerfUtil.GetNanoSecondsFromTicks(ticks, Stopwatch.Frequency) - overheadNanoSecs;

                PerfDb.InsertMeasurement(dbConnStr, runID, benchmarkMethodID, n, iterations, nanoSecs, startTime, DateTime.Now);
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                if (!string.IsNullOrEmpty(dbConnStr))
                {
                    // write error to db
                    PerfDb.InsertRunError(dbConnStr, runID, benchmarkMethodID, ex);
                }
                else
                {
                    // log error to file
                }
            }
        }
 public IncomingPacketHistoryCollection(int capacity)
 {
     this.m_capacity = capacity;
     m_items = new uint[capacity];
     m_hashSet = new C5.HashSet<uint>();
 }
        /// <summary>
        /// Archive the region requested.
        /// </summary>
        /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
        public void ArchiveRegion()
        {
            Dictionary <UUID, int> assetUuids = new Dictionary <UUID, int>();

            List <EntityBase>       entities     = m_scene.GetEntities();
            List <SceneObjectGroup> sceneObjects = new List <SceneObjectGroup>();
            List <UUID>             userlist     = new List <UUID>();

            // Filter entities so that we only have scene objects.
            // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
            // end up having to do this
            foreach (EntityBase entity in entities)
            {
                if (entity is SceneObjectGroup)
                {
                    SceneObjectGroup sceneObject = (SceneObjectGroup)entity;

                    // If storing assets, assume cross-grid and include the user list file
                    if (m_storeAssets)
                    {
                        AddObjectUsersToList(userlist, sceneObject);
                    }
                    if (MustCheckCreatorIds)
                    {
                        bool failedCreatorCheck = false;
                        foreach (SceneObjectPart part in sceneObject.GetParts())
                        {
                            if (!ExportIsAllowed(part.CreatorID))
                            {
                                failedCreatorCheck = true;
                                break;
                            }
                        }

                        if (failedCreatorCheck)
                        {
                            continue;
                        }
                    }

                    if (!sceneObject.IsDeleted && !sceneObject.IsAttachment)
                    {
                        sceneObjects.Add(sceneObject);
                    }
                }
            }

            if (m_storeAssets)
            {
                UuidGatherer assetGatherer = new UuidGatherer(m_scene.CommsManager.AssetCache);

                foreach (SceneObjectGroup sceneObject in sceneObjects)
                {
                    assetGatherer.GatherAssetUuids(sceneObject, assetUuids);
                }
            }

            // Make sure that we also request terrain texture assets
            RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings;

            if (m_storeAssets)
            {
                if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
                {
                    assetUuids[regionSettings.TerrainTexture1] = 1;
                }

                if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
                {
                    assetUuids[regionSettings.TerrainTexture2] = 1;
                }

                if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
                {
                    assetUuids[regionSettings.TerrainTexture3] = 1;
                }

                if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
                {
                    assetUuids[regionSettings.TerrainTexture4] = 1;
                }
            }

            if (MustCheckCreatorIds)
            {
                int originalCount = assetUuids.Count;

                m_log.DebugFormat(
                    "[ARCHIVER]: Filtering {0} asset IDs for {1} allowed creators",
                    originalCount, m_allowedCreatorIds.Count);

                C5.HashSet <UUID> assetsCreatedByAllowedUsers = this.CollectCreatedAssetIdsFromUserInventories();

                IEnumerable <UUID> uuids = new List <UUID>(assetUuids.Keys);
                assetUuids.Clear();

                foreach (UUID assetId in uuids)
                {
                    if (assetsCreatedByAllowedUsers.Contains(assetId))
                    {
                        assetUuids.Add(assetId, 1);
                    }
                }

                m_log.DebugFormat(
                    "[ARCHIVER]: Allowing export of {0} of {1} assets",
                    assetUuids.Count, originalCount);
            }

            m_log.DebugFormat(
                "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets",
                sceneObjects.Count, assetUuids.Count);

            TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream);

            // Asynchronously request all the assets required to perform this archive operation
            ArchiveWriteRequestExecution awre
                = new ArchiveWriteRequestExecution(
                      sceneObjects,
                      m_scene.RequestModuleInterface <ITerrainModule>(),
                      m_scene.RequestModuleInterface <IRegionSerializerModule>(),
                      m_scene,
                      archiveWriter,
                      m_requestId);

            // Write out archive.xml control file first
            archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, awre.CreateControlFile(assetUuids.Count > 0));
            m_log.InfoFormat("[ARCHIVER]: Added {0} control file to archive.", ArchiveConstants.CONTROL_FILE_PATH);

            // Now include the user list file (only if assets are being saved and it produced a list).
            if (userlist.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (UUID id in userlist)
                {
                    String name = m_scene.CommsManager.UserService.Key2Name(id, false);
                    if (!String.IsNullOrWhiteSpace(name))
                    {
                        sb.AppendFormat("{0} {1}{2}", id, name, Environment.NewLine);
                    }
                }
                String userlistContents = sb.ToString();
                if (!String.IsNullOrWhiteSpace(userlistContents))
                {
                    archiveWriter.WriteFile(ArchiveConstants.USERLIST_FILE_PATH, userlistContents);
                    m_log.InfoFormat("[ARCHIVER]: Added {0} file to archive.", ArchiveConstants.USERLIST_FILE_PATH);
                }
            }

            new AssetsRequest(
                new AssetsArchiver(archiveWriter, m_scene), assetUuids.Keys,
                m_scene.CommsManager.AssetCache, awre.ReceivedAllAssets).Execute();
        }
Пример #28
0
 TypeKey[] GetBaseTypes( TypeDefinition type )
 {
     C5.HashSet<TypeKey> baseTypes = new C5.HashSet<TypeKey>( );
     GetBaseTypes( baseTypes, type );
     return baseTypes.ToArray( );
 }
Пример #29
0
 public void C5_HashSet() => _ = new C5.HashSet <Int32>();
Пример #30
0
 ///<summary>Gets a set of facet names</summary>
 ///<returns> set of facet names </returns>
 public virtual IEnumerable<string> GetFacetNames()
 {
     Dictionary<string, FacetHandler>.KeyCollection runtimeFacetNames = runtimeFacetHandlerMap.Keys;
     IEnumerable<string> installedFacetNames = reader.GetFacetNames();
     if (runtimeFacetNames.Count > 0)
     {
         C5.HashSet<string> names = new C5.HashSet<string>();
         names.AddAll(reader.GetFacetNames());
         names.AddAll(runtimeFacetHandlerMap.Keys);
         return names;
     }
     else
     {
         return installedFacetNames;
     }
 }
Пример #31
0
        private void PurgeFolderInternal(InventoryFolderBase folder, long timeStamp)
        {
            //block all deletion requests for a folder with a 0 id
            if (folder.ID == UUID.Zero)
            {
                throw new UnrecoverableInventoryStorageException("Refusing to allow the deletion of the inventory ZERO root folder");
            }

            Dictionary<byte[], Dictionary<string, List<Mutation>>> muts = new Dictionary<byte[], Dictionary<string, List<Mutation>>>();

            byte[] folderIdBytes = ByteEncoderHelper.GuidEncoder.ToByteArray(folder.ID.Guid);
            byte[] parentFolderIdBytes = ByteEncoderHelper.GuidEncoder.ToByteArray(folder.ParentID.Guid);

            //to purge a folder, we have to find all subfolders and items inside a folder
            //for each of the sub folders folders they choose, we need to recurse into all
            //sub-sub folders and grab out the items and folders. Once we have all of them
            //to the last leaf level we do simple removes on all the items and folders
            List<UUID> allFolders = new List<UUID>();
            List<UUID> allItems = new List<UUID>();
            C5.HashSet<UUID> rootItems = new C5.HashSet<UUID>();
            C5.HashSet<UUID> rootFolders = new C5.HashSet<UUID>();

            StringBuilder debugFolderList = new StringBuilder();
            this.RecursiveCollectSubfoldersAndItems(folder.ID, folder.Owner, allFolders, allItems, rootItems, rootFolders, true, null, debugFolderList);

            this.DebugFolderPurge("PurgeFolderInternal", folder, debugFolderList);

            List<byte[]> allFolderIdBytes = new List<byte[]>();
            foreach (UUID fid in allFolders)
            {
                allFolderIdBytes.Add(ByteEncoderHelper.GuidEncoder.ToByteArray(fid.Guid));
            }

            List<byte[]> allItemIdBytes = new List<byte[]>();
            List<byte[]> rootItemIdBytes = new List<byte[]>();
            foreach (UUID iid in allItems)
            {
                byte[] itemIdBytes = ByteEncoderHelper.GuidEncoder.ToByteArray(iid.Guid);

                allItemIdBytes.Add(itemIdBytes);

                if (rootItems.Contains(iid))
                {
                    rootItemIdBytes.Add(itemIdBytes);
                }
            }

            //we have all the contents, so delete the actual folders and their versions...
            //this will wipe out the folders and in turn all items in subfolders
            byte[] ownerIdBytes = ByteEncoderHelper.GuidEncoder.ToByteArray(folder.Owner.Guid);
            this.GetFolderDeletionMutations(ownerIdBytes, allFolderIdBytes, timeStamp, muts);
            //then we delete this actual folder
            this.GetSingleFolderDeletionMutations(ownerIdBytes, folderIdBytes, timeStamp, muts);
            //and remove the subfolder reference from this folders parent
            this.GetSubfolderEntryDeletionMutations(folderIdBytes, parentFolderIdBytes, timeStamp, muts);

            //delete the ItemParents folder references for the removed items...
            foreach (byte[] itemId in allItemIdBytes)
            {
                this.GetItemParentDeletionMutations(itemId, timeStamp, muts);
            }


            //increment the version of the parent of the purged folder
            if (folder.ParentID != UUID.Zero)
            {
                this.GetFolderVersionIncrementMutations(muts, parentFolderIdBytes);
            }

            ICluster cluster = AquilesHelper.RetrieveCluster(_clusterName);
            cluster.Execute(new ExecutionBlock(delegate(Apache.Cassandra.Cassandra.Client client)
            {
                client.batch_mutate(muts, DEFAULT_CONSISTENCY_LEVEL);

                return null;

            }), KEYSPACE);
        }
Пример #32
0
		IEnumerable<MemberReference> getMemberReferences()
		{
			C5.HashSet<MemberReference> memberreferences = new C5.HashSet<MemberReference>();
			foreach (TypeDefinition type in this.GetAllTypeDefinitions())
			{
				foreach (MethodDefinition method in type.Methods)
				{
					if (method.Body != null)
					{
						foreach (Instruction inst in method.Body.Instructions)
						{
							MemberReference memberref = inst.Operand as MemberReference;
							if (memberref != null)
							{
								if (memberref is MethodReference && !(memberref is MethodDefinition || memberref is MethodSpecification || memberref is CallSite)
									|| memberref is FieldReference && !(memberref is FieldDefinition))
								{
									int c = memberreferences.Count;
									memberreferences.Add(memberref);
								}
							}
						}
					}
				}
			}
			return memberreferences;
		}
Пример #33
0
 public HashedResultSet()
 {
     _results = new C5.HashSet <T>(new HashEqualityComparer <T>());
 }
Пример #34
0
		/// <summary>
		/// Called by project to finish initializing the assembly.
		/// </summary>
		internal void Init()
		{
			unrenamedReferences = new List<MemberReference>();
			foreach (MemberReference member in getMemberReferences())
			{
				MethodReference mr = member as MethodReference;
				FieldReference fr = member as FieldReference;
				if (project.Contains(member.DeclaringType))
					unrenamedReferences.Add(member);
			}

			C5.HashSet<TypeReference> typerefs = new C5.HashSet<TypeReference>();
			foreach (TypeReference type in definition.MainModule.GetTypeReferences())
			{
				if (type.FullName == "<Module>")
					continue;

				if (project.Contains(type))
					typerefs.Add(type);
			}

			// Type references in CustomAttributes
			List<CustomAttribute> customattributes = new List<CustomAttribute>();
			customattributes.AddRange(this.Definition.CustomAttributes);
			foreach (TypeDefinition type in GetAllTypeDefinitions())
			{

				customattributes.AddRange(type.CustomAttributes);
				foreach (MethodDefinition methoddef in type.Methods)
					customattributes.AddRange(methoddef.CustomAttributes);
				foreach (FieldDefinition fielddef in type.Fields)
					customattributes.AddRange(fielddef.CustomAttributes);
				foreach (EventDefinition eventdef in type.Events)
					customattributes.AddRange(eventdef.CustomAttributes);
				foreach (PropertyDefinition propertydef in type.Properties)
					customattributes.AddRange(propertydef.CustomAttributes);

				foreach (CustomAttribute customattribute in customattributes)
				{
					// Check Constructor and named parameter for argument of type "System.Type". i.e. typeof()
					List<CustomAttributeArgument> customattributearguments = new List<CustomAttributeArgument>();
					customattributearguments.AddRange(customattribute.ConstructorArguments);
					foreach (CustomAttributeNamedArgument namedargument in customattribute.Properties)
						customattributearguments.Add(namedargument.Argument);

					foreach (CustomAttributeArgument ca in customattributearguments)
					{
						if (ca.Type.FullName == "System.Type")
							typerefs.Add((TypeReference)ca.Value);
					}
				}
				customattributes.Clear();
			}

			unrenamedTypeReferences = new List<TypeReference>(typerefs);

			initialized = true;
		}
        private C5.HashSet<UUID> CollectCreatedAssetIdsFromUserInventories()
        {
            C5.HashSet<UUID> retAssets = new C5.HashSet<UUID>();

            foreach (UUID creatorId in m_allowedCreatorIds)
            {
                this.CollectCreatedAssetIdsFromUserInventory(creatorId, retAssets);
            }

            return retAssets;
        }
Пример #36
0
        public static IEnumerable <IPathNode <N> > GetShortestPath <N>(N start, N goal, IHeuristic <N> heuristic) where N : INode <N>
        {
            C5.IDictionary <N, PathNode <N> > nodeDictionary = new C5.HashDictionary <N, PathNode <N> >();
            C5.IPriorityQueue <PathNode <N> > openSet        = new C5.IntervalHeap <PathNode <N> >(new PathNodeComparer <N>());
            C5.ICollection <N> closedSet = new C5.HashSet <N>();

            PathNode <N> curNode = new PathNode <N>(start);

            curNode.g = 0;
            nodeDictionary.Add(start, curNode);
            while (true)
            {
                foreach (IEdge <N> edge in curNode.Node)
                {
                    N other = edge.GetEnd();
                    if (!closedSet.Contains(other))
                    {
                        PathNode <N> otherNode = null;
                        if (!nodeDictionary.Find(ref other, out otherNode))
                        {
                            otherNode = new PathNode <N>(other);
                            nodeDictionary.Add(other, otherNode);
                        }
                        float newG = edge.GetCost() + curNode.g;
                        if (otherNode.g > newG)
                        {
                            otherNode.g = newG;
                            if (otherNode.queueHandle != null)
                            {
                                openSet.Replace(otherNode.queueHandle, otherNode);
                            }
                            otherNode.prev = curNode;
                        }
                        if (otherNode.queueHandle == null)
                        {
                            otherNode.h = heuristic.MinDist(other, goal);
                            C5.IPriorityQueueHandle <PathNode <N> > handle = null;
                            openSet.Add(ref handle, otherNode);
                            otherNode.queueHandle = handle;
                        }
                    }
                }
                if (openSet.IsEmpty)
                {
                    return(null);
                }
                closedSet.Add(curNode.Node);
                curNode = openSet.DeleteMin();
                if (curNode.Node.Equals(goal))
                {
                    C5.ArrayList <IPathNode <N> > res = new C5.ArrayList <IPathNode <N> >();
                    do
                    {
                        res.Add(curNode);
                        curNode = curNode.prev;
                    } while (curNode != null);

                    res.Reverse();
                    return(res);
                }
            }
        }
Пример #37
0
        protected internal void DelinkObjects(IClientAPI remoteClient, List<uint> primIds, bool sendEvents)
        {
            List<SceneObjectPart> childParts = new List<SceneObjectPart>();
            List<SceneObjectPart> rootParts = new List<SceneObjectPart>();
            List<SceneObjectGroup> affectedGroups = new List<SceneObjectGroup>();
            C5.HashSet<uint> allAffectedIds = new C5.HashSet<uint>();

            lock (m_dictionary_lock)
            {
                // Look them all up in one go, since that is comparatively expensive
                //
                foreach (uint primID in primIds)
                {
                    SceneObjectPart part = this.GetSceneObjectPart(primID);
                    if (part != null)
                    {
                        if (!m_parentScene.Permissions.CanEditObject(part.ParentGroup.RootPart.UUID, remoteClient.AgentId))
                            continue;
                        if ((part.ParentGroup.RootPart.OwnerMask & (uint)PermissionMask.Modify) != (uint)PermissionMask.Modify)
                            continue;
                        if (part.LinkNum < 2) // Root or single
                            rootParts.Add(part);
                        else
                            childParts.Add(part);

                        SceneObjectGroup group = part.ParentGroup;
                        if (!affectedGroups.Contains(group))
                            affectedGroups.Add(group);

                        allAffectedIds.Add(part.LocalId);
                        allAffectedIds.Add(group.LocalId);
                    }
                    else
                    {
                        m_log.ErrorFormat("Viewer requested unlink of nonexistent part {0}", primID);
                    }
                }
            }

            using (SceneTransaction transaction = _transactionMgr.BeginTransaction(allAffectedIds))
            {
                foreach (SceneObjectPart child in childParts)
                {
                    // Unlink all child parts from their groups
                    //
                    child.ParentGroup.DelinkFromGroup(child, sendEvents, false);
                }

                foreach (SceneObjectPart root in rootParts)
                {
                    // In most cases, this will run only one time, and the prim
                    // will be a solo prim
                    // However, editing linked parts and unlinking may be different
                    //
                    SceneObjectGroup group = root.ParentGroup;
                    List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Children.Values);
                    int numChildren = group.Children.Count;

                    // If there are prims left in a link set, but the root is
                    // slated for unlink, we need to do this
                    //
                    if (numChildren != 1)
                    {
                        // Unlink the remaining set
                        //
                        bool sendEventsToRemainder = true;
                        if (numChildren > 1)
                            sendEventsToRemainder = false;

                        foreach (SceneObjectPart p in newSet)
                        {
                            if (p != group.RootPart)
                                group.DelinkFromGroup(p, sendEventsToRemainder, false);
                        }

                        // If there is more than one prim remaining, we
                        // need to re-link
                        //
                        if (numChildren > 2)
                        {
                            // Remove old root
                            //
                            if (newSet.Contains(root))
                                newSet.Remove(root);

                            // Preserve link ordering
                            //
                            newSet.Sort(delegate(SceneObjectPart a, SceneObjectPart b)
                            {
                                return a.LinkNum.CompareTo(b.LinkNum);
                            });

                            // Determine new root
                            //
                            SceneObjectPart newRoot = newSet[0];
                            newSet.RemoveAt(0);

                            List<uint> linkIDs = new List<uint>();

                            foreach (SceneObjectPart newChild in newSet)
                            {
                                linkIDs.Add(newChild.LocalId);
                            }

                            LinkObjects(remoteClient, newRoot.LocalId, linkIDs);
                            if (!affectedGroups.Contains(newRoot.ParentGroup))
                                affectedGroups.Add(newRoot.ParentGroup);
                        }
                    }
                }

                // Finally, trigger events in the roots
                //
                foreach (SceneObjectGroup g in affectedGroups)
                {
                    g.TriggerScriptChangedEvent(Changed.LINK);
                    g.ScheduleGroupForFullUpdate();
                }

                //m_log.DebugFormat("Delink finished for {0} prims", primIds.Count);
            }
        }
Пример #38
0
 public IncomingPacketHistoryCollection(int capacity)
 {
     this.m_capacity = capacity;
     m_items         = new uint[capacity];
     m_hashSet       = new C5.HashSet <uint>();
 }
Пример #39
0
        public static void PopulateCollections25_25_50PctUnique(int maxN, out int[] uniqueArray, out int[] mixedArray,
                                                                SCG.HashSet <int> h, FastHashSet <int> f = null, C5.HashSet <int> c5 = null, SCG.SortedSet <int> sortedSet = null, SCG.List <int> lst = null)
        {
            uniqueArray = new int[maxN];
            mixedArray  = new int[maxN];

            Random rand = new Random(89);

            BenchUtil.PopulateIntArray(uniqueArray, rand, int.MinValue, int.MaxValue, 1.0); // a array should have 100% unique values

            int uniqueValuesCount = maxN / 2;                                               // this should produce a c array that has 50% unique values (the other 50% are duplicates), but all are actually in the uniqueArray, so 1, 1, 2, 2 would be an example of this

            if (uniqueValuesCount == 0)
            {
                uniqueValuesCount = 1;
            }
            BenchUtil.PopulateIntArrayFromUniqueArray(mixedArray, rand, uniqueArray, uniqueValuesCount);
            BenchUtil.PopulateIntArrayAtRandomIndices(mixedArray, rand, int.MinValue, int.MaxValue, maxN - uniqueValuesCount);

            if (h != null)
            {
                for (int i = 0; i < maxN; i++)
                {
                    h.Add(uniqueArray[i]);
                }
            }

            if (f != null)
            {
                for (int i = 0; i < maxN; i++)
                {
                    f.Add(uniqueArray[i]);
                }
            }

            if (c5 != null)
            {
                for (int i = 0; i < maxN; i++)
                {
                    c5.Add(uniqueArray[i]);
                }
            }

            if (sortedSet != null)
            {
                for (int i = 0; i < maxN; i++)
                {
                    sortedSet.Add(uniqueArray[i]);
                }
            }

            if (lst != null)
            {
                for (int i = 0; i < maxN; i++)
                {
                    lst.Add(uniqueArray[i]);
                }
                lst.Sort();
            }
        }
        public static Dictionary <PointFr, C5.HashSet <LineSegmentFr> > IntersectionsBentleyOttmann(C5.HashSet <LineSegmentFr> segments, out Dictionary <PointFr, LineFr> sweepLines)
        {
            if (segments.Count < 2)
            {
                sweepLines = null;
                return(new Dictionary <PointFr, C5.HashSet <LineSegmentFr> >());
            }

            var sweepLine  = new SweepLine();
            var eventQueue = new EventQueue(segments, sweepLine);

            while (!eventQueue.isEmpty())
            {
                var eventPoints = eventQueue.DeleteMin();
                sweepLine.HandleEventPoints(eventPoints);
            }

            sweepLines = sweepLine.OldSweepLineValues;
            return(sweepLine.Intersections);
        }
Пример #41
0
 TypeKey[] GetBaseTypes(TypeDefinition type)
 {
     C5.HashSet <TypeKey> baseTypes = new C5.HashSet <TypeKey>( );
     GetBaseTypes(baseTypes, type);
     return(baseTypes.ToArray( ));
 }
Пример #42
0
        private void PurgeItemsInternal(IEnumerable<InventoryItemBase> items, long timeStamp)
        {
            C5.HashSet<byte[]> allParentFolderBytes = new C5.HashSet<byte[]>(new ByteArrayValueComparer());
            Dictionary<byte[], Dictionary<string, List<Mutation>>> muts = new Dictionary<byte[], Dictionary<string, List<Mutation>>>();

            foreach (InventoryItemBase item in items)
            {
                byte[] oldParentFolderBytes = ByteEncoderHelper.GuidEncoder.ToByteArray(item.Folder.Guid);
                allParentFolderBytes.FindOrAdd(ref oldParentFolderBytes);

                byte[] itemIdBytes = ByteEncoderHelper.GuidEncoder.ToByteArray(item.ID.Guid);

                muts[itemIdBytes] = new Dictionary<string, List<Mutation>>();

                //remove the item from the index
                this.GetItemParentDeletionMutations(itemIdBytes, timeStamp, muts);

                //remove the item from the old folder
                this.GetItemDeletionMutations(itemIdBytes, oldParentFolderBytes, timeStamp, muts, true);
            }

            ICluster cluster = AquilesHelper.RetrieveCluster(_clusterName);
            cluster.Execute(new ExecutionBlock(delegate(Apache.Cassandra.Cassandra.Client client)
            {
                client.batch_mutate(muts, DEFAULT_CONSISTENCY_LEVEL);

                return null;

            }), KEYSPACE);
        }
Пример #43
0
		protected void CheckEvents( string name, int expectedTypes, string[] expected, string[] notExpected )
		{
			C5.HashSet<string> eventsToFind = new C5.HashSet<string>( );
			eventsToFind.AddAll( expected );
			C5.HashSet<string> eventsNotToFind = new C5.HashSet<string>( );
			eventsNotToFind.AddAll( notExpected );

			C5.HashSet<string> methodsToFind = new C5.HashSet<string>( );
			for ( int i = 0; i < expected.Length; i++ )
			{
				methodsToFind.Add( "add_" + expected[i] );
				methodsToFind.Add( "remove_" + expected[i] );
			}

			C5.HashSet<string> methodsNotToFind = new C5.HashSet<string>( );
			for ( int i = 0; i < notExpected.Length; i++ )
			{
				methodsNotToFind.Add( "add_" + notExpected[i] );
				methodsNotToFind.Add( "remove_" + notExpected[i] );
			}

			bool foundDelType = false;

			AssemblyHelper.CheckAssembly( name, expectedTypes,
				delegate( TypeDefinition typeDef )
				{
					if ( typeDef.BaseType.FullName == "System.MulticastDelegate" )
					{
						foundDelType = true;
						return false;
					}
					else
						return true;
				},
				delegate( TypeDefinition typeDef )
				{
					// make sure we have enough methods...
					// 2 methods / event + a method to fire them
					Assert.AreEqual( methodsToFind.Count + methodsNotToFind.Count + 1, typeDef.Methods.Count,
						"Some of the methods for the type are missing." );

					foreach ( MethodDefinition method in typeDef.Methods )
					{
						Assert.IsFalse( methodsNotToFind.Contains( method.Name ), String.Format(
							"Did not expect to find method '{0}'.", method.Name ) );

						methodsToFind.Remove( method.Name );
					}

					Assert.AreEqual( expected.Length, typeDef.Events.Count,
						expected.Length == 1 ? "Type should have 1 event (others dropped by default)." :
						String.Format( "Type should have {0} events (others dropped by default).", expected.Length ) );

					foreach ( EventDefinition evt in typeDef.Events )
					{
						Assert.IsFalse( eventsNotToFind.Contains( evt.Name ), String.Format(
							"Did not expect to find event '{0}'.", evt.Name ) );

						eventsToFind.Remove( evt.Name );
					}

					Assert.IsFalse( methodsToFind.Count > 0, "Failed to find all expected methods." );
					Assert.IsFalse( eventsToFind.Count > 0, "Failed to find all expected events." );
				} );

			Assert.IsTrue( foundDelType, "Should have found the delegate type." );
		}
Пример #44
0
 public UpdateQueue()
 {
     m_queue = new Queue<SceneObjectPart>();
     m_ids = new C5.HashSet<uint>();
 }
Пример #45
0
        /// <summary>
        /// Called by project to finish initializing the assembly.
        /// </summary>
        internal void Init()
        {
            unrenamedReferences = new List <MemberReference>();
            foreach (MemberReference member in getMemberReferences())
            {
                MethodReference mr = member as MethodReference;
                FieldReference  fr = member as FieldReference;
                if (project.Contains(member.DeclaringType))
                {
                    unrenamedReferences.Add(member);
                }
            }

            C5.HashSet <TypeReference> typerefs = new C5.HashSet <TypeReference>();
            foreach (TypeReference type in definition.MainModule.GetTypeReferences())
            {
                if (type.FullName == "<Module>")
                {
                    continue;
                }

                if (project.Contains(type))
                {
                    typerefs.Add(type);
                }
            }

            // Type references in CustomAttributes
            List <CustomAttribute> customattributes = new List <CustomAttribute>();

            customattributes.AddRange(this.Definition.CustomAttributes);
            foreach (TypeDefinition type in GetAllTypeDefinitions())
            {
                customattributes.AddRange(type.CustomAttributes);
                foreach (MethodDefinition methoddef in type.Methods)
                {
                    customattributes.AddRange(methoddef.CustomAttributes);
                }
                foreach (FieldDefinition fielddef in type.Fields)
                {
                    customattributes.AddRange(fielddef.CustomAttributes);
                }
                foreach (EventDefinition eventdef in type.Events)
                {
                    customattributes.AddRange(eventdef.CustomAttributes);
                }
                foreach (PropertyDefinition propertydef in type.Properties)
                {
                    customattributes.AddRange(propertydef.CustomAttributes);
                }

                foreach (CustomAttribute customattribute in customattributes)
                {
                    // Check Constructor and named parameter for argument of type "System.Type". i.e. typeof()
                    List <CustomAttributeArgument> customattributearguments = new List <CustomAttributeArgument>();
                    customattributearguments.AddRange(customattribute.ConstructorArguments);
                    foreach (CustomAttributeNamedArgument namedargument in customattribute.Properties)
                    {
                        customattributearguments.Add(namedargument.Argument);
                    }

                    foreach (CustomAttributeArgument ca in customattributearguments)
                    {
                        if (ca.Type.FullName == "System.Type")
                        {
                            typerefs.Add((TypeReference)ca.Value);
                        }
                    }
                }
                customattributes.Clear();
            }

            unrenamedTypeReferences = new List <TypeReference>(typerefs);

            initialized = true;
        }