public T GetObject <T>(int index) where T : ComponentBase, new()
    {
        return(new T());

        //Debug.Log("GetObject " + index);

        T obj = null;
        FastStack <ComponentBase> stack = poolList[index];

        if (stack == null)
        {
            stack           = new FastStack <ComponentBase>();
            poolList[index] = stack;
        }
        if (stack.Count > 0)
        {
            obj = (T)stack.Pop();
            //stack.RemoveAt(0);
        }
        else
        {
            obj = new T();
        }

        return(obj);
    }
示例#2
0
        /// <summary>
        /// Create an uninitialized LSAgent
        /// </summary>
        /// <returns>The raw agent.</returns>
        /// <param name="agentCode">Agent code.</param>
        /// <param name="isBare">If set to <c>true</c> is bare.</param>
        public static LSAgent CreateRawAgent(string agentCode)
        {
            if (!ResourceManager.IsValidAgentCode(agentCode))
            {
                throw new System.ArgumentException(string.Format("Agent code '{0}' not found.", agentCode));
            }
            FastStack <LSAgent> cache    = CachedAgents[agentCode];
            LSAgent             curAgent = null;

            if (cache.IsNotNull() && cache.Count > 0)
            {
                curAgent = cache.Pop();
                ushort agentCodeID = ResourceManager.GetAgentCodeIndex(agentCode);
                Debug.Log(curAgent.TypeIndex);
                TypeAgentsActive[agentCodeID][curAgent.TypeIndex] = true;
            }
            else
            {
                IAgentData interfacer = ResourceManager.AgentCodeInterfacerMap[agentCode];

                curAgent = GameObject.Instantiate(ResourceManager.GetAgentTemplate(agentCode).gameObject).GetComponent <LSAgent>();
                curAgent.Setup(interfacer);

                RegisterRawAgent(curAgent);
            }
            return(curAgent);
        }
示例#3
0
        public BoardState(bool allocateStacks)
        {
            Pieces = new ulong[2][];
            Pieces[Color.White] = new ulong[6];
            Pieces[Color.Black] = new ulong[6];

            Occupancy    = new ulong[2];
            CastlingDone = new bool[2];
            Material     = new int[2];

            Position = new int[2][];
            Position[Color.White] = new int[2];
            Position[Color.Black] = new int[2];

            PieceTable = new int[64];

            if (allocateStacks)
            {
                _killedPieces            = new FastStack <int>(512);
                _enPassants              = new FastStack <ulong>(512);
                _castlings               = new FastStack <Castling>(512);
                _promotedPieces          = new FastStack <int>(512);
                _hashes                  = new FastStack <ulong>(512);
                _pawnHashes              = new FastStack <ulong>(512);
                _irreversibleMovesCounts = new FastStack <int>(512);
            }
        }
示例#4
0
 public RuleTable(int elems)
 {
     ActiveIndices = new FastStack(elems);
     SupportStack  = new FastStack(elems);
     ActiveSlots   = new bool[elems];
     SupportSlots  = new bool[elems];
 }
示例#5
0
 public RuleTable(int elems)
 {
     Active = new Func<float, RuleResult>[elems];
     ActiveIndices = new FastStack(elems);
     SupportStack = new FastStack(elems);
     ActiveSlots = new bool[elems];
 }
        /// <summary>
        /// Create an uninitialized RTSAgent
        /// </summary>
        /// <returns>The raw agent.</returns>
        /// <param name="agentCode">Agent code.</param>
        /// <param name="isBare">If set to <c>true</c> is bare.</param>
        public static RTSAgent CreateRawAgent(string agentCode, Vector2d startPosition = default(Vector2d), Vector2d startRotation = default(Vector2d))
        {
            if (!GameResourceManager.IsValidAgentCode(agentCode))
            {
                throw new System.ArgumentException(string.Format("Agent code '{0}' not found.", agentCode));
            }
            FastStack <RTSAgent> cache    = CachedAgents[agentCode];
            RTSAgent             curAgent = null;

            if (cache.IsNotNull() && cache.Count > 0)
            {
                curAgent = cache.Pop();
                ushort agentCodeID = GameResourceManager.GetAgentCodeIndex(agentCode);
                Debug.Log(curAgent.TypeIndex);
                TypeAgentsActive[agentCodeID][curAgent.TypeIndex] = true;
            }
            else
            {
                IAgentData interfacer = GameResourceManager.AgentCodeInterfacerMap[agentCode];

                Vector3    pos = startPosition.ToVector3();
                Quaternion rot = new Quaternion(0, startRotation.y, 0, startRotation.x);

                curAgent = GameObject.Instantiate(GameResourceManager.GetAgentTemplate(agentCode).gameObject, pos, rot).GetComponent <RTSAgent>();
                curAgent.Setup(interfacer);

                RegisterRawAgent(curAgent);
            }
            return(curAgent);
        }
示例#7
0
 public RuleTable(int elems)
 {
     Active        = new Func <float, RuleResult> [elems];
     ActiveIndices = new FastStack(elems);
     SupportStack  = new FastStack(elems);
     ActiveSlots   = new bool[elems];
 }
示例#8
0
 internal CodeWriter(FastList<Op> ops, FastList<Int32> opData)
 {
     this.ops = ops;
     this.opData = opData;
     labels = new FastList<Int32>();
     fixups = new FastList<Int32>();
     locals = new FastStack<StackSize>();
 }
示例#9
0
文件: CodeWriter.cs 项目: ngoffee/ela
 internal CodeWriter(FastList <Op> ops, FastList <Int32> opData)
 {
     this.ops    = ops;
     this.opData = opData;
     labels      = new FastList <Int32>();
     fixups      = new FastList <Int32>();
     locals      = new FastStack <StackSize>();
 }
示例#10
0
        public GameObjectPool(T item, int startCapacity, bool prefill, bool allowExpansion)
        {
            proto = item;
            this.allowExpansion = allowExpansion;
            this.prefill        = prefill;

            pool = new FastStack <T> (startCapacity);
        }
示例#11
0
 internal DebugWriter()
 {
     Symbols = new DebugInfo();
     scopes = new FastStack<ScopeSym>();
     funs = new FastStack<FunSym>();
     var glob = new ScopeSym(0, 0, 0, 0, 0) { EndOffset = Int32.MaxValue };
     scopes.Push(glob);
     Symbols.Scopes.Add(glob);
 }
 public TemplateRewriterContext(IScriptOutput output, TemplateRewriterOptions options = default(TemplateRewriterOptions))
 {
     _isWhileLoop = new FastStack <bool>(4);
     Options      = options;
     if (options.Mode != ScriptMode.Default)
     {
         throw new ArgumentException($"The rendering mode `{options.Mode}` is not supported. Only `ScriptMode.Default` is currently supported");
     }
     _output = output;
 }
示例#13
0
 private Processor(Processor parentProcessor)
 {
     m_ValueStack     = new FastStack <DynValue>(STACK_SIZE);
     m_ExecutionStack = new FastStack <CallStackItem>(STACK_SIZE);
     m_Debug          = parentProcessor.m_Debug;
     m_RootChunk      = parentProcessor.m_RootChunk;
     m_GlobalTable    = parentProcessor.m_GlobalTable;
     m_Script         = parentProcessor.m_Script;
     m_Parent         = parentProcessor;
     m_State          = CoroutineState.NotStarted;
 }
示例#14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TemplateContext" /> class.
        /// </summary>
        /// <param name="builtin">The builtin object used to expose builtin functions, default is <see cref="GetDefaultBuiltinObject"/>.</param>
        public TemplateContext(ScriptObject builtin)
        {
            BuiltinObject = builtin ?? GetDefaultBuiltinObject();
            EnableOutput  = true;
            EnableBreakAndContinueAsReturnOutsideLoop = false;
            LoopLimit      = 1000;
            RecursiveLimit = 100;
            MemberRenamer  = StandardMemberRenamer.Default;

            RegexTimeOut = TimeSpan.FromSeconds(10);

            TemplateLoaderParserOptions = new ParserOptions();
            TemplateLoaderLexerOptions  = LexerOptions.Default;

            NewLine = Environment.NewLine;

            _outputs = new FastStack <IScriptOutput>(4);
            _output  = new StringBuilderOutput();
            _outputs.Push(_output);

            _globalStores    = new FastStack <IScriptObject>(4);
            _localStores     = new FastStack <ScriptObject>(4);
            _loopStores      = new FastStack <ScriptObject>(4);
            _availableStores = new FastStack <ScriptObject>(4);
            _cultures        = new FastStack <CultureInfo>(4);
            _caseValues      = new FastStack <object>(4);

            _localTagsStack = new FastStack <Dictionary <object, object> >(1);
            _loopTagsStack  = new FastStack <Dictionary <object, object> >(1);
            _availableTags  = new FastStack <Dictionary <object, object> >(4);

            _sourceFiles = new FastStack <string>(4);

            _memberAccessors = new Dictionary <Type, IObjectAccessor>();
            _listAccessors   = new Dictionary <Type, IListAccessor>();
            _loops           = new FastStack <ScriptLoopStatementBase>(4);

            BlockDelegates = new FastStack <ScriptBlockStatement>(4);

            _availablePipeArguments = new FastStack <ScriptPipeArguments>(4);
            _pipeArguments          = new FastStack <ScriptPipeArguments>(4);

            _isFunctionCallDisabled = false;

            CachedTemplates = new Dictionary <string, Template>();

            Tags = new Dictionary <object, object>();

            PushPipeArguments();

            // Ensure that builtin is registered first
            PushGlobal(BuiltinObject);
        }
示例#15
0
 public void StepAll(float dt) {
   for (int i = 0; i < ActiveIndices.Top; i++ ){
     if(Active[i](dt) == RuleResult.Done)
       ActiveSlots[i] = false;
     else
       SupportStack.Push(i);
   }
   ActiveIndices.Clear();
   var tmp = SupportStack;
   SupportStack = ActiveIndices;
   ActiveIndices = tmp;
 }
示例#16
0
    /// <summary>
    /// Initializes a new instance of the <see cref="ResourcePool{T}"/> class with the given
    /// un-/initialize methods.
    /// </summary>
    /// <param name="create">
    /// The function that creates a new item of type <typeparamref name="T"/>.
    /// </param>
    /// <param name="initialize">
    /// The method that is executed on an item when it is obtained from the pool - can be
    /// <see langword="null"/>.
    /// </param>
    /// <param name="uninitialize">
    /// The method that is executed on an item when it is recycled - can be <see langword="null"/>.
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// <paramref name="create"/> is <see langword="null"/>.
    /// </exception>
    public ResourcePool(Func<T> create, Action<T> initialize, Action<T> uninitialize)
    {
      if (create == null)
        throw new ArgumentNullException("create");

      _create = create;
      _initialize = initialize;
      _uninitialize = uninitialize;
      _stack = new FastStack<T>();

      Register(this);
    }
示例#17
0
        //Takes the value and execution stack from recycleProcessor
        internal Processor(Processor parentProcessor, Processor recycleProcessor)
        {
            m_ValueStack     = recycleProcessor.m_ValueStack;
            m_ExecutionStack = recycleProcessor.m_ExecutionStack;

            m_Debug       = parentProcessor.m_Debug;
            m_RootChunk   = parentProcessor.m_RootChunk;
            m_GlobalTable = parentProcessor.m_GlobalTable;
            m_Script      = parentProcessor.m_Script;
            m_Parent      = parentProcessor;
            m_State       = CoroutineState.NotStarted;
        }
示例#18
0
        internal DebugWriter()
        {
            Symbols = new DebugInfo();
            scopes  = new FastStack <ScopeSym>();
            funs    = new FastStack <FunSym>();
            var glob = new ScopeSym(0, 0, 0, 0, 0, true)
            {
                EndOffset = Int32.MaxValue
            };

            scopes.Push(glob);
            Symbols.Scopes.Add(glob);
        }
示例#19
0
        public Processor(Script script, Table globalContext, ByteCode byteCode)
        {
            m_ValueStack      = new FastStack <DynValue>(STACK_SIZE);
            m_ExecutionStack  = new FastStack <CallStackItem>(STACK_SIZE);
            m_CoroutinesStack = new List <Processor>();

            m_Debug       = new DebugContext();
            m_RootChunk   = byteCode;
            m_GlobalTable = globalContext;
            m_Script      = script;
            m_State       = CoroutineState.Main;
            DynValue.NewCoroutine(new Coroutine(this));             // creates an associated coroutine for the main processor
        }
示例#20
0
        /// <summary>
        /// Just do some initialization and call the main routine,
        /// that is analyze_cell()
        /// </summary>
        public void GenerateMaze(int sizeX, int sizeY, int smoothness, int seed)
        {
            iSmooth    = smoothness;
            MazeSizeX  = sizeX;
            MazeSizeY  = sizeY;
            maze_base  = new int[MazeSizeX * MazeSizeY];
            maze_data  = new byte[MazeSizeX, MazeSizeY];
            stateStack = new FastStack <cMazeState>();
            r          = new Random(seed);
            MazeInit();
            cMazeState state = new cMazeState(r.Next() % MazeSizeX, r.Next() % MazeSizeY, 0);

            analyze_cell(state, r);
        }
示例#21
0
        public ScriptPrinter(IScriptOutput output, ScriptPrinterOptions options = default(ScriptPrinterOptions))
        {
            _isWhileLoop = new FastStack <bool>(4);
            Options      = options;
            if (options.Mode != ScriptMode.Default && options.Mode != ScriptMode.ScriptOnly)
            {
                throw new ArgumentException($"The rendering mode `{options.Mode}` is not supported. Only `ScriptMode.Default` or `ScriptMode.ScriptOnly` are currently supported");
            }

            _isScriptOnly      = options.Mode == ScriptMode.ScriptOnly;
            _isInCode          = _isScriptOnly || (options.Mode == ScriptMode.FrontMatterOnly || options.Mode == ScriptMode.FrontMatterAndContent);
            _output            = output;
            _hasEndOfStatement = true; // We start as if we were on a new line
        }
示例#22
0
        /// <summary>
        /// Pops a previous <see cref="ScriptVariableScope"/>.
        /// </summary>
        internal void PopVariableScope(ref FastStack <ScriptObject> stores)
        {
            if (stores.Count == 0)
            {
                // Should not happen at runtime
                throw new InvalidOperationException("Invalid number of matching push/pop VariableScope.");
            }

            var store = stores.Pop();

            // The store is cleanup once it is pushed back
            store.Clear();

            _availableStores.Push(store);
        }
    public void PutObject(int index, ComponentBase obj)
    {
        return;

        IRelease heapObj = obj as IRelease;

        if (heapObj != null)
        {
            heapObj.Release();
        }
        FastStack <ComponentBase> stack = poolList[index];

        if (stack == null)
        {
            stack           = new FastStack <ComponentBase>();
            poolList[index] = stack;
        }
        stack.Add(obj);
    }
示例#24
0
    public void StepAll(float dt)
    {
        for (int i = 0; i < ActiveIndices.Top; i++)
        {
            if (Active[i](dt) == RuleResult.Done)
            {
                ActiveSlots[i] = false;
            }
            else
            {
                SupportStack.Push(i);
            }
        }
        ActiveIndices.Clear();
        var tmp = SupportStack;

        SupportStack  = ActiveIndices;
        ActiveIndices = tmp;
    }
        public static void Initialize(GameObject[] agentObjects)
        {
            if (FirstInitializeStatic)
            {
                AgentCodes = (AgentCode[])System.Enum.GetValues (typeof(AgentCode));
                CachedAgents = new FastStack<LSAgent>[AgentCodes.Length];
                AgentObjects = new GameObject[AgentCodes.Length];
                for (i = 0; i < AgentCodes.Length; i++)
                {
                    AgentObjects[(int)AgentCodes[i]] = agentObjects[i];
                }
                FirstInitializeStatic = false;
            }
            GlobalActiveAgents = new Dictionary<ushort, LSAgent> (1024);

            OpenGlobalIDs.FastClear ();
            PeakGlobalID = 0;
            InstanceManagers.Clear ();
        }
示例#26
0
        public void Update(FastStack <TreePage> stack, TreePage newVal)
        {
            var oldNode = stack.Pop();

            stack.Push(newVal);

            var oldPageNumber = oldNode.PageNumber;
            var newPageNumber = newVal.PageNumber;

            if (oldPageNumber == newPageNumber)
            {
                _pagesByNum[oldPageNumber] = newVal;
                return;
            }

            _anyOverrides = true;
            _pagesByNum[oldPageNumber] = newVal;
            _pagesByNum.Add(newPageNumber, newVal);
        }
        private static LSProjectile RawCreate(string projCode)
        {
            if (ProjectilePool.ContainsKey(projCode) == false)
            {
                Debug.Log(projCode + " fired by " + Attack.LastFire + " Caused boom");
                return(null);
            }
            FastStack <LSProjectile> pool    = ProjectilePool[projCode];
            LSProjectile             curProj = null;

            if (pool.Count > 0)
            {
                curProj = pool.Pop();
            }
            else
            {
                curProj = NewProjectile(projCode);
            }
            return(curProj);
        }
示例#28
0
    public void ComputeSubTreeSize(int root)
    {
        const long X     = 1000000000;
        var        stack = new FastStack <long>(N + 1);

        stack.Push(root * X);
        par[root] = -1;
        d[root]   = 0;

        while (stack.Any())
        {
            var val = stack.Peek();
            var u   = (int)(val / X);
            var it  = (int)(val % X);

            if (it == G[u].Count)
            {
                stack.Pop();
                subTreeSize[u]++;
                if (par[u] >= 0)
                {
                    subTreeSize[par[u]] += subTreeSize[u];
                }
            }
            else
            {
                var to = G[u][it].to;
                stack.Last++;
                if (to == par[u])
                {
                    continue;
                }

                par[to] = u;
                d[to]   = d[u] + 1;
                stack.Push(to * X);
            }
        }
    }
示例#29
0
        public static void WorksForReferenceTypes()
        {
            var c = new FastStack <string>();

            c.Push("1");
            Assert.Equal(1, c.Count);
            Assert.Equal("1", c.Peek());
            Assert.Equal(1, c.Count);
            Assert.Equal("1", c.Pop());
            Assert.Equal(0, c.Count);
            c.Push("1");
            c.Push("2");
            Assert.Equal(2, c.Count);
            Assert.Equal("2", c.Peek());
            Assert.Equal(2, c.Count);
            Assert.Equal("2", c.Pop());
            Assert.Equal(1, c.Count);
            Assert.Equal("1", c.Peek());
            Assert.Equal(1, c.Count);
            Assert.Equal("1", c.Pop());
            Assert.Equal(0, c.Count);
        }
示例#30
0
        public static void WorksForValueTypes()
        {
            var c = new FastStack <int>();

            c.Push(1);
            Assert.Equal(1, c.Count);
            Assert.Equal(1, c.Peek());
            Assert.Equal(1, c.Count);
            Assert.Equal(1, c.Pop());
            Assert.Equal(0, c.Count);
            c.Push(1);
            c.Push(2);
            Assert.Equal(2, c.Count);
            Assert.Equal(2, c.Peek());
            Assert.Equal(2, c.Count);
            Assert.Equal(2, c.Pop());
            Assert.Equal(1, c.Count);
            Assert.Equal(1, c.Peek());
            Assert.Equal(1, c.Count);
            Assert.Equal(1, c.Pop());
            Assert.Equal(0, c.Count);
        }
示例#31
0
        public static void DoesntHoldReferences()
        {
            var wr1 = new WeakReference(new object());
            var wr2 = new WeakReference(new object());
            var c   = new FastStack <object>();

            c.Push(wr1.Target);
            c.Push(wr2.Target);
            GCEx.CollectAndWait();
            Assert.Equal(2, c.Count);
            Assert.True(wr1.IsAlive);
            Assert.True(wr2.IsAlive);
            c.Pop();
            GCEx.CollectAndWait();
            Assert.Equal(1, c.Count);
            Assert.True(wr1.IsAlive);
            Assert.False(wr2.IsAlive);
            c.Pop();
            GCEx.CollectAndWait();
            Assert.Equal(0, c.Count);
            Assert.False(wr1.IsAlive);
            Assert.False(wr2.IsAlive);
        }
示例#32
0
 public RuleTable(int elems)
 {
     ActiveIndices = new FastStack(elems);
     SupportStack = new FastStack(elems);
     ActiveSlots = new bool[elems];
 }
示例#33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TemplateContext" /> class.
        /// </summary>
        /// <param name="builtin">The builtin object used to expose builtin functions, default is <see cref="GetDefaultBuiltinObject"/>.</param>
        public TemplateContext(ScriptObject builtin)
        {
            BuiltinObject = builtin ?? GetDefaultBuiltinObject();
            EnableOutput  = true;
            EnableBreakAndContinueAsReturnOutsideLoop = false;
            EnableRelaxedTargetAccess   = false;
            EnableRelaxedMemberAccess   = true;
            EnableRelaxedFunctionAccess = false;
            EnableRelaxedIndexerAccess  = true;
            LoopLimit      = 1000;
            RecursiveLimit = 100;
            LimitToString  = 0;
            MemberRenamer  = StandardMemberRenamer.Default;

            RegexTimeOut = TimeSpan.FromSeconds(10);

            TemplateLoaderParserOptions = new ParserOptions();
            TemplateLoaderLexerOptions  = LexerOptions.Default;

            NewLine = Environment.NewLine;

            Language = ScriptLang.Default;

            _outputs = new FastStack <IScriptOutput>(4);
            _output  = new StringBuilderOutput();
            _outputs.Push(_output);

            _globalStores           = new FastStack <IScriptObject>(4);
            _availableLocalContexts = new FastStack <LocalContext>(4);
            _localContexts          = new FastStack <LocalContext>(4);
            _availableStores        = new FastStack <ScriptObject>(4);
            _cultures   = new FastStack <CultureInfo>(4);
            _caseValues = new FastStack <object>(4);

            _availableTags = new FastStack <Dictionary <object, object> >(4);

            _sourceFiles = new FastStack <string>(4);

            _memberAccessors = new Dictionary <Type, IObjectAccessor>();
            _listAccessors   = new Dictionary <Type, IListAccessor>();
            _loops           = new FastStack <ScriptLoopStatementBase>(4);

            BlockDelegates = new FastStack <ScriptBlockStatement>(4);

            _availablePipeArguments         = new FastStack <ScriptPipeArguments>(4);
            _pipeArguments                  = new FastStack <ScriptPipeArguments>(4);
            _availableScriptExpressionLists = new FastStack <List <ScriptExpression> >(4);
            _availableReflectionArguments   = new object[ScriptFunctionCall.MaximumParameterCount + 1][];
            for (int i = 0; i < _availableReflectionArguments.Length; i++)
            {
                _availableReflectionArguments[i] = new object[i];
            }
            _isFunctionCallDisabled = false;

            CachedTemplates = new Dictionary <string, Template>();

            Tags = new Dictionary <object, object>();

            // Ensure that builtin is registered first
            PushGlobal(BuiltinObject);
        }
示例#34
0
 private void DefloodLight(IEnumerable<Vector3i> start)
 {
     FastStack<Vector3i> q = new FastStack<Vector3i>();
     q.Initialize(1024);
     Vector3i ss = new Vector3i();
     foreach (var s in start)
     {
         q.Push(s);
         ss = s;
     }
     Dictionary<Vector3i, bool> reflood = new Dictionary<Vector3i, bool>();
     int searched = 1;
     for (; ; )
     {
         if (q.Count == 0)
         {
             break;
         }
         Vector3i v = q.Pop();
         searched++;
         if (distancesquare(v, new Vector3i(ss.x, ss.y, ss.z)) > maxlight * 2 * maxlight * 2)
         {
             continue;
         }
         int vblock = map.GetBlock(v.x, v.y, v.z);
         if (!data.GrassGrowsUnder(vblock)
             && data.GetLightRadius(vblock) == 0)
         {
             continue;
         }
         int vlight = LightGetBlock(v.x, v.y, v.z);
         if (vlight == maxlight
             || data.GetLightRadius(vblock) != 0)
         {
             reflood[v] = true;
             continue;
         }
         if (vlight == minlight)
         {
             continue;
         }
         SetLight(v.x, v.y, v.z, minlight);
         foreach (var n in BlocksNear(v.x, v.y, v.z))
         {
             if (!MapUtil.IsValidPos(map, n.x, n.y, n.z))
             {
                 continue;
             }
             if (LightGetBlock(n.x, n.y, n.z) < vlight)
             {
                 q.Push(n);
             }
             else
             {
                 reflood[n] = true;
             }
         }
     }
     //Console.WriteLine("reflood: {0}, searched: {1}", reflood.Keys.Count, searched);
     foreach (var p in reflood.Keys)
     {
         currentlightchunk = null;
         FloodLight(p.x, p.y, p.z);
     }
 }
示例#35
0
        private void BackgroundLogger()
        {
            NativeMemory.EnsureRegistered();
            try
            {
                Interlocked.Increment(ref _generation);
                var threadStates         = new List <WeakReference <LocalThreadWriterState> >();
                var threadStatesToRemove = new FastStack <WeakReference <LocalThreadWriterState> >();
                while (_keepLogging)
                {
                    try
                    {
                        const int maxFileSize = 1024 * 1024 * 256;
                        using (var currentFile = GetNewStream(maxFileSize))
                        {
                            var sizeWritten = 0;

                            var foundEntry = true;

                            while (sizeWritten < maxFileSize)
                            {
                                if (foundEntry == false)
                                {
                                    if (_keepLogging == false)
                                    {
                                        return;
                                    }

                                    _hasEntries.Wait();
                                    if (_keepLogging == false)
                                    {
                                        return;
                                    }

                                    _hasEntries.Reset();
                                }

                                foundEntry = false;
                                foreach (var threadStateRef in threadStates)
                                {
                                    if (threadStateRef.TryGetTarget(out LocalThreadWriterState threadState) == false)
                                    {
                                        threadStatesToRemove.Push(threadStateRef);
                                        continue;
                                    }

                                    for (var i = 0; i < 16; i++)
                                    {
                                        if (threadState.Full.Dequeue(out WebSocketMessageEntry item) == false)
                                        {
                                            break;
                                        }

                                        foundEntry = true;

                                        sizeWritten += ActualWriteToLogTargets(item, currentFile);

                                        threadState.Free.Enqueue(item);
                                    }
                                }

                                while (threadStatesToRemove.TryPop(out var ts))
                                {
                                    threadStates.Remove(ts);
                                }

                                if (_newThreadStates.IsEmpty)
                                {
                                    continue;
                                }

                                while (_newThreadStates.TryDequeue(out WeakReference <LocalThreadWriterState> result))
                                {
                                    threadStates.Add(result);
                                }

                                _hasEntries.Set(); // we need to start writing logs again from new thread states
                            }
                        }
                    }
                    catch (OutOfMemoryException)
                    {
                        Console.Error.WriteLine("ERROR! Out of memory exception while trying to log, will avoid logging for the next 5 seconds");

                        var time    = 5000;
                        var current = Stopwatch.GetTimestamp();

                        while (time > 0 &&
                               _hasEntries.Wait(time))
                        {
                            _hasEntries.Reset();
                            time = (int)(((Stopwatch.GetTimestamp() - current) * Stopwatch.Frequency) / 1000);
                            foreach (var threadStateRef in threadStates)
                            {
                                DiscardThreadLogState(threadStateRef);
                            }
                            foreach (var newThreadState in _newThreadStates)
                            {
                                DiscardThreadLogState(newThreadState);
                            }
                            current = Stopwatch.GetTimestamp();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                var msg = $"FATAL ERROR trying to log!{Environment.NewLine}{e}";
                Console.Error.WriteLine(msg);
            }
        }
示例#36
0
 public LocalContext(ScriptObject localObject)
 {
     LocalObject = localObject;
     Loops       = new FastStack <ScriptObject>(4);
 }
示例#37
0
 public VariableContext(IScriptObject localObject)
 {
     LocalObject = localObject;
     Loops       = new FastStack <ScriptObject>(4);
 }