Пример #1
0
            public void EqualityComparer()
            {
                var dict = new ThreadSafeDictionary <string, int>(StringComparer.InvariantCultureIgnoreCase);

                dict.Add("Weißbier", 93);
                Assert.AreEqual(dict["WEISSBIER"], 93);
                dict["weissbier"] = 777;
                Assert.AreEqual(dict["Weißbier"], 777);
                dict.Add(new KeyValuePair <string, int>("Δίος", 21));
                Assert.AreEqual(2, dict.Count);
                Assert.IsTrue(dict.ContainsKey("ΔΊΟΣ"));
                Assert.IsTrue(dict.Contains(new KeyValuePair <string, int>("δίος", 21)));
                Assert.IsFalse(dict.Contains(new KeyValuePair <string, int>("δίος", 3)));
                Assert.IsTrue(dict.Keys.Contains("δίος"));
                Assert.IsFalse(dict.Keys.Contains("δίοςδίος"));
                Assert.IsTrue(dict.Values.Contains(770, new RoundedEquality()));
                Assert.IsFalse(dict.Values.Contains(770));
                int result;

                Assert.IsTrue(dict.TryGetValue("ΔΊΟΣ", out result) && result == 21);
                Assert.IsFalse(dict.TryGetValue("Eggplant", out result));
                Assert.IsFalse(dict.Remove("aubergine"));
                Assert.IsTrue(dict.Remove("Δίος"));
                Assert.IsFalse(dict.Remove(new KeyValuePair <string, int>("WEISSBIER", 93)));
                Assert.IsTrue(dict.Remove(new KeyValuePair <string, int>("WEISSBIER", 777)));
                Assert.IsFalse(dict.ContainsKey("WEISSBIER"));
                Assert.IsFalse(dict.Remove(new KeyValuePair <string, int>("WEISSBIER", 777)));
                Assert.AreEqual(dict.Count, 0);
                dict.Add("Palmer", 1111);
                Assert.IsFalse(dict.Remove("Palmer", 1110, out result));
                Assert.AreEqual(dict.Count, 1);
                Assert.IsTrue(dict.Remove("Palmer", 1110, new RoundedEquality(), out result));
                Assert.AreEqual(result, 1111);
                Assert.AreEqual(dict.Count, 0);
            }
Пример #2
0
 public Player GetPlayer(NebulaConnection conn)
 {
     if (connectedPlayers.TryGetValue(conn, out Player player))
     {
         return(player);
     }
     return(null);
 }
Пример #3
0
        public MultiplayerSessionReservation ReservePlayerContext(
            NitroxConnection connection,
            PlayerSettings playerSettings,
            AuthenticationContext authenticationContext,
            string correlationId)
        {
            // TODO: ServerPassword in NitroxClient

            if (!string.IsNullOrEmpty(serverConfig.ServerPassword) && (!authenticationContext.ServerPassword.HasValue || authenticationContext.ServerPassword.Value != serverConfig.ServerPassword))
            {
                MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.AUTHENTICATION_FAILED;
                return(new MultiplayerSessionReservation(correlationId, rejectedState));
            }

            if (reservedPlayerNames.Count >= serverConfig.MaxConnections)
            {
                MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.SERVER_PLAYER_CAPACITY_REACHED;
                return(new MultiplayerSessionReservation(correlationId, rejectedState));
            }

            string playerName = authenticationContext.Username;
            Player player;

            allPlayersByName.TryGetValue(playerName, out player);
            if ((player?.IsPermaDeath == true) && serverConfig.IsHardcore)
            {
                MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.HARDCORE_PLAYER_DEAD;
                return(new MultiplayerSessionReservation(correlationId, rejectedState));
            }

            if (reservedPlayerNames.Contains(playerName))
            {
                MultiplayerSessionReservationState rejectedState = MultiplayerSessionReservationState.REJECTED | MultiplayerSessionReservationState.UNIQUE_PLAYER_NAME_CONSTRAINT_VIOLATED;
                return(new MultiplayerSessionReservation(correlationId, rejectedState));
            }

            ConnectionAssets assetPackage;

            assetsByConnection.TryGetValue(connection, out assetPackage);
            if (assetPackage == null)
            {
                assetPackage = new ConnectionAssets();
                assetsByConnection.Add(connection, assetPackage);
                reservedPlayerNames.Add(playerName);
            }


            bool   hasSeenPlayerBefore = player != null;
            ushort playerId            = hasSeenPlayerBefore ? player.Id : ++currentPlayerId;

            PlayerContext playerContext  = new PlayerContext(playerName, playerId, !hasSeenPlayerBefore, playerSettings);
            string        reservationKey = Guid.NewGuid().ToString();

            reservations.Add(reservationKey, playerContext);
            assetPackage.ReservationKey = reservationKey;

            return(new MultiplayerSessionReservation(correlationId, playerId, reservationKey));
        }
Пример #4
0
        //public static long GetComponentCount = 0;

        public T Get <T>() where T : IComponent
        {
            //GetComponentCount++;
            IComponent component;

            if (components.TryGetValue(typeof(T), out component))
            {
                return((T)component);
            }
            return(default(T));
        }
Пример #5
0
        private ValidatableElement GetElementOrNew(System.Type entityType)
        {
            ValidatableElement element;

            if (!validators.TryGetValue(entityType, out element))
            {
                IClassValidator cv = GetClassValidator(entityType);
                element = new ValidatableElement(entityType, cv);
                AddValidatableElement(element);
            }
            return(element);
        }
Пример #6
0
        public bool RemoveChild(TKey key)
        {
            IMonohierarchy <T, TKey> child;

            if (DictChildren.TryGetValue(key, out child))
            {
                if (!DictChildren.Remove(key))
                {
                    return(false);
                }
                OnChildRemoved(child);
                return(true);
            }
            return(false);
        }
Пример #7
0
 public void UpdateVehicle(VehicleMovementData vehicleMovement)
 {
     if (vehiclesById.TryGetValue(vehicleMovement.Id, out VehicleModel vehicleModel))
     {
         vehicleModel.Position = vehicleMovement.Position;
         vehicleModel.Rotation = vehicleMovement.Rotation;
     }
 }
        private static Delegate GetCachedDelegate(object delegateKey)
        {
            Delegate result;

            return
                (cachedDelegates.TryGetValue(delegateKey, out result) ? result : null);
        }
Пример #9
0
        internal IRequestResponseCorrelationWrapper TryGetWrapper(Guid correlationId)
        {
            IRequestResponseCorrelationWrapper wrapper;

            _requestWrappers.TryGetValue(correlationId, out wrapper);
            return(wrapper);
        }
Пример #10
0
        public Optional <VehicleModel> GetVehicleModel(NitroxId id)
        {
            VehicleModel vehicleModel;

            vehiclesById.TryGetValue(id, out vehicleModel);
            return(Optional.OfNullable(vehicleModel));
        }
 public void Unsubscribe(Observable <T> observable)
 {
     //lock (SyncObject)
     //{
     if (observable == null)
     {
         return;
     }
     try
     {
         Unsubscriber <T> target = null;
         if (m_DictObservables.TryGetValue(observable, out target))
         {
             m_DictObservables.Remove(observable);
             if (target != null)
             {
                 target.Dispose();
             }
         }
         if (m_DictObservables.Count == 0)
         {
             MessageQueue.Quit();
             MessageQueue.Clear();
         }
     }
     catch (Exception e)
     {
         e.LogError();
     }
     //}
 }
Пример #12
0
        static bool MonitorUpdateDurationInternal(IEnumerator tickable, string threadInfo)
        {
            TaskInfo info;

            bool result;

            if (taskInfos.TryGetValue(tickable.ToString(), out info) == false)
            {
                info = new TaskInfo(tickable);

                info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds);

                info.AddThreadInfo(threadInfo);

                taskInfos.Add(tickable.ToString(), info);
            }
            else
            {
                info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds);

                info.AddThreadInfo(threadInfo);
            }

            _stopwatch.Reset();
            _stopwatch.Start();
            result = tickable.MoveNext();
            _stopwatch.Stop();

            return(result);
        }
Пример #13
0
        public static bool MonitorUpdateDuration(IEnumerator tickable, string runnerName)
        {
            var key = tickable.ToString().FastConcat(runnerName);

#if ENABLE_PIX_EVENTS
            PixWrapper.PIXBeginEventEx(0x11000000, key);
#endif
            _stopwatch.Start();
            var result = tickable.MoveNext();
            _stopwatch.Stop();
#if ENABLE_PIX_EVENTS
            PixWrapper.PIXEndEventEx();
#endif
            lock (LOCK_OBJECT)
            {
                TaskInfo info;

                if (taskInfos.TryGetValue(key, out info) == false)
                {
                    info = new TaskInfo(tickable);
                    info.AddThreadInfo(runnerName.FastConcat(": "));
                    taskInfos.Add(key, ref info);
                }
                else
                {
                    info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds);

                    taskInfos.Update(key, ref info);
                }
            }

            _stopwatch.Reset();

            return(result);
        }
Пример #14
0
        private bool GetGlyphIndex(char c, out GlyphInfo gli)
        {
            GlyphInfo info;

            if (CharMap.TryGetValue(c, out info))
            {
                if (info.ListID > 0 && info.Width > 0)
                {
                    gli = info;
                    return(true);
                }
                else
                {
                    gli = GlyphInfo.Empty;
                    return(false);
                }
            }
            else if (OnDemand)
            {
                lock (SyncObject) {
                    uint glyphindex = Font.GetCharIndex(c);
                    info = CompileCharacter(Font, glyphindex, c);
                    CharMap.Add(c, info);
                    gli = info;
                }
                return(true);
            }

            gli = GlyphInfo.Empty;
            return(false);
        }
Пример #15
0
        public ICache GetSecondLevelCacheRegion(string regionName)
        {
            ICache result;

            allCacheRegions.TryGetValue(regionName, out result);
            return(result);
        }
        public static XmlAttributeOverrides Create(Type objectType)
        {
            XmlAttributeOverrides xOver = null;

            if (!table.TryGetValue(objectType, out xOver))
            {
                // Create XmlAttributeOverrides object.
                xOver = new XmlAttributeOverrides();

                /* Create an XmlTypeAttribute and change the name of the XML type. */
                XmlTypeAttribute xType = new XmlTypeAttribute();
                xType.TypeName = objectType.Name;

                // Set the XmlTypeAttribute to the XmlType property.
                XmlAttributes attrs = new XmlAttributes();
                attrs.XmlType = xType;

                /* Add the XmlAttributes to the XmlAttributeOverrides,
                 * specifying the member to override. */
                xOver.Add(objectType, attrs);

                table.MergeSafe(objectType, xOver);
            }

            return(xOver);
        }
        ThreadSafeStack <T> ReturnValidPool(ThreadSafeDictionary <int, ThreadSafeStack <T> > pools, int pool)
        {
            if (pools.TryGetValue(pool, out var localPool) == false)
            {
                pools[pool] = localPool = new ThreadSafeStack <T>();
            }

            return(localPool);
        }
Пример #18
0
 public bool TryGetValue(string key, out TextureImage image)
 {
     if (String.IsNullOrEmpty(key))
     {
         image = null;
         return(false);
     }
     return(m_Images.TryGetValue(key, out image));
 }
Пример #19
0
        public IEntity EntityByID(int id)
        {
            Entity entity;

            if (entities.TryGetValue(id, out entity))
            {
                return(entity);
            }
            return(null);
        }
Пример #20
0
 public SerializeMode this[string name]
 {
     get {
         SerializeMode n = SerializeMode.None;
         if (Rules.TryGetValue(name, out n))
         {
             return(n);
         }
         return(SerializeMode.None);
     }
 }
Пример #21
0
        public static bool MonitorUpdateDuration <T
#if ENABLE_PLATFORM_PROFILER
                                                  , PP
#endif
                                                  >(T sveltoTask, string runnerName
#if ENABLE_PLATFORM_PROFILER
                                                    , PP profiler
#endif
                                                    )
            where T : ISveltoTask
#if ENABLE_PLATFORM_PROFILER
            where PP : IPlatformProfiler
#endif
        {
            var  key = sveltoTask.ToString().FastConcat(runnerName);
            bool result;

#if ENABLE_PLATFORM_PROFILER
            using (profiler.Sample(sveltoTask.ToString()))
#endif
            {
                _stopwatch.Start();
#if ENABLE_PIX_EVENTS
                PixWrapper.PIXBeginEventEx(0x11000000, key);
#endif
                result = sveltoTask.MoveNext();
#if ENABLE_PIX_EVENTS
                PixWrapper.PIXEndEventEx();
#endif
                _stopwatch.Stop();
            }

            lock (LOCK_OBJECT)
            {
                if (taskInfos.TryGetValue(key, out var info) == false)
                {
                    info = new TaskInfo(sveltoTask.ToString());
                    info.AddThreadInfo(runnerName.FastConcat(": "));
                    taskInfos.Add(key, ref info);
                }
                else
                {
                    info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds);

                    taskInfos.Update(key, ref info);
                }
            }

            _stopwatch.Reset();

            return(result);
        }
        private int ThreadSafeDictionaryReadTest(int count)
        {
            int j = 0, value;

            for (int i = 0; i < count; i++)
            {
                if (tsd.TryGetValue(i % FillCount, out value))
                {
                    j += value;
                }
            }

            return(j);
        }
Пример #23
0
        object IDictionary.this[object key]
        {
            get
            {
                switch (key)
                {
                case null:
                    // key could be null
                    throw new ArgumentNullException(nameof(key));

                case TKey keyAsTKey when _wrapped.TryGetValue(keyAsTKey, out var result):
                    return(result);

                default:
                    return(null);
                }
            }
            set
            {
                switch (key)
                {
                case null:
                    // key could be null
                    // ConcurrentDictionary hates null
                    throw new ArgumentNullException(nameof(key));

                case TKey keyAsTKey when value is TValue valueAsTValue:
                    this[keyAsTKey] = valueAsTValue;
                    break;

                default:
                    break;
                }

                throw new ArgumentException(string.Empty, nameof(value));
            }
        }
Пример #24
0
        public static bool MonitorUpdateDuration <T, PP>(ref T sveltoTask, string runnerName, PP profiler)
            where T : ISveltoTask where PP : IPlatformProfiler
        {
            var  samplerName = sveltoTask.name;
            var  key         = samplerName.FastConcat(runnerName);
            bool result;

            using (profiler.Sample(samplerName))
            {
                _stopwatch.Start();
#if ENABLE_PIX_EVENTS
                PixWrapper.PIXBeginEventEx(0x11000000, key);
#endif
                result = sveltoTask.MoveNext();
#if ENABLE_PIX_EVENTS
                PixWrapper.PIXEndEventEx();
#endif
                _stopwatch.Stop();
            }

            lock (LOCK_OBJECT)
            {
                if (taskInfos.TryGetValue(key, out var info) == false)
                {
                    info = new TaskInfo(samplerName);
#warning Todo for seb: avoid allocation here please
                    info.AddThreadInfo(runnerName);
                    taskInfos.Add(key, ref info);
                }
                else
                {
                    info.AddUpdateDuration(_stopwatch.Elapsed.TotalMilliseconds);

                    taskInfos.Update(key, ref info);
                }
            }

            _stopwatch.Reset();

            return(result);
        }
Пример #25
0
 public bool TryResolveType(string name, out TypeConverterTuple ttc)
 {
     if (TypeConverters.TryGetValue(name, out ttc))
     {
         return(true);
     }
     else
     {
         Type t = Type.GetType(name, false, false);
         if (t == null)
         {
             return(false);
         }
         else
         {
             TypeConverter      tc   = TypeDescriptor.GetConverter(t);
             TypeConverterTuple nttc = new TypeConverterTuple(t, tc);
             TypeConverters.Add(name, nttc);
             ttc = nttc;
             return(true);
         }
     }
 }
Пример #26
0
        /// <summary>
        /// Gets a dynamically created Comparison delegate that compare instances based on a compound property expression
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="properties">List of property names representing the property or fields to get. E.g. prop0.prop1.prop2 is represented as a list with items "prop0", "prop1" and "prop2".</param>
        /// <param name="ascending">true to search in ascending order, false to sort in descending order</param>
        /// <returns>
        /// A Comparison delegate for the given property.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">if properties is null.</exception>
        /// <exception cref="System.ArgumentException">If any of the strings in properties is not recognized as a public property or field.</exception>
        public static Comparison GetPropertyComparison(Type type, List <String> properties, bool ascending)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            Comparison comparison;

            if (cache.TryGetValue(properties, out comparison) == false)
            {
                comparison = CreatePropertyComparison(type, properties, true);
                cache[new List <String>(properties)] = comparison;
            }

            if (ascending)
            {
                return(comparison);
            }
            else
            {
                return((Comparison) delegate(object x, object y) { return -comparison(x, y); });
            }
        }
Пример #27
0
        /// <summary>
        /// Create or reuse a XmlSerializer with a specific override!
        /// The .NET Factory method "CreateSerializer" do not support caching with a custom override!
        /// This method is optimized for speed and is threadsafe.
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="type"></param>
        /// <param name="overrides"></param>
        /// <returns></returns>
        public static XmlSerializer GetSerializer(this XmlSerializerFactory factory, Type type, XmlAttributeOverrides overrides)
        {
            XmlSerializer result = null;

            string key = type.AssemblyQualifiedName;

            if (overrides != null)
            {
                key += overrides.GetHashCode();

                if (!serializerTable.TryGetValue(key, out result))
                {
                    result = factory.CreateSerializer(type, overrides);
                    serializerTable.MergeSafe(key, result);
                }
            }
            else
            {
                result = factory.CreateSerializer(type);
            }

            return(result);
        }
Пример #28
0
        private object ConstructObjectInternal(Type type)
        {
            Func <PoorMansIoC, object> factory;

            if (_factoryDelegates.TryGetValue(type, out factory))
            {
                var instance = factory(this);
                RegisterInstance(instance);
                return(instance);
            }
            else
            {
                var concreteType = ExtractConcreteTypeFor(type);
                var args         = concreteType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                                   .Single()
                                   .GetParameters()
                                   .Select(p => Resolve(p.ParameterType))
                                   .ToArray();

                var instance = Activator.CreateInstance(concreteType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, args, null);
                RegisterInstance(instance);
                return(instance);
            }
        }
Пример #29
0
        private void InitFont(float scaleFactor)
        {
            try {
                System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

                ScaleFactor   = scaleFactor;
                YOffsetScaled = YOffset * scaleFactor;

                // Reset everything
                Clear();

                Font = new Face(FontManager.Library, FilePath);

                // Go on

                float size = Size.Scale(ScaleFactor);

                Fixed26Dot6 sz = new Fixed26Dot6(size / 64);
                Font.SetCharSize(sz, sz, 72, 72);

                int pixelSize = (size * 1.3334).Ceil();
                Font.SetPixelSizes((uint)pixelSize, (uint)pixelSize);

                GlyphCount = Font.GlyphCount;
                int glyphCount = GlyphCount;
                Monospace = Font.FaceFlags.HasFlag(FaceFlags.FixedWidth);

                string tmpName = Font.GetPostscriptName();
                if (!String.IsNullOrEmpty(tmpName))
                {
                    Name = tmpName;
                }


                // We support 4 different glyph loading strategies:
                //
                // (1) All: all glyphs loaded at once on start
                // (2) Filtered: all filtered glyphs loaded at once on start
                // (3) OnDemand: no glyphs loaded at start, all glyphs on demand


                if (OnDemand)
                {
                    // Startegy (3)
                    GlyphCount = 0;
                }
                else if (Filter > GlyphFilterFlags.OnDemand)
                {
                    // Startegy (2)
                    // If we have a Filter set, let's count the number of valid glyphs
                    // to minimize graphics memory.
                    uint glyphindex;
                    uint cc    = Font.GetFirstChar(out glyphindex);
                    int  count = 0;
                    while (glyphindex > 0)
                    {
                        char c = (char)cc;
                        if (Filter.IsValid(c))
                        {
                            count++;
                        }
                        cc = Font.GetNextChar(cc, out glyphindex);
                    }
                    GlyphCount = count;
                }
                else
                {
                    // Strategy (1), loading the entire font
                }

                m_Textures = new int[Math.Max(32, GlyphCount)];
                CharMap    = new ThreadSafeDictionary <char, GlyphInfo>(Math.Max(31, GlyphCount));

                if (!OnDemand)
                {
                    // Strategy (1) + (2): Load all or filtered glyphs
                    m_ListBase = GL.GenLists(GlyphCount);
                    GL.GenTextures(GlyphCount, m_Textures);

                    uint glyphindex;
                    uint cc = Font.GetFirstChar(out glyphindex);
                    while (glyphindex > 0)
                    {
                        char c = (char)cc;
                        if (!CharMap.ContainsKey(c) && Filter.IsValid(c))
                        {
                            try {
                                CharMap.Add(c, CompileCharacter(Font, glyphindex, c));
                            } catch (Exception ex) {
                                ex.LogWarning();
                            }
                        }
                        cc = Font.GetNextChar(cc, out glyphindex);
                    }
                    CharMap.TryGetValue(SpecialCharacters.Ellipsis, out m_EllipsisGlyphIndex);
                }
                else
                {
                    try {
                        GetGlyphIndex(SpecialCharacters.Ellipsis, out m_EllipsisGlyphIndex);
                    } catch (Exception ex) {
                        ex.LogError();
                    }
                }

                //if (Height <= 1)
                //Height = pixelSize.NextPowerOf2();
                //Height = pixelSize * 1.33335f;

                Height = pixelSize;

                float fscale = Height / Font.Height * 1.33334f;
                //float fscale = Height / Font.Height * 0.776f;

                Ascender  = Font.Ascender * fscale;
                Descender = Font.Descender * fscale;
                //HalfHeight = Height / 2;

                Height     = (Ascender).Ceil();
                HalfHeight = (int)(Height / 2);

                //LineHeight = Height * 1.42f * LineSpacing;
                LineHeight = (int)((Height * 1.42f * LineSpacing) + 0.5f);

                //TextBoxHeight = ((Height * 2f) + (ScaleFactor * 2f)).Ceil();
                //TextBoxHeight = (int)(Height * 1.85f + 0.5f);
                TextBoxHeight = (int)(Height * 1.85f + 2);
                CaptionHeight = (int)(Height * 1.55 + 2);

                YOffsetScaled = (YOffset * ScaleFactor) - HalfHeight;

                if (OnDemand)
                {
                    Count.LogInformation("Font {0} ({1}), {2}/{3} glyphs pre-loaded in {4} ms, more glyphs are loaded on demand.", Name, Size, Count, glyphCount, sw.ElapsedMilliseconds);
                }
                else
                {
                    Count.LogInformation("Font {0} ({1}), {2}/{3} glyphs loaded in {4} ms.", Name, Size, Count, glyphCount, sw.ElapsedMilliseconds);
                }
            } catch (Exception ex) {
                ex.LogError();
            } finally {
                if (!OnDemand && Font != null)
                {
                    Font.Dispose();
                    Font = null;
                }
            }
        }
Пример #30
0
 /// <summary>
 ///     Returns the specified queue if it already exists but does not create one if it does not.
 /// </summary>
 /// <returns>True if the queue exists; false otherwise.</returns>
 /// <remarks>
 ///     Senders should use this so that we don't fill up in-memory queues with messages for which there are no handlers.
 ///     Receivers should use GetOrCreateMessageQueue.
 /// </remarks>
 public bool TryGetExistingMessageQueue(string path, out AsyncBlockingCollection <NimbusMessage> queue)
 {
     return(_messageQueues.TryGetValue(path, out queue));
 }