public void Sort()
 {
     if (list.Count > 1)
     {
         IndexedItem <T>[] oldItems = GetIndexedItems();
         list.StableSort();
         OnItemsMoved(GetIndexedItems(), oldItems);
         OnPropertyChanged("Item[]");
     }
 }
Example #2
0
        /// <summary>Gets the best encoding available for the specified charset request.</summary>
        /// <param name="acceptableCharsets">
        /// The Accept-Charset header value (eg: "iso-8859-5, unicode-1-1;q=0.8").
        /// </param>
        /// <param name="mediaType">The media type used to compute the default encoding for the payload.</param>
        /// <param name="utf8Encoding">The encoding to use for UTF-8 charsets; we use the one without the BOM.</param>
        /// <param name="defaultEncoding">The encoding to use if no encoding could be computed from the <paramref name="acceptableCharsets"/> or <paramref name="mediaType"/>.</param>
        /// <returns>An Encoding object appropriate to the specifed charset request.</returns>
        internal static Encoding EncodingFromAcceptableCharsets(string acceptableCharsets, MediaType mediaType, Encoding utf8Encoding, Encoding defaultEncoding)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(mediaType != null, "mediaType != null");

            // Determines the appropriate encoding mapping according to
            // RFC 2616.14.2 (http://tools.ietf.org/html/rfc2616#section-14.2).
            Encoding result = null;

            if (!string.IsNullOrEmpty(acceptableCharsets))
            {
                // PERF: in the future if we find that computing the encoding from the accept charsets is
                //       too expensive we could introduce a cache of original strings to resolved encoding.
                CharsetPart[] parts = new List <CharsetPart>(AcceptCharsetParts(acceptableCharsets)).ToArray();

                // NOTE: List<T>.Sort uses an unstable sort algorithm; if charsets have the same quality value
                //       we want to pick the first one specified so we need a stable sort.
                KeyValuePair <int, CharsetPart>[] sortedParts = parts.StableSort(delegate(CharsetPart x, CharsetPart y)
                {
                    return(y.Quality - x.Quality);
                });

                foreach (KeyValuePair <int, CharsetPart> sortedPart in sortedParts)
                {
                    CharsetPart part = sortedPart.Value;
                    if (part.Quality > 0)
                    {
                        // When UTF-8 is specified, select the version that doesn't use the BOM.
                        if (String.Compare("utf-8", part.Charset, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            result = utf8Encoding;
                            break;
                        }
                        else
                        {
                            result = GetEncodingFromCharsetName(part.Charset);
                            if (result != null)
                            {
                                break;
                            }

                            // If the charset is not supported it is ignored so other possible charsets are evaluated.
                        }
                    }
                }
            }

            // No Charset was specifed, or if charsets were specified, no valid charset was found.
            // Returning a different charset is also valid. Get the default encoding for the media type.
            if (result == null)
            {
                result = mediaType.SelectEncoding();
                if (result == null)
                {
                    return(defaultEncoding);
                }
            }

            return(result);
        }
        public void GenericList_StableSort_2()
        {
            var list = new List <SortItem>
            {
                new SortItem {
                    SortOrder = 2, Name = "Name2"
                },
                new SortItem {
                    SortOrder = 1, Name = "Name1"
                },
                new SortItem {
                    SortOrder = 2, Name = "Name3"
                },
            };

            list.StableSort();

            Assert.AreEqual(3, list.Count);

            Assert.AreEqual(1, list[0].SortOrder);
            Assert.AreEqual("Name1", list[0].Name);

            Assert.AreEqual(2, list[1].SortOrder);
            Assert.AreEqual("Name2", list[1].Name);

            Assert.AreEqual(2, list[2].SortOrder);
            Assert.AreEqual("Name3", list[2].Name);
        }
Example #4
0
        private void OnUpdate(GraphicsContext gfx, float dt)
        {
            // Update the game
            Update(dt);

            //
            _entities.StableSort();

            // Render the game
            Renderer.Render(gfx, dt, _entities);
        }
        public void GenericList_StableSort_Order()
        {
            var elements = new[] { 10, 5, 20 };

            var list1 = new List <int>(elements);
            var list2 = new List <int>(elements);

            list1.Sort();
            list2.StableSort();

            Assert.IsTrue(list1.SequenceEqual(list2));
        }
Example #6
0
 /// <summary>
 /// Retrieves a matching <see cref="Duality.Serialization.ISerializeSurrogate"/> for the specified <see cref="System.Type"/>.
 /// </summary>
 /// <param name="t">The <see cref="System.Type"/> to retrieve a <see cref="Duality.Serialization.ISerializeSurrogate"/> for.</param>
 /// <returns></returns>
 protected static ISerializeSurrogate GetSurrogateFor(Type type)
 {
     if (surrogates == null)
     {
         surrogates =
             DualityApp.GetAvailDualityTypes(typeof(ISerializeSurrogate))
             .Select(t => t.CreateInstanceOf())
             .OfType <ISerializeSurrogate>()
             .NotNull()
             .ToList();
         surrogates.StableSort((s1, s2) => s1.Priority - s2.Priority);
     }
     return(surrogates.FirstOrDefault(s => s.MatchesType(type)));
 }
Example #7
0
        private void QueryGraphicsModes()
        {
            // Gather available graphics modes
            Logs.Core.Write("Available graphics modes:");
            Logs.Core.PushIndent();
            int[] aaLevels = new int[] { 0, 2, 4, 6, 8, 16 };
            this.availGraphicsModes = new HashSet <GraphicsMode>(new GraphicsModeComparer());
            foreach (int samplecount in aaLevels)
            {
                GraphicsMode mode = new GraphicsMode(32, 24, 0, samplecount, new OpenTK.Graphics.ColorFormat(0), 2, false);
                if (!this.availGraphicsModes.Contains(mode))
                {
                    this.availGraphicsModes.Add(mode);
                    Logs.Core.Write("{0}", mode);
                }
            }
            Logs.Core.PopIndent();

            // Select the default graphics mode we'll prefer for game window and other rendering surfaces
            List <GraphicsMode> sortedModes = this.availGraphicsModes.ToList();

            sortedModes.StableSort((a, b) => a.Samples - b.Samples);
            int highestAALevel = MathF.RoundToInt(MathF.Log(MathF.Max(sortedModes.Max(m => m.Samples), 1.0f), 2.0f));
            int targetAALevel  = highestAALevel;

            if (DualityApp.AppData.Instance.MultisampleBackBuffer)
            {
                switch (DualityApp.UserData.Instance.AntialiasingQuality)
                {
                case AAQuality.High:    targetAALevel = highestAALevel;         break;

                case AAQuality.Medium:  targetAALevel = highestAALevel / 2; break;

                case AAQuality.Low:             targetAALevel = highestAALevel / 4; break;

                case AAQuality.Off:             targetAALevel = 0;                                      break;
                }
            }
            else
            {
                targetAALevel = 0;
            }
            int targetSampleCount = MathF.RoundToInt(MathF.Pow(2.0f, targetAALevel));

            this.defaultGraphicsMode = sortedModes.LastOrDefault(m => m.Samples <= targetSampleCount) ?? sortedModes.Last();

            Logs.Core.Write("Duality default graphics mode: {0}", this.defaultGraphicsMode);
            Logs.Core.Write("OpenTK default graphics mode: {0}", GraphicsMode.Default);
        }
Example #8
0
 internal static void Init()
 {
     foreach (TypeInfo genType in DualityEditorApp.GetAvailDualityEditorTypes(typeof(IAssetImporter)))
     {
         if (genType.IsAbstract)
         {
             continue;
         }
         IAssetImporter gen = genType.CreateInstanceOf() as IAssetImporter;
         if (gen != null)
         {
             importers.Add(gen);
         }
     }
     importers.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);
 }
Example #9
0
 /// <summary>
 /// Attempts to handle a serialization error dynamically by invoking available <see cref="SerializeErrorHandler">SerializeErrorHandlers</see>.
 /// </summary>
 /// <param name="error"></param>
 /// <returns>Returns true, if the error has been handled successfully.</returns>
 protected static bool HandleSerializeError(SerializeError error)
 {
     if (error.Handled)
     {
         return(true);
     }
     if (serializeHandlerCache.Count == 0)
     {
         IEnumerable <Type> handlerTypes = DualityApp.GetAvailDualityTypes(typeof(SerializeErrorHandler));
         foreach (Type handlerType in handlerTypes)
         {
             if (handlerType.IsAbstract)
             {
                 continue;
             }
             try
             {
                 SerializeErrorHandler handler = handlerType.CreateInstanceOf() as SerializeErrorHandler;
                 if (handler != null)
                 {
                     serializeHandlerCache.Add(handler);
                 }
             }
             catch (Exception) {}
         }
         serializeHandlerCache.StableSort((a, b) => b.Priority - a.Priority);
     }
     foreach (SerializeErrorHandler handler in serializeHandlerCache)
     {
         try
         {
             handler.HandleError(error);
             if (error.Handled)
             {
                 return(true);
             }
         }
         catch (Exception e)
         {
             Log.Core.WriteError("An error occurred while trying to perform a serialization fallback: {0}", Log.Exception(e));
         }
     }
     return(false);
 }
Example #10
0
            protected Heap(IEnumerable <T> collection, IComparer <T> comparer)
            {
                if (collection == null)
                {
                    throw new ArgumentNullException("collection");
                }
                if (comparer == null)
                {
                    throw new ArgumentNullException("comparer");
                }

                Comparer = comparer;

                foreach (var item in collection)
                {
                    heap.Add(item);
                }

                heap.StableSort();
            }
Example #11
0
        public void StableSortFuzzTest()
        {
            var list = new List <IntPair>(100);

            for (int t = 0; t < FuzzTrials; t++)
            {
                MakeRandomList(list);
                var TEMP = new List <IntPair>(list);
                list.StableSort();
                for (int i = 1; i < list.Count; i++)
                {
                    IntPair a = list[i - 1], b = list[i];
                    Assert.LessOrEqual(a.Key, b.Key);
                    if (a.Key == b.Key)
                    {
                        Assert.Less(a.Value, b.Value);
                    }
                }
            }
        }
Example #12
0
 internal static ICloneSurrogate GetSurrogateFor(TypeInfo type)
 {
     if (surrogates == null)
     {
         surrogates =
             DualityApp.GetAvailDualityTypes(typeof(ICloneSurrogate))
             .Select(t => t.CreateInstanceOf())
             .OfType <ICloneSurrogate>()
             .NotNull()
             .ToList();
         surrogates.StableSort((s1, s2) => s1.Priority - s2.Priority);
     }
     for (int i = 0; i < surrogates.Count; i++)
     {
         if (surrogates[i].MatchesType(type))
         {
             return(surrogates[i]);
         }
     }
     return(null);
 }
        protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
        {
            List <T> itemsList = (List <T>) this.Items;

            Type propertyType = property.PropertyType;
            PropertyComparer <T> comparer;

            if (!this.comparers.TryGetValue(propertyType, out comparer))
            {
                comparer = new PropertyComparer <T>(property, direction);
                this.comparers.Add(propertyType, comparer);
            }

            comparer.SetPropertyAndDirection(property, direction);
            itemsList.StableSort(comparer);

            this.propertyDescriptor = property;
            this.listSortDirection  = direction;
            this.isSorted           = true;

            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }
Example #14
0
        private static void GatherAvailable()
        {
            availableCodecs = new List <IImageCodec>();
            foreach (TypeInfo imageCodecType in DualityApp.GetAvailDualityTypes(typeof(IImageCodec)))
            {
                if (imageCodecType.IsAbstract)
                {
                    continue;
                }
                if (imageCodecType.IsInterface)
                {
                    continue;
                }

                IImageCodec codec = imageCodecType.CreateInstanceOf() as IImageCodec;
                if (codec != null)
                {
                    availableCodecs.Add(codec);
                }
            }
            availableCodecs.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);
        }
Example #15
0
        /// <summary>
        /// Performs the sort
        /// </summary>
        /// <param name="startSp"></param>
        /// <returns></returns>
        public IEnumerable <PlanEntry> Sort(int startSp)
        {
            int initialCount = m_entries.Count();

            // Apply first pass (learning skills)
            // We split the entries into a head (learnings) and a tail (non-learnings)
            PlanScratchpad   headPlan    = new PlanScratchpad(m_character);
            List <PlanEntry> tailEntries = new List <PlanEntry>();

            if (m_learningSkillsFirst)
            {
                tailEntries.AddRange(m_entries.Where(x => x.Skill.LearningClass == LearningClass.None));

                var learningSkills = m_entries.Where(x => x.Skill.LearningClass != LearningClass.None);
                headPlan = OptimizeLearningSkills(learningSkills, startSp);
            }
            else
            {
                tailEntries.AddRange(m_entries);
            }


            // Apply second pass (priorities grouping)
            // We split the tail into multiple tail groups
            List <PlanScratchpad> tailEntryPlans = new List <PlanScratchpad>();
            var scratchpad = new CharacterScratchpad(m_character);

            scratchpad.Train(headPlan);

            if (m_groupByPriority)
            {
                foreach (var group in tailEntries.GroupBy(x => x.Priority))
                {
                    tailEntryPlans.Add(new PlanScratchpad(scratchpad, group));
                }
            }
            else
            {
                tailEntryPlans.Add(new PlanScratchpad(scratchpad, tailEntries));
            }


            // Apply third pass (sorts)
            // We sort every tail group, and merge them once they're sorted.
            List <PlanEntry> list = new List <PlanEntry>();

            list.AddRange(headPlan);

            foreach (var tailPlan in tailEntryPlans)
            {
                tailPlan.UpdateStatistics(scratchpad, false, false);
                tailPlan.SimpleSort(m_sort, m_reverseOrder);
                list.AddRange(tailPlan);
            }

            // This is actually what GroupByPriority should do
            if (m_groupByPriority)
            {
                list.StableSort(PlanSorter.CompareByPriority);
            }

            // Fix prerequisites order
            FixPrerequisitesOrder(list);

            // Check we didn't mess up anything
            if (initialCount != list.Count)
            {
                throw new UnauthorizedAccessException("The sort algorithm messed up and deleted items");
            }

            // Return
            return(list);
        }
Example #16
0
        internal static void InitBackend <T>(out T target, Func <Type, IEnumerable <TypeInfo> > typeFinder = null) where T : class, IDualityBackend
        {
            if (typeFinder == null)
            {
                typeFinder = GetAvailDualityTypes;
            }

            Logs.Core.Write("Initializing {0}...", LogFormat.Type(typeof(T)));
            Logs.Core.PushIndent();

            // Generate a list of available backends for evaluation
            List <IDualityBackend> backends = new List <IDualityBackend>();

            foreach (TypeInfo backendType in typeFinder(typeof(IDualityBackend)))
            {
                if (backendType.IsInterface)
                {
                    continue;
                }
                if (backendType.IsAbstract)
                {
                    continue;
                }
                if (!backendType.IsClass)
                {
                    continue;
                }
                if (!typeof(T).GetTypeInfo().IsAssignableFrom(backendType))
                {
                    continue;
                }

                IDualityBackend backend = backendType.CreateInstanceOf() as IDualityBackend;
                if (backend == null)
                {
                    Logs.Core.WriteWarning("Unable to create an instance of {0}. Skipping it.", backendType.FullName);
                    continue;
                }
                backends.Add(backend);
            }

            // Sort backends from best to worst
            backends.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);

            // Try to initialize each one and select the first that works
            T selectedBackend = null;

            foreach (T backend in backends)
            {
                if (DualityApp.AppData.Instance?.SkipBackends != null &&
                    DualityApp.AppData.Instance.SkipBackends.Any(s => string.Equals(s, backend.Id, StringComparison.OrdinalIgnoreCase)))
                {
                    Logs.Core.Write("Backend '{0}' skipped because of AppData settings.", backend.Name);
                    continue;
                }

                bool available = false;
                try
                {
                    available = backend.CheckAvailable();
                    if (!available)
                    {
                        Logs.Core.Write("Backend '{0}' reports to be unavailable. Skipping it.", backend.Name);
                    }
                }
                catch (Exception e)
                {
                    available = false;
                    Logs.Core.WriteWarning("Backend '{0}' failed the availability check with an exception: {1}", backend.Name, LogFormat.Exception(e));
                }
                if (!available)
                {
                    continue;
                }

                Logs.Core.Write("{0}...", backend.Name);
                Logs.Core.PushIndent();
                {
                    try
                    {
                        backend.Init();
                        selectedBackend = backend;
                    }
                    catch (Exception e)
                    {
                        Logs.Core.WriteError("Failed: {0}", LogFormat.Exception(e));
                    }
                }
                Logs.Core.PopIndent();

                if (selectedBackend != null)
                {
                    break;
                }
            }

            // If we found a proper backend and initialized it, add it to the list of active backends
            if (selectedBackend != null)
            {
                target = selectedBackend;

                TypeInfo selectedBackendType = selectedBackend.GetType().GetTypeInfo();
                pluginManager.LockPlugin(selectedBackendType.Assembly);
            }
            else
            {
                target = null;
            }

            Logs.Core.PopIndent();
        }
Example #17
0
        /// <summary>Gets the best encoding available for the specified charset request.</summary>
        /// <param name="acceptableCharsets">
        /// The Accept-Charset header value (eg: "iso-8859-5, unicode-1-1;q=0.8").
        /// </param>
        /// <param name="mediaType">The media type used to compute the default encoding for the payload.</param>
        /// <param name="utf8Encoding">The encoding to use for UTF-8 charsets; we use the one without the BOM.</param>
        /// <param name="defaultEncoding">The encoding to use if no encoding could be computed from the <paramref name="acceptableCharsets"/> or <paramref name="mediaType"/>.</param>
        /// <returns>An Encoding object appropriate to the specifed charset request.</returns>
        internal static Encoding EncodingFromAcceptableCharsets(string acceptableCharsets, MediaType mediaType, Encoding utf8Encoding, Encoding defaultEncoding)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(mediaType != null, "mediaType != null");

            // Determines the appropriate encoding mapping according to
            // RFC 2616.14.2 (http://tools.ietf.org/html/rfc2616#section-14.2).
            Encoding result = null;
            if (!string.IsNullOrEmpty(acceptableCharsets))
            {
                // PERF: in the future if we find that computing the encoding from the accept charsets is
                //       too expensive we could introduce a cache of original strings to resolved encoding.
                CharsetPart[] parts = new List<CharsetPart>(AcceptCharsetParts(acceptableCharsets)).ToArray();

                // NOTE: List<T>.Sort uses an unstable sort algorithm; if charsets have the same quality value
                //       we want to pick the first one specified so we need a stable sort.
                KeyValuePair<int, CharsetPart>[] sortedParts = parts.StableSort(delegate(CharsetPart x, CharsetPart y)
                {
                    return y.Quality - x.Quality;
                });

                foreach (KeyValuePair<int, CharsetPart> sortedPart in sortedParts)
                {
                    CharsetPart part = sortedPart.Value;
                    if (part.Quality > 0)
                    {
                        // When UTF-8 is specified, select the version that doesn't use the BOM.
                        if (String.Compare("utf-8", part.Charset, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            result = utf8Encoding;
                            break;
                        }
                        else
                        {
                            result = GetEncodingFromCharsetName(part.Charset);
                            if (result != null)
                            {
                                break;
                            }

                            // If the charset is not supported it is ignored so other possible charsets are evaluated.
                        }
                    }
                }
            }

            // No Charset was specifed, or if charsets were specified, no valid charset was found.
            // Returning a different charset is also valid. Get the default encoding for the media type.
            if (result == null)
            {
                result = mediaType.SelectEncoding();
                if (result == null)
                {
                    return defaultEncoding;
                }
            }

            return result;
        }
Example #18
0
        public IEnumerable <object> Perform(Type target, Operation restrictTo = Operation.All)
        {
            Operation oldAllowedOp = this.allowedOp;

            this.allowedOp = oldAllowedOp & restrictTo;

            // Convert ContentRef requests to their respective Resource-requests
            Type originalType = target;

            target = ResTypeFromRefType(target);

            //Logs.Editor.Write("Convert to {0}", target.Name);
            bool fittingDataFound = false;

            // Check if there already is fitting data available
            IEnumerable <object> fittingData = null;

            if (fittingData == null)
            {
                // Single object
                if (this.data.GetDataPresent(target))
                {
                    fittingData = new[] { this.data.GetData(target) }
                }
                ;
            }
            if (fittingData == null)
            {
                // Object array
                Type arrType = target.MakeArrayType();
                if (this.data.GetDataPresent(arrType))
                {
                    fittingData = this.data.GetData(arrType) as IEnumerable <object>;
                }
            }
            if (fittingData == null)
            {
                // Components
                Component[] comps;
                if (this.data.TryGetComponents(target, DataObjectStorage.Reference, out comps))
                {
                    fittingData = comps;
                }
            }
            if (fittingData == null)
            {
                // ContentRefs
                IContentRef[] content;
                if (this.data.TryGetContentRefs(target, out content))
                {
                    fittingData = content.Res();
                }
            }

            // If something fitting was found, directly add it to the operation results
            if (fittingData != null)
            {
                fittingDataFound = true;
                foreach (object obj in fittingData)
                {
                    this.AddResult(obj);
                }
            }

            // No result yet? Search suitable converters
            if (!fittingDataFound)
            {
                IEnumerable <DataConverter> converterQuery = GetConverters(target);
                List <ConvComplexityEntry>  converters     = new List <ConvComplexityEntry>();
                foreach (DataConverter c in converterQuery)
                {
                    this.maxComplexity = 0;
                    if (this.usedConverters.Contains(c))
                    {
                        continue;
                    }
                    if (!c.CanConvertFrom(this))
                    {
                        continue;
                    }
                    converters.Add(new ConvComplexityEntry(c, this.maxComplexity));
                }

                // Perform conversion
                try
                {
                    converters.StableSort((c1, c2) => (c2.Converter.Priority - c1.Converter.Priority) * 10000 + (c1.Complexity - c2.Complexity));
                    foreach (ConvComplexityEntry c in converters)
                    {
                        this.usedConverters.Add(c.Converter);
                        bool handled = c.Converter.Convert(this);
                        this.usedConverters.Remove(c.Converter);
                        if (handled)
                        {
                            break;
                        }
                    }
                }
                // Since convert operations are often performed in dragdrop handlers (which internally catch all exceptions),
                // we should do some basic error logging in here to make sure users won't end up without explanation for
                // their operation not performing correctly or at all.
                catch (Exception e)
                {
                    Logs.Editor.WriteError(
                        "There was an error trying to convert data to target type {0}: {1}",
                        LogFormat.Type(target),
                        LogFormat.Exception(e));
                }
            }

            IEnumerable <object> returnValue = this.result;

            // Convert back to Resource requests
            if (typeof(IContentRef).IsAssignableFrom(originalType))
            {
                returnValue = this.result.OfType <Resource>().Select(r => r.GetContentRef());
            }

            returnValue = returnValue ?? (IEnumerable <object>)Array.CreateInstance(originalType, 0);
            returnValue = returnValue.Where(originalType.IsInstanceOfType);

            this.allowedOp = oldAllowedOp;
            return(returnValue);
        }
Example #19
0
		/// <summary>
		/// Performs a 2d physical raycast in world coordinates.
		/// </summary>
		/// <param name="worldCoordA">The starting point.</param>
		/// <param name="worldCoordB">The desired end point.</param>
		/// <param name="callback">
		/// The callback that is invoked for each hit on the raycast. Note that the order in which each hit occurs isn't deterministic
		/// and may appear random. Return -1 to ignore the curret shape, 0 to terminate the raycast, data.Fraction to clip the ray for current hit, or 1 to continue.
		/// </param>
		/// <returns>Returns a list of all occurred hits, ordered by their Fraction value.</returns>
		public static List<RayCastData> RayCast(Vector2 worldCoordA, Vector2 worldCoordB, RayCastCallback callback = null)
		{
			if (callback == null) callback = Raycast_DefaultCallback;
			Vector2 fsWorldCoordA = PhysicsConvert.ToPhysicalUnit(worldCoordA);
			Vector2 fsWorldCoordB = PhysicsConvert.ToPhysicalUnit(worldCoordB);
			List<RayCastData> hitData = new List<RayCastData>();
			Scene.PhysicsWorld.RayCast(delegate(Fixture fixture, Vector2 pos, Vector2 normal, float fraction)
			{
				RayCastData data = new RayCastData(
					fixture.UserData as ShapeInfo, 
					PhysicsConvert.ToDualityUnit(pos), 
					normal, 
					fraction);
				float result = callback(data);
				if (result >= 0.0f) hitData.Add(data);
				return result;
			}, fsWorldCoordA, fsWorldCoordB);
			hitData.StableSort((d1, d2) => (int)(1000000.0f * (d1.Fraction - d2.Fraction)));
			return hitData;
		}
Example #20
0
        public IEnumerable <object> Perform(Type target, Operation restrictTo = Operation.All)
        {
            Operation oldAllowedOp = this.allowedOp;

            this.allowedOp = oldAllowedOp & restrictTo;

            // Convert ContentRef requests to their respective Resource-requests
            Type originalType = target;

            target = ResTypeFromRefType(target);

            //Log.Editor.Write("Convert to {0}", target.Name);
            bool fittingDataFound = false;

            // Check if there already is fitting data available
            IEnumerable <object> fittingData = null;

            if (fittingData == null)
            {
                // Single object
                if (this.data.GetDataPresent(target))
                {
                    fittingData = new[] { this.data.GetData(target) }
                }
                ;
            }
            if (fittingData == null)
            {
                // Object array
                Type arrType = target.MakeArrayType();
                if (this.data.GetDataPresent(arrType))
                {
                    fittingData = this.data.GetData(arrType) as IEnumerable <object>;
                }
            }
            if (fittingData == null)
            {
                // ComponentRefs
                if (this.data.ContainsComponentRefs(target))
                {
                    fittingData = this.data.GetComponentRefs(target);
                }
            }
            if (fittingData == null)
            {
                // ContentRefs
                if (this.data.ContainsContentRefs(target))
                {
                    fittingData = this.data.GetContentRefs(target).Res();
                }
            }

            // If something fitting was found, directly add it to the operation results
            if (fittingData != null)
            {
                fittingDataFound = true;
                foreach (object obj in fittingData)
                {
                    this.AddResult(obj);
                }
            }

            // No result yet? Search suitable converters
            if (!fittingDataFound)
            {
                var converterQuery = GetConverters(target);
                List <ConvComplexityEntry> converters = new List <ConvComplexityEntry>();
                foreach (var c in converterQuery)
                {
                    this.maxComplexity = 0;
                    if (this.usedConverters.Contains(c))
                    {
                        continue;
                    }
                    if (!c.CanConvertFrom(this))
                    {
                        continue;
                    }
                    converters.Add(new ConvComplexityEntry(c, this.maxComplexity));
                }

                // Perform conversion
                converters.StableSort((c1, c2) => (c2.Converter.Priority - c1.Converter.Priority) * 10000 + (c1.Complexity - c2.Complexity));
                foreach (var c in converters)
                {
                    //Log.Editor.Write("using {0}", s.GetType().Name);
                    //Log.Editor.PushIndent();
                    //Log.Editor.Write("before: {0}", this.Result.ToString(o => string.Format("{0} {1}", o.GetType().Name, o), ", "));
                    this.usedConverters.Add(c.Converter);
                    bool handled = c.Converter.Convert(this);
                    this.usedConverters.Remove(c.Converter);
                    //Log.Editor.Write("after: {0}", this.Result.ToString(o => string.Format("{0} {1}", o.GetType().Name, o), ", "));
                    //Log.Editor.PopIndent();
                    if (handled)
                    {
                        break;
                    }
                }
            }

            IEnumerable <object> returnValue = this.result;

            // Convert back to Resource requests
            if (typeof(IContentRef).IsAssignableFrom(originalType))
            {
                returnValue = result.OfType <Resource>().Select(r => r.GetContentRef());
            }

            returnValue = returnValue ?? (IEnumerable <object>)Array.CreateInstance(originalType, 0);
            returnValue = returnValue.Where(originalType.IsInstanceOfType);

            this.allowedOp = oldAllowedOp;
            return(returnValue);
        }
Example #21
0
        public void UpdateResults(List <UDT_DLL.udtPatternMatch> results, List <DemoInfo> demos)
        {
            _cutResultsListView.Items.Clear();
            _fileResultsListView.Items.Clear();

            results.Sort((a, b) => a.StartTimeMs.CompareTo(b.StartTimeMs));
            results.StableSort((a, b) => a.GameStateIndex.CompareTo(b.GameStateIndex));
            results.StableSort((a, b) => a.DemoInputIndex.CompareTo(b.DemoInputIndex));

            _results     = results;
            _resultDemos = demos;

            foreach (var result in results)
            {
                var index = result.DemoInputIndex;
                if (index >= demos.Count)
                {
                    continue;
                }

                var copyMenuItem = new MenuItem();
                copyMenuItem.Header  = App.CreateContextMenuHeader("Copy to Clipboard", "(Ctrl+C)");
                copyMenuItem.Command = _cutCopyCommand.RoutedCommand;

                var cutMenuItem = new MenuItem();
                cutMenuItem.Header  = "Apply Cut(s)";
                cutMenuItem.Command = _cutCutCommand.RoutedCommand;

                var revealMenuItem = new MenuItem();
                revealMenuItem.Header  = "Reveal in File Explorer";
                revealMenuItem.Command = _cutRevealCommand.RoutedCommand;

                var selectMenuItem = new MenuItem();
                selectMenuItem.Header  = "Select in Demo List";
                selectMenuItem.Command = _cutSelectCommand.RoutedCommand;

                var contextMenu = new ContextMenu();
                contextMenu.Items.Add(copyMenuItem);
                contextMenu.Items.Add(selectMenuItem);
                contextMenu.Items.Add(cutMenuItem);
                contextMenu.Items.Add(new Separator());
                contextMenu.Items.Add(revealMenuItem);

                var demo      = demos[(int)index];
                var fileName  = Path.GetFileNameWithoutExtension(demo.FilePath);
                var gs        = result.GameStateIndex.ToString();
                var start     = App.FormatMinutesSeconds(result.StartTimeMs / 1000);
                var end       = App.FormatMinutesSeconds(result.EndTimeMs / 1000);
                var patterns  = FormatPatterns(result.Patterns);
                var cutResult = new SearchResultCutDisplayInfo(fileName, gs, start, end, patterns, result, demo);
                var cutItem   = new ListViewItem();
                cutItem.Content     = cutResult;
                cutItem.ContextMenu = contextMenu;
                _cutResultsListView.Items.Add(cutItem);
            }

            uint currentFileIndex = uint.MaxValue;
            var  fileResults      = new List <UDT_DLL.udtPatternMatch>();

            foreach (var result in results)
            {
                var index = result.DemoInputIndex;
                if (index >= demos.Count)
                {
                    continue;
                }

                if (currentFileIndex != index)
                {
                    if (fileResults.Count > 0)
                    {
                        AddSingleFileResult(fileResults, demos);
                        fileResults.Clear();
                    }
                }
                fileResults.Add(result);
                currentFileIndex = index;
            }
            if (fileResults.Count > 0)
            {
                AddSingleFileResult(fileResults, demos);
            }

            var cutCount  = _cutResultsListView.Items.Count;
            var fileCount = _fileResultsListView.Items.Count;

            _resultsTextBlock.Text = string.Format("Found {0} match{1} in {2} demo file{3}.",
                                                   cutCount, cutCount > 1 ? "es" : "", fileCount, fileCount > 1 ? "s" : "");

            var fileMode = _displayFilesRadioButton.IsChecked ?? false;

            if (fileMode)
            {
                OnFileModeChecked();
            }
            else
            {
                OnCutModeChecked();
            }
        }
Example #22
0
        internal static void InitBackend <T>(out T target, Func <Type, IEnumerable <TypeInfo> > typeFinder = null) where T : class, IDualityBackend
        {
            if (typeFinder == null)
            {
                typeFinder = GetAvailDualityTypes;
            }

            // Generate a list of available backends for evaluation
            List <IDualityBackend> backends = new List <IDualityBackend>();

            foreach (TypeInfo backendType in typeFinder(typeof(IDualityBackend)))
            {
                if (backendType.IsInterface)
                {
                    continue;
                }
                if (backendType.IsAbstract)
                {
                    continue;
                }
                if (!backendType.IsClass)
                {
                    continue;
                }
                if (!typeof(T).GetTypeInfo().IsAssignableFrom(backendType))
                {
                    continue;
                }

                IDualityBackend backend = backendType.CreateInstanceOf() as IDualityBackend;
                if (backend == null)
                {
                    //Log.Core.WriteWarning("Unable to create an instance of {0}. Skipping it.", backendType.FullName);
                    continue;
                }
                backends.Add(backend);
            }

            // Sort backends from best to worst
            backends.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);

            // Try to initialize each one and select the first that works
            T selectedBackend = null;

            foreach (T backend in backends)
            {
                bool available = false;
                try {
                    available = backend.CheckAvailable();
                    if (!available)
                    {
                        Log.Write(LogType.Error, "Backend '{0}' reports to be unavailable. Skipping it.", backend.Name);
                    }
                } catch (Exception e) {
                    available = false;
                    Log.Write(LogType.Error, "Backend '{0}' failed the availability check with an exception: {1}", backend.Name, e);
                }
                if (!available)
                {
                    continue;
                }

                try {
                    backend.Init();
                    selectedBackend = backend;
                } catch (Exception e) {
                    Log.Write(LogType.Error, "Backend '{0}' failed: {1}", backend.Name, e);
                }

                if (selectedBackend != null)
                {
                    break;
                }
            }

            // If we found a proper backend and initialized it, add it to the list of active backends
            if (selectedBackend != null)
            {
                target = selectedBackend;

                TypeInfo selectedBackendType = selectedBackend.GetType().GetTypeInfo();
                pluginManager.LockPlugin(selectedBackendType.Assembly);
            }
            else
            {
                target = null;
            }
        }
 public static void StableSort <T>(this List <T> values, Comparison <T> comparison)
 {
     values.StableSort(new StableSortComparer <T>(comparison));
 }
 public static void StableSort <T>(this List <T> values, int index, int count, Comparison <T> comparison)
 {
     values.StableSort(index, count, new StableSortComparer <T>(comparison));
 }