Exemple #1
0
            public unsafe void CreateTexture(BinaryReader reader)
            {
                int w = Width;  // + (4 - Width % 4) % 4;
                int h = Height; // + (4 - Height % 4) % 4;

                if (w == 0 || h == 0)
                {
                    return;
                }
                if ((w < 2) || (h < 2))
                {
                    return;
                }

                GraphicsStream stream = null;

                ImageTexture = new Texture(DXManager.Device, w, h, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
                stream       = ImageTexture.LockRectangle(0, LockFlags.Discard);
                Data         = (byte *)stream.InternalDataPointer;

                byte[] decomp = DecompressImage(reader.ReadBytes(Length));

                stream.Write(decomp, 0, decomp.Length);

                stream.Dispose();
                ImageTexture.UnlockRectangle(0);

                if (HasMask)
                {
                    reader.ReadBytes(12);
                    w = Width;  // + (4 - Width % 4) % 4;
                    h = Height; // + (4 - Height % 4) % 4;

                    MaskImageTexture = new Texture(DXManager.Device, w, h, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
                    stream           = MaskImageTexture.LockRectangle(0, LockFlags.Discard);

                    decomp = DecompressImage(reader.ReadBytes(Length));

                    stream.Write(decomp, 0, decomp.Length);

                    stream.Dispose();
                    MaskImageTexture.UnlockRectangle(0);
                }

                //DXManager.TextureList.Add(this);
                TextureValid = true;
                //Image.Disposing += (o, e) =>
                //{
                //    TextureValid = false;
                //    Image = null;
                //    MaskImage = null;
                //    Data = null;
                //    DXManager.TextureList.Remove(this);
                //};
            }
Exemple #2
0
        public unsafe void CreateTexture(BinaryReader reader)
        {
            int            w      = Width;  // + (4 - Width % 4) % 4;
            int            h      = Height; // + (4 - Height % 4) % 4;
            GraphicsStream stream = null;

            Image  = new Texture(DXManager.Device, w, h, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
            stream = Image.LockRectangle(0, LockFlags.Discard);
            Data   = (byte *)stream.InternalDataPointer;

            byte[] decomp = DecompressImage(reader.ReadBytes(Length));

            stream.Write(decomp, 0, decomp.Length);

            stream.Dispose();
            Image.UnlockRectangle(0);

            if (HasMask)
            {
                reader.ReadBytes(12);
                w = Width;  // + (4 - Width % 4) % 4;
                h = Height; // + (4 - Height % 4) % 4;

                MaskImage = new Texture(DXManager.Device, w, h, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
                stream    = MaskImage.LockRectangle(0, LockFlags.Discard);

                decomp = DecompressImage(reader.ReadBytes(Length));

                stream.Write(decomp, 0, decomp.Length);

                stream.Dispose();
                MaskImage.UnlockRectangle(0);
            }

            DXManager.TextureList.Add(this);
            TextureValid     = true;
            Image.Disposing += (o, e) =>
            {
                TextureValid = false;
                Image        = null;
                MaskImage    = null;
                Data         = null;
                DXManager.TextureList.Remove(this);
            };


            CleanTime = CMain.Time + Settings.CleanDelay;
        }
Exemple #3
0
        public void render()
        {
            Device dev = this._device;

            //頂点データをセット
            dev.RenderState.CullMode = Cull.None;
            GraphicsStream gs = this._container.mesh.LockVertexBuffer(LockFlags.Discard);

            gs.Write(this._vertex_array);
            gs.Dispose();
            this._container.mesh.UnlockVertexBuffer();

            for (int i = 0; i < this._container.material.Length; i++)
            {
                if (this._container.texture[i] != null)
                {
                    dev.SetTexture(0, this._container.texture[i]);
                }
                else
                {
                    dev.SetTexture(0, null);
                }
                dev.Material = this._container.material[i];
                this._container.mesh.DrawSubset(i);
            }
            return;
        }
        private void использоватьGPUToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                return;
            }
            Surface newbb = dr.CreateRenderTarget(bmhm.Width, bmhm.Height, Format.A8R8G8B8, MultiSampleType.None, 0, true);
            Surface oldbb = dr.GetRenderTarget(0);

            dr.SetRenderTarget(0, newbb);
            dr.BeginScene();
            dr.Clear(ClearFlags.Target, Color.Black, 1f, 0); //Очистка фона
            eff.SetValue("w", Matrix.Scaling(2.0f, 2.0f, 2.0f));
            eff.SetValue("v", Matrix.RotationX(0));
            eff.SetValue("p", Matrix.RotationX(0));
            eff.SetValue("txh", txh);
            eff.SetValue("h", himax);
            eff.Begin(FX.None);
            eff.BeginPass(2);
            dr.VertexFormat = CustomVertex.PositionNormalTextured.Format;
            dr.DrawUserPrimitives(PrimitiveType.TriangleFan, 2, dp);
            eff.EndPass();
            eff.End();
            dr.EndScene();

            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
            }
            if (gstr != null)
            {
                gstr.Dispose();
            }
            gstr = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, newbb);
            if (bmnm != null)
            {
                bmnm.Dispose();
            }
            bmnm = (Bitmap)Image.FromStream(gstr);
            pictureBox2.Image = (Image)bmnm;
            hdv = (float)bmnm.Width / (float)bmnm.Height;
            if (txn != null)
            {
                txn.Dispose();
            }
            txn = Texture.FromBitmap(dr, bmnm, Usage.None, Pool.Managed);
            dr.SetRenderTarget(0, oldbb);
            newbb.Dispose();
            oldbb.Dispose();
        }
Exemple #5
0
        public void render()
        {
            Device dev = this._device;
            //頂点データをセット
            GraphicsStream stm = this._vertex_buffer.Lock(0, 0, 0);

            stm.Write(this._vertex_array);
            stm.Dispose();
            this._vertex_buffer.Unlock();

            //
            D3dMaterial[] material = this._materials;
            for (int i = 0; i < material.Length; i++)
            {
                //カリング判定:何となくうまくいったから
                if ((0x100 & material[i].unknown) == 0x100)
                {
                    dev.RenderState.CullMode = Cull.None;
                }
                else
                {
                    dev.RenderState.CullMode = Cull.CounterClockwise;
                }

                dev.Material = material[i].material;
                if (material[i].texture != null)
                {
                    dev.SetTexture(0, material[i].texture);
                }
                else
                {
                    dev.SetTexture(0, null);
                }

                //インデクスをセット
                dev.Indices = material[i].index_buf;
                dev.SetStreamSource(0, this._vertex_buffer, 0);
                dev.VertexFormat = CustomVertex.PositionNormalTextured.Format;
                dev.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, material[i].ulNumIndices, 0, material[i].ulNumIndices / 3);
            }
            return;
        }
Exemple #6
0
        /// <summary>
        /// This callback function will be called immediately after the Direct3D device has
        /// been destroyed, which generally happens as a result of application termination or
        /// windowed/full screen toggles. Resources created in the OnCreateDevice callback
        /// should be released here, which generally includes all Pool.Managed resources.
        /// </summary>
        private void OnDestroyDevice(object sender, EventArgs e)
        {
            meshTextures  = null;
            meshMaterials = null;

            if (systemMemoryMesh != null)
            {
                systemMemoryMesh.Dispose();
                systemMemoryMesh = null;
            }
            if (adjacencyBuffer != null)
            {
                adjacencyBuffer.Dispose();
                adjacencyBuffer = null;
            }

            if (defaultTexture != null)
            {
                defaultTexture.Dispose();
                defaultTexture = null;
            }
        }
Exemple #7
0
        internal bool VisiblePixel(Point P)
        {
            bool Result = false;

            if (P.X < 0 || P.Y < 0 || P.X >= Size.Width || P.Y >= Size.Height)
            {
                return(false);
            }

            if (ImageTexture != null)
            {
                GraphicsStream GS = ImageTexture.LockRectangle(0, LockFlags.ReadOnly);
                unsafe
                {
                    byte *ImageBytes = (byte *)GS.InternalData;
                    Result = ImageBytes[(P.Y * Size.Width + P.X) * 4 + 3] != 0;
                }
                GS.Dispose();
                ImageTexture.UnlockRectangle(0);
            }
            return(Result);
        }
Exemple #8
0
        public void CreateTexture(BinaryReader BReader, int[] Palette)
        {
            if (ImageTexture != null && !ImageTexture.Disposed)
            {
                ImageTexture.Dispose();
            }

            byte[] Bytes = FullImageBytes(BReader, Palette);
            if (Bytes == null)
            {
                return;
            }

            LastAccess   = Main.Now;
            ImageTexture = new Texture(DXManager.Device, Size.Width, Size.Height, 0, Usage.None, Format.A8R8G8B8, Pool.Managed);

            GraphicsStream GS = ImageTexture.LockRectangle(0, LockFlags.Discard);

            GS.Write(Bytes);
            GS.Dispose();
            ImageTexture.UnlockRectangle(0);
        }
Exemple #9
0
        /// <summary>
        ///     Loads a D3D shader from the assembler source.
        /// </summary>
        protected override void LoadFromSource()
        {
            string errors;

            // load the shader from the source string
            GraphicsStream microcode = ShaderLoader.FromString(source, null, ShaderFlags.SkipValidation, out errors);

            if (errors != null && errors != string.Empty)
            {
                string msg = string.Format("Error while compiling pixel shader '{0}':\n {1}", name, errors);
                throw new AxiomException(msg);
            }

            // load the code into a shader object (polymorphic)
            LoadFromMicrocode(microcode);

            if (microcode != null)
            {
                microcode.Dispose();
                microcode = null;
            }
        }
Exemple #10
0
        /// <summary>
        /// Sets the data for the current vertex buffers.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="device"></param>
        public void setData(List <oSingleData> data, ref Device device)
        {
            if (data == null || device == null)
            {
                return;
            }

            // Clear the link vertex arrays
            vertexBufferLinks = null;
            vertexLinks       = null;

            // Clear the status of the previous executed functions
            foreach (int index in executedVertexIndices)
            {
                // Clear this vertex colouring
                vertexFunctions[index].Color = Color.FromArgb(60, 60, 60).ToArgb();
            }
            executedVertexIndices.Clear();

            // Clear the vertex function call links
            vertexLinks      = new CustomVertex.TransformedColored[data.Count * 2];
            vertexLinksCount = 0;

            if (data.Count > 0)
            {
                // Convert the data
                //Int32[] callArray = (Int32[]) oMemoryFunctions.RawDataToObject(ref data, typeof (Int32[]));
                //uint[] callArray = oMemoryFunctions.ByteArrayToUintArray(ref data);

                // Process the new function calls)
                for (int i = 0; i < data.Count; i++)
                {
                    // Process this function call

                    // Load the source function address
                    uint sourceFunctionAddress;
                    if (directCallSourcesHash.Contains((uint)data[i].source))
                    {
                        // We can perform a hash table lookup. This was probably a direct fixed offset call.
                        sourceFunctionAddress = (uint)directCallSourcesHash[(uint)data[i].source];
                    }
                    else
                    {
                        // We have to do a binary search lookup, this is more expensive computationally. This was probably a PE table call.
                        int n = functionLocationsList.BinarySearch((uint)data[i].source);
                        if (n < 0)
                        {
                            n = ~n - 1;
                        }
                        if (n < 0)
                        {
                            n = 0;
                        }
                        sourceFunctionAddress = (uint)functionLocationsList[n];
                    }

                    // Load the source vertex index, or create a new vertex if needed
                    int sourceVertexIndex;
                    if (functionLocationsHash.Contains(sourceFunctionAddress))
                    {
                        sourceVertexIndex = (int)functionLocationsHash[sourceFunctionAddress];
                    }
                    else
                    {
                        // We need to create the vertex for this funciton
                        sourceVertexIndex = moduleManager.addNewFunction(sourceFunctionAddress);
                    }

                    if (sourceVertexIndex >= 0)
                    {
                        // Highlight the source index function
                        vertexFunctions[sourceVertexIndex].Color = Color.FromArgb(255, 255, 50).ToArgb();
                        executedVertexIndices.Add(sourceVertexIndex);
                    }

                    // Load the destination vertex index, or create a new vertex if needed
                    int destinationVertexIndex;
                    if (functionLocationsHash.Contains((uint)((oSingleData)data[i]).destination))
                    {
                        destinationVertexIndex = (int)functionLocationsHash[(uint)data[i].destination];
                    }
                    else
                    {
                        // We need to create the vertex for this funciton
                        destinationVertexIndex = moduleManager.addNewFunction((uint)data[i].destination);
                    }

                    if (destinationVertexIndex >= 0)
                    {
                        // Highlight the destination index function
                        vertexFunctions[destinationVertexIndex].Color = Color.FromArgb(255, 255, 50).ToArgb();
                        executedVertexIndices.Add(destinationVertexIndex);
                    }

                    // Draw the link line
                    if (destinationVertexIndex >= 0 && sourceVertexIndex >= 0)
                    {
                        vertexLinks[vertexLinksCount] =
                            new CustomVertex.TransformedColored(vertexFunctions[sourceVertexIndex].X,
                                                                vertexFunctions[sourceVertexIndex].Y + 1,
                                                                vertexFunctions[sourceVertexIndex].Z,
                                                                vertexFunctions[sourceVertexIndex].Rhw,
                                                                Color.FromArgb(150, 0, 0).ToArgb());
                        vertexLinks[vertexLinksCount + 1] =
                            new CustomVertex.TransformedColored(vertexFunctions[destinationVertexIndex].X,
                                                                vertexFunctions[destinationVertexIndex].Y + 1,
                                                                vertexFunctions[destinationVertexIndex].Z,
                                                                vertexFunctions[destinationVertexIndex].Rhw,
                                                                Color.FromArgb(0, 0, 150).ToArgb());
                        vertexLinksCount += 2;
                    }
                }
            }
            else
            {
                vertexLinksCount = 0;
            }

            // Write the function vertex buffers
            if (vertexFunctionsCount > 0)
            {
                CustomVertex.TransformedColored[] vertexFunctionsRange =
                    new CustomVertex.TransformedColored[vertexFunctionsCount];
                Array.Copy(vertexFunctions, vertexFunctionsRange, vertexFunctionsRange.Length);
                if (vertexBufferFunctions != null)
                {
                    vertexBufferFunctions.Dispose();
                }
                vertexBufferFunctions = new VertexBuffer(typeof(CustomVertex.TransformedColored),
                                                         vertexFunctionsCount,
                                                         device,
                                                         0,
                                                         CustomVertex.TransformedColored.Format,
                                                         Pool.Default);
                GraphicsStream stm = vertexBufferFunctions.Lock(0, 0, 0);
                stm.Seek(0, SeekOrigin.Begin);
                stm.Write(vertexFunctionsRange);
                vertexBufferFunctions.Unlock();
                stm.Dispose();
            }

            // Write the link line vertex buffers
            if (vertexLinksCount > 0)
            {
                CustomVertex.TransformedColored[] vertexLinksRange =
                    new CustomVertex.TransformedColored[vertexLinksCount];
                Array.Copy(vertexLinks, vertexLinksRange, vertexLinksRange.Length);
                if (vertexBufferLinks != null)
                {
                    vertexBufferLinks.Dispose();
                }
                vertexBufferLinks = new VertexBuffer(typeof(CustomVertex.TransformedColored),
                                                     vertexLinksCount,
                                                     device,
                                                     0,
                                                     CustomVertex.TransformedColored.Format,
                                                     Pool.Default);

                GraphicsStream stm = vertexBufferLinks.Lock(0, 0, 0);
                stm.Seek(0, SeekOrigin.Begin);
                stm.Write(vertexLinksRange);
                vertexBufferLinks.Unlock();
                stm.Dispose();
            }
            else
            {
                vertexBufferLinks = null;
            }
        }
Exemple #11
0
        private void ExportThread()
        {
            //create timer so we can check how long it takes to create the whole file
            Stopwatch stopwatch = new Stopwatch();

            // Begin timing
            stopwatch.Start();

            //for (int i = 0; i < _refLibrary.Count; i++)
            for (int i = Convert.ToInt16(text_test_framemin.Text); i < Convert.ToInt16(text_test_framemax.Text); i++)
            {
                showRefImage     = false;       //turns off the ref image while we render the new library
                nud_frame.Value  = i;           //just setting this value and then calling Render() is enough to cycle through the frames
                backgroundColour = Color.Black; //set the background to black so the crop code can detect the blank areas and remove pure black pixels from the image, if set to any other colour the image will have a solid colour background and not become transparent
                UpdateTextBoxes();              //this will set the _selectedRefImage for the current frame
                Render();

                #region Save Snapshot of the Directx panel
                try
                {
                    Surface backbuffer = device.GetBackBuffer(0, 0, BackBufferType.Mono);
                    //SurfaceLoader.Save("Screenshot.bmp", ImageFileFormat.Bmp, backbuffer); //saves file (to test it is working)

                    //if you continue to Render the DirectX panel while updating the GraphicsStream it causes the device to be lost and crashes
                    //so I just call Render(); when I need to update the panel instead of using the infinite loop thread
                    #region Graphics Lock
                    GraphicsStream gs = backbuffer.LockRectangle(LockFlags.Discard);

                    gs.Position = 0; //set start position
                    int bytesPerPixel   = 4;
                    int currentPosition = 0;
                    int heightInPixels  = 250;
                    int widthInPixels   = 250;

                    //Crop offsets
                    int XMin = 249;
                    int XMax = 0;
                    int YMin = 249;
                    int YMax = 0;

                    for (int y = 0; y < heightInPixels; y++)
                    {
                        //couldn't use the Parallel.For loop as it would overwrite the GraphicsStream.Position because it was working on two or
                        //more pixels at once causing a speckled effect as it misses pixels (well I think that is what was causing the errors I was having)
                        //Parallel.For(0, heightInPixels, y =>
                        //{
                        //int currentLine = (y * ((widthInPixels * bytesPerPixel) + (4 *12))); //4*12 is how many pixels (12 for 500pixel image) was missing from each row (not sure why 12 but I guess the backbuffer extends beyond the screen)
                        int currentLine = (y * (widthInPixels * bytesPerPixel) + (y * (4 * 6))); //4*6 is how many pixels (6 for 250pixel image) was missing from each row (not sure why 6 but I guess the backbuffer extends beyond the screen)

                        for (int x = 0; x < widthInPixels; x++)
                        {
                            byte[] bu = new byte[4];                             //new byte to store current pixel data
                            currentPosition = currentLine + (x * bytesPerPixel); //calculate current position
                            gs.Position     = currentPosition;                   //set pixel position in GraphicsStream
                            gs.Read(bu, 0, 4);                                   //read image pixel data

                            //gets RGB values
                            int   r = bu[2];
                            int   g = bu[1];
                            int   b = bu[0];
                            Color c = Color.FromArgb(r, g, b);

                            if (c.R != backgroundColour.R && c.G != backgroundColour.G && c.B != backgroundColour.B) //if not the same as backgroundColour set the min/max values
                            {
                                if (XMin > x)
                                {
                                    XMin = x;
                                }
                                if (XMax < x)
                                {
                                    XMax = x;
                                }
                                if (YMin > y)
                                {
                                    YMin = y;
                                }
                                if (YMax < y)
                                {
                                    YMax = y;
                                }
                            }

                            //if (y == YMin) //this is a way to show where the image is cropped
                            //{
                            //    bu[2] = 255;
                            //    bu[1] = 0;
                            //    bu[0] = 0;
                            //}

                            gs.Position = currentPosition; //sets the position back to the starting pixel
                            gs.Write(bu, 0, 4);            //updates the GraphicsStream with the new changes
                        }
                        //}); //end of Parallel.For loop
                    }

                    //Shows the detected bounds of the image for testing
                    //MessageBox.Show("XMin: " + XMin
                    //    + Environment.NewLine + "XMax: " + XMax
                    //    + Environment.NewLine + "YMin: " + YMin
                    //    + Environment.NewLine + "YMax: " + YMax
                    //    + Environment.NewLine + "Width: " + (XMax - XMin)
                    //    + Environment.NewLine + "Height: " + (YMax - YMin));

                    backbuffer.UnlockRectangle();
                    gs.Dispose();
                    #endregion

                    Bitmap Preview = new Bitmap(SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, backbuffer));

                    #region crop

                    //create target image and draw cropped part of the Preview image to the target image
                    Bitmap target = new Bitmap((XMax - XMin) + 1, (YMax - YMin) + 1, PixelFormat.Format32bppArgb);
                    using (Graphics g = Graphics.FromImage(target))
                    {
                        g.DrawImage(Preview, new RectangleF(0, 0, target.Width, target.Height), new RectangleF(XMin, YMin, (XMax - XMin) + 1, (YMax - YMin) + 1), GraphicsUnit.Pixel);
                    }

                    #endregion

                    //Add Image and offsets to the _library
                    _library.AddImage(target,
                                      (short)(XMin - characterGlobalOffsetX),
                                      (short)(YMin - characterGlobalOffsetY));

                    //target.Save("Test1.PNG", ImageFormat.Png); //testing screen capture and crop image from directx works by saving to file

                    target.Dispose();
                    Preview.Dispose();
                    backbuffer.Dispose();
                }
                catch (Direct3DXException ee) //Display error Messages with the DirectX code
                {
                    MessageBox.Show("Message: " + ee.Message
                                    + Environment.NewLine + "ErrorString: " + ee.ErrorString
                                    + Environment.NewLine + "ErrorCode: " + ee.ErrorCode
                                    + Environment.NewLine + "StackTrace: " + ee.StackTrace
                                    );
                }
                #endregion


                toolStripProgressBar.Value = i + 1;
            }

            //save file as normal .lib (true = reference file, false = normal .lib)
            _library.Save(false);

            stopwatch.Stop();
            MessageBox.Show(string.Format("Time Taken: {0:n0} Seconds", stopwatch.Elapsed.TotalMilliseconds / 1000));
            toolStripProgressBar.Value = 0;
            showRefImage    = true;
            nud_frame.Value = 0;
            Render();
        }
Exemple #12
0
        protected void BlitFromMemoryImpl(PixelBox src, BasicBox dstBox)
        {
            // TODO: This currently does way too many copies.  We copy
            // from src to a converted buffer (if needed), then from
            // converted to a byte array, then into the temporary surface,
            // and finally from the temporary surface to the real surface.
            PixelBox converted   = src;
            IntPtr   bufPtr      = IntPtr.Zero;
            GCHandle bufGCHandle = new GCHandle();

            // convert to pixelbuffer's native format if necessary
            if (D3DHelper.ConvertEnum(src.Format) == D3D.Format.Unknown)
            {
                int    bufSize   = PixelUtil.GetMemorySize(src.Width, src.Height, src.Depth, format);
                byte[] newBuffer = new byte[bufSize];
                bufGCHandle = GCHandle.Alloc(newBuffer, GCHandleType.Pinned);
                bufPtr      = bufGCHandle.AddrOfPinnedObject();
                converted   = new PixelBox(src.Width, src.Height, src.Depth, format, bufPtr);
                PixelUtil.BulkPixelConversion(src, converted);
            }

            // int formatBytes = PixelUtil.GetNumElemBytes(converted.Format);
            Surface tmpSurface = device.CreateOffscreenPlainSurface(converted.Width, converted.Height, D3DHelper.ConvertEnum(converted.Format), Pool.Scratch);
            int     pitch;
            // Ideally I would be using the Array mechanism here, but that doesn't seem to work
            GraphicsStream buf = tmpSurface.LockRectangle(LockFlags.NoSystemLock, out pitch);

            buf.Position = 0;
            unsafe {
                int    bufSize = PixelUtil.GetMemorySize(converted.Width, converted.Height, converted.Depth, converted.Format);
                byte * srcPtr  = (byte *)converted.Data.ToPointer();
                byte[] ugh     = new byte[bufSize];
                for (int i = 0; i < bufSize; ++i)
                {
                    ugh[i] = srcPtr[i];
                }
                buf.Write(ugh);
            }
            tmpSurface.UnlockRectangle();
            buf.Dispose();

            //ImageInformation imageInfo = new ImageInformation();
            //imageInfo.Format = D3DHelper.ConvertEnum(converted.Format);
            //imageInfo.Width = converted.Width;
            //imageInfo.Height = converted.Height;
            //imageInfo.Depth = converted.Depth;
            if (surface != null)
            {
                // I'm trying to write to surface using the data in converted
                Rectangle srcRect  = ToD3DRectangleExtent(converted);
                Rectangle destRect = ToD3DRectangle(dstBox);
                SurfaceLoader.FromSurface(surface, destRect, tmpSurface, srcRect, Filter.None, 0);
            }
            else
            {
                D3D.Box srcBox  = ToD3DBoxExtent(converted);
                D3D.Box destBox = ToD3DBox(dstBox);
                Debug.Assert(false, "Volume textures not yet supported");
                // VolumeLoader.FromStream(volume, destBox, converted.Data, converted.RowPitch * converted.SlicePitch * formatBytes, srcBox, Filter.None, 0);
                VolumeLoader.FromStream(volume, destBox, buf, srcBox, Filter.None, 0);
            }

            tmpSurface.Dispose();

            // If we allocated a buffer for the temporary conversion, free it here
            // If I used bufPtr to store my temporary data while I converted
            // it, I need to free it here.  This invalidates converted.
            // My data has already been copied to tmpSurface and then to the
            // real surface.
            if (bufGCHandle.IsAllocated)
            {
                bufGCHandle.Free();
            }

            if (doMipmapGen)
            {
                GenMipmaps();
            }
        }