System.Array.Copy(System.Array, long, System.Array, long, long)

Here are the examples of the csharp api System.Array.Copy(System.Array, long, System.Array, long, long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1820 Examples 7

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static void DecodeBase58StringFromByte(byte[] data, int offset, int length, out string decodedData)
        {
            decodedData = "";
            byte[] dataCopy = new byte[length];
            Array.Copy(data, (long)offset, dataCopy, 0, length);

            decodedData = Base58Encoding.Encode(dataCopy);
        }

19 View Source File : SkinnedState.cs
License : MIT License
Project Creator : AmplifyCreations

private void UpdateVerticesFallback( bool starting )
	{
		if ( !starting && m_wasVisible )
			Array.Copy( m_currVertices, m_prevVertices, m_vertexCount );

		m_renderer.BakeMesh( m_clonedMesh );

		if ( m_clonedMesh.vertexCount == 0 || m_clonedMesh.vertexCount != m_prevVertices.Length )
		{
			IssueError( "[AmplifyMotion] Invalid mesh obtained from SkinnedMeshRenderer.BakeMesh in object " + m_obj.name + ". Skipping." );
			return;
		}

		Array.Copy( m_clonedMesh.vertices, m_currVertices, m_vertexCount );

		if ( starting || !m_wasVisible )
			Array.Copy( m_currVertices, m_prevVertices, m_vertexCount );
	}

19 View Source File : SimpleBuffer.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

public override long Read(byte[] ba, long index, long pos, long len) 
	{
		Array.Copy(data, pos, ba, index, len);
		return len;
	}

19 View Source File : ReadOnlyByteStream.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public override int Read(byte[] buffer, int offset, int count)
        {
            var actualCount = count;
            if (this.Position + count > this.Length)
            {
                actualCount = (int)(this.Length - this.Position);
            }

            Array.Copy(this.Data, this.Position, buffer, offset, actualCount);

            this.Position += actualCount;
            return actualCount;
        }

19 View Source File : DOTMogTypes.cs
License : Apache License 2.0
Project Creator : ajuna-network

public void Create(BigInteger value)
        {
            var byteArray = new byte[16];
            Array.Copy(value.ToByteArray(), 0, byteArray, 0, value.ToByteArray().Length);
            Bytes = byteArray;
            Value = value;
        }

19 View Source File : EntityStateReadBuffers.cs
License : The Unlicense
Project Creator : aeroson

public void GetStates(MotionState[] states)
        {
            lock (FlipLocker)
            {
                if (states.Length < manager.enreplacedies.Count)
                {
                    throw new ArgumentException("Array is not large enough to hold the buffer.", "states");
                }
                Array.Copy(frontBuffer, states, manager.enreplacedies.Count);
            }
        }

19 View Source File : ChunkingReadStreamTest.cs
License : Apache License 2.0
Project Creator : aloneguid

protected override int SmallRead(long globalPos, byte[] buffer, int offset, int count)
      {
         int left = (int)(_data.Length - globalPos);
         int canRead = Math.Min(left, count);

         Array.Copy(_data, globalPos, buffer, offset, canRead);

         return canRead;
      }

19 View Source File : ImgTex.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void TileCSI(byte[] data, uint dest_height, uint dest_width, ImgTex csi_tex, uint tiling)
        {
            var src_data = csi_tex.ImageData.Data;

            for (var i = 0; i < tiling * 2; i++)
                Array.Copy(src_data, 0, data, src_data.Length * i, src_data.Length);
        }

19 View Source File : DataBuffer.cs
License : MIT License
Project Creator : AndreasAmMueller

public void ResizeTo(int size)
		{
			if (size < 0)
				throw new ArgumentOutOfRangeException(nameof(size));

			byte[] newBuffer = new byte[size];
			int len = Math.Min(size, Length);
			Array.Copy(Buffer, newBuffer, len);
			Buffer = newBuffer;
		}

19 View Source File : TextureCache.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

private static Texture2D LoadTexture(uint textureID, bool useDummy = false, Surface surface = null, Dictionary<int, uint> customPaletteColors = null)
        {
            //Console.WriteLine($"--> TextureCache.LoadTexture({textureID:X8})");

            if (textureID >> 24 == 0x04)
                return LoadPalette(textureID);
            else if (textureID >> 24 == 0x0F)
                return LoadPaletteSet(textureID);

            var isClipMap = surface != null && surface.Type.HasFlag(SurfaceType.Base1ClipMap);

            MainWindow.Instance.Status.WriteLine($"Loading texture {textureID:X8}");

            var texture = DatManager.PortalDat.ReadFromDat<ACE.DatLoader.FileTypes.Texture>(textureID);
            if (texture.SourceData == null)
                texture = DatManager.HighResDat.ReadFromDat<ACE.DatLoader.FileTypes.Texture>(textureID);

            if (customPaletteColors != null)
                texture.CustomPaletteColors = customPaletteColors;

            var surfaceFormat = SurfaceFormat.Color;
            switch (texture.Format)
            {
                case SurfacePixelFormat.PFID_DXT1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;
                case SurfacePixelFormat.PFID_DXT3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;
                case SurfacePixelFormat.PFID_DXT5:
                    //if (!isClipMap)
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;
                case SurfacePixelFormat.PFID_CUSTOM_LSCAPE_ALPHA:
                case SurfacePixelFormat.PFID_A8:
                case SurfacePixelFormat.PFID_P8:    // indexed color
                    surfaceFormat = SurfaceFormat.Alpha8;
                    break;
            }

            var width = texture.Width;
            var height = texture.Height;

            var data = new byte[texture.SourceData.Length];
            Array.Copy(texture.SourceData, data, data.Length);  // fixme: multiple rgb reversals

            if (surfaceFormat == SurfaceFormat.Color)
            {
                switch (texture.Format)
                {
                    case SurfacePixelFormat.PFID_R8G8B8:
                    case SurfacePixelFormat.PFID_CUSTOM_LSCAPE_R8G8B8:
                        data = AddAlpha(data);
                        break;
                    case SurfacePixelFormat.PFID_INDEX16:
                        data = IndexToColor(texture, isClipMap);
                        break;

                    case SurfacePixelFormat.PFID_CUSTOM_RAW_JPEG:
                    case SurfacePixelFormat.PFID_R5G6B5:
                    case SurfacePixelFormat.PFID_A4R4G4B4:
                        //case SurfacePixelFormat.PFID_DXT5:
                        var bitmap = texture.GetBitmap();
                        var _tex = GetTexture2DFromBitmap(GameView.Instance.GraphicsDevice, bitmap);
                        //if (isClipMap)
                        //AdjustClip(_tex);
                        return _tex;

                    case SurfacePixelFormat.PFID_A8R8G8B8:
                        ConvertToABGR(data);
                        break;
                }
            }

            Texture2D tex = null;
            if (useDummy)
            {
                if (surfaceFormat == SurfaceFormat.Alpha8)
                {
                    tex = new Texture2D(GameView.Instance.GraphicsDevice, 1, 1, false, SurfaceFormat.Alpha8);
                    var alpha = new byte[1];
                    alpha[0] = 255;
                    tex.SetData(alpha);
                }
                else
                {
                    tex = new Texture2D(GameView.Instance.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
                    var color = new Microsoft.Xna.Framework.Color[1];
                    color[0].A = data[3];
                    color[0].R = data[2];
                    color[0].G = data[1];
                    color[0].B = data[0];
                    tex.SetData(color);
                }
            }
            else
            {
                if (UseMipMaps && surfaceFormat == SurfaceFormat.Color && texture.Width == texture.Height)
                    tex = GenerateMipMaps(data, texture.Width);
                else
                {
                    tex = new Texture2D(GameView.Instance.GraphicsDevice, texture.Width, texture.Height, false, surfaceFormat);
                    tex.SetData(data);
                }
            }
            return tex;
        }

19 View Source File : ImmutableDictionary.cs
License : MIT License
Project Creator : alexandrnikitin

internal override ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value, uint hash, int shift)
        {
            var bit = 1U << (int) ((hash >> shift) & Mask);
            if ((_bitmap & bit) != 0)
            {
                var newNodes = new ImmutableDictionary<TKey, TValue>[_nodes.Length];
                Array.Copy(_nodes, newNodes, _nodes.Length);
                var index = Popcnt.PopCount((_bitmap >> (int) bit) & Mask);
                newNodes[index] = _nodes[index].Add(key, value, hash, shift + Shift);
                return new BitMapNode<TKey, TValue>(_bitmap, newNodes);
            }
            else
            {
                var index = Popcnt.PopCount((_bitmap >> (int)bit) & Mask);
                var newNodes = new ImmutableDictionary<TKey, TValue>[_nodes.Length + 1];
                Array.Copy(_nodes, newNodes, index);
                Array.Copy(_nodes, index, newNodes, index + 1, _nodes.Length - index);
                newNodes[index] = new KeyValueNode<TKey, TValue>(key, value, hash);
                return new BitMapNode<TKey, TValue>(_bitmap | bit, newNodes);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

private void Resize()
    {
        Entry[] oldEntries = entries;

        hashBits++;
        hashMask = (1u << hashBits) - 1;

        Entry[] newEntries = new Entry[1 << hashBits];
        uint[] newBuckets = new uint[1 << hashBits];

        buckets = newBuckets;
        entries = newEntries;

        Array.Copy(oldEntries, 0, newEntries, 0, count);

        for (uint i = 0; i < count; i++)
        {
            uint bucket = GetBucketIndex(newEntries[i].key);
            newEntries[i].next = newBuckets[bucket] - 1;
            newBuckets[bucket] = i + 1;
        }
    }

19 View Source File : SecretSharingHelper.cs
License : MIT License
Project Creator : AElfProject

public static List<byte[]> EncodeSecret(byte[] secretMessage, int threshold, int totalParts)
        {
            // Polynomial construction.
            var coefficients = new BigInteger[threshold];
            // Set p(0) = secret message.
            coefficients[0] = secretMessage.ToBigInteger();
            for (var i = 1; i < threshold; i++)
            {
                var foo = new byte[32];
                Array.Copy(HashHelper.ComputeFrom(Guid.NewGuid().ToByteArray()).ToArray(), foo, 32);
                coefficients[i] = BigInteger.Abs(new BigInteger(foo));
            }

            var result = new List<byte[]>();
            for (var i = 1; i < totalParts + 1; i++)
            {
                var secretBigInteger = coefficients[0];
                for (var j = 1; j < threshold; j++)
                {
                    secretBigInteger += coefficients[j] * BigInteger.Pow(new BigInteger(i), j);
                    secretBigInteger %= SecretSharingConsts.FieldPrime;
                }

                result.Add(secretBigInteger.ToByteArray());
            }

            return result;
        }

19 View Source File : EdgeDetectionTool.cs
License : Apache License 2.0
Project Creator : Algoryx

private AGXUnity.Edge FindClosestEdgeIncludingTargetPrincipalAxes( Ray ray, AGXUnity.Edge triangleEdge, float principalEdgeExtension = 10.0f )
    {
      if ( m_collectedData.Target == null )
        return new AGXUnity.Edge();

      var edges      = new AGXUnity.Edge[ 4 ];
      var shape      = m_collectedData.Target.GetComponent<Shape>();
      var shapeUtils = shape?.GetUtils();
      if ( shapeUtils != null )
        Array.Copy( shapeUtils.GetPrincipalEdgesWorld( principalEdgeExtension ), edges, 3 );
      else {
        var mesh = shape is AGXUnity.Collide.Mesh ?
                     ( shape as AGXUnity.Collide.Mesh ).SourceObjects.FirstOrDefault() :
                   m_collectedData.Target.GetComponent<MeshFilter>() != null ?
                     m_collectedData.Target.GetComponent<MeshFilter>().sharedMesh :
                     null;
        var halfExtents = 0.5f * Vector3.one;
        if ( mesh != null )
          halfExtents = mesh.bounds.extents;

        Array.Copy( ShapeUtils.ExtendAndTransformEdgesToWorld( m_collectedData.Target.transform,
                                                               new AGXUnity.Edge[]
                                                               {
                                                                 new AGXUnity.Edge()
                                                                 {
                                                                   Start  = BoxShapeUtils.GetLocalFace( halfExtents, ShapeUtils.Direction.Negative_X ),
                                                                   End    = BoxShapeUtils.GetLocalFace( halfExtents, ShapeUtils.Direction.Positive_X ),
                                                                   Normal = ShapeUtils.GetLocalFaceDirection( ShapeUtils.Direction.Positive_Y ),
                                                                   Type   = AGXUnity.Edge.EdgeType.Principal
                                                                 },
                                                                 new AGXUnity.Edge()
                                                                 {
                                                                   Start  = BoxShapeUtils.GetLocalFace( halfExtents, ShapeUtils.Direction.Negative_Y ),
                                                                   End    = BoxShapeUtils.GetLocalFace( halfExtents, ShapeUtils.Direction.Positive_Y ),
                                                                   Normal = ShapeUtils.GetLocalFaceDirection( ShapeUtils.Direction.Positive_Z ),
                                                                   Type   = AGXUnity.Edge.EdgeType.Principal
                                                                 },
                                                                 new AGXUnity.Edge()
                                                                 {
                                                                   Start  = BoxShapeUtils.GetLocalFace( halfExtents, ShapeUtils.Direction.Negative_Z ),
                                                                   End    = BoxShapeUtils.GetLocalFace( halfExtents, ShapeUtils.Direction.Positive_Z ),
                                                                   Normal = ShapeUtils.GetLocalFaceDirection( ShapeUtils.Direction.Positive_X ),
                                                                   Type   = AGXUnity.Edge.EdgeType.Principal
                                                                 }
                                                               },
                                                               principalEdgeExtension ), edges, 3 );
      }

      edges[ 3 ] = triangleEdge;

      return ShapeUtils.FindClosestEdgeToSegment( ray.origin, ray.GetPoint( 5000.0f ), edges ).Edge;
    }

19 View Source File : ConstructGltf.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static async Task ConstructTextureAsync(this GltfObject gltfObject, GltfTexture gltfTexture)
        {
            if (gltfObject.UseBackgroundThread) await BackgroundThread;

            if (gltfTexture.source >= 0)
            {
                GltfImage gltfImage = gltfObject.images[gltfTexture.source];

                byte[] imageData = null;
                Texture2D texture = null;

                if (!string.IsNullOrEmpty(gltfObject.Uri) && !string.IsNullOrEmpty(gltfImage.uri))
                {
                    var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
                    var path = Path.Combine(parentDirectory, gltfImage.uri);

#if UNITY_EDITOR
                    if (gltfObject.UseBackgroundThread) await Update;
                    var projectPath = Path.GetFullPath(path).Replace(Path.GetFullPath(Application.dataPath), "replacedets");
                    texture = UnityEditor.replacedetDatabase.LoadreplacedetAtPath<Texture2D>(projectPath);

                    if (gltfObject.UseBackgroundThread) await BackgroundThread;
#endif

                    if (texture == null)
                    {
#if WINDOWS_UWP
                        if (gltfObject.UseBackgroundThread)
                        {
                            try
                            {
                                var storageFile = await StorageFile.GetFileFromPathAsync(path);

                                if (storageFile != null)
                                {

                                    var buffer = await FileIO.ReadBufferAsync(storageFile);

                                    using (DataReader dataReader = DataReader.FromBuffer(buffer))
                                    {
                                        imageData = new byte[buffer.Length];
                                        dataReader.ReadBytes(imageData);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.LogError(e.Message);
                            }
                        }
                        else
                        {
                            imageData = UnityEngine.Windows.File.ReadAllBytes(path);
                        }
#else
                        using (FileStream stream = File.Open(path, FileMode.Open))
                        {
                            imageData = new byte[stream.Length];

                            if (gltfObject.UseBackgroundThread)
                            {
                                await stream.ReadAsync(imageData, 0, (int)stream.Length);
                            }
                            else
                            {
                                stream.Read(imageData, 0, (int)stream.Length);
                            }
                        }
#endif
                    }
                }
                else
                {
                    var imageBufferView = gltfObject.bufferViews[gltfImage.bufferView];
                    imageData = new byte[imageBufferView.byteLength];
                    Array.Copy(imageBufferView.Buffer.BufferData, imageBufferView.byteOffset, imageData, 0, imageData.Length);
                }

                if (texture == null)
                {
                    if (gltfObject.UseBackgroundThread) await Update;
                    // TODO Load texture async
                    texture = new Texture2D(2, 2);
                    gltfImage.Texture = texture;
                    gltfImage.Texture.LoadImage(imageData);
                }
                else
                {
                    gltfImage.Texture = texture;
                }

                gltfTexture.Texture = texture;

                if (gltfObject.UseBackgroundThread) await BackgroundThread;
            }
        }

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static void DecodeUlongFromByte(byte[] data, int offset, out ulong decodedData)
        {
            decodedData = 0;
            byte[] dataCopy = new byte[8];
            Array.Copy(data, (long)offset, dataCopy, 0, 8);
            decodedData = BitConverter.ToUInt64(dataCopy, 0);
        }

19 View Source File : ObservableList.cs
License : The Unlicense
Project Creator : aeroson

public void CopyTo(T[] array, int arrayIndex)
        {
            Array.Copy(WrappedList.Elements, 0, array, 0, WrappedList.Count);
        }

19 View Source File : TMP_TextInfo.cs
License : MIT License
Project Creator : Alword

public TMP_MeshInfo[] CopyMeshInfoVertexData()
        {
            if (m_CachedMeshInfo == null || m_CachedMeshInfo.Length != meshInfo.Length)
            {
                m_CachedMeshInfo = new TMP_MeshInfo[meshInfo.Length];

                // Initialize all the vertex data arrays
                for (int i = 0; i < m_CachedMeshInfo.Length; i++)
                {
                    int length = meshInfo[i].vertices.Length;

                    m_CachedMeshInfo[i].vertices = new Vector3[length];
                    m_CachedMeshInfo[i].uvs0 = new Vector2[length];
                    m_CachedMeshInfo[i].uvs2 = new Vector2[length];
                    m_CachedMeshInfo[i].colors32 = new Color32[length];

                    //m_CachedMeshInfo[i].normals = new Vector3[length];
                    //m_CachedMeshInfo[i].tangents = new Vector4[length];
                    //m_CachedMeshInfo[i].triangles = new int[meshInfo[i].triangles.Length];
                }
            }

            for (int i = 0; i < m_CachedMeshInfo.Length; i++)
            {
                int length = meshInfo[i].vertices.Length;

                if (m_CachedMeshInfo[i].vertices.Length != length)
                {
                    m_CachedMeshInfo[i].vertices = new Vector3[length];
                    m_CachedMeshInfo[i].uvs0 = new Vector2[length];
                    m_CachedMeshInfo[i].uvs2 = new Vector2[length];
                    m_CachedMeshInfo[i].colors32 = new Color32[length];

                    //m_CachedMeshInfo[i].normals = new Vector3[length];
                    //m_CachedMeshInfo[i].tangents = new Vector4[length];
                    //m_CachedMeshInfo[i].triangles = new int[meshInfo[i].triangles.Length];
                }


                // Only copy the primary vertex data
                Array.Copy(meshInfo[i].vertices, m_CachedMeshInfo[i].vertices, length);
                Array.Copy(meshInfo[i].uvs0, m_CachedMeshInfo[i].uvs0, length);
                Array.Copy(meshInfo[i].uvs2, m_CachedMeshInfo[i].uvs2, length);
                Array.Copy(meshInfo[i].colors32, m_CachedMeshInfo[i].colors32, length);

                //Array.Copy(meshInfo[i].normals, m_CachedMeshInfo[i].normals, length);
                //Array.Copy(meshInfo[i].tangents, m_CachedMeshInfo[i].tangents, length);
                //Array.Copy(meshInfo[i].triangles, m_CachedMeshInfo[i].triangles, meshInfo[i].triangles.Length);
            }

            return m_CachedMeshInfo;
        }

19 View Source File : UMAGeneratorBase.cs
License : Apache License 2.0
Project Creator : A7ocin

public void SaveAnimatorState(Animator animator)
			{
				int layerCount = animator.layerCount;
				stateHashes = new int[layerCount];
				stateTimes = new float[layerCount];
				parameters = new AnimatorControllerParameter[animator.parameterCount];

				for (int i = 0; i < layerCount; i++)
				{
					var state = animator.GetCurrentAnimatorStateInfo(i);
					stateHashes[i] = state.fullPathHash;
					stateTimes[i] = Mathf.Max(0, state.normalizedTime + Time.deltaTime / state.length);
				}

				Array.Copy(animator.parameters, parameters, animator.parameterCount);

				foreach(AnimatorControllerParameter param in parameters)
				{
					switch(param.type)
					{
						case AnimatorControllerParameterType.Bool:
							param.defaultBool = animator.GetBool(param.nameHash);
							break;
						case AnimatorControllerParameterType.Float:
							param.defaultFloat = animator.GetFloat(param.nameHash);
							break;
						case AnimatorControllerParameterType.Int:
							param.defaultInt = animator.GetInteger(param.nameHash);
							break;
					}
				}
			}

19 View Source File : DataBuffer.cs
License : MIT License
Project Creator : AndreasAmMueller

public byte[] GetBytes(int index, int count)
		{
			if (index < 0 || Length <= index)
				throw new ArgumentOutOfRangeException(nameof(index));

			if (Length < index + count)
				throw new ArgumentOutOfRangeException(nameof(count));

			byte[] bytes = new byte[count];
			Array.Copy(Buffer, index, bytes, 0, count);

			return bytes;
		}

19 View Source File : Texture.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public void SetTextureData(int level, byte[] data)
        {
            uint offset = 0;
            for (var i = 0; i < level; i++)
            {
                offset += GetTextureDataSize(i);
            }
            var size = GetTextureDataSize(level);

            Array.Copy(data, 0, TextureData, offset, size);
        }

19 View Source File : Program.cs
License : The Unlicense
Project Creator : AigioL

static void Main(string[] args)
        {
            TryMain();
            void TryMain()
            {
                try
                {
                    Main();
                }
                catch (Exception ex)
                {
                    var index = byte.MinValue;
                    while (ex != null)
                    {
                        if (index++ > sbyte.MaxValue) break;
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        ex = ex.InnerException;
                    }
                }
                Console.ReadLine();
            }
            void Main()
            {
                // ReSharper disable PossibleNullReferenceException
                var entryreplacedembly = replacedembly.GetEntryreplacedembly();
                var replacedle = entryreplacedembly.FullName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
                // ReSharper disable once replacedignNullToNotNullAttribute
                if (!replacedle.IsNullOrWhiteSpace()) Console.replacedle = replacedle;
                var rootPath = Path.GetDirectoryName(entryreplacedembly.Location);
                if (rootPath == null) throw new ArgumentNullException(nameof(rootPath));
                var sofilepath = args?.FirstOrDefault(x => x != null && File.Exists(x) && Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase));
                if (sofilepath == null)
                {
                    var sofilepaths = Directory.GetFiles(rootPath).Where(x => Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase)).ToArray();
                    sofilepath =
                       sofilepaths.FirstOrDefault(x => Path.GetFileName(x).Equals(GetSoDefaultFileName(), StringComparison.OrdinalIgnoreCase)) ??
                       sofilepaths.FirstOrDefault();
                }
                if (sofilepath == null) ReadLineAndExit("Can not find the .so file.");
                // ReSharper disable once replacedignNullToNotNullAttribute
                var bytes = File.ReadAllBytes(sofilepath);
                var elf = Elf.FromFile(sofilepath);
                var rodata = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".rodata"));
                if (rodata == null) ReadLineAndExit(".rodata not found.");
                var packedFiles = new List<string>();
                var addr = (uint)rodata.Addr;
                while (true)
                {
                    //up to 16 bytes of alignment
                    uint i;
                    for (i = 0; i < 16; i++)
                        if (bytes[addr + i] != 0)
                            break;

                    if (i == 16)
                        break; //We found all the files
                    addr += i;

                    var name = GetString(bytes, addr);
                    if (name.IsNullOrWhiteSpace())
                        break;

                    //We only care about dlls
                    if (!name.EndsWith(".dll"))
                        break;

                    packedFiles.Add(name);
                    addr += (uint)name.Length + 1u;
                }
                var data = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".data"));
                if (data == null) ReadLineAndExit(".data not found.");
                int ixGzip = 0;
                addr = (uint)data.Offset;
                var output = Path.Combine(rootPath, "replacedemblies");
                if (!Directory.Exists(output)) Directory.CreateDirectory(output);
                Console.WriteLine($"output:{output}");
                foreach (var item in packedFiles)
                {
                    ixGzip = findNextGZIPIndex(bytes, ixGzip);
                    if (ixGzip > 0)
                    {
                        var ptr = ixGzip;
                        var length = GetBigEndianUInt32(bytes, addr + 8);
                        var compressedbytes = new byte[length];
                        if (ptr + length <= bytes.LongLength)
                        {
                            Array.Copy(bytes, ptr, compressedbytes, 0, length);
                            try
                            {
                                var decompbytes = Decompress(compressedbytes);
                                var path = Path.Combine(output, item);
                                File.WriteAllBytes(path, decompbytes);
                                Console.WriteLine($"file:{item}");
                                addr += 0x10;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Failed to decompress file: {item} {e.Message}.");
                            }
                        }
                    }
                }
                TryOpenDir(output);
                // ReSharper restore PossibleNullReferenceException
            }
            void ReadLineAndExit(string writeLine = null)
            {
                if (writeLine != null) Console.WriteLine(writeLine);
                Console.ReadLine();
                Environment.Exit(0);
            }
            string GetSoFileExtension() => ".so";
            string GetSoDefaultFileName() => "libmonodroid_bundle_app" + GetSoFileExtension();
            string GetString(byte[] bytes, uint address)
            {
                int maxLength = 255;
                for (int i = (int)address; i < address + maxLength; i++)
                {
                    if (bytes[i] == 0)
                    {
                        maxLength = i - (int)address;
                        break;
                    }
                }
                var buffer = new byte[maxLength];
                Array.Copy(bytes, address, buffer, 0, maxLength);
                return Encoding.ASCII.GetString(buffer);
            }
            int findNextGZIPIndex(byte[] bytes, int ixGzip)
            {
                for (var j = ixGzip + 2; j < bytes.Length; j++)
                {
                    if (bytes[j - 1] == 0x1f && bytes[j] == 0x8b)
                    {
                        ixGzip = j - 1;
                        return ixGzip;
                    }
                }
                return 0;
            }
            byte[] Decompress(byte[] data)
            {
                using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var resultStream = new MemoryStream())
                {
                    zipStream.CopyTo(resultStream);
                    return resultStream.ToArray();
                }
            }
            uint GetBigEndianUInt32(byte[] bytes, uint address)
            {
                var byte1 = (uint)bytes[(int)address + 3] << 24;
                var byte2 = (uint)bytes[(int)address + 2] << 16;
                var byte3 = (uint)bytes[(int)address + 1] << 8;
                var byte4 = bytes[(int)address];
                return byte1 + byte2 + byte3 + byte4;
            }
            void TryOpenDir(string dirpath)
            {
                try
                {
                    Process.Start(dirpath);
                }
                catch
                {
                    // ignored
                }
            }
        }

19 View Source File : FoldingManager.cs
License : MIT License
Project Creator : Abdesol

internal void RemoveFromTextView(TextView textView)
		{
			int pos = textViews.IndexOf(textView);
			if (pos < 0)
				throw new ArgumentException();
			textViews.RemoveAt(pos);
			foreach (FoldingSection fs in foldings) {
				if (fs.collapsedSections != null) {
					var c = new CollapsedLineSection[textViews.Count];
					Array.Copy(fs.collapsedSections, 0, c, 0, pos);
					fs.collapsedSections[pos].Uncollapse();
					Array.Copy(fs.collapsedSections, pos + 1, c, pos, c.Length - pos);
					fs.collapsedSections = c;
				}
			}
		}

19 View Source File : RustTuple.cs
License : Apache License 2.0
Project Creator : ajuna-network

public override void Decode(byte[] byteArray, ref int p)
        {
            var start = p;

            Value = new IType[2];

            var t1 = new T1();
            t1.Decode(byteArray, ref p);
            Value[0] = t1;

            var t2 = new T2();
            t2.Decode(byteArray, ref p);
            Value[1] = t2;

            _size = p - start;

            Bytes = new byte[_size];
            Array.Copy(byteArray, start, Bytes, 0, _size);
        }

19 View Source File : RegistryKey.cs
License : MIT License
Project Creator : ADeltaX

private RegistryValue AddRegistryValue(string name)
        {
            byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4);
            if (valueList == null)
            {
                valueList = new byte[0];
            }

            int insertIdx = 0;
            while (insertIdx < _cell.NumValues)
            {
                int valueCellIndex = EndianUtilities.ToInt32LittleEndian(valueList, insertIdx * 4);
                ValueCell cell = _hive.GetCell<ValueCell>(valueCellIndex);
                if (string.Compare(name, cell.Name, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    break;
                }

                ++insertIdx;
            }

            // Allocate a new value cell (note _hive.UpdateCell does actual allocation).
            ValueCell valueCell = new ValueCell(name);
            _hive.UpdateCell(valueCell, true);

            // Update the value list, re-allocating if necessary
            byte[] newValueList = new byte[_cell.NumValues * 4 + 4];
            Array.Copy(valueList, 0, newValueList, 0, insertIdx * 4);
            EndianUtilities.WriteBytesLittleEndian(valueCell.Index, newValueList, insertIdx * 4);
            Array.Copy(valueList, insertIdx * 4, newValueList, insertIdx * 4 + 4, (_cell.NumValues - insertIdx) * 4);
            if (_cell.ValueListIndex == -1 ||
                !_hive.WriteRawCellData(_cell.ValueListIndex, newValueList, 0, newValueList.Length))
            {
                int newListCellIndex = _hive.AllocateRawCell(MathUtilities.RoundUp(newValueList.Length, 8));
                _hive.WriteRawCellData(newListCellIndex, newValueList, 0, newValueList.Length);

                if (_cell.ValueListIndex != -1)
                {
                    _hive.FreeCell(_cell.ValueListIndex);
                }

                _cell.ValueListIndex = newListCellIndex;
            }

            // Record the new value and save this cell
            _cell.NumValues++;
            _hive.UpdateCell(_cell, false);

            // Finally, set the data in the value cell
            return new RegistryValue(_hive, valueCell);
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public void CutStream(long offset, long length)
        {
            byte[] data = GetStreamData();
            byte[] buffer = new byte[length];
            Array.Copy(data, offset, buffer, 0, length);
            this.stream = new MemoryStream();
            MemoryStream m = new MemoryStream(buffer);
            this.stream = new MemoryStream();
            m.CopyTo(this.stream);
            this.offset = 0;
            bit = 0;
        }

19 View Source File : SpanHelper.cs
License : MIT License
Project Creator : Alan-FGR

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Copy<T>(ref Array<T> source, int sourceIndex, ref Array<T> target, int targetIndex, int count)
        {
            Validate<T, Array<T>, Array<T>>(ref source, sourceIndex, ref target, targetIndex, count);
            var byteCount = count * Unsafe.SizeOf<T>();
            Array.Copy(source.Memory, sourceIndex, target.Memory, targetIndex, count);
        }

19 View Source File : SecretSharingExtensions.cs
License : MIT License
Project Creator : AElfProject

public static byte[] ToBytesArray(this BigInteger integer)
        {
            var tempBytes = integer.ToByteArray().Reverse().ToArray();
            var result = new byte[tempBytes.Length-1];
            Array.Copy(tempBytes,0,result,0,result.Length);

            return result;
        }

19 View Source File : ImmutableDictionary.cs
License : MIT License
Project Creator : alexandrnikitin

internal override ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value, uint hash, int shift)
        {
            var bit = 1U << (int) ((hash >> shift) & Mask);
            if ((_bitmapNodes & bit) != 0)
            {
                var newNodes = new ImmutableDictionary<TKey, TValue>[_nodes.Length];
                Array.Copy(_nodes, newNodes, _nodes.Length);
                var index = Popcnt.PopCount(_bitmapNodes & (bit - 1));
                newNodes[index] = _nodes[index].Add(key, value, hash, shift + Shift);
                return new BitMapNode<TKey, TValue, TValues>(_bitmapNodes, newNodes, _bitmapValues, _values);
            }
            else if ((_bitmapValues & bit) != 0)
            {
                // TODO collisions and same value
                var newNodes = new ImmutableDictionary<TKey, TValue>[_nodes.Length + 1];
                var index = Popcnt.PopCount(_bitmapNodes & (bit - 1));
                Array.Copy(_nodes, newNodes, index);
                Array.Copy(_nodes, index, newNodes, index + 1, _nodes.Length - index);

                var indexValues = Popcnt.PopCount(_bitmapValues & (bit - 1));
                var key2 = _values.GetKey(indexValues);
                var value2 = _values.GetValue(indexValues);
                newNodes[index] = BitMapNode<TKey, TValue, TValues>.From(key, value, hash, shift + Shift, key2, value2);
                return _values.Shrink(_bitmapNodes | bit, newNodes, _bitmapValues ^ bit, (uint) indexValues);
            }
            else
            {
                var index = (uint)Popcnt.PopCount(_bitmapValues & (bit - 1));
                return _values.Add(key, value, _bitmapNodes, _nodes, _bitmapValues | bit, index);
            }
        }

19 View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static GltfObject GetGltfObjectFromGlb(byte[] glbData)
        {
            const int stride = sizeof(uint);

            var magicNumber = BitConverter.ToUInt32(glbData, 0);
            var version = BitConverter.ToUInt32(glbData, stride);
            var length = BitConverter.ToUInt32(glbData, stride * 2);

            if (magicNumber != GltfMagicNumber)
            {
                Debug.LogError("File is not a glb object!");
                return null;
            }

            if (version != 2)
            {
                Debug.LogError("Glb file version mismatch! Glb must use version 2");
                return null;
            }

            if (length != glbData.Length)
            {
                Debug.LogError("Glb file size does not match the glb header defined size");
                return null;
            }

            var chunk0Length = (int)BitConverter.ToUInt32(glbData, stride * 3);
            var chunk0Type = BitConverter.ToUInt32(glbData, stride * 4);

            if (chunk0Type != (ulong)GltfChunkType.Json)
            {
                Debug.LogError("Expected chunk 0 to be Json data!");
                return null;
            }

            var jsonChunk = Encoding.ASCII.GetString(glbData, stride * 5, chunk0Length);
            var gltfObject = GetGltfObjectFromJson(jsonChunk);
            var chunk1Length = (int)BitConverter.ToUInt32(glbData, stride * 5 + chunk0Length);
            var chunk1Type = BitConverter.ToUInt32(glbData, stride * 6 + chunk0Length);

            if (chunk1Type != (ulong)GltfChunkType.BIN)
            {
                Debug.LogError("Expected chunk 1 to be BIN data!");
                return null;
            }

            // Per the spec, "byte length of BIN chunk could be up to 3 bytes bigger than JSON-defined buffer.byteLength to satisfy GLB padding requirements"
            // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-stored-buffer
            Debug.replacedert(gltfObject.buffers[0].byteLength <= chunk1Length && gltfObject.buffers[0].byteLength >= chunk1Length - 3, "chunk 1 & buffer 0 length mismatch");

            gltfObject.buffers[0].BufferData = new byte[chunk1Length];
            Array.Copy(glbData, stride * 7 + chunk0Length, gltfObject.buffers[0].BufferData, 0, chunk1Length);

            return gltfObject;
        }

19 View Source File : GarbageHolder.cs
License : Apache License 2.0
Project Creator : alexyakunin

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void TryReleaseGarbage(int bucketIndex, long generationCount)
        {
            while (generationCount != 0 && bucketIndex < _buckets.Length) {
                ref var collected = ref _collected[bucketIndex]; // ref is just to speed this up
                var remaining = generationCount - collected;
                collected = generationCount;
                if (remaining >= BucketSize)
                    remaining = BucketSize;
                var bucket = _buckets[bucketIndex];
                Array.Copy(bucket, remaining, bucket, 0, BucketSize - remaining);
                for (var i = remaining; i < BucketSize; i++)
                    bucket[i] = new List<object>();

                // Kind of a tail call
                bucketIndex++;
                generationCount /= BucketSize;
            }
        }

19 View Source File : AudioPlaybackEngine.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public int Read(float[] buffer, int offset, int count)
        {
            var availableSamples = cachedSound.AudioData.Length - position;
            var samplesToCopy = Math.Min(availableSamples, count);
            Array.Copy(cachedSound.AudioData, position, buffer, offset, samplesToCopy);
            position += samplesToCopy;
            return (int)samplesToCopy;
        }

19 View Source File : TorrentInfo.cs
License : MIT License
Project Creator : aljazsim

public static bool TryLoad(byte[] data, out TorrentInfo torrentInfo)
        {
            data.CannotBeNullOrEmpty();

            BEncodedValue value;
            BEncodedDictionary general;
            BEncodedDictionary info;
            List<TorrentFileInfo> files = new List<TorrentFileInfo>();
            long pieceLength;
            List<string> pieceHashes = new List<string>();
            bool isPrivate = false;
            Uri tmpUri;
            List<Uri> announceList = new List<Uri>();
            DateTime? creationDate = null;
            string comment = null;
            string createdBy = null;
            Encoding encoding = Encoding.ASCII;
            string filePath;
            long fileLength = 0;
            string fileHash;
            string tmpString;
            BEncodedString infoKey = new BEncodedString("info");
            BEncodedString pieceLengthKey = new BEncodedString("piece length");
            BEncodedString piecesKey = new BEncodedString("pieces");
            BEncodedString privateKey = new BEncodedString("private");
            BEncodedString nameKey = new BEncodedString("name");
            BEncodedString lengthKey = new BEncodedString("length");
            BEncodedString md5sumKey = new BEncodedString("md5sum");
            BEncodedString filesKey = new BEncodedString("files");
            BEncodedString pathKey = new BEncodedString("path");
            BEncodedString announceKey = new BEncodedString("announce");
            BEncodedString announceListKey = new BEncodedString("announce-list");
            BEncodedString creationDateKey = new BEncodedString("creation date");
            BEncodedString commentKey = new BEncodedString("comment");
            BEncodedString createdByKey = new BEncodedString("created by");
            BEncodedString encodingKey = new BEncodedString("encoding");

            torrentInfo = null;

            try
            {
                value = BEncodedValue.Decode(data);
            }
            catch (BEncodingException)
            {
                return false;
            }

            if (value is BEncodedDictionary)
            {
                general = value as BEncodedDictionary;

                if (general.ContainsKey(infoKey) &&
                    general[infoKey] is BEncodedDictionary)
                {
                    info = general[infoKey] as BEncodedDictionary;

                    // piece length
                    if (info.ContainsKey(pieceLengthKey) &&
                        info[pieceLengthKey] is BEncodedNumber)
                    {
                        pieceLength = info[pieceLengthKey].As<BEncodedNumber>().Number;
                    }
                    else
                    {
                        return false;
                    }

                    // pieces
                    if (info.ContainsKey(piecesKey) &&
                        info[piecesKey] is BEncodedString &&
                        info[piecesKey].As<BEncodedString>().TextBytes.Length % 20 == 0)
                    {
                        for (int i = 0; i < info[piecesKey].As<BEncodedString>().TextBytes.Length; i += 20)
                        {
                            byte[] tmpBytes = new byte[20];

                            Array.Copy(info[piecesKey].As<BEncodedString>().TextBytes, i, tmpBytes, 0, tmpBytes.Length);

                            pieceHashes.Add(tmpBytes.ToHexaDecimalString());
                        }

                        if (pieceHashes.Count == 0)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }

                    // is private
                    if (info.ContainsKey(privateKey) &&
                        info[privateKey] is BEncodedNumber)
                    {
                        isPrivate = info[privateKey].As<BEncodedNumber>().Number == 1;
                    }

                    // files
                    if (info.ContainsKey(nameKey) &&
                        info[nameKey] is BEncodedString &&
                        info.ContainsKey(lengthKey) &&
                        info[lengthKey] is BEncodedNumber)
                    {
                        // single file
                        filePath = info[nameKey].As<BEncodedString>().Text;
                        fileLength = info[lengthKey].As<BEncodedNumber>().Number;

                        if (info.ContainsKey(md5sumKey) &&
                            info[md5sumKey] is BEncodedString)
                        {
                            fileHash = info[md5sumKey].As<BEncodedString>().Text;
                        }
                        else
                        {
                            fileHash = null;
                        }

                        files.Add(new TorrentFileInfo(filePath, fileHash, fileLength));
                    }
                    else if (info.ContainsKey(nameKey) &&
                             info[nameKey] is BEncodedString &&
                             info.ContainsKey(filesKey) &&
                             info[filesKey] is BEncodedList)
                    {
                        tmpString = info[nameKey].As<BEncodedString>().Text;

                        // multi file
                        foreach (var item in info[filesKey].As<BEncodedList>())
                        {
                            if (item is BEncodedDictionary &&
                                item.As<BEncodedDictionary>().ContainsKey(pathKey) &&
                                item.As<BEncodedDictionary>()[pathKey] is BEncodedList &&
                                item.As<BEncodedDictionary>()[pathKey].As<BEncodedList>().All(x => x is BEncodedString) &&
                                item.As<BEncodedDictionary>().ContainsKey(lengthKey) &&
                                item.As<BEncodedDictionary>()[lengthKey] is BEncodedNumber)
                            {
                                filePath = Path.Combine(tmpString, Path.Combine(item.As<BEncodedDictionary>()[pathKey].As<BEncodedList>().Select(x => x.As<BEncodedString>().Text).ToArray()));
                                fileLength = item.As<BEncodedDictionary>()[lengthKey].As<BEncodedNumber>().Number;

                                if (item.As<BEncodedDictionary>().ContainsKey(md5sumKey) &&
                                    item.As<BEncodedDictionary>()[md5sumKey] is BEncodedString)
                                {
                                    fileHash = item.As<BEncodedDictionary>()[md5sumKey].As<BEncodedString>().Text;
                                }
                                else
                                {
                                    fileHash = null;
                                }

                                files.Add(new TorrentFileInfo(filePath, fileHash, fileLength));
                            }
                            else
                            {
                                return false;
                            }
                        }

                        if (files.Count == 0)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }

                // announce
                if (general.ContainsKey(announceKey) &&
                    general[announceKey] is BEncodedString &&
                    Uri.TryCreate(general[announceKey].As<BEncodedString>().Text, UriKind.Absolute, out tmpUri))
                {
                    announceList.Add(tmpUri);
                }
                else
                {
                    return false;
                }

                // announce list
                if (general.ContainsKey(announceListKey) &&
                    general[announceListKey] is BEncodedList)
                {
                    foreach (var item in general[announceListKey].As<BEncodedList>())
                    {
                        if (item is BEncodedList)
                        {
                            foreach (var item2 in item.As<BEncodedList>())
                            {
                                if (Uri.TryCreate(item2.As<BEncodedString>().Text, UriKind.Absolute, out tmpUri))
                                {
                                    announceList.Add(tmpUri);
                                }
                            }
                        }
                    }

                    announceList = announceList.Select(x => x.AbsoluteUri).Distinct().Select(x => new Uri(x)).ToList();
                }

                // creation adte
                if (general.ContainsKey(creationDateKey) &&
                    general[creationDateKey] is BEncodedNumber)
                {
                    creationDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(general[creationDateKey].As<BEncodedNumber>().Number).ToLocalTime();
                }

                // comment
                if (general.ContainsKey(commentKey) &&
                    general[commentKey] is BEncodedString)
                {
                    comment = general[commentKey].As<BEncodedString>().Text;
                }

                // created by
                if (general.ContainsKey(createdByKey) &&
                    general[createdByKey] is BEncodedString)
                {
                    createdBy = general[createdByKey].As<BEncodedString>().Text;
                }

                // encoding
                if (general.ContainsKey(encodingKey) &&
                    general[encodingKey] is BEncodedString)
                {
                    if (general[encodingKey].As<BEncodedString>().Text == "UTF8")
                    {
                        encoding = Encoding.UTF8;
                    }
                }

                torrentInfo = new TorrentInfo(
                    general,
                    info.Encode().CalculateSha1Hash().ToHexaDecimalString(),
                    pieceLength,
                    new ReadOnlyCollection<string>(pieceHashes),
                    isPrivate,
                    new ReadOnlyCollection<Uri>(announceList),
                    creationDate,
                    comment,
                    createdBy,
                    encoding,
                    new ReadOnlyCollection<TorrentFileInfo>(files));

                return true;
            }
            else
            {
                return false;
            }
        }

19 View Source File : SkinnedMeshCombiner.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void CombineMeshes(UMAMeshData target, CombineInstance[] sources, UMAData.BlendShapeSettings blendShapeSettings = null)
		{
			if (blendShapeSettings == null)
				blendShapeSettings = new UMAData.BlendShapeSettings();
            
			int vertexCount = 0;
			int bindPoseCount = 0;
			int transformHierarchyCount = 0;
			int blendShapeCount = 0;

			MeshComponents meshComponents = MeshComponents.none;
			int subMeshCount = FindTargetSubMeshCount(sources);
			var subMeshTriangleLength = new int[subMeshCount];
			replacedyzeSources(sources, subMeshTriangleLength, ref vertexCount, ref bindPoseCount, ref transformHierarchyCount, ref meshComponents, ref blendShapeCount);

			int[][] submeshTriangles = new int[subMeshCount][];
			for (int i = 0; i < subMeshTriangleLength.Length; i++)
			{
				submeshTriangles[i] = target.GetSubmeshBuffer(subMeshTriangleLength[i], i);
				subMeshTriangleLength[i] = 0;
			}

			bool has_normals = (meshComponents & MeshComponents.has_normals) != MeshComponents.none;
			bool has_tangents = (meshComponents & MeshComponents.has_tangents) != MeshComponents.none;
			bool has_uv = (meshComponents & MeshComponents.has_uv) != MeshComponents.none;
			bool has_uv2 = (meshComponents & MeshComponents.has_uv2) != MeshComponents.none;
			bool has_uv3 = (meshComponents & MeshComponents.has_uv3) != MeshComponents.none;
			bool has_uv4 = (meshComponents & MeshComponents.has_uv4) != MeshComponents.none;
			bool has_colors32 = (meshComponents & MeshComponents.has_colors32) != MeshComponents.none;
			bool has_blendShapes = (meshComponents & MeshComponents.has_blendShapes) != MeshComponents.none;
			if (blendShapeSettings.ignoreBlendShapes)
				has_blendShapes = false;
			bool has_clothSkinning = (meshComponents & MeshComponents.has_clothSkinning) != MeshComponents.none;

			Vector3[] vertices = EnsureArrayLength(target.vertices, vertexCount);
			BoneWeight[] boneWeights = EnsureArrayLength(target.unityBoneWeights, vertexCount);
			Vector3[] normals = has_normals ? EnsureArrayLength(target.normals, vertexCount) : null;
			Vector4[] tangents = has_tangents ? EnsureArrayLength(target.tangents, vertexCount) : null;
			Vector2[] uv = has_uv ? EnsureArrayLength(target.uv, vertexCount) : null;
			Vector2[] uv2 = has_uv2 ? EnsureArrayLength(target.uv2, vertexCount) : null;
			Vector2[] uv3 = has_uv3 ? EnsureArrayLength(target.uv3, vertexCount) : null;
			Vector2[] uv4 = has_uv4 ? EnsureArrayLength(target.uv4, vertexCount) : null;
			Color32[] colors32 = has_colors32 ? EnsureArrayLength(target.colors32, vertexCount) : null;
			UMABlendShape[] blendShapes = has_blendShapes ? new UMABlendShape[blendShapeCount] : null;
			UMATransform[] umaTransforms = EnsureArrayLength(target.umaBones, transformHierarchyCount);
			ClothSkinningCoefficient[] clothSkinning = has_clothSkinning ? EnsureArrayLength(target.clothSkinning, vertexCount) : null;
			Dictionary<Vector3, int> clothVertices = has_clothSkinning ? new Dictionary<Vector3, int>(vertexCount) : null;
			Dictionary<Vector3, int> localClothVertices = has_clothSkinning ? new Dictionary<Vector3, int>(vertexCount) : null;

			int boneCount = 0;
			foreach (var source in sources)
			{
				MergeSortedTransforms(umaTransforms, ref boneCount, source.meshData.umaBones);
			}
			int vertexIndex = 0;

			if (bonesCollection == null)
				bonesCollection = new Dictionary<int, BoneIndexEntry>(boneCount);
			else
				bonesCollection.Clear();
			if (bindPoses == null)
				bindPoses = new List<Matrix4x4>(bindPoseCount);
			else
				bindPoses.Clear();
			if (bonesList == null)
				bonesList = new List<int>(boneCount);
			else
				bonesList.Clear();

			int blendShapeIndex = 0;

			foreach (var source in sources)
			{
				int sourceVertexCount = source.meshData.vertices.Length;
				BuildBoneWeights(source.meshData.boneWeights, 0, boneWeights, vertexIndex, sourceVertexCount, source.meshData.boneNameHashes, source.meshData.bindPoses, bonesCollection, bindPoses, bonesList);

				Array.Copy(source.meshData.vertices, 0, vertices, vertexIndex, sourceVertexCount);

				if (has_normals)
				{
					if (source.meshData.normals != null && source.meshData.normals.Length > 0)
					{
						Array.Copy(source.meshData.normals, 0, normals, vertexIndex, sourceVertexCount);
					}
					else
					{
						FillArray(tangents, vertexIndex, sourceVertexCount, Vector3.zero);
					}
				}
				if (has_tangents)
				{
					if (source.meshData.tangents != null && source.meshData.tangents.Length > 0)
					{
						Array.Copy(source.meshData.tangents, 0, tangents, vertexIndex, sourceVertexCount);
					}
					else
					{
						FillArray(tangents, vertexIndex, sourceVertexCount, Vector4.zero);
					}
				}
				if (has_uv)
				{
					if (source.meshData.uv != null && source.meshData.uv.Length >= sourceVertexCount)
					{
						Array.Copy(source.meshData.uv, 0, uv, vertexIndex, sourceVertexCount);
					}
					else
					{
						FillArray(uv, vertexIndex, sourceVertexCount, Vector4.zero);
					}
				}
				if (has_uv2)
				{
					if (source.meshData.uv2 != null && source.meshData.uv2.Length >= sourceVertexCount)
					{
						Array.Copy(source.meshData.uv2, 0, uv2, vertexIndex, sourceVertexCount);
					}
					else
					{
						FillArray(uv2, vertexIndex, sourceVertexCount, Vector4.zero);
					}
				}
				if (has_uv3)
				{
					if (source.meshData.uv3 != null && source.meshData.uv3.Length >= sourceVertexCount)
					{
						Array.Copy(source.meshData.uv3, 0, uv3, vertexIndex, sourceVertexCount);
					}
					else
					{
						FillArray(uv3, vertexIndex, sourceVertexCount, Vector4.zero);
					}
				}
				if (has_uv4)
				{
					if (source.meshData.uv4 != null && source.meshData.uv4.Length >= sourceVertexCount)
					{
						Array.Copy(source.meshData.uv4, 0, uv4, vertexIndex, sourceVertexCount);
					}
					else
					{
						FillArray(uv4, vertexIndex, sourceVertexCount, Vector4.zero);
					}
				}

				if (has_colors32)
				{
					if (source.meshData.colors32 != null && source.meshData.colors32.Length > 0)
					{
						Array.Copy(source.meshData.colors32, 0, colors32, vertexIndex, sourceVertexCount);
					}
					else
					{
						Color32 white32 = Color.white;
						FillArray(colors32, vertexIndex, sourceVertexCount, white32);
					}
				}

				if (has_blendShapes) 
				{
					if (source.meshData.blendShapes != null && source.meshData.blendShapes.Length > 0) 
					{
						for (int shapeIndex = 0; shapeIndex < source.meshData.blendShapes.Length; shapeIndex++)
						{
                            #region BlendShape Baking
                            if(blendShapeSettings.bakeBlendShapes != null || blendShapeSettings.bakeBlendShapes.Count == 0)
                            {
                                // If there are names in the bakeBlendShape dictionary and we find them in the meshData blendshape list, then lets bake them instead of adding them.
                                UMABlendShape currentShape = source.meshData.blendShapes[shapeIndex];
                                if( blendShapeSettings.bakeBlendShapes.ContainsKey(currentShape.shapeName))
                                {
                                    float weight = blendShapeSettings.bakeBlendShapes[currentShape.shapeName] * 100.0f;
									if (weight <= 0f) continue; // Baking in nothing, so skip it entirely

                                    // Let's find the frame this weight is in
                                    int frameIndex;
									int prevIndex;
                                    for (frameIndex = 0; frameIndex < currentShape.frames.Length; frameIndex++)
                                    {
                                        if (currentShape.frames[frameIndex].frameWeight >= weight)
                                            break;
                                    }

									// Let's calculate the weight for the frame we're in
									float frameWeight = 1f;
									float prevWeight = 0f;
									bool doLerp = false;
									// Weight is higher than the last frame, shape is over 100%
									if (frameIndex >= currentShape.frames.Length)
									{
										frameIndex = currentShape.frames.Length - 1;
										frameWeight = (weight / currentShape.frames[frameIndex].frameWeight);
									}
									else if (frameIndex > 0)
									{
										doLerp = true;
										prevWeight = currentShape.frames[frameIndex - 1].frameWeight;
										frameWeight = ((weight - prevWeight) / (currentShape.frames[frameIndex].frameWeight - prevWeight));
										prevWeight = 1f - frameWeight;
									}
									else
									{
										frameWeight = (weight / currentShape.frames[frameIndex].frameWeight);
									}
									prevIndex = frameIndex - 1;

                                    // The blend shape frames lerp between the deltas of two adjacent frames.
									int vertIndex = vertexIndex;
									for (int bakeIndex = 0; bakeIndex < currentShape.frames[frameIndex].deltaVertices.Length; bakeIndex++, vertIndex++)
                                    {
                                        // Add the current frame's deltas
										vertices[vertIndex] += currentShape.frames[frameIndex].deltaVertices[bakeIndex] * frameWeight;
                                        // Add in the previous frame's deltas
										if (doLerp)
											vertices[vertIndex] += currentShape.frames[prevIndex].deltaVertices[bakeIndex] * prevWeight;
                                    }

                                    if (has_normals)
                                    {
										vertIndex = vertexIndex;
										for (int bakeIndex = 0; bakeIndex < currentShape.frames[frameIndex].deltaNormals.Length; bakeIndex++, vertIndex++)
                                        {
											normals[vertIndex] += currentShape.frames[frameIndex].deltaNormals[bakeIndex] * frameWeight;
											if (doLerp)
												normals[vertIndex] += currentShape.frames[prevIndex].deltaNormals[bakeIndex] * prevWeight;
                                        }
                                    }

                                    if (has_tangents)
                                    {
										vertIndex = vertexIndex;
										for (int bakeIndex = 0; bakeIndex < currentShape.frames[frameIndex].deltaTangents.Length; bakeIndex++, vertIndex++)
                                        {
											tangents[vertIndex] += (Vector4)currentShape.frames[frameIndex].deltaTangents[bakeIndex] * frameWeight;
											if (doLerp)
												tangents[vertIndex] += (Vector4)currentShape.frames[prevIndex].deltaTangents[bakeIndex] * prevWeight;    
                                        }
                                    }
                                    continue; // If we bake then don't perform the rest of this interation of the loop.
                                }                                
                            }
                            #endregion

							bool nameAlreadyExists = false;
							int i = 0;
							//Probably this would be better with a dictionary
							for (i = 0; i < blendShapeIndex; i++) 
							{
								if (blendShapes[i].shapeName == source.meshData.blendShapes[shapeIndex].shapeName) 
								{
									nameAlreadyExists = true;
									break;
								}
							}

							if (nameAlreadyExists)//Lets add the vertices data to the existing blendShape
							{ 
								if (blendShapes[i].frames.Length != source.meshData.blendShapes[shapeIndex].frames.Length) 
								{
									Debug.LogError("SkinnedMeshCombiner: mesh blendShape frame counts don't match!");
									break;
								}
								for (int frameIndex = 0; frameIndex < source.meshData.blendShapes[shapeIndex].frames.Length; frameIndex++) {
									Array.Copy(source.meshData.blendShapes[shapeIndex].frames[frameIndex].deltaVertices, 0, blendShapes[i].frames[frameIndex].deltaVertices, vertexIndex, sourceVertexCount);
									Array.Copy(source.meshData.blendShapes[shapeIndex].frames[frameIndex].deltaNormals, 0, blendShapes[i].frames[frameIndex].deltaNormals, vertexIndex, sourceVertexCount);
									Array.Copy(source.meshData.blendShapes[shapeIndex].frames[frameIndex].deltaTangents, 0, blendShapes[i].frames[frameIndex].deltaTangents, vertexIndex, sourceVertexCount);
								}
							} 
							else
							{
								blendShapes[blendShapeIndex] = new UMABlendShape();
								blendShapes[blendShapeIndex].shapeName = source.meshData.blendShapes[shapeIndex].shapeName;
								blendShapes[blendShapeIndex].frames = new UMABlendFrame[source.meshData.blendShapes[shapeIndex].frames.Length];

								for (int frameIndex = 0; frameIndex < source.meshData.blendShapes[shapeIndex].frames.Length; frameIndex++) {
									blendShapes[blendShapeIndex].frames[frameIndex] = new UMABlendFrame(vertexCount); 
									blendShapes[blendShapeIndex].frames[frameIndex].frameWeight = source.meshData.blendShapes[shapeIndex].frames[frameIndex].frameWeight;
									Array.Copy(source.meshData.blendShapes[shapeIndex].frames[frameIndex].deltaVertices, 0, blendShapes[blendShapeIndex].frames[frameIndex].deltaVertices, vertexIndex, sourceVertexCount);
									Array.Copy(source.meshData.blendShapes[shapeIndex].frames[frameIndex].deltaNormals, 0, blendShapes[blendShapeIndex].frames[frameIndex].deltaNormals, vertexIndex, sourceVertexCount);
									Array.Copy(source.meshData.blendShapes[shapeIndex].frames[frameIndex].deltaTangents, 0, blendShapes[blendShapeIndex].frames[frameIndex].deltaTangents, vertexIndex, sourceVertexCount);
								}
								blendShapeIndex++;
							}
						}
					}
				}
				if (has_clothSkinning)
				{
					localClothVertices.Clear();
					if (source.meshData.clothSkinningSerialized != null && source.meshData.clothSkinningSerialized.Length > 0)
					{
						for (int i = 0; i < source.meshData.vertexCount; i++)
						{
							var vertice = source.meshData.vertices[i];
							if (!localClothVertices.ContainsKey(vertice))
							{
								int localCount = localClothVertices.Count;
								localClothVertices.Add(vertice, localCount);
								if (!clothVertices.ContainsKey(vertice))
								{
									ConvertData(ref source.meshData.clothSkinningSerialized[localCount], ref clothSkinning[clothVertices.Count]);
									clothVertices.Add(vertice, clothVertices.Count);
								}
								else
								{
									ConvertData(ref source.meshData.clothSkinningSerialized[localCount], ref clothSkinning[clothVertices[vertice]]);
								}
							}
						}
					}
					else
					{
						for (int i = 0; i < source.meshData.vertexCount; i++)
						{
							var vertice = source.meshData.vertices[i];
							if (!clothVertices.ContainsKey(vertice))
							{
								clothSkinning[clothVertices.Count].maxDistance = 0;
								clothSkinning[clothVertices.Count].collisionSphereDistance = float.MaxValue;
								clothVertices.Add(vertice, clothVertices.Count);
								localClothVertices.Add(vertice, clothVertices.Count);
							}
						}
					}
				}

				for (int i = 0; i < source.meshData.subMeshCount; i++)
				{
					if (source.targetSubmeshIndices[i] >= 0)
					{
						int[] subTriangles = source.meshData.submeshes[i].triangles;
						int triangleLength = subTriangles.Length;
						int destMesh = source.targetSubmeshIndices[i];

						if (source.triangleMask == null)
						{
							CopyIntArrayAdd(subTriangles, 0, submeshTriangles[destMesh], subMeshTriangleLength[destMesh], triangleLength, vertexIndex);
							subMeshTriangleLength[destMesh] += triangleLength;
						}
						else
						{
							MaskedCopyIntArrayAdd(subTriangles, 0, submeshTriangles[destMesh], subMeshTriangleLength[destMesh], triangleLength, vertexIndex, source.triangleMask[i] );
							subMeshTriangleLength[destMesh] += (triangleLength - (UMAUtils.GetCardinality(source.triangleMask[i])*3));
						}
					}
				}

				vertexIndex += sourceVertexCount;
			}

			if (vertexCount != vertexIndex)
			{
				Debug.LogError("Combined vertices size didn't match precomputed value!");
			}

			// fill in new values.
			target.vertexCount = vertexCount;
			target.vertices = vertices;
			target.unityBoneWeights = boneWeights;
			target.bindPoses = bindPoses.ToArray();
			target.normals = normals;
			target.tangents = tangents;
			target.uv = uv;
			target.uv2 = uv2;
			target.uv3 = uv3;
			target.uv4 = uv4;
			target.colors32 = colors32;

			if (has_blendShapes) 
				target.blendShapes = blendShapes;

			if (has_clothSkinning)
			{
				Array.Resize(ref clothSkinning, clothVertices.Count);
			}
			target.clothSkinning = clothSkinning;

			target.subMeshCount = subMeshCount;
			target.submeshes = new SubMeshTriangles[subMeshCount];
			target.umaBones = umaTransforms;
			target.umaBoneCount = boneCount;
			for (int i = 0; i < subMeshCount; i++)
			{
				target.submeshes[i].triangles = submeshTriangles[i];
			}
			target.boneNameHashes = bonesList.ToArray();
		}

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static void DecodeUTF8StringFromByte(byte[] data, int offset, int length, out string decodedData)
        {
            decodedData = "";
            byte[] dataCopy = new byte[length];
            Array.Copy(data, (long)offset, dataCopy, 0, length);

            decodedData = Encoding.UTF8.GetString(dataCopy).Replace("\u0000", "");
        }

19 View Source File : InterpolatedStatesManager.cs
License : The Unlicense
Project Creator : aeroson

public void GetStates(RigidTransform[] states)
        {
            lock (FlipLocker)
            {
                if (states.Length < manager.enreplacedies.Count)
                {
                    throw new ArgumentException("Array is not large enough to hold the buffer.", "states");
                }
                Array.Copy(this.states, states, manager.enreplacedies.Count);
            }
        }

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static void DecodeUIntFromByte(byte[] data, int offset, out uint decodedData)
        {
            decodedData = 0;
            byte[] dataCopy = new byte[4];
            Array.Copy(data, (long)offset, dataCopy, 0, 4);
            decodedData = BitConverter.ToUInt32(dataCopy, 0);
        }

19 View Source File : ResamplingOfGridDataSeries3D.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private WaterfallDataSeries3D<double> ResampleDataSeries(WaterfallDataSeries3D<double> dataSeries, double[] slicePositions)
        {
            var pointsPerSlice = dataSeries.XSize;
            var sliceCount = dataSeries.ZSize;

            var resamplerFactory = new PointResamplerFactory();

            var resamplingParams = new ResamplingParams
            {
                IsSortedData = true,
                IsEvenlySpacedData = true,
                IsCategoryData = false,
                ContainsNaN = false,
                ZeroLineY = 0.0,
                PointRange = new IndexRange(0, pointsPerSlice - 1),
                VisibleRange = dataSeries.XRange,
                ViewportWidth = Width > 0.0 ? (int) Width : 640,
                ResamplingPrecision = 1
            };

            var resampledSeriesesArray = new IPointSeries[sliceCount];
            var sliceAsXySeries = new XyDataSeries<double>(pointsPerSlice);
            var sliceAsXySeriesYValues = sliceAsXySeries.YValues as ISciList<double>;
            sliceAsXySeriesYValues.SetCount(pointsPerSlice);

            var xValues = new double[pointsPerSlice];
            var xRangeMin = (double)dataSeries.XRange.Min;
            var stepX = dataSeries.StepX;
            for (int i = 0; i < pointsPerSlice; i++)
            {
                xValues[i] = xRangeMin + stepX * i;
            }

            // Init the XY series by first slice of the waterfall data series 
            sliceAsXySeries.InsertRange(0, xValues, dataSeries.InternalArray[0]);
            resampledSeriesesArray[0] = sliceAsXySeries.ToPointSeries(resamplingParams, ResamplingMode.Auto, resamplerFactory, null);

            for (int i = 1; i < sliceCount; i++)
            {
                var curRow = dataSeries.GetRowAt(i);
                Array.Copy(curRow, sliceAsXySeriesYValues.ItemsArray, pointsPerSlice);

                resampledSeriesesArray[i] = sliceAsXySeries.ToPointSeries(resamplingParams, ResamplingMode.Auto, resamplerFactory, null);
            }

            var resampledPerPointsPerSlice = resampledSeriesesArray[0].Count;
            var resampledDataSeries = new WaterfallDataSeries3D<double>(resampledPerPointsPerSlice, slicePositions);
            resampledDataSeries.StartX = dataSeries.StartX;
            resampledDataSeries.StepX = dataSeries.StepX;
            for (int i = 0; i < sliceCount; i++)
            {
                resampledDataSeries.SetRowAt(i, resampledSeriesesArray[i].YValues.Items);
            }

            return resampledDataSeries;
        }

19 View Source File : ArrayExtension.cs
License : MIT License
Project Creator : AlphaYu

public static void Copy([NotNull] this Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
        {
            Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length);
        }

19 View Source File : SimpleBuffer.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

public override void Append(byte[] d, long index, long length) 
	{
		if (length == 0)
			return;
		
		if (data.Length > 0) {
			byte[] tmp = new byte[data.LongLength + length];
			data.CopyTo(tmp, 0);
			Array.Copy(d, index, tmp, data.LongLength, length);
			data = tmp;
		}
		else {
			data = new byte[length];
			Array.Copy(d, index, data, 0, length);
		}
	}

19 View Source File : Response.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public static Response Get(ResourceRef res, NameValueCollection param = null, AccessToken token = null, string responseType = "application/json", Response previous = null, CancellationToken ct = default)
        {
            // Create request.
            var request = WebRequest.Create(res.Uri);
            request.CachePolicy = CachePolicy;
            request.Proxy = null;
            if (token != null)
                token.AddToRequest(request);
            if (request is HttpWebRequest httpRequest)
            {
                httpRequest.UserAgent = UserAgent;
                httpRequest.Accept = responseType;
                if (previous != null && param != null)
                {
                    httpRequest.IfModifiedSince = previous.Timestamp;

                    if (previous.ETag != null)
                        httpRequest.Headers.Add("If-None-Match", previous.ETag);
                }
            }

            if (param != null)
            {
                // Send data.
                UTF8Encoding utf8 = new UTF8Encoding();
                var binBody = Encoding.ASCII.GetBytes(string.Join("&", param.Cast<string>().Select(e => string.Format("{0}={1}", HttpUtility.UrlEncode(e, utf8), HttpUtility.UrlEncode(param[e], utf8)))));
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = binBody.Length;
                try
                {
                    using (var requestStream = request.GetRequestStream())
                        requestStream.Write(binBody, 0, binBody.Length, ct);
                }
                catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorUploading, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
            }

            ct.ThrowIfCancellationRequested();

            // Wait for data to start comming in.
            WebResponse response;
            try { response = request.GetResponse(); }
            catch (WebException ex)
            {
                // When the content was not modified, return the previous one.
                if (ex.Response is HttpWebResponse httpResponse)
                {
                    if (httpResponse.StatusCode == HttpStatusCode.NotModified)
                    {
                        previous.IsFresh = false;
                        return previous;
                    }

                    throw new WebExceptionEx(ex, ct);
                }

                throw new AggregateException(Resources.Strings.ErrorDownloading, ex);
            }

            ct.ThrowIfCancellationRequested();

            using (response)
            {
                // Read the data.
                var data = new byte[0];
                using (var stream = response.GetResponseStream())
                {
                    var buffer = new byte[1048576];
                    for (; ; )
                    {
                        // Read data chunk.
                        var count = stream.Read(buffer, 0, buffer.Length, ct);
                        if (count == 0)
                            break;

                        // Append it to the data.
                        var newData = new byte[data.LongLength + count];
                        Array.Copy(data, newData, data.LongLength);
                        Array.Copy(buffer, 0, newData, data.LongLength, count);
                        data = newData;
                    }
                }

                if (res.PublicKeys != null)
                {
                    // Generate signature URI.
                    var uriBuilderSig = new UriBuilder(res.Uri);
                    uriBuilderSig.Path += ".minisig";

                    // Create signature request.
                    request = WebRequest.Create(uriBuilderSig.Uri);
                    request.CachePolicy = CachePolicy;
                    request.Proxy = null;
                    if (token != null)
                        token.AddToRequest(request);
                    if (request is HttpWebRequest httpRequestSig)
                    {
                        httpRequestSig.UserAgent = UserAgent;
                        httpRequestSig.Accept = "text/plain";
                    }

                    // Read the Minisign signature.
                    byte[] signature = null;
                    try
                    {
                        using (var responseSig = request.GetResponse())
                        using (var streamSig = responseSig.GetResponseStream())
                        {
                            ct.ThrowIfCancellationRequested();

                            using (var readerSig = new StreamReader(streamSig))
                            {
                                foreach (var l in readerSig.ReadToEnd(ct).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    if (l.Trim().StartsWith($"untrusted comment:"))
                                        continue;
                                    signature = Convert.FromBase64String(l);
                                    break;
                                }
                                if (signature == null)
                                    throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
                            }
                        }
                    }
                    catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorDownloadingSignature, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }

                    ct.ThrowIfCancellationRequested();

                    // Verify Minisign signature.
                    using (var s = new MemoryStream(signature, false))
                    using (var r = new BinaryReader(s))
                    {
                        if (r.ReadChar() != 'E')
                            throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
                        byte[] payload;
                        switch (r.ReadChar())
                        {
                            case 'd': // PureEdDSA
                                payload = data;
                                break;

                            case 'D': // HashedEdDSA
                                payload = new eduEd25519.BLAKE2b(512).ComputeHash(data);
                                break;

                            default:
                                throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
                        }
                        ulong keyId = r.ReadUInt64();
                        if (!res.PublicKeys.ContainsKey(keyId))
                            throw new SecurityException(Resources.Strings.ErrorUntrustedMinisignPublicKey);
                        var sig = new byte[64];
                        if (r.Read(sig, 0, 64) != 64)
                            throw new ArgumentException(Resources.Strings.ErrorInvalidMinisignSignature);
                        using (eduEd25519.ED25519 key = new eduEd25519.ED25519(res.PublicKeys[keyId]))
                            if (!key.VerifyDetached(payload, sig))
                                throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
                    }
                }

                return
                    response is HttpWebResponse webResponse ?
                    new Response()
                    {
                        Value = Encoding.UTF8.GetString(data),
                        Timestamp = DateTime.TryParse(webResponse.GetResponseHeader("Last-Modified"), out var timestamp) ? timestamp : default,
                        ETag = webResponse.GetResponseHeader("ETag"),
                        IsFresh = true
                    } :
                    new Response()
                    {
                        Value = Encoding.UTF8.GetString(data),
                        IsFresh = true
                    };
            }
        }

19 View Source File : LeapImageRetriever.cs
License : MIT License
Project Creator : 39M

public void UpdateTexture(Image image) {
        Array.Copy(image.Data, 0, _intermediateArray, 0, _intermediateArray.Length);
        _combinedTexture.LoadRawTextureData(_intermediateArray);
        _combinedTexture.Apply();
      }

19 View Source File : Memory.cs
License : MIT License
Project Creator : ancientproject

public void load(byte[] binary, int memOffset, int maxLen)
        {
            if (binary.Length % sizeof(long) != 0)
                _cpu.halt(0xD6);
            var bin = binary.Batch(sizeof(long)).Select(x => BitConverter.ToInt64(x.ToArray())).Reverse().ToArray();
            Array.Copy(bin, 0, mem, memOffset, maxLen);
        }

19 View Source File : Texture.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public byte[] GetTextureData(int level)
        {
            byte[] data;
            if (level == 0)
            {
                data = TextureData;
            }
            else
            {
                uint offset = 0;
                for(var i=0; i<level; i++)
                {
                    offset += GetTextureDataSize(i);
                }
                var size = GetTextureDataSize(level);

                data = new byte[size];
                Array.Copy(TextureData, offset, data, 0, size);
            }
            return data;
        }

19 View Source File : ImgTex.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void MergeTexture(byte[] data, uint dest_height, uint dest_width, ImgTex csi_merge_tex, uint tiling, ImgTex alphaMap, LandDefs.Rotation rot)
        {
            var imageData = csi_merge_tex.ImageData;

            var src_height = imageData != null ? imageData.Height : 0;
            var src_width = imageData != null ? imageData.Width : 0;

            var alphaData = alphaMap.ImageData;
            var alpha_width = alphaData != null ? alphaData.Width : 0;
            var alpha_height = alphaData != null ? alphaData.Height : 0;

            var alpha_scale = (float)dest_width / alpha_width;

            var pixelIdx = 0;
            var stepX = 0;
            var stepY = 0;

            switch (rot)
            {
                case LandDefs.Rotation.Rot0:
                    pixelIdx = 0;
                    stepX = 1;
                    stepY = src_width;
                    break;
                case LandDefs.Rotation.Rot90:
                    pixelIdx = src_width - 1;
                    stepX = src_width;
                    stepY = -1;
                    break;
                case LandDefs.Rotation.Rot180:
                    pixelIdx = src_width * src_height - 1;
                    stepX = -1;
                    stepY = -src_width;
                    break;
                case LandDefs.Rotation.Rot270:
                    pixelIdx = src_width * (src_height - 1);
                    stepX = -src_width;
                    stepY = -1;
                    break;
            }

            // alphaStep handles upscaling / downscaling
            var alphaStep = 1.0f / alpha_scale;

            // copy csi_merge_tex into dest buffer (data)
            Array.Copy(imageData.Data, data, imageData.Data.Length);

            // start walking the alpha map
            for (var _alphaY = 0.0f; _alphaY < alpha_height; _alphaY += alphaStep)
            {
                var alphaY = (int)Math.Round(_alphaY);

                for (var _alphaX = 0.0f; _alphaX < alpha_width; _alphaX += alphaStep)
                {
                    // TODO: handle rotation
                    var alphaX = (int)Math.Round(_alphaX);

                    var idx = (alphaY * alpha_width + alphaX) * 4;
                    var a = alphaData.Data[idx];
                    data[idx] = a;
                }
            }
        }

19 View Source File : ExpandableBufferWriter.cs
License : MIT License
Project Creator : 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public byte[] GetBufferedArrayWithKeepFirstBuffer()
        {
            if (complexBuffer.Spans.Length == 1)
            {
                return complexBuffer.CurrentSpan.Buffer;
            }

            FlushLastSpanBoundary();
            byte[] array = new byte[complexBuffer.Spans[0].Start + Buffered];
            //save first buffer start front port
            int copyLen = complexBuffer.Spans[0].Start + bufferedsRelativeSpan[0];
            Array.Copy(complexBuffer.Spans[0].Buffer, array, copyLen);

            int start = copyLen;
            for (int i = 1; i < complexBuffer.Spans.Length; i++)
            {
                if (bufferedsRelativeSpan[i] != 0)
                {
                    Unsafe.CopyBlock(ref array[start], ref complexBuffer.Spans[i].GetBufferStartRef(), (uint)bufferedsRelativeSpan[i]);
                    start += bufferedsRelativeSpan[i];
                }
            }
            return array;
        }

19 View Source File : RingBuffer.cs
License : MIT License
Project Creator : 39M

private void doubleCapacityIfFull() {
      if (_count >= _array.Length) {
        T[] newArray = new T[_array.Length * 2];

        uint front = getBackIndex();
        if (_front <= front) {
          //values do not wrap around, we can use a simple copy
          Array.Copy(_array, _front, newArray, 0, _count);
        } else {
          //values do wrap around, we need to use 2 copies
          uint backOffset = (uint)_array.Length - _front;
          Array.Copy(_array, _front, newArray, 0, backOffset);
          Array.Copy(_array, 0, newArray, backOffset, _count - backOffset);
        }

        _front = 0;
        _array = newArray;
        recalculateIndexMask();
      }
    }

19 View Source File : RopeTextReader.cs
License : MIT License
Project Creator : Abdesol

public override int Read(char[] buffer, int index, int count)
		{
			if (currentNode == null)
				return 0;
			int amountInCurrentNode = currentNode.length - indexInsideNode;
			if (count < amountInCurrentNode) {
				Array.Copy(currentNode.contents, indexInsideNode, buffer, index, count);
				indexInsideNode += count;
				return count;
			} else {
				// read to end of current node
				Array.Copy(currentNode.contents, indexInsideNode, buffer, index, amountInCurrentNode);
				GoToNextNode();
				return amountInCurrentNode;
			}
		}

19 View Source File : FsBufferedReaderWriter.cs
License : MIT License
Project Creator : Adoxio

public override object Clone()
		{
			// Lucene does input reader clone. So we need to handle it properly

			var copy = (FsBufferedReaderWriter)MemberwiseClone();
			copy.IsClone = true;

			copy.pageBuffer = new byte[this.PageSize];
			Array.Copy(this.pageBuffer, copy.pageBuffer, this.PageSize);

			return copy;
		}

19 View Source File : MicroSplatShaderGUI_Compiler.cs
License : MIT License
Project Creator : alelievr

public void Compile(Material m, string shaderName = null)
      {
         int hash = 0;
         for (int i = 0; i < m.shaderKeywords.Length; ++i)
         {
            hash += 31 + m.shaderKeywords[i].GetHashCode();
         }
         var path = replacedetDatabase.GetreplacedetPath(m.shader);
         string nm = m.shader.name;
         if (!string.IsNullOrEmpty(shaderName))
         {
            nm = shaderName;
         }
         string baseName = "Hidden/" + nm + "_Base" + hash.ToString();

         string terrainShader = Compile(m.shaderKeywords, nm, baseName);

         string blendShader = null;

         // strip extra feature from terrain blending to make it cheaper
         if (m.IsKeywordEnabled("_TERRAINBLENDING"))
         {
            List<string> blendKeywords = new List<string>(m.shaderKeywords);
            if (m.IsKeywordEnabled("_TBDISABLE_DETAILNOISE") && blendKeywords.Contains("_DETAILNOISE"))
            {
               blendKeywords.Remove("_DETAILNOISE");
            }
            if (m.IsKeywordEnabled("_TBDISABLE_DISTANCENOISE") && blendKeywords.Contains("_DISTANCENOISE"))
            {
               blendKeywords.Remove("_DISTANCENOISE");
            }
            if (m.IsKeywordEnabled("_TBDISABLE_DISTANCERESAMPLE") && blendKeywords.Contains("_DISTANCERESAMPLE"))
            {
               blendKeywords.Remove("_DISTANCERESAMPLE");
            }

            blendShader = Compile(blendKeywords.ToArray(), nm, null, true);
         }


         // generate fallback
         string[] oldKeywords = new string[m.shaderKeywords.Length];
         System.Array.Copy(m.shaderKeywords, oldKeywords, m.shaderKeywords.Length);
         m.DisableKeyword("_TESSDISTANCE");
         m.DisableKeyword("_TESSEDGE");
         m.DisableKeyword("_PARALLAX");
         m.DisableKeyword("_DETAILNOISE");

         // maybe reduce layers in distance? can cause a pop though..
         //m.DisableKeyword("_MAX3LAYER");
         //m.EnableKeyword("_MAX2LAYER");


         string fallback = Compile(m.shaderKeywords, baseName);
         m.shaderKeywords = oldKeywords;

         System.IO.File.WriteAllText(path, terrainShader);
         string fallbackPath = path.Replace(".shader", "_Base.shader");
         string terrainBlendPath = path.Replace(".shader", "_TerrainObjectBlend.shader");
         System.IO.File.WriteAllText(fallbackPath, fallback);
         if (blendShader != null)
         {
            System.IO.File.WriteAllText(terrainBlendPath, blendShader); 
         }

         EditorUtility.SetDirty(m);
         replacedetDatabase.Refresh();
         MicroSplatTerrain.SyncAll(); 
      }

See More Examples