RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
    {
        var pRenderModel = System.IntPtr.Zero;

        EVRRenderModelError error;

        while (true)
        {
            error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
            if (error != EVRRenderModelError.Loading)
            {
                break;
            }
#if UNITY_STANDALONE
            System.Threading.Thread.Sleep(1);
#endif
        }

        if (error != EVRRenderModelError.None)
        {
            Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
            return(null);
        }

        var renderModel = MarshalRenderModel(pRenderModel);

        var vertices = new Vector3[renderModel.unVertexCount];
        var normals  = new Vector3[renderModel.unVertexCount];
        var uv       = new Vector2[renderModel.unVertexCount];

        var type = typeof(RenderModel_Vertex_t);
        for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
        {
            var ptr  = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
            var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

            vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
            normals[iVert]  = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
            uv[iVert]       = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
        }

        int indexCount = (int)renderModel.unTriangleCount * 3;
        var indices    = new short[indexCount];
        Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

        var triangles = new int[indexCount];
        for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
        {
            triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
            triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
            triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
        }

        var mesh = new Mesh();
        mesh.vertices  = vertices;
        mesh.normals   = normals;
        mesh.uv        = uv;
        mesh.triangles = triangles;

#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
        mesh.Optimize();
#endif
        //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

        // Check cache before loading texture.
        var material = materials[renderModel.diffuseTextureId] as Material;
        if (material == null || material.mainTexture == null)
        {
            var pDiffuseTexture = System.IntPtr.Zero;

            while (true)
            {
                error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                if (error != EVRRenderModelError.Loading)
                {
                    break;
                }
#if UNITY_STANDALONE
                System.Threading.Thread.Sleep(1);
#endif
            }

            if (error == EVRRenderModelError.None)
            {
                var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
                var texture        = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.ARGB32, false);
                if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
                {
                    texture.Apply();

                    while (true)
                    {
                        error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texture.GetNativeTexturePtr());
                        if (error != EVRRenderModelError.Loading)
                        {
                            break;
                        }
#if UNITY_STANDALONE
                        System.Threading.Thread.Sleep(1);
#endif
                    }
                }
                else
                {
                    var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4];                     // RGBA
                    Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

                    var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
                    int iColor = 0;
                    for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
                    {
                        for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
                        {
                            var r = textureMapData[iColor++];
                            var g = textureMapData[iColor++];
                            var b = textureMapData[iColor++];
                            var a = textureMapData[iColor++];
                            colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                        }
                    }

                    texture.SetPixels32(colors);
                    texture.Apply();
                }

                material             = new Material(shader != null ? shader : Shader.Find("Standard"));
                material.mainTexture = texture;
                //material.hideFlags = HideFlags.DontUnloadUnusedAsset;

                materials[renderModel.diffuseTextureId] = material;

                renderModels.FreeTexture(pDiffuseTexture);
            }
            else
            {
                Debug.Log("Failed to load render model texture for render model " + renderModelName);
            }
        }

        // Delay freeing when we can since we'll often get multiple requests for the same model right
        // after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
        if (!Application.isPlaying)
        {
            renderModels.FreeRenderModel(pRenderModel);
        }
        else
#endif
        StartCoroutine(FreeRenderModel(pRenderModel));

        return(new RenderModel(mesh, material));
    }
示例#2
0
 public void CopyTo_NullSource_ThrowsArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("source", () => Marshal.Copy((short[])null, 0, new IntPtr(1), 0));
     AssertExtensions.Throws <ArgumentNullException>("source", () => Marshal.Copy(IntPtr.Zero, new short[10], 0, 0));
 }
        private byte[] DecryptBlob(byte[] dwData)
        {
            if (hKey == null && hAlg == null)
            {
                return(ProtectedData.Unprotect(dwData, null, DataProtectionScope.CurrentUser));
            }
            byte[] dwDataOut = null;
            // magic decryption happens here
            BCrypt.BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
            int dwDataOutLen;
            //IntPtr pDataOut = IntPtr.Zero;
            IntPtr pData = IntPtr.Zero;
            uint   ntStatus;

            byte[] subArrayNoV10;
            int    pcbResult = 0;

            unsafe
            {
                if (ByteArrayEquals(dwData, 0, DPAPI_CHROME_UNKV10, 0, 3))
                {
                    subArrayNoV10 = new byte[dwData.Length - DPAPI_CHROME_UNKV10.Length];
                    Array.Copy(dwData, 3, subArrayNoV10, 0, dwData.Length - DPAPI_CHROME_UNKV10.Length);
                    pData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * dwData.Length);
                    //byte[] shiftedEncVal = new byte[dwData.Length - 3];
                    //Array.Copy(dwData, 3, shiftedEncVal, 0, dwData.Length - 3);
                    //IntPtr shiftedEncValPtr = IntPtr.Zero;
                    try
                    {
                        //shiftedEncValPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * shiftedEncVal.Length);
                        Marshal.Copy(dwData, 0, pData, dwData.Length);
                        Utils.MiscUtils.BCRYPT_INIT_AUTH_MODE_INFO(out info);
                        info.pbNonce = (byte *)(pData + DPAPI_CHROME_UNKV10.Length);
                        info.cbNonce = 12;
                        info.pbTag   = info.pbNonce + dwData.Length - (DPAPI_CHROME_UNKV10.Length + AES_BLOCK_SIZE); // AES_BLOCK_SIZE = 16
                        info.cbTag   = AES_BLOCK_SIZE;                                                               // AES_BLOCK_SIZE = 16
                        dwDataOutLen = dwData.Length - DPAPI_CHROME_UNKV10.Length - info.cbNonce - info.cbTag;
                        dwDataOut    = new byte[dwDataOutLen];

                        fixed(byte *pDataOut = dwDataOut)
                        {
                            ntStatus = BCrypt.BCryptDecrypt(hKey, info.pbNonce + info.cbNonce, dwDataOutLen, (void *)&info, null, 0, pDataOut, dwDataOutLen, out pcbResult, 0);
                        }
                        if (NT_SUCCESS(ntStatus))
                        {
                            //Console.WriteLine("{0} : {1}", dwDataOutLen, pDataOut);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        if (pData != null && pData != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(pData);
                        }
                        //if (pDataOut != null && pDataOut != IntPtr.Zero)
                        //    Marshal.FreeHGlobal(pDataOut);
                        //if (pInfo != null && pInfo != IntPtr.Zero)
                        //    Marshal.FreeHGlobal(pDataOut);
                    }
                }
            }
            return(dwDataOut);
        }
示例#4
0
        static public void Fill(Bitmap bmp, Point pt, Color pointColor, Color replaceColor)
        {
            BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            int[] bits = new int[data.Stride / 4 * data.Height];
            Marshal.Copy(data.Scan0, bits, 0, bits.Length);
            int           x = pt.X, y = pt.Y;
            Stack <Point> check = new Stack <Point>();
            int           To    = replaceColor.ToArgb();
            int           From  = bits[x + y * data.Stride / 4];

            bits[x + y * data.Stride / 4] = To;
            if (To != From)
            {
                Bitmap     tempBmp  = new Bitmap(bmp.Width, bmp.Height);
                BitmapData tempdata = tempBmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                int[]      tempbits = new int[tempdata.Stride / 4 * tempdata.Height];
                Marshal.Copy(tempdata.Scan0, tempbits, 0, tempbits.Length);
                check.Push(new Point(x, y));
                while (check.Count > 0)
                {
                    Point cur  = check.Pop();
                    Point next = new Point(cur.X, cur.Y - 1);
                    foreach (Point off in new Point[] {
                        new Point(0, -1), new Point(0, 1),
                        new Point(-1, 0), new Point(1, 0)
                    })
                    {
                        next = new Point(cur.X + off.X, cur.Y + off.Y);
                        if (next.X >= 0 && next.Y >= 0 && next.X < data.Width && next.Y < data.Height)
                        {
                            if (bits[next.X + next.Y * data.Stride / 4] == From)
                            {
                                check.Push(next);
                            }
                            bits[next.X + next.Y * data.Stride / 4]     = To;
                            tempbits[next.X + next.Y * data.Stride / 4] = To;
                        }
                    }
                }
                Marshal.Copy(tempbits, 0, tempdata.Scan0, tempbits.Length);
                bmp.UnlockBits(data);
                tempBmp.UnlockBits(tempdata);
                Graphics gra = Graphics.FromImage(bmp);
                gra.SmoothingMode   = SmoothingMode.AntiAlias;
                gra.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                gra.SmoothingMode   = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                gra.DrawImage(tempBmp, 0, 0, bmp.Width, bmp.Height);
            }
            else
            {
                Bitmap     tempbmp  = new Bitmap(bmp.Width, bmp.Height);
                BitmapData tempdata = tempbmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                int[]      tempbits = new int[tempdata.Stride / 4 * tempdata.Height];
                Marshal.Copy(tempdata.Scan0, tempbits, 0, tempbits.Length);
                check.Push(new Point(x, y));
                while (check.Count > 0)
                {
                    Point cur  = check.Pop();
                    Point next = new Point(cur.X, cur.Y - 1);
                    foreach (Point off in new Point[] {
                        new Point(0, -1), new Point(0, 1),
                        new Point(-1, 0), new Point(1, 0)
                    })
                    {
                        next = new Point(cur.X + off.X, cur.Y + off.Y);
                        if (next.X >= 0 && next.Y >= 0 &&
                            next.X < data.Width &&
                            next.Y < data.Height)
                        {
                            if (bits[next.X + next.Y * data.Stride / 4] == From)
                            {
                                check.Push(next);
                                bits[next.X + next.Y * data.Stride / 4]     = Color.Transparent.ToArgb();
                                tempbits[next.X + next.Y * data.Stride / 4] = To;
                            }
                        }
                    }
                }
                Marshal.Copy(tempbits, 0, tempdata.Scan0, tempbits.Length);
                bmp.UnlockBits(data);
                tempbmp.UnlockBits(tempdata);
                Graphics gra = Graphics.FromImage(bmp);
                gra.SmoothingMode   = SmoothingMode.AntiAlias;
                gra.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                gra.SmoothingMode   = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                gra.DrawImage(tempbmp, 0, 0, bmp.Width, bmp.Height);
            }
        }
示例#5
0
        private void TimerOnElapsed(object sender, EventArgs eventArgs)
        {
            IntPtr pData = IntPtr.Zero;

            //read in CHRocodile data
            while (true)
            {
                var res = TCHRDLLFunctionWrapper.GetNextSample(_deviceHandle, ref pData, out var sigNumber);

                if (res > 0)
                {
                    //display data
                    Marshal.Copy(pData, _oneSampleData, 0, sigNumber);

                    if (sigNumber > 0)
                    {
                        for (int i = 0; i < sigNumber; i++)
                        {
                            _sampleBuffers[i][_currentDataPos] = _oneSampleData[i];
                        }
                        _currentDataPos++;
                        if (_currentDataPos >= _dataLength)
                        {
                            _currentDataPos = 0;
                        }
                    }
                }
                else
                {
                    if (res < 0)
                    {
                        TCHRDLLFunctionWrapper.FlushInputBuffer(_deviceHandle);
                    }
                    break;
                }
            }

            // Convert to dictionary
            var curvesDict = new Dictionary <string, double[]>();

            for (int i = 0; i < _signalNames.Length; i++)
            {
                curvesDict[_signalNames[i]] = _sampleBuffers[i];
            }

            OnCurvesUpdated(curvesDict);

            //download spectrum
            int SpecType = TCHRDLLFunctionWrapper.Raw_Spectrum;

            if (TCHRDLLFunctionWrapper.DownloadDeviceSpectrum(_deviceHandle, SpecType, ref pData, out var signalCount) == 0)
            {
                if (signalCount > _dataLength)
                {
                    signalCount = _dataLength;
                }
                Marshal.Copy(pData, _specData, 0, signalCount);
                // Assign 0s to unassigned entries
                for (int i = signalCount; i < _dataLength; i++)
                {
                    _specData[i] = 0;
                }

                OnSpectrumDataUpdated(_specData);
            }
        }
示例#6
0
 public static int[] ToIntsArray(this IntPtr ptr, int size)
 {
     int[] result = new int[size];
     Marshal.Copy(ptr, result, 0, size);
     return(result);
 }
示例#7
0
        /// <summary>
        /// Execute a second pass through the brush
        /// </summary>
        /// <param name="sourceData">The source brush, locked into memory</param>
        /// <param name="output">The output brush</param>
        /// <param name="x">The x in pixels of the image</param>
        /// <param name="height">The height in pixels of the image</param>
        /// <param name="bounds">The bounding rectangle</param>
        /// <param name="stride"></param>
        protected virtual void SecondPass(byte[] sourceData, Bitmap output, int width, int height, Rectangle bounds, int stride)
        {
            BitmapData outputLock = null;

            try
            {
                // Lock the output brush into memory
                outputLock = output.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                byte[] outputData = new byte[outputLock.Stride * output.Height];

                // Define the source data pointers. The source row is a byte to
                // keep addition of the stride value easier (as this is in bytes)
                //IntPtr pSourceRow = sourceData.Scan0;
                //IntPtr pSourcePixel = pSourceRow;
                //IntPtr pPreviousPixel = pSourcePixel;
                int srcRow       = 0;
                int srcPixel     = 0;
                int srcPrevPixel = 0;

                // Now define the destination data pointers
                //IntPtr pDestinationRow = outputLock.Scan0;
                //IntPtr pDestinationPixel = pDestinationRow;
                int dstRow   = 0;
                int dstPixel = 0;

                // And convert the first pixel, so that I have values going into the loop

                byte pixelValue = QuantizePixel(new Color32(sourceData, srcPixel));

                // Assign the value of the first pixel
                //Marshal.WriteByte(pDestinationPixel, pixelValue);
                outputData[dstPixel] = pixelValue;

                // Loop through each row
                for (int row = 0; row < height; row++)
                {
                    // Set the source pixel to the first pixel in this row
                    //pSourcePixel = pSourceRow;
                    srcPixel = srcRow;

                    // And set the destination pixel pointer to the first pixel in the row
                    //pDestinationPixel = pDestinationRow;
                    dstPixel = dstRow;

                    // Loop through each pixel on this scan line
                    for (int col = 0; col < width; col++)
                    {
                        // Check if this is the same as the last pixel. If so use that value
                        // rather than calculating it again. This is an inexpensive optimisation.
                        //if (Marshal.ReadByte(pPreviousPixel) != Marshal.ReadByte(pSourcePixel))
                        //{
                        // Quantize the pixel
                        pixelValue = QuantizePixel(new Color32(sourceData, srcPixel));

                        // And setup the previous pointer
                        //pPreviousPixel = pSourcePixel;
                        srcPrevPixel = srcPixel;
                        //}

                        // And set the pixel in the output
                        //Marshal.WriteByte(pDestinationPixel, pixelValue);
                        outputData[dstPixel] = pixelValue;

                        //pSourcePixel = (IntPtr)((long)pSourcePixel + _pixelSize);
                        srcPixel += _pixelSize;
                        //pDestinationPixel = (IntPtr)((long)pDestinationPixel + 1);
                        dstPixel++;
                    }

                    // Add the stride to the source row
                    //pSourceRow = (IntPtr)((long)pSourceRow + sourceData.Stride);
                    srcRow += stride;

                    // And to the destination row
                    //pDestinationRow = (IntPtr)((long)pDestinationRow + outputLock.Stride);
                    dstRow += outputLock.Stride;
                }
                Marshal.Copy(outputData, 0, outputLock.Scan0, outputData.Length);
            }
            finally
            {
                // Ensure that I unlock the output bits
                output.UnlockBits(outputLock);
            }
        }
示例#8
0
文件: FileIndex.cs 项目: roxya/Razor
        public FileIndex(string idxFile, string mulFile, string uopFile, int length, int file, string uopEntryExtension,
                         int idxLength, bool hasExtra)
        {
            Index = new Entry3D[length];

            string idxPath = null;

            MulPath = null;
            string uopPath = null;

            if (Files.MulPath == null)
            {
                Files.LoadMulPath();
            }

            if (Files.MulPath.Count > 0)
            {
                idxPath = Files.MulPath[idxFile.ToLower()];
                MulPath = Files.MulPath[mulFile.ToLower()];

                if (!String.IsNullOrEmpty(uopFile) && Files.MulPath.ContainsKey(uopFile.ToLower()))
                {
                    uopPath = Files.MulPath[uopFile.ToLower()];
                }

                if (String.IsNullOrEmpty(idxPath))
                {
                    idxPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(idxPath)))
                    {
                        idxPath = Path.Combine(Files.RootDir, idxPath);
                    }

                    if (!File.Exists(idxPath))
                    {
                        idxPath = null;
                    }
                }

                if (String.IsNullOrEmpty(MulPath))
                {
                    MulPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(MulPath)))
                    {
                        MulPath = Path.Combine(Files.RootDir, MulPath);
                    }

                    if (!File.Exists(MulPath))
                    {
                        MulPath = null;
                    }
                }

                if (String.IsNullOrEmpty(uopPath))
                {
                    uopPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(uopPath)))
                    {
                        uopPath = Path.Combine(Files.RootDir, uopPath);
                    }

                    if (!File.Exists(uopPath))
                    {
                        uopPath = null;
                    }
                    else
                    {
                        MulPath = uopPath;
                    }
                }
            }

            /* UOP files support code, written by Wyatt (c) www.ruosi.org
             * idxLength variable was added for compatibility with legacy code for art (see art.cs)
             * At the moment the only UOP file having entries with extra field is gumpartlegacy.uop,
             * and it's two dwords in the beginning of the entry.
             * It's possible that UOP can include some entries with unknown hash: not really unknown for me, but
             * not useful for reading legacy entries. That's why i removed unknown hash exception throwing from this code
             */
            if (MulPath != null && MulPath.EndsWith(".uop"))
            {
                using (FileStream index = new FileStream(MulPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Stream = new FileStream(MulPath, FileMode.Open, FileAccess.Read, FileShare.Read);

                    FileInfo fi         = new FileInfo(MulPath);
                    string   uopPattern = fi.Name.Replace(fi.Extension, "").ToLowerInvariant();

                    using (BinaryReader br = new BinaryReader(Stream))
                    {
                        br.BaseStream.Seek(0, SeekOrigin.Begin);

                        if (br.ReadInt32() != 0x50594D)
                        {
                            throw new ArgumentException("Bad UOP file.");
                        }

                        br.ReadInt64(); // version + signature
                        long nextBlock = br.ReadInt64();
                        br.ReadInt32(); // block capacity
                        int count = br.ReadInt32();

                        if (idxLength > 0)
                        {
                            IdxLength = idxLength * 12;
                        }

                        Dictionary <ulong, int> hashes = new Dictionary <ulong, int>();

                        for (int i = 0; i < length; i++)
                        {
                            string entryName = string.Format("build/{0}/{1:D8}{2}", uopPattern, i, uopEntryExtension);
                            ulong  hash      = HashFileName(entryName);

                            if (!hashes.ContainsKey(hash))
                            {
                                hashes.Add(hash, i);
                            }
                        }

                        br.BaseStream.Seek(nextBlock, SeekOrigin.Begin);

                        do
                        {
                            int filesCount = br.ReadInt32();
                            nextBlock = br.ReadInt64();

                            for (int i = 0; i < filesCount; i++)
                            {
                                long  offset             = br.ReadInt64();
                                int   headerLength       = br.ReadInt32();
                                int   compressedLength   = br.ReadInt32();
                                int   decompressedLength = br.ReadInt32();
                                ulong hash = br.ReadUInt64();
                                br.ReadUInt32(); // Adler32
                                short flag = br.ReadInt16();

                                int entryLength = flag == 1 ? compressedLength : decompressedLength;

                                if (offset == 0)
                                {
                                    continue;
                                }

                                int idx;
                                if (hashes.TryGetValue(hash, out idx))
                                {
                                    if (idx < 0 || idx > Index.Length)
                                    {
                                        throw new IndexOutOfRangeException(
                                                  "hashes dictionary and files collection have different count of entries!");
                                    }

                                    Index[idx].lookup = (int)(offset + headerLength);
                                    Index[idx].length = entryLength;

                                    if (hasExtra)
                                    {
                                        long curPos = br.BaseStream.Position;

                                        br.BaseStream.Seek(offset + headerLength, SeekOrigin.Begin);

                                        byte[] extra = br.ReadBytes(8);

                                        short extra1 =
                                            (short)((extra[3] << 24) | (extra[2] << 16) | (extra[1] << 8) | extra[0]);
                                        short extra2 =
                                            (short)((extra[7] << 24) | (extra[6] << 16) | (extra[5] << 8) | extra[4]);

                                        Index[idx].lookup += 8;
                                        Index[idx].extra   = extra1 << 16 | extra2;

                                        br.BaseStream.Seek(curPos, SeekOrigin.Begin);
                                    }
                                }
                            }
                        } while (br.BaseStream.Seek(nextBlock, SeekOrigin.Begin) != 0);
                    }
                }
            }
            else if ((idxPath != null) && (MulPath != null))
            {
                using (FileStream index = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Stream = new FileStream(MulPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    int count = (int)(index.Length / 12);
                    IdxLength = index.Length;
                    GCHandle gc     = GCHandle.Alloc(Index, GCHandleType.Pinned);
                    byte[]   buffer = new byte[index.Length];
                    index.Read(buffer, 0, (int)index.Length);
                    Marshal.Copy(buffer, 0, gc.AddrOfPinnedObject(), (int)Math.Min(IdxLength, length * 12));
                    gc.Free();
                    for (int i = count; i < length; ++i)
                    {
                        Index[i].lookup = -1;
                        Index[i].length = -1;
                        Index[i].extra  = -1;
                    }
                }
            }
            else
            {
                Stream = null;
                return;
            }

            Entry5D[] patches = Verdata.Patches;

            if (file > -1)
            {
                for (int i = 0; i < patches.Length; ++i)
                {
                    Entry5D patch = patches[i];

                    if (patch.file == file && patch.index >= 0 && patch.index < length)
                    {
                        Index[patch.index].lookup = patch.lookup;
                        Index[patch.index].length = patch.length | (1 << 31);
                        Index[patch.index].extra  = patch.extra;
                    }
                }
            }
        }
示例#9
0
文件: FileIndex.cs 项目: roxya/Razor
        public FileIndex(string idxFile, string mulFile, int file)
        {
            string idxPath = null;

            MulPath = null;
            if (Files.MulPath == null)
            {
                Files.LoadMulPath();
            }
            if (Files.MulPath.Count > 0)
            {
                idxPath = Files.MulPath[idxFile.ToLower()];
                MulPath = Files.MulPath[mulFile.ToLower()];
                if (String.IsNullOrEmpty(idxPath))
                {
                    idxPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(idxPath)))
                    {
                        idxPath = Path.Combine(Files.RootDir, idxPath);
                    }
                    if (!File.Exists(idxPath))
                    {
                        idxPath = null;
                    }
                }

                if (String.IsNullOrEmpty(MulPath))
                {
                    MulPath = null;
                }
                else
                {
                    if (String.IsNullOrEmpty(Path.GetDirectoryName(MulPath)))
                    {
                        MulPath = Path.Combine(Files.RootDir, MulPath);
                    }
                    if (!File.Exists(MulPath))
                    {
                        MulPath = null;
                    }
                }
            }

            if ((idxPath != null) && (MulPath != null))
            {
                using (FileStream index = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Stream = new FileStream(MulPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    int count = (int)(index.Length / 12);
                    IdxLength = index.Length;
                    Index     = new Entry3D[count];
                    GCHandle gc     = GCHandle.Alloc(Index, GCHandleType.Pinned);
                    byte[]   buffer = new byte[index.Length];
                    index.Read(buffer, 0, (int)index.Length);
                    Marshal.Copy(buffer, 0, gc.AddrOfPinnedObject(), (int)index.Length);
                    gc.Free();
                }
            }
            else
            {
                Stream = null;
                Index  = new Entry3D[1];
                return;
            }

            Entry5D[] patches = Verdata.Patches;

            if (file > -1)
            {
                for (int i = 0; i < patches.Length; ++i)
                {
                    Entry5D patch = patches[i];

                    if (patch.file == file && patch.index >= 0 && patch.index < Index.Length)
                    {
                        Index[patch.index].lookup = patch.lookup;
                        Index[patch.index].length = patch.length | (1 << 31);
                        Index[patch.index].extra  = patch.extra;
                    }
                }
            }
        }
示例#10
0
        public void ExecuteModuleUnManaged(bool blockdlls)
        {
            string output = "";

            IntPtr hReadPipe  = IntPtr.Zero;
            IntPtr hWritePipe = IntPtr.Zero;

            if (!Spawner.CreatePipe(ref hReadPipe, ref hWritePipe))
            {
                return;
            }

            Core.Natives.PROCESS_INFORMATION procInfo = new Core.Natives.PROCESS_INFORMATION();
            if (blockdlls)
            {
                if (!Spawner.CreateProcess(hReadPipe, hWritePipe, this.processname, true, ref procInfo))
                {
                    return;
                }
            }
            else
            {
                if (!Spawner.CreateProcessPCMPBNMBSAO(hReadPipe, hWritePipe, this.processname, true, ref procInfo))
                {
                    return;
                }
            }

            string pipename = GetPipeName(procInfo.dwProcessId);
            InjectionLoaderListener injectionLoaderListener = new InjectionLoaderListener(pipename, task);

            byte[] payload = Core.Utility.DecompressDLL(Convert.FromBase64String(task.ModuleTask.Assembly));

            //Round payload size to page size
            uint size = InjectionHelper.GetSectionSize(payload.Length);

            //Crteate section in current process
            IntPtr section = IntPtr.Zero;

            section = InjectionHelper.CreateSection(size, Core.Natives.PAGE_EXECUTE_READWRITE);
            if (section == IntPtr.Zero)
            {
                return;
            }

            //Map section to current process
            IntPtr baseAddr = IntPtr.Zero;
            IntPtr viewSize = (IntPtr)size;

            InjectionHelper.MapViewOfSection(section, Core.Natives.GetCurrentProcess(), ref baseAddr, ref viewSize, Core.Natives.PAGE_READWRITE);
            if (baseAddr == IntPtr.Zero)
            {
                return;
            }

            //Copy payload to current process section
            Marshal.Copy(payload, 0, baseAddr, payload.Length);

            //Map remote section
            IntPtr baseAddrEx = IntPtr.Zero;
            IntPtr viewSizeEx = (IntPtr)size;

            InjectionHelper.MapViewOfSection(section, procInfo.hProcess, ref baseAddrEx, ref viewSizeEx, Core.Natives.PAGE_EXECUTE);
            if (baseAddrEx == IntPtr.Zero || viewSizeEx == IntPtr.Zero)
            {
                return;
            }

            if (!InjectionHelper.UnMapViewOfSection(baseAddr))
            {
                return;
            }

            // Assign address of shellcode to the target thread apc queue
            if (!InjectionHelper.QueueApcThread(baseAddrEx, procInfo))
            {
                return;
            }

            InjectionHelper.SetInformationThread(procInfo);

            InjectionHelper.ResumeThread(procInfo);

            output = injectionLoaderListener.Execute(procInfo.hProcess, hReadPipe);

            Core.Natives.CloseHandle(procInfo.hThread);
            Core.Natives.CloseHandle(procInfo.hProcess);

            SendResponse(output);
        }
示例#11
0
        public static ResultStatus ImportStreamableTextureImage(ContentManager assetManager, TextureTool textureTool, TexImage texImage, TextureHelper.ImportParameters convertParameters, CancellationToken cancellationToken, ICommandContext commandContext)
        {
            // Perform normal texture importing (but don't save it to file now)
            var importResult = TextureHelper.ImportTextureImageRaw(textureTool, texImage, convertParameters, cancellationToken, commandContext.Logger);

            if (importResult != ResultStatus.Successful)
            {
                return(importResult);
            }

            // Make sure we don't compress mips data
            var dataUrl = convertParameters.OutputUrl + "_Data";

            commandContext.AddTag(new ObjectUrl(UrlType.Content, dataUrl), Builder.DoNotCompressTag);

            using (var outputImage = textureTool.ConvertToStrideImage(texImage))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(ResultStatus.Cancelled);
                }

                // Create texture mips data containers (storage all array slices for every mip in separate chunks)
                var           desc     = outputImage.Description;
                List <byte[]> mipsData = new List <byte[]>(desc.MipLevels);
                for (int mipIndex = 0; mipIndex < desc.MipLevels; mipIndex++)
                {
                    int totalSize = 0;
                    for (int arrayIndex = 0; arrayIndex < desc.ArraySize; arrayIndex++)
                    {
                        var pixelBuffer = outputImage.GetPixelBuffer(arrayIndex, 0, mipIndex);
                        totalSize += pixelBuffer.BufferStride;
                    }

                    var buf        = new byte[totalSize];
                    int startIndex = 0;
                    for (int arrayIndex = 0; arrayIndex < desc.ArraySize; arrayIndex++)
                    {
                        var pixelBuffer = outputImage.GetPixelBuffer(arrayIndex, 0, mipIndex);
                        int size        = pixelBuffer.BufferStride;

                        Marshal.Copy(pixelBuffer.DataPointer, buf, startIndex, size);
                        startIndex += size;
                    }
                    mipsData.Add(buf);
                }

                // Pack mip maps to the storage container
                ContentStorageHeader storageHeader;
                ContentStorage.Create(assetManager, dataUrl, mipsData, out storageHeader);

                if (cancellationToken.IsCancellationRequested)
                {
                    return(ResultStatus.Cancelled);
                }

                // Serialize texture to file
                var outputTexture = new TextureSerializationData(outputImage, true, storageHeader);
                assetManager.Save(convertParameters.OutputUrl, outputTexture.ToSerializableVersion(), typeof(Texture));

                commandContext.Logger.Verbose($"Compression successful [{dataUrl}] to ({outputImage.Description.Width}x{outputImage.Description.Height},{outputImage.Description.Format})");
            }

            return(ResultStatus.Successful);
        }
示例#12
0
        private void SaveTransposedData(IChannel ch, Stream stream, ITransposeDataView data, int[] cols)
        {
            _host.AssertValue(ch);
            ch.AssertValue(stream);
            ch.AssertValue(data);
            ch.AssertNonEmpty(cols);
            ch.Assert(stream.CanSeek);

            // Initialize what we can in the header, though we will not be writing out things in the
            // header until we have confidence that things were written out correctly.
            TransposeLoader.Header header = default(TransposeLoader.Header);
            header.Signature         = TransposeLoader.Header.SignatureValue;
            header.Version           = TransposeLoader.Header.WriterVersion;
            header.CompatibleVersion = TransposeLoader.Header.WriterVersion;
            var slotType = data.GetSlotType(cols[0]);

            ch.AssertValue(slotType);
            header.RowCount    = slotType.Size;
            header.ColumnCount = cols.Length;

            // We keep track of the offsets of the start of each sub-IDV, for use in writing out the
            // offsets/length table later.
            List <long> offsets = new List <long>();

            // First write a bunch of zeros at the head, as a placeholder for the header that
            // will go there assuming we can successfully load it. We'll keep this array around
            // for the real marshalling and writing of the header bytes structure.
            byte[] headerBytes = new byte[TransposeLoader.Header.HeaderSize];
            stream.Write(headerBytes, 0, headerBytes.Length);
            offsets.Add(stream.Position);

            // This is a convenient delegate to write out an IDV substream, then save the offsets
            // where writing stopped to the offsets list.
            Action <string, IDataView> viewAction =
                (name, view) =>
            {
                using (var substream = new SubsetStream(stream))
                {
                    _internalSaver.SaveData(substream, view, Utils.GetIdentityPermutation(view.Schema.Count));
                    substream.Seek(0, SeekOrigin.End);
                    ch.Info("Wrote {0} data view in {1} bytes", name, substream.Length);
                }
                offsets.Add(stream.Position);
            };

            // First write out the no-row data, limited to these columns.
            IDataView subdata = new ChooseColumnsByIndexTransform(_host,
                                                                  new ChooseColumnsByIndexTransform.Arguments()
            {
                Indices = cols
            }, data);

            // If we want the "dual mode" row-wise and slot-wise file, don't filter out anything.
            if (!_writeRowData)
            {
                subdata = SkipTakeFilter.Create(_host, new SkipTakeFilter.TakeArguments()
                {
                    Count = 0
                }, subdata);
            }

            string msg = _writeRowData ? "row-wise data, schema, and metadata" : "schema and metadata";

            viewAction(msg, subdata);
            foreach (var col in cols)
            {
                viewAction(data.Schema[col].Name, new TransposerUtils.SlotDataView(_host, data, col));
            }

            // Wrote out the dataview. Write out the table offset.
            using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
            {
                // Format of the table is offset, length, both as 8-byte integers.
                // As it happens we wrote things out as adjacent sub-IDVs, so the
                // length can be derived from the offsets. The first will be the
                // start of the first sub-IDV, and all subsequent entries will be
                // the start/end of the current/next sub-IDV, respectively, so a total
                // of cols.Length + 2 entries.
                ch.Assert(offsets.Count == cols.Length + 2);
                ch.Assert(offsets[offsets.Count - 1] == stream.Position);
                header.SubIdvTableOffset = stream.Position;
                for (int c = 1; c < offsets.Count; ++c)
                {
                    // 8-byte int for offsets, 8-byte int for length.
                    writer.Write(offsets[c - 1]);
                    writer.Write(offsets[c] - offsets[c - 1]);
                }
                header.TailOffset = stream.Position;
                writer.Write(TransposeLoader.Header.TailSignatureValue);

                // Now we are confident that things will work, so write it out.
                unsafe
                {
                    Marshal.Copy(new IntPtr(&header), headerBytes, 0, Marshal.SizeOf(typeof(Header)));
                }
                writer.Seek(0, SeekOrigin.Begin);
                writer.Write(headerBytes);
            }
        }
示例#13
0
        private Bitmap SmartDownscale(Bitmap pixel, int factor, Color skip)
        {
            //generate output
            var output = new Bitmap(pixel.Width / factor, pixel.Height / factor);

            var olock = output.LockBits(new Rectangle(0, 0, output.Width, output.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            var odat  = new byte[olock.Stride * olock.Height];

            //lock input for read
            var plock = pixel.LockBits(new Rectangle(0, 0, pixel.Width, pixel.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            var pdat  = new byte[plock.Stride * plock.Height];

            Marshal.Copy(plock.Scan0, pdat, 0, pdat.Length);

            bool useSkip = skip != Color.FromArgb(0, 0, 0, 0);

            int index = 0;

            for (int y = 0; y < output.Height; y++)
            {
                for (int x = 0; x < output.Width; x++)
                {
                    //we want to sum a factor*factor area of the source and compute an average
                    //instances of the "skip" color are ignored.
                    int sumr = 0, sumg = 0, sumb = 0;
                    int div = 0;
                    for (int ix = 0; ix < factor; ix++)
                    {
                        for (int iy = 0; iy < factor; iy++)
                        {
                            var srcIndex = ((x * factor + ix) + (y * factor + iy) * pixel.Width) * 4;
                            if (!(useSkip && pdat[srcIndex] == skip.B && pdat[srcIndex + 1] == skip.G && pdat[srcIndex + 2] == skip.R))
                            {
                                div++;
                                sumr += pdat[srcIndex + 2];
                                sumg += pdat[srcIndex + 1];
                                sumb += pdat[srcIndex];
                            }
                        }
                    }

                    if (div == 0)
                    {
                        div  = 1;
                        sumr = skip.R;
                        sumg = skip.G;
                        sumb = skip.B;
                    }
                    else
                    {
                    }

                    odat[index]     = (byte)(sumb / div);
                    odat[index + 1] = (byte)(sumg / div);
                    odat[index + 2] = (byte)(sumr / div);
                    odat[index + 3] = 255;
                    index          += 4;
                }
            }

            pixel.UnlockBits(plock);

            Marshal.Copy(odat, 0, olock.Scan0, odat.Length);
            output.UnlockBits(olock);

            return(output);
        }
示例#14
0
        private void ReplaceSprite(Bitmap[] bmps, int frame)
        {
            var pixel = bmps[0];
            //first search pixel for the bounding rectangle.
            var plock = pixel.LockBits(new Rectangle(0, 0, pixel.Width, pixel.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            var pdat  = new byte[plock.Stride * plock.Height];

            Marshal.Copy(plock.Scan0, pdat, 0, pdat.Length);
            int maxX = int.MinValue, maxY = int.MinValue,
                minX = int.MaxValue, minY = int.MaxValue;

            int index = 0;

            for (int y = 0; y < pixel.Height; y++)
            {
                for (int x = 0; x < pixel.Width; x++)
                {
                    if (!(pdat[index] == 0 && pdat[index + 1] == 255 && pdat[index + 2] == 255))
                    {
                        if (x < minX)
                        {
                            minX = x;
                        }
                        if (x > maxX)
                        {
                            maxX = x;
                        }
                        if (y < minY)
                        {
                            minY = y;
                        }
                        if (y > maxY)
                        {
                            maxY = y;
                        }
                    }
                    index += 4;
                }
            }

            pixel.UnlockBits(plock);

            var rect = (minX == int.MaxValue) ? new Rectangle() : new Rectangle(minX, minY, (maxX - minX) + 1, (maxY - minY) + 1);
            var px   = rect.Width * rect.Height;

            var locks    = new BitmapData[3];
            var data     = new byte[3][];
            var pxOut    = new Microsoft.Xna.Framework.Color[px];
            var depthOut = new byte[px];

            for (int i = 0; i < 3; i++)
            {
                locks[i] = bmps[i].LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                data[i]  = new byte[locks[i].Stride * locks[i].Height];
                Marshal.Copy(locks[i].Scan0, data[i], 0, data[i].Length);
            }

            int scanStart = 0;
            int dstidx    = 0;

            for (int y = 0; y < locks[0].Height; y++)
            {
                int srcidx = scanStart;
                for (int j = 0; j < rect.Width; j++)
                {
                    pxOut[dstidx]    = new Microsoft.Xna.Framework.Color(data[0][srcidx + 2], data[0][srcidx + 1], data[0][srcidx], data[1][srcidx]);
                    depthOut[dstidx] = data[2][srcidx];
                    srcidx          += 4;
                    dstidx++;
                }
                scanStart += locks[0].Stride;
            }


            //set data first. we also want to get back the a palette we can change
            PALT targ = null;

            Microsoft.Xna.Framework.Color[] used;
            Content.Content.Get().Changes.BlockingResMod(new ResAction(() =>
            {
                used = GraphicChunk.Frames[frame].SetData(pxOut, depthOut, rect);

                var ownPalt     = GraphicChunk.ChunkParent.Get <PALT>(GraphicChunk.Frames[frame].PaletteID);
                ushort freePalt = GraphicChunk.ChunkID;
                if (GraphicChunk.Frames[frame].PaletteID != 0 && ownPalt != null && ownPalt.References == 1)
                {
                    targ = ownPalt;
                }
                else
                {
                    var palts = GraphicChunk.ChunkParent.List <PALT>();
                    palts     = (palts == null) ? new List <PALT>() : palts.OrderBy(x => x.ChunkID).ToList();
                    foreach (var palt in palts)
                    {
                        if (palt.ChunkID == freePalt)
                        {
                            freePalt++;
                        }
                        if (palt.PalMatch(used) || palt.References == 0)
                        {
                            targ = palt;
                            break;
                        }
                    }
                }

                if (targ != null)
                {
                    //replace existing palt.
                    lock (targ)
                    {
                        if (targ.References == 0 || targ == ownPalt)
                        {
                            targ.Colors = used;
                        }
                    }
                    Content.Content.Get().Changes.ChunkChanged(targ);
                    GraphicChunk.Frames[frame].SetPalt(targ);
                }
                else
                {
                    //we need to make a new PALT.
                    //a bit hacky for now
                    var nPalt = new PALT()
                    {
                        ChunkID        = freePalt,
                        ChunkLabel     = GraphicChunk.ChunkLabel + " Auto PALT",
                        AddedByPatch   = true,
                        ChunkProcessed = true,
                        ChunkType      = "PALT",
                        RuntimeInfo    = ChunkRuntimeState.Modified,
                        Colors         = used
                    };

                    GraphicChunk.ChunkParent.AddChunk(nPalt);
                    GraphicChunk.Frames[frame].SetPalt(nPalt);
                    Content.Content.Get().Changes.ChunkChanged(nPalt);
                }
            }, GraphicChunk));

            for (int i = 0; i < 3; i++)
            {
                bmps[i].UnlockBits(locks[i]);
            }
        }
示例#15
0
 public static float[] ToFloatsArray(this IntPtr ptr, int size)
 {
     float[] result = new float[size];
     Marshal.Copy(ptr, result, 0, size);
     return(result);
 }
示例#16
0
        /// <summary>
        /// Process each log entry
        /// </summary>
        /// <param name="packettype">packet type</param>
        /// <param name="br">input file</param>
        /// <returns>string of converted data</returns>
        static string logEntry(byte packettype, Stream br)
        {
            switch (packettype)
            {
            case 0x80:      // FMT

                log_Format logfmt = new log_Format();

                object obj = logfmt;

                int len = Marshal.SizeOf(obj);

                byte[] bytearray = new byte[len];

                br.Read(bytearray, 0, bytearray.Length);

                IntPtr i = Marshal.AllocHGlobal(len);

                // create structure from ptr
                obj = Marshal.PtrToStructure(i, obj.GetType());

                // copy byte array to ptr
                Marshal.Copy(bytearray, 0, i, len);

                obj = Marshal.PtrToStructure(i, obj.GetType());

                Marshal.FreeHGlobal(i);

                logfmt = (log_Format)obj;

                string lgname   = ASCIIEncoding.ASCII.GetString(logfmt.name).Trim(new char[] { '\0' });
                string lgformat = ASCIIEncoding.ASCII.GetString(logfmt.format).Trim(new char[] { '\0' });
                string lglabels = ASCIIEncoding.ASCII.GetString(logfmt.labels).Trim(new char[] { '\0' });

                logformat[lgname] = logfmt;

                string line = String.Format("FMT, {0}, {1}, {2}, {3}, {4}\r\n", logfmt.type, logfmt.length, lgname, lgformat, lglabels);

                return(line);

            default:
                string format = "";
                string name   = "";
                int    size   = 0;

                foreach (log_Format fmt in logformat.Values)
                {
                    if (fmt.type == packettype)
                    {
                        name   = ASCIIEncoding.ASCII.GetString(fmt.name).Trim(new char[] { '\0' });
                        format = ASCIIEncoding.ASCII.GetString(fmt.format).Trim(new char[] { '\0' });
                        size   = fmt.length;
                        break;
                    }
                }

                // didnt find a match, return unknown packet type
                if (size == 0)
                {
                    return("UNKW, " + packettype);
                }

                byte[] data = new byte[size - 3];  // size - 3 = message - messagetype - (header *2)

                br.Read(data, 0, data.Length);

                return(ProcessMessage(data, name, format));
            }
        }
示例#17
0
 public static byte[] ToBytesArray(this IntPtr ptr, int size)
 {
     byte[] result = new byte[size];
     Marshal.Copy(ptr, result, 0, size);
     return(result);
 }
示例#18
0
 public unsafe void CopyTo(IntPtr destDeviceData, int length)
 {
     Marshal.Copy(_buffer, 0, destDeviceData, length);
 }
示例#19
0
        private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream)
        {
#if IOS || MONOMAC
#if IOS
            using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream)))
#elif MONOMAC
            using (var nsImage = NSImage.FromStream(stream))
#endif
            {
#if IOS
                var cgImage = uiImage.CGImage;
#elif MONOMAC
#if PLATFORM_MACOS_LEGACY
                var rectangle = RectangleF.Empty;
#else
                var rectangle = CGRect.Empty;
#endif
                var cgImage = nsImage.AsCGImage(ref rectangle, null, null);
#endif

                return(PlatformFromStream(graphicsDevice, cgImage));
            }
#endif
#if ANDROID
            using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options
            {
                InScaled = false,
                InDither = false,
                InJustDecodeBounds = false,
                InPurgeable = true,
                InInputShareable = true,
            }))
            {
                return(PlatformFromStream(graphicsDevice, image));
            }
#endif
#if DESKTOPGL || ANGLE
            Bitmap image = (Bitmap)Bitmap.FromStream(stream);
            try
            {
                // Fix up the Image to match the expected format
                image = (Bitmap)image.RGBToBGR();

                var data = new byte[image.Width * image.Height * 4];

                BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                                                       ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                if (bitmapData.Stride != image.Width * 4)
                {
                    throw new NotImplementedException();
                }
                Marshal.Copy(bitmapData.Scan0, data, 0, data.Length);
                image.UnlockBits(bitmapData);

                Texture2D texture = null;
                texture = new Texture2D(graphicsDevice, image.Width, image.Height);
                texture.SetData(data);

                return(texture);
            }
            finally
            {
                image.Dispose();
            }
#endif
        }
示例#20
0
        public byte[] Export(X509ContentType contentType, String password)
        {
            switch (contentType)
            {
            case X509ContentType.Cert:
            {
                SafeCertContextHandle pCertContext = null;
                if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext))
                {
                    return(null);
                }
                try
                {
                    unsafe
                    {
                        byte[] rawData = new byte[pCertContext.CertContext->cbCertEncoded];
                        Marshal.Copy((IntPtr)(pCertContext.CertContext->pbCertEncoded), rawData, 0, rawData.Length);
                        GC.KeepAlive(pCertContext);
                        return(rawData);
                    }
                }
                finally
                {
                    pCertContext.Dispose();
                }
            }

            case X509ContentType.SerializedCert:
            {
                SafeCertContextHandle pCertContext = null;
                if (!Interop.crypt32.CertEnumCertificatesInStore(_certStore, ref pCertContext))
                {
                    return(null);
                }

                try
                {
                    int cbEncoded = 0;
                    if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, null, ref cbEncoded))
                    {
                        throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                    }

                    byte[] pbEncoded = new byte[cbEncoded];
                    if (!Interop.crypt32.CertSerializeCertificateStoreElement(pCertContext, 0, pbEncoded, ref cbEncoded))
                    {
                        throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                    }

                    return(pbEncoded);
                }
                finally
                {
                    pCertContext.Dispose();
                }
            }

            case X509ContentType.Pkcs12:
            {
                unsafe
                {
                    CRYPTOAPI_BLOB dataBlob = new CRYPTOAPI_BLOB(0, (byte *)null);

                    if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
                    {
                        throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                    }

                    byte[] pbEncoded = new byte[dataBlob.cbData];
                    fixed(byte *ppbEncoded = pbEncoded)
                    {
                        dataBlob.pbData = ppbEncoded;
                        if (!Interop.crypt32.PFXExportCertStore(_certStore, ref dataBlob, password, PFXExportFlags.EXPORT_PRIVATE_KEYS | PFXExportFlags.REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
                        {
                            throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                        }
                    }

                    return(pbEncoded);
                }
            }

            case X509ContentType.SerializedStore:
                return(SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_STORE));

            case X509ContentType.Pkcs7:
                return(SaveToMemoryStore(CertStoreSaveAs.CERT_STORE_SAVE_AS_PKCS7));

            default:
                throw new CryptographicException(SR.Cryptography_X509_InvalidContentType);
            }
        }
示例#21
0
        /// <summary>
        /// Quantize an image and return the resulting output brush
        /// </summary>
        /// <param name="source">The image to quantize</param>
        /// <returns>T quantized version of the image</returns>
        public Bitmap Quantize(Image source)
        {
            // Get the size of the source image
            int height = source.Height;
            int width  = source.Width;

            // And construct a rectangle from these dimensions
            Rectangle bounds = new Rectangle(0, 0, width, height);

            // First off take a 32bpp copy of the image
            Bitmap copy = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            // And construct an 8bpp version
            Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

            byte[] sourceData;
            // Now lock the brush into memory
            using (Graphics g = Graphics.FromImage(copy))
            {
                g.PageUnit = GraphicsUnit.Pixel;

                // Draw the source image onto the copy brush,
                // which will effect a widening as appropriate.
                g.DrawImage(source, bounds);
            }

            // Define a pointer to the brush data
            BitmapData sourceLock = null;

            try
            {
                // Get the source image bits and lock into memory
                sourceLock = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                sourceData = new byte[sourceLock.Stride * source.Height];
                Marshal.Copy(sourceLock.Scan0, sourceData, 0, sourceData.Length);

                // Call the FirstPass function if not a single pass algorithm.
                // For something like an octree quantizer, this will run through
                // all image pixels, build a data structure, and create a paletteIndex.
                if (!_singlePass)
                {
                    FirstPass(sourceData, width, height, sourceLock.Stride);
                }

                // Then set the color paletteIndex on the output brush. I'm passing in the current paletteIndex
                // as there's no way to construct a new, empty paletteIndex.
                output.Palette = GetPalette(output.Palette);


                // Then call the second pass which actually does the conversion
                SecondPass(sourceData, output, width, height, bounds, sourceLock.Stride);
            }
            finally
            {
                // Ensure that the bits are unlocked
                copy.UnlockBits(sourceLock);
            }

            // Last but not least, return the output brush
            return(output);
        }
示例#22
0
        /// <summary>
        ///     Sends an ATA command in 48-bit mode
        /// </summary>
        /// <returns>0 if no error occurred, otherwise, errno</returns>
        /// <param name="dev">CAM device</param>
        /// <param name="buffer">Buffer for SCSI command response</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense"><c>True</c> if ATA error returned non-OK status</param>
        /// <param name="registers">Registers to send to drive</param>
        /// <param name="errorRegisters">Registers returned by drive</param>
        /// <param name="protocol">ATA protocol to use</param>
        internal static int SendAtaCommand(IntPtr dev, AtaRegistersLba48 registers,
                                           out AtaErrorRegistersLba48 errorRegisters, AtaProtocol protocol,
                                           ref byte[]                 buffer, uint timeout,
                                           out double duration, out bool sense)
        {
            duration       = 0;
            sense          = false;
            errorRegisters = new AtaErrorRegistersLba48();

            // 48-bit ATA CAM commands can crash FreeBSD < 9.2-RELEASE
            if (Environment.Version.Major == 9 && Environment.Version.Minor < 2 ||
                Environment.Version.Major < 9)
            {
                return(-1);
            }

            if (buffer == null)
            {
                return(-1);
            }

            IntPtr ccbPtr = cam_getccb(dev);

            CcbAtaio ataio = (CcbAtaio)Marshal.PtrToStructure(ccbPtr, typeof(CcbAtaio));

            ataio.ccb_h.func_code   = XptOpcode.XptAtaIo;
            ataio.ccb_h.flags       = AtaProtocolToCamFlags(protocol);
            ataio.ccb_h.xflags      = 0;
            ataio.ccb_h.retry_count = 1;
            ataio.ccb_h.cbfcnp      = IntPtr.Zero;
            ataio.ccb_h.timeout     = timeout;
            ataio.data_ptr          = Marshal.AllocHGlobal(buffer.Length);
            ataio.dxfer_len         = (uint)buffer.Length;
            ataio.ccb_h.flags      |= CcbFlags.CamDevQfrzdis;
            ataio.cmd.flags         = CamAtaIoFlags.NeedResult | CamAtaIoFlags.ExtendedCommand;
            switch (protocol)
            {
            case AtaProtocol.Dma:
            case AtaProtocol.DmaQueued:
            case AtaProtocol.UDmaIn:
            case AtaProtocol.UDmaOut:
                ataio.cmd.flags |= CamAtaIoFlags.Dma;
                break;

            case AtaProtocol.FpDma:
                ataio.cmd.flags |= CamAtaIoFlags.Fpdma;
                break;
            }

            ataio.cmd.lba_high_exp     = (byte)((registers.LbaHigh & 0xFF00) >> 8);
            ataio.cmd.lba_mid_exp      = (byte)((registers.LbaMid & 0xFF00) >> 8);
            ataio.cmd.features_exp     = (byte)((registers.Feature & 0xFF00) >> 8);
            ataio.cmd.sector_count_exp = (byte)((registers.SectorCount & 0xFF00) >> 8);
            ataio.cmd.lba_low_exp      = (byte)((registers.LbaLow & 0xFF00) >> 8);
            ataio.cmd.lba_high         = (byte)(registers.LbaHigh & 0xFF);
            ataio.cmd.lba_mid          = (byte)(registers.LbaMid & 0xFF);
            ataio.cmd.features         = (byte)(registers.Feature & 0xFF);
            ataio.cmd.sector_count     = (byte)(registers.SectorCount & 0xFF);
            ataio.cmd.lba_low          = (byte)(registers.LbaLow & 0xFF);
            ataio.cmd.command          = registers.Command;
            ataio.cmd.device           = (byte)(0x40 | registers.DeviceHead);

            Marshal.Copy(buffer, 0, ataio.data_ptr, buffer.Length);
            Marshal.StructureToPtr(ataio, ccbPtr, false);

            DateTime start = DateTime.UtcNow;
            int      error = cam_send_ccb(dev, ccbPtr);
            DateTime end   = DateTime.UtcNow;

            if (error < 0)
            {
                error = Marshal.GetLastWin32Error();
            }

            ataio = (CcbAtaio)Marshal.PtrToStructure(ccbPtr, typeof(CcbAtaio));

            if ((ataio.ccb_h.status & CamStatus.CamStatusMask) != CamStatus.CamReqCmp &&
                (ataio.ccb_h.status & CamStatus.CamStatusMask) != CamStatus.CamScsiStatusError)
            {
                error = Marshal.GetLastWin32Error();
                DicConsole.DebugWriteLine("FreeBSD devices", "CAM status {0} error {1}", ataio.ccb_h.status, error);
                sense = true;
            }

            if ((ataio.ccb_h.status & CamStatus.CamStatusMask) == CamStatus.CamAtaStatusError)
            {
                sense = true;
            }

            errorRegisters.SectorCount = (ushort)((ataio.res.sector_count_exp << 8) + ataio.res.sector_count);
            errorRegisters.LbaLow      = (ushort)((ataio.res.lba_low_exp << 8) + ataio.res.lba_low);
            errorRegisters.LbaMid      = (ushort)((ataio.res.lba_mid_exp << 8) + ataio.res.lba_mid);
            errorRegisters.LbaHigh     = (ushort)((ataio.res.lba_high_exp << 8) + ataio.res.lba_high);
            errorRegisters.DeviceHead  = ataio.res.device;
            errorRegisters.Error       = ataio.res.error;
            errorRegisters.Status      = ataio.res.status;

            buffer = new byte[ataio.dxfer_len];

            Marshal.Copy(ataio.data_ptr, buffer, 0, buffer.Length);
            duration = (end - start).TotalMilliseconds;

            Marshal.FreeHGlobal(ataio.data_ptr);
            cam_freeccb(ccbPtr);

            sense = errorRegisters.Error != 0 || (errorRegisters.Status & 0xA5) != 0 || error != 0;

            return(error);
        }
示例#23
0
        public static void SetValue(this Mat mat, int row, int col, dynamic value)
        {
            var target = CreateElement(mat.Depth, value);

            Marshal.Copy(target, 0, mat.DataPointer + (row * mat.Cols + col) * mat.ElementSize, 1);
        }
示例#24
0
        /// <summary>
        ///     Sends a SCSI command (64-bit arch)
        /// </summary>
        /// <returns>0 if no error occurred, otherwise, errno</returns>
        /// <param name="dev">CAM device</param>
        /// <param name="cdb">SCSI CDB</param>
        /// <param name="buffer">Buffer for SCSI command response</param>
        /// <param name="senseBuffer">Buffer with the SCSI sense</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="direction">SCSI command transfer direction</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense">
        ///     <c>True</c> if SCSI error returned non-OK status and <paramref name="senseBuffer" /> contains SCSI
        ///     sense
        /// </param>
        internal static int SendScsiCommand64(IntPtr dev, byte[] cdb, ref byte[] buffer,
                                              out byte[] senseBuffer,
                                              uint timeout, CcbFlags direction, out double duration, out bool sense)
        {
            senseBuffer = null;
            duration    = 0;
            sense       = false;

            if (buffer == null)
            {
                return(-1);
            }

            IntPtr ccbPtr = cam_getccb(dev);
            IntPtr cdbPtr = IntPtr.Zero;

            if (ccbPtr.ToInt64() == 0)
            {
                sense = true;
                return(Marshal.GetLastWin32Error());
            }

            CcbScsiio64 csio = (CcbScsiio64)Marshal.PtrToStructure(ccbPtr, typeof(CcbScsiio64));

            csio.ccb_h.func_code   = XptOpcode.XptScsiIo;
            csio.ccb_h.flags       = direction;
            csio.ccb_h.xflags      = 0;
            csio.ccb_h.retry_count = 1;
            csio.ccb_h.cbfcnp      = IntPtr.Zero;
            csio.ccb_h.timeout     = timeout;
            csio.data_ptr          = Marshal.AllocHGlobal(buffer.Length);
            csio.dxfer_len         = (uint)buffer.Length;
            csio.sense_len         = 32;
            csio.cdb_len           = (byte)cdb.Length;
            // TODO: Create enum?
            csio.tag_action = 0x20;
            csio.cdb_bytes  = new byte[CAM_MAX_CDBLEN];
            if (cdb.Length <= CAM_MAX_CDBLEN)
            {
                Array.Copy(cdb, 0, csio.cdb_bytes, 0, cdb.Length);
            }
            else
            {
                cdbPtr = Marshal.AllocHGlobal(cdb.Length);
                byte[] cdbPtrBytes = BitConverter.GetBytes(cdbPtr.ToInt64());
                Array.Copy(cdbPtrBytes, 0, csio.cdb_bytes, 0, IntPtr.Size);
                csio.ccb_h.flags |= CcbFlags.CamCdbPointer;
            }

            csio.ccb_h.flags |= CcbFlags.CamDevQfrzdis;

            Marshal.Copy(buffer, 0, csio.data_ptr, buffer.Length);
            Marshal.StructureToPtr(csio, ccbPtr, false);

            DateTime start = DateTime.UtcNow;
            int      error = cam_send_ccb(dev, ccbPtr);
            DateTime end   = DateTime.UtcNow;

            if (error < 0)
            {
                error = Marshal.GetLastWin32Error();
            }

            csio = (CcbScsiio64)Marshal.PtrToStructure(ccbPtr, typeof(CcbScsiio64));

            if ((csio.ccb_h.status & CamStatus.CamStatusMask) != CamStatus.CamReqCmp &&
                (csio.ccb_h.status & CamStatus.CamStatusMask) != CamStatus.CamScsiStatusError)
            {
                error = Marshal.GetLastWin32Error();
                DicConsole.DebugWriteLine("FreeBSD devices", "CAM status {0} error {1}", csio.ccb_h.status, error);
                sense = true;
            }

            if ((csio.ccb_h.status & CamStatus.CamStatusMask) == CamStatus.CamScsiStatusError)
            {
                sense          = true;
                senseBuffer    = new byte[1];
                senseBuffer[0] = csio.scsi_status;
            }

            if ((csio.ccb_h.status & CamStatus.CamAutosnsValid) != 0)
            {
                if (csio.sense_len - csio.sense_resid > 0)
                {
                    sense          = (csio.ccb_h.status & CamStatus.CamStatusMask) == CamStatus.CamScsiStatusError;
                    senseBuffer    = new byte[csio.sense_len - csio.sense_resid];
                    senseBuffer[0] = csio.sense_data.error_code;
                    Array.Copy(csio.sense_data.sense_buf, 0, senseBuffer, 1, senseBuffer.Length - 1);
                }
            }

            buffer = new byte[csio.dxfer_len];
            cdb    = new byte[csio.cdb_len];

            Marshal.Copy(csio.data_ptr, buffer, 0, buffer.Length);
            if (csio.ccb_h.flags.HasFlag(CcbFlags.CamCdbPointer))
            {
                Marshal.Copy(new IntPtr(BitConverter.ToInt64(csio.cdb_bytes, 0)), cdb, 0, cdb.Length);
            }
            else
            {
                Array.Copy(csio.cdb_bytes, 0, cdb, 0, cdb.Length);
            }
            duration = (end - start).TotalMilliseconds;

            if (csio.ccb_h.flags.HasFlag(CcbFlags.CamCdbPointer))
            {
                Marshal.FreeHGlobal(cdbPtr);
            }
            Marshal.FreeHGlobal(csio.data_ptr);
            cam_freeccb(ccbPtr);

            return(error);
        }
示例#25
0
 public void CopyTo_NullDestination_ThrowsArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("destination", () => Marshal.Copy(new short[10], 0, IntPtr.Zero, 0));
     AssertExtensions.Throws <ArgumentNullException>("destination", () => Marshal.Copy(new IntPtr(1), (short[])null, 0, 0));
 }
示例#26
0
        static unsafe void Initialize()
        {
            uint   old;
            Module module = typeof(AntiDump).Module;
            var    bas    = (byte *)Marshal.GetHINSTANCE(module);
            byte * ptr    = bas + 0x3c;
            byte * ptr2;

            ptr  = ptr2 = bas + *(uint *)ptr;
            ptr += 0x6;
            ushort sectNum = *(ushort *)ptr;

            ptr += 14;
            ushort optSize = *(ushort *)ptr;

            ptr = ptr2 = ptr + 0x4 + optSize;

            byte * @new = stackalloc byte[11];

            if (module.FullyQualifiedName[0] != '<')             //Mapped
            {
                //VirtualProtect(ptr - 16, 8, 0x40, out old);
                //*(uint*)(ptr - 12) = 0;
                byte *mdDir = bas + *(uint *)(ptr - 16);
                //*(uint*)(ptr - 16) = 0;

                if (*(uint *)(ptr - 0x78) != 0)
                {
                    byte *importDir = bas + *(uint *)(ptr - 0x78);
                    byte *oftMod    = bas + *(uint *)importDir;
                    byte *modName   = bas + *(uint *)(importDir + 12);
                    byte *funcName  = bas + *(uint *)oftMod + 2;
                    VirtualProtect(modName, 11, 0x40, out old);

                    *(uint *)@new         = 0x6c64746e;
                    *((uint *)@new + 1)   = 0x6c642e6c;
                    *((ushort *)@new + 4) = 0x006c;
                    *(@new + 10)          = 0;

                    for (int i = 0; i < 11; i++)
                    {
                        *(modName + i) = *(@new + i);
                    }

                    VirtualProtect(funcName, 11, 0x40, out old);

                    *(uint *)@new         = 0x6f43744e;
                    *((uint *)@new + 1)   = 0x6e69746e;
                    *((ushort *)@new + 4) = 0x6575;
                    *(@new + 10)          = 0;

                    for (int i = 0; i < 11; i++)
                    {
                        *(funcName + i) = *(@new + i);
                    }
                }

                for (int i = 0; i < sectNum; i++)
                {
                    VirtualProtect(ptr, 8, 0x40, out old);
                    Marshal.Copy(new byte[8], 0, (IntPtr)ptr, 8);
                    ptr += 0x28;
                }
                VirtualProtect(mdDir, 0x48, 0x40, out old);
                byte *mdHdr = bas + *(uint *)(mdDir + 8);
                *(uint *)mdDir       = 0;
                *((uint *)mdDir + 1) = 0;
                *((uint *)mdDir + 2) = 0;
                *((uint *)mdDir + 3) = 0;

                VirtualProtect(mdHdr, 4, 0x40, out old);
                *(uint *)mdHdr = 0;
                mdHdr         += 12;
                mdHdr         += *(uint *)mdHdr;
                mdHdr          = (byte *)(((ulong)mdHdr + 7) & ~3UL);
                mdHdr         += 2;
                ushort numOfStream = *mdHdr;
                mdHdr += 2;
                for (int i = 0; i < numOfStream; i++)
                {
                    VirtualProtect(mdHdr, 8, 0x40, out old);
                    //*(uint*)mdHdr = 0;
                    mdHdr += 4;
                    //*(uint*)mdHdr = 0;
                    mdHdr += 4;
                    for (int ii = 0; ii < 8; ii++)
                    {
                        VirtualProtect(mdHdr, 4, 0x40, out old);
                        *mdHdr = 0;
                        mdHdr++;
                        if (*mdHdr == 0)
                        {
                            mdHdr += 3;
                            break;
                        }
                        *mdHdr = 0;
                        mdHdr++;
                        if (*mdHdr == 0)
                        {
                            mdHdr += 2;
                            break;
                        }
                        *mdHdr = 0;
                        mdHdr++;
                        if (*mdHdr == 0)
                        {
                            mdHdr += 1;
                            break;
                        }
                        *mdHdr = 0;
                        mdHdr++;
                    }
                }
            }
            else             //Flat
            {
                //VirtualProtect(ptr - 16, 8, 0x40, out old);
                //*(uint*)(ptr - 12) = 0;
                uint mdDir = *(uint *)(ptr - 16);
                //*(uint*)(ptr - 16) = 0;
                uint importDir = *(uint *)(ptr - 0x78);

                var vAdrs  = new uint[sectNum];
                var vSizes = new uint[sectNum];
                var rAdrs  = new uint[sectNum];
                for (int i = 0; i < sectNum; i++)
                {
                    VirtualProtect(ptr, 8, 0x40, out old);
                    Marshal.Copy(new byte[8], 0, (IntPtr)ptr, 8);
                    vAdrs[i]  = *(uint *)(ptr + 12);
                    vSizes[i] = *(uint *)(ptr + 8);
                    rAdrs[i]  = *(uint *)(ptr + 20);
                    ptr      += 0x28;
                }


                if (importDir != 0)
                {
                    for (int i = 0; i < sectNum; i++)
                    {
                        if (vAdrs[i] <= importDir && importDir < vAdrs[i] + vSizes[i])
                        {
                            importDir = importDir - vAdrs[i] + rAdrs[i];
                            break;
                        }
                    }
                    byte *importDirPtr = bas + importDir;
                    uint  oftMod       = *(uint *)importDirPtr;
                    for (int i = 0; i < sectNum; i++)
                    {
                        if (vAdrs[i] <= oftMod && oftMod < vAdrs[i] + vSizes[i])
                        {
                            oftMod = oftMod - vAdrs[i] + rAdrs[i];
                            break;
                        }
                    }
                    byte *oftModPtr = bas + oftMod;
                    uint  modName   = *(uint *)(importDirPtr + 12);
                    for (int i = 0; i < sectNum; i++)
                    {
                        if (vAdrs[i] <= modName && modName < vAdrs[i] + vSizes[i])
                        {
                            modName = modName - vAdrs[i] + rAdrs[i];
                            break;
                        }
                    }
                    uint funcName = *(uint *)oftModPtr + 2;
                    for (int i = 0; i < sectNum; i++)
                    {
                        if (vAdrs[i] <= funcName && funcName < vAdrs[i] + vSizes[i])
                        {
                            funcName = funcName - vAdrs[i] + rAdrs[i];
                            break;
                        }
                    }
                    VirtualProtect(bas + modName, 11, 0x40, out old);

                    *(uint *)@new         = 0x6c64746e;
                    *((uint *)@new + 1)   = 0x6c642e6c;
                    *((ushort *)@new + 4) = 0x006c;
                    *(@new + 10)          = 0;

                    for (int i = 0; i < 11; i++)
                    {
                        *(bas + modName + i) = *(@new + i);
                    }

                    VirtualProtect(bas + funcName, 11, 0x40, out old);

                    *(uint *)@new         = 0x6f43744e;
                    *((uint *)@new + 1)   = 0x6e69746e;
                    *((ushort *)@new + 4) = 0x6575;
                    *(@new + 10)          = 0;

                    for (int i = 0; i < 11; i++)
                    {
                        *(bas + funcName + i) = *(@new + i);
                    }
                }


                for (int i = 0; i < sectNum; i++)
                {
                    if (vAdrs[i] <= mdDir && mdDir < vAdrs[i] + vSizes[i])
                    {
                        mdDir = mdDir - vAdrs[i] + rAdrs[i];
                        break;
                    }
                }
                byte *mdDirPtr = bas + mdDir;
                VirtualProtect(mdDirPtr, 0x48, 0x40, out old);
                uint mdHdr = *(uint *)(mdDirPtr + 8);
                for (int i = 0; i < sectNum; i++)
                {
                    if (vAdrs[i] <= mdHdr && mdHdr < vAdrs[i] + vSizes[i])
                    {
                        mdHdr = mdHdr - vAdrs[i] + rAdrs[i];
                        break;
                    }
                }
                *(uint *)mdDirPtr       = 0;
                *((uint *)mdDirPtr + 1) = 0;
                *((uint *)mdDirPtr + 2) = 0;
                *((uint *)mdDirPtr + 3) = 0;


                byte *mdHdrPtr = bas + mdHdr;
                VirtualProtect(mdHdrPtr, 4, 0x40, out old);
                *(uint *)mdHdrPtr = 0;
                mdHdrPtr         += 12;
                mdHdrPtr         += *(uint *)mdHdrPtr;
                mdHdrPtr          = (byte *)(((ulong)mdHdrPtr + 7) & ~3UL);
                mdHdrPtr         += 2;
                ushort numOfStream = *mdHdrPtr;
                mdHdrPtr += 2;
                for (int i = 0; i < numOfStream; i++)
                {
                    VirtualProtect(mdHdrPtr, 8, 0x40, out old);
                    //*(uint*)mdHdrPtr = 0;
                    mdHdrPtr += 4;
                    //*(uint*)mdHdrPtr = 0;
                    mdHdrPtr += 4;
                    for (int ii = 0; ii < 8; ii++)
                    {
                        VirtualProtect(mdHdrPtr, 4, 0x40, out old);
                        *mdHdrPtr = 0;
                        mdHdrPtr++;
                        if (*mdHdrPtr == 0)
                        {
                            mdHdrPtr += 3;
                            break;
                        }
                        *mdHdrPtr = 0;
                        mdHdrPtr++;
                        if (*mdHdrPtr == 0)
                        {
                            mdHdrPtr += 2;
                            break;
                        }
                        *mdHdrPtr = 0;
                        mdHdrPtr++;
                        if (*mdHdrPtr == 0)
                        {
                            mdHdrPtr += 1;
                            break;
                        }
                        *mdHdrPtr = 0;
                        mdHdrPtr++;
                    }
                }
            }
        }
示例#27
0
        public void CopyTo_NegativeLength_ThrowsArgumentOutOfRangeException()
        {
            short[] array = new short[10];
            IntPtr  ptr   = Marshal.AllocCoTaskMem(sizeof(short) * array.Length);

            try
            {
                AssertExtensions.Throws <ArgumentOutOfRangeException>(null, () => Marshal.Copy(array, 0, ptr, -1));
                AssertExtensions.Throws <ArgumentOutOfRangeException>("length", () => Marshal.Copy(ptr, array, 0, -1));
            }
            finally
            {
                Marshal.FreeCoTaskMem(ptr);
            }
        }
示例#28
0
        private ServiceElement BuildElement(IntPtr pElemData)
        {
            var elemData = (Structs.SDP_Data_Element)Marshal.PtrToStructure(
                pElemData, typeof(Structs.SDP_Data_Element));
            var sizeofElemData = Marshal.SizeOf(typeof(Structs.SDP_Data_Element));
            //
            ElementTypeDescriptor etd; SizeIndex sizeIndex;

            Map(elemData.SDP_Data_Element_Type, out etd, out sizeIndex);
            //
            const int OffsetOf_FakeAtUnionPosition = 8;

#if !NETCF
            var dbgOffset = Marshal.OffsetOf(typeof(Structs.SDP_Data_Element), "FakeAtUnionPosition");
            Debug.Assert(new IntPtr(OffsetOf_FakeAtUnionPosition) == dbgOffset,
                         "OffsetOf_FakeAtUnionPosition but: " + dbgOffset);
#endif
            IntPtr pDataInStruct = Pointers.Add(pElemData, OffsetOf_FakeAtUnionPosition);
            IntPtr pArrElements  = Marshal.ReadIntPtr(pDataInStruct);
            if (etd == ElementTypeDescriptor.ElementSequence ||
                etd == ElementTypeDescriptor.ElementAlternative)
            {
                var list = new List <ServiceElement>();
                var pCur = pArrElements;
                for (int i = 0; i < elemData.SDP_Data_Element_Length; ++i)
                {
                    var e = BuildElement(pCur);
                    list.Add(e);
                    // Next
                    pCur = Pointers.Add(pCur, sizeofElemData);
                }//for
#if DEBUG
                ElementTypeDescriptor cover;
                if (etd == ElementTypeDescriptor.ElementAlternative)
                {
                    cover = etd; //COVERAGE
                }
                else
                {
                    cover = etd; //COVERAGE
                }
#endif
                return(new ServiceElement(
                           etd == ElementTypeDescriptor.ElementSequence
                        ? ElementType.ElementSequence
                        : ElementType.ElementAlternative,
                           list));
            }
            else
            {
                byte[] buf = new byte[elemData.SDP_Data_Element_Length];
                IntPtr pData;
                if (etd == ElementTypeDescriptor.TextString ||
                    etd == ElementTypeDescriptor.Url)
                {
                    pData = pArrElements;
                }
                else
                {
                    pData = pDataInStruct;
                }
                Marshal.Copy(pData, buf, 0, buf.Length);
                int readLen = buf.Length;
                var elem    = _parser.ParseContent(false, true,
                                                   buf, 0, buf.Length, ref readLen,
                                                   etd, sizeIndex, buf.Length, 0);
                return(elem);
            }
        }
示例#29
0
        /// <summary>
        /// Loads a mesh and creates the vertex/index buffers for the part
        /// </summary>
        /// <param name="part"></param>
        /// <param name="meshData"></param>
        void LoadMesh(ref Part part, IXDataObject dataObject)
        {
            // load vertex data
            int dataOffset = 0;
            Match vertexCount = findArrayCount.Match(dataObject.Body);
            if(!vertexCount.Success)
                throw new System.IO.InvalidDataException("problem reading vertex count");

            List<Vector4F> vertexList = new List<Vector4F>();
            int verticies = int.Parse(vertexCount.Groups[1].Value, CultureInfo.InvariantCulture);
            dataOffset = vertexCount.Index + vertexCount.Length;
            for(int vertexIndex = 0; vertexIndex < verticies; vertexIndex++)
            {
                Match vertex = findVector3F.Match(dataObject.Body, dataOffset);
                if(!vertex.Success)
                    throw new System.IO.InvalidDataException("problem reading vertex");
                else
                    dataOffset = vertex.Index + vertex.Length;

                vertexList.Add(
                    new Vector4F(
                        float.Parse(vertex.Groups[1].Value, CultureInfo.InvariantCulture),
                        float.Parse(vertex.Groups[2].Value, CultureInfo.InvariantCulture),
                        float.Parse(vertex.Groups[3].Value, CultureInfo.InvariantCulture),
                        1.0f));
            }

            // load triangle index data
            Match triangleIndexCount = findArrayCount.Match(dataObject.Body, dataOffset);
            dataOffset = triangleIndexCount.Index + triangleIndexCount.Length;
            if(!triangleIndexCount.Success)
                throw new System.IO.InvalidDataException("problem reading index count");

            List<Int32> triangleIndiciesList = new List<Int32>();
            int triangleIndexListCount = int.Parse(triangleIndexCount.Groups[1].Value, CultureInfo.InvariantCulture);
            dataOffset = triangleIndexCount.Index + triangleIndexCount.Length;
            for(int triangleIndicyIndex = 0; triangleIndicyIndex < triangleIndexListCount; triangleIndicyIndex++)
            {
                Match indexEntry = findVertexIndex.Match(dataObject.Body, dataOffset);
                if(!indexEntry.Success)
                    throw new System.IO.InvalidDataException("problem reading vertex index entry");
                else
                    dataOffset = indexEntry.Index + indexEntry.Length;

                int indexEntryCount = int.Parse(indexEntry.Groups[1].Value, CultureInfo.InvariantCulture);
                string[] vertexIndexes = indexEntry.Groups[2].Value.Split(new char[] { ',' });
                if(indexEntryCount != vertexIndexes.Length)
                    throw new System.IO.InvalidDataException("vertex index count does not equal count of indicies found");

                for(int entryIndex = 0; entryIndex <= indexEntryCount - 3; entryIndex++)
                {
                    triangleIndiciesList.Add(int.Parse(vertexIndexes[0], CultureInfo.InvariantCulture));
                    triangleIndiciesList.Add(int.Parse(vertexIndexes[1 + entryIndex].ToString(), CultureInfo.InvariantCulture));
                    triangleIndiciesList.Add(int.Parse(vertexIndexes[2 + entryIndex].ToString(), CultureInfo.InvariantCulture));
                }
            }

            // load mesh colors
            IXDataObject vertexColorData = GetSingleChild(dataObject, "MeshVertexColors");
            Dictionary<int, Vector4F> colorDictionary = null;
            if (vertexColorData != null)
                colorDictionary = LoadMeshColors(vertexColorData);

            // load mesh normals
            IXDataObject meshNormalData = GetSingleChild(dataObject, "MeshNormals");
            IndexedMeshNormals meshNormals = null;
            if(meshNormalData != null)
            {
                meshNormals = LoadMeshNormals(meshNormalData);
            }

            // load mesh texture coordinates
            IXDataObject meshTextureCoordsData = GetSingleChild(dataObject, "MeshTextureCoords");
            List<Vector2F> meshTextureCoords = null;
            if(meshTextureCoordsData != null)
            {
                meshTextureCoords = LoadMeshTextureCoordinates(meshTextureCoordsData);
            }

            // load mesh material
            IXDataObject meshMaterialsData = GetSingleChild(dataObject, "MeshMaterialList");
            List<MaterialSpecification> meshMaterials = null;
            if(meshMaterialsData != null)
            {
                meshMaterials = LoadMeshMaterialList(meshMaterialsData);
            }
            
            // copy vertex data to HGLOBAL
            int byteLength = Marshal.SizeOf(typeof(XMeshVertex)) * triangleIndiciesList.Count;
            IntPtr nativeVertex = Marshal.AllocHGlobal(byteLength);
            byte[] byteBuffer = new byte[byteLength];
            XMeshVertex[] varray = new XMeshVertex[triangleIndiciesList.Count];
            for(int n = 0; n < triangleIndiciesList.Count; n++)
            {
                XMeshVertex vertex = new XMeshVertex()
                {
                    Vertex = vertexList[triangleIndiciesList[n]],
                    Normal = (meshNormals == null) ? new Vector4F(0, 0, 0, 1.0f) : meshNormals.normalVectors[meshNormals.normalIndexMap[n]],
                    Color = ((colorDictionary == null) ? new Vector4F(0, 0, 0, 0) : colorDictionary[triangleIndiciesList[n]]),
                    Texture = ((meshTextureCoords == null) ? new Vector2F(0, 0) : meshTextureCoords[triangleIndiciesList[n]])
                };
                byte[] vertexData = RawSerialize(vertex);
                Buffer.BlockCopy(vertexData, 0, byteBuffer, vertexData.Length * n, vertexData.Length);
            }
            Marshal.Copy(byteBuffer, 0, nativeVertex, byteLength);

            // build vertex buffer
            BufferDescription bdv = new BufferDescription()
            {
                Usage = Usage.Default,
                ByteWidth = (uint)(Marshal.SizeOf(typeof(XMeshVertex)) * triangleIndiciesList.Count),
                BindingOptions = BindingOptions.VertexBuffer,
                CpuAccessOptions = CpuAccessOptions.None,
                MiscellaneousResourceOptions = MiscellaneousResourceOptions.None
            };
            SubresourceData vertexInit = new SubresourceData()
            {
                SystemMemory = nativeVertex
            };

            part.vertexBuffer = device.CreateBuffer(bdv, vertexInit);
            Debug.Assert(part.vertexBuffer != null);


            part.vertexCount = triangleIndiciesList.Count;

            if(meshMaterials != null)
            {
                // only a single material is currently supported
                MaterialSpecification m = meshMaterials[0];

                part.material = new Material()
                {
                    emissiveColor = m.emissiveColor,
                    specularColor = m.specularColor,
                    materialColor = m.materialColor,
                    specularPower = m.specularPower
                };
                
                string texturePath = "";
                if(File.Exists(m.textureFileName))
                    texturePath = m.textureFileName;
                if(File.Exists(meshDirectory + "\\" + m.textureFileName))
                    texturePath = meshDirectory + "\\" + m.textureFileName;
                if(File.Exists(meshDirectory + "\\..\\" + m.textureFileName))
                    texturePath = meshDirectory + "\\..\\" + m.textureFileName;

                if(texturePath.Length == 0)
                {
                    part.material.textureResource = null;
                }
                else
                {
                    part.material.textureResource =
                        D3D10XHelpers.CreateShaderResourceViewFromFile(
                            device,
                            texturePath);
                }
            }
            Marshal.FreeHGlobal(nativeVertex);
        }
示例#30
0
 public byte[] ToArray()
 {
     byte[] data = new byte[count];
     Marshal.Copy(new IntPtr(this.data), data, 0, count);
     return(data);
 }