public void SetRenderTargetDX10(SharpDX.Direct3D10.Texture2D renderTarget)
        {
            if (RenderTarget != null)
            {
                RenderTarget = null;

                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                base.Unlock();
            }

            if (renderTarget == null)
                return;

            if (!IsShareable(renderTarget))
                throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");

            Format format = DX10ImageSource.TranslateFormat(renderTarget);
            if (format == Format.Unknown)
                throw new ArgumentException("Texture format is not compatible with OpenSharedResource");

            IntPtr handle = GetSharedHandle(renderTarget);
            if (handle == IntPtr.Zero)
                throw new ArgumentNullException("Handle");

            RenderTarget = new Texture(DX10ImageSource.D3DDevice, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle);
            using (Surface surface = RenderTarget.GetSurfaceLevel(0))
            {
                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                base.Unlock();
            }
        }
Example #2
0
        public BlurComponent(Device graphics, int size)
        {
            _graphics = graphics;

            Dims = size;
            Format = Format.A8R8G8B8;

            _sampleOffsetsHoriz = new Vector4D[SampleCount];
            _sampleOffsetsVert = new Vector4D[SampleCount];

            _sampleWeightsHoriz = new float[SampleCount];
            _sampleWeightsVert = new float[SampleCount];

            int width = Dims - 5;
            int height = Dims - 5;

            SetBlurEffectParameters(1.0f / width, 0, ref _sampleOffsetsHoriz, ref _sampleWeightsHoriz);
            SetBlurEffectParameters(0, 1.0f / height, ref _sampleOffsetsVert, ref _sampleWeightsVert);

            _effect = new GaussianBlurEffect(_graphics);

            OutputTexture = new Texture(_graphics, Dims, Dims, 1, Usage.RenderTarget, Format, Pool.Default);
            _intermediateTexture = new Texture(_graphics, Dims, Dims, 1, Usage.RenderTarget, Format, Pool.Default);

            _sprite = new Sprite(_graphics);
        }
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
                case PostProcessStage.AlphaBlended:
                    {
                        BlendState.Opaque.Apply();
                        DepthStencilState.None.Apply();
                        RasterizerState.CullCounterClockwise.Apply();

                        MyRender.SetRenderTarget(availableRenderTarget, null);

                        MyEffectChromaticAberration effectChromaAberr = MyRender.GetEffect(MyEffects.ChromaticAberration) as MyEffectChromaticAberration;
                        effectChromaAberr.SetInputTexture(source);
                        effectChromaAberr.SetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height);
                        effectChromaAberr.SetAspectRatio((float)source.GetLevelDescription(0).Width / (float)source.GetLevelDescription(0).Height);
                        effectChromaAberr.SetDistortionLens(DistortionLens);
                        effectChromaAberr.SetDistortionCubic(DistortionCubic);
                        effectChromaAberr.SetDistortionWeights(ref DistortionWeights);

                        effectChromaAberr.Enable();

                        MyRender.GetFullscreenQuad().Draw(effectChromaAberr);
                        return availableRenderTarget;
                    }
            }
            return source;
        }
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
                case PostProcessStage.AlphaBlended:
                {
                    //BlendState.Opaque.Apply();
                    //DepthStencilState.None.Apply();
                    //RasterizerState.CullCounterClockwise.Apply();

                    //MyRender.SetRenderTarget(availableRenderTarget, null);

                    //MyEffectVignetting effectVignetting = MyRender.GetEffect(MyEffects.Vignetting) as MyEffectVignetting;
                    //effectVignetting.SetInputTexture(source);
                    //effectVignetting.SetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height);
                    //effectVignetting.SetVignettingPower(VignettingPower);

                    //effectVignetting.EnableVignetting();

                    //MyRender.GetFullscreenQuad().Draw(effectVignetting);
                    return availableRenderTarget;
                }
            }
            return source;
        }
Example #5
0
        public unsafe Texture CreateTexture(int index)
        {
            if (!_fileIndex.FilesExist)
                return null;

            int length, extra;
            bool patched;

            Stream stream = _fileIndex.Seek(index, out length, out extra, out patched);

            if (stream == null)
                return null;

            int size = extra == 0 ? 64 : 128;

            Texture texture = new Texture(_device, size, size, 0, Usage.None, Format.A1R5G5B5, Pool.Managed);
            DataRectangle rect = texture.LockRectangle(0, LockFlags.None);
            BinaryReader bin = new BinaryReader(stream);

            ushort* line = (ushort*)rect.DataPointer;
            int delta = rect.Pitch >> 1;

            for (int y = 0; y < size; ++y, line += delta)
            {
                ushort* cur = line;
                ushort* end = cur + size;

                while (cur < end)
                    *cur++ = (ushort)(bin.ReadUInt16() ^ 0x8000);
            }

            texture.UnlockRectangle(0);

            return texture;
        }
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things 
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
                case PostProcessStage.AlphaBlended:
                    {
                        BlendState.Opaque.Apply();
                        DepthStencilState.None.Apply();
                        RasterizerState.CullCounterClockwise.Apply();

                        MyRender.SetRenderTarget(availableRenderTarget, null);

                        MyEffectAntiAlias effectAntiAlias = MyRender.GetEffect(MyEffects.AntiAlias) as MyEffectAntiAlias;
                        effectAntiAlias.SetDiffuseTexture(source);
                        effectAntiAlias.SetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height);

                        if (MyRenderConstants.RenderQualityProfile.EnableFXAA)
                            effectAntiAlias.ApplyFxaa();
                        else
                            return source; // Nothing to do, return source

                        MyRender.GetFullscreenQuad().Draw(effectAntiAlias);
                        return availableRenderTarget;
                    }
                    break;
            }
            return source;
        }
        public override void Dispose()
        {
            base.Dispose();

            m_outputFrame.Dispose();
            m_outputFrame = null;
        }
Example #8
0
        public SkillBar(Menu config)
        {
            MenuSkillBar = config.AddSubMenu(new Menu("Cooldown Tracker", "SkillBar"));
            MenuSkillBar.AddItem(new MenuItem("OnAllies", "On Allies").SetValue(false));
            MenuSkillBar.AddItem(new MenuItem("OnEnemies", "On Enemies").SetValue(true));
            Sprite = new Sprite(Drawing.Direct3DDevice);
            HudTexture = Texture.FromMemory(
                Drawing.Direct3DDevice, (byte[]) new ImageConverter().ConvertTo(Resources.main, typeof(byte[])), 127, 41,
                0, Usage.None, Format.A1, Pool.Managed, Filter.Default, Filter.Default, 0);
            FrameLevelTexture = Texture.FromMemory(
                Drawing.Direct3DDevice, (byte[]) new ImageConverter().ConvertTo(Resources.spell_level, typeof(byte[])),
                2, 3, 0, Usage.None, Format.A1, Pool.Managed, Filter.Default, Filter.Default, 0);
            ButtonRedTexture = Texture.FromMemory(
                Drawing.Direct3DDevice, (byte[]) new ImageConverter().ConvertTo(Resources.disable, typeof(byte[])), 14,
                14, 0, Usage.None, Format.A1, Pool.Managed, Filter.Default, Filter.Default, 0);
            SmallText = new Font(
                Drawing.Direct3DDevice,
                new FontDescription
                {
                    FaceName = "Calibri",
                    Height = 13,
                    OutputPrecision = FontPrecision.Default,
                    Quality = FontQuality.Default,
                });

            AppDomain.CurrentDomain.DomainUnload += DomainUnload;
            AppDomain.CurrentDomain.ProcessExit += DomainUnload;
            CustomEvents.Game.OnGameLoad += Game_OnGameLoad;
        }
Example #9
0
 public CCHero(string name, CCBuff ccBuff, CCSpell ccSpells, Texture icon)
 {
     this.Name = name;
     this.CCBuff = ccBuff;
     this.CCSpells = ccSpells;
     this.Icon = icon;
 }
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things 
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
                case PostProcessStage.HDR:
                    {
                        MyMinerGame.SetRenderTarget(availableRenderTarget, null);
                        MyEffectContrast effectContrast = MyRender.GetEffect(MyEffects.Contrast) as MyEffectContrast;


                        effectContrast.SetDiffuseTexture(source);
                        effectContrast.SetHalfPixel(MyUtils.GetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height));
                        effectContrast.SetContrast(Contrast);
                        effectContrast.SetHue(Hue);
                        effectContrast.SetSaturation(Saturation);

                        MyGuiManager.GetFullscreenQuad().Draw(effectContrast);

                        return availableRenderTarget;
                    }
                    break;
            }

            return source;
        }
Example #11
0
        public Poll(Device device, float height)
        {
            _height = height;
            Texture = Texture ?? Texture.FromFile(device, "Assets/Textures/poll.png");
            TextureTop = TextureTop ?? Texture.FromFile(device, "Assets/Textures/poll_top.png");

            _topFlagLocation = new Vector3(-0.5f, 0.25f + (height / 2 - 1.5f), 0);

            _flag = Add(new Sprite(device, "flag", 1));
            _flag.Translate(_topFlagLocation);

            Add(new GameObject
            {
                new MeshRenderer
                {
                    Mesh = new TexturedCube(device, 0.5f, 0.5f, 0.5f, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV),
                    Material = new TextureMaterial(TextureTop, false)
                }
            }).Translate(0, 0.25f + (height / 2 - 0.5f), 0);

            Add(new GameObject
            {
                new MeshRenderer
                {
                    Mesh = new TexturedCube(device, 0.2f, height - 0.5f, 0.2f, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV),
                    Material = new TextureMaterial(Texture, false)
                }
            }).Translate(0, -0.25f, 0);

            Add(new Trigger(SlideDown, 0.5f, height, 0.5f, Vector3.Zero));
        }
Example #12
0
 public static void SaveScreenshotUserFolder(Texture texture2D, string name)
 {
     var datetimePrefix = MyValueFormatter.GetFormatedDateTimeForFilename(DateTime.Now);
     var folder = Path.Combine(MyFileSystemUtils.GetApplicationUserDataFolder(), "Screenshots\\");
     var path = Path.Combine(folder, "MinerWars_" + MyEnumsToStrings.CameraDirection[(int)MyCamera.ActualCameraDirection] + "_" + datetimePrefix + "_" + name);
     SaveScreenshot(texture2D, path);
 }
    public override void Render(RenderContext parentRenderContext)
    {
      Effect effect = Effect;
      if (!IsVisible || effect == null)
        return;

      RectangleF bounds = ActualBounds;
      if (bounds.Width <= 0 || bounds.Height <= 0)
        return;

      Matrix? layoutTransformMatrix = LayoutTransform == null ? new Matrix?() : LayoutTransform.GetTransform();
      Matrix? renderTransformMatrix = RenderTransform == null ? new Matrix?() : RenderTransform.GetTransform();

      RenderContext localRenderContext = parentRenderContext.Derive(bounds, layoutTransformMatrix, renderTransformMatrix, RenderTransformOrigin, Opacity);
      _inverseFinalTransform = Matrix.Invert(localRenderContext.Transform);

      DeviceEx device = SkinContext.Device;
      Surface backBuffer = device.GetRenderTarget(0);
      SurfaceDescription desc = backBuffer.Description;
      SurfaceDescription? textureDesc = _texture == null ? new SurfaceDescription?() : _texture.GetLevelDescription(0);
      if (!textureDesc.HasValue || textureDesc.Value.Width != desc.Width || textureDesc.Value.Height != desc.Height)
      {
        TryDispose(ref _texture);
        _texture = new Texture(device, desc.Width, desc.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
      }
      using (Surface destSurfaceRef = _texture.GetSurfaceLevel(0))
        device.StretchRectangle(backBuffer, destSurfaceRef, TextureFilter.None);

      UpdateEffectMask(effect, localRenderContext.OccupiedTransformedBounds, desc.Width, desc.Height, localRenderContext.ZOrder);
      if (effect.BeginRender(_texture, new RenderContext(Matrix.Identity, 1.0d, bounds, localRenderContext.ZOrder)))
      {
        _effectContext.Render(0);
        effect.EndRender();
      }
    }
        public void SetRenderTarget(CubeTexture environmentRT, CubeTexture ambientRT, Texture fullSizeRT)
        {
            m_setup.RenderTargets[0] = fullSizeRT;

            m_environmentRT = environmentRT;
            m_ambientRT = ambientRT;
            m_fullSizeRT = fullSizeRT;
        }
 public override void LoadContent()
 {
     //int size = GetSquareDimension();
     int size = 256;
     m_render = new Texture(MyRender.GraphicsDevice, size, size, 1, Usage.Dynamic, Format.X8R8G8B8, Pool.Default);
     m_update = new Texture(MyRender.GraphicsDevice, size, size, 1, Usage.Dynamic, Format.X8R8G8B8, Pool.Default);
     UpdateBones();
 }
Example #16
0
File: Art.cs Project: nydehi/openuo
        public unsafe Texture CreateTexture(int index)
        {
            index &= 0x3FFF;
            index += 0x4000;

            int length, extra;
            bool patched;

            Stream stream = _fileIndex.Seek(index, out length, out extra, out patched);

            if (stream == null)
                return null;

            BinaryReader bin = new BinaryReader(stream);

            bin.ReadInt32(); // Unknown
            int width = bin.ReadInt16();
            int height = bin.ReadInt16();

            if (width <= 0 || height <= 0)
                return null;

            int[] lookups = new int[height];

            int start = (int)bin.BaseStream.Position + (height * 2);

            for (int i = 0; i < height; ++i)
                lookups[i] = (int)(start + (bin.ReadUInt16() * 2));

            Texture texture = new Texture(_device, width, height, 0, Usage.None, Format.A1R5G5B5, Pool.Managed);
            DataRectangle rect = texture.LockRectangle(0, LockFlags.None);

            ushort* line = (ushort*)rect.DataPointer;
            int delta = rect.Pitch >> 1;

            for (int y = 0; y < height; ++y, line += delta)
            {
                bin.BaseStream.Seek(lookups[y], SeekOrigin.Begin);

                ushort* cur = line;
                ushort* end;

                int xOffset, xRun;

                while (((xOffset = bin.ReadUInt16()) + (xRun = bin.ReadUInt16())) != 0)
                {
                    cur += xOffset;
                    end = cur + xRun;

                    while (cur < end)
                        *cur++ = (ushort)(bin.ReadUInt16() ^ 0x8000);
                }
            }

            texture.UnlockRectangle(0);

            return texture;
        }
Example #17
0
 public Texture2D(Device d, int width, int height, Usage u)
 {
     handle = new Texture(d, width, height, 1, u, Format.A8R8G8B8, Pool.Default);
     usage = u;
     Width = width;
     Height = height;
     device = d;
     managed = false;
 }
Example #18
0
 public Texture2D(Device d, int width, int height)
 {
     handle = new Texture(d, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
     Width = width;
     Height = height;
     device = d;
     managed = true;
     usage = Usage.None;
 }
Example #19
0
        public Mario(Device device)
        {
            Tag = "player";

            Texture = Texture ?? Texture.FromFile(device, "Assets/Textures/new-mario.png");

            LoadBehaviors();
            CreateBody(device, Texture);
            IsSmall = false;
        }
Example #20
0
 public Texture2D(Device d, string file)
 {
     handle = Texture.FromFile(d, Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), file), Usage.None, Pool.Managed);
     ImageInformation i = ImageInformation.FromFile(file);
     Width = i.Width;
     Height = i.Height;
     device = d;
     managed = true;
     usage = Usage.None;
 }
 public static void DrawCentered(this Sprite sprite,
     Texture texture,
     Vector2 position,
     Rectangle? rectangle = null)
 {
     var desc = texture.GetLevelDescription(0);
     sprite.Draw(
         texture, new ColorBGRA(255, 255, 255, 255), rectangle,
         new Vector3(-(position.X - desc.Width / 2f), -(position.Y - desc.Height / 2f), 0));
 }
 public override void SetTextureDiffuse(Texture texture2D)
 {
     //TODO
     /*
     if (texture2D == null && MyRender.CheckDiffuseTextures)
         m_D3DEffect.SetTexture(m_textureDiffuse, (Texture)MyRender.GetDebugTexture());
     else
         m_D3DEffect.SetTexture(m_textureDiffuse, texture2D);
      * */
 }
 public override void UnloadContent()
 {
     if (m_render != null)
     {
         m_render.Dispose();
         m_render = null;
     }
     if (m_update != null)
     {
         m_update.Dispose();
         m_update = null;
     }
 }
Example #24
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="graphicsDevice"></param>
        /// <param name="vertexBufferSize"></param>
        /// <param name="matrixStackSize"></param>
        /// <param name="colorStackSize"></param>
        public GraphicsBatch(GraphicsDevice graphicsDevice, int vertexBufferSize, int matrixStackSize)
        {
            if (graphicsDevice == null)
                throw new ArgumentNullException("graphicsDevice");

            graphicsDevice.EnsureDeviceCreated();

            this.GraphicsDevice = graphicsDevice;

            this.vertexDeclaration = new D3D.VertexDeclaration(this.GraphicsDevice.InternalDevice, new[] {
                new D3D.VertexElement(0, 0, D3D.DeclarationType.Float4, D3D.DeclarationMethod.Default, D3D.DeclarationUsage.Position, 0),
                new D3D.VertexElement(0, 16, D3D.DeclarationType.Float4, D3D.DeclarationMethod.Default, D3D.DeclarationUsage.Color, 0),
                new D3D.VertexElement(0, 32, D3D.DeclarationType.Float2, D3D.DeclarationMethod.Default, D3D.DeclarationUsage.TextureCoordinate, 0),
                D3D.VertexElement.VertexDeclarationEnd
            });

            this.vertices = new Vertex[vertexBufferSize * 4];
            this.vertexCount = 0;

            this.indices = new short[vertexBufferSize * 6];

            for (short i = 0, vertex = 0; i < this.indices.Length; i += 6, vertex += 4)
            {
                this.indices[i] = vertex;
                this.indices[i + 1] = (short)(vertex + 1);
                this.indices[i + 2] = (short)(vertex + 2);
                this.indices[i + 3] = vertex;
                this.indices[i + 4] = (short)(vertex + 2);
                this.indices[i + 5] = (short)(vertex + 3);
            }

            this.basicEffect = new BasicEffect(this.GraphicsDevice);

            this.pixel = D3DHelper.CreateTexture(this.GraphicsDevice.InternalDevice, 1, 1, TextureUsage.None);

            SharpDX.DataRectangle dataRectangle = this.pixel.LockRectangle(0, D3D.LockFlags.None);

            using (SharpDX.DataStream dataStream = new SharpDX.DataStream(dataRectangle.DataPointer, dataRectangle.Pitch, true, true))
            {
                dataStream.WriteRange(new Color[] { Color.White });
            }

            this.pixel.UnlockRectangle(0);

            this.pixelSource = new Rectangle(0, 0, 1, 1);

            this.matrixStack = new Matrix[matrixStackSize];
            this.matrixStackCount = 0;

            this.texture = null;
        }
Example #25
0
 static void Game_OnGameLoad(EventArgs args)
 {
     Game.PrintChat("Unban.exe By DZ191 Loaded. Credits to DETUKS");
     sprite = new Sprite(dxDevice);
    taco = Texture.FromMemory(
             Drawing.Direct3DDevice,
             (byte[])new ImageConverter().ConvertTo(LoadPicture("http://puu.sh/cP1qD/d23cd24220.jpg"), typeof(byte[])), 513, 744, 0,
             Usage.None, Format.A1, Pool.Managed, Filter.Default, Filter.Default, 0);
     Drawing.OnEndScene += Drawing_OnEndScene;
     Drawing.OnPreReset += DrawingOnOnPreReset;
     Drawing.OnPostReset += DrawingOnOnPostReset;
     AppDomain.CurrentDomain.DomainUnload += CurrentDomainOnDomainUnload;
     AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnDomainUnload;
 }
Example #26
0
        public ItemBlock(Device device)
        {
            DefaultTexture = DefaultTexture ?? Texture.FromFile(device, "Assets/Textures/block_question.png");
            EmptyTexture = EmptyTexture ?? Texture.FromFile(device, "Assets/Textures/block_empty.png");

            Add(new MeshRenderer
            {
                Mesh = new TexturedCube(device, 1, 1, 1, UV, UV, UV, UV, UV, UV),
                Material = (_material = new TextureMaterial(DefaultTexture, false))
            });

            Add(new AxisAlignedBoxCollider());
            Add(new HeadStomp());
        }
Example #27
0
 public static void LoadTexture(String name, ref Texture texture, TextureType type)
 {
     Game.PrintChat(name.ToLower());
     if ((type == TextureType.Default) && MyResources.ContainsKey(name.ToLower()))
     {
         try
         {
             texture = Texture.FromMemory(Drawing.Direct3DDevice, MyResources[name.ToLower()]);
         }
         catch (Exception ex)
         {
             Console.WriteLine("SAwarness: Couldn't load texture: " + name + "\n Ex: " + ex);
         }
     }
 }
Example #28
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="graphicsDevice"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="usage"></param>
        public Texture(GraphicsDevice graphicsDevice, int width, int height, TextureUsage usage)
            : base()
        {
            if (graphicsDevice == null)
                throw new ArgumentNullException("graphicsDevice");

            graphicsDevice.EnsureDeviceCreated();

            this.Width = width;
            this.Height = height;
            this.Usage = usage;

            this.CalculateInternalSize(graphicsDevice);

            this.InternalTexture = D3DHelper.CreateTexture(graphicsDevice.InternalDevice, this.InternalWidth, this.InternalHeight, this.Usage);
        }
Example #29
0
        protected TextureBase(DeviceContext context, int width, int height, int levelCount, Usage usage, Format format, Pool pool)
            : base(context)
        {
            _size = new Vector2(width, height);
            _width = width;
            _height = height;
            _levelCount = levelCount;
            _usage = usage;
            _format = format;
            _pool = pool;

            _texture = new Texture(context, width, height, levelCount, usage, format, pool);
            #if DEBUG
            Context.PerformanceMonitor.IncreaseLifetimeCounter(LifetimeCounters.TextureCount);
            #endif
        }
Example #30
0
        public Hues(Engine engine)
        {
            IConfigurationService configurationService = engine.Kernel.Get<IConfigurationService>();

            string ultimaOnlineDirectory = configurationService.GetValue<string>(ConfigSections.UltimaOnline, ConfigKeys.UltimaOnlineDirectory);

            if (!Directory.Exists(ultimaOnlineDirectory))
            {
                _filesExist = false;
                return;
            }

            string path = Path.Combine(ultimaOnlineDirectory, "hues.mul");

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BinaryReader bin = new BinaryReader(fs);

                int blockCount = (int)fs.Length / 708;

                if (blockCount > 375)
                    blockCount = 375;

                _hues = new Texture[blockCount];

                for (int i = 0; i < blockCount; ++i)
                {
                    bin.ReadInt32();

                    Texture texture = new Texture(engine.Device, 34, 1, 0, Usage.None, Format.A1R5G5B5, Pool.Managed); ;
                    IntPtr dataPtr = texture.LockRectangle(0, LockFlags.None).DataPointer;

                    unsafe
                    {
                        ushort* line = (ushort*)dataPtr;

                        for (int j = 0; j < 34; j++)
                            (*line++) = (ushort)(bin.ReadUInt16() | 0x8000);

                        texture.UnlockRectangle(0);
                        bin.ReadBytes(20); //Don't need to know the names

                        _hues[i] = texture;
                    }
                }
            }
        }
Example #31
0
 public override void UpdateTexturePart(int texId, int texX, int texY, FastBitmap part)
 {
     D3D.Texture texture = textures[texId];
     texture.SetPartData(0, LockFlags.None, part.Scan0, texX, texY, part.Width, part.Height);
 }
Example #32
0
        public void Init(SharpDX.Direct3D11.Texture2D sharedTexture)
        {
            logger.Debug("D3DRenderer::Setup()");

            if (state != RendererState.Closed)
            {
                throw new InvalidOperationException("Invalid capture state " + State);
            }

            try
            {
                var descr = sharedTexture.Description;
                logger.Verb(string.Join(", ", descr.Width + "x" + descr.Height, descr.Format));

                if (descr.Format != SharpDX.DXGI.Format.B8G8R8A8_UNorm)
                {
                    throw new InvalidOperationException("Invalid renderer state " + State);
                }

                direct3D = new Direct3DEx();

                var hWnd = NativeAPIs.User32.GetDesktopWindow();

                var presentParams = new PresentParameters
                {
                    //Windowed = true,
                    //SwapEffect = SharpDX.Direct3D9.SwapEffect.Discard,
                    //DeviceWindowHandle = IntPtr.Zero,
                    //PresentationInterval = SharpDX.Direct3D9.PresentInterval.Default
                    //BackBufferCount = 1,

                    Windowed        = true,
                    MultiSampleType = MultisampleType.None,
                    SwapEffect      = SwapEffect.Discard,
                    PresentFlags    = PresentFlags.None,
                };

                var flags = CreateFlags.HardwareVertexProcessing |
                            CreateFlags.Multithreaded |
                            CreateFlags.FpuPreserve;

                int adapterIndex = 0;

                device = new DeviceEx(direct3D, adapterIndex, DeviceType.Hardware, hWnd, flags, presentParams);

                using (var resource = sharedTexture.QueryInterface <SharpDX.DXGI.Resource>())
                {
                    var handle = resource.SharedHandle;

                    if (handle == IntPtr.Zero)
                    {
                        throw new ArgumentNullException(nameof(handle));
                    }

                    // D3DFMT_A8R8G8B8 или D3DFMT_X8R8G8B8
                    // D3DUSAGE_RENDERTARGET
                    // D3DPOOL_DEFAULT
                    using (var texture3d9 = new SharpDX.Direct3D9.Texture(device,
                                                                          descr.Width, descr.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default,
                                                                          ref handle))
                    {
                        surface = texture3d9.GetSurfaceLevel(0);
                    };
                }

                this.texture2D11 = sharedTexture;
                var pSurface = surface.NativePointer;

                state = RendererState.Initialized;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Close();

                throw;
            }
        }
        protected void Blit(D3D9.Device d3d9Device, HardwarePixelBuffer rsrc, BasicBox srcBox, BasicBox dstBox,
                            BufferResources srcBufferResources, BufferResources dstBufferResources)
        {
            if (dstBufferResources.Surface != null && srcBufferResources.Surface != null)
            {
                // Surface-to-surface
                var dsrcRect  = ToD3DRectangle(srcBox);
                var ddestRect = ToD3DRectangle(dstBox);

                var srcDesc = srcBufferResources.Surface.Description;

                // If we're blitting from a RTT, try GetRenderTargetData
                // if we're going to try to use GetRenderTargetData, need to use system mem pool

                // romeoxbm: not used even in Ogre
                //var tryGetRenderTargetData = false;

                if ((srcDesc.Usage & D3D9.Usage.RenderTarget) != 0 && srcDesc.MultiSampleType == D3D9.MultisampleType.None)
                {
                    // Temp texture
                    var tmptex = new D3D9.Texture(d3d9Device, srcDesc.Width, srcDesc.Height, 1,
                                                  // 1 mip level ie topmost, generate no mipmaps
                                                  0, srcDesc.Format, D3D9.Pool.SystemMemory);

                    var tmpsurface = tmptex.GetSurfaceLevel(0);

                    if (d3d9Device.GetRenderTargetData(srcBufferResources.Surface, tmpsurface).Success)
                    {
                        // Hey, it worked
                        // Copy from this surface instead
                        var res = D3D9.Surface.FromSurface(dstBufferResources.Surface, tmpsurface, D3D9.Filter.Default, 0, dsrcRect,
                                                           ddestRect);
                        if (res.Failure)
                        {
                            tmpsurface.SafeDispose();
                            tmptex.SafeDispose();
                            throw new AxiomException("D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.Blit");
                        }
                        tmpsurface.SafeDispose();
                        tmptex.SafeDispose();
                        return;
                    }
                }

                // Otherwise, try the normal method
                var res2 = D3D9.Surface.FromSurface(dstBufferResources.Surface, srcBufferResources.Surface, D3D9.Filter.Default, 0,
                                                    dsrcRect, ddestRect);
                if (res2.Failure)
                {
                    throw new AxiomException("D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.Blit");
                }
            }
            else if (dstBufferResources.Volume != null && srcBufferResources.Volume != null)
            {
                // Volume-to-volume
                var dsrcBox  = ToD3DBox(srcBox);
                var ddestBox = ToD3DBox(dstBox);

                var res = D3D9.Volume.FromVolume(dstBufferResources.Volume, srcBufferResources.Volume, D3D9.Filter.Default, 0,
                                                 dsrcBox, ddestBox);
                if (res.Failure)
                {
                    throw new AxiomException("D3D9.Volume.FromVolume failed in D3D9HardwarePixelBuffer.Blit");
                }
            }
            else
            {
                // Software fallback
                base.Blit(rsrc, srcBox, dstBox);
            }
        }
        protected void BlitToMemory(BasicBox srcBox, PixelBox dst, BufferResources srcBufferResources, D3D9.Device d3d9Device)
        {
            // Decide on pixel format of temp surface
            PixelFormat tmpFormat = Format;

            if (D3D9Helper.ConvertEnum(dst.Format) != D3D9.Format.Unknown)
            {
                tmpFormat = dst.Format;
            }

            if (srcBufferResources.Surface != null)
            {
                Debug.Assert(srcBox.Depth == 1 && dst.Depth == 1);
                var srcDesc  = srcBufferResources.Surface.Description;
                var temppool = D3D9.Pool.Scratch;

                // if we're going to try to use GetRenderTargetData, need to use system mem pool
                var tryGetRenderTargetData = false;
                if (((srcDesc.Usage & D3D9.Usage.RenderTarget) != 0) && (srcBox.Width == dst.Width) &&
                    (srcBox.Height == dst.Height) && (srcBox.Width == Width) && (srcBox.Height == Height) &&
                    (Format == tmpFormat))
                {
                    tryGetRenderTargetData = true;
                    temppool = D3D9.Pool.SystemMemory;
                }

                // Create temp texture
                var tmp = new D3D9.Texture(d3d9Device, dst.Width, dst.Height, 1,                  // 1 mip level ie topmost, generate no mipmaps
                                           0, D3D9Helper.ConvertEnum(tmpFormat), temppool);

                var surface = tmp.GetSurfaceLevel(0);

                // Copy texture to this temp surface
                var srcRect  = ToD3DRectangle(srcBox);
                var destRect = ToD3DRectangle(dst);

                // Get the real temp surface format
                var dstDesc = surface.Description;
                tmpFormat = D3D9Helper.ConvertEnum(dstDesc.Format);

                // Use fast GetRenderTargetData if we are in its usage conditions
                var fastLoadSuccess = false;
                if (tryGetRenderTargetData)
                {
                    var result = d3d9Device.GetRenderTargetData(srcBufferResources.Surface, surface);
                    fastLoadSuccess = result.Success;
                }
                if (!fastLoadSuccess)
                {
                    var res = D3D9.Surface.FromSurface(surface, srcBufferResources.Surface, D3D9.Filter.Default, 0, srcRect, destRect);
                    if (res.Failure)
                    {
                        surface.SafeDispose();
                        tmp.SafeDispose();
                        throw new AxiomException("D3D9.Surface.FromSurface failed in D3D9HardwarePixelBuffer.BlitToMemory");
                    }
                }

                // Lock temp surface and copy it to memory
                var lrect = surface.LockRectangle(D3D9.LockFlags.ReadOnly);

                // Copy it
                var locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
                FromD3DLock(locked, lrect);
                PixelConverter.BulkPixelConversion(locked, dst);
                surface.UnlockRectangle();
                // Release temporary surface and texture
                surface.SafeDispose();
                tmp.SafeDispose();
            }
            else if (srcBufferResources.Volume != null)
            {
                // Create temp texture
                var tmp = new D3D9.VolumeTexture(d3d9Device, dst.Width, dst.Height, dst.Depth, 0, 0,
                                                 D3D9Helper.ConvertEnum(tmpFormat), D3D9.Pool.Scratch);

                var surface = tmp.GetVolumeLevel(0);

                // Volume
                var ddestBox = ToD3DBoxExtent(dst);
                var dsrcBox  = ToD3DBox(srcBox);

                var res = D3D9.Volume.FromVolume(surface, srcBufferResources.Volume, D3D9.Filter.Default, 0, dsrcBox, ddestBox);
                if (res.Failure)
                {
                    surface.SafeDispose();
                    tmp.SafeDispose();
                    throw new AxiomException("D3D9.Surface.FromVolume failed in D3D9HardwarePixelBuffer.BlitToMemory");
                }

                // Lock temp surface and copy it to memory
                var lbox = surface.LockBox(D3D9.LockFlags.ReadOnly);                   // Filled in by D3D

                // Copy it
                var locked = new PixelBox(dst.Width, dst.Height, dst.Depth, tmpFormat);
                FromD3DLock(locked, lbox);
                PixelConverter.BulkPixelConversion(locked, dst);
                surface.UnlockBox();
                // Release temporary surface and texture
                surface.SafeDispose();
                tmp.SafeDispose();
            }
        }
Example #35
0
 public static void DrawSprite(Sprite sprite, Texture texture, Size size, float[] scale = null,
                               float rotation = 0.0f)
 {
     DrawSprite(sprite, texture, size, Color.White, scale, rotation);
 }
Example #36
0
        private static void InternalDDSFromStream(Stream stream, Device device, int streamOffset, bool loadMipMap, int offsetMipMaps, out SharpDX.Direct3D9.Texture texture)
        {
            var fileStream = stream as FileStream;

            byte[] data = fileStream != null ? null : SharpDX.Utilities.ReadStream(stream);

            int maxTextureDimension = MyRender.GraphicsDevice.Capabilities.MaxTextureWidth;

            if (IntPtr.Size == 4 || MyRender.GraphicsDevice.AvailableTextureMemory < 1024 * 1024 * 600)
            {
                maxTextureDimension = 2048;
            }

            ImageInformation imageInfo;

            if (fileStream != null)
            {
                imageInfo = GetImageInfoFromFileW(fileStream.Name);
            }
            else
            {
                imageInfo = ImageInformation.FromMemory(data);
            }
            var textureWidth  = imageInfo.Width;
            var textureHeight = imageInfo.Height;

            textureWidth  = Math.Max(1, textureWidth >> offsetMipMaps);
            textureHeight = Math.Max(1, textureHeight >> offsetMipMaps);
            int loadMipmapOffset = offsetMipMaps;

            while (textureWidth > maxTextureDimension || textureHeight > maxTextureDimension)
            {
                loadMipmapOffset++;
                textureWidth  = Math.Max(1, textureWidth >> 1);
                textureHeight = Math.Max(1, textureHeight >> 1);
            }

            if (offsetMipMaps == 0 && loadMipmapOffset == 0)
            {
                if (fileStream != null)
                {
                    texture = SharpDX.Direct3D9.Texture.FromFile(device, fileStream.Name, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.Linear, 0);
                }
                else
                {
                    texture = SharpDX.Direct3D9.Texture.FromMemory(device, data, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.Linear, 0);
                }
            }
            else if (loadMipmapOffset > 0)
            {
                var skipFilter = (Filter)D3DXSkipDDSMipLevels((uint)loadMipmapOffset);

                if (fileStream != null)
                {
                    texture = SharpDX.Direct3D9.Texture.FromFile(device, fileStream.Name, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, skipFilter, 0);
                }
                else
                {
                    texture = SharpDX.Direct3D9.Texture.FromMemory(device, data, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, skipFilter, 0);
                }
            }
            else
            {
                if (fileStream != null)
                {
                    texture = SharpDX.Direct3D9.Texture.FromFile(device, fileStream.Name, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0);
                }
                else
                {
                    texture = SharpDX.Direct3D9.Texture.FromMemory(device, data, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0);
                }

                int width        = MipMapSize(offsetMipMaps, texture.GetLevelDescription(0).Width);
                int height       = MipMapSize(offsetMipMaps, texture.GetLevelDescription(0).Height);
                int maxLevels    = Math.Min(MaxMipMapLevels(width), MaxMipMapLevels(height));
                int actualLevels = Math.Min(maxLevels, texture.LevelCount - offsetMipMaps);

                Format  format          = texture.GetLevelDescription(0).Format;
                Texture offsetedTexture = new Texture(device, width, height, actualLevels, Usage.Dynamic, format, Pool.Default);
                for (int i = offsetMipMaps, j = 0; j < actualLevels; i++, j++)
                {
                    int levelWidth  = MipMapSize(j, width);
                    int levelHeight = MipMapSize(j, height);

                    SharpDX.DataStream ds;
                    texture.LockRectangle(i, LockFlags.ReadOnly, out ds);
                    texture.UnlockRectangle(i);

                    SharpDX.DataStream ds2;
                    offsetedTexture.LockRectangle(j, LockFlags.None, out ds2);
                    ds2.Position = 0;
                    ds2.Write(ds.DataPointer, 0, (int)MipMapSizeInBytes(levelWidth, levelHeight, format));
                    offsetedTexture.UnlockRectangle(j);
                }

                texture.Dispose();
                texture = offsetedTexture;
            }
        }
 public override int CreateTexture(int width, int height, IntPtr scan0)
 {
     D3D.Texture texture = device.CreateTexture(width, height, 0, Usage.None, Format.A8R8G8B8, Pool.Managed);
     texture.SetData(0, LockFlags.None, scan0, width * height * 4);
     return(GetOrExpand(ref textures, texture, texBufferSize));
 }
Example #38
0
 public static void DDSFromFile(string fileName, Device device, bool loadMipMap, int offsetMipMaps, out SharpDX.Direct3D9.Texture texture)
 {
     try
     {
         using (var stream = MyFileSystem.OpenRead(fileName))
         {
             InternalDDSFromStream(stream, device, 0, loadMipMap, offsetMipMaps, out texture);
         }
     }
     catch (Exception e)
     {
         MyLog.Default.WriteLine("ERROR: Failed loading texture " + fileName.ToString());
         MyLog.Default.WriteLine(e.ToString());
         throw;
     }
 }