/// <summary> /// Updates the vertex buffer to be a quad with 1pt in width/height and with the pivot in the center of it /// </summary> /// <param name="vertexBuffer">Vertex Buffer to update</param> /// <param name="colorKey">Color Key to apply to the buffer</param> protected void UpdateBufferData(VertexBuffer vertexBuffer, Color colorKey) { int color = colorKey.ToArgb(); try { Microsoft.DirectX.GraphicsStream stm = vertexBuffer.Lock(0, 0, 0); CustomVertex.PositionColoredTextured[] verts = (CustomVertex.PositionColoredTextured[])vertexBuffer.Lock(0, LockFlags.Discard); // Bottom left verts[0] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( -0.5f, 0.5f, 0), color, 0.0f, 1.0f); // Top left verts[1] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( -0.5f, -0.5f, 0), color, 0.0f, 0.0f); // Bottom right verts[2] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( 0.5f, 0.5f, 0), color, 1.0f, 1.0f); // Top right verts[3] = new CustomVertex.PositionColoredTextured( new Microsoft.DirectX.Vector3( 0.5f, -0.5f, 0), color, 1.0f, 0.0f); stm.Write(verts); vertexBuffer.Unlock(); } catch (Exception) { try { vertexBuffer.Unlock(); } catch (Exception) {} } }
public static void GetBoundingBox(D3D.Mesh mesh, float scale, out DX.Vector3 min, out DX.Vector3 max) { D3D.VertexBuffer verts = mesh.VertexBuffer; DX.GraphicsStream stream = verts.Lock(0, 0, D3D.LockFlags.None); D3D.Geometry.ComputeBoundingBox(stream, mesh.NumberVertices, mesh.VertexFormat, out min, out max); verts.Unlock(); stream = null; verts = null; }
private void fixBitmapAlpha(Microsoft.DirectX.GraphicsStream gs, Bitmap btmap, ImageInformation imInfo) { btmap.MakeTransparent(); gs.Seek(0, 0); System.Drawing.Imaging.BitmapData bmpData = btmap.LockBits(new Rectangle(0, 0, imInfo.Width, imInfo.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, btmap.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * btmap.Height; int gsLen = (int)gs.Length; byte[] rgbaValues = new byte[bytes]; byte[] gsBytes = new byte[gsLen]; gs.Read(gsBytes, 0, gsLen); int gsLastI = gsLen - 1; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbaValues, 0, bytes); int i = 0; for (int y = 0; y < bmpData.Height; y++) { for (int x = 0; x < bmpData.Width; x++) { byte g = gsBytes[gsLastI - i++], b = gsBytes[gsLastI - i++], a = gsBytes[gsLastI - i++], r = gsBytes[gsLastI - i++]; if (invertAlpha.Checked) { a = (byte)(255 - a); } Color pClr = Color.FromArgb(a, r, g, b); System.Runtime.InteropServices.Marshal.WriteInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x), pClr.ToArgb()); } } btmap.UnlockBits(bmpData); btmap.RotateFlip(RotateFlipType.Rotate180FlipY); }
public static float GetBoundingRadius(D3D.Mesh mesh, float scale) { D3D.VertexBuffer verts = mesh.VertexBuffer; DX.GraphicsStream stream = verts.Lock(0, 0, D3D.LockFlags.None); DX.Vector3 meshCenter; float radius = D3D.Geometry.ComputeBoundingSphere(stream, mesh.NumberVertices, mesh.VertexFormat, out meshCenter) * scale; verts.Unlock(); stream = null; verts = null; return(radius); }
/// <summary> /// Unloads data that is no longer needed. /// </summary> protected override void UnloadHighLevelImpl() { if (microcode != null) { microcode.Close(); microcode = null; } if (constantTable != null) { constantTable.Dispose(); constantTable = null; } }
/// <summary> /// Compiles the high level shader source to low level microcode. /// </summary> protected override void LoadFromSource() { string errors; Macro [] macros = null; if (preprocessorDefines != "") { string [] values = preprocessorDefines.Split(new char[] { ',', ';' }); macros = new Macro[values.Length]; for (int i = 0; i < values.Length; i++) { string s = values[i].Trim(); string [] stm = s.Split(new char[] { '=' }); Macro macro = new Macro(); if (stm.Length == 1) { macro.Name = s; } else { macro.Name = stm[0].Trim(); macro.Definition = stm[1].Trim(); } macros[i] = macro; } } // compile the high level shader to low level microcode // note, we need to pack matrices in row-major format for HLSL microcode = ShaderLoader.CompileShader( source, entry, macros, new HLSLInclude(), target, (columnMajorMatrices ? ShaderFlags.PackMatrixColumnMajor : ShaderFlags.PackMatrixRowMajor), out errors, out constantTable); //LogManager.Instance.Write(ShaderLoader.DisassembleShader(microcode, false, null)); // check for errors if (errors != null && errors.Length > 0) { LogManager.Instance.Write("Error compiling HLSL shader {0}:\n{1}", name, errors); // errors can include warnings, so don't throw unless the compile actually failed. if (microcode == null) { throw new AxiomException("HLSL: Unable to compile high level shader {0}:\n{1}", name, errors); } } }
/// <summary> /// Creates a texture from a bitmap. Much, much faster than Texture.FromBitmap. /// </summary> /// <param name="bmp"></param> Texture TextureFromBitmap(Bitmap bmp) { Texture texture = new Texture(display[0], bmp.Width, bmp.Height, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default); Microsoft.DirectX.GraphicsStream a = texture.LockRectangle(0, LockFlags.None); BitmapData bd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); unsafe { uint *to = (uint *)a.InternalDataPointer; uint *from = (uint *)bd.Scan0.ToPointer(); for (int i = 0; i < bd.Height * bd.Width; ++i) { to[i] = from[i]; } } texture.UnlockRectangle(0); bmp.UnlockBits(bd); a.Dispose(); return(texture); }
private void setIconImage(string path, PictureBox pBx) { try { PresentParameters pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Copy; Device device = new Device(0, DeviceType.Hardware, this.tgaIconPicBx, CreateFlags.HardwareVertexProcessing, pp); Microsoft.DirectX.Direct3D.Texture tx = TextureLoader.FromFile(device, path); Microsoft.DirectX.GraphicsStream gs = TextureLoader.SaveToStream(ImageFileFormat.Png, tx); Bitmap btmap = new Bitmap(gs); pBx.Image = btmap; gs.Dispose(); tx.Dispose(); device.Dispose(); } catch (Exception ex) { } }
/// <summary> /// Initializes all the Textures based on the configuration settings /// </summary> private void InitDeviceMem() { // generic quad vertex buffer try { int color = Color.White.ToArgb(); this.GenericQuad = new VertexBuffer(typeof(CustomVertex.PositionColoredTextured), 4, display, Usage.Dynamic, CustomVertex.TransformedColoredTextured.Format, Pool.Default); Microsoft.DirectX.GraphicsStream stm = GenericQuad.Lock(0, 0, 0); CustomVertex.PositionColoredTextured[] verts = (CustomVertex.PositionColoredTextured[])GenericQuad.Lock(0, LockFlags.None); // Bottom left verts[0] = new CustomVertex.PositionColoredTextured( new Vector3( -0.5f, 0.5f, 0), color, 0.0f, 1.0f); // Top left verts[1] = new CustomVertex.PositionColoredTextured( new Vector3( -0.5f, -0.5f, 0), color, 0.0f, 0.0f); // Bottom right verts[2] = new CustomVertex.PositionColoredTextured( new Vector3( 0.5f, 0.5f, 0), color, 1.0f, 1.0f); // Top right verts[3] = new CustomVertex.PositionColoredTextured( new Vector3( 0.5f, -0.5f, 0), color, 1.0f, 0.0f); stm.Write(verts); GenericQuad.Unlock(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace); try { GenericQuad.Unlock(); } catch (Exception) {} } // font objects fntOut = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font(Global.Configuration.Fonts.LabelFont, Global.Configuration.Fonts.LabelSize, Global.Configuration.Fonts.LabelStyle)); descOut = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font(Global.Configuration.Fonts.DescriptionFont, Global.Configuration.Fonts.DescriptionSize, Global.Configuration.Fonts.DescriptionStyle)); #if DEBUG dbo = new Microsoft.DirectX.Direct3D.Font(display, new System.Drawing.Font("Tahoma", 10)); #endif // init Sprite painter SpritePainter = new Sprite(display); // get a pointer to the back buffer back = display.GetBackBuffer(0, 0, BackBufferType.Mono); // init composite texture InitCompositeTexture(); // load bg only if is not using transparency if (Global.Configuration.Appearance.Transparency != Orbit.Configuration.TransparencyMode.Real) { // load the proper background provider if (Global.Configuration.Images.UseWindowsWallpaper) { // init the wallpaper sync background provider BGProvider = new WindowsBackgroundProvider(display, SpritePainter); BGProvider.BackgroundColor = Global.Configuration.Images.BackgroundColor; } else { // init the background provider BGProvider = new BackgroundProvider(display, SpritePainter); // assing bg image if (Global.Configuration.Images.BackgroundImagePath != "") { BGProvider.BackgroundPath = Global.Configuration.Images.BackgroundImagePath; // pass on the backgorund size ImageInformation ii = Microsoft.DirectX.Direct3D.TextureLoader.ImageInformationFromFile(Global.Configuration.Images.BackgroundImagePath); BGProvider.BackgroundSize = new Size(ii.Width, ii.Height); } // pass the background color BGProvider.BackgroundColor = Color.FromArgb(0xFF, Global.Configuration.Images.BackgroundColor); } } // Load Icon Background if (Global.Configuration.Images.IconBackgroundImagePath != "") { SetIconBg(Global.Configuration.Images.IconBackgroundImagePath); } // Load Selected Icon overlay if (Global.Configuration.Images.IconSelectedImagePath != "") { SetIconSelected(Global.Configuration.Images.IconSelectedImagePath); } // load the scroll up image if (Global.Configuration.Images.ScrollUpImagePath != "") { SetScrollUp(Global.Configuration.Images.ScrollUpImagePath); } // load the scroll down image if (Global.Configuration.Images.ScrollDownImagePath != "") { SetScrollDown(Global.Configuration.Images.ScrollDownImagePath); } }
private void setIconImage(string path) { try { PresentParameters pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Copy; Device device = new Device(0, DeviceType.Hardware, this.rgb_picBx, CreateFlags.HardwareVertexProcessing, pp); Microsoft.DirectX.Direct3D.Texture tx = TextureLoader.FromFile(device, path); Microsoft.DirectX.GraphicsStream gs = TextureLoader.SaveToStream(ImageFileFormat.Dib, tx); Bitmap RGB_bitmap = new Bitmap(gs); Bitmap alpha_bitmap = new Bitmap(gs); rgb_picBx.Image = RGB_bitmap; //alpha_bitmap.MakeTransparent(); gs.Seek(0, 0); System.Drawing.Imaging.BitmapData bmpData = alpha_bitmap.LockBits(new Rectangle(0, 0, alpha_bitmap.Width, alpha_bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, alpha_bitmap.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * alpha_bitmap.Height; int gsLen = (int)gs.Length; byte[] rgbaValues = new byte[bytes]; byte[] gsBytes = new byte[gsLen]; gs.Read(gsBytes, 0, gsLen); int gsLastI = gsLen - 1; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbaValues, 0, bytes); int i = 0; for (int y = 0; y < bmpData.Height; y++) { for (int x = 0; x < bmpData.Width; x++) { byte g = gsBytes[gsLastI - i++], b = gsBytes[gsLastI - i++], a = gsBytes[gsLastI - i++], r = gsBytes[gsLastI - i++]; Color pClr = Color.FromArgb(255, a, a, a); System.Runtime.InteropServices.Marshal.WriteInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x), pClr.ToArgb()); } } alpha_bitmap.UnlockBits(bmpData); alpha_bitmap.RotateFlip(RotateFlipType.Rotate180FlipY); alpha_picBx.Image = alpha_bitmap; gs.Dispose(); tx.Dispose(); device.Dispose(); } catch (Exception ex) { } }
private Bitmap getImage(string fileName) { Microsoft.DirectX.GraphicsStream gs = null; Microsoft.DirectX.Direct3D.Texture tx = null; try { this.invertAlpha.Enabled = false; System.IO.MemoryStream mSr = getMemStream(fileName); mSr.Seek(0, 0); tx = TextureLoader.FromStream(device, mSr); mSr.Seek(0, 0); ImageInformation imInfo = TextureLoader.ImageInformationFromStream(mSr); mSr.Close(); fillTxtBx(imInfo); gs = TextureLoader.SaveToStream(ImageFileFormat.Dib, tx); Bitmap btmap = new Bitmap(gs); if (hasAlpha) { aChk.Enabled = true; invertAlpha.Enabled = true; fixBitmapAlpha(gs, btmap, imInfo); } return(btmap); } catch (Exception e) { if (gs != null) { gs.Close(); gs.Dispose(); } if (tx != null) { tx.Dispose(); } if (pp != null) { pp = null; pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Copy; } if (device != null) { device.Dispose(); device = null; device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp); } return(null); } }
private Bitmap getBitmap(string path) { PresentParameters pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Copy; Device device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp); Microsoft.DirectX.Direct3D.Texture tx = TextureLoader.FromFile(device, path); Microsoft.DirectX.GraphicsStream gs = TextureLoader.SaveToStream(ImageFileFormat.Dib, tx); ImageInformation imInfo = TextureLoader.ImageInformationFromStream(gs); Bitmap btmap = new Bitmap(gs); btmap.MakeTransparent(); gs.Seek(0, 0); System.Drawing.Imaging.BitmapData bmpData = btmap.LockBits(new Rectangle(0, 0, btmap.Width, btmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, btmap.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * btmap.Height; int gsLen = (int)gs.Length; byte[] rgbaValues = new byte[bytes]; byte[] gsBytes = new byte[gsLen]; gs.Read(gsBytes, 0, gsLen); int gsLastI = gsLen - 1; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbaValues, 0, bytes); int i = 0; for (int y = 0; y < bmpData.Height; y++) { for (int x = 0; x < bmpData.Width; x++) { byte g = gsBytes[gsLastI - i++], b = gsBytes[gsLastI - i++], a = gsBytes[gsLastI - i++], r = gsBytes[gsLastI - i++]; if (invertAlpha.Checked) { a = (byte)(255 - a); } Color pClr = Color.FromArgb(a, r, g, b); System.Runtime.InteropServices.Marshal.WriteInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x), pClr.ToArgb()); } } btmap.UnlockBits(bmpData); btmap.RotateFlip(RotateFlipType.Rotate180FlipY); return(btmap); }
public void RefreshTexture() { if (tileData != null && dirtyImage) { EnsureTextureIsDynamic(); // Unload texture & recreate if needed Texture texture = TextureManager.Instance.GetByName(textureName); if (texture == null) { // We couldn't find the texture. It might be that we're in // the midst of swapping them at the DirectX level (this is // only speculation) return; } if (texture is D3DTexture) { // Turns out that to get performance, not only did I have to go // straight to DirectX, unsafe code is much faster as well. What // we're doing here is keeping a temporary surface around that we // can lock and draw to at our leisure, then copying the surface // over to the correct texture data when we're done. To do this, // the easiest way is to lock the desired rectangle on the temp // surface, and get a graphics stream object back from it. You // might think you could then use byte arrays, or even ask for // an Array of bytes back from LockRectangle, but not only was // that slower, it also produced unpredictable results, possibly // due to storing the array in row order vs. column order in the // native vs. managed areas. // // The temporary surface is necessary because, well, I could // never seem to acquire the lock on the real surface. However, // an offscreen plain surface (as used above) seems to lock fine. // // Next caveat: The pointer on the graphics stream points to the // start of the row of the locked rectangle. You'd be surprised // how long it took me to figure that one out. Further, it's // important to use the pitch returned by LockRectangle to adjust // your row array position, as the pitch may or may not be your // surface width in bytes. (Some drivers store extra data on the // ends of the rows, it seems.) Rectangle lockRect = new Rectangle(); lockRect.X = dirtyArea.X; lockRect.Y = dirtyArea.Y; lockRect.Width = dirtyArea.Width; lockRect.Height = dirtyArea.Height; D3D.Texture t = (texture as D3DTexture).DXTexture as D3D.Texture; int pitch; int bpp = PixelUtil.GetNumElemBytes(texture.Format); D3D.Surface dst = t.GetSurfaceLevel(0); DX.GraphicsStream g = dynamicSurface.LockRectangle(lockRect, D3D.LockFlags.NoSystemLock, out pitch); unsafe { uint *dstArray = (uint *)g.InternalDataPointer; pitch /= sizeof(uint); for (int z = 0; z < lockRect.Height; z++) { for (int x = 0; x < lockRect.Width; x++) { uint data = GetData(x + lockRect.X, z + lockRect.Y); uint converted = ConvertPixel(data, INTERNAL_DATA_FORMAT, texture.Format); dstArray[z * pitch + x] = converted; } } } dynamicSurface.UnlockRectangle(); D3D.SurfaceLoader.FromSurface(dst, dynamicSurface, D3D.Filter.None, 0); } else { #if false // following code is for blitting only the dirty rectangle BasicBox destBox = new BasicBox(dirtyArea.X, dirtyArea.Y, dirtyArea.X + dirtyArea.Width, dirtyArea.Y + dirtyArea.Height); PixelBox srcPixel = textureImage.GetPixelBox(0, 0); BasicBox srcBox = new BasicBox(0, 0, dirtyArea.Width, dirtyArea.Height); PixelBox trimmedSrcPixel = srcPixel.GetSubVolume(srcBox); buffer.BlitFromMemory(trimmedSrcPixel, destBox); #endif } // Clean up dirty bit dirtyImage = false; dirtyArea.X = 0; dirtyArea.Y = 0; dirtyArea.Width = 0; dirtyArea.Height = 0; } }
/// <summary> /// Compiles the high level shader source to low level microcode. /// </summary> protected override void LoadFromSource() { string errors; Macro [] macros = null; if (preprocessorDefines != "") { string [] values = preprocessorDefines.Split(new char[] {',', ';'}); macros = new Macro[values.Length]; for (int i=0; i<values.Length; i++) { string s = values[i].Trim(); string [] stm = s.Split(new char[] {'='}); Macro macro = new Macro(); if (stm.Length == 1) macro.Name = s; else { macro.Name = stm[0].Trim(); macro.Definition = stm[1].Trim(); } macros[i] = macro; } } // compile the high level shader to low level microcode // note, we need to pack matrices in row-major format for HLSL microcode = ShaderLoader.CompileShader( source, entry, macros, new HLSLInclude(), target, (columnMajorMatrices ? ShaderFlags.PackMatrixColumnMajor : ShaderFlags.PackMatrixRowMajor), out errors, out constantTable); //LogManager.Instance.Write(ShaderLoader.DisassembleShader(microcode, false, null)); // check for errors if(errors != null && errors.Length > 0) { LogManager.Instance.Write("Error compiling HLSL shader {0}:\n{1}", name, errors); // errors can include warnings, so don't throw unless the compile actually failed. if (microcode == null) { throw new AxiomException("HLSL: Unable to compile high level shader {0}:\n{1}", name, errors); } } }
/// <summary> /// Loads a shader object from the supplied microcode. /// </summary> /// <param name="microcode"> /// GraphicsStream that contains the assembler instructions for the program. /// </param> protected abstract void LoadFromMicrocode(Microsoft.DirectX.GraphicsStream microcode);