Ejemplo n.º 1
0
        protected override byte[] BuildCreatePacket()
        {
            foreach (var creationUpdateFieldEntry in entity.Info.CreationUpdateFieldEntries)
            {
                UpdateQueue.Enqueue(creationUpdateFieldEntry);
            }

            SetInfoFields(entity.Info);

            var writer = new BinaryWriter(new MemoryStream());

            writer.Write((byte)ObjectUpdateType.UPDATETYPE_CREATE_OBJECT);
            writer.WritePackedUInt64(this.entity.ObjectGUID.RawGUID);
            writer.Write((byte)TypeID.TYPEID_GAMEOBJECT);

            ObjectUpdateFlag updateFlags = ObjectUpdateFlag.UPDATEFLAG_TRANSPORT | ObjectUpdateFlag.UPDATEFLAG_ALL
                                           | ObjectUpdateFlag.UPDATEFLAG_HAS_POSITION;

            writer.Write((byte)updateFlags);

            // Position
            writer.Write(entity.Location.X);
            writer.Write(entity.Location.Y);
            writer.Write(entity.Location.Z);

            writer.Write(entity.Location.Orientation); // R

            writer.Write((uint)0x1);                   // Unkown... time?
            writer.Write((uint)0);                     // Unkown... time?

            WriteUpdateFields(writer);

            return((writer.BaseStream as MemoryStream).ToArray());
        }
Ejemplo n.º 2
0
        private void ApplyUpdates()
        {
            UpdateQueue queue = _gameInstance.GameClientConnection.RetrieveUpdatesAndClear();

            foreach (EntityPacket packet in queue.Packets)
            {
                if (_gameEntities.ContainsKey(packet.EntityID))
                {
                    Entity entityToReplace = _gameEntities[packet.EntityID];
                    entityToReplace.SetState(packet.EntityState);
                    TimeSpan lag = DateTime.Now - entityToReplace.LastUpdated;
                    entityToReplace.Update((int)lag.TotalMilliseconds);
                }
                else
                {
                    Entity updatedEntity = worldData.EntityFactory(packet.EntityType, packet.EntityState);
                    addGameEntityFromHost(updatedEntity);
                }
            }

            foreach (int entityID in queue._deadEntities)
            {
                RemoveDeadEntity(entityID);
            }
        }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public override void Dispose()
        {
            try { UpdateQueue?.Dispose(); }
            catch { /* at least we tried */ }

            base.Dispose();
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Unregisters a mod handler.
        /// </summary>
        /// <returns><c>true</c>, if mod handler was unregistered, <c>false</c> otherwise.</returns>
        /// <param name="modName">Mod Name.</param>
        public bool UnregisterModHandler(string modName)
        {
            var unregistered = false;

            lock (EventLock)
            {
                if (RegisteredRawMods.ContainsKey(modName))
                {
                    RegisteredRawMods.Remove(modName);
                    unregistered = true;
                }
                if (RegisteredUpdateMods.ContainsKey(modName))
                {
                    RegisteredUpdateMods.Remove(modName);
                    UpdateQueue.Remove(modName);
                    unregistered = true;
                }
                if (RegisteredFixedUpdateMods.ContainsKey(modName))
                {
                    RegisteredFixedUpdateMods.Remove(modName);
                    FixedUpdateQueue.Remove(modName);
                    unregistered = true;
                }
            }
            return(unregistered);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Flushs the update queue. Takes the list of all updates queued for the client and calls the client's callback, passing this list as parameter
        /// </summary>
        private void FlushUpdateQueue()
        {
            while (true)
            {
                bool gotLock = false;
                try
                {
                    QueueLock.Enter(ref gotLock);

                    if (UpdateQueue.Count > 0)
                    {
                        InvokeClientCallbacks();
                        UpdateQueue.Clear();
                    }
                }
                finally
                {
                    if (gotLock)
                    {
                        QueueLock.Exit();
                    }
                }

                // Wait for updates to accumulate (to send them in batches)
                Thread.Sleep(10);
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Constructor
 /// </summary>
 internal DSAsyncUpdatesProcessor(DatasourceMgr dsMgr, ILogger NCacheLog)
 {
     this._ncacheLog    = NCacheLog;
     this._worker       = null;
     this._processMutex = new object();
     this._isDisposing  = false;
     this._dsMgr        = dsMgr;
     this._updateQueue  = new UpdateQueue();
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes the device.
        /// </summary>
        public void Initialize(UpdateQueue updateQueue)
        {
            InitializeLayout();

            if (Size == Size.Invalid)
            {
                Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
                Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
            }

            UpdateQueue = updateQueue;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes the device.
        /// </summary>
        public void Initialize(IDeviceUpdateTrigger updateTrigger)
        {
            InitializeLayout();

            if (Size == Size.Invalid)
            {
                Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
                Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
            }

            UpdateQueue = new WootingUpdateQueue(updateTrigger);
        }
Ejemplo n.º 9
0
        protected override byte[] BuildCreatePacket()
        {
            //Add all info field entries to the queue
            foreach (var creationUpdateFieldEntry in entity.Info.CreationUpdateFieldEntries)
            {
                UpdateQueue.Enqueue(creationUpdateFieldEntry);
            }

            SetInfoFields(entity.Info);

            var writer = new BinaryWriter(new MemoryStream());

            //TODO Work out why "adder" unit crashes client. Maybe a pet or dynamic object?
            writer.Write((byte)ObjectUpdateType.UPDATETYPE_CREATE_OBJECT);

            writer.WritePackedUInt64(entity.ObjectGUID.RawGUID);

            writer.Write((byte)TypeID.TYPEID_UNIT);

            ObjectUpdateFlag updateFlags = ObjectUpdateFlag.UPDATEFLAG_ALL | ObjectUpdateFlag.UPDATEFLAG_LIVING
                                           | ObjectUpdateFlag.UPDATEFLAG_HAS_POSITION;

            writer.Write((byte)updateFlags);
            writer.Write((uint)MovementFlags.MOVEFLAG_NONE); // MovementFlags

            writer.Write((uint)Environment.TickCount);       // Time

            // 3 bytes ahead?

            // Position
            writer.Write(entity.Location.X);
            writer.Write(entity.Location.Y);
            writer.Write(entity.Location.Z);
            writer.Write(entity.Location.Orientation); // R

            // Movement speeds
            writer.Write((float)0);              // ????

            writer.Write(entity.Info.WalkSpeed); // MOVE_WALK
            writer.Write((float)7);              // MOVE_RUN
            writer.Write(4.5f);                  // MOVE_RUN_BACK
            writer.Write(4.72f);                 // MOVE_SWIM
            writer.Write(2.5f);                  // MOVE_SWIM_BACK
            writer.Write(3.14f);                 // MOVE_TURN_RATE

            writer.Write(0x1);                   // Unkown...

            // entity.GUID = 1141440694;
            this.WriteUpdateFields(writer);

            return((writer.BaseStream as MemoryStream).ToArray());
        }
Ejemplo n.º 10
0
Archivo: Room.cs Proyecto: kaerber/kmud
        public void Update()
        {
            UpdateQueue.AddRelative((200 + World.RndGen.Next(200)) * Clock.TimeBase, Update);
            UpdateQueue.Run();

            if (Resets != null)
            {
                lock (this)
                    Resets.Update();
            }

            Log.Info(World.Instance.Time / 1000 + ": room " + Id + " updated.");
        }
Ejemplo n.º 11
0
        private void HandleAuthenticatedClientDisconnected(object sender, EventArgs e)
        {
            Connection connection = sender as Connection;

            onNewEntityHandlers.Remove(connection);
            onRemovedEntityHandlers.Remove(connection);
            UpdateQueue.StopClientUpdates(connection);
            authenticatedClients.Remove(connection);
            if (ClientDisconnected != null)
            {
                ClientDisconnected(this, new ClientConnectionEventArgs(connection));
            }
        }
        public static void ProcessQueue()
        {
            var pause = TimeSpan.FromMilliseconds(100);

            while (true)
            {
                if (UpdateQueue.IsEmpty)
                {
                    // no pending updates available pause
                    Thread.Sleep(pause);
                    continue;
                }

                bool tryDQ = false;
                do
                {
                    MarketDataUpdate mdUpdate = new MarketDataUpdate();
                    tryDQ = UpdateQueue.TryDequeue(out mdUpdate);
                    if (tryDQ)
                    {
                        if (mdUpdate.Nounce <= Markets[mdUpdate.MarketName].Nounce || Markets[mdUpdate.MarketName] == null)
                        {
                            break;
                        }
                        else if (mdUpdate.Nounce > Markets[mdUpdate.MarketName].Nounce + 1)
                        {
                            //IF NOUNCE IS DE-SYNCED, WIPE BOOK AND RE-SNAP
                            Trace.WriteLine(string.Format("    !!!!ERR>>  NOUNCE OUT OF ORDER! " + mdUpdate.MarketName + " BOOK-DSYNC.  {0}, {1}", Markets[mdUpdate.MarketName].Nounce, mdUpdate.Nounce));
                            bool removed;
                            do
                            {
                                Market.Market m;
                                removed = Markets.TryRemove(mdUpdate.MarketName, out m);
                            } while (!removed);

                            //Request MarketQuery from websocket, and OpenBook() with new snapshot
                            MarketQueryResponse marketQuery = BtrexWS.WSSharpTransport.HubProxy.Invoke <MarketQueryResponse>("QueryExchangeState", mdUpdate.MarketName).Result;
                            marketQuery.MarketName = mdUpdate.MarketName;
                            OpenMarket(marketQuery).Wait();
                            Trace.WriteLine("    [BOOK RE-SYNCED]");
                            break;
                        }
                        else
                        {
                            Markets[mdUpdate.MarketName].SetUpdate(mdUpdate);
                        }
                    }
                } while (!tryDQ);
            }
        }
Ejemplo n.º 13
0
        private void WrapUpdateMethods(Connection connection)
        {
            var newObjectUpdates = connection.GenerateClientFunction("objectsync", "receiveNewObjects");

            onNewEntityHandlers[connection] = newObjectUpdates;

            var removedObjectUpdates = connection.GenerateClientFunction("objectsync", "removeObject");

            onRemovedEntityHandlers[connection] = removedObjectUpdates;

            var updatedObjectUpdates = connection.GenerateClientFunction("objectsync", "receiveObjectUpdates");

            UpdateQueue.RegisterToClientUpdates(connection, updatedObjectUpdates);
        }
Ejemplo n.º 14
0
        public PSUpdateObject BuildOwnCharacterPacket()
        {
            foreach (var creationUpdateFieldEntry in entity.Info.CreationUpdateFieldEntries)
            {
                UpdateQueue.Enqueue(creationUpdateFieldEntry);
            }

            SetInfoFields(entity.Info);

            BinaryWriter writer = new BinaryWriter(new MemoryStream());

            writer.Write((byte)ObjectUpdateType.UPDATETYPE_CREATE_OBJECT2);
            writer.WritePackedUInt64(this.entity.ObjectGUID.RawGUID);
            writer.Write((byte)TypeID.TYPEID_PLAYER);

            ObjectUpdateFlag updateFlags = ObjectUpdateFlag.UPDATEFLAG_ALL |
                                           ObjectUpdateFlag.UPDATEFLAG_SELF |
                                           ObjectUpdateFlag.UPDATEFLAG_HAS_POSITION |
                                           ObjectUpdateFlag.UPDATEFLAG_LIVING;

            writer.Write((byte)updateFlags);

            writer.Write((UInt32)MovementFlags.MOVEFLAG_NONE);
            writer.Write((UInt32)Environment.TickCount); // Time?

            // Position
            writer.Write((float)entity.Location.X);
            writer.Write((float)entity.Location.Y);
            writer.Write((float)entity.Location.Z);
            writer.Write((float)entity.Location.Orientation); // R

            // Movement speeds
            writer.Write((float)0);                     // ????

            writer.Write((float)entity.Info.WalkSpeed); // MOVE_WALK
            writer.Write((float)20f);                   // MOVE_RUN
            writer.Write((float)4.5f);                  // MOVE_RUN_BACK
            writer.Write((float)4.72f);                 // MOVE_SWIM
            writer.Write((float)2.5f);                  // MOVE_SWIM_BACK
            writer.Write((float)3.14f);                 // MOVE_TURN_RATE

            writer.Write(0x1);                          // Unkown...

            this.WriteUpdateFields(writer);

            return(new PSUpdateObject(new List <byte[]>()
            {
                (writer.BaseStream as MemoryStream).ToArray()
            }));
        }
Ejemplo n.º 15
0
        protected override byte[] BuildUpdatePacket()
        {
            foreach (var creationUpdateFieldEntry in entity.Info.CreationUpdateFieldEntries)
            {
                UpdateQueue.Enqueue(creationUpdateFieldEntry);
            }

            this.SetInfoFields(entity.Info);
            var writer = new BinaryWriter(new MemoryStream());

            writer.Write((byte)ObjectUpdateType.UPDATETYPE_VALUES);
            writer.WritePackedUInt64(entity.ObjectGUID.RawGUID);
            this.WriteUpdateFields(writer);
            return((writer.BaseStream as MemoryStream).ToArray());
        }
Ejemplo n.º 16
0
 /// <summary>
 ///     Registers a mod handler function that will be called on every Update.
 /// </summary>
 /// <param name="modName">Mod Name.</param>
 /// <param name="handlerFunction">Handler function.</param>
 public bool RegisterUpdateModHandler(string modName, MessageCallback handlerFunction)
 {
     lock (EventLock)
     {
         if (RegisteredUpdateMods.ContainsKey(modName))
         {
             Debug.Log($"[LMP]: Failed to register Update mod handler for {modName}, mod already registered");
             return(false);
         }
         Debug.Log($"[LMP]: Registered Update mod handler for {modName}");
         RegisteredUpdateMods.Add(modName, handlerFunction);
         UpdateQueue.Add(modName, new ConcurrentQueue <byte[]>());
     }
     return(true);
 }
        public void RequestUpdate(TextAreaUpdate update)
        {
            if (UpdateQueue.Count == 1 && UpdateQueue[0].TextAreaUpdateType == TextAreaUpdateType.WholeTextArea)
            {
                // if we're going to update the whole text area, we don't need to store detail updates
                return;
            }

            if (update.TextAreaUpdateType == TextAreaUpdateType.WholeTextArea)
            {
                // if we're going to update the whole text area, we don't need to store detail updates
                UpdateQueue.Clear();
            }

            UpdateQueue.Add(update);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Adds update information about an entity to the update queue after having received an attributeChanged event
        /// </summary>
        /// <param name="sender">Entity that invoked the attribute change event</param>
        /// <param name="e">Event Arguments</param>
        private void AddEntityUpdateToQueue(Object sender, ChangedAttributeEventArgs e)
        {
            bool gotLock = false;

            try
            {
                QueueLock.Enter(ref gotLock);
                UpdateQueue.Add(CreateUpdateInfoFromEventArgs((Entity)sender, e));
            }
            finally
            {
                if (gotLock)
                {
                    QueueLock.Exit();
                }
            }
        }
Ejemplo n.º 19
0
        /// <inheritdoc />
        public void ClearChunks()
        {
            UpdateQueue.Clear();
            FastUpdateQueue.Clear();
            UpdateBorderQueue.Clear();
            var chunks = Chunks.ToArray();

            Chunks.Clear();

            Scheduled.Clear();

            _renderedChunks = new ChunkData[0];
            foreach (var chunk in chunks)
            {
                chunk.Value.Dispose();
            }
        }
Ejemplo n.º 20
0
        private static void ApplyUpdates()
        {
            UpdateQueue queue = SyncManager.RetrieveUpdatesAndClear();

            foreach (EntityPacket packet in queue.Packets)
            {
                if (_gameEntities.ContainsKey(packet.EntityID))
                {
                    Entity entityToReplace = _gameEntities[packet.EntityID];
                    entityToReplace.SetState(packet.EntityState);
                    TimeSpan lag = DateTime.Now - entityToReplace.LastUpdated;
                    entityToReplace.Update((int)lag.TotalMilliseconds);
                }
                else
                {
                    Entity updatedEntity = ModelHelper.EntityFactory(packet.EntityType, packet.EntityState);
                    addGameEntityFromHost(updatedEntity);
                }
            }
        }
Ejemplo n.º 21
0
        public Server(TextWriter log)
        {
            this.log = log;

            Name   = "Custom Minecraft server";
            Motd   = "Welcome to my custom Minecraft server!";
            Public = false;
            Verify = true;
            Slots  = 16;
            Help   = "&eTo show a list of commands, type '/help commands'.";

            listener.AcceptEvent += Accept;
            heartbeat             = new Heartbeat(this);
            updateThread          = new Thread(UpdateBodies);
            lua      = new Lua(this);
            Commands = new Command.List(this);
            Groups   = new Group.List();
            Accounts = new Account.List();
            Queue    = new UpdateQueue(this);
        }
Ejemplo n.º 22
0
        /// <inheritdoc />
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            try
            {
                //Graphics?.Dispose();
                BlockLightCalculations?.Dispose();
                BlockLightCalculations = null;

                SkyLightCalculator?.Dispose();
                SkyLightCalculator = null;

                _renderSampler.Dispose();
                CancellationToken.Cancel();
                UpdateQueue.Clear();
                FastUpdateQueue.Clear();
                UpdateBorderQueue.Clear();

                foreach (var chunk in Chunks)
                {
                    chunk.Value.Dispose();
                }

                Chunks.Clear();

                foreach (var rendered in _renderedChunks)
                {
                    rendered.Dispose();
                }

                _renderedChunks = null;
            }
            finally
            {
                _disposed = true;
            }
        }
Ejemplo n.º 23
0
        /// <inheritdoc />
        public void RemoveChunk(ChunkCoordinates position, bool dispose = true)
        {
            BlockLightCalculations.Remove(position);

            if (Chunks.TryRemove(position, out var column))
            {
                foreach (var blockEntity in column.GetBlockEntities)
                {
                    World.EntityManager.RemoveBlockEntity(
                        new BlockCoordinates((column.X << 4) + blockEntity.X, blockEntity.Y, (column.Z << 4) + blockEntity.Z));
                }

                UpdateQueue.Remove(position);
                UpdateBorderQueue.Remove(position);

                if (dispose)
                {
                    column.Dispose();
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Initializes the device.
        /// </summary>
        void ISteelSeriesRGBDevice.Initialize(UpdateQueue updateQueue, Dictionary <LedId, SteelSeriesLedId> ledMapping)
        {
            _ledMapping = ledMapping;

            int counter = 0;

            foreach (KeyValuePair <LedId, SteelSeriesLedId> mapping in ledMapping)
            {
                InitializeLed(mapping.Key, new Rectangle((counter++) * 10, 0, 10, 10));
            }

            InitializeLayout();

            if (Size == Size.Invalid)
            {
                Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
                Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
            }

            UpdateQueue = updateQueue;
        }
Ejemplo n.º 25
0
        /// <inheritdoc />
        public void Dispose()
        {
            //Graphics?.Dispose();
            CancellationToken.Cancel();
            UpdateQueue.Clear();
            FastUpdateQueue.Clear();
            UpdateBorderQueue.Clear();

            foreach (var chunk in Chunks)
            {
                chunk.Value.Dispose();
            }

            Chunks.Clear();

            foreach (var rendered in _renderedChunks)
            {
                rendered.Dispose();
            }

            _renderedChunks = null;
        }
Ejemplo n.º 26
0
        public City(long seed, RantEngine rant, CityConfig config)
        {
            _seed = seed;
            _rant = rant;
            _updateQueue = new UpdateQueue(this);

            citizenCache = new SeedCache<CitizenInfo>(CITIZEN_CACHE_CAPACITY, s => new CitizenInfo(this, s));

            var data = rant.DoPackaged("sp/city", seed);

            Name = data["name"];
            int year, month, day;
            if (!(
                    int.TryParse(data["year"], out year) &&
                    int.TryParse(data["month"], out month) &&
                    int.TryParse(data["day"], out day)))
            {
                year = 1990;
                month = 4;
                day = 1;
            }
            StartingTime = CurrentTime = new DateTime(year, month, day);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Removes all unsent update information of a removed entity from the update queue
        /// </summary>
        /// <param name="entityGuid">Guid of the removed entity/param>
        private void RemoveEntityFromQueue(Entity entity)
        {
            bool gotLock = false;

            try
            {
                QueueLock.Enter(ref gotLock);

                foreach (UpdateInfo entityUpdate in UpdateQueue)
                {
                    if (entityUpdate.entityGuid.Equals(entity.Guid))
                    {
                        UpdateQueue.Remove(entityUpdate);
                    }
                }
            }
            finally
            {
                if (gotLock)
                {
                    QueueLock.Exit();
                }
            }
        }
Ejemplo n.º 28
0
        private void HandleAuthenticatedClientDisconnected(object sender, EventArgs e)
        {
            Connection connection = sender as Connection;

            if (onNewEntityHandlers.ContainsKey(connection))
            {
                foreach (var handler in onNewEntityHandlers[connection])
                {
                    World.Instance.AddedEntity -= handler;
                }
            }

            if (onRemovedEntityHandlers.ContainsKey(connection))
            {
                foreach (var handler in onRemovedEntityHandlers[connection])
                {
                    World.Instance.RemovedEntity -= handler;
                }
            }

            UpdateQueue.StopClientUpdates(connection);

            authenticatedClients.Remove(connection);
        }
Ejemplo n.º 29
0
 /// <inheritdoc />
 protected override void UpdateLeds(IEnumerable <Led> ledsToUpdate) => UpdateQueue.SetData(ledsToUpdate.Where(x => x.Color.A > 0));
Ejemplo n.º 30
0
 public EventBetweenTurn(SceneGame world, UpdateQueue updateQueue)
 {
     World       = world;
     UpdateQueue = updateQueue;
 }
 protected override void UpdateLeds(IEnumerable <Led> ledsToUpdate) => UpdateQueue.SetData(GetUpdateData(ledsToUpdate.Take(1)));