/// <summary>
        ///
        /// </summary>
        protected virtual void Idle()
        {
            SlimDX.Direct3D9.Device device = Device;

            device.BeginScene();

            // reset the depth buffer to 1.0 and the render target to black
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer,
                         new Color4(0, 0, 0), 1.0f, 0);

            // prepare for drawing sprites. We need transparency and z-order
            Sprite.Begin(SpriteFlags.AlphaBlend
                         | SpriteFlags.SortDepthBackToFront);

            OnRender(new RenderEventArgs(this, Device));

            System.Diagnostics.Debug.Assert(device != null);

            // aaaannnd.... done!
            Sprite.End();

            // painting done ...
            device.EndScene();

            // ... so show the result on screen
            device.Present();

            OnIdleEvent(new EventArgs());
        }
        public ShaderManager()
        {
            device = GlobalRenderSettings.Instance.Device;

            this.UsePixelShader = true;
            this.Effects        = new List <Effect>();
        }
Example #3
0
        /// <summary>
        /// Draw the hit boxes.
        /// </summary>
        /// <param name="player">The player to draw to.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawHitbox(int player, Device device)
        {
            byte[] hit = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { player == 1 ? 0x8 : 0xC, 0x134, 0x0, 0x0, 0x0 }, 25248);

            // Because of how fireballs and HIT(red)boxes work,
            // I did this ugly hack. They are either d0 or e0 apart, but you don't know if they start with d0 or e0, so I did both.
            // They are checked later either way (byte 0xac from the fireball-box must be 0x2 for it to display on screen).
            bool isD0 = false;

            for (int i = 0x0; i <= 0x2420; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(hit, i, _strikeHitBoxColor, device);
            }

            isD0 = false;
            for (int i = 0xd0; i <= 0x2420; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(hit, i, _strikeHitBoxColor, device);
            }
        }
Example #4
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="device">Requests the DirectX graphics device.</param>
 public UITexture(D3D.Device device)
 {
     _device        = device;
     RotationCenter = new DX.Vector2();
     Scaling        = new DX.Vector2();
     Translation    = new DX.Vector2();
 }
Example #5
0
        /// <summary>
        /// Draws basic boxes (throw, hurt, physics...)
        /// </summary>
        /// <param name="playerBoxes">The player boxes information.</param>
        /// <param name="device">The draw device.</param>
        private void DrawHurtBoxes(byte[] playerBoxes, Device device)
        {
            if (_interface.DrawBasic1)
            {
                //    DrawQuadFromArray(playerBoxes, 0x530, _hurtBoxColor, device);
                //    DrawQuadFromArray(playerBoxes, 0x5d0, _hurtBoxColor, device);
                //    DrawQuadFromArray(playerBoxes, 0x350, _hurtBoxColor, device);
                //    DrawQuadFromArray(playerBoxes, 0x3f0, _hurtBoxColor, device);

                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.Head, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftShoulder, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftElbow, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftWrist, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftHand, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftHip, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftKnee, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftAnkle, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftFoot, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightShoulder, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightElbow, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightWrist, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightHand, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightHip, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightKnee, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightAnkle, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightFoot, _hurtBoxColor, device);

                //DrawBoxFromArray(playerBoxes, 0x530, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x5d0, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x350, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x3f0, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x2a10, _hurtBoxColor, device); //Head
            }
        }
Example #6
0
 void IPluginDXResource.UpdateResource(IPluginOut pin, EX9.Device device)
 {
     foreach (var renderer in FWebRenderers)
     {
         renderer.UpdateResources(device);
     }
 }
Example #7
0
 void IPluginDXResource.DestroyResource(IPluginOut pin, EX9.Device device, bool onlyUnmanaged)
 {
     foreach (var renderer in FWebRenderers)
     {
         renderer.DestroyResources(device);
     }
 }
Example #8
0
        /*
		public D3DTextureManager(D3D.Direct3D manager, D3D.Device device)
		{
           
		}
         */
         

		protected override Resource _create( string name, ulong handle, string group, bool isManual, IManualResourceLoader loader, NameValuePairList createParams )
		{
            // temporary hack
            manager = D3DRenderSystem.Direct3D9;
            device = D3DRenderSystem.ActiveD3D9Device;
			return new D3DTexture( this, name, handle, group, isManual, loader, this.device, this.manager );
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="DynamicPrimitiveBuffer9"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 public DynamicPrimitiveBuffer9(D3D.Device device)
 {
     if (device == null)
     {
         throw new ArgumentNullException("device");
     }
     this.device = device;
 }
Example #10
0
 // Constructor
 public Camera(SlimDX.Direct3D9.Device device)
 {
     this.device = device;
     //worldMatrix[0, 2] = -1f;
     //worldMatrix[1, 0] = -1f;
     //worldMatrix[2, 1] = 1f;
     //worldMatrix[3, 3] = 1f;
 }
Example #11
0
 /// <summary>
 /// Implements logic to update any relevant sample state.
 /// </summary>
 protected virtual void OnUpdate()
 {
     if (Freelook.Update(FrameDelta))
     {
         Device.SetTransform(TransformState.View, Freelook.View);
     }
     PhysicsContext.Update(FrameDelta);
 }
Example #12
0
        protected Device CreateDevice(int width, int height, bool windowed)
        {
            var d3D9 = CreateDirect3D();

            if (d3D9 == null)
            {
                return(null);
            }
            var caps = d3D9.GetDeviceCaps(0, DeviceType.Hardware);
            var vp   = CreateFlags.Multithreaded | (caps.DeviceCaps.HasFlag(DeviceCaps.HWTransformAndLight) ?
                                                    CreateFlags.HardwareVertexProcessing  :
                                                    CreateFlags.SoftwareVertexProcessing);

            if (caps.VertexShaderVersion < new Version(2, 0) || caps.PixelShaderVersion < new Version(2, 0))
            {
                Debug.Print("Warning - Your graphic card does not support vertex and pixel shaders version 2.0");
            }

            var format = (windowed) ? Format.Unknown : Format.A8R8G8B8;
            var pp     = new PresentParameters {
                BackBufferWidth              = width,
                BackBufferHeight             = height,
                BackBufferFormat             = format,
                BackBufferCount              = 1,
                Multisample                  = MultisampleType.None,
                MultisampleQuality           = 0,
                SwapEffect                   = SwapEffect.Discard,
                DeviceWindowHandle           = MainWindow.Handle,
                Windowed                     = windowed,
                EnableAutoDepthStencil       = true,
                AutoDepthStencilFormat       = Format.D24S8,
                PresentFlags                 = PresentFlags.None,
                FullScreenRefreshRateInHertz = 0,
                PresentationInterval         = PresentInterval.Immediate
            };
            Device device = null;

            try {
                device = new Device(d3D9, 0, DeviceType.Hardware, MainWindow.Handle, vp, pp);
            } catch (Exception ex) {
                Debug.Print("Failed to create Device - {0}", ex.Message);
            }
            d3D9.Dispose();
            System.Diagnostics.Debug.Assert(device != null, "device != null");
            System.Diagnostics.Debug.Assert(device.ComPointer != IntPtr.Zero);
            try {
                device.GetRenderState(RenderState.Lighting);
            } catch (Exception ex) {
                Debug.Print("Error in {0} - {1}\n{2}", ex.TargetSite, ex.Message, ex.StackTrace);
                return(null);
            }
            device.Material = new Material {
                Diffuse = Color.White
            };

            return(device);
        }
Example #13
0
        /// <summary>
        /// Draws throw vulnerable boxes.
        /// </summary>
        /// <param name="playerBoxes">The player boxes information.</param>
        /// <param name="device">The draw device.</param>
        private void DrawThrowVulnerableBoxes(byte[] playerBoxes, Device device)
        {
            DrawQuadFromArray(playerBoxes, 0x2650, _throwHitBoxColor, device);
            DrawQuadFromArray(playerBoxes, 0x2330, _throwHitBoxColor, device); //There's at least 1 missing!
            DrawQuadFromArray(playerBoxes, 0x25b0, _throwHitBoxColor, device);

            // should this be here?
            //// DrawQuadFromArray(testread, 0x170, GetColor("blue"));
        }
Example #14
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="device">Requests the DirectX device.</param>
        protected UIBaseControl(D3D.Device device)
        {
            // define control styles to enable transparency
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.Opaque, true);
            BackColor = Color.Transparent;

            // create texture and sprite
            Texture = new UITexture(device);
            Sprite  = new UISprite(device);
        }
Example #15
0
 public Render(D3D.Device device, int shiftX = 0, int shiftY = 0)
 {
     this.device = device;
     this.shiftX = shiftX;
     this.shiftY = shiftY;
     line        = new D3D.Line(device);
     fonts       = new D3D.Font[3];
     fonts[0]    = new D3D.Font(device, new Font("Dotum", 8, FontStyle.Regular));
     fonts[1]    = new D3D.Font(device, new Font("Calibri", 8, FontStyle.Regular));
     fonts[2]    = new D3D.Font(device, new Font("Tahoma", 9, FontStyle.Regular));
 }
Example #16
0
        /// <summary>
        /// Draw a colored line.
        /// </summary>
        /// <param name="a">Vector A.</param>
        /// <param name="b">Vector B.</param>
        /// <param name="color">The color of the quad.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawLine(Vector3 a, Vector3 b, Color color, Device device)
        {
            LineVertex[] lineData = new LineVertex[2];

            lineData[0].Position = a;
            lineData[0].Color    = color.ToArgb();
            lineData[1].Position = b;
            lineData[1].Color    = color.ToArgb();

            device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;
            device.DrawUserPrimitives <LineVertex>(PrimitiveType.LineList, 0, lineData.Length / 2, lineData);
        }
Example #17
0
        public static void Initialize()
        {
            frm = new Form();
            frm.Show();

            d3d = new DX.Direct3D();

            DX.PresentParameters pm = new DX.PresentParameters();
            pm.Windowed = true; pm.AutoDepthStencilFormat = DX.Format.D24S8;

            device = new DX.Device(d3d, 0, DX.DeviceType.Reference, frm.Handle, DX.CreateFlags.SoftwareVertexProcessing, pm);
        }
Example #18
0
        /// <summary>
        /// Draw a filled box from an array of coordinates.
        /// </summary>
        /// <param name="array">The byte array.</param>
        /// <param name="startindex">The start index.</param>
        /// <param name="color">The color of the box.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawBoxFromArray(byte[] array, int startindex, Color color, Device device)
        {
            BoxPoints boxFromArray = GetBoxFromArray(array, startindex);

            DrawBox(
                boxFromArray.D,
                boxFromArray.A,
                boxFromArray.B,
                boxFromArray.C,
                color,
                device);
        }
Example #19
0
        protected virtual void OnResetDevice()
        {
            Fps.OnResetDevice();

            Matrix projection = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, NearPlane, FarPlane);

            Device.SetTransform(TransformState.Projection, projection);
            Device.SetTransform(TransformState.View, Freelook.View);

            Device.SetRenderState(RenderState.Ambient, Ambient);

            MeshFactory.OnResetDevice();
        }
Example #20
0
        //this method gets called, when Reinitialize() was called in evaluate,
        //or a graphics device asks for its data
        protected override Texture CreateTexture(int Slice, SlimDX.Direct3D9.Device device)
        {
            var pool  = Pool.Managed;
            var usage = Usage.None;

            if (device is DeviceEx)
            {
                pool  = Pool.Default;
                usage = Usage.Dynamic;
            }

            return(new Texture(device, FTexWidth, FTexHeight, 1, usage, Format.L16, pool));
        }
Example #21
0
        public void ToggleFullScreen()
        {
            if (Context9 == null)
            {
                return;
            }

            togglingFullScreen = true;

            OnLostDevice();

            if (Context9.PresentParameters.Windowed)
            {
                windowedFormWindowState = Form.WindowState;
                windowedFormBorderStyle = Form.FormBorderStyle;

                Width  = Form.ClientSize.Width;
                Height = Form.ClientSize.Height;

                // Only normal window can be used in full screen.
                if (Form.WindowState != FormWindowState.Normal)
                {
                    Form.WindowState = FormWindowState.Normal;
                }

                Context9.PresentParameters.BackBufferWidth  = FullScreenWidth;
                Context9.PresentParameters.BackBufferHeight = FullScreenHeight;
                Form.FormBorderStyle = FormBorderStyle.None;

                Context9.PresentParameters.Windowed = false;
            }
            else
            {
                Context9.PresentParameters.BackBufferWidth  = Width;
                Context9.PresentParameters.BackBufferHeight = Height;
                Form.FormBorderStyle = windowedFormBorderStyle;
                Form.WindowState     = windowedFormWindowState;
                if (Form.WindowState == FormWindowState.Normal)
                {
                    Form.ClientSize = new System.Drawing.Size(Width, Height);
                }

                Context9.PresentParameters.Windowed = true;
            }

            Device.Reset(Context9.PresentParameters);
            OnResetDevice();

            togglingFullScreen = false;
        }
Example #22
0
 private void CreateNullDevice()
 {
     form = new Form();
     using (var direct3D = new D3D9.Direct3D())
         device9 = new D3D9.Device(direct3D, 0, D3D9.DeviceType.Reference, form.Handle, D3D9.CreateFlags.SoftwareVertexProcessing, new D3D9.PresentParameters
         {
             BackBufferCount = 1,
             BackBufferFormat = D3D9.Format.X8R8G8B8,
             BackBufferHeight = 512,
             BackBufferWidth = 512,
             SwapEffect = D3D9.SwapEffect.Discard,
             Windowed = true
         });
 }
        public void RipModel(SlimDX.Direct3D9.Device device, SlimDX.Direct3D9.PrimitiveType primitiveType,
                             int baseVertexIndex, int startIndex, int primCount)
        {
            IndexBuffer ib = device.Indices;

            if (primitiveType == PrimitiveType.TriangleList)
            {
                RipTriangleList(baseVertexIndex, startIndex, primCount, ref ib);
            }
            if (primitiveType == PrimitiveType.TriangleStrip)
            {
                RipTriangleStrip(baseVertexIndex, startIndex, primCount, ref ib);
            }
        }
Example #24
0
        public void Initialize()
        {
            // Get maximum screen size.
            Size maxSize = new Size(LOW_RES_WIDTH, LOW_RES_HEIGHT);

            foreach (var screen in Screen.AllScreens)
            {
                maxSize.Width  = Math.Max(maxSize.Width, screen.Bounds.Width);
                maxSize.Height = Math.Max(maxSize.Height, screen.Bounds.Height);
            }

            this.CreateNewBitmapBunch(false, ScalingAlgorithm.None);

            /////////////////////////////////////////
            // Initialize direct3d 9

            this.direct3D = new Direct3D();

            var presentParams = new PresentParameters();

            presentParams.Windowed           = true;
            presentParams.SwapEffect         = SwapEffect.Discard;
            presentParams.DeviceWindowHandle = this.Handle;
            presentParams.BackBufferWidth    = maxSize.Width;
            presentParams.BackBufferHeight   = maxSize.Height;

            this.device = new Device(this.direct3D, 0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, presentParams);

            this.device.SetRenderState(RenderState.Lighting, false);

            /////////////////
            // Set up texture.
            this.texture = new Texture(this.device, textureWidth, textureHeight, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
            var desc = this.texture.GetLevelDescription(0);

            /////////////////
            // Set up vertex buffers
            this.vertexBuffer = new VertexBuffer(this.device
                                                 , 6 * (Marshal.SizeOf(typeof(TexturedVertex)))
                                                 , Usage.WriteOnly, VertexFormat.None, Pool.Default);

            this.vertexDeclaration = new VertexDeclaration(this.device, new[] {
                new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                VertexElement.VertexDeclarationEnd
            });

            initialized = true;
        }
Example #25
0
 public bool Direct3DInit()
 {
     try
     {
         Direct3D           direct3D       = new Direct3D();
         AdapterInformation defaultAdapter = direct3D.Adapters.DefaultAdapter;
         CreateFlags        createFlags    = (direct3D.GetDeviceCaps(defaultAdapter.Adapter, SlimDX.Direct3D9.DeviceType.Hardware).DeviceCaps & DeviceCaps.HWTransformAndLight) != DeviceCaps.HWTransformAndLight ? CreateFlags.SoftwareVertexProcessing : CreateFlags.HardwareVertexProcessing;
         this.GlobalData.presentParams = new PresentParameters()
         {
             BackBufferWidth    = 640,
             BackBufferHeight   = 480,
             BackBufferFormat   = defaultAdapter.CurrentDisplayMode.Format,
             DeviceWindowHandle = this.Form_Main.Handle,
             Windowed           = !this.fullWindow,
             PresentFlags       = PresentFlags.DiscardDepthStencil,
             SwapEffect         = SwapEffect.Discard
         };
         if (this.presentInterval == 1)
         {
             this.GlobalData.presentParams.PresentationInterval = !this.verticalSync ? PresentInterval.Immediate : PresentInterval.Default;
         }
         else if (this.fullWindow && this.verticalSync)
         {
             if (this.presentInterval == 2)
             {
                 this.GlobalData.presentParams.PresentationInterval = PresentInterval.Two;
             }
             else if (this.presentInterval == 3)
             {
                 this.GlobalData.presentParams.PresentationInterval = PresentInterval.Three;
             }
         }
         else
         {
             this.GlobalData.presentParams.PresentationInterval = PresentInterval.Immediate;
         }
         this.DeviceMain = new SlimDX.Direct3D9.Device(direct3D, defaultAdapter.Adapter, SlimDX.Direct3D9.DeviceType.Hardware, this.Form_Main.Handle, createFlags, new PresentParameters[1]
         {
             this.GlobalData.presentParams
         });
         this.GlobalData.SpriteMain = new MySprite(this.DeviceMain);
         return(true);
     }
     catch
     {
         int num = (int)MessageBox.Show("DirectX初始化失败", "DirectX Initial Error");
         return(false);
     }
 }
		/// <summary>
		///		Default constructor.
		/// </summary>
		/// <param name="device">Reference to a Direct3D device.</param>
		public D3DHardwareOcclusionQuery( D3D.Device device )
		{
			this.device = device;

			isQueryResultStillOutstanding = true;

			// check if queries are supported
			isSupported = Root.Instance.RenderSystem.Capabilities.HasCapability( Capabilities.HardwareOcculusion );

			if ( isSupported )
			{
				// attempt to create an occlusion query
				query = new D3D.Query( device, D3D.QueryType.Occlusion );
			}
		}
Example #27
0
        void RenderInstances(SlimDX.Direct3D9.Device device, TimeSpan deltaTime)
        {
            lock (mInstLock)
            {
                foreach (var mat in mInstances.Values)
                {
                    if (Game.GameManager.GraphicsThread.GraphicsManager.Camera.ViewFrustum.Contains(mFile.BoundingBox, mat) == ContainmentType.Disjoint)
                    {
                        return;
                    }

                    mFile.Draw(mat);
                }
            }
        }
Example #28
0
        protected virtual void OnResetDevice()
        {
            Info.OnResetDevice();

            Matrix projection = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, NearPlane, FarPlane);

            Device.SetTransform(TransformState.Projection, projection);
            UpdateView();

            Device.SetRenderState(RenderState.Ambient, Ambient);

            Device.SetLight(0, light);
            Device.EnableLight(0, true);

            _meshFactory.OnResetDevice();
        }
Example #29
0
        /// <summary>
        /// Renders the game.
        /// </summary>
        private void Render()
        {
            if (deviceLost)
            {
                // This should only become true if we're using D3D9, so we can assume the
                // D3D9 context is valid at this point.
                if (Device.TestCooperativeLevel() == SlimDX.Direct3D9.ResultCode.DeviceNotReset)
                {
                    Device.Reset(Context9.PresentParameters);
                    deviceLost = false;
                    OnResetDevice();
                }
                else
                {
                    Thread.Sleep(100);
                    return;
                }
            }

            frameAccumulator += FrameDelta;
            ++frameCount;
            if (frameAccumulator >= 1.0f)
            {
                FramesPerSecond = frameCount / frameAccumulator;

                frameAccumulator = 0.0f;
                frameCount       = 0;
            }

            try
            {
                OnRender();
            }
            catch (SlimDX.Direct3D9.Direct3D9Exception e)
            {
                if (e.ResultCode == SlimDX.Direct3D9.ResultCode.DeviceLost)
                {
                    OnLostDevice();
                    deviceLost = true;
                }
                else
                {
                    throw;
                }
            }
        }
Example #30
0
        public static Direct3D.VertexDeclaration CreateVertexDeclaration(Direct3D.Device d3dDevice, VertexLayout layout)
        {
            List <Direct3D.VertexElement> formats = new List <Direct3D.VertexElement>();
            short loc = 0;

            for (int i = 0; i < layout.Count; i++)
            {
                var element = layout[i];

                Direct3D.VertexElement d3d_element = ConvertElement(element, ref loc);

                formats.Add(d3d_element);
            }

            formats.Add(Direct3D.VertexElement.VertexDeclarationEnd);

            return(new Direct3D.VertexDeclaration(d3dDevice, formats.ToArray()));
        }
        private void HandleResize(object sender, EventArgs e)
        {
            if (Form.WindowState == FormWindowState.Minimized)
            {
                return;
            }

            OnLostDevice();

            if (Context9 != null)
            {
                Context9.PresentParameters.BackBufferWidth  = Form.ClientSize.Width;
                Context9.PresentParameters.BackBufferHeight = Form.ClientSize.Height;

                Device.Reset(Context9.PresentParameters);
            }

            OnResetDevice();
        }
Example #32
0
        /// <summary>
        /// Draws physics boxes.
        /// </summary>
        /// <param name="playerBoxes">The player boxes information.</param>
        /// <param name="device">The draw device.</param>
        private void DrawPhysicsBoxes(byte[] playerBoxes, Device device)
        {
            DrawBoxFromArray(playerBoxes, 0x490, _physicsBoxColor, device);
            DrawBoxFromArray(playerBoxes, 0x350, _physicsBoxColor, device); //There's at least one missing.
            DrawBoxFromArray(playerBoxes, 0x3f0, _physicsBoxColor, device);

            // should this be here?
            //// DrawBoxFromArray(testread, 0x2330, GetColor("yellow"));

            /*
             * if (hurtboxes != null) //These are extra boxes, unknown, broken, empty, missing etc....
             * {
             *  foreach (int i in hurtboxes)
             *  {
             *      DrawQuadFromArray(boxes, i, GetColor("green"));
             *  }
             * }
             */
        }
Example #33
0
        //this method gets called, when Reinitialize() was called in evaluate,
        //or a graphics device asks for its data
        protected override Texture CreateTexture(int Slice, SlimDX.Direct3D9.Device device)
        {
            var pool  = Pool.Managed;
            var usage = Usage.None;

            if (device is DeviceEx)
            {
                pool  = Pool.Default;
                usage = Usage.Dynamic;
            }

            if (FOutputMode[0] == UserTexturetMode.Raw)
            {
                return(new Texture(device, FTexWidth, FTexHeight, 1, usage, Format.L16, pool));
            }
            else
            {
                return(new Texture(device, FTexWidth, FTexHeight, 1, usage, Format.A8R8G8B8, pool));
            }
        }
Example #34
0
 private EX9.Texture CreateTexture(FrameInfo frameInfo, EX9.Device device)
 {
     using (var sharpDxDevice = new SharpDX.Direct3D9.Device(device.ComPointer))
     {
         ((SharpDX.IUnknown)sharpDxDevice).AddReference(); // Dispose will call release
         var decoder = frameInfo.Decoder;
         if (decoder != null)
         {
             using (var texture = decoder.Decode(sharpDxDevice))
             {
                 ((SharpDX.IUnknown)texture).AddReference(); // Dispose will call release
                 return(SlimDX.Direct3D9.Texture.FromPointer(texture.NativePointer));
             }
         }
         else
         {
             return(null);
         }
     }
 }
Example #35
0
        public void DirectXRelease()
        {
            try
            {
                if (DX9device != null)
                {
                    DX9device.Dispose();
                    DX9device = null;
                }

                if (render_event != null)
                {
                    render_event.Close();
                    render_event = null;
                }

                foreach (var item in ObjectTable.Objects)
                    item.Dispose();
            }
            catch (Exception ex)
            {
                Debug.Write("DX release error!" + ex.ToString());
            }
        }
        /// <summary>
        /// Draws throw vulnerable boxes.
        /// </summary>
        /// <param name="playerBoxes">The player boxes information.</param>
        /// <param name="device">The draw device.</param>
        private void DrawThrowVulnerableBoxes(byte[] playerBoxes, Device device)
        {
            DrawQuadFromArray(playerBoxes, 0x2650, _throwHitBoxColor, device);
            DrawQuadFromArray(playerBoxes, 0x2330, _throwHitBoxColor, device); //There's at least 1 missing!
            DrawQuadFromArray(playerBoxes, 0x25b0, _throwHitBoxColor, device);

            // should this be here?
            //// DrawQuadFromArray(testread, 0x170, GetColor("blue"));
        }
        /// <summary>
        /// Draw the grab boxes.
        /// </summary>
        /// <param name="player">The player to draw to.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawGrabBox(int player, Device device)
        {
            byte[] grab = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { player == 1 ? 0x8 : 0xC, 0x138, 0x0, 0x0, 0x0 }, 0xad);

            DrawBoxFromArrayOnHit(grab, 0x0, _throwHitBoxColor, device);
        }
        /// <summary>
        /// Sets the render states and draws the selected objects to scene.
        /// </summary>
        /// <param name="direct3DDevice">The direct 3D device pointer.</param>
        /// <returns><see cref="int"/></returns>
        public int EndSceneHook(IntPtr direct3DDevice)
        {
            // Do the first scan.
            if (!_opened)
            {
                _memory.OpenSF4Process();
                _memory.RunScan();

                _interface.WriteConsole("Street Fighter 4 Process hooked.");

                _opened = true;
            }

            if (_device == null)
            {
                _device = Device.FromPointer(direct3DDevice);

                _interface.WriteConsole(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\uiBackground.png");

                _background = Texture.FromFile(
                    _device,
                    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Resources\Images\uiBackground.png");

                _interface.WriteConsole("Device created.");

                // Attempting to scale the font.
                _fontSize = _device.Viewport.Height / 48;
                _interface.WriteConsole(string.Format("Font size set to {0}", _fontSize));

                _font = new Font(_device, new System.Drawing.Font("Consolas", _fontSize));
            }

            // The game calls endscene twice a frame. We only need to draw once.
            // We should just return as normal the other time.
            if (_endsceneSkip)
            {
                _endsceneSkip = false;
                return _device.EndScene().Code;
            }

            _endsceneSkip = true;

            //// _device.SetRenderState(RenderState.Lighting, false);
            //// _device.SetRenderState(RenderState.SpecularEnable, false);

            _device.SetRenderState(RenderState.CullMode, Cull.None);
            _device.SetRenderState(RenderState.AlphaBlendEnable, true);
            _device.SetRenderState(RenderState.VertexBlend, VertexBlend.Disable);
            _device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
            _device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
            _device.SetRenderState(RenderState.BlendOperationAlpha, BlendOperation.Minimum);
            _device.SetRenderState(RenderState.FillMode, FillMode.Solid);
            _device.SetRenderState(RenderState.ColorWriteEnable, 0xF);
            _device.SetRenderState(RenderState.MultisampleAntialias, false);

            // Setting up the camera
            Vector3 eye = new Vector3 { X = _memory.GetCamX(), Y = _memory.GetCamY(), Z = _memory.GetCamZ() };
            Vector3 target = new Vector3 { X = _memory.GetCamXp(), Y = _memory.GetCamYp(), Z = _memory.GetCamZp() };

            float zoom = _memory.GetCamZoom();

            _device.SetRenderState(RenderState.Lighting, false); // We don't need light for this...
            _device.SetTransform(TransformState.View, Matrix.LookAtLH(eye, target, new Vector3(0, 1, 0)));

            // Fix this shit later!
            _device.SetTransform(
                TransformState.Projection,
                Matrix.PerspectiveLH(0.1f * 16 / 9 * zoom + 0.008f, 0.1f * zoom + 0.008f, 0.1F, 100.0F));

            _playerOneBoxes = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { 0x8, 0x2190 }, 25248);
            _playerTwoBoxes = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { 0xC, 0x2190 }, 25248);

            // Draw everything...
            if (_interface.DrawBasic1)
            {
                DrawHurtBoxes(_playerOneBoxes, _device);
            }

            if (_interface.DrawBasic2)
            {
                DrawHurtBoxes(_playerTwoBoxes, _device);
            }

            if (_interface.DrawPhysics1)
            {
                DrawPhysicsBoxes(_playerOneBoxes, _device);
            }

            if (_interface.DrawPhysics2)
            {
                DrawPhysicsBoxes(_playerTwoBoxes, _device);
            }

            if (_interface.DrawGrab1)
            {
                DrawThrowVulnerableBoxes(_playerOneBoxes, _device);
            }

            if (_interface.DrawGrab2)
            {
                DrawThrowVulnerableBoxes(_playerTwoBoxes, _device);
            }

            if (_interface.DrawHit1)
            {
                DrawHitbox(1, _device);
            }

            if (_interface.DrawHit2)
            {
                DrawHitbox(2, _device);
            }

            if (_interface.DrawGrab1)
            {
                DrawGrabBox(1, _device);
            }

            if (_interface.DrawGrab2)
            {
                DrawGrabBox(2, _device);
            }

            if (_interface.DrawProjectile1)
            {
                DrawProjectileBox(1, _device);
            }

            if (_interface.DrawProjectile2)
            {
                DrawProjectileBox(2, _device);
            }

            if (_interface.DrawProx1)
            {
                DrawProxBox(1, _device);
            }

            if (_interface.DrawProx2)
            {
                DrawProxBox(2, _device);
            }

            if (_interface.DrawInfo)
            {
                DrawInfo(_device);
            }

            _interface.FrameNumber = _memory.GetFrameCount();

            // This does not use the sprite we use for all the other text...
            _font.DrawString(null, "Frame Trapped Lab Active", 20, 20, _textColor);

            return _device.EndScene().Code;
        }
        /// <summary>
        /// Draw the projectile boxes.
        /// </summary>
        /// <param name="player">The player to draw to.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawProjectileBox(int player, Device device)
        {
            byte[] projectile1 = _memory.ReadMemoryByteArrayWithBase(0x00688E88, new int[] { player == 1 ? 0x8 : 0xC, 0x98, 0x0, 0xF8, 0x1b0 }, 0x25000);
            byte[] projectile2 = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { player == 1 ? 0x8 : 0xC, 0x138, 0x0, 0x1F8, 0x1b0 }, 0x190);
            byte[] projectile3 = _memory.ReadMemoryByteArrayWithBase(0x00688E88, new int[] { player == 1 ? 0x8 : 0xC, 0x90, 0x0, 0xF8, 0x1b0 }, 0x500);

            // Because of how fireballs and HIT(red)boxes work,
            // I did this ugly hack. They are either d0 or e0 apart, but you don't know if they start with d0 or e0, so I did both.
            // They are checked later either way (byte 0xac from the fireball-box must be 0x2 for it to display on screen).

            // Regular fireball
            bool isD0 = false;
            for (int i = 0x0; i <= 0x2420; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(projectile1, i, _projectileHitBoxColor, device);
            }

            isD0 = false;
            for (int i = 0xd0; i <= 0x2420; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(projectile1, i, _projectileHitBoxColor, device);
            }

            // Yoga flame!
            isD0 = false;
            for (int i = 0x0; i <= 0x180; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(projectile2, i, _projectileHitBoxColor, device);
            }

            // Yoga flame!
            isD0 = false;
            for (int i = 0xd0; i <= 0x180; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(projectile2, i, _projectileHitBoxColor, device);
            }

            // Knife/Kunai
            isD0 = false;
            for (int i = 0x0; i <= 0x350; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(projectile3, i, _strikeHitBoxColor, device);
            }

            // Knife/Kunai
            isD0 = false;
            for (int i = 0xd0; i <= 0x350; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(projectile3, i, _strikeHitBoxColor, device);
            }
        }
        /// <summary>
        /// Draw a filled box when on hit is active from an array of coordinates.
        /// </summary>
        /// <param name="array">The byte array.</param>
        /// <param name="startindex">The start index.</param>
        /// <param name="color">The color of the box.</param>
        /// <param name="device">The direct3D device.</param>
        /// <remarks>Draws box from array only if it's active.</remarks>
        private void DrawBoxFromArrayOnHit(byte[] array, int startindex, Color color, Device device)
        {
            // This byte should be 0x2 when the box is active, but for some reason that is not always the case.
            if (array[startindex + 0xac] != 0x2)
            {
                return;
            }

            BoxPoints boxFromArray = GetBoxFromArray(array, startindex);
            DrawBox(
                boxFromArray.D,
                boxFromArray.A,
                boxFromArray.B,
                boxFromArray.C,
                color,
                device);
        }
Example #41
0
        private void Main_Load(object sender, EventArgs e)
        {
            HotKey = new Hotkey();
            HotKey.enable(this.Handle, Hotkey.Modifiers.None, Keys.Insert); // Delete //Insert
            HotKey.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.F1);
            HotKey.enable(this.Handle, Hotkey.Modifiers.None, Keys.N);
            HotKey.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.F3);
            HotKey.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.F5);
            //HotKey.enable(base.Handle, Hotkey.Modifiers.None, Keys.CapsLock);
            //HotKey.enable(base.Handle, Hotkey.Modifiers.None, Keys.Q);

            Native.SetWindowLong(this.Handle, -20, (IntPtr)((Native.GetWindowLong(this.Handle, -20) ^ 0x80000) ^ 0x20));
            Native.SetLayeredWindowAttributes(this.Handle, 0, 0xff, 2);

            PresentParameters parameters = new SlimDX.Direct3D9.PresentParameters();
            parameters.Windowed = true;
            parameters.SwapEffect = SwapEffect.Discard;
            parameters.BackBufferFormat = Format.A8R8G8B8;
            parameters.BackBufferHeight = this.Height;
            parameters.BackBufferWidth = this.Width;
            parameters.PresentationInterval = PresentInterval.One;

            DXDevice = new SlimDX.Direct3D9.Device(new Direct3D(), 0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters[] { parameters });
            if (System.IO.File.Exists("map_large.png")) DXTextrureMapLarge = SlimDX.Direct3D9.Texture.FromFile(DXDevice, "map_large.png");
            if (System.IO.File.Exists("map.png")) DXTextrureMap = SlimDX.Direct3D9.Texture.FromFile(DXDevice, "map.png");
            if (System.IO.File.Exists("LagerMap.jpg")) DXTextureGameMap = SlimDX.Direct3D9.Texture.FromFile(DXDevice, "LagerMap.jpg");
            CircleVertices = new VertexBuffer(DXDevice, (circleComplexity + 2) * TexVertex.SizeBytes, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
            DXSprite = new SlimDX.Direct3D9.Sprite(DXDevice);
            DXLine = new SlimDX.Direct3D9.Line(DXDevice);
            DXFont = new SlimDX.Direct3D9.Font(DXDevice, new System.Drawing.Font("NewRoman", 9f)); //NewRoman
            DXFontB = new SlimDX.Direct3D9.Font(DXDevice, new System.Drawing.Font("Tahoma", 12f)); //NewRoman

            if (this.GameMemory.Attach("H1Z1 PlayClient (Live)") == false) { Application.Exit(); return; }
            Thread dxThread = new Thread(new ThreadStart(DoProcess));
            dxThread.IsBackground = true;
            dxThread.Start();

            //Thread aimThread = new Thread(new ThreadStart(DoAiming));
            //aimThread.IsBackground = true;
            //aimThread.Start();
        }
        /// <summary>
        /// Draw the player information.
        /// </summary>
        /// <param name="device">The direct3D device.</param>
        private void DrawInfo(Device device)
        {
            try
            {
                int deviceWidth = device.Viewport.Width;
                int deviceHeight = device.Viewport.Height;
                long frameCounter = _memory.GetFrameCount();

                if (frameCounter > 10)
                {
                    if (string.IsNullOrEmpty(_playerOneName))
                    {
                        _playerOneName = _memory.GetCharacter(1);
                    }

                    if (string.IsNullOrEmpty(_playerTwoName))
                    {
                        _playerTwoName = _memory.GetCharacter(2);
                    }

                    _sprite = new Sprite(_device);
                    _sprite.Begin(SpriteFlags.AlphaBlend);

                    _sprite.Transform
                        = Matrix.Scaling(new Vector3(_fontSize / (12 / 2), _fontSize / (7 / 2), 0));

                    _spritePosition = new Vector2(
                        _fontSize,
                        (deviceHeight / _fontSize) * 7);

                    _sprite.Draw(_background, new Vector3(1, 1, 0), new Vector3(_spritePosition, -1), Color.White);

                    _spritePosition = new Vector2(
                        deviceWidth - (_fontSize * 13),
                        (deviceHeight / _fontSize) * 7);

                    _sprite.Draw(_background, new Vector3(1, 1, 0), new Vector3(_spritePosition, -1), Color.White);

                    _sprite.End();
                    _sprite.Dispose();

                    _sprite = new Sprite(_device);
                    _sprite.Begin(SpriteFlags.AlphaBlend);

                    // P1
                    string playerOneHeader = string.Format("-{0}'s STATS-", _playerOneName);
                    string playerOnePos = string.Format(
                        "[{0},{1}]",
                        _memory.GetPosX(1).ToString("F3"),
                        _memory.GetPosY(1).ToString("F3"));
                    string playerOneHealth = string.Format("HP    : {0}", _memory.GetHealth(1));
                    string playerOneStun = string.Format("STUN  : {0}", _memory.GetStun(1));
                    string playerOneEx = string.Format("EX    : {0}", _memory.GetEXmeter(1));
                    string playerOneUltra = string.Format("ULTRA : {0}", _memory.GetUltraMeter(1));
                    string playerOneScript = string.Format(
                        "ANIM  : {0} ({1})",
                        _memory.PlayerAnim(1),
                        _memory.GetAnimFrame(1));
                    int playerOneInterruptFrame = _memory.GetInterruptFrame(1);
                    string playerOneInterrupt = string.Format("INTRPT: {0}", playerOneInterruptFrame);

                    // P2
                    string playerTwoHeader = string.Format("-{0}'s STATS-", _playerTwoName);
                    string playerTwoPos = string.Format(
                        "[{0},{1}]",
                        _memory.GetPosX(2).ToString("F3"),
                        _memory.GetPosY(2).ToString("F3"));
                    string playerTwoHealth = string.Format("HP    : {0}", _memory.GetHealth(2));
                    string playerTwoStun = string.Format("STUN  : {0}", _memory.GetStun(2));
                    string playerTwoEx = string.Format("EX    : {0}", _memory.GetEXmeter(2));
                    string playerTwoUltra = string.Format("ULTRA : {0}", _memory.GetUltraMeter(2));
                    string playerTwoScript = string.Format(
                        "ANIM  : {0} ({1})",
                        _memory.PlayerAnim(2),
                        _memory.GetAnimFrame(2));
                    int playerTwoInterruptFrame = _memory.GetInterruptFrame(2);
                    string playerTwoInterrupt = string.Format("INTRPT: {0}", playerTwoInterruptFrame);

                    string playerOneAdv = string.Format("ADV   : {0}", playerOneInterruptFrame - playerTwoInterruptFrame);
                    string playerTwoAdv = string.Format("ADV   : {0}", playerTwoInterruptFrame - playerOneInterruptFrame);

                    string playerOneStats = string.Join(
                        "\n",
                        playerOneHeader,
                        playerOnePos,
                        playerOneHealth,
                        playerOneStun,
                        playerOneEx,
                        playerOneUltra,
                        playerOneScript,
                        playerOneInterrupt,
                        playerOneAdv);

                    string playerTwoStats = string.Join(
                        "\n",
                        playerTwoHeader,
                        playerTwoPos,
                        playerTwoHealth,
                        playerTwoStun,
                        playerTwoEx,
                        playerTwoUltra,
                        playerTwoScript,
                        playerTwoInterrupt,
                        playerTwoAdv);

                    _font.DrawString(null, playerOneStats, _fontSize, (deviceHeight / _fontSize) * 8, _textColor);

                    _font.DrawString(null, playerTwoStats, deviceWidth - (_fontSize * 13), (deviceHeight / _fontSize) * 8, _textColor);

                    // Both
                    _font.DrawString(
                        null,
                        string.Format("Combo Counter: {0}", _memory.ComboCounter()),
                        deviceWidth / 20 * 9,
                        30,
                        _textColor);
                    _font.DrawString(
                        null,
                        string.Format("Distance: {0}", _memory.GetDistance()),
                        deviceWidth / 20 * 8,
                        deviceHeight / 20 * 18,
                        _textColor);
                    _font.DrawString(
                        null,
                        string.Format("Frame Counter: {0}", frameCounter),
                        deviceWidth / 20 * 8,
                        deviceHeight / 20 * 19,
                        _textColor);

                    _sprite.End();
                    _sprite.Dispose();
                }
                else
                {
                    _playerOneName = string.Empty;
                    _playerTwoName = string.Empty;
                }
            }
            catch
            {

            }
        }
Example #43
0
        public bool DirectX_Init(string background_image)
        {
            PresentParameters presentParms = new PresentParameters();
            presentParms.Windowed = true;
            presentParms.SwapEffect = SwapEffect.Discard;
            presentParms.Multisample = MultisampleType.None;
            presentParms.EnableAutoDepthStencil = true;
            presentParms.AutoDepthStencilFormat = Format.D16;
            presentParms.PresentFlags = PresentFlags.DiscardDepthStencil;
            presentParms.PresentationInterval = PresentInterval.Default;
            presentParms.BackBufferFormat = Format.X8R8G8B8;
            presentParms.BackBufferHeight = gauge_target.Height;
            presentParms.BackBufferWidth = gauge_target.Width;
            presentParms.Windowed = true;
            presentParms.BackBufferCount = 1;

            switch (directx_render_type)
            {
                case RenderType.HARDWARE:
                    try
                    {
                        DX9device = new Device(new Direct3D(), 0, DeviceType.Hardware,
                            gauge_target.Handle, CreateFlags.HardwareVertexProcessing |
                        CreateFlags.FpuPreserve | CreateFlags.Multithreaded,
                            presentParms);
                    }
                    catch (Direct3D9Exception ex)
                    {
                        MessageBox.Show("Problem u inicijalizaciji DirectX-a greska 1\n" + ex.ToString());
                    }
                    break;

                case RenderType.SOFTWARE:
                    {
                        try
                        {
                            DX9device = new Device(new Direct3D(), 0,
                                DeviceType.Hardware,
                                gauge_target.Handle, CreateFlags.SoftwareVertexProcessing |
                            CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms);
                        }
                        catch (Direct3D9Exception exe)
                        {
                            MessageBox.Show("Problem u inicijalizaciji DirectX-a greska 2\n" + exe.ToString());
                            return false;
                        }
                    }
                    break;
            }

            var vertexElems = new[] {
                        new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
                        new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                        VertexElement.VertexDeclarationEnd
                        };

            var vertexDecl = new VertexDeclaration(DX9device, vertexElems);
            DX9device.VertexDeclaration = vertexDecl;

            if (File.Exists(background_image))
            {
                BackgroundTexture = Texture.FromFile(DX9device, background_image, this.Width, this.Height,
                    1, Usage.None, Format.Unknown, Pool.Default, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0);
            }

            texture_size.Width = gauge_target.Width;
            texture_size.Height = gauge_target.Height;
            sprite = new Sprite(DX9device);

            if (render_event == null)
                render_event = new AutoResetEvent(true);

            line = new Line(DX9device);
            line.Antialias = true;
            line.Width = 3;
            line.GLLines = true;
            DX9device.SetRenderState(RenderState.AntialiasedLineEnable, true);

            return true;
        }
        /// <summary>
        /// Draw the hit boxes.
        /// </summary>
        /// <param name="player">The player to draw to.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawHitbox(int player, Device device)
        {
            byte[] hit = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { player == 1 ? 0x8 : 0xC, 0x134, 0x0, 0x0, 0x0 }, 25248);

            // Because of how fireballs and HIT(red)boxes work,
            // I did this ugly hack. They are either d0 or e0 apart, but you don't know if they start with d0 or e0, so I did both.
            // They are checked later either way (byte 0xac from the fireball-box must be 0x2 for it to display on screen).
            bool isD0 = false;

            for (int i = 0x0; i <= 0x2420; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(hit, i, _strikeHitBoxColor, device);
            }

            isD0 = false;
            for (int i = 0xd0; i <= 0x2420; i += 0xd0)
            {
                if (isD0)
                {
                    i += 0x10;
                }

                isD0 = !isD0;

                DrawBoxFromArrayOnHit(hit, i, _strikeHitBoxColor, device);
            }
        }
		/// <summary>
		///
		/// </summary>
		/// <param name="device"></param>
		public D3DHardwareBufferManagerBase( D3D.Device device )
		{
			this.device = device;
		}
		///<summary>
		///    Call this to associate a D3D volume with this pixel buffer
		///</summary>
		public void Bind( D3D.Device device, D3D.Volume volume, bool update )
		{
			this.device = device;
			this.volume = volume;

			D3D.VolumeDescription desc = volume.Description;
			Width = desc.Width;
			Height = desc.Height;
			Depth = desc.Depth;
			Format = D3DHelper.ConvertEnum( desc.Format );
			// Default
			RowPitch = Width;
			SlicePitch = Height * Width;
			sizeInBytes = PixelUtil.GetMemorySize( Width, Height, Depth, Format );

			if ( ( (int)usage & (int)TextureUsage.RenderTarget ) != 0 )
				CreateRenderTextures( update );
		}
		public D3DHardwarePixelBuffer( BufferUsage usage )
			: base( 0, 0, 0, Axiom.Media.PixelFormat.Unknown, usage, false, false )
		{
			device = null;
			surface = null;
			volume = null;
			tempSurface = null;
			tempVolume = null;
			doMipmapGen = false;
			HWMipmaps = false;
			mipTex = null;
			sliceTRT = new List<RenderTexture>();
		}
        /// <summary>
        /// Draws basic boxes (throw, hurt, physics...)
        /// </summary> 
        /// <param name="playerBoxes">The player boxes information.</param>
        /// <param name="device">The draw device.</param>
        private void DrawHurtBoxes(byte[] playerBoxes, Device device)
        {
            if (_interface.DrawBasic1)
            {
                //    DrawQuadFromArray(playerBoxes, 0x530, _hurtBoxColor, device);
                //    DrawQuadFromArray(playerBoxes, 0x5d0, _hurtBoxColor, device);
                //    DrawQuadFromArray(playerBoxes, 0x350, _hurtBoxColor, device);
                //    DrawQuadFromArray(playerBoxes, 0x3f0, _hurtBoxColor, device);

                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.Head, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftShoulder, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftElbow, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftWrist, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftHand, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftHip, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftKnee, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftAnkle, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.LeftFoot, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightShoulder, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightElbow, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightWrist, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightHand, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightHip, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightKnee, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightAnkle, _hurtBoxColor, device);
                DrawFilledQuadFromArray(playerBoxes, (int)BodyPartHurtBox.RightFoot, _hurtBoxColor, device);

                //DrawBoxFromArray(playerBoxes, 0x530, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x5d0, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x350, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x3f0, _hurtBoxColor, device);
                //DrawBoxFromArray(playerBoxes, 0x2a10, _hurtBoxColor, device); //Head
            }
        }
 /// <summary>
 /// Draw a filled quad using lines.
 /// </summary>
 /// <param name="a">Vector A.</param>
 /// <param name="b">Vector B.</param>
 /// <param name="c">Vector C.</param>
 /// <param name="d">Vector D.</param> 
 /// <param name="color">The color of the quad.</param>
 /// <param name="device">The direct3D device.</param>
 private void DrawFilledQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Color color, Device device)
 {
     DrawBox(a, b, c, d, color, device);
     DrawQuad(a, b, c, d, color, device);
 }
        //public override void ApplySettings()
        //{
        //    if (Settings.RequiresDeviceReset)
        //    {
        //        MarkForReset();
        //        Settings.RequiresDeviceReset = false;
        //    }
        //}
        public override void Create()
        {
            D3D = new SlimDX.Direct3D9.Direct3D();
            InitParams();
            #if DEBUG
            int adapter = 0;
            bool perfHud = false;
            #endif

            Application.Log("Listing adapters..");

            for (int i = 0; i < D3D.AdapterCount; i++)
            {
                var res = D3D.GetAdapterIdentifier(i);
                Application.Log("[" + i + "] Adapter: " + res.Description);
            #if DEBUG
                if (res.Description.Contains("PerfHUD"))
                {
                    adapter = i;
                    perfHud = true;
                    break;
                }
            #endif
            }

            // Multithreaded flag:
            // "If you set that flag in D3D9 or D3D10, then the device will enter a critical section every time you call
            // one of its methods (or a method on any objects created by the device, like a texture or vertex buffer).
            // This makes it safe for you to do whatever you want from multiple threads, but it will end up serializing
            // all of your API calls which will kill performance."
            // http://www.gamedev.net/community/forums/topic.asp?topic_id=533801&whichpage=1&#3450338
            //  * Needed since the physics thread performs mesh intersections which crashes the application if performed on an object being rendered
            #if DEBUG
            if (perfHud)
            {
                Application.Log("Using NVidia PerfHUD adapter");
                Device9 = new Device(D3D, adapter, DeviceType.Reference, presentParams.DeviceWindowHandle,
                    CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded,   // see above
                    presentParams);
            }
            else
            {
            #endif
                if (SettingConverters.VertexProcessing == CreateFlags.None)
                {
                    Device9 = new Device(D3D, 0, DeviceType.Hardware, presentParams.DeviceWindowHandle,
                        CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded,    // see above
                        presentParams);
                }
                else
                {
                    if (SettingConverters.VertexProcessing == CreateFlags.SoftwareVertexProcessing)
                    {
                        Device9 = new Device(D3D, 0, DeviceType.Hardware, presentParams.DeviceWindowHandle,
                                 SettingConverters.VertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded,    // see above
                                 presentParams);
                    }
                    else if (Settings.PureDevice)
                    {
                        Device9 = new Device(D3D, 0, DeviceType.Hardware, presentParams.DeviceWindowHandle,
                            SettingConverters.VertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded | CreateFlags.PureDevice,    // see above
                            presentParams);
                    }
                    else
                    {
                        Device9 = new Device(D3D, 0, DeviceType.Hardware, presentParams.DeviceWindowHandle,
                            SettingConverters.VertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded,    // see above
                            presentParams);
                    }
                }
            #if DEBUG
            }
            #endif

            markedForReset = false;
        }
        /// <summary>
        /// Draw simple colored filled box.
        /// </summary>
        /// <param name="a">Vector A.</param>
        /// <param name="b">Vector B.</param>
        /// <param name="c">Vector C.</param>
        /// <param name="d">Vector D.</param> 
        /// <param name="color">The color of the quad.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawBox(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Color color, Device device)
        {
            LineVertex[] lineData = new LineVertex[4];

            lineData[0].Position = a;
            lineData[0].Color = color.ToArgb();
            lineData[1].Position = b;
            lineData[1].Color = color.ToArgb();

            lineData[2].Position = c;
            lineData[2].Color = color.ToArgb();
            lineData[3].Position = d;
            lineData[3].Color = color.ToArgb();

            device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;
            device.DrawUserPrimitives<LineVertex>(PrimitiveType.TriangleFan, 0, lineData.Length / 2, lineData);
        }
Example #52
0
        public override void Hook()
        {
            //dev.SetCooperativeLevel(new System.Windows.Forms.Form(), CooperativeLevelFlags.Normal);
            //desc.SurfaceCaps.OffScreenPlain = true;
            //desc.Height = 300;
            //desc.Width = 300;
            //s1 = new Microsoft.DirectX.DirectDraw.Surface(desc, dev);
            

            this.DebugMessage("Hook: DD Begin");
            // First we need to determine the function address for IDirect3DDevice9
            SlimDX.Direct3D9.Device mydevice;
            List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>();
            this.DebugMessage("Hook: Before device creation");
            using (Direct3D d3d = new Direct3D())
            {
                this.DebugMessage("Hook: Device created");
                using (mydevice = new SlimDX.Direct3D9.Device(d3d, 0, DeviceType.NullReference, IntPtr.Zero, SlimDX.Direct3D9.CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(mydevice.ComPointer, D3D9_DEVICE_METHOD_COUNT));
                }
            }
            
            
            int r;
            IntPtr ir;
            #region Test - try to find dd surface blt method addr
            IDirectDraw7 mydd;
            Type DDinterfaceType = typeof(IDirectDrawSurface);
            DirectDrawCreate(IntPtr.Zero, out mydd, IntPtr.Zero);
            this.DebugMessage("Created directDraw object");
            IDirectDrawSurface mysurface;
            r = mydd.SetCooperativeLevel(IntPtr.Zero, new IntPtr(1));
            this.DebugMessage("Setcooperativelevel, returned: " + r.ToString());
            DDSURFACEDESC2 ddesc = new DDSURFACEDESC2();
            ddesc.dwSize = 124;
            ddesc.ddsCaps.dwCaps = 64;
            ddesc.dwFlags = 7;
            ddesc.dwHeight = 300;
            ddesc.dwWidth = 300;

            ir = mydd.CreateSurface(ref ddesc, out mysurface, IntPtr.Zero);
            //ir = mydd.CreateSurface(0x0018fbf8, out mysurface, IntPtr.Zero);
            this.DebugMessage("Created directDraw surface, returned: " + ir.ToString() );
            IntPtr ddinterfaceIntPtr = Marshal.GetComInterfaceForObject(mysurface, DDinterfaceType);
            unsafe
            {
                int* faddr;
                int*** ddinterfaceRawPtr = (int***)ddinterfaceIntPtr.ToPointer();
                int** vTable = *ddinterfaceRawPtr;
                this.DebugMessage("directDraw surface intptr, returned: " + ddinterfaceIntPtr.ToString());
                                
                MethodInfo mi = DDinterfaceType.GetMethod("Blt");
                int mi_vto = Marshal.GetComSlotForMethodInfo(mi);
                faddr = vTable[mi_vto];
                
                this.DebugMessage("Hook: comslot: " + mi_vto.ToString ());
                this.DebugMessage("Hook: final blt addr: " + (int)faddr);

                DirectDrawSurface_BltHook = LocalHook.Create(new System.IntPtr(faddr), new DirectDrawSurface_BltDelegate(BltHook), this);
            }
            #endregion
                        
            #region Test - try to find device addr my way, and FOUND IT!
            Type interfaceType = typeof(IDirect3DDevice9);
            IDirect3D9 d = Direct3DCreate9(32);
            IDirect3DDevice9 mydevice2;
            D3DPRESENT_PARAMETERS2 d3dpp = new D3DPRESENT_PARAMETERS2();
            d3dpp.Windowed = 1;
            d3dpp.SwapEffect = D3DSWAPEFFECT.D3DSWAPEFFECT_DISCARD ;
            d3dpp.BackBufferFormat = D3DFORMAT.D3DFMT_A8R8G8B8;
            d3dpp.EnableAutoDepthStencil = 1;
            d3dpp.AutoDepthStencilFormat = D3DFORMAT.D3DFMT_D16;

            r = d.CreateDevice(0, D3DDEVTYPE.D3DDEVTYPE_NULLREF, IntPtr.Zero, CreateFlags.D3DCREATE_MIXED_VERTEXPROCESSING, ref d3dpp, out mydevice2);
            this.DebugMessage("Hook: Device create return 2.0 " + r.ToString ());
            IntPtr interfaceIntPtr = Marshal.GetComInterfaceForObject(mydevice2, interfaceType);
            
            unsafe {int*** interfaceRawPtr = (int***)interfaceIntPtr.ToPointer();
            int** vTable = *interfaceRawPtr; 
            this.DebugMessage("Hook: ih com ptr " + mydevice.ComPointer.ToString ());
            this.DebugMessage("Hook: my com ptr (interface int ptr) " + interfaceIntPtr.ToString() );
            

            MethodInfo mi = interfaceType.GetMethod("EndScene");
            int mi_vto = Marshal.GetComSlotForMethodInfo(mi);
            int* faddr = vTable[mi_vto];

            this.DebugMessage("Hook: ih addr to end_scene " + id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene]);
            this.DebugMessage("Hook: my addr to end_scene " + (int)faddr);
            }
            #endregion

            // We want to hook each method of the IDirect3DDevice9 interface that we are interested in
            
            // 42 - EndScene (we will retrieve the back buffer here)
            Direct3DDevice_EndSceneHook = LocalHook.Create(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                // (IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x1ce09),
                // A 64-bit app would use 0xff18
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_EndSceneDelegate(EndSceneHook),
                this);

            // 16 - Reset (called on resolution change or windowed/fullscreen change - we will reset some things as well)
            Direct3DDevice_ResetHook = LocalHook.Create(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                //(IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x58dda),
                // A 64-bit app would use 0x3b3a0
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_ResetDelegate(ResetHook),
                this);

            /*
             * Don't forget that all hooks will start deactivated...
             * The following ensures that all threads are intercepted:
             * Note: you must do this for each hook.
             */
            Direct3DDevice_EndSceneHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            Direct3DDevice_ResetHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            DirectDrawSurface_BltHook.ThreadACL.SetExclusiveACL(new Int32[1]);

            this.DebugMessage("Hook: End");
        }
        /// <summary>
        /// The run method.
        /// </summary>
        /// <param name="inContext">The remote hook context.</param>
        /// <param name="inChannelName">The channel name.</param>
        public void Run(RemoteHooking.IContext inContext, string inChannelName)
        {
            Device dev = new Device(
                new Direct3D(),
                0,
                DeviceType.Hardware,
                IntPtr.Zero,
                CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice,
                new PresentParameters { BackBufferWidth = 1, BackBufferHeight = 1 });
            IntPtr addy = dev.ComPointer;
            addy = (IntPtr)Marshal.ReadInt32(addy);
            addy = (IntPtr)((int)addy + 0xA8);  // Endscene
            addy = (IntPtr)Marshal.ReadInt32(addy);
            _endSceneHooker = LocalHook.Create(addy, new DEndScene(EndSceneHook), this);
            _endSceneHooker.ThreadACL.SetExclusiveACL(new int[] { 0 });

            while (true)
            {
            }
        }
        /// <summary>
        /// Draw the proximity box.
        /// </summary>
        /// <param name="player">The player to draw to.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawProxBox(int player, Device device)
        {
            byte[] prox = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { player == 1 ? 0x8 : 0xC, 0x130, 0x0, 0x0, 0x0 }, 0xad);

            DrawBoxFromArrayOnHit(prox, 0x0, _proximityBoxColor, device);
        }
        /// <summary>
        /// Draws physics boxes.
        /// </summary>
        /// <param name="playerBoxes">The player boxes information.</param>
        /// <param name="device">The draw device.</param>
        private void DrawPhysicsBoxes(byte[] playerBoxes, Device device)
        {
            DrawBoxFromArray(playerBoxes, 0x490, _physicsBoxColor, device);
            DrawBoxFromArray(playerBoxes, 0x350, _physicsBoxColor, device); //There's at least one missing.
            DrawBoxFromArray(playerBoxes, 0x3f0, _physicsBoxColor, device);

            // should this be here?
            //// DrawBoxFromArray(testread, 0x2330, GetColor("yellow"));

            /*
            if (hurtboxes != null) //These are extra boxes, unknown, broken, empty, missing etc....
            {
                foreach (int i in hurtboxes)
                {
                    DrawQuadFromArray(boxes, i, GetColor("green"));
                }
            }
            */
        }
Example #56
0
        public static bool DirectXInit()
        {
            if (!MainForm.booting)
            {
                try
                {
                    if (!MainForm.booting)
                    {
                        rendering = false;

                        switch (display_mode)
                        {
                            case DisplayMode.PANADAPTER:
                            case DisplayMode.PANAFALL:
                            case DisplayMode.PANASCOPE:
                                panadapter_target = (Control)MainForm.picPanadapter;
                                panadapter_W = panadapter_target.Width;
                                panadapter_H = panadapter_target.Height;
                                waterfall_target = (Control)MainForm.picWaterfall;
                                waterfall_H = waterfall_target.Height;
                                waterfall_W = waterfall_target.Width;
                                waterfallX_data = new float[waterfall_W];
                                panadapterX_scope_data = new float[waterfall_W * 2];
                                panadapterX_scope_data_mark = new float[waterfall_W * 2];
                                panadapterX_scope_data_space = new float[waterfall_W * 2];
                                Audio.ScopeDisplayWidth = waterfall_W;
                                break;
                            case DisplayMode.PANAFALL_INV:
                            case DisplayMode.PANASCOPE_INV:
                                panadapter_target = (Control)MainForm.picWaterfall;
                                panadapter_W = panadapter_target.Width;
                                panadapter_H = panadapter_target.Height;
                                waterfall_target = (Control)MainForm.picPanadapter;
                                waterfall_H = waterfall_target.Height;
                                waterfall_W = waterfall_target.Width;
                                waterfallX_data = new float[waterfall_W];
                                panadapterX_scope_data = new float[waterfall_W * 2];
                                Audio.ScopeDisplayWidth = waterfall_W;
                                break;
                            case DisplayMode.WATERFALL:
                                waterfall_target = (Control)MainForm.picWaterfall;
                                break;
                            default:
                                panadapter_H = panadapter_target.Height;
                                panadapter_W = panadapter_target.Width;
                                panadapterX_scope_data = new float[panadapter_W];
                                panadapter_target = (Control)MainForm.picPanadapter;
                                break;
                        }

                        panadapterX_data = new float[panadapter_target.Width];
                        refresh_panadapter_grid = true;

                        average_buffer = new float[BUFFER_SIZE];	// initialize averaging buffer array
                        average_buffer[0] = CLEAR_FLAG;		// set the clear flag

                        average_waterfall_buffer = new float[BUFFER_SIZE];	// initialize averaging buffer array
                        average_waterfall_buffer[0] = CLEAR_FLAG;		// set the clear flag

                        peak_buffer = new float[BUFFER_SIZE];
                        peak_buffer[0] = CLEAR_FLAG;

                        new_display_data = new float[BUFFER_SIZE];
                        new_waterfall_data = new float[BUFFER_SIZE];
                        current_display_data = new float[BUFFER_SIZE];
                        current_waterfall_data = new float[BUFFER_SIZE];
                        waterfall_display_data = new float[BUFFER_SIZE];

                        for (int i = 0; i < BUFFER_SIZE; i++)
                        {
                            new_display_data[i] = 0.0f;
                            new_waterfall_data[i] = 0.0f;
                            current_display_data[i] = 0.0f;
                            current_waterfall_data[i] = 0.0f;
                            waterfall_display_data[i] = 0.0f;
                        }

                        PresentParameters presentParms = new PresentParameters();
                        presentParms.Windowed = true;
                        presentParms.SwapEffect = SwapEffect.Discard;
                        presentParms.BackBufferFormat = SlimDX.Direct3D9.Format.Unknown;
                        presentParms.BackBufferHeight = panadapter_target.Height;
                        presentParms.BackBufferWidth = panadapter_target.Width;
                        presentParms.BackBufferCount = 1;
                        presentParms.BackBufferFormat = Format.X8R8G8B8;

                        PresentParameters waterfall_presentParms = new PresentParameters();
                        waterfall_presentParms.Windowed = true;
                        waterfall_presentParms.SwapEffect = SwapEffect.Discard;
                        waterfall_presentParms.BackBufferFormat = SlimDX.Direct3D9.Format.Unknown;
                        waterfall_presentParms.BackBufferHeight = waterfall_target.Height;
                        waterfall_presentParms.BackBufferWidth = waterfall_target.Width;
                        waterfall_presentParms.BackBufferCount = 1;
                        waterfall_presentParms.BackBufferFormat = Format.X8R8G8B8;

                        switch (directx_render_type)
                        {
                            case RenderType.HARDWARE:
                                try
                                {
                                    device = new Device(new Direct3D(), 0, DeviceType.Hardware,
                                        panadapter_target.Handle, CreateFlags.HardwareVertexProcessing |
                                        CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms);

                                    waterfall_dx_device = new Device(new Direct3D(), 0,
                                        DeviceType.Hardware, waterfall_target.Handle,
                                        CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve |
                                         CreateFlags.Multithreaded, waterfall_presentParms);
                                }
                                catch (Direct3D9Exception ex)
                                {
                                    MessageBox.Show("DirectX hardware init error!" + ex.ToString());
                                }
                                break;

                            case RenderType.SOFTWARE:
                                {
                                    try
                                    {
                                        device = new Device(new Direct3D(), 0,
                                            DeviceType.Hardware,
                                            panadapter_target.Handle, CreateFlags.SoftwareVertexProcessing |
                                            CreateFlags.FpuPreserve, presentParms);

                                        waterfall_dx_device = new Device(new Direct3D(), 0,
                                            DeviceType.Hardware, waterfall_target.Handle,
                                            CreateFlags.SoftwareVertexProcessing | CreateFlags.FpuPreserve,
                                            waterfall_presentParms);

                                    }
                                    catch (Direct3D9Exception ex)
                                    {
                                        MessageBox.Show("DirectX software init error!\n" + ex.ToString());
                                        return false;
                                    }
                                }
                                break;
                        }

                        var vertexElems = new[] {
                        new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
                        new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                        VertexElement.VertexDeclarationEnd
                        };

                        var vertexElems1 = new[] {
                        new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
                        new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                        VertexElement.VertexDeclarationEnd
                        };

                        var vertexDecl = new VertexDeclaration(device, vertexElems);
                        device.VertexDeclaration = vertexDecl;
                        var vertexDecl1 = new VertexDeclaration(waterfall_dx_device, vertexElems1);
                        waterfall_dx_device.VertexDeclaration = vertexDecl1;

                        waterfall_bmp = new System.Drawing.Bitmap(waterfall_target.Width, waterfall_target.Height,
                            System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                        BitmapData bitmapData = waterfall_bmp.LockBits(
                            new Rectangle(0, 0, waterfall_bmp.Width, waterfall_bmp.Height),
                            ImageLockMode.ReadWrite, waterfall_bmp.PixelFormat);

                        waterfall_bmp_size = bitmapData.Stride * waterfall_bmp.Height;
                        waterfall_bmp_stride = bitmapData.Stride;
                        waterfall_memory = new byte[waterfall_bmp_size];
                        waterfall_bmp.UnlockBits(bitmapData);
                        waterfall_rect = new Rectangle(0, 0, waterfall_target.Width, waterfall_target.Height);

                        panadapter_font = new SlimDX.Direct3D9.Font(device, pan_font);

                        if (File.Exists(background_image))
                        {
                            PanadapterTexture = Texture.FromFile(device, background_image, panadapter_target.Width, panadapter_target.Height,
                                1, Usage.None, Format.Unknown, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0);
                            Panadapter_texture_size.Width = panadapter_target.Width;
                            Panadapter_texture_size.Height = panadapter_target.Height;
                            Panadapter_Sprite = new Sprite(device);
                            WaterfallTexture = Texture.FromFile(waterfall_dx_device, background_image, waterfall_target.Width, waterfall_target.Height,
                                1, Usage.None, Format.X8R8G8B8, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0);
                            Waterfall_texture_size.Width = waterfall_target.Width;
                            Waterfall_texture_size.Height = waterfall_target.Height;
                            Waterfall_Sprite = new Sprite(waterfall_dx_device);
                        }
                        else
                        {
                            Panadapter_Sprite = null;
                            WaterfallTexture = new Texture(waterfall_dx_device, waterfall_target.Width, waterfall_target.Height, 0,
                                Usage.None, Format.X8R8G8B8, Pool.Managed);
                            Waterfall_texture_size.Width = waterfall_target.Width;
                            Waterfall_texture_size.Height = waterfall_target.Height;
                            Waterfall_Sprite = new Sprite(waterfall_dx_device);
                        }

                        if (Panadapter_Event == null)
                            Panadapter_Event = new AutoResetEvent(true);
                        if (Waterfall_Event == null)
                            Waterfall_Event = new AutoResetEvent(true);

                        ScopeLine_vb = new VertexBuffer(waterfall_dx_device, waterfall_W * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
                        ScopeLine_verts = new Vertex[waterfall_W * 2];
                        ScopeLine_vb_monitor = new VertexBuffer(MainForm.waterfall_dx_device, MainForm.picMonitor.Width * 2 * 20,
                            Usage.WriteOnly, VertexFormat.None, Pool.Managed);

                        PanLine_vb = new VertexBuffer(device, panadapterX_data.Length * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
                        PanLine_vb_fill = new VertexBuffer(device, panadapter_W * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
                        PanLine_verts = new Vertex[panadapter_W];
                        PanLine_verts_fill = new Vertex[panadapter_W * 2];

                        return true;
                    }

                    return false;
                }
                catch (Exception ex)
                {
                    Debug.Write("DirectX init general fault!\n" + ex.ToString());
                    return false;
                }
            }
            return false;
        }
Example #57
0
        public static void DirectXRelease()
        {
            try
            {
                if (!MainForm.booting)
                {
                    waterfallX_data = null;
                    panadapterX_data = null;

                    new_display_data = null;
                    new_waterfall_data = null;
                    current_display_data = null;
                    current_waterfall_data = null;
                    waterfall_display_data = null;

                    average_buffer = null;
                    average_waterfall_buffer = null;

                    peak_buffer = null;
                    if (waterfall_bmp != null)
                        waterfall_bmp.Dispose();
                    waterfall_bmp = null;
                    if (Panadapter_Sprite != null)
                        Panadapter_Sprite.Dispose();
                    Panadapter_Sprite = null;
                    if (Waterfall_Sprite != null)
                        Waterfall_Sprite.Dispose();
                    Waterfall_Sprite = null;

                    if (PanadapterTexture != null)
                    {
                        PanadapterTexture.Dispose();
                        PanadapterTexture = null;
                    }

                    if (WaterfallTexture != null)
                    {
                        WaterfallTexture.Dispose();
                        WaterfallTexture = null;
                    }

                    if (Panadapter_Event != null)
                    {
                        Panadapter_Event.Close();
                        Panadapter_Event = null;
                    }

                    if (Waterfall_Event != null)
                    {
                        Waterfall_Event.Close();
                        Waterfall_Event = null;
                    }

                    if (VerLine_vb != null)
                    {
                        VerLine_vb.Dispose();
                        VerLine_vb = null;
                    }

                    if (VerLines_vb != null)
                    {
                        VerLines_vb.Dispose();
                        VerLines_vb = null;
                    }

                    if (HorLine_vb != null)
                    {
                        HorLine_vb.Dispose();
                        HorLine_vb = null;
                    }

                    if (HorLines_vb != null)
                    {
                        HorLines_vb.Dispose();
                        HorLines_vb = null;
                    }

                    if (PanLine_vb != null)
                    {
                        PanLine_vb.Dispose();
                        PanLine_vb.Dispose();
                    }

                    if (PanLine_vb_fill != null)
                    {
                        PanLine_vb_fill.Dispose();
                        PanLine_vb_fill.Dispose();
                    }

                    if (vertical_label != null)
                        vertical_label = null;

                    if (horizontal_label != null)
                        horizontal_label = null;

                    if (device != null)
                    {
                        device.Dispose();
                        device = null;
                    }

                    if (waterfall_dx_device != null)
                    {
                        waterfall_dx_device.Dispose();
                        waterfall_dx_device = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Write("DX release error!" + ex.ToString());
            }
        }
 /// <summary>
 /// Draw a non-filled box from array of coordinates.
 /// </summary>
 /// <param name="array">The byte array.</param>
 /// <param name="startindex">The start index.</param>
 /// <param name="color">The color of the box.</param>
 /// <param name="device">The direct3D device.</param>
 private void DrawQuadFromArray(byte[] array, int startindex, Color color, Device device)
 {
     BoxPoints boxFromArray = GetBoxFromArray(array, startindex);
     DrawQuad(
         boxFromArray.D,
         boxFromArray.A,
         boxFromArray.B,
         boxFromArray.C,
         color,
         device);
 }
 /// <summary>
 /// Draw a quad using lines.
 /// </summary>
 /// <param name="a">Vector A.</param>
 /// <param name="b">Vector B.</param>
 /// <param name="c">Vector C.</param>
 /// <param name="d">Vector D.</param> 
 /// <param name="color">The color of the quad.</param>
 /// <param name="device">The direct3D device.</param>
 private void DrawQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Color color, Device device)
 {
     DrawLine(a, b, color, device);
     DrawLine(b, c, color, device);
     DrawLine(c, d, color, device);
     DrawLine(d, a, color, device);
 }
        /// <summary>
        /// Draw a colored line.
        /// </summary>
        /// <param name="a">Vector A.</param>
        /// <param name="b">Vector B.</param>
        /// <param name="color">The color of the quad.</param>
        /// <param name="device">The direct3D device.</param>
        private void DrawLine(Vector3 a, Vector3 b, Color color, Device device)
        {
            LineVertex[] lineData = new LineVertex[2];

            lineData[0].Position = a;
            lineData[0].Color = color.ToArgb();
            lineData[1].Position = b;
            lineData[1].Color = color.ToArgb();

            device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;
            device.DrawUserPrimitives<LineVertex>(PrimitiveType.LineList, 0, lineData.Length / 2, lineData);
        }