Esempio n. 1
0
        public override void Serialize()
        {
            Data.SkipBytes(8);

            Data.ReadIntLE();   // unk
            Data.ReadShortLE(); // unk

            var PosY = Data.ReadShortLE();

            Data.ReadShortLE();            // unk
            var PosX = Data.ReadShortLE(); // CONFIRMED CORRECT

            Data.SkipBytes(15);            // unk stuff

            MoveType moveType = (MoveType)Data.ReadByte();

            Data.ReadIntLE(); // unk zeros

            Data.ResetReaderIndex();
            Logger.Debug($"\n{HexUtils.Dump(Data)}");
            Logger.Debug($"X,Y[{PosX}, {PosY}] MoveType[{moveType.ToString()}]");

            // DEBUG INFO

            /*
             * Logger.Debug(
             *  $"\nPos1: {pos1}\n" +
             *  $"Pos2: {pos2}\n" +
             *  $"Pos3: {pos3}\n" +
             *  $"PossibleZone: {possibleZone}\n" +
             *  $"UnkFloatOrInt: {pos4}\n" +
             *  $"IsMoving: {IsMoving}\n"
             *  );
             */
        }
Esempio n. 2
0
        void EncodeDeclareByte(string hexBytes)
        {
            const int   bitness = 64;
            const ulong newRip  = 0x8000000000000000;

            var data         = HexUtils.ToByteArray(hexBytes);
            var instructions = new Instruction[] {
                Instruction.Create(Code.Nopd),
                Instruction.CreateDeclareByte(data),
                Instruction.Create(Code.Nopd),
            };

            var expectedData = new byte[data.Length + 2];

            expectedData[0] = 0x90;
            Array.Copy(data, 0, expectedData, 1, data.Length);
            expectedData[expectedData.Length - 1] = 0x90;

            var  codeWriter = new CodeWriterImpl();
            bool b          = BlockEncoder.TryEncode(bitness, new InstructionBlock(codeWriter, instructions, newRip), out var errorMessage, out var result);

            Assert.True(b);
            Assert.Null(errorMessage);
            Assert.Equal(expectedData, codeWriter.ToArray());
            Assert.Equal(newRip, result.RIP);
            Assert.Null(result.RelocInfos);
            Assert.NotNull(result.NewInstructionOffsets);
            Assert.True(result.NewInstructionOffsets.Length == 0);
            Assert.NotNull(result.ConstantOffsets);
            Assert.True(result.ConstantOffsets.Length == 0);
        }
Esempio n. 3
0
        protected void NonDecodeEncodeBase(int codeSize, ref Instruction instr, string hexBytes, ulong rip)
        {
            var expectedBytes = HexUtils.ToByteArray(hexBytes);
            var writer        = new CodeWriterImpl();
            var encoder       = Encoder.Create(codeSize, writer);

            Assert.Equal(codeSize, encoder.Bitness);
            var  origInstrCopy = instr;
            bool result        = encoder.TryEncode(instr, rip, out uint encodedInstrLen, out string errorMessage);

            Assert.True(errorMessage is null, "Unexpected ErrorMessage: " + errorMessage);
            Assert.True(result, "Error, result from Encoder.TryEncode must be true");
            var encodedBytes = writer.ToArray();

            Assert.Equal(encodedBytes.Length, (int)encodedInstrLen);
            Assert.True(Instruction.TEST_BitByBitEquals(instr, origInstrCopy));
            if (!ArrayEquals(expectedBytes, encodedBytes))
            {
#pragma warning disable xUnit2006 // Do not use invalid string equality check
                // Show the full string without ellipses by using Equal<string>() instead of Equal()
                Assert.Equal <string>(ToString(expectedBytes), ToString(encodedBytes));
                throw new InvalidOperationException();
#pragma warning restore xUnit2006 // Do not use invalid string equality check
            }
        }
Esempio n. 4
0
        public void ZoomMod()
        {
            // 0 to 3 over 3 steps

            // No range, no modifier
            int mod = HexUtils.DecayingModifier(0, -3, 3, 0.0f);

            Assert.AreEqual(0, mod);

            // Range just under step count of 3 * 30 = 89.9
            mod = HexUtils.DecayingModifier(0, -3, 3, 89.9f);
            Assert.AreEqual(0, mod);

            // Range at first step count
            mod = HexUtils.DecayingModifier(0, -3, 3, 90.0f);
            Assert.AreEqual(-1, mod);

            // Range at second step count
            mod = HexUtils.DecayingModifier(0, -3, 3, 180.0f);
            Assert.AreEqual(-2, mod);

            // Range at third step count
            mod = HexUtils.DecayingModifier(0, -3, 3, 270.0f);
            Assert.AreEqual(-3, mod);

            // Range at fourth step count
            mod = HexUtils.DecayingModifier(0, -3, 3, 360.0f);
            Assert.AreEqual(-3, mod);
        }
Esempio n. 5
0
        protected void EncodeInvalidBase(int codeSize, Code code, string hexBytes, int invalidCodeSize)
        {
            var origBytes = HexUtils.ToByteArray(hexBytes);
            var decoder   = CreateDecoder(codeSize, origBytes);
            var origRip   = decoder.InstructionPointer;
            var origInstr = decoder.Decode();

            Assert.Equal(code, origInstr.Code);
            Assert.Equal(origBytes.Length, origInstr.ByteLength);
            Assert.True(origInstr.ByteLength <= Iced.Intel.DecoderConstants.MaxInstructionLength);
            Assert.Equal((ushort)origRip, origInstr.IP16);
            Assert.Equal((uint)origRip, origInstr.IP32);
            Assert.Equal(origRip, origInstr.IP64);
            var afterRip = decoder.InstructionPointer;

            Assert.Equal((ushort)afterRip, origInstr.NextIP16);
            Assert.Equal((uint)afterRip, origInstr.NextIP32);
            Assert.Equal(afterRip, origInstr.NextIP64);

            var writer          = new CodeWriterImpl();
            var encoder         = CreateEncoder(invalidCodeSize, writer);
            var origInstrCopy   = origInstr;
            int encodedInstrLen = encoder.Encode(ref origInstr, origRip, out string errorMessage);

            Assert.True(errorMessage == Encoder.ERROR_ONLY_1632_BIT_MODE || errorMessage == Encoder.ERROR_ONLY_64_BIT_MODE);
            Assert.True(Instruction.TEST_BitByBitEquals(ref origInstr, ref origInstrCopy));
            Assert.True(encodedInstrLen >= 0);
        }
Esempio n. 6
0
        public static RegSETrackPoint FromByteArray(byte[] buffer, int offset)
        {
            //* 16 Byte Blocke
            //* Byte 0-1: little endian 16bit, flags: 1=TRACK_START, 2=WAYPOINT,4=OVER_SPEED
            //* Byte 2-5: little endian 32bit: timestamp
            //* Byte 6-9: little endian 32bit: lattitude in Grad, wenn man es durch 10000000 dividiert
            //* Byte 10-13: little endian 32bit: longitude in Grad, wenn man es durch 10000000 dividiert
            //* Byte 14-15: little endian 16bit: altitude

            var type = HexUtils.ToInt16LE(buffer, offset + 0);

            var timeCode = HexUtils.ToInt32LE(buffer, offset + 2);
            int sec      = (((timeCode) >> 0) & 0x3F);
            int min      = (((timeCode) >> 6) & 0x3F);
            int hours    = (((timeCode) >> 12) & 0x1F);
            int day      = (((timeCode) >> 17) & 0x1F);
            int month    = (((timeCode) >> 22) & 0x0F);
            int year     = (((timeCode) >> 26) & 0x3F);
            var time     = new DateTime(2000 + year, month, day, hours, min, sec);

            var latitudeValue  = HexUtils.ToInt32LE(buffer, offset + 6);
            var longitudeValue = HexUtils.ToInt32LE(buffer, offset + 10);
            var altitude       = HexUtils.ToInt16LE(buffer, offset + 14);
            var latitude       = new Decimal(latitudeValue) / new Decimal(10000000);
            var longitude      = new Decimal(longitudeValue) / new Decimal(10000000);

            return(new RegSETrackPoint(time, latitude, longitude, altitude, type));
        }
Esempio n. 7
0
        public void HarkonnenMod()
        {
            int initialMod = 0, finalMod = 5, hexSteps = 2;
            int mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 0f);

            Assert.AreEqual(0, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 60f);
            Assert.AreEqual(1, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 120f);
            Assert.AreEqual(2, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 180f);
            Assert.AreEqual(3, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 240f);
            Assert.AreEqual(4, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 300f);
            Assert.AreEqual(5, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 360f);
            Assert.AreEqual(5, mod);

            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 500f);
            Assert.AreEqual(5, mod);
        }
Esempio n. 8
0
        private static float GetVisualRange(float visionRange, AbstractActor source)
        {
            float visualRange;

            if (source.IsShutDown)
            {
                visualRange = visionRange * source.Combat.Constants.Visibility.ShutdownSpottingDistanceMultiplier;
            }
            else if (source.IsProne)
            {
                visualRange = visionRange * source.Combat.Constants.Visibility.ProneSpottingDistanceMultiplier;
            }
            else
            {
                float multipliers = VisualLockHelper.GetAllSpotterMultipliers(source);
                float absolutes   = VisualLockHelper.GetAllSpotterAbsolutes(source);

                visualRange = visionRange * multipliers + absolutes;
                //Mod.Log.Trace?.Write($" -- source:{CombatantUtils.Label(source)} has spotting " +
                //    $"multi:x{multipliers} absolutes:{absolutes} visionRange:{visionRange}");
            }

            if (visualRange < Mod.Config.Vision.MinimumVisionRange())
            {
                visualRange = Mod.Config.Vision.MinimumVisionRange();
            }

            // Round up to the nearest full hex
            float normalizedRange = HexUtils.CountHexes(visualRange, false) * 30f;

            //LowVisibility.Logger.Trace($" -- source:{CombatantUtils.Label(source)} visual range is:{normalizedRange}m normalized from:{visualRange}m");
            return(normalizedRange);
        }
Esempio n. 9
0
        // WARNING: DUPLICATE OF HBS CODE. THIS IS LIKELY TO BREAK IF HBS CHANGES THE SOURCE FUNCTIONS
        public static float GetAdjustedSpotterRange(AbstractActor source, ICombatant target)
        {
            float         targetVisibility = 1f;
            AbstractActor targetActor      = target as AbstractActor;

            if (targetActor != null)
            {
                EWState sourceState = source.GetEWState();
                targetVisibility = VisualLockHelper.GetTargetVisibility(targetActor, sourceState);
            }

            float spotterRange = VisualLockHelper.GetSpotterRange(source);

            float modifiedRange = spotterRange * targetVisibility;

            if (modifiedRange < Mod.Config.Vision.MinimumVisionRange())
            {
                modifiedRange = Mod.Config.Vision.MinimumVisionRange();
            }

            // Round up to the nearest full hex
            float normalizedRange = HexUtils.CountHexes(modifiedRange, true) * 30f;

            Mod.Log.Trace?.Write($" -- source:{CombatantUtils.Label(source)} adjusted spotterRange:{normalizedRange}m normalized from:{modifiedRange}m");
            return(normalizedRange);
        }
Esempio n. 10
0
        public void CreateResources(ICanvasResourceCreator resourceCreator)
        {
            DestroyResources();

            // define path
            var pb      = new CanvasPathBuilder(resourceCreator);
            var radiusH = HexUtils.GetRadiusHeight(Radius);

            pb.BeginFigure(-1 * Radius * HexUtils.COS60, radiusH);
            pb.AddLine(Radius * HexUtils.COS60, radiusH);
            pb.AddLine(Radius, 0);
            pb.AddLine(Radius * HexUtils.COS60, -1 * radiusH);
            pb.AddLine(-1 * Radius * HexUtils.COS60, -1 * radiusH);
            pb.AddLine(-1 * Radius, 0);
            pb.EndFigure(CanvasFigureLoop.Closed);

            // create and cache
            _strokeStyle = new CanvasStrokeStyle();

            var geo = CanvasGeometry.CreatePath(pb);

            if (Filled)
            {
                _geo = CanvasCachedGeometry.CreateFill(geo);
            }
            else
            {
                _geo = CanvasCachedGeometry.CreateStroke(geo, Style.StrokeWidth, _strokeStyle);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a coinbase transaction and adds it the block.
        /// </summary>
        /// <returns>The created coinbase transaction.</returns>
        /// <remarks>
        /// Since coinbase transaction must be the first transaction in a block,
        /// this method will throw an exception if the block already contains more than 0 transactions.
        /// </remarks>
        public Transaction AddCoinbaseTx(string address, long feeInNekoshi)
        {
            if (Transactions.Count > 0)
            {
                throw new System.InvalidOperationException("Coinbase must be the first transaction.");
            }

            long reward = Config.CalculateRewardInNekoshi(Index);
            var  txIn   = new TxIn
            {
                TxId       = HexUtils.HexFromInt(Index),
                TxOutIndex = 0,
                Signature  = "",
            };
            var txOut = new TxOut
            {
                AmountInNekoshi = reward + feeInNekoshi,
                Address         = address,
            };
            var tx = new Transaction();

            tx.Inputs.Add(txIn);
            tx.Outputs.Add(txOut);
            tx.Id = tx.GetId();
            Transactions.Add(tx);
            return(tx);
        }
        private void Update()
        {
            // TODO: Use a better source of pointer input than Input.mousePosition.
            var viewportPosition = Input.mousePosition;

            viewportPosition.z = _camera.transform.position.y;
            var worldPosition = _camera.ScreenToWorldPoint(viewportPosition);

            // Snap the cursor display to the cell the mouse is over.
            _cursorGridPosition        = HexUtils.WorldToGrid(new Vector2(worldPosition.x, worldPosition.z));
            worldPosition              = HexUtils.GridToWorld(_cursorGridPosition);
            _cursor.transform.position = new Vector3(worldPosition.x, 0f, worldPosition.y);

            // TODO: Use a better source of input than Input. It would be nice to
            // use the EventSystem, but it's not clear how use it when clicking on
            // empty space.
            if (Input.GetMouseButtonDown(0) && _selectedDrone != null)
            {
                var command = new MoveToPosition
                {
                    Target = _cursorGridPosition,
                };

                AddCommandToQueue(CommandType.MoveToPosition, JsonUtility.ToJson(command), 5);
            }
        }
Esempio n. 13
0
    /// <summary>
    /// Collects all empty tiles in the given direction.
    /// Adds to the workingSet variable.
    /// </summary>
    /// <param name="workingSet">The set into which tiles should be added.</param>
    private void getTileLine(Player owningPlayer, HashSet <Tile> workingSet, HexUtils.hexDir dir, int dist)
    {
        if (this.associatedPlayer == null && dist > 0)
        {
            workingSet.Add(this);

            bool   adjacentToEnemy = false;
            Tile[] neighbors       = this.getNeighbors();

            for (int i = 0; i < neighbors.Length; i++)
            {
                if (neighbors[i] != null && neighbors[i].associatedPlayer != null && neighbors[i].associatedPlayer != owningPlayer)
                {
                    adjacentToEnemy = true;
                }
            }

            Tile tle = board.getTile(HexUtils.getIndexForDirection(this.gridLocation, dir));

            if (tle != null && !adjacentToEnemy)
            {
                board.getTile(HexUtils.getIndexForDirection(this.gridLocation, dir)).getTileLine(owningPlayer, workingSet, dir, dist - 1);
            }
        }
    }
Esempio n. 14
0
        /// <summary>
        /// Attempts to mine the block with the next range of nonce values.
        /// </summary>
        /// <returns>True if the block is successfully mined.</returns>
        public bool Attempt()
        {
            int nonceRange = int.MaxValue - _startingNonce;

            if (nonceRange > _nonceRange)
            {
                nonceRange = _nonceRange;
            }

            for (int n = _startingNonce, c = _startingNonce + nonceRange; n < c; ++n)
            {
                HexUtils.AppendHexFromInt(_headerStreamWriter, n);
                _headerStreamWriter.Flush();

                var hash = Pow.Hash(_headerStream);
                if (Pow.IsValidHash(hash, _difficulty))
                {
                    Block.Nonce = n;
                    Block.Hash  = HexUtils.HexFromByteArray(hash);
                    return(true);
                }

                _headerStream.Seek(_streamOrgPosition, SeekOrigin.Begin);
            }

            _startingNonce += nonceRange;

            if (_startingNonce == int.MaxValue)
            {
                _maxNonceReached = true;
            }

            return(false);
        }
Esempio n. 15
0
		void CreateTest(int bitness, string hexBytes, Func<Instruction> create) {
			var bytes = HexUtils.ToByteArray(hexBytes);
			var decoder = Decoder.Create(bitness, new ByteArrayCodeReader(bytes));
			switch (bitness) {
			case 16: decoder.InstructionPointer = DecoderConstants.DEFAULT_IP16; break;
			case 32: decoder.InstructionPointer = DecoderConstants.DEFAULT_IP32; break;
			case 64: decoder.InstructionPointer = DecoderConstants.DEFAULT_IP64; break;
			default: throw new InvalidOperationException();
			}
			var origRip = decoder.InstructionPointer;
			decoder.Decode(out var decodedInstr);
			decodedInstr.CodeSize = 0;
			decodedInstr.ByteLength = 0;
			decodedInstr.NextIP64 = 0;

			var createdInstr = create();
			Assert.True(Instruction.TEST_BitByBitEquals(ref decodedInstr, ref createdInstr));

			var writer = new CodeWriterImpl();
			var encoder = decoder.CreateEncoder(writer);
			bool result = encoder.TryEncode(ref createdInstr, origRip, out _, out var errorMessage);
			Assert.Null(errorMessage);
			Assert.True(result);
			Assert.Equal(bytes, writer.ToArray());
		}
Esempio n. 16
0
        public JObject GetChildrenByHash(string nodeHash)
        {
            IHashTrieNode?node = _nodeRetrieval.TryGetNode(HexUtils.HexToBytes(nodeHash), out var childrenHash);

            if (node == null)
            {
                return new JObject {
                }
            }
            ;

            JArray children = new JArray {
            };

            foreach (var childHash in childrenHash)
            {
                JObject child = GetNodeByHash(Web3DataFormatUtils.Web3Data(childHash));

                if (child.Count == 0)
                {
                    return new JObject {
                    }
                }
                ;
                children.Add(child);
            }

            JObject nodeHashWithChildren = new JObject {
            };

            nodeHashWithChildren[Web3DataFormatUtils.Web3Data(node.Hash)] = children;
            return(nodeHashWithChildren);
        }
Esempio n. 17
0
 public ZoomVision(int mod, int cap, int decay)
 {
     this.AttackMod       = mod;
     this.AttackCap       = cap;
     this.HexesUntilDecay = decay;
     this.MaximumRange    = HexUtils.HexesInRange(mod, cap, decay) * 30;
 }
Esempio n. 18
0
    /// <summary>
    /// Counts the number of triples (3 mutually adjacent units) by "scrubbing over every unit in the group with two kernels."
    /// The two 'kernels' simply search for an up or down triangle with the unit in question being the left most unit.
    /// </summary>
    private void CountTriples()
    {
        this.numTriples = 0;

        foreach (Tile t in this.tiles)
        {
            // Find neighbor to the right
            Tile rNghbr = t.board.getTile(HexUtils.getIndexForDirection(t.gridLocation, HexUtils.hexDir.Right));

            if (rNghbr != null && rNghbr.associatedPlayer == t.associatedPlayer)
            {
                // Find the neigbor up and to the right
                Tile ruNghbr = t.board.getTile(HexUtils.getIndexForDirection(t.gridLocation, HexUtils.hexDir.UpRight));

                if (ruNghbr != null && ruNghbr.associatedPlayer == t.associatedPlayer)
                {
                    this.numTriples++;
                }

                // Find the neigbor down and to the right
                Tile rdNghbr = t.board.getTile(HexUtils.getIndexForDirection(t.gridLocation, HexUtils.hexDir.DownRight));

                if (rdNghbr != null && rdNghbr.associatedPlayer == t.associatedPlayer)
                {
                    this.numTriples++;
                }
            }
        }
    }
Esempio n. 19
0
        public void LAMod2()
        {
            int initialMod = -4, finalMod = 0, hexSteps = 4;

            // No range, no modifier
            int mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 0f);

            Assert.AreEqual(-4, mod);

            // Not full step, no modifier
            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 110f);
            Assert.AreEqual(-4, mod);

            // One step
            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 125f);
            Assert.AreEqual(-3, mod);

            // Two steps
            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 245f);
            Assert.AreEqual(-2, mod);

            // Three steps
            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 365f);
            Assert.AreEqual(-1, mod);

            // Four steps, same modifier
            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 485f);
            Assert.AreEqual(-0, mod);

            // Five steps, same modifier
            mod = HexUtils.DecayingModifier(initialMod, finalMod, hexSteps, 610f);
            Assert.AreEqual(0, mod);
        }
Esempio n. 20
0
        public float XZPositionToHeight(float x, float z, bool scaleByMapHeight = false)
        {
            Vector2 mapPoint = new Vector2(x, z) / tileSize * mapScale;

            return(HexUtils.GetHeightOnNoiseMap(noiseMap, mapPoint) *
                   (scaleByMapHeight ? mapHeight : 1));
        }
Esempio n. 21
0
        public void SniperMod()
        {
            // +3 to -3 over 6 steps

            // No range, full modifier
            int mod = HexUtils.DecayingModifier(3, -3, 2, 0.0f);

            Assert.AreEqual(3, mod);

            // First step (2*1*30), worse mod
            mod = HexUtils.DecayingModifier(3, -3, 2, 60.0f);
            Assert.AreEqual(2, mod);

            // Third step (2*3*30), neutral
            mod = HexUtils.DecayingModifier(3, -3, 2, 180.0f);
            Assert.AreEqual(0, mod);

            // Fourth step (2*4*30), positive
            mod = HexUtils.DecayingModifier(3, -3, 2, 240.0f);
            Assert.AreEqual(-1, mod);

            // Sixth step (2*6*30), positive
            mod = HexUtils.DecayingModifier(3, -3, 2, 360.0f);
            Assert.AreEqual(-3, mod);

            // Seventh step (2*7*30), capped
            mod = HexUtils.DecayingModifier(3, -3, 2, 420.0f);
            Assert.AreEqual(-3, mod);
        }
Esempio n. 22
0
    public void CreateOption(int index)
    {
        var uiChooseTile = UIManager.Singleton.UIChoosingTile;

        HexTile hexTile = null;

        if (index == 0)
        {
            hexTile = HexUtils.BuildHexTile(_hexTile.Data, Player.MyPlayer, HexTileRole.InUI);
        }
        else
        {
            var         affordAble = false;
            var         counter    = 0;
            HexTileData randomData = null;
            while (!affordAble)
            {
                randomData = HexUtils.CreateRandomData(_hexTile.Data.X, _hexTile.Data.Y);
                counter++;
                if (counter == 100)
                {
                    randomData = _hexTile.Data;
                    UnityEngine.Debug.LogWarning("Could not find Random Data");
                }
                affordAble = Player.MyPlayer.HasResource(HexUtils.CalcHexPrice(randomData));
            }

            hexTile = HexUtils.BuildHexTile(randomData, Player.MyPlayer, HexTileRole.InUI);
        }

        hexTile.transform.SetParent(uiChooseTile.ChoosingTransforms[index].transform, false);

        hexTile.OnClickCallback = OnTileChosen;
    }
        public static EntityTemplate Drone(AxialCoordinate position, string playerId)
        {
            // Calculate the world position based off the grid position.
            var worldPosition = HexUtils.GridToWorld(position);

            var entityTemplate = new EntityTemplate();

            entityTemplate.AddComponent(
                new Drone.Snapshot {
                Owner = playerId, CommandQueue = new List <Command>()
            },
                WorkerUtils.UnityGameLogic);

            entityTemplate.AddComponent(
                new Position.Snapshot(new Coordinates
            {
                X = worldPosition.x,
                Z = worldPosition.y
            }),
                WorkerUtils.UnityGameLogic);

            entityTemplate.AddComponent(
                new PlayerInventory.Snapshot(0, 0),
                WorkerUtils.UnityGameLogic);

            entityTemplate.AddComponent(new Metadata.Snapshot("Drone"), WorkerUtils.UnityGameLogic);
            entityTemplate.AddComponent(new Persistence.Snapshot(), WorkerUtils.UnityGameLogic);
            entityTemplate.SetReadAccess(WorkerUtils.AllWorkers);
            entityTemplate.SetComponentWriteAccess(EntityAcl.ComponentId, WorkerUtils.UnityGameLogic);

            return(entityTemplate);
        }
Esempio n. 24
0
        /**
         * Sends the provided data to the XBee device of the network corresponding
         * to the given 16-bit address.
         *
         * <p>This method blocks until a success or error response arrives or the
         * configured receive timeout expires.</p>
         *
         * <p>The received timeout is configured using the {@code setReceiveTimeout}
         * method and can be consulted with {@code getReceiveTimeout} method.</p>
         *
         * <p>For non-blocking operations use the method
         * {@link #sendData(XBee16BitAddress, byte[])}.</p>
         *
         * @param address The 16-bit address of the XBee that will receive the data.
         * @param data Byte array containing data to be sent.
         *
         * @throws InterfaceNotOpenException if the device is not open.
         * @throws ArgumentNullException if {@code address == null} or
         *                              if {@code data == null}.
         * @throws TimeoutException if there is a timeout sending the data.
         * @throws XBeeException if there is any other XBee related exception.
         *
         * @see com.digi.xbee.api.models.XBee16BitAddress
         * @see XBeeDevice#getReceiveTimeout()
         * @see XBeeDevice#setReceiveTimeout(int)
         * @see #sendData(RemoteXBeeDevice, byte[])
         * @see #sendData(XBee64BitAddress, byte[])
         * @see #sendDataAsync(RemoteXBeeDevice, byte[])
         * @see #sendDataAsync(XBee16BitAddress, byte[])
         * @see #sendDataAsync(XBee64BitAddress, byte[])
         */
        public void SendData(XBee16BitAddress address, byte[] data)        /*throws TimeoutException, XBeeException */
        {
            // Verify the parameters are not null, if they are null, throw an exception.
            if (address == null)
            {
                throw new ArgumentNullException("Address cannot be null");
            }
            if (data == null)
            {
                throw new ArgumentNullException("Data cannot be null");
            }

            // Check connection.
            if (!connectionInterface.SerialPort.IsOpen)
            {
                throw new InterfaceNotOpenException();
            }
            // Check if device is remote.
            if (IsRemote)
            {
                throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device.");
            }

            logger.InfoFormat(ToString() + "Sending data to {0} >> {1}.", address, HexUtils.PrettyHexString(data));

            XBeePacket xbeePacket = new TX16Packet(GetNextFrameID(), address, (byte)XBeeTransmitOptions.NONE, data);

            SendAndCheckXBeePacket(xbeePacket, false);
        }
Esempio n. 25
0
        public void Can_Encrypt_And_Decrypt_Forms_Authentication_Ticket()
        {
            // These would come from the asp.net 3.5 applications <machineKey decryption="AES" decryptionKey"" validation="SHA1" validationKey="" /> web.config.
            // I have made these up for the purposes of this test.
            string validationKey = "30101052676849B0B494466B7A99656346328E8964748448E422D7344467A45777D972414947271744423422851D6742C9A09A65212C276C7F839157501291C6";
            string decryptionKey = "AC7387D7E54B156377D81930CF237888854B5B5B515CF2D6356541255E696144";

            // Arrange
            var issueDate  = DateTime.Now;
            var expiryDate = issueDate.AddHours(1);
            var formsAuthenticationTicket = new FormsAuthenticationTicket(2, "*****@*****.**", issueDate, expiryDate, false, "custom data", "/");

            byte[] decryptionKeyBytes = HexUtils.HexToBinary(decryptionKey);
            byte[] validationKeyBytes = HexUtils.HexToBinary(validationKey);

            var legacyFormsAuthenticationTicketEncryptor = new LegacyFormsAuthenticationTicketEncryptor(decryptionKeyBytes, validationKeyBytes);

            // Act
            // We encrypt the forms auth cookie.
            var encryptedText = legacyFormsAuthenticationTicketEncryptor.Encrypt(formsAuthenticationTicket);

            Assert.IsNotNull(encryptedText);

            // We decrypt the encypted text back into a forms auth ticket, and compare it to the original ticket to make sure it
            // roundtripped successfully.
            FormsAuthenticationTicket decryptedFormsAuthenticationTicket = legacyFormsAuthenticationTicketEncryptor.DecryptCookie(encryptedText);

            Assert.AreEqual(formsAuthenticationTicket.CookiePath, decryptedFormsAuthenticationTicket.CookiePath);
            Assert.AreEqual(formsAuthenticationTicket.Expiration, decryptedFormsAuthenticationTicket.Expiration);
            Assert.AreEqual(formsAuthenticationTicket.Expired, decryptedFormsAuthenticationTicket.Expired);
            Assert.AreEqual(formsAuthenticationTicket.IsPersistent, decryptedFormsAuthenticationTicket.IsPersistent);
            Assert.AreEqual(formsAuthenticationTicket.IssueDate, decryptedFormsAuthenticationTicket.IssueDate);
            Assert.AreEqual(formsAuthenticationTicket.UserData, decryptedFormsAuthenticationTicket.UserData);
            Assert.AreEqual(formsAuthenticationTicket.Version, decryptedFormsAuthenticationTicket.Version);
        }
Esempio n. 26
0
        static OptionsInstructionInfo?ReadTestCase(string line, int lineNo)
        {
            var parts = line.Split(seps);

            if (parts.Length != 4)
            {
                throw new InvalidOperationException($"Invalid number of commas ({parts.Length - 1} commas)");
            }

            int bitness  = NumberConverter.ToInt32(parts[0].Trim());
            var hexBytes = parts[1].Trim();

            HexUtils.ToByteArray(hexBytes);
            var codeStr = parts[2].Trim();

            if (CodeUtils.IsIgnored(codeStr))
            {
                return(null);
            }
            var code = ToCode(codeStr);

            var properties = new List <(OptionsProps property, object value)>();

            foreach (var part in parts[3].Split(optsseps, StringSplitOptions.RemoveEmptyEntries))
            {
                properties.Add(OptionsParser.ParseOption(part));
            }

            return(new OptionsInstructionInfo(bitness, hexBytes, code, properties));
        }
Esempio n. 27
0
        public static byte[] StringToBytesBlazeUnion(string s)
        {
            List <byte> data = new List <byte>();

            for (int i = 0; i < s.Length; ++i)
            {
                char c = s[i];
                if (c == '<' && s.Substring(i, "<Voice:".Length) == "<Voice:")
                {
                    StringBuilder sb = new StringBuilder();
                    i += "<Voice:".Length;
                    while (s[i] != '>')
                    {
                        sb.Append(s[i++]);
                    }
                    data.Add(0x02);
                    data.Add(0x00);
                    data.AddRange(HexUtils.HumanReadableHexStringToByteArray(sb.ToString().Trim()).Reverse());
                }
                else
                {
                    data.AddRange(TextUtils.ShiftJISEncoding.GetBytes(c.ToString()));
                }
            }
            return(data.ToArray());
        }
Esempio n. 28
0
        protected void EncodeBase(uint id, int bitness, Code code, string hexBytes, string encodedHexBytes, DecoderOptions options)
        {
            var origBytes           = HexUtils.ToByteArray(hexBytes);
            var decoder             = CreateDecoder(bitness, origBytes, options);
            var origRip             = decoder.IP;
            var origInstr           = decoder.Decode();
            var origConstantOffsets = decoder.GetConstantOffsets(origInstr);

            Assert.Equal(code, origInstr.Code);
            Assert.Equal(origBytes.Length, origInstr.Length);
            Assert.True(origInstr.Length <= IcedConstants.MaxInstructionLength);
            Assert.Equal((ushort)origRip, origInstr.IP16);
            Assert.Equal((uint)origRip, origInstr.IP32);
            Assert.Equal(origRip, origInstr.IP);
            var afterRip = decoder.IP;

            Assert.Equal((ushort)afterRip, origInstr.NextIP16);
            Assert.Equal((uint)afterRip, origInstr.NextIP32);
            Assert.Equal(afterRip, origInstr.NextIP);

            var writer  = new CodeWriterImpl();
            var encoder = Encoder.Create(decoder.Bitness, writer);

            Assert.Equal(bitness, encoder.Bitness);
            var  origInstrCopy = origInstr;
            bool result        = encoder.TryEncode(origInstr, origRip, out uint encodedInstrLen, out string errorMessage);

            Assert.True(errorMessage is null, "Unexpected error message: " + errorMessage);
            Assert.True(result, "Error, result from Encoder.TryEncode must be true");
            var encodedConstantOffsets = encoder.GetConstantOffsets();

            FixConstantOffsets(ref encodedConstantOffsets, origInstr.Length, (int)encodedInstrLen);
            Assert.True(Equals(ref origConstantOffsets, ref encodedConstantOffsets));
            var encodedBytes = writer.ToArray();

            Assert.Equal(encodedBytes.Length, (int)encodedInstrLen);
            Assert.True(Instruction.EqualsAllBits(origInstr, origInstrCopy));

            var expectedBytes = HexUtils.ToByteArray(encodedHexBytes);

            if (!ArrayEquals(expectedBytes, encodedBytes))
            {
#pragma warning disable xUnit2006 // Do not use invalid string equality check
                // Show the full string without ellipses by using Equal<string>() instead of Equal()
                Assert.Equal <string>(ToString(expectedBytes), ToString(encodedBytes));
                throw new InvalidOperationException();
#pragma warning restore xUnit2006 // Do not use invalid string equality check
            }

            var newInstr = CreateDecoder(bitness, encodedBytes, options).Decode();
            Assert.Equal(code, newInstr.Code);
            Assert.Equal(encodedBytes.Length, newInstr.Length);
            newInstr.Length = origInstr.Length;
            newInstr.NextIP = origInstr.NextIP;
            if (origBytes.Length != expectedBytes.Length && (origInstr.MemoryBase == Register.EIP || origInstr.MemoryBase == Register.RIP))
            {
                newInstr.MemoryDisplacement += (uint)(expectedBytes.Length - origBytes.Length);
            }
            Assert.True(Instruction.EqualsAllBits(origInstr, newInstr));
        }
Esempio n. 29
0
        protected void EncodeInvalidBase(int codeSize, Code code, string hexBytes, DecoderOptions options, int invalidCodeSize)
        {
            var origBytes = HexUtils.ToByteArray(hexBytes);
            var decoder   = CreateDecoder(codeSize, origBytes, options);
            var origRip   = decoder.IP;
            var origInstr = decoder.Decode();

            Assert.Equal(code, origInstr.Code);
            Assert.Equal(origBytes.Length, origInstr.ByteLength);
            Assert.True(origInstr.ByteLength <= Iced.Intel.DecoderConstants.MaxInstructionLength);
            Assert.Equal((ushort)origRip, origInstr.IP16);
            Assert.Equal((uint)origRip, origInstr.IP32);
            Assert.Equal(origRip, origInstr.IP);
            var afterRip = decoder.IP;

            Assert.Equal((ushort)afterRip, origInstr.NextIP16);
            Assert.Equal((uint)afterRip, origInstr.NextIP32);
            Assert.Equal(afterRip, origInstr.NextIP);

            var  writer        = new CodeWriterImpl();
            var  encoder       = CreateEncoder(invalidCodeSize, writer);
            var  origInstrCopy = origInstr;
            bool result        = encoder.TryEncode(origInstr, origRip, out uint encodedInstrLen, out string errorMessage);

            Assert.Equal(invalidCodeSize == 64 ? Encoder.ERROR_ONLY_1632_BIT_MODE : Encoder.ERROR_ONLY_64_BIT_MODE, errorMessage);
            Assert.False(result);
            Assert.True(Instruction.TEST_BitByBitEquals(origInstr, origInstrCopy));
        }
Esempio n. 30
0
        override protected void ProcessBuffer(byte[] buffer)
        {
            if (CompareFirstN(buffer, End, End.Length))
            {
                _status.FirstLoadedPointNumber = 0;
                _status.LastLoadedPointNumber  = -1;
                _status.IsFinished             = true;
                return;
            }
            var from = HexUtils.ToInt16(buffer, 3 + 22);
            var to   = HexUtils.ToInt16(buffer, 3 + 22 + 2);

            if (_status.LastLoadedPointNumber + 1 != from)
            {
                throw new GH615MCommunicationError(String.Format("Loading error! Expected points from {0}, but get from {1} to {2}!", _status.LastLoadedPointNumber + 1, from, to));
            }
            int      offset     = 3 + 22 + 4;
            DateTime timeOffset = _status.TrackInfo.Date;

            if (_status.TrackPoints.Count > 0)
            {
                timeOffset = _status.TrackPoints[_status.TrackPoints.Count - 1].Time;
            }
            for (int i = 0; i <= to - from; i++)
            {
                GH615MTrackPoint point = GH615MTrackPoint.FromByteArray(buffer, offset, timeOffset);
                _status.TrackPoints.Add(point);
                timeOffset = point.Time;
                offset    += 15;
            }
            _status.FirstLoadedPointNumber = from;
            _status.LastLoadedPointNumber  = to;
        }