Пример #1
0
 public Geometry(byte[] blop)
 {
     this.Endian       = (EndianEncode)extractBytes(blop, 0, 1).First();
     this.GeometryType = (GeometryType)BitConverter.ToInt32(extractBytes(blop, 1, 4), 0);
 }
Пример #2
0
        public static string GetChaptersOfDDS(byte[] d3dtx, int poz, List <byte[]> head, List <TTG_Tools.AutoPacker.chapterOfDDS> chaptersOfDDS, string version)
        {
            //теперь разбираем
            string s_temp = "";
            //Волк среди нас и Ходячие 2: 23 шт.
            //Покер 2: 22 шт.
            //Борда и ИП: 27 шт.
            int countHeadByte = 23;

            if (version == "TFTB" || version == "WDM")
            {
                countHeadByte = 27;
            }
            else if (version == "PN2")
            {
                countHeadByte = 22;
            }
            else if (version == "Batman")
            {
                countHeadByte = 32;
            }

            for (int q = 0; q < countHeadByte; q++)                    //25
            {
                byte[] temp = new byte[4];
                Array.Copy(d3dtx, poz, temp, 0, 4);
                head.Add(temp);
                poz    += 4;
                s_temp += BitConverter.ToInt32(temp, 0).ToString() + "\r\n";
            }

            int kolvo;

            if (version == "TFTB" || version == "WDM")
            {
                kolvo = BitConverter.ToInt32(head[24], 0);
            }
            else if (version == "PN2")
            {
                kolvo = BitConverter.ToInt32(head[19], 0);
            }
            else if (version == "Batman")
            {
                kolvo = BitConverter.ToInt32(head[29], 0);
            }
            else
            {
                kolvo = BitConverter.ToInt32(head[20], 0);                    //найти смещение для количества текстур и подумать насчет 27
            }
            //System.Windows.Forms.MessageBox.Show(Convert.ToString(kolvo));
            //Смещения для количества текстур в играх:
            //Покер 2 - 19
            //Волк среди нас - 20
            //Борда - 24

            for (int k = 0; k < kolvo; k++)
            {
                List <byte[]> bTemp = new List <byte[]>();
                int           countHeadByteChapterDDS = 4;           //Волк среди нас
                if (version == "TFTB" || version == "WDM")
                {
                    countHeadByteChapterDDS = 5;                     //Борда
                }
                else if (version == "PN2")
                {
                    countHeadByteChapterDDS = 3;                     //Покер 2
                }
                else if (version == "Batman")
                {
                    countHeadByteChapterDDS = 6;                     //Бэтмен
                }


                for (int b = 0; b < countHeadByteChapterDDS; b++)
                {
                    byte[] t = new byte[4];
                    Array.Copy(d3dtx, poz, t, 0, 4);
                    bTemp.Add(t);
                    poz += 4;
                }

                if (version == "TFTB" || version == "WDM")
                {
                    chaptersOfDDS.Add(new TTG_Tools.AutoPacker.chapterOfDDS(bTemp[0], bTemp[1], bTemp[3], bTemp[2], null, bTemp[4]));
                }
                else if (version == "PN2")
                {
                    chaptersOfDDS.Add(new TTG_Tools.AutoPacker.chapterOfDDS(bTemp[0], null, bTemp[1], bTemp[2], null, null));
                }
                else if (version == "Batman")
                {
                    chaptersOfDDS.Add(new TTG_Tools.AutoPacker.chapterOfDDS(bTemp[1], bTemp[2], bTemp[3], bTemp[2], null, bTemp[5]));
                }
                else
                {
                    chaptersOfDDS.Add(new TTG_Tools.AutoPacker.chapterOfDDS(bTemp[0], bTemp[1], bTemp[2], bTemp[3], null, null));
                }
            }

            for (int k = 0; k < kolvo; k++)
            {
                int len = BitConverter.ToInt32(chaptersOfDDS[k].lenght_of_chapter, 0);
                chaptersOfDDS[k].content_chapter = new byte[len];
                Array.Copy(d3dtx, poz, chaptersOfDDS[k].content_chapter, 0, len);
                poz += len;
            }
            return("\r\n" + s_temp + "                                                        ");
        }
Пример #3
0
 /// <summary>
 /// 读取大端序的int
 /// </summary>
 /// <param name="value"></param>
 public int ReadInt(byte[] intbytes)
 {
     Array.Reverse(intbytes);
     return(BitConverter.ToInt32(intbytes, 0));
 }
Пример #4
0
 /// <summary>
 /// Конвертирует массив 4 байтов в Int32
 /// </summary>
 /// <param name="data">массив</param>
 /// <param name="index">Индекс первого числа в массиве</param>
 /// <returns></returns>
 public static int Byte4toInt32(byte[] data, int index)
 {
     return(BitConverter.ToInt32(data, index));
 }
Пример #5
0
 public override int GetHashCode()
 {
     return(BitConverter.ToInt32(BitConverter.GetBytes(Boost), 0) ^ 0x1AA71190);
 }
Пример #6
0
 public int ReadInt32(Stream s)
 {
     byte[] IntData = new byte[0x4];
     s.Read(IntData, 0x00, 0x4);
     return(BitConverter.ToInt32(IntData, 0x00));
 }
Пример #7
0
        public void ImportPSK(string path)
        {
            psk = new PSKContainer();

            FileStream pskFile = new FileStream(path, FileMode.Open, FileAccess.Read);


            do
            {
                PSKHeader h = ReadHeader(pskFile);
                byte[]    buffer;
                switch (h.name)
                {
                case "ACTRHEAD":
                    break;

                case "PNTS0000":
                {
                    #region PNTS0000
                    psk.points = new List <PSKPoint>();
                    for (int i = 0; i < h.count; i++)
                    {
                        PSKPoint pskPoint = new PSKPoint();
                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskPoint.x = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        pskPoint.y = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        pskPoint.z = BitConverter.ToSingle(buffer, 0);
                        psk.points.Add(pskPoint);
                    }
                    #endregion
                }; break;

                case "VTXW0000":
                {
                    #region VTXW0000
                    psk.edges = new List <PSKEdge>();
                    for (int i = 0; i < h.count; i++)
                    {
                        PSKEdge pskEdge = new PSKEdge();

                        buffer = new byte[2];
                        pskFile.Read(buffer, 0, 2);
                        pskEdge.index = BitConverter.ToInt16(buffer, 0);

                        buffer = new byte[2];
                        pskFile.Read(buffer, 0, 2);
                        pskEdge.padding1 = BitConverter.ToInt16(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskEdge.U = BitConverter.ToSingle(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskEdge.V = BitConverter.ToSingle(buffer, 0);

                        pskEdge.material = (byte)pskFile.ReadByte();

                        pskEdge.reserved = (byte)pskFile.ReadByte();

                        buffer = new byte[2];
                        pskFile.Read(buffer, 0, 2);
                        pskEdge.padding2 = BitConverter.ToInt16(buffer, 0);

                        psk.edges.Add(pskEdge);
                    }
                    #endregion
                }; break;


                case "FACE0000":
                {
                    #region FACE0000
                    psk.faces = new List <PSKFace>();
                    for (int i = 0; i < h.count; i++)
                    {
                        PSKFace pskFace = new PSKFace();
                        buffer = new byte[2];
                        pskFile.Read(buffer, 0, 2);
                        pskFace.v0 = BitConverter.ToInt16(buffer, 0);

                        buffer = new byte[2];
                        pskFile.Read(buffer, 0, 2);
                        pskFace.v1 = BitConverter.ToInt16(buffer, 0);

                        buffer = new byte[2];
                        pskFile.Read(buffer, 0, 2);
                        pskFace.v2 = BitConverter.ToInt16(buffer, 0);

                        pskFace.material = (byte)pskFile.ReadByte();

                        pskFace.auxmaterial = (byte)pskFile.ReadByte();

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskFace.smoothgroup = BitConverter.ToInt32(buffer, 0);

                        psk.faces.Add(pskFace);
                    }
                    #endregion
                }; break;

                case "MATT0000":
                {
                    #region MATT0000
                    psk.materials = new List <PSKMaterial>();
                    for (int i = 0; i < h.count; i++)
                    {
                        PSKMaterial pskMaterial = new PSKMaterial();
                        buffer = new byte[64];
                        pskFile.Read(buffer, 0, 64);

                        pskMaterial.name = "";
                        for (int j = 0; j < 64; j++)
                        {
                            if (buffer[j] != 0)
                            {
                                pskMaterial.name += (char)buffer[j];
                            }
                        }

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskMaterial.texture = BitConverter.ToInt32(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskMaterial.polyflags = BitConverter.ToInt32(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskMaterial.auxmaterial = BitConverter.ToInt32(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskMaterial.auxflags = BitConverter.ToInt32(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskMaterial.LODbias = BitConverter.ToInt32(buffer, 0);

                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskMaterial.LODstyle = BitConverter.ToInt32(buffer, 0);

                        psk.materials.Add(pskMaterial);
                    }

                    #endregion
                }; break;

                case "REFSKELT":
                {
                    #region REFSKELT
                    psk.bones = new List <PSKBone>();
                    for (int i = 0; i < h.count; i++)
                    {
                        PSKBone b = new PSKBone();
                        buffer = new byte[64];
                        pskFile.Read(buffer, 0, 64);
                        b.name = "";
                        for (int j = 0; j < 64; j++)
                        {
                            if (buffer[j] != 0)
                            {
                                b.name += (char)buffer[j];
                            }
                        }
                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        pskFile.Read(buffer, 0, 4);
                        b.childs = BitConverter.ToInt32(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.parent = BitConverter.ToInt32(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.rotation.x = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.rotation.y = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.rotation.z = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.rotation.w = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.location.x = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.location.y = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        b.location.z = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        pskFile.Read(buffer, 0, 4);
                        pskFile.Read(buffer, 0, 4);
                        pskFile.Read(buffer, 0, 4);
                        psk.bones.Add(b);
                    }

                    #endregion
                }; break;

                case "RAWWEIGHTS":
                {
                    psk.weights = new List <PSKWeight>();
                    for (int i = 0; i < h.count; i++)
                    {
                        PSKWeight w = new PSKWeight();
                        buffer = new byte[4];
                        pskFile.Read(buffer, 0, 4);
                        w.weight = BitConverter.ToSingle(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        w.point = BitConverter.ToInt32(buffer, 0);
                        pskFile.Read(buffer, 0, 4);
                        w.bone = BitConverter.ToInt32(buffer, 0);
                        psk.weights.Add(w);
                    }
                }; break;

                    #region The rest

                case "EXTRAUVS0":
                {
                    psk.extrauv1 = new List <PSKExtraUV>();
                    buffer       = new byte[h.size * h.count];
                    pskFile.Read(buffer, 0, h.size * h.count);

                    //buffer = new byte[4];
                    //pskFile.Read(buffer, 0, 4);


                    //float size = BitConverter.ToInt32(buffer, 0);

                    //buffer = new byte[4];
                    //pskFile.Read(buffer, 0, 4);


                    //int count = BitConverter.ToInt32(buffer, 0);

                    //for (int i = 0; i < count; i++)
                    //{
                    //    PSKExtraUV uvSet = new PSKExtraUV();
                    //    buffer = new byte[4];
                    //    pskFile.Read(buffer, 0, 4);


                    //    uvSet.U = BitConverter.ToSingle(buffer, 0);

                    //    buffer = new byte[4];
                    //    pskFile.Read(buffer, 0, 4);


                    //    uvSet.V = BitConverter.ToSingle(buffer, 0);

                    //    psk.extrauv1.Add(uvSet);
                    //}
                }; break;
                    //yeah, so much about not typing too much :p
                    //Well you wrote everything in the cases, you could have easily used functions :p
                    #endregion
                }
            } while (pskFile.Position < pskFile.Length);
        }
Пример #8
0
        public bool ReadByteQPack(byte[] buf,ref int offs)
        {
            if (buf.Length - offs < 5)
            {
                return(true);
            }
            IsTransferingAltPacks = BitConverter.ToBoolean(buf,offs);
            ++offs;
            int n = BitConverter.ToInt32(buf,offs);

            offs += 4;
            int l = buf.Length - offs;

            while (0 < n)
            {
                if (l < 4)
                {
                    return(true);
                }
                --n;
                int   x;
                Level lv;
                if (Enum.IsDefined(typeof(Level),x = BitConverter.ToInt32(buf,offs)))
                {
                    lv = (Level)x;
                }
                else
                {
                    return(true);
                }
                l    -= 4;
                offs += 4;
                if (MainPacks[lv].ReadByte(buf, ref offs))
                {
                    return(true);
                }
            }
            if (n != 0)
            {
                return(true);
            }
            //
            if (buf.Length - offs < 4)
            {
                return(true);
            }
            n     = BitConverter.ToInt32(buf, offs);
            offs += 4;
            l     = buf.Length - offs;
            while (0 < n)
            {
                if (l < 4)
                {
                    return(true);
                }
                --n;
                int   x;
                Level lv;
                if (Enum.IsDefined(typeof(Level), x = BitConverter.ToInt32(buf, offs)))
                {
                    lv = (Level)x;
                }
                else
                {
                    return(true);
                }
                offs += 4;
                if (AltPacks[lv].ReadByte(buf, ref offs))
                {
                    return(true);
                }
            }
            if (n != 0)
            {
                return(true);
            }
            return(false);
        }
        public static Bitmap CalculateMedianFilter(this Bitmap sourceBitmap,
                                                   int matrixSize,
                                                   int bias       = 0,
                                                   bool grayscale = false)
        {
            BitmapData sourceData =
                sourceBitmap.LockBits(new Rectangle(0, 0,
                                                    sourceBitmap.Width, sourceBitmap.Height),
                                      ImageLockMode.ReadOnly,
                                      PixelFormat.Format32bppArgb);


            byte[] pixelBuffer = new byte[sourceData.Stride *
                                          sourceData.Height];


            byte[] resultBuffer = new byte[sourceData.Stride *
                                           sourceData.Height];


            Marshal.Copy(sourceData.Scan0, pixelBuffer, 0,
                         pixelBuffer.Length);


            sourceBitmap.UnlockBits(sourceData);


            if (grayscale == true)
            {
                float rgb = 0;


                for (int k = 0; k < pixelBuffer.Length; k += 4)
                {
                    rgb  = pixelBuffer[k] * 0.11f;
                    rgb += pixelBuffer[k + 1] * 0.59f;
                    rgb += pixelBuffer[k + 2] * 0.3f;


                    pixelBuffer[k]     = (byte)rgb;
                    pixelBuffer[k + 1] = pixelBuffer[k];
                    pixelBuffer[k + 2] = pixelBuffer[k];
                    pixelBuffer[k + 3] = 255;
                }
            }


            int filterOffset = (matrixSize - 1) / 2;
            int calcOffset   = 0;


            int byteOffset = 0;

            List <int> neighbourPixels = new List <int>();

            byte[] middlePixel;


            for (int offsetY = filterOffset; offsetY <
                 sourceBitmap.Height - filterOffset; offsetY++)
            {
                for (int offsetX = filterOffset; offsetX <
                     sourceBitmap.Width - filterOffset; offsetX++)
                {
                    byteOffset = offsetY *
                                 sourceData.Stride +
                                 offsetX * 4;


                    neighbourPixels.Clear();


                    for (int filterY = -filterOffset;
                         filterY <= filterOffset; filterY++)
                    {
                        for (int filterX = -filterOffset;
                             filterX <= filterOffset; filterX++)
                        {
                            calcOffset = byteOffset +
                                         (filterX * 4) +
                                         (filterY * sourceData.Stride);


                            neighbourPixels.Add(BitConverter.ToInt32(
                                                    pixelBuffer, calcOffset));
                        }
                    }


                    neighbourPixels.Sort();

                    middlePixel = BitConverter.GetBytes(
                        neighbourPixels[filterOffset]);


                    resultBuffer[byteOffset]     = middlePixel[0];
                    resultBuffer[byteOffset + 1] = middlePixel[1];
                    resultBuffer[byteOffset + 2] = middlePixel[2];
                    resultBuffer[byteOffset + 3] = middlePixel[3];
                }
            }


            Bitmap resultBitmap = new Bitmap(sourceBitmap.Width,
                                             sourceBitmap.Height);


            BitmapData resultData =
                resultBitmap.LockBits(new Rectangle(0, 0,
                                                    resultBitmap.Width, resultBitmap.Height),
                                      ImageLockMode.WriteOnly,
                                      PixelFormat.Format32bppArgb);


            Marshal.Copy(resultBuffer, 0, resultData.Scan0,
                         resultBuffer.Length);


            resultBitmap.UnlockBits(resultData);


            return(resultBitmap);
        }
Пример #10
0
        /// <summary>
        /// Setup the DataLayer by starting up the pre-fetching.
        /// </summary>
        /// <param name="colBottom">Not used.</param>
        /// <param name="colTop">Specifies the collection of top (output) Blobs.</param>
        protected override void DataLayerSetUp(BlobCollection <T> colBottom, BlobCollection <T> colTop)
        {
            int  nBatchSize        = (int)m_param.data_param.batch_size;
            bool bLoadDataCriteria = false;

            m_bMatchingCycle = true;

            m_cursor = m_db.NewCursor(m_transformer, (m_param.data_param.output_image_information) ? m_log : null);

            if (m_bOutputLabels && m_param.data_param.label_type == DataParameter.LABEL_TYPE.MULTIPLE)
            {
                bLoadDataCriteria = true;
            }

            // Read a data point, and use it to initialize the top blob.
            SimpleDatum datum = m_cursor.GetValue(null, bLoadDataCriteria);

            // Use data transformer to infer the expected blob shape from the datum.
            m_rgTopShape = m_transformer.InferBlobShape(datum, m_rgTopShape);

            // When using noise as the secondary image, fill it with noise.
            if (m_param.data_param.enable_noise_for_nonmatch)
            {
                m_datumNoise = createNoisyData(m_rgTopShape, datum);
            }

            // Double the channels when loading image pairs where the first image is loaded followed by the second on the channel.
            if (m_param.data_param.images_per_blob > 1)
            {
                m_log.CHECK_EQ(m_param.data_param.images_per_blob, 2, "Currently images_per_blob only supports 2 image pairing and must be set to 2 for image pairing.");
                m_rgTopShape[1] *= m_param.data_param.images_per_blob;
            }

            // Reshape colTop[0] and prefetch data according to the batch size.
            m_rgTopShape[0] = nBatchSize;
            colTop[0].Reshape(m_rgTopShape);

            for (int i = 0; i < m_rgPrefetch.Length; i++)
            {
                m_rgPrefetch[i].Data.Reshape(m_rgTopShape);
            }

            m_log.WriteLine("output data size: " + colTop[0].ToSizeString());

            // Fill out the masks, if used.
            if (m_param.transform_param.mask_param != null && m_param.transform_param.mask_param.Active)
            {
                createMasks(Utility.Clone <int>(m_rgTopShape));
            }

            // Reshape debug data, if used.
            if (m_param.data_param.enable_debug_output)
            {
                createDebug(Utility.Clone <int>(m_rgTopShape));
            }

            // Label
            if (m_bOutputLabels)
            {
                List <int> rgLabelShape = new List <int>()
                {
                    nBatchSize
                };

                // When using multi-labels, resize to batch x the number of multiple
                // labels per image.
                if (m_param.data_param.label_type == DataParameter.LABEL_TYPE.MULTIPLE)
                {
                    if (m_param.data_param.one_hot_label_size == 0)
                    {
                        if (m_param.data_param.images_per_blob > 1)
                        {
                            m_log.FAIL("Image pairing per blob currently only supports the " + DataParameter.LABEL_TYPE.SINGLE.ToString() + " label type.");
                        }

                        if (datum.DataCriteria == null || datum.DataCriteria.Length == 0)
                        {
                            m_log.FAIL("Could not find the multi-label data.  The data source '" + m_param.data_param.source + "' does not appear to have any Image Criteria data.");
                        }

                        if (datum.DataCriteriaFormat == SimpleDatum.DATA_FORMAT.LIST_DOUBLE)
                        {
                            List <double> rg   = BinaryData.UnPackDoubleList(datum.DataCriteria, datum.DataCriteriaFormat);
                            int           nLen = rg.Count;
                            rgLabelShape.Add(nLen);
                            rgLabelShape.Add(1);
                            rgLabelShape.Add(1);
                        }
                        else if (datum.DataCriteriaFormat == SimpleDatum.DATA_FORMAT.LIST_FLOAT)
                        {
                            List <float> rg   = BinaryData.UnPackFloatList(datum.DataCriteria, datum.DataCriteriaFormat);
                            int          nLen = rg.Count;
                            rgLabelShape.Add(nLen);
                            rgLabelShape.Add(1);
                            rgLabelShape.Add(1);
                        }
                        else
                        {
                            // Get the number of items and the item size from the end of the data.
                            int nLen      = BitConverter.ToInt32(datum.DataCriteria, datum.DataCriteria.Length - (sizeof(int) * 4));
                            int nItemSize = BitConverter.ToInt32(datum.DataCriteria, datum.DataCriteria.Length - (sizeof(int) * 3));

                            rgLabelShape.Add(nLen);
                            m_log.CHECK_EQ(nItemSize, 1, "Currently only byte sized labels are supported in multi-label scenarios.");
                        }
                    }
                    else
                    {
                        rgLabelShape.Add(m_param.data_param.one_hot_label_size);
                        rgLabelShape.Add(1);
                        rgLabelShape.Add(1);
                    }
                }
                else
                {
                    int nChannels = 1;

                    // 1 label comparison + each label in pair order to which they were added to the blob.
                    if (m_param.data_param.images_per_blob > 1)
                    {
                        if (m_param.data_param.output_all_labels)
                        {
                            nChannels = m_param.data_param.images_per_blob;
                        }
                    }

                    rgLabelShape.Add(nChannels);
                }

                colTop[1].Reshape(rgLabelShape);

                for (int i = 0; i < m_rgPrefetch.Length; i++)
                {
                    m_rgPrefetch[i].Label.Reshape(rgLabelShape);
                }
            }

            m_nIteration  = 0;
            m_nBatchCount = 0;
        }
Пример #11
0
        /// <summary>
        /// Load a batch of data in the background (this is run on an internal thread within the BasePrefetchingDataLayer class).
        /// </summary>
        /// <param name="batch">Specifies the Batch of data to load.</param>
        protected override void load_batch(Batch <T> batch)
        {
            m_log.CHECK(batch.Data.count() > 0, "There is no space allocated for data!");
            int  nBatchSize        = (int)m_param.data_param.batch_size;
            bool bLoadDataCriteria = false;

            if (m_bOutputLabels && m_param.data_param.one_hot_label_size == 0 && m_param.data_param.label_type == DataParameter.LABEL_TYPE.MULTIPLE)
            {
                bLoadDataCriteria = true;
            }

            if (m_bOutputLabels)
            {
                if (m_param.data_param.one_hot_label_size > 0 && m_param.data_param.label_type == DataParameter.LABEL_TYPE.MULTIPLE)
                {
                    int nCount = m_param.data_param.one_hot_label_size;

                    if (m_rgOneHotLabel == null || m_rgOneHotLabel.Length != nCount)
                    {
                        m_rgOneHotLabel = new T[nCount];
                    }

                    nCount = batch.Label.count();

                    if (m_rgTopLabel == null || m_rgTopLabel.Length != nCount)
                    {
                        m_rgTopLabel = new T[nCount];
                    }
                }
                else
                {
                    int nCount = batch.Label.count();
                    m_log.CHECK_GT(nCount, 0, "The label count cannot be zero!");

                    if (m_rgTopLabel == null || m_rgTopLabel.Length < nCount)
                    {
                        m_rgTopLabel = new T[nCount];
                    }
                }
            }

            if (m_param.data_param.display_timing)
            {
                m_swTimerBatch.Restart();
                m_dfReadTime  = 0;
                m_dfTransTime = 0;
            }

            SimpleDatum datum;
            int         nDim           = 0;
            List <int>  rgLabels       = null;
            List <int>  rgTargetLabels = null;

            if (OnBatchLoad != null)
            {
                rgLabels = new List <int>();
            }

            // If we are synced with another dataset, wait for it to load the initial data set.
            if (m_param.data_param.synchronize_target)
            {
                m_log.CHECK_EQ(m_param.data_param.images_per_blob, 1, "DataLayer synchronize targets are not supported when loading more than 1 image per blob.");

                int nWait = m_rgBatchLabels.WaitReady;
                if (nWait == 0)
                {
                    return;
                }

                rgTargetLabels = m_rgBatchLabels.Get();
                m_log.CHECK_EQ(nBatchSize, m_rgBatchLabels.Count, "The batch label count (previously loaded by the primary dataset) does not match the batch size '" + m_param.data_param.batch_size.ToString() + "' of this layer!");
            }

            for (int i = 0; i < nBatchSize; i++)
            {
                if (m_param.data_param.display_timing)
                {
                    m_swTimerTransaction.Restart();
                }

                while (Skip())
                {
                    if (m_evtCancel.WaitOne(0))
                    {
                        return;
                    }
                    Next();
                }

                if (rgTargetLabels == null)
                {
                    datum = m_cursor.GetValue(null, bLoadDataCriteria);

                    if (m_param.data_param.images_per_blob > 1)
                    {
                        if (m_rgDatum == null || m_rgDatum.Length != m_param.data_param.images_per_blob - 1)
                        {
                            m_rgDatum = new SimpleDatum[m_param.data_param.images_per_blob - 1];
                        }

                        for (int j = 0; j < m_param.data_param.images_per_blob - 1; j++)
                        {
                            Next();

                            while (Skip())
                            {
                                if (m_evtCancel.WaitOne(0))
                                {
                                    return;
                                }
                                Next();
                            }

                            if (m_param.data_param.balance_matches)
                            {
                                if (m_bMatchingCycle)
                                {
                                    m_rgDatum[j] = getNextPair(true, datum, bLoadDataCriteria);
                                }
                                else
                                {
                                    if (m_param.data_param.enable_noise_for_nonmatch)
                                    {
                                        m_rgDatum[j] = m_datumNoise;
                                    }
                                    else
                                    {
                                        m_rgDatum[j] = getNextPair(false, datum, bLoadDataCriteria);
                                    }
                                }
                            }
                            else
                            {
                                if (m_param.data_param.enable_noise_for_nonmatch)
                                {
                                    m_rgDatum[j] = m_datumNoise;
                                }
                                else
                                {
                                    m_rgDatum[j] = m_cursor.GetValue(null, bLoadDataCriteria);
                                }
                            }
                        }

                        m_bMatchingCycle = !m_bMatchingCycle;
                    }
                }
                else
                {
                    datum = m_cursor.GetValue(rgTargetLabels[i], bLoadDataCriteria);
                }

                // When debug output is enabled, output information each image loaded.
                if (m_param.data_param.enable_debug_output)
                {
                    saveImageInfo(m_param.data_param.data_debug_param, datum, i, 0);

                    if (m_rgDatum != null)
                    {
                        for (int n = 0; n < m_rgDatum.Length; n++)
                        {
                            saveImageInfo(m_param.data_param.data_debug_param, m_rgDatum[n], i, n + 1);
                        }
                    }
                }

                if (m_param.data_param.display_timing)
                {
                    m_dfReadTime += m_swTimerTransaction.Elapsed.TotalMilliseconds;
                    m_swTimerTransaction.Restart();
                }

                if (i == 0)
                {
                    // Reshape according to the first datum of each batch
                    // on single input batches allows for inputs of varying dimension.
                    // Use data transformer to infer the expected blob shape for datum.
                    m_rgTopShape = m_transformer.InferBlobShape(datum, m_rgTopShape);

                    // Double the channels when loading image pairs where the first image is loaded followed by the second on the channel.
                    if (m_rgDatum != null)
                    {
                        m_rgTopShape[1] *= (m_rgDatum.Length + 1);
                    }

                    // Reshape batch according to the batch size.
                    m_rgTopShape[0] = nBatchSize;
                    batch.Data.Reshape(m_rgTopShape);

                    nDim = 1;
                    for (int k = 1; k < m_rgTopShape.Length; k++)
                    {
                        nDim *= m_rgTopShape[k];
                    }

                    int nTopLen = nDim * nBatchSize;
                    if (m_rgTopData == null || m_rgTopData.Length != nTopLen)
                    {
                        m_rgTopData = new T[nTopLen];
                    }
                }

                // Apply data transformations (mirrow, scaling, crop, etc)
                int nDimCount = nDim;

                if (m_rgDatum != null)
                {
                    nDimCount /= (m_rgDatum.Length + 1);
                }

                T[] rgTrans = m_transformer.Transform(datum);
                Array.Copy(rgTrans, 0, m_rgTopData, nDim * i, nDimCount);

                // When using load_image_pairs, stack the additional images right after the first.
                if (m_rgDatum != null)
                {
                    for (int j = 0; j < m_rgDatum.Length; j++)
                    {
                        rgTrans = m_transformer.Transform(m_rgDatum[j]);
                        int nOffset = (nDim * i) + (nDimCount * (j + 1));
                        Array.Copy(rgTrans, 0, m_rgTopData, nOffset, nDimCount);
                    }
                }

                // Copy label.
                if (m_bOutputLabels)
                {
                    if (m_param.data_param.label_type == DataParameter.LABEL_TYPE.MULTIPLE)
                    {
                        if (m_param.data_param.one_hot_label_size > 0)
                        {
                            int nMask = 0x1;

                            for (int j = 0; j < m_rgOneHotLabel.Length; j++)
                            {
                                if ((datum.Label & nMask) == 0)
                                {
                                    m_rgOneHotLabel[j] = m_tZero;
                                }
                                else
                                {
                                    m_rgOneHotLabel[j] = m_tOne;
                                }

                                nMask <<= 1;
                            }

                            Array.Copy(m_rgOneHotLabel, 0, m_rgTopLabel, i * m_rgOneHotLabel.Length, m_rgOneHotLabel.Length);
                        }
                        else
                        {
                            if (m_param.data_param.images_per_blob > 1)
                            {
                                m_log.FAIL("Loading image pairs (images_per_blob > 1) currently only supports the " + DataParameter.LABEL_TYPE.SINGLE.ToString() + " label type.");
                            }

                            if (m_param.transform_param.label_mapping.Active)
                            {
                                m_log.FAIL("Label mapping is not supported on labels of type 'MULTIPLE'.");
                            }

                            if (datum.DataCriteria == null || datum.DataCriteria.Length == 0)
                            {
                                m_log.FAIL("Could not find the multi-label data.  The data source '" + m_param.data_param.source + "' does not appear to have any Image Criteria data.");
                            }

                            // Get the number of items and the item size from the end of the data.
                            int nLen      = BitConverter.ToInt32(datum.DataCriteria, datum.DataCriteria.Length - (sizeof(int) * 4));
                            int nItemSize = BitConverter.ToInt32(datum.DataCriteria, datum.DataCriteria.Length - (sizeof(int) * 3));
                            int nDstIdx   = i * nLen;

                            m_log.CHECK_EQ(nItemSize, 1, "Currently only byte sized labels are supported in multi-label scenarios.");
                            Array.Copy(datum.DataCriteria, 0, m_rgTopLabel, nDstIdx, nLen);
                        }
                    }
                    else
                    {
                        // When using image pairs, the label is set to 1 when the labels are the same and 0 when they are different.
                        if (m_rgDatum != null)
                        {
                            if (m_rgDatum.Length == 1)
                            {
                                int nLabelDim = 1;

                                if (m_param.data_param.output_all_labels)
                                {
                                    nLabelDim = m_param.data_param.images_per_blob;
                                }

                                if (m_param.data_param.output_all_labels)
                                {
                                    int nLabel = datum.Label;
                                    if (m_param.data_param.forced_primary_label >= 0)
                                    {
                                        nLabel = m_param.data_param.forced_primary_label;
                                    }

                                    m_rgTopLabel[i * nLabelDim] = (T)Convert.ChangeType(nLabel, typeof(T));

                                    for (int j = 0; j < m_rgDatum.Length; j++)
                                    {
                                        m_rgTopLabel[i * nLabelDim + 1 + j] = (T)Convert.ChangeType(m_rgDatum[j].Label, typeof(T));
                                    }
                                }
                                else
                                {
                                    if (datum.Label == m_rgDatum[0].Label)
                                    {
                                        m_rgTopLabel[i * nLabelDim] = m_tOne;
                                    }
                                    else
                                    {
                                        m_rgTopLabel[i * nLabelDim] = m_tZero;
                                    }
                                }
                            }
                            else
                            {
                                m_log.FAIL("Currently image pairing only supports up to 2 images per blob.");
                            }
                        }
                        else
                        {
                            m_rgTopLabel[i] = (T)Convert.ChangeType(datum.Label, typeof(T));
                        }
                    }
                }

                if (m_param.data_param.display_timing)
                {
                    m_dfTransTime += m_swTimerTransaction.Elapsed.TotalMilliseconds;
                }

                if (rgLabels != null)
                {
                    rgLabels.Add(datum.Label);
                }

                Next();

                if (m_evtCancel.WaitOne(0))
                {
                    return;
                }
            }

            m_nBatchCount++;
            batch.Data.SetCPUData(m_rgTopData);

            if (m_bOutputLabels)
            {
                batch.Label.SetCPUData(m_rgTopLabel);
            }

            if (m_param.data_param.display_timing)
            {
                m_swTimerBatch.Stop();
                m_swTimerTransaction.Stop();
                m_log.WriteLine("Prefetch batch: " + m_swTimerBatch.ElapsedMilliseconds.ToString() + " ms.", true);
                m_log.WriteLine("     Read time: " + m_dfReadTime.ToString() + " ms.", true);
                m_log.WriteLine("Transform time: " + m_dfTransTime.ToString() + " ms.", true);
            }

            if (m_param.data_param.synchronize_target)
            {
                if (m_rgBatchLabels != null)
                {
                    m_rgBatchLabels.Done();
                }
            }

            if (OnBatchLoad != null)
            {
                OnBatchLoad(this, new LastBatchLoadedArgs(rgLabels));
            }
        }
Пример #12
0
 private static int ConvertBytesToInt32(byte[] bytes)
 {
     ConvertFrom4Bytes(bytes);
     return(BitConverter.ToInt32(_byteBlock, 0));
 }
Пример #13
0
        // For more information about the format: https://docs.microsoft.com/en-us/previous-versions/ms969901(v=msdn.10)?redirectedfrom=MSDN
        private void CreateBitmap(Stream stream)
        {
            #region BMP Header

            Byte[] _int   = new byte[4];
            Byte[] _short = new byte[2];
            //Assume that we are using the BMP (Windows) V3 header format

            //reading magic number to identify if BMP file (BM as string - 42 4D as Hex) - bytes 0 -> 2
            stream.Read(_short, 0, 2);
            if ("42-4D" != BitConverter.ToString(_short))
            {
                throw new Exception("Header is not from a BMP");
            }

            //read size of BMP file - byte 2 -> 6
            stream.Read(_int, 0, 4);
            uint fileSize = BitConverter.ToUInt32(_int, 0);

            stream.Position = 10;
            //read header - bytes 10 -> 14 is the offset of the bitmap image data
            stream.Read(_int, 0, 4);
            uint pixelTableOffset = BitConverter.ToUInt32(_int, 0);

            //now reading size of BITMAPINFOHEADER should be 40 - bytes 14 -> 18
            stream.Read(_int, 0, 4);
            uint infoHeaderSize = BitConverter.ToUInt32(_int, 0);
            if (infoHeaderSize != 40)
            {
                throw new Exception("Info header size has the wrong value!");
            }
            //now reading width of image in pixels - bytes 18 -> 22
            stream.Read(_int, 0, 4);
            uint imageWidth = BitConverter.ToUInt32(_int, 0);

            //now reading height of image in pixels - byte 22 -> 26
            stream.Read(_int, 0, 4);
            uint imageHeight = BitConverter.ToUInt32(_int, 0);

            //now reading number of planes should be 1 - byte 26 -> 28
            stream.Read(_short, 0, 2);
            ushort planes = BitConverter.ToUInt16(_short, 0);
            if (planes != 1)
            {
                throw new Exception("Number of planes is not 1! Can not read file!");
            }
            //now reading size of bits per pixel (1, 4, 8, 24, 32) - bytes 28 - 30
            stream.Read(_short, 0, 2);
            ushort pixelSize = BitConverter.ToUInt16(_short, 0);
            //TODO: Be able to handle other pixel sizes
            if (!(pixelSize == 32 || pixelSize == 24))
            {
                throw new NotImplementedException("Can only handle 32bit or 24bit bitmaps!");
            }
            //now reading compression type - bytes 30 -> 34
            stream.Read(_int, 0, 4);
            uint compression = BitConverter.ToUInt32(_int, 0);
            //TODO: Be able to handle compressed files
            if (compression != 0)
            {
                Global.mDebugger.Send("Can only handle uncompressed files!");
                throw new NotImplementedException("Can only handle uncompressed files!");
            }
            //now reading total image data size(including padding) - bytes 34 -> 38
            stream.Read(_int, 0, 4);
            uint totalImageSize = BitConverter.ToUInt32(_int, 0);
            if (totalImageSize == 0)
            {
                totalImageSize = (uint)((((imageWidth * pixelSize) + 31) & ~31) >> 3) * imageHeight; // Look at the link above for the explanation
                Global.mDebugger.SendInternal("Calcualted image size: " + totalImageSize);
            }

            #endregion BMP Header

            //Set the bitmap to have the correct values
            Width  = imageWidth;
            Height = imageHeight;
            Depth  = (ColorDepth)pixelSize;
            Global.mDebugger.SendInternal("Width: " + Width);
            Global.mDebugger.SendInternal("Height: " + Height);
            Global.mDebugger.SendInternal("Depth: " + pixelSize);

            rawData = new int[Width * Height];

            #region Pixel Table

            //Calculate padding
            int paddingPerRow;
            int pureImageSize = (int)(imageWidth * imageHeight * pixelSize / 8);
            if (totalImageSize != 0)
            {
                int remainder = (int)totalImageSize - pureImageSize;
                if (remainder < 0)
                {
                    throw new Exception("Total Image Size is smaller than pure image size");
                }
                paddingPerRow = remainder / (int)imageHeight;
                pureImageSize = (int)totalImageSize;
            }
            else
            {
                //total image size is 0 if it is not compressed
                paddingPerRow = 0;
            }
            //Read data
            stream.Position = (int)pixelTableOffset;
            int    position  = 0;
            Byte[] pixelData = new byte[pureImageSize];
            stream.Read(pixelData, 0, pureImageSize);
            Byte[] pixel = new byte[4]; //All must have the same size

            for (int y = 0; y < imageHeight; y++)
            {
                for (int x = 0; x < imageWidth; x++)
                {
                    if (pixelSize == 32)
                    {
                        pixel[0] = pixelData[position++];
                        pixel[1] = pixelData[position++];
                        pixel[2] = pixelData[position++];
                        pixel[3] = pixelData[position++];
                    }
                    else
                    {
                        pixel[0] = pixelData[position++];
                        pixel[1] = pixelData[position++];
                        pixel[2] = pixelData[position++];
                        pixel[3] = 0;
                    }
                    rawData[x + (imageHeight - (y + 1)) * imageWidth] = BitConverter.ToInt32(pixel, 0); //This bits should be A, R, G, B but order is switched
                }
                position += paddingPerRow;
            }

            #endregion Pixel Table
        }
Пример #14
0
        public static void Main(string[] args)
        {
            Console.Title = "Wow RDP Patcher";
            ColorPrint(@"  _      __             ___  ___  ___    ___       __      __          ", ConsoleColor.White);
            ColorPrint(@" | | /| / /__ _    __  / _ \/ _ \/ _ \  / _ \___ _/ /_____/ /  ___ ____", ConsoleColor.White);
            ColorPrint(@" | |/ |/ / _ \ |/|/ / / , _/ // / ___/ / ___/ _ `/ __/ __/ _ \/ -_) __/", ConsoleColor.White);
            ColorPrint(@" |__/|__/\___/__,__/ /_/|_/____/_/    /_/   \_,_/\__/\__/_//_/\__/_/   ", ConsoleColor.White);
            ColorPrint($"                                      Version: ", $"{Assembly.GetEntryAssembly().GetName().Version}\n", ConsoleColor.Yellow);

            if (args.Length < 1)
            {
                ColorPrint(">> Drop an *.exe on me...");
            }
            else
            {
                string file = args[0];

                if (string.IsNullOrEmpty(file))
                {
                    ColorPrint(">> Invalid filepath...");
                }
                else
                {
                    if (File.Exists(file))
                    {
                        byte[] exeBytes = File.ReadAllBytes(file);

                        if (exeBytes[0] != 'M' || exeBytes[1] != 'Z')
                        {
                            ColorPrint($">> {Path.GetFileName(file)} is not a valid PE file...", ConsoleColor.Red);
                        }
                        else
                        {
                            FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(file);
                            ColorPrint($">> File version:\t\t", versionInfo.FileVersion, ConsoleColor.Yellow);

                            if (FindByteSequence(exeBytes, rdpStringBytes, out int stringOffset))
                            {
                                if (FindByteSequence(exeBytes, peHeader, out int peHeaderOffset))
                                {
                                    if (FindByteSequence(exeBytes, rdataHeader, out int rdataOffset))
                                    {
                                        // for wow this should be 0x400000
                                        int imageBase = BitConverter.ToInt32(exeBytes, peHeaderOffset + 0x34);
                                        ColorPrint($">> PE ImageBase:\t\t", $"0x{imageBase:X}", ConsoleColor.Cyan);

                                        rdataOffset += imageBase;
                                        ColorPrint($">> .rdata section at:\t\t", $"0x{rdataOffset:X}", ConsoleColor.Cyan);

                                        // the string is stored in the .rdata section
                                        int virtualAddress   = BitConverter.ToInt32(exeBytes, rdataOffset - imageBase + 12);
                                        int pointerToRawData = BitConverter.ToInt32(exeBytes, rdataOffset - imageBase + 20);

                                        ColorPrint($">> VirtualAddress:\t\t", $"0x{virtualAddress:X}", ConsoleColor.Cyan);
                                        ColorPrint($">> PointerToRawData:\t\t", $"0x{pointerToRawData:X}", ConsoleColor.Cyan);

                                        // virtual memory offset to find the usage of our string
                                        int vaOffset = virtualAddress - pointerToRawData;
                                        ColorPrint($">> Virtual Address Offset:\t", $"0x{vaOffset:X}", ConsoleColor.Cyan);

                                        // add base offset
                                        stringOffset += imageBase + vaOffset;
                                        ColorPrint(">> Found RDP string at:\t\t", $"0x{stringOffset:X}", ConsoleColor.Cyan);

                                        // we will look for the place, where the string gets loaded
                                        // 0x68 = PUSH
                                        byte[] stringOffsetBytes = BitConverter.GetBytes(stringOffset);
                                        byte[] bytesRdpCheck     = new byte[] { 0x68, 0x00, 0x00, 0x00, 0x00 };

                                        // copy the string offset behind the push instruction
                                        Array.Copy(stringOffsetBytes, 0, bytesRdpCheck, 1, 4);

                                        StringBuilder sbRdpCheck = new StringBuilder();

                                        for (int i = 0; i < 5; ++i)
                                        {
                                            sbRdpCheck.Append($"0x{bytesRdpCheck[i]:X} ");
                                        }

                                        ColorPrint($">> Searching RDP string PUSH:\t", sbRdpCheck.ToString(), ConsoleColor.Cyan);

                                        if (FindByteSequence(exeBytes, bytesRdpCheck, out int offset))
                                        {
                                            ColorPrint(">> Found RDP check function at: ", $"0x{offset:X}", ConsoleColor.Cyan);

                                            if (exeBytes[offset] == 0x90)
                                            {
                                                ColorPrint($">> Wow is already patched");
                                            }
                                            else
                                            {
                                                string backupFilename = $"{file}.backup";

                                                File.WriteAllBytes(backupFilename, exeBytes);
                                                ColorPrint($">> Backup exe:\t\t\t", Path.GetFileName(backupFilename), ConsoleColor.Green);

                                                StringBuilder sbRdpFunc = new StringBuilder();

                                                // fill the next 15 bytes with NOP's to prevent wow from exiting
                                                for (int i = 0; i < 15; ++i)
                                                {
                                                    sbRdpFunc.Append($"0x{exeBytes[offset + i]:X} ");
                                                    exeBytes[offset + i] = 0x90; // NOP
                                                }

                                                ColorPrint($">> Replaced bytes with NOP:\t", sbRdpFunc.ToString(), ConsoleColor.Cyan);
                                                File.WriteAllBytes(file, exeBytes);

                                                ColorPrint(">> Patching: ", "successful", ConsoleColor.Green);
                                            }
                                        }
                                        else
                                        {
                                            ColorPrint(">> Unable to locate rdp check function...", ConsoleColor.Red);
                                            ColorPrint(">> Executeable is already patched or incompatible...");
                                        }
                                    }
                                    else
                                    {
                                        ColorPrint(">> Unable to locate .rdata section header...", ConsoleColor.Red);
                                    }
                                }
                                else
                                {
                                    ColorPrint(">> Unable to locate PE header...", ConsoleColor.Red);
                                }
                            }
                            else
                            {
                                ColorPrint(">> Unable to locate RDP string", ConsoleColor.Red);
                            }
                        }
                    }
                    else
                    {
                        ColorPrint(">> File not found...", ConsoleColor.Red);
                    }
                }
            }

            ColorPrint(">> Press a key to exit...");
            Console.ReadKey();
        }
        void ReadCallback(IAsyncResult ar)
        {
            if (!this.ClientHandler.Connected)
            {
                Close(false);
                return;
            }
            if (this.ClientMessageReceived == null)
            {
                GetNewMessage();
                return;
            }

            int bytesRead = this.ClientHandler.EndReceive(ar);

            if (bytesRead > 0)
            {
                List <byte> data = buffer.Take(bytesRead).ToList();
                if (readingData == null)
                {
                    if (bytesRead < 12)
                    {
                        //mensagem inválida
                        GetNewMessage();
                        return;
                    }
                    try
                    {
                        messageCheckSum      = BitConverter.ToInt32(data.Take(4).ToArray(), 0);
                        readingMessageTypeID = BitConverter.ToInt32(data.Skip(4).Take(4).ToArray(), 0);
                        messageSize          = BitConverter.ToInt32(data.Skip(8).Take(4).ToArray(), 0);
                        receivedCheckSum     = 0;
                        //checksum
                        unchecked
                        {
                            for (int i = 4; i < data.Count; i++)
                            {
                                receivedCheckSum = receivedCheckSum ^ data[i];
                            }
                        }
                    }
                    catch (Exception)
                    {
                        readingMessageTypeID = -1;
                        messageSize          = 0;
                    }

                    if (readingMessageTypeID <= -1 || messageSize <= 0)
                    {
                        GetNewMessage();
                        return;
                    }
                    readingData = new List <byte>();
                    if (bytesRead > 12)
                    {
                        readingData.AddRange(data.Skip(12));
                        if (readingData.Count == messageSize)
                        {
                            if (messageCheckSum != receivedCheckSum)
                            {
                                //mensagem inválida ignora
                                GetNewMessage();
                                return;
                            }
                            MessageReceived(readingMessageTypeID, readingData.ToArray());
                            return;
                        }//invalid command
                        else if (readingData.Count > messageSize)
                        {
                            GetNewMessage();
                            return;
                        }
                    }
                    GetMoreData();
                }
                else
                {
                    //checksum
                    unchecked
                    {
                        for (int i = 4; i < data.Count; i++)
                        {
                            receivedCheckSum = receivedCheckSum ^ data[i];
                        }
                    }
                    readingData.AddRange(data);
                    if (readingData.Count == messageSize)
                    {
                        if (messageCheckSum != receivedCheckSum)
                        {
                            //mensagem inválida ignora
                            GetNewMessage();
                            return;
                        }
                        MessageReceived(readingMessageTypeID, readingData.ToArray());
                        return;
                    }//invalid command
                    else if (readingData.Count > messageSize)
                    {
                        GetNewMessage();
                        return;
                    }
                    GetMoreData();
                }
            }
        }
Пример #16
0
        private static ArrayRange <RenderTreeFrame> ReadReferenceFrames(ReadOnlySpan <byte> data, string[] strings)
        {
            var result = new RenderTreeFrame[data.Length / 16];

            for (var i = 0; i < data.Length; i += 16)
            {
                var frameData = data.Slice(i, 16);

                var type = (RenderTreeFrameType)BitConverter.ToInt32(frameData.Slice(0, 4));

                // We want each frame to take up the same number of bytes, so that the
                // recipient can index into the array directly instead of having to
                // walk through it.
                // Since we can fit every frame type into 3 ints, use that as the
                // common size. For smaller frames, we add padding to expand it to
                // 12 bytes (i.e., 3 x 4-byte ints).
                // The total size then for each frame is 16 bytes (frame type, then
                // 3 other ints).
                switch (type)
                {
                case RenderTreeFrameType.Attribute:
                    var attributeName           = ReadString(frameData.Slice(4, 4), strings);
                    var attributeValue          = ReadString(frameData.Slice(8, 4), strings);
                    var attributeEventHandlerId = BitConverter.ToInt32(frameData.Slice(12, 4));
                    result[i / 16] = RenderTreeFrame.Attribute(0, attributeName, attributeValue).WithAttributeEventHandlerId(attributeEventHandlerId);
                    break;

                case RenderTreeFrameType.Component:
                    var componentSubtreeLength = BitConverter.ToInt32(frameData.Slice(4, 4));
                    var componentId            = BitConverter.ToInt32(frameData.Slice(8, 4)); // Nowhere to put this without creating a ComponentState
                    result[i / 16] = RenderTreeFrame.ChildComponent(0, componentType: null)
                                     .WithComponentSubtreeLength(componentSubtreeLength)
                                     .WithComponent(new ComponentState(Renderer, componentId, new FakeComponent(), null));
                    break;

                case RenderTreeFrameType.ComponentReferenceCapture:
                    // Client doesn't process these, skip.
                    result[i / 16] = RenderTreeFrame.ComponentReferenceCapture(0, null, 0);
                    break;

                case RenderTreeFrameType.Element:
                    var elementSubtreeLength = BitConverter.ToInt32(frameData.Slice(4, 4));
                    var elementName          = ReadString(frameData.Slice(8, 4), strings);
                    result[i / 16] = RenderTreeFrame.Element(0, elementName).WithElementSubtreeLength(elementSubtreeLength);
                    break;

                case RenderTreeFrameType.ElementReferenceCapture:
                    var referenceCaptureId = ReadString(frameData.Slice(4, 4), strings);
                    result[i / 16] = RenderTreeFrame.ElementReferenceCapture(0, null)
                                     .WithElementReferenceCaptureId(referenceCaptureId);
                    break;

                case RenderTreeFrameType.Region:
                    var regionSubtreeLength = BitConverter.ToInt32(frameData.Slice(4, 4));
                    result[i / 16] = RenderTreeFrame.Region(0).WithRegionSubtreeLength(regionSubtreeLength);
                    break;

                case RenderTreeFrameType.Text:
                    var text = ReadString(frameData.Slice(4, 4), strings);
                    result[i / 16] = RenderTreeFrame.Text(0, text);
                    break;

                case RenderTreeFrameType.Markup:
                    var markup = ReadString(frameData.Slice(4, 4), strings);
                    result[i / 16] = RenderTreeFrame.Markup(0, markup);
                    break;

                default:
                    throw new ArgumentException($"Unsupported frame type: {type}");
                }
            }

            return(new ArrayRange <RenderTreeFrame>(result, result.Length));
        }
Пример #17
0
 public static Int32 ReadInt32BE(this BinaryReader binRdr)
 {
     return(BitConverter.ToInt32(binRdr.ReadBytesRequired(sizeof(Int32)).Reverse(), 0));
 }
Пример #18
0
        private static string ReadString(ReadOnlySpan <byte> data, string[] strings)
        {
            var index = BitConverter.ToInt32(data.Slice(0, 4));

            return(index >= 0 ? strings[index] : null);
        }
Пример #19
0
        public static void Picking()
        {
            ScanCmdPacket ScanCmdPack = new ScanCmdPacket();
            ScanEchoPacket ScanEchoPack = new ScanEchoPacket();
            MachIDCmdPacket MachIDCmdPack = new MachIDCmdPacket();
            MachIDEchoPacket MachIDEchoPack = new MachIDEchoPacket();
            MachConnectCmdPacket MachConnectCmdPack = new MachConnectCmdPacket();
            MachConnectEchoPacket MachConnectEchoPack = new MachConnectEchoPacket();
            MachDataCmdPacket MachDataCmdPack = new MachDataCmdPacket();
            MachDataEchoPacket MachDataEchoPack = new MachDataEchoPacket();
            //MachConnectCmdPacket[] PassWord = new MachConnectCmdPacket[1];
            //MachDataCmdPacket[] DataBuf = new MachDataCmdPacket[1];
            MachConnectCmdPack.Password = new char[60];
            MachDataCmdPack.DataBuf = new byte[800];

            LaserPACKET LaserPack = new LaserPACKET(); //Data Package

            #region package initialize

            ScanCmdPack.ID = 0x0;
            ScanCmdPack.Sz = 0x0;
            ScanCmdPack.Cmd = 0x20;
            ScanCmdPack.Count = 0x0;
            ScanCmdPack.Sum = 0xe0;

            //   MachIDCmdPacket
            MachIDCmdPack.ID = 0x0;
            MachIDCmdPack.Sz = 0x0;
            MachIDCmdPack.Cmd = 0x21;
            MachIDCmdPack.Count = 0x0;
            MachIDCmdPack.Sum = 0xdf;

            //   MachConnectCmdPacket
            MachConnectCmdPack.ID = 1;
            MachConnectCmdPack.Sz = 0x4a;
            MachConnectCmdPack.Cmd = 0x22;
            MachConnectCmdPack.Count = 0;
            MachConnectCmdPack.DataSz = 0x42;
            MachConnectCmdPack.DataCmd0 = 0x03;
            MachConnectCmdPack.DataCmd1 = 0;
            MachConnectCmdPack.Part = 0;
            MachConnectCmdPack.ver1 = 4;
            MachConnectCmdPack.ver2 = 3;
            MachConnectCmdPack.BugFix = 7;
            MachConnectCmdPack.TypeID = 0x10;
            MachConnectCmdPack.SubTypeID = 0xa0;
            Array.Clear(MachConnectCmdPack.Password, 0x00, 60);
            for (int i = 0; i < 4; i++)
            {
                MachConnectCmdPack.Password[i] = '0';
            }
            //+ Array.ConvertAll<char, int>(MachConnectCmdPack.Password, value => Convert.ToInt32(value));
            MachConnectCmdPack.Sum = (byte)0xd0;

            //   MachDataCmdPacket
            MachDataCmdPack.ID = 1;
            MachDataCmdPack.Sz = 0x330;
            MachDataCmdPack.Cmd = 0x01;
            MachDataCmdPack.Count = 0x00;
            MachDataCmdPack.DataSz = 0x328;
            MachDataCmdPack.DataCmd0 = 0x50;
            MachDataCmdPack.DataCmd1 = 0;
            MachDataCmdPack.Part = 0;
            MachDataCmdPack.Code = 0xa000;
            MachDataCmdPack.Len = 0x320;
            //memset((char*)MachDataCmdPack.DataBuf, 0x00, sizeof(DataSent));
            Array.Clear(MachDataCmdPack.DataBuf, 0, 800);
            MachDataCmdPack.Sum = (byte)0x8d;
            Console.WriteLine(MachDataCmdPack.Sum);

            #endregion
            //PackageSetting(ref ScanCmdPack, ref MachIDCmdPack, ref MachConnectCmdPack, ref MachDataCmdPack);

            //設定本機IP位址,可用IPAddress.Any自行尋找,或直接使用IPAddress.Parse("X.X.X.X")設定
            IPAddress localAddress = IPAddress.Parse("10.1.10.210");
            IPAddress destAddress = IPAddress.Parse("10.1.10.200");
            ushort portNumber = 0x869C;
            try
            {
                localAddress = IPAddress.Parse(Form1.localIP);
                //如果為傳送端,使用IPAddress.Parse("X.X.X.X")設定
                destAddress = IPAddress.Parse(Form1.lasorIP);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetType().FullName);
                Console.WriteLine(ex.Message);
                Form1.textMessage += "\r\n" + ex.Message;
                Form1.ResetThread();
            }

            //*******************選擇是否為傳送端*******************//
            bool udpSender = true;

            //預設byte陣列數量
            int bufferSize = 512;

            //初始化物件
            UdpClient udpSocket = null; //UDP instance的宣告(類似初始化)
            byte[] sendBuffer = new byte[bufferSize], receiveBuffer = new byte[bufferSize];  //為了暫時存放序列化資料的變數
            int byteSize; //為顯示傳送出去封包大小而宣告的變數
            ushort cmdState = 0;

            List<string> mpBuffer = new List<string>(); //為一次存取所有資料的暫存變數
            long records = 0;
            

            try
            {    
                while (true)
                {
                    if(flagflag == 0)
                    {
                        break;
                    }

                    if (udpSender == false)
                    {
                        udpSocket = new UdpClient(new IPEndPoint(localAddress, portNumber));
                    }
                    else
                    {
                        udpSocket = new UdpClient(new IPEndPoint(localAddress, 0));
                    }


                    if (udpSender == true)
                    {
                        udpSocket.Connect(destAddress, portNumber);
                        Console.WriteLine("Connect() is OK...");
                    }

                    udpSocket.Client.ReceiveTimeout = 200; //等待訊息接收時間上限

                    if (udpSender == true)
                    {
                        if (cmdState == 0)
                        {
                            Console.WriteLine("Sending the first requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(ScanCmdPack.Sum);
                            bw.Write(ScanCmdPack.ID);
                            bw.Write(ScanCmdPack.Sz);
                            bw.Write(ScanCmdPack.Cmd);
                            bw.Write(ScanCmdPack.Count);
                            bw.Write(ScanCmdPack.Sum);

                            sendBuffer = stream.ToArray();
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.scan;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.scanE)
                        {
                            Console.WriteLine("Sending the second requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(ScanCmdPack.Sum);
                            bw.Write(MachIDCmdPack.ID);
                            bw.Write(MachIDCmdPack.Sz);
                            bw.Write(MachIDCmdPack.Cmd);
                            bw.Write(MachIDCmdPack.Count);
                            bw.Write(MachIDCmdPack.Sum);
                            Console.WriteLine("sfgvafgv {0}", MachIDCmdPack.Sum);

                            sendBuffer = stream.ToArray();
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.machid;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.machidE)
                        {
                            Console.WriteLine("Sending the third requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(ScanCmdPack.Sum);
                            bw.Write(MachConnectCmdPack.ID);
                            bw.Write(MachConnectCmdPack.Sz);
                            bw.Write(MachConnectCmdPack.Cmd);
                            bw.Write(MachConnectCmdPack.Count);
                            bw.Write(MachConnectCmdPack.DataSz);
                            bw.Write(MachConnectCmdPack.DataCmd0);
                            bw.Write(MachConnectCmdPack.DataCmd1);
                            bw.Write(MachConnectCmdPack.Part);
                            bw.Write(MachConnectCmdPack.ver1);
                            bw.Write(MachConnectCmdPack.ver2);
                            bw.Write(MachConnectCmdPack.BugFix);
                            bw.Write(MachConnectCmdPack.TypeID);
                            bw.Write(MachConnectCmdPack.SubTypeID);
                            //bw.Write(MachConnectCmdPack.Password);
                            bw.Write(MachConnectCmdPack.Password);
                            bw.Write(MachConnectCmdPack.Sum);

                            sendBuffer = stream.ToArray();
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.machcon;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.machconE)
                        {
                            Form1.textMessage += "\r\nPicking...";
                            Console.WriteLine("Sending the forth requested number of packets to the destination, Send()...");

                            MemoryStream stream = new MemoryStream();
                            BinaryWriter bw = new BinaryWriter(stream);
                            Console.WriteLine(MachDataCmdPack.Sum);

                            bw.Write(MachDataCmdPack.ID);
                            bw.Write(MachDataCmdPack.Sz);
                            bw.Write(MachDataCmdPack.Cmd);
                            bw.Write(MachDataCmdPack.Count);
                            bw.Write(MachDataCmdPack.DataSz);
                            bw.Write(MachDataCmdPack.DataCmd0);
                            bw.Write(MachDataCmdPack.DataCmd1);
                            bw.Write(MachDataCmdPack.Part);
                            bw.Write(MachDataCmdPack.Code);
                            bw.Write(MachDataCmdPack.Len);
                            //bw.Write(MachDataCmdPack.DataBuf);
                            bw.Write(MachDataCmdPack.DataBuf);
                            bw.Write(MachDataCmdPack.Sum);


                            sendBuffer = stream.ToArray();
                            Console.WriteLine(sendBuffer);
                            byteSize = udpSocket.Send(sendBuffer, sendBuffer.Length);
                            cmdState = (ushort)ME.machdata;

                            Console.WriteLine("Sent {0} bytes to {1}", byteSize, destAddress.ToString());
                            stream.Close();
                            udpSender = false;
                            Console.WriteLine("Change to receiving mode");
                        }

                        if (cmdState == (ushort)ME.machdataE)
                        {
                            Console.WriteLine("Receive successfully, keep receiving.");
                            cmdState = (ushort)ME.machconE;
                        }
                        udpSocket.Close();
                    }
                    else
                    {
                        IPEndPoint senderEndPoint = new IPEndPoint(localAddress, 0);
                        Console.WriteLine("Receiving datagrams in a little time...");

                        if (cmdState == (ushort)ME.scan)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);
                                cmdState = (ushort)ME.scanE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                ScanEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);//反序列化
                                Console.WriteLine("Receive ID = {0}", ScanEchoPack.ID);

                                ScanEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", ScanEchoPack.Sz);

                                ScanEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", ScanEchoPack.Cmd);

                                ScanEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", ScanEchoPack.Count);

                                ScanEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", ScanEchoPack.Sum);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = 0;
                            }
                            udpSender = true;
                        }

                        if (cmdState == (ushort)ME.machid)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);

                                cmdState = (ushort)ME.machidE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                MachIDEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive ID = {0}", MachIDEchoPack.ID);

                                MachIDEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", MachIDEchoPack.Sz);

                                MachIDEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", MachIDEchoPack.Cmd);

                                MachIDEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", MachIDEchoPack.Count);

                                MachIDEchoPack.ID0 = br.ReadByte();
                                Console.WriteLine("Receive ID0 = {0}", MachIDEchoPack.ID0);

                                MachIDEchoPack.Ver1 = br.ReadByte();
                                Console.WriteLine("Receive Ver1 = {0}", MachIDEchoPack.Ver1);

                                MachIDEchoPack.Ver2 = br.ReadByte();
                                Console.WriteLine("Receive Ver2 = {0}", MachIDEchoPack.Ver2);

                                MachIDEchoPack.BugFix = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive BugFix = {0}", MachIDEchoPack.BugFix);

                                MachIDEchoPack.TypeID = br.ReadByte();
                                Console.WriteLine("Receive TypeID = {0}", MachIDEchoPack.TypeID);

                                MachIDEchoPack.SubTypeID = br.ReadByte();
                                Console.WriteLine("Receive SubTypeID = {0}", MachIDEchoPack.SubTypeID);

                                MachIDEchoPack.UserDef = br.ReadBytes(60);
                                Console.WriteLine("Receive UserDef");

                                MachIDEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", MachIDEchoPack.Sum);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = (ushort)ME.scanE;
                            }
                            udpSender = true;
                        }

                        if (cmdState == (ushort)ME.machcon)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);
                                cmdState = (ushort)ME.machconE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                MachConnectEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive ID = {0}", MachConnectEchoPack.ID);

                                MachConnectEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", MachConnectEchoPack.Sz);

                                MachConnectEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", MachConnectEchoPack.Cmd);

                                MachConnectEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", MachConnectEchoPack.Count);

                                MachConnectEchoPack.DataSz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive DataSz = {0}", MachConnectEchoPack.DataSz);

                                MachConnectEchoPack.DataCmd0 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd0 = {0}", MachConnectEchoPack.DataCmd0);

                                MachConnectEchoPack.DataCmd1 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd1 = {0}", MachConnectEchoPack.DataCmd1);

                                MachConnectEchoPack.Part = BitConverter.ToUInt16(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Part = {0}", MachConnectEchoPack.Part);

                                MachConnectEchoPack.Security = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Security = {0}", MachConnectEchoPack.Security);

                                MachConnectEchoPack.MachID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive MachID = {0}", MachConnectEchoPack.MachID);

                                MachConnectEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", MachIDEchoPack.Sum);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = (ushort)ME.machidE;
                            }
                            udpSender = true;
                        }

                        if (cmdState == (ushort)ME.machdata)
                        {
                            try
                            {
                                receiveBuffer = udpSocket.Receive(ref senderEndPoint);
                                cmdState = (ushort)ME.machdataE;
                                Console.WriteLine("It is {0} bytes from {1}", receiveBuffer.Length, senderEndPoint.ToString());

                                MemoryStream stream = new MemoryStream(receiveBuffer);
                                BinaryReader br = new BinaryReader(stream);

                                MachDataEchoPack.ID = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive ID = {0}", MachDataEchoPack.ID);

                                MachDataEchoPack.Sz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Sz = {0}", MachDataEchoPack.Sz);

                                MachDataEchoPack.Cmd = br.ReadByte();
                                Console.WriteLine("Receive Cmd = {0}", MachDataEchoPack.Cmd);

                                MachDataEchoPack.Count = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive Count = {0}", MachDataEchoPack.Count);

                                MachDataEchoPack.DataSz = BitConverter.ToUInt16(br.ReadBytes(2), 0);
                                Console.WriteLine("Receive DataSz = {0}", MachDataEchoPack.DataSz);

                                MachDataEchoPack.DataCmd0 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd0 = {0}", MachDataEchoPack.DataCmd0);

                                MachDataEchoPack.DataCmd1 = br.ReadByte();
                                Console.WriteLine("Receive DataCmd1 = {0}", MachDataEchoPack.DataCmd1);

                                MachDataEchoPack.Part = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Part = {0}", MachDataEchoPack.Part);

                                MachDataEchoPack.Code = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Code = {0}", MachDataEchoPack.Code);

                                MachDataEchoPack.Len = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive Len = {0}", MachDataEchoPack.Len);

                                MachDataEchoPack.ActctLen = BitConverter.ToUInt32(br.ReadBytes(4), 0);
                                Console.WriteLine("Receive ActctLen = {0}", MachDataEchoPack.ActctLen);

                                MachDataEchoPack.DataBuf = br.ReadBytes(532);
                                Console.WriteLine("Receive DataBuf");

                                MachDataEchoPack.Sum = br.ReadByte();
                                Console.WriteLine("Receive Sum = {0}", MachDataEchoPack.Sum);

                                LaserPack = (LaserPACKET)ByteToStruct(MachDataEchoPack.DataBuf, typeof(LaserPACKET));
                                
                                byte start = 0;
                                if (MachDataEchoPack.DataBuf[96] == 0xFC) { start = 1; } else { start = 0; }
                                mpBuffer.Add(
                                    DateTime.Now.ToString("HH: mm:ss.ffffzzz") + "," +
                                    BitConverter.ToInt32(MachDataEchoPack.DataBuf, 100).ToString() + "," +
                                    BitConverter.ToInt32(MachDataEchoPack.DataBuf, 104).ToString() + "," +
                                    BitConverter.ToInt32(MachDataEchoPack.DataBuf, 108).ToString() + "," +
                                    BitConverter.ToDouble(MachDataEchoPack.DataBuf, 316).ToString() + "," +
                                    start.ToString()
                                    );
                                
                                Thread.Sleep(10);
                                records++;
                                if (records % 500 == 0)
                                {
                                    Form1.textMessage += "\r\nPicking...(have picked above " + records.ToString() + " records)";
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.GetType().FullName);
                                Console.WriteLine(ex.Message);
                                Form1.textMessage += "\r\n" + ex.Message;
                                cmdState = (ushort)ME.machconE;
                            }
                            udpSender = true;
                        }
                        udpSocket.Close();
                    }
                }
            }
            catch (SocketException err)
            {
                Console.WriteLine("Socket error occurred: {0}", err.Message);
                Console.WriteLine("Stack: {0}", err.StackTrace);
                Form1.textMessage += "\r\nIP or Port " + err.Message;
                Form1.ResetThread();
            }
            catch (Exception err)
            {
                Form1.textMessage += "\r\n" + err.Message;
                Form1.ResetThread();
            }
            finally
            {
                if (udpSocket != null)
                {
                    // Free up the underlying network resources
                    Console.WriteLine("Closing the socket...");
                    // udpSocket.Close();
                }
                //初始化檔案
                try
                {
                    string path = @Form1.localPath;
                    if (!Directory.Exists(Path.GetDirectoryName(path)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                    }
                    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                    TextWriter sw = new StreamWriter(fs);

                    sw.WriteLine("Time,x,y,z,Speed,Cycle Start");
                    foreach (string eachLine in mpBuffer)
                    {
                        sw.WriteLine("{0}", eachLine);
                    }
                    sw.Close();
                    Form1.textMessage += "\r\nTotal records: " + records.ToString();
                }
                catch (Exception ex)
                {
                    if (!Directory.Exists(Path.GetDirectoryName(@"C:\temp\temp.csv")))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(@"C:\temp\temp.csv"));
                    }
                    FileStream fs = new FileStream(@"C:\temp\temp.csv", FileMode.OpenOrCreate);
                    TextWriter sw = new StreamWriter(fs);

                    sw.WriteLine("Time,x,y,z,Speed,Cycle Start");
                    foreach (string eachLine in mpBuffer)
                    {
                        sw.WriteLine("{0}", eachLine);
                    }
                    sw.Close();
                    
                    Form1.textMessage += "\r\n" + ex.Message + ", 已先暫存到C:\\temp\\temp.csv";
                    Form1.textMessage += "\r\nTotal records: " + records.ToString();
                }
                
            }
        }
Пример #20
0
        private static ArrayRange <RenderTreeDiff> ReadUpdatedComponents(ReadOnlySpan <byte> data, ReadOnlySpan <byte> indexes, string[] strings)
        {
            var result = new RenderTreeDiff[indexes.Length / 4];

            for (var i = 0; i < indexes.Length; i += 4)
            {
                var index = BitConverter.ToInt32(indexes.Slice(i, 4));

                var componentId = BitConverter.ToInt32(data.Slice(index, 4));
                var editCount   = BitConverter.ToInt32(data.Slice(index + 4, 4));

                var editData = data.Slice(index + 8);
                var edits    = new RenderTreeEdit[editCount];
                for (var j = 0; j < editCount; j++)
                {
                    var type         = (RenderTreeEditType)BitConverter.ToInt32(editData.Slice(0, 4));
                    var siblingIndex = BitConverter.ToInt32(editData.Slice(4, 4));

                    // ReferenceFrameIndex and MoveToSiblingIndex share a slot, so this reads
                    // whichever one applies to the edit type
                    var referenceFrameIndex  = BitConverter.ToInt32(editData.Slice(8, 4));
                    var removedAttributeName = ReadString(editData.Slice(12, 4), strings);

                    editData = editData.Slice(16);

                    switch (type)
                    {
                    case RenderTreeEditType.UpdateText:
                        edits[j] = RenderTreeEdit.UpdateText(siblingIndex, referenceFrameIndex);
                        break;

                    case RenderTreeEditType.UpdateMarkup:
                        edits[j] = RenderTreeEdit.UpdateMarkup(siblingIndex, referenceFrameIndex);
                        break;

                    case RenderTreeEditType.SetAttribute:
                        edits[j] = RenderTreeEdit.SetAttribute(siblingIndex, referenceFrameIndex);
                        break;

                    case RenderTreeEditType.RemoveAttribute:
                        edits[j] = RenderTreeEdit.RemoveAttribute(siblingIndex, removedAttributeName);
                        break;

                    case RenderTreeEditType.PrependFrame:
                        edits[j] = RenderTreeEdit.PrependFrame(siblingIndex, referenceFrameIndex);
                        break;

                    case RenderTreeEditType.RemoveFrame:
                        edits[j] = RenderTreeEdit.RemoveFrame(siblingIndex);
                        break;

                    case RenderTreeEditType.StepIn:
                        edits[j] = RenderTreeEdit.StepIn(siblingIndex);
                        break;

                    case RenderTreeEditType.StepOut:
                        edits[j] = RenderTreeEdit.StepOut();
                        break;

                    case RenderTreeEditType.PermutationListEntry:
                        edits[j] = RenderTreeEdit.PermutationListEntry(siblingIndex, referenceFrameIndex);
                        break;

                    case RenderTreeEditType.PermutationListEnd:
                        edits[j] = RenderTreeEdit.PermutationListEnd();
                        break;

                    default:
                        throw new InvalidOperationException("Unknown edit type:" + type);
                    }
                }

                result[i / 4] = new RenderTreeDiff(componentId, ToArrayBuilderSegment(edits));
            }

            return(new ArrayRange <RenderTreeDiff>(result, result.Length));
        }
        /// <summary>
        /// Handles a read complete event.
        /// </summary>
        private ServiceResult DoReadComplete(SocketAsyncEventArgs e)
        {
            // complete operation.
            int bytesRead = e.BytesTransferred;

            lock (m_socketLock)
            {
                BufferManager.UnlockBuffer(m_receiveBuffer);
            }

            if (bytesRead == 0)
            {
                // free the empty receive buffer.
                if (m_receiveBuffer != null)
                {
                    m_bufferManager.ReturnBuffer(m_receiveBuffer, "DoReadComplete");
                    m_receiveBuffer = null;
                }

                return(ServiceResult.Good);
            }

            m_bytesReceived += bytesRead;

            // check if more data left to read.
            if (m_bytesReceived < m_bytesToReceive)
            {
                ReadNextBlock();

                return(ServiceResult.Good);
            }

            // start reading the message body.
            if (m_incomingMessageSize < 0)
            {
                m_incomingMessageSize = BitConverter.ToInt32(m_receiveBuffer, 4);

                if (m_incomingMessageSize <= 0 || m_incomingMessageSize > m_receiveBufferSize)
                {
                    Utils.Trace(
                        "BadTcpMessageTooLarge: BufferSize={0}; MessageSize={1}",
                        m_receiveBufferSize,
                        m_incomingMessageSize);

                    return(ServiceResult.Create(
                               StatusCodes.BadTcpMessageTooLarge,
                               "Messages size {1} bytes is too large for buffer of size {0}.",
                               m_receiveBufferSize,
                               m_incomingMessageSize));
                }

                // set up buffer for reading the message body.
                m_bytesToReceive = m_incomingMessageSize;

                ReadNextBlock();

                return(ServiceResult.Good);
            }

            // notify the sink.
            if (m_sink != null)
            {
                try
                {
                    // send notification (implementor responsible for freeing buffer) on success.
                    ArraySegment <byte> messageChunk = new ArraySegment <byte>(m_receiveBuffer, 0, m_incomingMessageSize);

                    // must allocate a new buffer for the next message.
                    m_receiveBuffer = null;

                    m_sink.OnMessageReceived(this, messageChunk);
                }
                catch (Exception ex)
                {
                    Utils.Trace(ex, "Unexpected error invoking OnMessageReceived callback.");
                }
            }

            // free the receive buffer.
            if (m_receiveBuffer != null)
            {
                m_bufferManager.ReturnBuffer(m_receiveBuffer, "DoReadComplete");
                m_receiveBuffer = null;
            }

            // start receiving next message.
            ReadNextMessage();

            return(ServiceResult.Good);
        }
Пример #22
0
        public async Task <TcpMessage> Receieve()
        {
            //var stream = _tcpClient.GetStream();

            //var packetLengthBytes = new byte[4];
            //if (await stream.ReadAsync(packetLengthBytes, 0, 4) != 4)
            //    throw new InvalidOperationException("Couldn't read the packet length");
            //int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            //var seqBytes = new byte[4];
            //if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
            //    throw new InvalidOperationException("Couldn't read the sequence");
            //int seq = BitConverter.ToInt32(seqBytes, 0);

            //int readBytes = 0;
            //var body = new byte[packetLength - 12];
            //int neededToRead = packetLength - 12;

            //do
            //{
            //    var bodyByte = new byte[packetLength - 12];
            //    var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);
            //    neededToRead -= availableBytes;
            //    Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
            //    readBytes += availableBytes;
            //}
            //while (readBytes != packetLength - 12);

            //var crcBytes = new byte[4];
            //if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
            //    throw new InvalidOperationException("Couldn't read the crc");
            //int checksum = BitConverter.ToInt32(crcBytes, 0);

            // packet length
            var packetLengthBytes = new byte[4];

            if (!await ReadBuffer(_stream, packetLengthBytes))
            {
                return(null);
            }

            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            // seq
            var seqBytes = new byte[4];

            if (!await ReadBuffer(_stream, seqBytes))
            {
                return(null);
            }

            int seq = BitConverter.ToInt32(seqBytes, 0);

            // body
            var bodyBytes = new byte[packetLength - 12];

            if (!await ReadBuffer(_stream, bodyBytes))
            {
                return(null);
            }

            // crc
            var crcBytes = new byte[4];

            if (!await ReadBuffer(_stream, crcBytes))
            {
                return(null);
            }

            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + bodyBytes.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(bodyBytes, 0, rv, packetLengthBytes.Length + seqBytes.Length, bodyBytes.Length);
            var crc32 = new Ionic.Crc.CRC32();

            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return(new TcpMessage(seq, bodyBytes));
        }
        public void Deserialize(BinaryReader from)
        {
            // Bezier File Format :
            //   Header ('BZR ')            | sizeof(uint)
            //   Version (1.1)              | sizeof(uint)
            //   Regular patch count        | sizeof(uint)
            //   Quad patch count           | sizeof(uint)
            //   Triangle patch count       | sizeof(uint)

            this.Header = from.ReadStructure <BezierMesh.BezierHeader>();

            byte[] expectedHeader = { Convert.ToByte(' '), Convert.ToByte('R'), Convert.ToByte('Z'), Convert.ToByte('B') };

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(expectedHeader);
            }

            if (Header.Header != BitConverter.ToInt32(expectedHeader, 0) || (Header.Version != 0x0100 && Header.Version != 0x0101))
            {
                throw new ArgumentException("Incorrect input header or unsupported file format version");
            }


            //   Part 1.  Precomputed Control Points:
            //     Regular Patches:
            //       Bezier control points        | 16 * regularPatchCount * sizeof(float3)
            //       Texture coordinates          | 16 * regularPatchCount * sizeof(float2)
            //       Normal control points        | 16 * regularPatchCount * sizeof(float3)
            _RegularBezierControlPoints = new List <Vector3>(from.ReadStructure <Vector3>(Header.RegularPatchCount * 16));
            _RegularTextureCoordinates  = new List <Vector2>(from.ReadStructure <Vector2>(Header.RegularPatchCount * 16));
            if (Header.Version == 0x0101)
            {
                // Load normals
                _RegularNormals = new List <Vector3>(from.ReadStructure <Vector3>(Header.RegularPatchCount * 16));
            }
            else
            {
                _RegularNormals = new List <Vector3>();
            }

            //     Quad Patches:
            //       Bezier control points        | 32 * quadPatchCount * sizeof(float3)
            //       Gregory control points       | 20 * quadPatchCount * sizeof(float3)
            //       Pm control points            | 24 * quadPatchCount * sizeof(float3)
            //       Texture coordinates          | 16 * quadPatchCount * sizeof(float2)
            //       Normal control points        | 16 * quadPatchCount * sizeof(float3)
            _QuadBezierControlPoints  = new List <Vector3>(from.ReadStructure <Vector3>(Header.QuadPatchCount * 32));
            _QuadGregoryControlPoints = new List <Vector3>(from.ReadStructure <Vector3>(Header.QuadPatchCount * 20));
            _QuadPmControlPoints      = new List <Vector3>(from.ReadStructure <Vector3>(Header.QuadPatchCount * 24));
            _QuadTextureCoordinates   = new List <Vector2>(from.ReadStructure <Vector2>(Header.QuadPatchCount * 16));
            if (Header.Version == 0x0101)
            {
                // Load normals
                _QuadNormals = new List <Vector3>(from.ReadStructure <Vector3>(Header.QuadPatchCount * 16));
            }
            else
            {
                _QuadNormals = new List <Vector3>();
            }

            //     Triangle Patches:
            //       Gregory control points       | 15 * trianglePatchCount * sizeof(float3)
            //       Pm control points            | 19 * trianglePatchCount * sizeof(float3)
            //       Texture coordinates          | 12 * trianglePatchCount * sizeof(float2)
            _TriGregoryControlPoints = new List <Vector3>(from.ReadStructure <Vector3>(Header.TriPatchCount * 15));
            _TriPmControlPoints      = new List <Vector3>(from.ReadStructure <Vector3>(Header.TriPatchCount * 19));
            _TriTextureCoordinates   = new List <Vector2>(from.ReadStructure <Vector2>(Header.TriPatchCount * 12));

            //   Part 2. Stencils:
            //     faceTopologyCount              | sizeof(int)
            //     primitiveSize                  | sizeof(int)
            //     Bezier Stencil                 | faceTopologyCount * 32 * m_primitiveSize * sizeof(float)
            //     Gregory Stencil                | faceTopologyCount * 20 * m_primitiveSize * sizeof(float)
            //     regularFaceTopologyIndex       | regularPatchCount * sizeof(uint)
            //     regularVertexIndices           | 16 * regularPatchCount * sizeof(uint)
            //     regularStencilIndices          | 16 * regularPatchCount * sizeof(uint)
            //     quadVertexCount                | quadPatchCount * sizeof(uint)
            //     quadFaceTopologyIndex          | quadPatchCount * sizeof(uint)
            //     quadVertexIndices              | primitiveSize * quadpatchCount * sizeof(uint)
            //     quadStecilIndices              | primitiveSize * quadPatchCount * sizeof(uint)

            FaceTopologyCount = from.ReadInt32();
            PrimitiveSize     = from.ReadInt32();

            _BezierStencil  = new List <float>(from.ReadStructure <float>(FaceTopologyCount * 32 * PrimitiveSize));
            _GregoryStencil = new List <float>(from.ReadStructure <float>(FaceTopologyCount * 20 * PrimitiveSize));

            _RegularFaceTopologyIndex = new List <int>(from.ReadStructure <int>(Header.RegularPatchCount));
            _RegularVertexIndices     = new List <int>(from.ReadStructure <int>(Header.RegularPatchCount * 16));
            _RegularStencilIndices    = new List <int>(from.ReadStructure <int>(Header.RegularPatchCount * 16));

            _QuadFaceVertexCount   = new List <int>(from.ReadStructure <int>(Header.QuadPatchCount));
            _QuadFaceTopologyIndex = new List <int>(from.ReadStructure <int>(Header.QuadPatchCount));
            _QuadVertexIndices     = new List <int>(from.ReadStructure <int>(Header.QuadPatchCount * PrimitiveSize));
            _QuadStencilIndices    = new List <int>(from.ReadStructure <int>(Header.QuadPatchCount * PrimitiveSize));

            //   Part 3. Input Mesh Topology:
            //     Vertex count                   | sizeof(uint)
            //     Vertices                       | vertexCount * sizeof(float3)
            //     Tangents/Bitangents            | vertexCount * 2 * sizeof(float3)
            //     Valences                       | vertexCount * sizeof(int)
            //     Texture coordinates            | vertexCount * sizeof(float2)
            //     Max valence                    | sizeof(uint)
            //     Regular face indices           | 4 * regularPatchCount * sizeof(uint)
            //     Quad face indices              | 4 * irregularpatchCount * sizeof(uint)
            //     Triangle face indices          | 3 * trianglePatchCount * sizeof(uint)

            VertexCount         = from.ReadInt32();
            _Vertices           = new List <Vector3>(from.ReadStructure <Vector3>(VertexCount));
            _Tangents           = new List <Vector3>(from.ReadStructure <Vector3>(VertexCount * 2));
            _Valences           = new List <int>(from.ReadStructure <int>(VertexCount));
            _TextureCoordinates = new List <Vector2>(from.ReadStructure <Vector2>(VertexCount));

            MaxValence = from.ReadInt32();

            _RegularFaceIndices = new List <int>(from.ReadStructure <int>(Header.RegularPatchCount * 4));
            _QuadFaceIndices    = new List <int>(from.ReadStructure <int>(Header.QuadPatchCount * 4));
            _TriFaceIndices     = new List <int>(from.ReadStructure <int>(Header.TriPatchCount * 3));

            #region Calculate the patch corner point indices relative to the patch

            // For each regular patch (bicubic bezier) set the indices for the
            // regular that define the face (i.e. the 4 corners)
            var regularIndices = new int[Header.RegularPatchCount * 4];
            for (int k = 0; k < Header.RegularPatchCount; k++)
            {
                for (int j = 0; j < 4; j++)
                {
                    for (int i = 0; i < 16; i++)
                    {
                        if (_RegularVertexIndices[k * 16 + i] == _RegularFaceIndices[k * 4 + j])
                        {
                            regularIndices[k * 4 + j] = i;
                        }
                    }
                }
            }

            // For an irregular patch (Gregory patch) set the indices for the
            // patch that define the face (i.e. the 4 corners)
            var quadIndices = new int[Header.QuadPatchCount * 4];
            for (int k = 0; k < Header.QuadPatchCount; k++)
            {
                for (int j = 0; j < 4; j++)
                {
                    for (int i = 0; i < PrimitiveSize; i++)
                    {
                        if (_QuadVertexIndices[k * PrimitiveSize + i] == _QuadFaceIndices[k * 4 + j])
                        {
                            quadIndices[k * 4 + j] = i;
                        }
                    }
                }
            }

            #endregion

            #region Compute input mesh indices

            var indexCount = 6 * Header.RegularPatchCount + 6 * Header.QuadPatchCount + 3 * Header.TriPatchCount;
            //var indexCount2 = 8 * Header.RegularPatchCount + 8 * Header.QuadPatchCount;

            var indices = new int[indexCount];

            int idx = 0;
            for (int i = 0; i < Header.RegularPatchCount; i++)
            {
                indices[idx++] = _RegularFaceIndices[4 * i + 2];
                indices[idx++] = _RegularFaceIndices[4 * i + 0];
                indices[idx++] = _RegularFaceIndices[4 * i + 1];

                indices[idx++] = _RegularFaceIndices[4 * i + 0];
                indices[idx++] = _RegularFaceIndices[4 * i + 2];
                indices[idx++] = _RegularFaceIndices[4 * i + 3];
            }
            for (int i = 0; i < Header.QuadPatchCount; i++)
            {
                indices[idx++] = _QuadFaceIndices[4 * i + 2];
                indices[idx++] = _QuadFaceIndices[4 * i + 0];
                indices[idx++] = _QuadFaceIndices[4 * i + 1];

                indices[idx++] = _QuadFaceIndices[4 * i + 0];
                indices[idx++] = _QuadFaceIndices[4 * i + 2];
                indices[idx++] = _QuadFaceIndices[4 * i + 3];
            }

            for (int i = 0; i < Header.TriPatchCount; i++)
            {
                indices[idx++] = _TriFaceIndices[4 * i + 2];
                indices[idx++] = _TriFaceIndices[4 * i + 0];
                indices[idx++] = _TriFaceIndices[4 * i + 1];
            }

            _Indices = new List <int>(indices);
            #endregion

            // Calculate the bounding box
            Vector3 minCorner = _Vertices[0];
            Vector3 maxCorner = _Vertices[0];

            foreach (var vertex in _Vertices)
            {
                if (minCorner.X > vertex.X)
                {
                    minCorner.X = vertex.X;
                }
                else if (maxCorner.X < vertex.X)
                {
                    maxCorner.X = vertex.X;
                }

                if (minCorner.Y > vertex.Y)
                {
                    minCorner.Y = vertex.Y;
                }
                else if (maxCorner.Y < vertex.Y)
                {
                    maxCorner.Y = vertex.Y;
                }

                if (minCorner.Z > vertex.Z)
                {
                    minCorner.Z = vertex.Z;
                }
                else if (maxCorner.Z < vertex.Z)
                {
                    maxCorner.Z = vertex.Z;
                }
            }

            Center = (minCorner + maxCorner) * 0.5f;
        }
Пример #24
0
        private void finish()
        {
            if (_z == null)
            {
                return;
            }

            if (_streamMode == StreamMode.Writer)
            {
                bool done = false;
                do
                {
                    _z.OutputBuffer      = workingBuffer;
                    _z.NextOut           = 0;
                    _z.AvailableBytesOut = _workingBuffer.Length;
                    int rc = (_wantCompress)
                        ? _z.Deflate(FlushType.Finish)
                        : _z.Inflate(FlushType.Finish);

                    if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
                    {
                        string verb = (_wantCompress ? "de" : "in") + "flating";
                        if (_z.Message == null)
                        {
                            throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc));
                        }
                        else
                        {
                            throw new ZlibException(verb + ": " + _z.Message);
                        }
                    }

                    if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
                    {
                        _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
                    }

                    done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
                    // If GZIP and de-compress, we're done when 8 bytes remain.
                    if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
                    {
                        done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
                    }
                }while (!done);

                Flush();

                // workitem 7159
                if (_flavor == ZlibStreamFlavor.GZIP)
                {
                    if (_wantCompress)
                    {
                        // Emit the GZIP trailer: CRC32 and  size mod 2^32
                        int c1 = crc.Crc32Result;
                        _stream.Write(BitConverter.GetBytes(c1), 0, 4);
                        int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF);
                        _stream.Write(BitConverter.GetBytes(c2), 0, 4);
                    }
                    else
                    {
                        throw new ZlibException("Writing with decompression is not supported.");
                    }
                }
            }
            // workitem 7159
            else if (_streamMode == StreamMode.Reader)
            {
                if (_flavor == ZlibStreamFlavor.GZIP)
                {
                    if (!_wantCompress)
                    {
                        // workitem 8501: handle edge case (decompress empty stream)
                        if (_z.TotalBytesOut == 0L)
                        {
                            return;
                        }

                        // Read and potentially verify the GZIP trailer:
                        // CRC32 and size mod 2^32
                        byte[] trailer = new byte[8];

                        // workitems 8679 & 12554
                        if (_z.AvailableBytesIn < 8)
                        {
                            // Make sure we have read to the end of the stream
                            Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn);
                            int bytesNeeded = 8 - _z.AvailableBytesIn;
                            int bytesRead   = _stream.Read(trailer,
                                                           _z.AvailableBytesIn,
                                                           bytesNeeded);
                            if (bytesNeeded != bytesRead)
                            {
                                throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.",
                                                                      _z.AvailableBytesIn + bytesRead));
                            }
                        }
                        else
                        {
                            Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length);
                        }

                        Int32 crc32_expected = BitConverter.ToInt32(trailer, 0);
                        Int32 crc32_actual   = crc.Crc32Result;
                        Int32 isize_expected = BitConverter.ToInt32(trailer, 4);
                        Int32 isize_actual   = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF);

                        if (crc32_actual != crc32_expected)
                        {
                            throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected));
                        }

                        if (isize_actual != isize_expected)
                        {
                            throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected));
                        }
                    }
                    else
                    {
                        throw new ZlibException("Reading with compression is not supported.");
                    }
                }
            }
        }
Пример #25
0
        public static string FindingDecrytKey(byte[] bytes, string TypeFile) //Ищем ключ расшифровки для файлов langdb, dlog и d3dtx
        {
            string result = null;

            byte[] decKey;

            byte[] CheckVersion = new byte[4];
            Array.Copy(bytes, 4, CheckVersion, 0, 4);

            if ((BitConverter.ToInt32(CheckVersion, 0) < 0) || (BitConverter.ToInt32(CheckVersion, 0) > 6))
            {
                for (int a = 0; a < MainMenu.gamelist.Count; a++)
                {
                    byte[] CheckVerOld = CheckVersion;           //Старый метод шифрования (Версии 2-6)
                    byte[] tempFileOld = new byte[bytes.Length]; //Временный файл для расшифровки (старый метод шифрования)
                    byte[] CheckVerNew = CheckVersion;           //Поновее метод шифрования (Версии 7-9)
                    byte[] tempFileNew = new byte[bytes.Length];

                    decKey = MainMenu.gamelist[a].key;

                    Array.Copy(bytes, 0, tempFileOld, 0, bytes.Length);
                    Array.Copy(bytes, 0, tempFileNew, 0, bytes.Length);

                    if (((BitConverter.ToInt32(CheckVerOld, 0) < 0) || BitConverter.ToInt32(CheckVerOld, 0) > 6) ||
                        (BitConverter.ToInt32(CheckVerNew, 0) < 0) || (BitConverter.ToInt32(CheckVerNew, 0) > 6))
                    {
                        Methods.meta_crypt(tempFileOld, decKey, 2, true);
                        CheckVerOld = new byte[4];
                        Array.Copy(tempFileOld, 4, CheckVerOld, 0, 4);
                        Methods.meta_crypt(tempFileNew, decKey, 7, true);
                        CheckVerNew = new byte[4];
                        Array.Copy(tempFileNew, 4, CheckVerNew, 0, 4);
                    }

                    if ((BitConverter.ToInt32(CheckVerOld, 0) > 0) && (BitConverter.ToInt32(CheckVerOld, 0) < 6))
                    {
                        Array.Copy(tempFileOld, 0, bytes, 0, bytes.Length);

                        if (TypeFile == "texture" || TypeFile == "font")
                        {
                            int TexturePosition = -1;
                            if (FindStartOfStringSomething(bytes, 4, "DDS ") > bytes.Length - 100)
                            {
                                if (TypeFile == "texture")
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                                }
                                else
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                                }


                                int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, decKey, 2);
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(decKey, 2);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 2, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            }
                        }

                        result = "Decryption key: " + MainMenu.gamelist[a].gamename + ". Blowfish type: old (versions 2-6)";
                        break;
                    }
                    else if ((BitConverter.ToInt32(CheckVerNew, 0) > 0) && (BitConverter.ToInt32(CheckVerNew, 0) < 6))
                    {
                        Array.Copy(tempFileNew, 0, bytes, 0, bytes.Length);

                        if (TypeFile == "texture" || TypeFile == "font")
                        {
                            int TexturePosition = -1;
                            if (FindStartOfStringSomething(bytes, 4, "DDS ") > bytes.Length - 100)
                            {
                                if (TypeFile == "texture")
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                                }
                                else
                                {
                                    TexturePosition = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                                }

                                int    DDSPos     = meta_find_encrypted(bytes, "DDS ", TexturePosition, decKey, 7);
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(decKey, 7);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 7, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                            }
                        }

                        result = "Decryption key: " + MainMenu.gamelist[a].gamename + ". Blowfish type: new (versions 7-9)";
                        break;
                    }
                }
            }
            else //Проверка файлов, в которых зашифрован только заголовок DDS-текстуры
            {
                try
                {
                    if (TypeFile == "texture" || TypeFile == "font")
                    {
                        int DDSstart = -1;
                        //Пока что придумал сделать авторасшифровку для одиночных текстур. Да и вроде шрифты были зашифрованы с 1 текстурой.
                        if (TypeFile == "texture")
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".d3dtx") + 6;
                        }
                        else
                        {
                            DDSstart = FindStartOfStringSomething(bytes, 4, ".tga") + 4;
                        }

                        for (int i = 0; i < MainMenu.gamelist.Count; i++)
                        {
                            int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, MainMenu.gamelist[i].key, 2);

                            if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                            {
                                byte[] tempHeader = new byte[2048];
                                if (tempHeader.Length > bytes.Length - DDSPos)
                                {
                                    tempHeader = new byte[bytes.Length - DDSPos];
                                }

                                Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(MainMenu.gamelist[i].key, 2);
                                tempHeader = decHeader.Crypt_ECB(tempHeader, 2, true);
                                Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                DDSstart = DDSPos;

                                result = "Decryption key: " + MainMenu.gamelist[i].gamename + ". Blowfish type: old (versions 2-6)";
                            }
                        }

                        if (DDSstart == -1)
                        {
                            for (int i = 0; i < MainMenu.gamelist.Count; i++)
                            {
                                int DDSPos = meta_find_encrypted(bytes, "DDS ", DDSstart, MainMenu.gamelist[i].key, 7);

                                if ((DDSPos != -1) && (DDSPos < (bytes.Length - 100)))
                                {
                                    byte[] tempHeader = new byte[2048];
                                    if (tempHeader.Length > bytes.Length - DDSPos)
                                    {
                                        tempHeader = new byte[bytes.Length - DDSPos];
                                    }

                                    Array.Copy(bytes, DDSPos, tempHeader, 0, tempHeader.Length);
                                    BlowFishCS.BlowFish decHeader = new BlowFishCS.BlowFish(MainMenu.gamelist[i].key, 7);
                                    tempHeader = decHeader.Crypt_ECB(tempHeader, 7, true);
                                    Array.Copy(tempHeader, 0, bytes, DDSPos, tempHeader.Length);
                                    DDSstart = DDSPos;

                                    result = "Decryption key: " + MainMenu.gamelist[i].gamename + ". Blowfish type: new (versions 7-9)";
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = "Error " + ex.Message;
                }
            }

            return(result);
        }
Пример #26
0
        // </Snippet5>
        #endregion

        #region Snippet6 - DecryptFile
        // <Snippet6>
        private void DecryptFile(string inFile)
        {
            // Create instance of Rijndael for
            // symetric decryption of the data.
            RijndaelManaged rjndl = new RijndaelManaged();

            rjndl.KeySize   = 256;
            rjndl.BlockSize = 256;
            rjndl.Mode      = CipherMode.CBC;

            // Create byte arrays to get the length of
            // the encrypted key and IV.
            // These values were stored as 4 bytes each
            // at the beginning of the encrypted package.
            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            // Consruct the file name for the decrypted file.
            string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

            // Use FileStream objects to read the encrypted
            // file (inFs) and save the decrypted file (outFs).
            using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open))
            {
                inFs.Seek(0, SeekOrigin.Begin);
                inFs.Seek(0, SeekOrigin.Begin);
                inFs.Read(LenK, 0, 3);
                inFs.Seek(4, SeekOrigin.Begin);
                inFs.Read(LenIV, 0, 3);

                // Convert the lengths to integer values.
                int lenK  = BitConverter.ToInt32(LenK, 0);
                int lenIV = BitConverter.ToInt32(LenIV, 0);

                // Determine the start postition of
                // the ciphter text (startC)
                // and its length(lenC).
                int startC = lenK + lenIV + 8;
                int lenC   = (int)inFs.Length - startC;

                // Create the byte arrays for
                // the encrypted Rijndael key,
                // the IV, and the cipher text.
                byte[] KeyEncrypted = new byte[lenK];
                byte[] IV           = new byte[lenIV];

                // Extract the key and IV
                // starting from index 8
                // after the length values.
                inFs.Seek(8, SeekOrigin.Begin);
                inFs.Read(KeyEncrypted, 0, lenK);
                inFs.Seek(8 + lenK, SeekOrigin.Begin);
                inFs.Read(IV, 0, lenIV);
                Directory.CreateDirectory(DecrFolder);
                //<Snippet10>
                // Use RSACryptoServiceProvider
                // to decrypt the Rijndael key.
                byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

                // Decrypt the key.
                ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);
                //</Snippet10>

                // Decrypt the cipher text from
                // from the FileSteam of the encrypted
                // file (inFs) into the FileStream
                // for the decrypted file (outFs).
                using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                {
                    int count  = 0;
                    int offset = 0;

                    // blockSizeBytes can be any arbitrary size.
                    int    blockSizeBytes = rjndl.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];

                    // By decrypting a chunk a time,
                    // you can save memory and
                    // accommodate large files.

                    // Start at the beginning
                    // of the cipher text.
                    inFs.Seek(startC, SeekOrigin.Begin);
                    using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                    {
                        do
                        {
                            count   = inFs.Read(data, 0, blockSizeBytes);
                            offset += count;
                            outStreamDecrypted.Write(data, 0, count);
                        }while (count > 0);

                        outStreamDecrypted.FlushFinalBlock();
                        outStreamDecrypted.Close();
                    }
                    outFs.Close();
                }
                inFs.Close();
            }
        }
Пример #27
0
        public static TLDecryptedMessageBase DecryptMessage(TLString data, TLEncryptedChat chat, out bool commitChat)
        {
            commitChat = false;

            var bytes = data.Data;

            var keyFingerprint           = BitConverter.ToInt64(bytes, 0);
            var msgKey                   = bytes.SubArray(8, 16);
            var key                      = chat.Key.Data;
            var keyHash                  = Utils.ComputeSHA1(key);
            var calculatedKeyFingerprint = BitConverter.ToInt64(keyHash, keyHash.Length - 8);

            if (keyFingerprint != calculatedKeyFingerprint)
            {
                var chat20 = chat as TLEncryptedChat20;
                if (chat20 != null && chat20.PFS_Key != null)
                {
                    var pfsKeyHash        = Utils.ComputeSHA1(chat20.PFS_Key.Data);
                    var pfsKeyFingerprint = BitConverter.ToInt64(pfsKeyHash, pfsKeyHash.Length - 8);
                    if (pfsKeyFingerprint == keyFingerprint)
                    {
                        chat20.Key                = chat20.PFS_Key;
                        chat20.PFS_Key            = null;
                        chat20.PFS_KeyFingerprint = null;
                        chat20.PFS_A              = null;
                        chat20.PFS_ExchangeId     = null;
                        commitChat                = true;
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }

            var x      = 0;
            var sha1_a = Utils.ComputeSHA1(Combine(msgKey, key.SubArray(x, 32)));
            var sha1_b = Utils.ComputeSHA1(Combine(key.SubArray(32 + x, 16), msgKey, key.SubArray(48 + x, 16)));
            var sha1_c = Utils.ComputeSHA1(Combine(key.SubArray(64 + x, 32), msgKey));
            var sha1_d = Utils.ComputeSHA1(Combine(msgKey, key.SubArray(96 + x, 32)));

            var aesKey = Combine(sha1_a.SubArray(0, 8), sha1_b.SubArray(8, 12), sha1_c.SubArray(4, 12));
            var aesIV  = Combine(sha1_a.SubArray(8, 12), sha1_b.SubArray(0, 8), sha1_c.SubArray(16, 4), sha1_d.SubArray(0, 8));

            var encryptedBytes = bytes.SubArray(24, bytes.Length - 24);
            var decryptedBytes = Utils.AesIge(encryptedBytes, aesKey, aesIV, false);

            var length = BitConverter.ToInt32(decryptedBytes, 0);

            if (length <= 0 || (4 + length) > decryptedBytes.Length)
            {
                return(null);
            }

            var calculatedMsgKey = Utils.ComputeSHA1(decryptedBytes.SubArray(0, 4 + length));

            for (var i = 0; i < 16; i++)
            {
                if (msgKey[i] != calculatedMsgKey[i + 4])
                {
                    return(null);
                }
            }

            var position                            = 4;
            var decryptedObject                     = TLObject.GetObject <TLObject>(decryptedBytes, ref position);
            var decryptedMessageLayer               = decryptedObject as TLDecryptedMessageLayer;
            var decryptedMessageLayer17             = decryptedObject as TLDecryptedMessageLayer17;
            TLDecryptedMessageBase decryptedMessage = null;

            if (decryptedMessageLayer17 != null)
            {
                decryptedMessage = decryptedMessageLayer17.Message;
                var decryptedMessage17 = decryptedMessage as ISeqNo;
                if (decryptedMessage17 != null)
                {
                    decryptedMessage17.InSeqNo  = decryptedMessageLayer17.InSeqNo;
                    decryptedMessage17.OutSeqNo = decryptedMessageLayer17.OutSeqNo;
                }
            }
            else if (decryptedMessageLayer != null)
            {
                decryptedMessage = decryptedMessageLayer.Message;
            }
            else if (decryptedObject is TLDecryptedMessageBase)
            {
                decryptedMessage = (TLDecryptedMessageBase)decryptedObject;
            }

            return(decryptedMessage);
        }
Пример #28
0
 /// <inheritdoc />
 public override int Next()
 {
     _rng.GetBytes(_uint32Buffer);
     return(BitConverter.ToInt32(_uint32Buffer, 0) & 0x7FFFFFFF);
 }
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void WriteFloat(float v)
 {
     WriteInt(BitConverter.ToInt32(BitConverter.GetBytes(v), 0));
 }
Пример #30
0
        internal object GetValue(IFormatProvider formatProvider, OracleConnection conn)
        {
            object tmp;

            byte [] buffer = null;

            switch (DataType)
            {
            case OciDataType.VarChar2:
            case OciDataType.String:
            case OciDataType.VarChar:
            case OciDataType.Char:
            case OciDataType.CharZ:
            case OciDataType.OciString:
            case OciDataType.RowIdDescriptor:
                buffer = new byte [Size];
                Marshal.Copy(Value, buffer, 0, Size);

                // Get length of returned string
                int rsize = 0;
                //IntPtr	env = Parent.Parent;	// Parent is statement, grandparent is environment
                IntPtr env    = conn.Environment;
                int    status = OciCalls.OCICharSetToUnicode(env, null, buffer, out rsize);
                OciErrorHandle.ThrowExceptionIfError(ErrorHandle, status);

                // Get string
                StringBuilder ret = new StringBuilder(rsize);
                status = OciCalls.OCICharSetToUnicode(env, ret, buffer, out rsize);
                OciErrorHandle.ThrowExceptionIfError(ErrorHandle, status);

                return(ret.ToString());

            case OciDataType.LongVarChar:
            case OciDataType.Long:
                buffer = new byte [LongVarCharMaxValue];
                Marshal.Copy(Value, buffer, 0, buffer.Length);

                int longSize = 0;
                if (BitConverter.IsLittleEndian)
                {
                    longSize = BitConverter.ToInt32(new byte[] { buffer[0], buffer[1], buffer[2], buffer[3] }, 0);
                }
                else
                {
                    longSize = BitConverter.ToInt32(new byte[] { buffer[3], buffer[2], buffer[1], buffer[0] }, 0);
                }

                ASCIIEncoding encoding = new ASCIIEncoding();
                string        e        = encoding.GetString(buffer, 4, longSize);
                return(e);

            case OciDataType.Integer:
            case OciDataType.Number:
            case OciDataType.Float:
            case OciDataType.VarNum:
            case OciDataType.UnsignedInt:
                tmp = Marshal.PtrToStringAnsi(Value, Size);
                if (tmp != null)
                {
                    return(Decimal.Parse(tmp.ToString(), formatProvider));
                }
                break;

            case OciDataType.TimeStamp:
                return(dateTimeDesc.GetDateTime(conn.Environment, dateTimeDesc.ErrorHandle));

            case OciDataType.Date:
                return(UnpackDate());

            case OciDataType.Raw:
            case OciDataType.VarRaw:
                byte [] raw_buffer = new byte [Size];
                Marshal.Copy(Value, raw_buffer, 0, Size);
                return(raw_buffer);

            case OciDataType.LongRaw:
            case OciDataType.LongVarRaw:
                buffer = new byte [LongVarRawMaxValue];
                Marshal.Copy(Value, buffer, 0, buffer.Length);

                int longrawSize = 0;
                if (BitConverter.IsLittleEndian)
                {
                    longrawSize = BitConverter.ToInt32(new byte[] { buffer[0], buffer[1], buffer[2], buffer[3] }, 0);
                }
                else
                {
                    longrawSize = BitConverter.ToInt32(new byte[] { buffer[3], buffer[2], buffer[1], buffer[0] }, 0);
                }

                byte[] longraw_buffer = new byte [longrawSize];
                Array.ConstrainedCopy(buffer, 4, longraw_buffer, 0, longrawSize);
                return(longraw_buffer);

            case OciDataType.Blob:
            case OciDataType.Clob:
                return(GetOracleLob());

            case OciDataType.IntervalDayToSecond:
                return(new OracleTimeSpan(intervalDesc.GetDayToSecond(conn.Environment, intervalDesc.ErrorHandle)));

            case OciDataType.IntervalYearToMonth:
                return(new OracleMonthSpan(intervalDesc.GetYearToMonth(conn.Environment, intervalDesc.ErrorHandle)));

            default:
                throw new Exception("OciDataType not implemented: " + DataType.ToString());
            }

            return(DBNull.Value);
        }