Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.Copy(System.IntPtr, System.IntPtr[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
597 Examples
19
View Source File : MetadataCustomMarshaler.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public IntPtr MarshalManagedToNative(object ManagedObj)
{
if (ManagedObj == null)
{
return IntPtr.Zero;
}
WebPNative.MetadataParams metadata = (WebPNative.MetadataParams)ManagedObj;
IntPtr nativeStructure = Marshal.AllocHGlobal(NativeMetadataParamsSize);
unsafe
{
NativeMetadataParams* nativeMetadata = (NativeMetadataParams*)nativeStructure;
if (metadata.iccProfile != null && metadata.iccProfile.Length > 0)
{
nativeMetadata->iccProfile = Marshal.AllocHGlobal(metadata.iccProfile.Length);
Marshal.Copy(metadata.iccProfile, 0, nativeMetadata->iccProfile, metadata.iccProfile.Length);
nativeMetadata->iccProfileSize = new UIntPtr((uint)metadata.iccProfile.Length);
}
else
{
nativeMetadata->iccProfile = IntPtr.Zero;
nativeMetadata->iccProfileSize = UIntPtr.Zero;
}
if (metadata.exif != null && metadata.exif.Length > 0)
{
nativeMetadata->exif = Marshal.AllocHGlobal(metadata.exif.Length);
Marshal.Copy(metadata.exif, 0, nativeMetadata->exif, metadata.exif.Length);
nativeMetadata->exifSize = new UIntPtr((uint)metadata.exif.Length);
}
else
{
nativeMetadata->exif = IntPtr.Zero;
nativeMetadata->exifSize = UIntPtr.Zero;
}
if (metadata.xmp != null && metadata.xmp.Length > 0)
{
nativeMetadata->xmp = Marshal.AllocHGlobal(metadata.xmp.Length);
Marshal.Copy(metadata.xmp, 0, nativeMetadata->xmp, metadata.xmp.Length);
nativeMetadata->xmpSize = new UIntPtr((uint)metadata.xmp.Length);
}
else
{
nativeMetadata->xmp = IntPtr.Zero;
nativeMetadata->xmpSize = UIntPtr.Zero;
}
}
return nativeStructure;
}
19
View Source File : OpenVRRenderModel.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
{
var pRenderModel = System.IntPtr.Zero;
EVRRenderModelError error;
while (true)
{
error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
if (error != EVRRenderModelError.None)
{
Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
return null;
}
var renderModel = MarshalRenderModel(pRenderModel);
var vertices = new Vector3[renderModel.unVertexCount];
var normals = new Vector3[renderModel.unVertexCount];
var uv = new Vector2[renderModel.unVertexCount];
var type = typeof(RenderModel_Vertex_t);
for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
{
var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);
vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
}
int indexCount = (int)renderModel.unTriangleCount * 3;
var indices = new short[indexCount];
Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);
var triangles = new int[indexCount];
for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
{
triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
}
var mesh = new Mesh
{
vertices = vertices,
normals = normals,
uv = uv,
triangles = triangles
};
// Check cache before loading texture.
var material = materials[renderModel.diffuseTextureId] as Material;
if (material == null || material.mainTexture == null)
{
var pDiffuseTexture = System.IntPtr.Zero;
while (true)
{
error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
if (error != EVRRenderModelError.Loading)
{
break;
}
Sleep();
}
if (error == EVRRenderModelError.None)
{
var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
{
texture.Apply();
System.IntPtr texturePointer = texture.GetNativeTexturePtr();
while (true)
{
error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texturePointer);
if (error != EVRRenderModelError.Loading)
{
break;
}
Sleep();
}
}
else
{
var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);
var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
int iColor = 0;
for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
{
for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
{
var r = textureMapData[iColor++];
var g = textureMapData[iColor++];
var b = textureMapData[iColor++];
var a = textureMapData[iColor++];
colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
}
}
texture.SetPixels32(colors);
texture.Apply();
}
material = new Material(shader != null ? shader : Shader.Find("Mixed Reality Toolkit/Standard"))
{
mainTexture = texture
};
materials[renderModel.diffuseTextureId] = material;
renderModels.FreeTexture(pDiffuseTexture);
}
else
{
Debug.Log("Failed to load render model texture for render model " + renderModelName + ". Error: " + error.ToString());
}
}
// Delay freeing when we can since we'll often get multiple requests for the same model right
// after another (e.g. two controllers or two base stations).
#if UNITY_EDITOR
if (!Application.isPlaying)
{
renderModels.FreeRenderModel(pRenderModel);
}
else
#endif
{
StartCoroutine(FreeRenderModel(pRenderModel));
}
return new RenderModel(mesh, material);
}
19
View Source File : Packet.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public ulong ReadBytes(byte[] destination)
{
if ((ulong) destination.LongLength < size)
{
throw new System.ArgumentException(String.Format("Destination array was not big enough to hold {0} bytes", size));
}
Marshal.Copy(CAPI.ovr_Packet_GetBytes(packetHandle), destination, 0, (int) size);
return size;
}
19
View Source File : OVRHaptics.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public void Process()
{
var hapticsState = OVRPlugin.GetControllerHapticsState(m_controller);
float elapsedTime = Time.realtimeSinceStartup - m_prevSamplesQueuedTime;
if (m_prevSamplesQueued > 0)
{
int expectedSamples = m_prevSamplesQueued - (int)(elapsedTime * OVRHaptics.Config.SampleRateHz + 0.5f);
if (expectedSamples < 0)
expectedSamples = 0;
if ((hapticsState.SamplesQueued - expectedSamples) == 0)
m_numPredictionHits++;
else
m_numPredictionMisses++;
//Debug.Log(hapticsState.SamplesAvailable + "a " + hapticsState.SamplesQueued + "q " + expectedSamples + "e "
//+ "Prediction Accuracy: " + m_numPredictionHits / (float)(m_numPredictionMisses + m_numPredictionHits));
if ((expectedSamples > 0) && (hapticsState.SamplesQueued == 0))
{
m_numUnderruns++;
//Debug.LogError("Samples Underrun (" + m_controller + " #" + m_numUnderruns + ") -"
// + " Expected: " + expectedSamples
// + " Actual: " + hapticsState.SamplesQueued);
}
m_prevSamplesQueued = hapticsState.SamplesQueued;
m_prevSamplesQueuedTime = Time.realtimeSinceStartup;
}
int desiredSamplesCount = OVRHaptics.Config.OptimalBufferSamplesCount;
if (m_lowLatencyMode)
{
float sampleRateMs = 1000.0f / (float)OVRHaptics.Config.SampleRateHz;
float elapsedMs = elapsedTime * 1000.0f;
int samplesNeededPerFrame = (int)Mathf.Ceil(elapsedMs / sampleRateMs);
int lowLatencySamplesCount = OVRHaptics.Config.MinimumSafeSamplesQueued + samplesNeededPerFrame;
if (lowLatencySamplesCount < desiredSamplesCount)
desiredSamplesCount = lowLatencySamplesCount;
}
if (hapticsState.SamplesQueued > desiredSamplesCount)
return;
if (desiredSamplesCount > OVRHaptics.Config.MaximumBufferSamplesCount)
desiredSamplesCount = OVRHaptics.Config.MaximumBufferSamplesCount;
if (desiredSamplesCount > hapticsState.SamplesAvailable)
desiredSamplesCount = hapticsState.SamplesAvailable;
int acquiredSamplesCount = 0;
int clipIndex = 0;
while(acquiredSamplesCount < desiredSamplesCount && clipIndex < m_pendingClips.Count)
{
int numSamplesToCopy = desiredSamplesCount - acquiredSamplesCount;
int remainingSamplesInClip = m_pendingClips[clipIndex].Clip.Count - m_pendingClips[clipIndex].ReadCount;
if (numSamplesToCopy > remainingSamplesInClip)
numSamplesToCopy = remainingSamplesInClip;
if (numSamplesToCopy > 0)
{
int numBytes = numSamplesToCopy * OVRHaptics.Config.SampleSizeInBytes;
int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes;
int srcOffset = m_pendingClips[clipIndex].ReadCount * OVRHaptics.Config.SampleSizeInBytes;
Marshal.Copy(m_pendingClips[clipIndex].Clip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes);
m_pendingClips[clipIndex].ReadCount += numSamplesToCopy;
acquiredSamplesCount += numSamplesToCopy;
}
clipIndex++;
}
for (int i = m_pendingClips.Count - 1; i >= 0 && m_pendingClips.Count > 0; i--)
{
if (m_pendingClips[i].ReadCount >= m_pendingClips[i].Clip.Count)
m_pendingClips.RemoveAt(i);
}
if (m_paddingEnabled)
{
int desiredPadding = desiredSamplesCount - (hapticsState.SamplesQueued + acquiredSamplesCount);
if (desiredPadding < (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount))
desiredPadding = (OVRHaptics.Config.MinimumBufferSamplesCount - acquiredSamplesCount);
if (desiredPadding > hapticsState.SamplesAvailable)
desiredPadding = hapticsState.SamplesAvailable;
if (desiredPadding > 0)
{
int numBytes = desiredPadding * OVRHaptics.Config.SampleSizeInBytes;
int dstOffset = acquiredSamplesCount * OVRHaptics.Config.SampleSizeInBytes;
int srcOffset = 0;
Marshal.Copy(m_paddingClip.Samples, srcOffset, m_nativeBuffer.GetPointer(dstOffset), numBytes);
acquiredSamplesCount += desiredPadding;
}
}
if (acquiredSamplesCount > 0)
{
OVRPlugin.HapticsBuffer hapticsBuffer;
hapticsBuffer.Samples = m_nativeBuffer.GetPointer();
hapticsBuffer.SamplesCount = acquiredSamplesCount;
OVRPlugin.SetControllerHaptics(m_controller, hapticsBuffer);
hapticsState = OVRPlugin.GetControllerHapticsState(m_controller);
m_prevSamplesQueued = hapticsState.SamplesQueued;
m_prevSamplesQueuedTime = Time.realtimeSinceStartup;
}
}
19
View Source File : OVRBoundary.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public Vector3[] GetGeometry(OVRBoundary.BoundaryType boundaryType)
{
if (OVRManager.loadedXRDevice != OVRManager.XRDevice.Oculus)
{
#if !USING_XR_SDK && !REQUIRES_XR_SDK
if (Boundary.TryGetGeometry(cachedGeometryList, (boundaryType == BoundaryType.PlayArea) ? Boundary.Type.PlayArea : Boundary.Type.TrackedArea))
{
Vector3[] arr = cachedGeometryList.ToArray();
return arr;
}
#endif
Debug.LogError("This functionality is not supported in your current version of Unity.");
return null;
}
int pointsCount = 0;
if (OVRPlugin.GetBoundaryGeometry2((OVRPlugin.BoundaryType)boundaryType, IntPtr.Zero, ref pointsCount))
{
if (pointsCount > 0)
{
int requiredNativeBufferCapacity = pointsCount * cachedVector3fSize;
if (cachedGeometryNativeBuffer.GetCapacity() < requiredNativeBufferCapacity)
cachedGeometryNativeBuffer.Reset(requiredNativeBufferCapacity);
int requiredManagedBufferCapacity = pointsCount * 3;
if (cachedGeometryManagedBuffer.Length < requiredManagedBufferCapacity)
cachedGeometryManagedBuffer = new float[requiredManagedBufferCapacity];
if (OVRPlugin.GetBoundaryGeometry2((OVRPlugin.BoundaryType)boundaryType, cachedGeometryNativeBuffer.GetPointer(), ref pointsCount))
{
Marshal.Copy(cachedGeometryNativeBuffer.GetPointer(), cachedGeometryManagedBuffer, 0, requiredManagedBufferCapacity);
Vector3[] points = new Vector3[pointsCount];
for (int i = 0; i < pointsCount; i++)
{
points[i] = new OVRPlugin.Vector3f()
{
x = cachedGeometryManagedBuffer[3 * i + 0],
y = cachedGeometryManagedBuffer[3 * i + 1],
z = cachedGeometryManagedBuffer[3 * i + 2],
}.FromFlippedZVector3f();
}
return points;
}
}
}
return new Vector3[0];
}
19
View Source File : TextureCache.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator
License : GNU General Public License v3.0
Project Creator : ACEmulator
private static Texture2D GetTexture2DFromBitmap(GraphicsDevice device, Bitmap bitmap)
{
Texture2D tex = new Texture2D(device, bitmap.Width, bitmap.Height, false, SurfaceFormat.Color);
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int bufferSize = data.Height * data.Stride;
// create data buffer
byte[] bytes = new byte[bufferSize];
// copy bitmap data into buffer
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
// copy our buffer to the texture
tex.SetData(bytes);
// unlock the bitmap data
bitmap.UnlockBits(data);
return tex;
}
19
View Source File : Image.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator
License : GNU General Public License v3.0
Project Creator : ACEmulator
public static Texture2D GetTexture2DFromBitmap(GraphicsDevice device, Bitmap bitmap)
{
Texture2D tex = new Texture2D(device, bitmap.Width, bitmap.Height, false, SurfaceFormat.Color);
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
int bufferSize = data.Height * data.Stride;
//create data buffer
byte[] bytes = new byte[bufferSize];
// copy bitmap data into buffer
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
// copy our buffer to the texture
tex.SetData(bytes);
// unlock the bitmap data
bitmap.UnlockBits(data);
return tex;
}
19
View Source File : Z85.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static byte[] Encode(byte[] decoded)
{
int dataLen = decoded.Length;
if (dataLen % 4 > 0)
{
throw new InvalidOperationException("decoded.Length must be divisible by 4");
}
int destLen = (Int32)(decoded.Length * 1.25);
var data = GCHandle.Alloc(decoded, GCHandleType.Pinned);
// the buffer dest must be one byte larger than destLen to accomodate the null termination character
using (var dest = DispoIntPtr.Alloc(destLen + 1))
{
if (IntPtr.Zero == zmq.z85_encode(dest, data.AddrOfPinnedObject(), dataLen))
{
data.Free();
throw new InvalidOperationException();
}
data.Free();
var bytes = new byte[destLen];
Marshal.Copy(dest, bytes, 0, destLen);
return bytes;
}
}
19
View Source File : Z85.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void CurveKeypair(out byte[] publicKey, out byte[] secretKey)
{
const int destLen = 40;
using (var publicKeyData = DispoIntPtr.Alloc(destLen + 1))
using (var secretKeyData = DispoIntPtr.Alloc(destLen + 1))
{
if (0 != zmq.curve_keypair(publicKeyData, secretKeyData))
{
throw new InvalidOperationException();
}
publicKey = new byte[destLen];
Marshal.Copy(publicKeyData, publicKey, 0, destLen);
secretKey = new byte[destLen];
Marshal.Copy(secretKeyData, secretKey, 0, destLen);
}
}
19
View Source File : Z85.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static byte[] Decode(byte[] encoded)
{
int dataLen = encoded.Length;
if (dataLen % 5 > 0)
{
throw new InvalidOperationException("encoded.Length must be divisible by 5");
}
int destLen = (Int32)(encoded.Length * .8);
var data = GCHandle.Alloc(encoded, GCHandleType.Pinned);
using (var dest = DispoIntPtr.Alloc(destLen))
{
if (IntPtr.Zero == zmq.z85_decode(dest, data.AddrOfPinnedObject()))
{
data.Free();
throw new InvalidOperationException();
}
data.Free();
var decoded = new byte[destLen];
Marshal.Copy(dest, decoded, 0, decoded.Length);
return decoded;
}
}
19
View Source File : TextureEncoder.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
internal static void Encode(Texture texture, Image image, int level)
{
var width = texture.GetWidth(level);
var height = texture.GetHeight(level);
var data = new byte[width * height * 4]; // R G B A
var bitmap = new Bitmap((int)width, (int)height);
Graphics g = Graphics.FromImage(bitmap);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImage(image, 0, 0, (int)width, (int)height);
g.Dispose();
var rect = new Rectangle(0, 0, (int) width, (int) height);
BitmapData bmpdata = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
if (texture.TextureType == TextureType.A8R8G8B8)
{
Marshal.Copy(bmpdata.Scan0, data, 0, (int) width*(int) height*4);
}
else if (texture.TextureType == TextureType.L8)
{
var newData = new byte[width * height];
// Convert to L8
unsafe
{
var p = (byte*)bmpdata.Scan0;
for (var y = 0; y < bitmap.Height; y++)
{
for (var x = 0; x < bitmap.Width; x++)
{
var offset = y * bmpdata.Stride + x * 4;
var dataOffset = y * width + x;
newData[dataOffset] = (byte)((p[offset + 2] + p[offset + 1] + p[offset + 0])/3);
}
}
}
data = newData;
}
else
{
// Convert from the B G R A format stored by GDI+ to R G B A
unsafe
{
var p = (byte*)bmpdata.Scan0;
for (var y = 0; y < bitmap.Height; y++)
{
for (var x = 0; x < bitmap.Width; x++)
{
var offset = y * bmpdata.Stride + x * 4;
var dataOffset = y * width * 4 + x * 4;
data[dataOffset + 0] = p[offset + 2]; // R
data[dataOffset + 1] = p[offset + 1]; // G
data[dataOffset + 2] = p[offset + 0]; // B
data[dataOffset + 3] = p[offset + 3]; // A
}
}
}
}
bitmap.UnlockBits(bmpdata);
bitmap.Dispose();
switch (texture.TextureType)
{
case TextureType.DXT1:
data = DXTEncoder.EncodeDXT1(data, (int) width, (int) height);
break;
case TextureType.DXT3:
data = DXTEncoder.EncodeDXT3(data, (int) width, (int) height);
break;
case TextureType.DXT5:
data = DXTEncoder.EncodeDXT5(data, (int) width, (int) height);
break;
case TextureType.A8R8G8B8:
case TextureType.L8:
// Nothing to do
break;
default:
throw new ArgumentOutOfRangeException();
}
texture.SetTextureData(level, data);
}
19
View Source File : TextureDecoder.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
internal static Image Decode(Texture texture, int level)
{
var width = texture.GetWidth(level);
var height = texture.GetHeight(level);
var data = texture.GetTextureData(level);
switch(texture.TextureType)
{
case TextureType.DXT1:
data = DXTDecoder.DecodeDXT1(data, (int)width, (int)height);
break;
case TextureType.DXT3:
data = DXTDecoder.DecodeDXT3(data, (int)width, (int)height);
break;
case TextureType.DXT5:
data = DXTDecoder.DecodeDXT5(data, (int)width, (int)height);
break;
case TextureType.A8R8G8B8:
// Nothing to do, the data is already in the format we want it to be
break;
case TextureType.L8:
{
var newData = new byte[data.Length*4];
for (int i = 0; i < data.Length; i++)
{
newData[i*4 + 0] = data[i];
newData[i*4 + 1] = data[i];
newData[i*4 + 2] = data[i];
newData[i*4 + 3] = 255;
}
data = newData;
}
break;
default:
throw new ArgumentOutOfRangeException();
}
var bmp = new Bitmap((int) width, (int) height, PixelFormat.Format32bppArgb);
var rect = new Rectangle(0, 0, (int) width, (int) height);
var bmpdata = bmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(data, 0, bmpdata.Scan0, (int) width*(int) height*4);
bmp.UnlockBits(bmpdata);
return bmp;
}
19
View Source File : Bitmap.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public osf.ArrayList GetBytes(osf.BitmapData p1)
{
int num = Math.Abs(p1.M_BitmapData.Stride) * M_Bitmap.Height;
byte[] Bytes1 = new byte[num];
System.Runtime.InteropServices.Marshal.Copy(p1.M_BitmapData.Scan0, Bytes1, 0, num);
ArrayList ArrayList1 = new ArrayList();
for (int i = 0; i < num; i++)
{
ArrayList1.Add(System.Convert.ToInt32(Bytes1[i]));
}
return ArrayList1;
}
19
View Source File : Bitmap.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public void SetBytes(osf.BitmapData p1, osf.ArrayList p2)
{
int num = p2.M_ArrayList.Count;
byte[] Bytes1 = new byte[num];
for (int i = 0; i < num; i++)
{
Bytes1[i] = System.Convert.ToByte(p2.M_ArrayList[i].ToString());
}
System.Runtime.InteropServices.Marshal.Copy(Bytes1, 0, p1.M_BitmapData.Scan0, num);
}
19
View Source File : SteamVR_RenderModel.cs
License : MIT License
Project Creator : ajayyy
License : MIT License
Project Creator : ajayyy
RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
{
var pRenderModel = System.IntPtr.Zero;
EVRRenderModelError error;
while ( true )
{
error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
if (error != EVRRenderModelError.None)
{
Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
return null;
}
var renderModel = MarshalRenderModel(pRenderModel);
var vertices = new Vector3[renderModel.unVertexCount];
var normals = new Vector3[renderModel.unVertexCount];
var uv = new Vector2[renderModel.unVertexCount];
var type = typeof(RenderModel_Vertex_t);
for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
{
var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);
vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
}
int indexCount = (int)renderModel.unTriangleCount * 3;
var indices = new short[indexCount];
Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);
var triangles = new int[indexCount];
for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
{
triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
}
var mesh = new Mesh();
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.triangles = triangles;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
mesh.Optimize();
#endif
//mesh.hideFlags = HideFlags.DontUnloadUnusedreplacedet;
// Check cache before loading texture.
var material = materials[renderModel.diffuseTextureId] as Material;
if (material == null || material.mainTexture == null)
{
var pDiffuseTexture = System.IntPtr.Zero;
while (true)
{
error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
if (error == EVRRenderModelError.None)
{
var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
{
texture.Apply();
while (true)
{
error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texture.GetNativeTexturePtr());
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
}
else
{
var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);
var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
int iColor = 0;
for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
{
for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
{
var r = textureMapData[iColor++];
var g = textureMapData[iColor++];
var b = textureMapData[iColor++];
var a = textureMapData[iColor++];
colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
}
}
texture.SetPixels32(colors);
texture.Apply();
}
material = new Material(shader != null ? shader : Shader.Find("Standard"));
material.mainTexture = texture;
//material.hideFlags = HideFlags.DontUnloadUnusedreplacedet;
materials[renderModel.diffuseTextureId] = material;
renderModels.FreeTexture(pDiffuseTexture);
}
else
{
Debug.Log("Failed to load render model texture for render model " + renderModelName);
}
}
// Delay freeing when we can since we'll often get multiple requests for the same model right
// after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
if (!Application.isPlaying)
renderModels.FreeRenderModel(pRenderModel);
else
#endif
StartCoroutine(FreeRenderModel(pRenderModel));
return new RenderModel(mesh, material);
}
19
View Source File : DirectBitmap.cs
License : MIT License
Project Creator : altskop
License : MIT License
Project Creator : altskop
public static Bitmap BuildImage(Byte[] sourceData, Int32 width, Int32 height, Int32 stride, PixelFormat pixelFormat, System.Drawing.Color[] palette, System.Drawing.Color? defaultColor)
{
Bitmap newImage = new Bitmap(width, height, pixelFormat);
BitmapData targetData = newImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, newImage.PixelFormat);
Int32 newDataWidth = ((Image.GetPixelFormatSize(pixelFormat) * width) + 7) / 8;
// Compensate for possible negative stride on BMP format.
Boolean isFlipped = stride < 0;
stride = Math.Abs(stride);
// Cache these to avoid unnecessary getter calls.
Int32 targetStride = targetData.Stride;
Int64 scan0 = targetData.Scan0.ToInt64();
for (Int32 y = 0; y < height; y++)
Marshal.Copy(sourceData, y * stride, new IntPtr(scan0 + y * targetStride), newDataWidth);
newImage.UnlockBits(targetData);
// Fix negative stride on BMP format.
if (isFlipped)
newImage.RotateFlip(RotateFlipType.Rotate180FlipX);
// For indexed images, set the palette.
if ((pixelFormat & PixelFormat.Indexed) != 0 && palette != null)
{
ColorPalette pal = newImage.Palette;
for (Int32 i = 0; i < pal.Entries.Length; i++)
{
if (i < palette.Length)
pal.Entries[i] = palette[i];
else if (defaultColor.HasValue)
pal.Entries[i] = defaultColor.Value;
else
break;
}
newImage.Palette = pal;
}
return newImage;
}
19
View Source File : MemoryUtil.cs
License : GNU General Public License v3.0
Project Creator : am0nsec
License : GNU General Public License v3.0
Project Creator : am0nsec
protected T GetStructureFromBlob<T>(Int64 offset) where T : struct {
Span<byte> bytes = this.GetStructureBytesFromOffset<T>(offset);
if (Marshal.SizeOf<T>() != bytes.Length)
return default;
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf<T>());
Marshal.Copy(bytes.ToArray(), 0, ptr, bytes.Length);
T s = Marshal.PtrToStructure<T>(ptr);
Marshal.FreeHGlobal(ptr);
return s;
}
19
View Source File : HellsGate.cs
License : GNU General Public License v3.0
Project Creator : am0nsec
License : GNU General Public License v3.0
Project Creator : am0nsec
private T NtInvocation<T>(Int16 syscall) where T: Delegate {
if (!this.IsGateReady || this.UnmanagedMethodAddress == IntPtr.Zero) {
Util.LogError("Unable to inject system call stub");
return default;
}
Span<byte> stub = stackalloc byte[24] {
0x4c, 0x8b, 0xd1, // mov r10, rcx
0xb8, (byte)syscall, (byte)(syscall >> 8), 0x00, 0x00, // mov eax, <syscall
0xf6, 0x04, 0x25, 0x08, 0x03, 0xfe, 0x7f, 0x01, // test byte ptr [SharedUserData+0x308],1
0x75, 0x03, // jne ntdll!<function>+0x15
0x0f, 0x05, // syscall
0xc3, // ret
0xcd, 0x2e, // int 2Eh
0xc3 // ret
};
Marshal.Copy(stub.ToArray(), 0, this.UnmanagedMethodAddress, stub.Length);
return Marshal.GetDelegateForFunctionPointer<T>(this.UnmanagedMethodAddress);
}
19
View Source File : EffectParameters.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
internal unsafe void __MarshalFrom(ref __Native @ref)
{
this.Flags = @ref.Flags;
this.Duration = @ref.Duration;
this.SamplePeriod = @ref.SamplePeriod;
this.Gain = @ref.Gain;
this.TriggerButton = @ref.TriggerButton;
this.TriggerRepeatInterval = @ref.TriggerRepeatInterval;
this.AxeCount = @ref.AxeCount;
this.StartDelay = @ref.StartDelay;
// Marshal Axes and Directions
if (AxeCount > 0)
{
if (@ref.AxePointer != IntPtr.Zero)
{
Axes = new int[AxeCount];
Marshal.Copy(@ref.AxePointer, Axes, 0, AxeCount);
}
if (@ref.DirectionPointer != IntPtr.Zero)
{
Directions = new int[AxeCount];
Marshal.Copy(@ref.DirectionPointer, Directions, 0, AxeCount);
}
}
// Marshal Envelope
if (@ref.EnvelopePointer != IntPtr.Zero)
{
var envelopeNative = *((Envelope.__Native*)@ref.EnvelopePointer);
Envelope = new Envelope();
Envelope.__MarshalFrom(ref envelopeNative);
}
// Marshal TypeSpecificParameters
if (@ref.TypeSpecificParamCount > 0 && @ref.TypeSpecificParamPointer != IntPtr.Zero)
Parameters = new TypeSpecificParameters(@ref.TypeSpecificParamCount, @ref.TypeSpecificParamPointer);
}
19
View Source File : SteamVR_RenderModel.cs
License : GNU General Public License v2.0
Project Creator : andrewjc
License : GNU General Public License v2.0
Project Creator : andrewjc
RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
{
var pRenderModel = System.IntPtr.Zero;
EVRRenderModelError error;
while ( true )
{
error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
if (error != EVRRenderModelError.Loading)
break;
System.Threading.Thread.Sleep(1);
}
if (error != EVRRenderModelError.None)
{
Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
return null;
}
var renderModel = (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));
var vertices = new Vector3[renderModel.unVertexCount];
var normals = new Vector3[renderModel.unVertexCount];
var uv = new Vector2[renderModel.unVertexCount];
var type = typeof(RenderModel_Vertex_t);
for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
{
var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);
vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
}
int indexCount = (int)renderModel.unTriangleCount * 3;
var indices = new short[indexCount];
Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);
var triangles = new int[indexCount];
for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
{
triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
}
var mesh = new Mesh();
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.triangles = triangles;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
mesh.Optimize();
#endif
//mesh.hideFlags = HideFlags.DontUnloadUnusedreplacedet;
// Check cache before loading texture.
var material = materials[renderModel.diffuseTextureId] as Material;
if (material == null || material.mainTexture == null)
{
var pDiffuseTexture = System.IntPtr.Zero;
while (true)
{
error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
if (error != EVRRenderModelError.Loading)
break;
System.Threading.Thread.Sleep(1);
}
if (error == EVRRenderModelError.None)
{
var diffuseTexture = (RenderModel_TextureMap_t)Marshal.PtrToStructure(pDiffuseTexture, typeof(RenderModel_TextureMap_t));
var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.ARGB32, false);
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
{
texture.Apply();
while (true)
{
error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texture.GetNativeTexturePtr());
if (error != EVRRenderModelError.Loading)
break;
System.Threading.Thread.Sleep(1);
}
}
else
{
var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);
var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
int iColor = 0;
for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
{
for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
{
var r = textureMapData[iColor++];
var g = textureMapData[iColor++];
var b = textureMapData[iColor++];
var a = textureMapData[iColor++];
colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
}
}
texture.SetPixels32(colors);
texture.Apply();
}
material = new Material(shader != null ? shader : Shader.Find("Standard"));
material.mainTexture = texture;
//material.hideFlags = HideFlags.DontUnloadUnusedreplacedet;
materials[renderModel.diffuseTextureId] = material;
renderModels.FreeTexture(pDiffuseTexture);
}
else
{
Debug.Log("Failed to load render model texture for render model " + renderModelName);
}
}
// Delay freeing when we can since we'll often get multiple requests for the same model right
// after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
if (!Application.isPlaying)
renderModels.FreeRenderModel(pRenderModel);
else
#endif
StartCoroutine(FreeRenderModel(pRenderModel));
return new RenderModel(mesh, material);
}
19
View Source File : MemoryMappedFileStreamCreator.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public void UnsafeDisableMemoryMappedIO() {
if (dataAry != null)
return;
if (unsafeUseAddress)
throw new InvalidOperationException("Can't convert to non-memory mapped I/O because the PDB reader uses the address. Use the managed PDB reader instead.");
var newAry = new byte[Length];
Marshal.Copy(data, newAry, 0, newAry.Length);
FreeMemoryMappedIoData();
dataLength = newAry.Length;
dataAry = newAry;
gcHandle = GCHandle.Alloc(dataAry, GCHandleType.Pinned);
this.data = gcHandle.AddrOfPinnedObject();
}
19
View Source File : OptFlowOfBlocks.cs
License : MIT License
Project Creator : aoso3
License : MIT License
Project Creator : aoso3
public static void calcOptFlowOfBlocks(Mat mag, Mat angle, Image<Gray, Byte> grayImg,out double[][][] opFlowOfBlocks,
out double[][][] centreOfBlocks, out int rows, out int cols,out int noOfRowInBlock,
out int noOfColInBlock, out int xBlockSize, out int yBlockSize,out int blockSize){
double val = 0;
double deg_threshold = 337.5;
rows = grayImg.Height;
cols = grayImg.Width;
noOfRowInBlock = 8;
noOfColInBlock = 8;
xBlockSize = rows / noOfRowInBlock + 1;
yBlockSize = cols / noOfColInBlock + 1;
blockSize = noOfRowInBlock * noOfColInBlock;
opFlowOfBlocks = new double[xBlockSize][][];
centreOfBlocks = new double[xBlockSize][][];
for (int r = 0; r < xBlockSize; r++)
{
opFlowOfBlocks[r] = new double[yBlockSize][];
centreOfBlocks[r] = new double[yBlockSize][];
for (int rr = 0; rr < yBlockSize; rr++)
{
opFlowOfBlocks[r][rr] = new double[2];
centreOfBlocks[r][rr] = new double[2];
}
}
for (int i = 0; i < mag.Height; i++)
for (int j = 0; j < mag.Width; j++)
{
double[] mag_value = new double[1];
Marshal.Copy(mag.DataPointer + (i * mag.Cols + j) * mag.ElementSize, mag_value, 0, 1);
opFlowOfBlocks[i / noOfRowInBlock][j / noOfColInBlock][0] += mag_value[0];
double[] angle_value = new double[1];
Marshal.Copy(angle.DataPointer + (i * angle.Cols + j) * angle.ElementSize, angle_value, 0, 1);
opFlowOfBlocks[i / noOfRowInBlock][j / noOfColInBlock][1] += angle_value[0];
}
for (int i = 0; i < xBlockSize; i++)
for (int j = 0; j < yBlockSize; j++)
for (int k = 0; k < 2; k++)
{
opFlowOfBlocks[i][j][k] /= noOfRowInBlock * noOfColInBlock;
val = opFlowOfBlocks[i][j][k];
double opt = 0;
if( k == 1 )
{
double angInDeg = val * (180 / Math.PI);
if (angInDeg > deg_threshold)
opt = 0;
else
{
double q = Math.Floor(angInDeg / 22.5);
double a1 = q * 22.5;
double q1 = (int)(angInDeg - a1);
double a2 = (q + 2) * 22.5;
double q2 = (a2 - angInDeg);
if (q1.CompareTo(q2) == -1)
opt = Math.Round(a1 / 45);
else
opt = Math.Round(a2 / 45);
}
opFlowOfBlocks[i][j][k] = opt;
double theta = val;
}
if (k == 1)
{
double r = val;
double x = ((i + 1) * noOfRowInBlock) - (noOfRowInBlock / 2);
double y = ((j + 1) * noOfColInBlock) - (noOfColInBlock / 2);
centreOfBlocks[i][j][0] = x;
centreOfBlocks[i][j][1] = y;
}
}
}
19
View Source File : ARApplicationDelegate.cs
License : Apache License 2.0
Project Creator : AppRopio
License : Apache License 2.0
Project Creator : AppRopio
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
byte[] result = new byte[deviceToken.Length];
Marshal.Copy(deviceToken.Bytes, result, 0, (int)deviceToken.Length);
var token = BitConverter.ToString(result).Replace("-", "");
Mvx.IoCProvider.Resolve<IMvxLog>().Trace($"\nPush token: {token}\n");
Mvx.IoCProvider.CallbackWhenRegistered<IPushNotificationsService>(async service =>
{
try
{
AppSettings.PushToken = token;
await service.RegisterDeviceForPushNotificatons(token);
}
catch { }
});
}
19
View Source File : ByteMatrix.cs
License : MIT License
Project Creator : architdate
License : MIT License
Project Creator : architdate
public Bitmap ToBitmap()
{
const byte BLACK = 0;
const byte WHITE = 255;
sbyte[][] array = this.Array;
int width = this.Width;
int height = this.Height;
//Here create the Bitmap to the known height, width and format
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
//Create a BitmapData and Lock all pixels to be written
BitmapData bmpData =
bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
// If you wanted to support formats other than 8bpp, you should use Bitmap.GetPixelFormatSize(bmp.PixelFormat) to adjust the array size
byte[] pixels = new byte[bmpData.Stride * height];
int iPixelsCounter = 0;
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
pixels[iPixelsCounter++] = array[y][x] == BLACK ? BLACK : WHITE;
}
iPixelsCounter += bmpData.Stride - width;
}
//Copy the data from the byte array into BitmapData.Scan0
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
//Unlock the pixels
bmp.UnlockBits(bmpData);
//Return the bitmap
return bmp;
}
19
View Source File : ThumbnailHandlerQb.cs
License : MIT License
Project Creator : Arlorean
License : MIT License
Project Creator : Arlorean
protected override Bitmap GetThumbnailImage(uint width) {
var size = (int)width;
var voxelData = QbFile.Read(SelectedItemStream);
if (voxelData == null) {
return null;
}
var bitmapBytes = Renderer.RenderBitmap((int)size, voxelData);
// Convert Skia bytes to GDI Bitmap
var format = PixelFormat.Format32bppArgb;
var bitmap = new Bitmap(size, size, format);
var bitmapData = bitmap.LockBits(new Rectangle(0,0,size,size), ImageLockMode.WriteOnly, format);
Marshal.Copy(bitmapBytes, 0, bitmapData.Scan0, bitmapBytes.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
19
View Source File : ThumbnailHandlerQbcl.cs
License : MIT License
Project Creator : Arlorean
License : MIT License
Project Creator : Arlorean
protected override Bitmap GetThumbnailImage(uint width) {
var thumb = QbclFile.Read(SelectedItemStream);
var format = PixelFormat.Format32bppArgb;
var bitmap = new Bitmap(thumb.Width, thumb.Height, format);
var bitmapData = bitmap.LockBits(new Rectangle(0, 0, thumb.Width, thumb.Height), ImageLockMode.WriteOnly, format);
Marshal.Copy(thumb.Bytes, 0, bitmapData.Scan0, thumb.Bytes.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
19
View Source File : ThumbnailHandlerVox.cs
License : MIT License
Project Creator : Arlorean
License : MIT License
Project Creator : Arlorean
protected override Bitmap GetThumbnailImage(uint width) {
var size = (int)width;
var voxelData = VoxFile.Read(SelectedItemStream);
if (voxelData == null) {
return null;
}
var bitmapBytes = Renderer.RenderBitmap((int)size, voxelData);
// Convert Skia bytes to GDI Bitmap
var format = PixelFormat.Format32bppArgb;
var bitmap = new Bitmap(size, size, format);
var bitmapData = bitmap.LockBits(new Rectangle(0,0,size,size), ImageLockMode.WriteOnly, format);
Marshal.Copy(bitmapBytes, 0, bitmapData.Scan0, bitmapBytes.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
19
View Source File : TrackedPlane.cs
License : MIT License
Project Creator : ARUnityBook
License : MIT License
Project Creator : ARUnityBook
private void _UpdatePlaneIfNeeded(ApiPlaneData apiPlaneData, TrackedPlane subsumedBy, bool forceUpdate)
{
if (m_initialized && apiPlaneData.id != m_apiPlaneData.id)
{
ARDebug.LogError("Cannot update plane with mismatched id.");
return;
}
else if (m_initialized && ! forceUpdate && apiPlaneData.timestamp == m_apiPlaneData.timestamp)
{
return;
}
if (subsumedBy != null)
{
SubsumedBy = subsumedBy;
}
m_apiPlaneData = apiPlaneData;
m_initialized = true;
m_lastUpdatedFrame = Time.frameCount;
Matrix4x4 startServiceTplane = Matrix4x4.TRS(apiPlaneData.pose.translation.ToVector3(),
apiPlaneData.pose.orientation.ToQuaternion(), Vector3.one);
// Because startServiceTplane is a Pose (position, orientation), the multiplication of the first two terms
// rotates plane orientation. This must be undone with the last term (inverse) of the equation.
m_unityWorldTPlane = Constants.UNITY_WORLD_T_START_SERVICE * startServiceTplane *
Constants.UNITY_WORLD_T_START_SERVICE.inverse;
Position = m_unityWorldTPlane.GetColumn(3);
Position += new Vector3((float)apiPlaneData.centerX, 0.0f, (float)apiPlaneData.centerY);
Quaternion yaw = Quaternion.Euler(0.0f, -Mathf.Rad2Deg * (float)apiPlaneData.yaw, 0.0f);
Rotation = yaw * Quaternion.LookRotation(m_unityWorldTPlane.GetColumn(2), m_unityWorldTPlane.GetColumn(1));
m_boundaryPolygonPoints.Clear();
int boudaryLength = m_apiPlaneData.boundaryPointNum;
if (boudaryLength != 0)
{
double[] apiBoundaryPolygon = new double[boudaryLength * 2];
Marshal.Copy(m_apiPlaneData.boundaryPolygon, apiBoundaryPolygon, 0, boudaryLength * 2);
m_boundaryPolygonPoints.Clear();
for(int i = 0; i < boudaryLength; ++i)
{
Vector3 localPoint = new Vector3((float)apiBoundaryPolygon[2 * i],
0.0f, (float)apiBoundaryPolygon[2*i+1]);
m_boundaryPolygonPoints.Add(m_unityWorldTPlane.MultiplyPoint3x4(localPoint));
}
}
// Reverse the m_boundaryPolygonPoints because the raw data is in counter-clockwise.
// As Unity is left handed system, this should be clockwise.
m_boundaryPolygonPoints.Reverse();
}
19
View Source File : ARCoreInterface.cs
License : MIT License
Project Creator : ARUnityBook
License : MIT License
Project Creator : ARUnityBook
public override bool TryGetCameraImage(ref CameraImage cameraImage)
{
ARCoreNative.NativeImage nativeImage = new ARCoreNative.NativeImage();
if (ARCoreNative.Device.TryAcquireLatestImageBuffer(ref nativeImage))
{
cameraImage.width = (int)nativeImage.width;
cameraImage.height = (int)nativeImage.height;
var planeInfos = nativeImage.planeInfos;
// The Y plane is always the first one.
var yOffset = planeInfos[0].offset;
var numYBytes = planeInfos[0].size;
IntPtr yPlaneStart = new IntPtr(nativeImage.planeData.ToInt64() + yOffset);
if (cameraImage.y == null || cameraImage.y.Length != numYBytes)
cameraImage.y = new byte[numYBytes];
Marshal.Copy(yPlaneStart, cameraImage.y, 0, (int)numYBytes);
// UV planes are not deterministic, but we want all the data in one go
// so the offset will be the min of the two planes.
int uvOffset = Mathf.Min(
(int)nativeImage.planeInfos[1].offset,
(int)nativeImage.planeInfos[2].offset);
// Find the end of the uv plane data
int uvDataEnd = 0;
for (int i = 1; i < planeInfos.Count; ++i)
{
uvDataEnd = Mathf.Max(uvDataEnd, (int)planeInfos[i].offset + planeInfos[i].size);
}
// Finally, compute the number of bytes by subtracting the end from the beginning
var numUVBytes = uvDataEnd - uvOffset;
IntPtr uvPlaneStart = new IntPtr(nativeImage.planeData.ToInt64() + uvOffset);
if (cameraImage.uv == null || cameraImage.uv.Length != numUVBytes)
cameraImage.uv = new byte[numUVBytes];
Marshal.Copy(uvPlaneStart, cameraImage.uv, 0, (int)numUVBytes);
ARCoreNative.Device.ReleaseImageBuffer(nativeImage);
// The data is usually provided as VU rather than UV,
// so we need to swap the bytes.
// There's no way to know this currently, but it's always
// been this way on every device so far.
for (int i = 1; i < numUVBytes; i += 2)
{
var b = cameraImage.uv[i - 1];
cameraImage.uv[i - 1] = cameraImage.uv[i];
cameraImage.uv[i] = b;
}
return true;
}
return false;
}
19
View Source File : TrimWhiteSpace.cs
License : MIT License
Project Creator : aspose-pdf
License : MIT License
Project Creator : aspose-pdf
public static void Run()
{
// ExStart:TrimWhiteSpace
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDoreplacedents();
// Load an existing PDF files
Doreplacedent doc = new Doreplacedent(dataDir + "input.pdf");
// Render the page to image with 72 DPI
PngDevice device = new PngDevice(new Resolution(72));
using (MemoryStream imageStr = new MemoryStream())
{
device.Process(doc.Pages[1], imageStr);
Bitmap bmp = (Bitmap)Bitmap.FromStream(imageStr);
System.Drawing.Imaging.BitmapData imageBitmapData = null;
// Determine white areas
try
{
imageBitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
Aspose.Pdf.Rectangle prevCropBox = doc.Pages[1].CropBox;
int toHeight = bmp.Height;
int toWidth = bmp.Width;
int? leftNonWhite = null;
int? rightNonWhite = null;
int? topNonWhite = null;
int? bottomNonWhite = null;
for (int y = 0; y < toHeight; y++)
{
byte[] imageRowBytes = new byte[imageBitmapData.Stride];
// Copy the row data to byte array
if (IntPtr.Size == 4)
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt32() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride);
else
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt64() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride);
int? leftNonWhite_row = null;
int? rightNonWhite_row = null;
for (int x = 0; x < toWidth; x++)
{
if (imageRowBytes[x * 4] != 255
|| imageRowBytes[x * 4 + 1] != 255
|| imageRowBytes[x * 4 + 2] != 255)
{
if (leftNonWhite_row == null)
leftNonWhite_row = x;
rightNonWhite_row = x;
}
}
if (leftNonWhite_row != null || rightNonWhite_row != null)
{
if (topNonWhite == null)
topNonWhite = y;
bottomNonWhite = y;
}
if (leftNonWhite_row != null
&& (leftNonWhite == null || leftNonWhite > leftNonWhite_row))
{
leftNonWhite = leftNonWhite_row;
}
if (rightNonWhite_row != null
&& (rightNonWhite == null || rightNonWhite < rightNonWhite_row))
{
rightNonWhite = rightNonWhite_row;
}
}
leftNonWhite = leftNonWhite ?? 0;
rightNonWhite = rightNonWhite ?? toWidth;
topNonWhite = topNonWhite ?? 0;
bottomNonWhite = bottomNonWhite ?? toHeight;
// Set crop box with correction to previous crop box
doc.Pages[1].CropBox =
new Aspose.Pdf.Rectangle(
leftNonWhite.Value + prevCropBox.LLX,
(toHeight + prevCropBox.LLY) - bottomNonWhite.Value,
rightNonWhite.Value + doc.Pages[1].CropBox.LLX,
(toHeight + prevCropBox.LLY) - topNonWhite.Value
);
}
finally
{
if (imageBitmapData != null)
bmp.UnlockBits(imageBitmapData);
}
}
dataDir = dataDir + "TrimWhiteSpace_out.pdf";
// Save the updated doreplacedent
doc.Save(dataDir);
// ExEnd:TrimWhiteSpace
Console.WriteLine("\nWhite-space trimmed successfully around a page.\nFile saved at " + dataDir);
}
19
View Source File : CaptureButton.cs
License : ISC License
Project Creator : AtsushiSuzuki
License : ISC License
Project Creator : AtsushiSuzuki
public void OnClick()
{
Debug.Log("OnClick");
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
int width = 0, height = 0;
float[] pixels = null;
capture_.AcquireNextFrame((pVideoData, videoWidth, videoHeight, pDepthData, depthWidth, depthHeight) =>
{
width = depthWidth;
height = depthHeight;
pixels = new float[width * height];
Marshal.Copy(pDepthData, pixels, 0, width * height);
});
var texture = new Texture2D(width, height);
for (var y = 0; y < (int)height; y++)
{
for (var x = 0; x < (int)width; x++)
{
var v = pixels[y * width + x];
Color color;
if (float.IsNaN(v))
{
color = new Color(0f, 1f, 0f);
}
else
{
color = new Color(v, v, v);
}
texture.SetPixel(x, y, color);
}
}
quad.GetComponent<Renderer>().material.mainTexture = texture;
texture.Apply();
}
}
19
View Source File : BatchImageProcessor.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
private byte[] GetBytes(Bitmap image)
{
var region = new Rect(0, 0, image.Width, image.Height);
var bitmapData = image.LockBits(region, ImageLockMode.ReadOnly, image.PixelFormat);
var ptr = bitmapData.Scan0;
var length = Math.Abs(bitmapData.Stride) * image.Height;
var rgbValues = new byte[length];
Marshal.Copy(ptr, rgbValues, 0, length);
image.UnlockBits(bitmapData);
return rgbValues;
}
19
View Source File : PipelineExtensionService.cs
License : MIT License
Project Creator : Azure-Samples
License : MIT License
Project Creator : Azure-Samples
private Image GetImageFromContent(ReadOnlyMemory<byte> content, int width, int height)
{
var imageBytes = content.ToArray();
var region = new System.Drawing.Rectangle(0, 0, width, height);
var bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData bitmapData = bitmap.LockBits(region, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
var length = Math.Abs(bitmapData.Stride) * height;
Marshal.Copy(imageBytes, 0, bitmapData.Scan0, length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
19
View Source File : Evasion.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik
License : BSD 3-Clause "New" or "Revised" License
Project Creator : b4rtik
private static void FunnyAmsi(byte[] patch)
{
try
{
var lib = RedPeanutAgent.Core.Natives.LoadLibrary("amsi.dll");
var addr = RedPeanutAgent.Core.Natives.GetProcAddress(lib, "AmsiScanBuffer");
uint oldProtect;
RedPeanutAgent.Core.Natives.VirtualProtect(addr, (UIntPtr)patch.Length, 0x40, out oldProtect);
Marshal.Copy(patch, 0, addr, patch.Length);
RedPeanutAgent.Core.Natives.VirtualProtect(addr, (UIntPtr)patch.Length, oldProtect, out oldProtect);
}
catch (Exception e)
{
Console.WriteLine(" [x] {0}", e.Message);
Console.WriteLine(" [x] {0}", e.InnerException);
}
}
19
View Source File : VirtualFileDataObject.cs
License : MIT License
Project Creator : Bassman2
License : MIT License
Project Creator : Bassman2
public void SetData(short dataFormat, IEnumerable<byte> data)
{
_dataObjects.Add(
new DataObject
{
FORMATETC = new FORMATETC
{
cfFormat = dataFormat,
ptd = IntPtr.Zero,
dwAspect = DVASPECT.DVASPECT_CONTENT,
lindex = -1,
tymed = TYMED.TYMED_HGLOBAL
},
GetData = () =>
{
var dataArray = data.ToArray();
var ptr = Marshal.AllocHGlobal(dataArray.Length);
Marshal.Copy(dataArray, 0, ptr, dataArray.Length);
return new Tuple<IntPtr, int>(ptr, NativeMethods.S_OK);
},
});
}
19
View Source File : PropVariantFacade.cs
License : MIT License
Project Creator : Bassman2
License : MIT License
Project Creator : Bassman2
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public byte[] ToByteArray()
{
if (this.Value.vt == PropVariantType.VT_ERROR)
{
Debug.WriteLine($"VT_ERROR: 0x{this.Value.errorCode:X}");
return null;
}
if (this.Value.vt != (PropVariantType.VT_VECTOR | PropVariantType.VT_UI1))
{
throw new InvalidOperationException($"ToByteArray does not work for value type {this.Value.vt}");
}
int size = (int)this.Value.dataVal.cData;
byte[] managedArray = new byte[size];
// bug fixed with manual COM wrapper clreplacedes
Marshal.Copy(this.Value.dataVal.pData, managedArray, 0, size);
return managedArray;
}
19
View Source File : LPAPIBody.cs
License : MIT License
Project Creator : BelkinAndrey
License : MIT License
Project Creator : BelkinAndrey
public static IntPtr[] GetBodyFixturesList(IntPtr body) {
int count = GetBodyFixturesCount(body);
IntPtr fixturesListPointer = GetBodyFixtures(body);
IntPtr[] fixturesList = new IntPtr[count];
Marshal.Copy(fixturesListPointer,fixturesList,0,count);
return fixturesList;
}
19
View Source File : LPParticleSystem.cs
License : MIT License
Project Creator : BelkinAndrey
License : MIT License
Project Creator : BelkinAndrey
public LPParticleGroup[] GetGroupDataFromPlugin()
{
int groupCount = LPAPIParticleSystems.GetParticleGroupCount(PartSysPtr);
Groups = new LPParticleGroup[groupCount];
if (groupCount > 0)
{
IntPtr groupsPointer = LPAPIParticleSystems.GetParticleGroupPointers(PartSysPtr);
IntPtr[] groupThingPtrs = new IntPtr[groupCount];
Marshal.Copy(groupsPointer, groupThingPtrs, 0, groupCount);
for (int i = 0; i < groupCount; i++)
{
Groups[i] = new LPParticleGroup();
Groups[i].SetThingPtr(groupThingPtrs[i]);
//Debug.Log("Group " + i + " has " + Groups[i].GetParticleCount());
}
}
return Groups;
}
19
View Source File : TrampolineTests.cs
License : GNU Lesser General Public License v2.1
Project Creator : BepInEx
License : GNU Lesser General Public License v2.1
Project Creator : BepInEx
[DataTestMethod]
[DataRow(64)]
[DataRow(32)]
public void TrampolineTest(int bitness)
{
byte[] exampleCode =
{
0x48, 0x89, 0x5C, 0x24, 0x10, 0x48, 0x89, 0x74, 0x24, 0x18, 0x55, 0x57, 0x41, 0x56, 0x48, 0x8D,
0xAC, 0x24, 0x00, 0xFF, 0xFF, 0xFF, 0x48, 0x81, 0xEC, 0x00, 0x02, 0x00, 0x00, 0x48, 0x8B, 0x05,
0x18, 0x57, 0x0A, 0x00, 0x48, 0x33, 0xC4, 0x48, 0x89, 0x85, 0xF0, 0x00, 0x00, 0x00, 0x4C, 0x8B,
0x05, 0x2F, 0x24, 0x0A, 0x00, 0x48, 0x8D, 0x05, 0x78, 0x7C, 0x04, 0x00, 0x33, 0xFF
};
var exampleCodePointer = Marshal.AllocHGlobal(80);
var trampolineCodePointer = Marshal.AllocHGlobal(80);
Marshal.Copy(exampleCode, 0, exampleCodePointer, exampleCode.Length);
void Disreplacedemble(byte[] data, ulong ip)
{
var formatter = new NasmFormatter();
var output = new StringOutput();
var codeReader = new ByteArrayCodeReader(data);
var decoder = Decoder.Create(bitness, codeReader);
decoder.IP = ip;
while (codeReader.CanReadByte)
{
decoder.Decode(out var instr);
formatter.Format(instr, output);
Console.WriteLine($"{instr.IP:X16} {output.ToStringAndReset()}");
}
Console.WriteLine();
}
Console.WriteLine("Original:");
Console.WriteLine();
Disreplacedemble(exampleCode, (ulong) exampleCodePointer.ToInt64());
DetourGenerator.CreateTrampolineFromFunction(exampleCodePointer, out var trampolineLength, out _);
Console.WriteLine("Modified:");
Console.WriteLine();
Marshal.Copy(exampleCodePointer, exampleCode, 0, exampleCode.Length);
Disreplacedemble(exampleCode, (ulong) exampleCodePointer.ToInt64());
Console.WriteLine();
Console.WriteLine("Trampoline:");
Console.WriteLine();
var trampolineArray = new byte[trampolineLength];
Marshal.Copy(trampolineCodePointer, trampolineArray, 0, trampolineLength);
Disreplacedemble(trampolineArray, (ulong) trampolineCodePointer.ToInt64());
Marshal.FreeHGlobal(exampleCodePointer);
Marshal.FreeHGlobal(trampolineCodePointer);
replacedert.IsFalse(false);
}
19
View Source File : RomFile.cs
License : MIT License
Project Creator : BleuBleu
License : MIT License
Project Creator : BleuBleu
public unsafe bool Save(Project originalProject, string filename, int[] songIds, string name, string author, bool pal)
{
#if !DEBUG
try
#endif
{
if (songIds.Length == 0)
return false;
Debug.replacedert(!originalProject.UsesAnyExpansionAudio || !pal);
if (songIds.Length > MaxSongs)
Array.Resize(ref songIds, MaxSongs);
var project = originalProject.DeepClone();
project.DeleteAllSongsBut(songIds);
project.SetExpansionAudioMask(ExpansionType.NoneMask);
var headerBytes = new byte[RomHeaderLength];
var codeBytes = new byte[RomCodeAndTocSize + RomTileSize];
// Load ROM header (16 bytes) + code/tiles (12KB).
string romName = "FamiStudio.Rom.rom";
if (project.UsesFamiTrackerTempo)
romName += "_famitracker";
romName += pal ? "_pal" : "_ntsc";
romName += ".nes";
var romBinStream = typeof(RomFile).replacedembly.GetManifestResourceStream(romName);
romBinStream.Read(headerBytes, 0, RomHeaderLength);
romBinStream.Seek(-RomCodeAndTocSize - RomTileSize, SeekOrigin.End);
romBinStream.Read(codeBytes, 0, RomCodeAndTocSize + RomTileSize);
Log.LogMessage(LogSeverity.Info, $"ROM code and graphics size: {codeBytes.Length} bytes.");
// Build project info + song table of content.
var projectInfo = BuildProjectInfo(songIds, name, author);
var songTable = BuildSongTableOfContent(project);
// Gathersong data.
var songBanks = new List<List<byte>>();
// Export each song individually, build TOC at the same time.
for (int i = 0; i < project.Songs.Count; i++)
{
if (i == MaxSongs)
{
Log.LogMessage(LogSeverity.Warning, $"Too many songs. There is a hard limit of {MaxSongs} at the moment. Ignoring any extra songs.");
break;
}
var song = project.Songs[i];
var songBytes = new FamitoneMusicFile(FamiToneKernel.FamiStudio, false).GetBytes(project, new int[] { song.Id }, RomSongDataStart, RomDpcmStart, pal ? MachineType.PAL : MachineType.NTSC);
if (songBytes.Length > MaxSongSize)
{
Log.LogMessage(LogSeverity.Warning, $"Song {song.Name} has a size of {songBytes.Length}, which is larger than the maximum allowed for ROM export ({MaxSongSize}). Truncating.");
Array.Resize(ref songBytes, MaxSongSize);
}
var numBanks = Utils.DivideAndRoundUp(songBytes.Length, RomBankSize);
Debug.replacedert(numBanks <= 2);
var songBank = songBanks.Count;
var songAddr = RomSongDataStart;
// If single bank, look for an existing bank with some free space at the end.
if (numBanks == 1)
{
var foundExistingBank = false;
for (int j = 0; j < songBanks.Count; j++)
{
var freeSpace = RomBankSize - songBanks[j].Count;
if (songBytes.Length <= freeSpace)
{
songBank = j;
songAddr = RomSongDataStart + songBanks[j].Count;
songBytes = new FamitoneMusicFile(FamiToneKernel.FamiStudio, false).GetBytes(project, new int[] { song.Id }, songAddr, RomDpcmStart, pal ? MachineType.PAL : MachineType.NTSC);
Debug.replacedert(songBytes.Length <= freeSpace);
foundExistingBank = true;
break;
}
}
// No free space found, allocation a new partial bank.
if (!foundExistingBank)
songBanks.Add(new List<byte>());
songBanks[songBank].AddRange(songBytes);
}
else
{
// When a song uses 2 banks, allocate a new full one and a partial one.
var bank0 = new List<byte>();
var bank1 = new List<byte>();
for (int j = 0; j < RomBankSize; j++)
bank0.Add(songBytes[j]);
for (int j = RomBankSize; j < songBytes.Length; j++)
bank1.Add(songBytes[j]);
songBanks.Add(bank0);
songBanks.Add(bank1);
}
songTable[i].bank = (byte)songBank;
songTable[i].address = (ushort)songAddr;
songTable[i].flags = (byte)(song.UsesDpcm ? 1 : 0);
Log.LogMessage(LogSeverity.Info, $"Song '{song.Name}' size: {songBytes.Length} bytes.");
}
//File.WriteAllBytes("D:\\debug.bin", songDataBytes.ToArray());
// Add extra empty banks if we haven't reached the minimum.
if (songBanks.Count < RomMinNumberBanks)
{
for (int i = songBanks.Count; i < RomMinNumberBanks; i++)
songBanks.Add(new List<byte>());
}
else if ((songBanks.Count & 1) != 0)
{
songBanks.Add(new List<byte>());
}
// Build final song bank data.
var songBanksBytes = new byte[songBanks.Count * RomBankSize];
for (int i = 0; i < songBanks.Count; i++)
Array.Copy(songBanks[i].ToArray(), 0, songBanksBytes, i * RomBankSize, songBanks[i].Count);
// Patch in code (project info and song table are after the code, 0xf000).
Marshal.Copy(new IntPtr(&projectInfo), codeBytes, RomTocOffset, sizeof(RomProjectInfo));
for (int i = 0; i < MaxSongs; i++)
{
fixed (RomSongEntry* songEntry = &songTable[i])
Marshal.Copy(new IntPtr(songEntry), codeBytes, RomTocOffset + sizeof(RomProjectInfo) + i * sizeof(RomSongEntry), sizeof(RomSongEntry));
}
// Patch header (iNES header always counts in 16KB banks, MMC3 counts in 8KB banks)
headerBytes[RomHeaderPrgOffset] = (byte)((songBanks.Count + RomCodeDpcmNumBanks) * RomBankSize / 0x4000);
// Build final ROM and save.
var romBytes = new List<byte>();
romBytes.AddRange(headerBytes);
romBytes.AddRange(songBanksBytes);
// Samples are at the end, right before the source engine code. MMC3 second to last and last banks respectively.
if (project.UsesSamples)
{
// Since we keep the code/engine at f000 all the time, we are limited to 12KB of samples in ROM.
var dpcmBytes = project.GetPackedSampleData();
Log.LogMessage(LogSeverity.Info, $"DPCM size: {dpcmBytes.Length} bytes.");
if (dpcmBytes.Length > MaxDpcmSize)
Log.LogMessage(LogSeverity.Warning, $"DPCM samples size ({dpcmBytes.Length}) is larger than the maximum allowed for ROM export ({MaxDpcmSize}). Truncating.");
// Always allocate the full 11KB of samples.
Array.Resize(ref dpcmBytes, MaxDpcmSize);
romBytes.AddRange(dpcmBytes);
}
else
{
romBytes.AddRange(new byte[MaxDpcmSize]);
}
romBytes.AddRange(codeBytes);
File.WriteAllBytes(filename, romBytes.ToArray());
Log.LogMessage(LogSeverity.Info, $"ROM export successful, final file size {romBytes.Count} bytes.");
}
#if !DEBUG
catch (Exception e)
{
Log.LogMessage(LogSeverity.Error, "Please contact the developer on GitHub!");
Log.LogMessage(LogSeverity.Error, e.Message);
Log.LogMessage(LogSeverity.Error, e.StackTrace);
return false;
}
#endif
return true;
}
19
View Source File : XAudio2Stream.cs
License : MIT License
Project Creator : BleuBleu
License : MIT License
Project Creator : BleuBleu
private void PlayAsync()
{
#if DEBUG
try
{
#endif
int nextBuffer = 0;
var waitEvents = new WaitHandle[] { quitEvent, bufferSemapreplaced };
while (true)
{
int idx = WaitHandle.WaitAny(waitEvents);
if (idx == 0)
{
break;
}
var size = memBuffers[nextBuffer].Size;
var data = bufferFill();
if (data != null)
{
size = data.Length * sizeof(short);
Debug.replacedert(data.Length * sizeof(short) <= memBuffers[nextBuffer].Size);
Marshal.Copy(data, 0, memBuffers[nextBuffer].Pointer, data.Length);
}
audioBuffersRing[nextBuffer].AudioDataPointer = memBuffers[nextBuffer].Pointer;
audioBuffersRing[nextBuffer].AudioBytes = size;
sourceVoice.SubmitSourceBuffer(audioBuffersRing[nextBuffer], null);
nextBuffer = ++nextBuffer % audioBuffersRing.Length;
}
#if DEBUG
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
if (Debugger.IsAttached)
Debugger.Break();
}
#endif
}
19
View Source File : XAudio2Stream.cs
License : MIT License
Project Creator : BleuBleu
License : MIT License
Project Creator : BleuBleu
public void PlayImmediate(short[] data, int sampleRate, float volume)
{
Debug.replacedert(PlatformUtils.IsInMainThread());
StopImmediate();
immediateDonePlaying = false;
immediateAudioBuffer = new AudioBuffer();
immediateAudioBuffer.AudioDataPointer = Utilities.AllocateMemory(data.Length * sizeof(short));
immediateAudioBuffer.AudioBytes = data.Length * sizeof(short);
Marshal.Copy(data, 0, immediateAudioBuffer.AudioDataPointer, data.Length);
var waveFormat = new WaveFormat(sampleRate, 16, 1);
immediateVoice = new SourceVoice(xaudio2, waveFormat);
immediateVoice.BufferEnd += ImmediateVoice_BufferEnd;
immediateVoice.SetVolume(volume);
immediateVoice.SubmitSourceBuffer(immediateAudioBuffer, null);
immediateVoice.Start();
}
19
View Source File : FdsFile.cs
License : MIT License
Project Creator : BleuBleu
License : MIT License
Project Creator : BleuBleu
public unsafe bool Save(Project originalProject, string filename, int[] songIds, string name, string author)
{
try
{
if (songIds.Length == 0)
return false;
if (songIds.Length > MaxSongs)
Array.Resize(ref songIds, MaxSongs);
var project = originalProject.DeepClone();
project.DeleteAllSongsBut(songIds);
// Need to be using only FDS.
if (project.ExpansionAudioMask != ExpansionType.FdsMask)
project.SetExpansionAudioMask(ExpansionType.FdsMask);
string fdsDiskName = "FamiStudio.Rom.fds";
if (project.UsesFamiTrackerTempo)
fdsDiskName += "_famitracker";
fdsDiskName += ".fds";
// Read FDS disk header + code.
var fdsDiskBinStream = typeof(RomFile).replacedembly.GetManifestResourceStream(fdsDiskName);
var fdsDiskInitBytes = new byte[fdsDiskBinStream.Length];
fdsDiskBinStream.Read(fdsDiskInitBytes, 0, fdsDiskInitBytes.Length);
TruncateToLastFile(ref fdsDiskInitBytes);
var fdsFileBytes = new List<byte>();
fdsFileBytes.AddRange(fdsDiskInitBytes);
Log.LogMessage(LogSeverity.Info, $"FDS code and graphics files: {fdsDiskInitBytes.Length} bytes.");
var fileIndex = FdsFirstFileIndex;
var dpcmFileIndex = 0;
// Create the DPCM file if needed.
if (project.UsesSamples)
{
var dpcmBytes = project.GetPackedSampleData();
if (dpcmBytes.Length > FdsMaxDpcmSize)
{
Log.LogMessage(LogSeverity.Warning, $"DPCM samples size ({dpcmBytes.Length}) is larger than the maximum allowed for FDS export ({FdsMaxDpcmSize}). Truncating.");
Array.Resize(ref dpcmBytes, FdsMaxDpcmSize);
}
AddFile(fdsFileBytes, fileIndex, FdsDpcmStart, "DPCM....", dpcmBytes);
dpcmFileIndex = fileIndex;
fileIndex++;
Log.LogMessage(LogSeverity.Info, $"DPCM file size: {dpcmBytes.Length} bytes.");
}
var projectInfo = BuildProjectInfo(songIds, name, author);
var songTable = BuildSongTableOfContent(project);
// Export each song as an individual file.
for (int i = 0; i < project.Songs.Count; i++)
{
var song = project.Songs[i];
var songBytes = new FamitoneMusicFile(FamiToneKernel.FamiStudio, false).GetBytes(project, new int[] { song.Id }, FdsSongDataAddr, FdsDpcmStart, MachineType.NTSC);
songTable[i].bank = (byte)fileIndex;
songTable[i].flags = (byte)(song.UsesDpcm ? dpcmFileIndex : 0);
if (songBytes.Length > FdsMaxSongSize)
{
Log.LogMessage(LogSeverity.Warning, $"Song '{song.Name}' is too large ({songBytes.Length} bytes, maximum is {FdsMaxSongSize}). File will be corrupted.");
Array.Resize(ref songBytes, FdsMaxSongSize);
}
if (fdsFileBytes.Count + FdsBlockHeaderSize + songBytes.Length > FdsMaxFileSize)
{
Log.LogMessage(LogSeverity.Warning, $"Reached maximum file size ({FdsMaxFileSize}). Songs will be missing.");
break;
}
AddFile(fdsFileBytes, fileIndex, FdsSongDataAddr, $"SONG{i}...", songBytes);
fileIndex++;
Log.LogMessage(LogSeverity.Info, $"Song '{song.Name}' file size: {songBytes.Length} bytes.");
}
//File.WriteAllBytes("D:\\dump\\fdsdata.bin", fdsFileBytes.ToArray());
// Use this field for the number of files.
projectInfo.fdsFileCount = (byte)fileIndex;
// Pad rest with zeroes.
fdsFileBytes.AddRange(new byte[FdsMaxFileSize - fdsFileBytes.Count]);
// Build project info + song table of content.
var tocBytes = new byte[sizeof(RomProjectInfo) + sizeof(RomSongEntry) * songTable.Length];
Marshal.Copy(new IntPtr(&projectInfo), tocBytes, 0, sizeof(RomProjectInfo));
for (int i = 0; i < MaxSongs; i++)
{
fixed (RomSongEntry* songEntry = &songTable[i])
Marshal.Copy(new IntPtr(songEntry), tocBytes, sizeof(RomProjectInfo) + i * sizeof(RomSongEntry), sizeof(RomSongEntry));
}
//File.WriteAllBytes("D:\\dump\\fdstoc.bin", tocBytes);
// Path TOC file.
var byteArray = fdsFileBytes.ToArray();
PatchFile(byteArray, "TOC.....", tocBytes);
// Build final ROM and save.
File.WriteAllBytes(filename, byteArray);
Log.LogMessage(LogSeverity.Info, $"FDS export successful, final file size {byteArray.Length} bytes.");
}
catch (Exception e)
{
Log.LogMessage(LogSeverity.Error, "Please contact the developer on GitHub!");
Log.LogMessage(LogSeverity.Error, e.Message);
Log.LogMessage(LogSeverity.Error, e.StackTrace);
return false;
}
return true;
}
19
View Source File : LocalGroupTasks.cs
License : GNU General Public License v3.0
Project Creator : BloodHoundAD
License : GNU General Public License v3.0
Project Creator : BloodHoundAD
private static bool CallLocalGroupApi(Computer computer, LocalGroupRids rid, out IntPtr[] sids)
{
//Initialize pointers for later
var serverHandle = IntPtr.Zero;
var domainHandle = IntPtr.Zero;
var aliasHandle = IntPtr.Zero;
var members = IntPtr.Zero;
sids = new IntPtr[0];
//Create some objects required for SAMRPC calls
var server = new UNICODE_STRING(computer.APIName);
var objectAttributes = new OBJECT_ATTRIBUTES();
try
{
//Step 1: Call SamConnect to open a handle to the computer's SAM
//0x1 = SamServerLookupDomain, 0x20 = SamServerConnect
var status = SamConnect(ref server, out serverHandle, 0x1 | 0x20, ref objectAttributes);
switch (status)
{
case NtStatus.StatusRpcServerUnavailable:
if (Options.Instance.DumpComputerStatus)
OutputTasks.AddComputerStatus(new ComputerStatus
{
ComputerName = computer.DisplayName,
Status = status.ToString(),
Task = $"GetNetLocalGroup-{rid}"
});
return false;
case NtStatus.StatusSuccess:
break;
default:
if (Options.Instance.DumpComputerStatus)
OutputTasks.AddComputerStatus(new ComputerStatus
{
ComputerName = computer.DisplayName,
Status = status.ToString(),
Task = $"GetNetLocalGroup-{rid}"
});
return false;
}
//Step 2 - Open the built in domain, which is identified by the SID S-1-5-32
//0x200 = Lookup
status = SamOpenDomain(serverHandle, 0x200, LocalSidBytes.Value, out domainHandle);
if (status != NtStatus.StatusSuccess)
{
if (Options.Instance.DumpComputerStatus)
OutputTasks.AddComputerStatus(new ComputerStatus
{
ComputerName = computer.DisplayName,
Status = status.ToString(),
Task = $"GetNetLocalGroup-{rid}"
});
return false;
}
//Step 3 - Open the alias that corresponds to the group we want to enumerate.
//0x4 = ListMembers
status = SamOpenAlias(domainHandle, 0x4, (int)rid, out aliasHandle);
if (status != NtStatus.StatusSuccess)
{
if (Options.Instance.DumpComputerStatus)
OutputTasks.AddComputerStatus(new ComputerStatus
{
ComputerName = computer.DisplayName,
Status = status.ToString(),
Task = $"GetNetLocalGroup-{rid}"
});
}
//Step 4 - Get the members of the alias we opened in step 3.
status = SamGetMembersInAlias(aliasHandle, out members, out var count);
if (status != NtStatus.StatusSuccess)
{
if (Options.Instance.DumpComputerStatus)
OutputTasks.AddComputerStatus(new ComputerStatus
{
ComputerName = computer.DisplayName,
Status = status.ToString(),
Task = $"GetNetLocalGroup-{rid}"
});
return false;
}
//If we didn't get any objects, just return false
if (count == 0)
{
return false;
}
//Copy the IntPtr to an array so we can loop over it
sids = new IntPtr[count];
Marshal.Copy(members, sids, 0, count);
return true;
}
finally
{
//Free memory from handles acquired during the process
if (serverHandle != IntPtr.Zero)
SamCloseHandle(serverHandle);
if (domainHandle != IntPtr.Zero)
SamCloseHandle(domainHandle);
if (aliasHandle != IntPtr.Zero)
SamCloseHandle(aliasHandle);
if (members != IntPtr.Zero)
SamFreeMemory(members);
}
}
19
View Source File : Window.cs
License : MIT License
Project Creator : BluestormDNA
License : MIT License
Project Creator : BluestormDNA
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Render(int[] vram) {
//Console.WriteLine($"x1 {displayX1} x2 {displayX2} y1 {displayY1} y2 {displayY2}");
int horizontalEnd = horizontalRes;
int verticalEnd = verticalRes;
if (isVramViewer) {
horizontalEnd = 1024;
verticalEnd = 512;
Marshal.Copy(vram, 0, display.BitmapData, 0x80000);
} else if (is24BitDepth) {
blit24bpp(vram);
} else {
blit16bpp(vram);
}
fps++;
using var deviceContext = new GdiDeviceContext(screen.Handle);
Gdi32.StretchBlt(deviceContext, 0, 0, screen.Width, screen.Height,
display.DeviceContext, 0, 0, horizontalEnd, verticalEnd,
RasterOp.SRCCOPY);
}
19
View Source File : ViveMediaDecoder.cs
License : MIT License
Project Creator : bodhid
License : MIT License
Project Creator : bodhid
public static void getMetaData(string filePath, out string[] key, out string[] value) {
IntPtr keyptr = IntPtr.Zero;
IntPtr valptr = IntPtr.Zero;
int metaCount = nativeGetMetaData(filePath, out keyptr, out valptr);
IntPtr[] keys = new IntPtr[metaCount];
IntPtr[] vals = new IntPtr[metaCount];
Marshal.Copy(keyptr, keys, 0, metaCount);
Marshal.Copy(valptr, vals, 0, metaCount);
string[] keyArray = new string[metaCount];
string[] valArray = new string[metaCount];
for (int i = 0; i < metaCount; i++) {
keyArray[i] = Marshal.PtrToStringAnsi(keys[i]);
valArray[i] = Marshal.PtrToStringAnsi(vals[i]);
Marshal.FreeCoTaskMem(keys[i]);
Marshal.FreeCoTaskMem(vals[i]);
}
Marshal.FreeCoTaskMem(keyptr);
Marshal.FreeCoTaskMem(valptr);
key = keyArray;
value = valArray;
}
19
View Source File : FirFilter.cs
License : MIT License
Project Creator : bonsai-rx
License : MIT License
Project Creator : bonsai-rx
public override IObservable<Mat> Process(IObservable<Mat> source)
{
return Observable.Defer(() =>
{
Mat kernel = null;
Mat overlap = null;
Mat overlapInput = null;
Mat overlapEnd = null;
Mat overlapStart = null;
Mat overlapFilter = null;
Rect overlapOutput = default(Rect);
float[] currentKernel = null;
return source.Select(input =>
{
if (Kernel != currentKernel ||
currentKernel != null &&
(input.Rows != overlapOutput.Height ||
input.Cols != overlapOutput.Width))
{
currentKernel = Kernel;
if (currentKernel == null || currentKernel.Length == 0) kernel = null;
else
{
kernel = new Mat(1, currentKernel.Length, Depth.F32, 1);
Marshal.Copy(currentKernel, 0, kernel.Data, currentKernel.Length);
var anchor = Anchor;
if (anchor == -1) anchor = kernel.Cols / 2;
overlap = new Mat(input.Rows, input.Cols + kernel.Cols - 1, input.Depth, input.Channels);
overlapInput = overlap.GetSubRect(new Rect(kernel.Cols - 1, 0, input.Cols, input.Rows));
overlapFilter = new Mat(overlap.Rows, overlap.Cols, overlap.Depth, overlap.Channels);
if (kernel.Cols > 1)
{
overlapEnd = overlap.GetSubRect(new Rect(overlap.Cols - kernel.Cols + 1, 0, kernel.Cols - 1, input.Rows));
overlapStart = overlap.GetSubRect(new Rect(0, 0, kernel.Cols - 1, input.Rows));
}
overlapOutput = new Rect(anchor, 0, input.Cols, input.Rows);
CV.CopyMakeBorder(input, overlap, new Point(kernel.Cols - 1, 0), IplBorder.Reflect);
}
}
if (kernel == null) return input;
else
{
CV.Copy(input, overlapInput);
CV.Filter2D(overlap, overlapFilter, kernel, new Point(Anchor, -1));
if (overlapEnd != null) CV.Copy(overlapEnd, overlapStart);
return overlapFilter.GetSubRect(overlapOutput).Clone();
}
});
});
}
19
View Source File : ThemeHelper.cs
License : MIT License
Project Creator : bonsai-rx
License : MIT License
Project Creator : bonsai-rx
public static Image Invert(Image image)
{
var result = new Bitmap(image);
var pixelRange = new Rectangle(0, 0, result.Width, result.Height);
var pixelData = result.LockBits(pixelRange, ImageLockMode.ReadWrite, result.PixelFormat);
try
{
var values = new byte[pixelData.Stride * pixelData.Height];
Marshal.Copy(pixelData.Scan0, values, 0, values.Length);
for (int i = 0; i < values.Length; i += 4)
{
Invert(ref values[i + 2],
ref values[i + 1],
ref values[i + 0]);
}
Marshal.Copy(values, 0, pixelData.Scan0, values.Length);
}
finally { result.UnlockBits(pixelData); }
return result;
}
19
View Source File : RoiActivity.cs
License : MIT License
Project Creator : bonsai-rx
License : MIT License
Project Creator : bonsai-rx
public override IObservable<RegionActivityCollection> Process(IObservable<IplImage> source)
{
return Observable.Defer(() =>
{
var roi = default(IplImage);
var mask = default(IplImage);
var currentRegions = default(Point[][]);
var boundingRegions = default(Rect[]);
return source.Select(input =>
{
var operation = Operation;
var output = new RegionActivityCollection();
mask = IplImageHelper.EnsureImageFormat(mask, input.Size, IplDepth.U8, 1);
if (operation != ReduceOperation.Sum) roi = null;
else roi = IplImageHelper.EnsureImageFormat(roi, input.Size, input.Depth, input.Channels);
if (Regions != currentRegions)
{
currentRegions = Regions;
if (currentRegions != null)
{
mask.SetZero();
CV.FillPoly(mask, currentRegions, Scalar.All(255));
boundingRegions = currentRegions.Select(polygon =>
{
var points = polygon.SelectMany(point => new[] { point.X, point.Y }).ToArray();
using (var mat = new Mat(1, polygon.Length, Depth.S32, 2))
{
Marshal.Copy(points, 0, mat.Data, points.Length);
return CV.BoundingRect(mat);
}
}).ToArray();
}
}
if (currentRegions != null)
{
var activeMask = mask;
if (roi != null)
{
roi.SetZero();
CV.Copy(input, roi, mask);
activeMask = roi;
}
var activation = ActivationFunction(operation);
for (int i = 0; i < boundingRegions.Length; i++)
{
var rect = boundingRegions[i];
var polygon = currentRegions[i];
using (var region = input.GetSubRect(rect))
using (var regionMask = activeMask.GetSubRect(rect))
{
output.Add(new RegionActivity
{
Roi = polygon,
Rect = rect,
Activity = activation(region, regionMask)
});
}
}
}
return output;
});
});
}
19
View Source File : CropPolygon.cs
License : MIT License
Project Creator : bonsai-rx
License : MIT License
Project Creator : bonsai-rx
public override IObservable<IplImage> Process(IObservable<IplImage> source)
{
return Observable.Defer(() =>
{
var mask = default(IplImage);
var boundingBox = default(Rect);
var currentRegions = default(Point[][]);
return source.Select(input =>
{
if (Regions != currentRegions)
{
currentRegions = Regions;
boundingBox = default(Rect);
if (currentRegions != null)
{
mask = new IplImage(input.Size, IplDepth.U8, 1);
mask.SetZero();
var points = currentRegions
.SelectMany(region => region)
.SelectMany(point => new[] { point.X, point.Y })
.ToArray();
if (points.Length > 0)
{
using (var mat = new Mat(1, points.Length / 2, Depth.S32, 2))
{
Marshal.Copy(points, 0, mat.Data, points.Length);
boundingBox = CV.BoundingRect(mat);
boundingBox = ClipRectangle(boundingBox, input.Size);
}
CV.FillPoly(mask, currentRegions, Scalar.All(255));
if (cropOutput) mask = mask.GetSubRect(boundingBox);
}
}
else mask = null;
}
var selectionType = MaskType;
if (selectionType <= ThresholdTypes.BinaryInv)
{
var size = mask != null ? mask.Size : input.Size;
var output = new IplImage(size, IplDepth.U8, 1);
switch (selectionType)
{
case ThresholdTypes.Binary:
if (mask == null) output.SetZero();
else CV.Copy(mask, output);
break;
case ThresholdTypes.BinaryInv:
if (mask == null) output.Set(Scalar.All(255));
else CV.Not(mask, output);
break;
default:
throw new InvalidOperationException("Selection operation is not supported.");
}
return output;
}
if (currentRegions != null && boundingBox.Width > 0 && boundingBox.Height > 0)
{
var output = new IplImage(mask.Size, input.Depth, input.Channels);
var inputRoi = cropOutput ? input.GetSubRect(boundingBox) : input;
try
{
switch (selectionType)
{
case ThresholdTypes.ToZeroInv:
var fillRoi = cropOutput ? inputRoi : input;
CV.Copy(fillRoi, output);
output.Set(FillValue, mask);
break;
case ThresholdTypes.ToZero:
output.Set(FillValue);
CV.Copy(inputRoi, output, mask);
break;
default:
throw new InvalidOperationException("Selection operation is not supported.");
}
}
finally
{
if (inputRoi != input) inputRoi.Close();
}
return output;
}
return input;
});
});
}
See More Examples