Exemple #1
0
        public static void Initialize(System.Windows.Forms.Form OurForm)
        {
            PresentParameters presentParams = new PresentParameters();
            presentParams.SwapEffect = SwapEffect.Discard;
            Format current = Manager.Adapters[0].CurrentDisplayMode.Format;
            if (Screen.ScreenType == ScreenMode.fullscreen)
            {
                presentParams.Windowed = false;
                presentParams.BackBufferFormat = current;
                presentParams.BackBufferCount = 1;
                presentParams.BackBufferWidth = Screen.ResolutionW;
                presentParams.BackBufferHeight = Screen.ResolutionH;
            }
            else
            {
                presentParams.Windowed = true;
                OurForm.Size = new Size(Screen.ResolutionW, Screen.ResolutionH);
            }
            //presentParams.EnableAutoDepthStencil = true;
            //presentParams.AutoDepthStencilFormat = DepthFormat.D16;

            OurDevice = new Microsoft.DirectX.Direct3D.Device(0, DeviceType.Hardware, OurForm, CreateFlags.SoftwareVertexProcessing, presentParams);
            OurDevice.RenderState.AlphaBlendEnable = true;
            OurDevice.RenderState.SourceBlend = Blend.SourceAlpha;
            OurDevice.RenderState.DestinationBlend = Blend.InvSourceAlpha;
            OurSprite = new Sprite(OurDevice);
            MeshRenderer.Initialize(OurDevice);
            TextRenderer.Initialize(OurDevice);
        }
        private static D3d.Device CreateDevice(System.Windows.Forms.Control renderWindow,
            D3d.PresentParameters presentParams,
            D3d.CreateFlags createFlags,
            Settings deviceSettings)
        {
            try
            {
                D3d.Device d3dDevice = new D3d.Device(deviceSettings.adapterIndex,
                                                        deviceSettings.deviceType,
                                                        renderWindow,
                                                        createFlags,
                                                        presentParams);
                return d3dDevice;
            }
            catch (D3d.DeviceLostException e)
            {
                log.Warning("Unable to create Direct3D device: {0}", e.Message);
            }
            catch (D3d.InvalidCallException e)
            {
                log.Warning("Unable to create Direct3D device: {0}", e.Message);
            }
            catch (D3d.NotAvailableException e)
            {
                log.Warning("Unable to create Direct3D device: {0}", e.Message);
            }
            catch (D3d.OutOfVideoMemoryException e)
            {
                log.Warning("Unable to create Direct3D device: {0}", e.Message);
            }

            return null;
        }
Exemple #3
0
 public xCamera(Microsoft.DirectX.Direct3D.Device d)
     : base("CAMERA")
 {
     m_D3DDevice = d;
     Position(0f, 0f, 0f);
     Target(0f, 0f, 0f);
 }
Exemple #4
0
        public D3DDevice(IntPtr windowPtr, bool bWindowed, long Width, long Height)
        {
            m_bWindowed = bWindowed;
            m_Format = Find16BitMode();

            PresentParameters presentParameters		 = new PresentParameters();
            presentParameters.Windowed				 = m_bWindowed;
            presentParameters.SwapEffect			 = SwapEffect.Discard;
            presentParameters.BackBufferCount		 = 1;
            presentParameters.PresentationInterval	 = PresentInterval.Immediate;
            presentParameters.AutoDepthStencilFormat = DepthFormat.D16;
            presentParameters.EnableAutoDepthStencil = true;

            if(!bWindowed)
            {
                presentParameters.BackBufferFormat	= m_Format;
                presentParameters.BackBufferWidth	= (int)Width;
                presentParameters.BackBufferHeight	= (int)Height;
            }
            else
            {
                presentParameters.BackBufferFormat	= Format.Unknown;
                presentParameters.BackBufferWidth	= (int)Width;
                presentParameters.BackBufferHeight	= (int)Height;
            }

            m_D3DDevice = new Microsoft.DirectX.Direct3D.Device(0,
                DeviceType.Hardware, windowPtr,
                CreateFlags.SoftwareVertexProcessing, presentParameters);
        }
Exemple #5
0
        public void InstalizeDevice()
        {
            PresentParameters presentparams= new PresentParameters();
            presentparams.Windowed = true;
            presentparams.SwapEffect = SwapEffect.Discard;

            device = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentparams);
        }
        /* i_width x i_heightのテクスチャを格納するインスタンスを生成します。
         * 
         */
        public NyARD3dSurface(Microsoft.DirectX.Direct3D.Device i_dev, int i_width, int i_height)
        {
            this.m_ref_dev = i_dev;
            this.m_height = i_height;
            this.m_width = i_width;
            this._surface = i_dev.CreateOffscreenPlainSurface(i_width, i_height, Format.X8R8G8B8, Pool.Default);

            //OK、完成だ。
            return;
        }
Exemple #7
0
        void init()
        {
            Microsoft.DirectX.Direct3D.PresentParameters pps = new Microsoft.DirectX.Direct3D.PresentParameters();
            pps.SwapEffect = Microsoft.DirectX.Direct3D.SwapEffect.Discard;
            pps.Windowed = true;
            pps.BackBufferCount = 1;
            pps.PresentationInterval = PresentInterval.One;
            pps.BackBufferFormat = Format.A8R8G8B8;

            if (GameWindow == null)
            {
                //pps.BackBufferWidth = GameControl.Width;
                //pps.BackBufferHeight = GameControl.Height;
                D3DDev = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, GameControl, Microsoft.DirectX.Direct3D.CreateFlags.SoftwareVertexProcessing, pps);
            }
            else
            {
                //pps.BackBufferWidth = GameWindow.Width;
                //pps.BackBufferHeight = GameWindow.Height;
                D3DDev = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, GameWindow, Microsoft.DirectX.Direct3D.CreateFlags.SoftwareVertexProcessing, pps);
            }
            D3DDev.VertexFormat = CustomVertex.PositionColoredTextured.Format;

            //D3DDev.ShowCursor(false);

            DSoundDev = new Microsoft.DirectX.DirectSound.Device();
            if (GameWindow == null)
            {
                DSoundDev.SetCooperativeLevel(GameControl, Microsoft.DirectX.DirectSound.CooperativeLevel.Normal);
            }
            else
            {
                DSoundDev.SetCooperativeLevel(GameWindow, Microsoft.DirectX.DirectSound.CooperativeLevel.Normal);
            }

            DKeyboardDev = new Microsoft.DirectX.DirectInput.Device(Microsoft.DirectX.DirectInput.SystemGuid.Keyboard);
            DKeyboardDev.Acquire();

            DMouseDev = new Microsoft.DirectX.DirectInput.Device(Microsoft.DirectX.DirectInput.SystemGuid.Mouse);
            DMouseDev.Acquire();

            VertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColoredTextured), 6, D3DDev, Usage.None, CustomVertex.PositionColoredTextured.Format, Pool.Managed);

            D3DDev.SetStreamSource(0, VertexBuffer, 0);
            D3DDev.TextureState[0].AlphaOperation = TextureOperation.Modulate;

            Sprite = new Sprite(D3DDev);

            FontDescription fd = new FontDescription();
            fd.FaceName = "新宋体";
            fd.Height = -12;
            Font2D = new Microsoft.DirectX.Direct3D.Font(D3DDev, fd);

            Font3D = new System.Drawing.Font("新宋体", 12);
        }
        /// <summary>
        /// SceneManager Constructor
        /// </summary>
        /// <param name="d">The device to render the scene</param>
        public xSceneManager(Microsoft.DirectX.Direct3D.Device d)
        {
            m_D3DDevice = d;
            m_xObjects = new ArrayList();

            m_timer = new System.Timers.Timer();
            m_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            m_timer.Enabled = true;
            m_timer.Interval = 1000;
            m_timer.Start();
        }
        /* i_width x i_heightのテクスチャを格納するインスタンスを生成します。
         * 確保されるテクスチャのサイズは指定したサイズと異なり、i_width x i_heightのサイズを超える
         * 2のべき乗サイズになります。
         *
         */
        public NyARD3dTexture(Microsoft.DirectX.Direct3D.Device i_dev, int i_width, int i_height)
        {
            this.m_ref_dev = i_dev;

            this.m_height = i_height;
            this.m_width = i_width;

            //テクスチャサイズの確定
            this.m_texture_height = getSquareSize(i_height);
            this.m_texture_width = getSquareSize(i_width);

            //テクスチャを作るよ!
            this.m_texture = new Texture(this.m_ref_dev, this.m_texture_width, this.m_texture_height, 1, Usage.Dynamic, Format.X8R8G8B8, Pool.Default);
            //OK、完成だ。
            return;
        }
Exemple #10
0
        public Form1()
        {
            //this.Size = new System.Drawing.Size(1280, 1024);
            this.Text = "GalaxySmash";
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
            this.WindowState = FormWindowState.Maximized;

            _presentParams = new PresentParameters();
            _presentParams.Windowed = true;
            _presentParams.SwapEffect = SwapEffect.Discard;

            _device = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, _presentParams);

            _input = new Input();

            _input.Init(this);

               _universalRemote = new UniversalRemote();
               // _universalRemote.Show();
        }
        public SplashButton(System.Windows.Forms.Form frm, 
                            D3D.Device device3D, Point location, Size dimension,
                            string normalFileName, string mouseOverFileName,
                            string mouseDownFileName, string disableFileName)
        {
            device3d = device3D;
            Location = location;
            size = dimension;

            int h = Location.Y + size.Height;
            int w = Location.X + size.Width;
            vertices = new D3D.CustomVertex.TransformedTextured[6];
            vertices[0] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, location.Y, 0f, 1f), 0, 0);
            vertices[1] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, location.Y, 0f, 1f), 1, 0);
            vertices[2] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, h, 0f, 1f), 0, 1);
            vertices[3] = new D3D.CustomVertex.TransformedTextured(new Vector4(location.X, h, 0f, 1f), 0, 1);
            vertices[4] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, location.Y, 0f, 1f), 1, 0);
            vertices[5] = new D3D.CustomVertex.TransformedTextured(new Vector4(w, h, 0f, 1f), 1, 1);
            normalTexture = D3D.TextureLoader.FromFile(device3d, normalFileName);
            mouseOverTexture = D3D.TextureLoader.FromFile(device3d, mouseOverFileName);
            mouseDownTexture = D3D.TextureLoader.FromFile(device3d, mouseDownFileName);
            disableTexture = D3D.TextureLoader.FromFile(device3d, disableFileName);
            Enable = true;
            //
            // set mouse device
            //
            try
            {
                MouseDevice = new DI.Device(DI.SystemGuid.Mouse);
                MouseDevice.SetDataFormat(DI.DeviceDataFormat.Mouse);
                MouseDevice.Acquire();
            }
            catch (DirectXException ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, ex.Source);
            }
            finally
            {
                frm.MouseMove += new System.Windows.Forms.MouseEventHandler(frm_MouseMove);
            }
        }
		/// <summary>
		/// 初始导演类
		/// </summary>
		/// <returns>是否初始化成功</returns>
		public bool Init()
		{
			try
			{
				//预设参数
				PresentParameters pp = new PresentParameters();
				pp.Windowed = true;
				pp.SwapEffect = SwapEffect.Discard;

				//创建设备
				d3dDevice = new Microsoft.DirectX.Direct3D.Device(
					0,
					Microsoft.DirectX.Direct3D.DeviceType.Hardware,
					this,
					CreateFlags.SoftwareVertexProcessing,
					pp
				);

				//input设备
				kbDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
				kbDevice.SetCooperativeLevel(this, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
				kbDevice.Acquire();

				//if (instance != null) return false;
				instance = this;

				//设置每帧时间间隔
				PerFrameTick = 1000.0f / 60;
				
				return true;
			}
			catch (DirectXException e)
			{
				ErrorReport.New(e);
				return false;
			}


		}
Exemple #13
0
        public void InitializeGraphics()
        {
            PresentParameters presentParams = new PresentParameters();
            presentParams.Windowed = true; presentParams.SwapEffect = SwapEffect.Discard;
              //      presentParams.MultiSample = MultiSampleType.FourSamples;
              //      presentParams.MultiSampleQuality = 4;

            presentParams.EnableAutoDepthStencil = true;
            presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            device = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
            device.VertexFormat = CustomVertex.PositionNormalTextured.Format;

            vb = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 36, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default);
            vb.Created += new EventHandler(this.OnVertexBufferCreate);
            OnVertexBufferCreate(vb, null);
            vbhor = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 6, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default);
            OnHorizonVertexBufferCreate(vbhor, null);
            for (int i = 0; i < 50; i++)
                roadCoords.Add(700.0f - 512.0f * i);

            InitializeKeyboard();

            road = new Texture(device, new Bitmap(this.GetType(), @"road2.jpg"), 0, Pool.Managed);
            grass = new Texture(device, new Bitmap(this.GetType(), @"GrassSample.jpg"), 0, Pool.Managed);
            horizon = new Texture(device, new Bitmap(this.GetType(), @"horizon2.bmp"), 0, Pool.Managed);
            LoadMesh(@"..\..\Mesh\cot_dodge.x", car);
            LoadMesh(@"..\..\Mesh\cot_chevy.x", car1);
            LoadMesh(@"..\..\Mesh\cot_toyota.x", car2);
            obstacle1.mesh = Mesh.Box(device, 200, 200, 200);
            obstacle2.mesh = Mesh.Cylinder(device, 100, 100, 200, 30, 30);
            obstacle3.mesh = Mesh.Sphere(device, 100, 30, 30);
            obstacle4.mesh = Mesh.Torus(device, 25, 100, 30, 30);

            car.distanceX = 0.0f;
            device.SamplerState[0].MinFilter = TextureFilter.Anisotropic;
            device.SamplerState[0].MagFilter = TextureFilter.Anisotropic;
            device.SamplerState[0].MaxAnisotropy = 16;
            device.SamplerState[0].SrgbTexture = false;
        }
Exemple #14
0
 protected virtual void RestoreDeviceObjects(object sender, EventArgs e)
 {
     D3D.Device device = (D3D.Device)sender;
 }
Exemple #15
0
        private void InitDirect3D()
        {
            Direct3D.PresentParameters presentParams;
            presentParams = new Direct3D.PresentParameters();

            presentParams.Windowed               = windowed;
            presentParams.EnableAutoDepthStencil = true;
            presentParams.AutoDepthStencilFormat = Direct3D.DepthFormat.D16;

            if(windowed)
            {
                presentParams.SwapEffect = Direct3D.SwapEffect.Copy;
            }
            else
            {
                presentParams.SwapEffect       = Direct3D.SwapEffect.Flip;
                presentParams.BackBufferFormat = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Format;
                presentParams.BackBufferWidth  = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Width;
                presentParams.BackBufferHeight = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Height;
                presentParams.FullScreenRefreshRateInHz = Direct3D.PresentParameters.DefaultPresentRate;
                presentParams.PresentationInterval      = Direct3D.PresentInterval.One;
            }

            device = new Direct3D.Device(0,
                                         Direct3D.DeviceType.Hardware,
                                         this,
                                         Direct3D.CreateFlags.SoftwareVertexProcessing,
                                         presentParams);

            device.DeviceReset += new System.EventHandler(this.OnDeviceReset);

            OnDeviceReset(device, null);
        }
Exemple #16
0
        /// <summary>
        /// Specifies the custom attribute by converting this to a string and passing to GetCustomAttribute()
        /// </summary>
        // public enum CustomAttribute { D3DDEVICE, D3DZBUFFER, D3DBACKBUFFER }

        public void CreateD3DResources()
        {
            // access device via driver
            Device device = driver.Device;

            if (isSwapChain && device == null)
            {
                throw new Exception("Secondary window has not been given the device from the primary!");
            }

            DeviceType devType = DeviceType.Hardware;

            presentParams            = new PresentParameters();
            presentParams.Windowed   = !isFullScreen;
            presentParams.SwapEffect = SwapEffect.Discard;
            // triple buffer if VSync is on
            presentParams.BackBufferCount           = isVSync ? 2 : 1;
            presentParams.EnableAutoDepthStencil    = isDepthBuffered;
            presentParams.DeviceWindow              = windowHandle;
            presentParams.BackBufferWidth           = width;
            presentParams.BackBufferHeight          = height;
            presentParams.FullScreenRefreshRateInHz = isFullScreen ? displayFrequency : 0;

            if (isVSync)
            {
                presentParams.PresentationInterval = PresentInterval.One;
            }
            else
            {
                // NB not using vsync in windowed mode in D3D9 can cause jerking at low
                // frame rates no matter what buffering modes are used (odd - perhaps a
                // timer issue in D3D9 since GL doesn't suffer from this)
                // low is < 200fps in this context
                if (!isFullScreen)
                {
                    log.Debug("Disabling VSync in windowed mode can cause timing issues at lower " +
                              "frame rates, turn VSync on if you observe this problem.");
                }
                presentParams.PresentationInterval = PresentInterval.Immediate;
            }

            presentParams.BackBufferFormat = Format.R5G6B5;
            if (colorDepth > 16)
            {
                presentParams.BackBufferFormat = Format.X8R8G8B8;
            }

            if (colorDepth > 16)
            {
                // Try to create a 32-bit depth, 8-bit stencil
                if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType,
                                                   presentParams.BackBufferFormat,
                                                   Usage.DepthStencil,
                                                   ResourceType.Surface, DepthFormat.D24S8))
                {
                    // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer
                    if (!D3D.Manager.CheckDeviceFormat(driver.AdapterNumber, devType,
                                                       presentParams.BackBufferFormat,
                                                       Usage.DepthStencil,
                                                       ResourceType.Surface, DepthFormat.D32))
                    {
                        // Jeez, what a naff card. Fall back on 16-bit depth buffering
                        presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                    }
                    else
                    {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D32;
                    }
                }
                else
                {
                    // Woohoo!
                    if (D3D.Manager.CheckDepthStencilMatch(driver.AdapterNumber, devType,
                                                           presentParams.BackBufferFormat,
                                                           presentParams.BackBufferFormat,
                                                           DepthFormat.D24S8))
                    {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D24S8;
                    }
                    else
                    {
                        presentParams.AutoDepthStencilFormat = DepthFormat.D24X8;
                    }
                }
            }
            else
            {
                // 16-bit depth, software stencil
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            }

            presentParams.MultiSample        = fsaaType;
            presentParams.MultiSampleQuality = fsaaQuality;

            if (isSwapChain)
            {
                swapChain = new SwapChain(device, presentParams);
                if (swapChain == null)
                {
                    // Try a second time, may fail the first time due to back buffer count,
                    // which will be corrected by the runtime
                    swapChain = new SwapChain(device, presentParams);
                }
                // Store references to buffers for convenience
                renderSurface = swapChain.GetBackBuffer(0, BackBufferType.Mono);
                // Additional swap chains need their own depth buffer
                // to support resizing them
                if (isDepthBuffered)
                {
                    renderZBuffer =
                        device.CreateDepthStencilSurface(width, height,
                                                         presentParams.AutoDepthStencilFormat,
                                                         presentParams.MultiSample,
                                                         presentParams.MultiSampleQuality,
                                                         false);
                }
                else
                {
                    renderZBuffer = null;
                }
                // Ogre releases the mpRenderSurface here (but not the mpRenderZBuffer)
                // release immediately so we don't hog them
                // mpRenderSurface->Release();
                // We'll need the depth buffer for rendering the swap chain
                // //mpRenderZBuffer->Release();
            }
            else
            {
                if (device == null)
                {
#if !USE_D3D_EVENTS
                    // Turn off default event handlers, since Managed DirectX seems confused.
                    Device.IsUsingEventHandlers = false;
#endif

                    // We haven't created the device yet, this must be the first time

                    // Do we want to preserve the FPU mode? Might be useful for scientific apps
                    CreateFlags extraFlags = 0;
                    if (multiThreaded)
                    {
                        extraFlags |= CreateFlags.MultiThreaded;
                    }
                    // TODO: query and preserve the fpu mode

                    // Set default settings (use the one Ogre discovered as a default)
                    int adapterToUse = driver.AdapterNumber;
                    if (useNVPerfHUD)
                    {
                        // Look for 'NVIDIA NVPerfHUD' adapter
                        // If it is present, override default settings
                        foreach (AdapterInformation identifier in D3D.Manager.Adapters)
                        {
                            log.Info("Device found: " + identifier.Information.Description);
                            if (identifier.Information.Description.Contains("PerfHUD"))
                            {
                                log.Info("Attempting to use PerfHUD");
                                adapterToUse = identifier.Adapter;
                                devType      = DeviceType.Reference;
                                break;
                            }
                        }
                    }

                    try
                    {
                        device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                CreateFlags.HardwareVertexProcessing | extraFlags,
                                                presentParams);
                    }
                    catch (Exception) {
                        log.Info("First device creation failed");
                        try
                        {
                            // Try a second time, may fail the first time due to back buffer count,
                            // which will be corrected down to 1 by the runtime
                            device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                    CreateFlags.HardwareVertexProcessing | extraFlags,
                                                    presentParams);
                        }
                        catch (Exception)
                        {
                            try
                            {
                                // Looks like we can't use HardwareVertexProcessing, so try Mixed
                                device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                        CreateFlags.MixedVertexProcessing | extraFlags,
                                                        presentParams);
                            }
                            catch (Exception)
                            {
                                // Ok, one last try. Try software.  If this fails, just throw up.
                                device = new D3D.Device(adapterToUse, devType, windowHandle,
                                                        CreateFlags.SoftwareVertexProcessing | extraFlags,
                                                        presentParams);
                            }
                        }
                    }

                    // TODO: For a full screen app, I'm supposed to do this to prevent alt-tab
                    //       from messing things up.
                    //device.DeviceResizing += new
                    //    System.ComponentModel.CancelEventHandler(this.CancelResize);
                }
                log.InfoFormat("Device constructed with presentation parameters: {0}", presentParams.ToString());

                // update device in driver
                driver.Device = device;
                // Store references to buffers for convenience
                renderSurface = device.GetRenderTarget(0);
                renderZBuffer = device.DepthStencilSurface;
                // Ogre releases these here
                // release immediately so we don't hog them
                // mpRenderSurface->Release();
                // mpRenderZBuffer->Release();
            }
        }
Exemple #17
0
        public override void Update()
        {
            D3D9RenderSystem rs = (D3D9RenderSystem)Root.Instance.RenderSystem;

            // access device through driver
            D3D.Device device = driver.Device;

            if (rs.DeviceLost)
            {
                log.Info("In D3DRenderWindow.Update, rs.DeviceLost is true");
                // Test the cooperative mode first
                int status;
                device.CheckCooperativeLevel(out status);
                if (status == (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceLost)
                {
                    // device lost, and we can't reset
                    // can't do anything about it here, wait until we get
                    // D3DERR_DEVICENOTRESET; rendering calls will silently fail until
                    // then (except Present, but we ignore device lost there too)
                    // FIXME: Ogre doesn't do these two Dispose calls here.
#if NOT
                    // This code is what Ogre does for this clause, but since
                    // Ogre gets to immediately call release on the renderSurface
                    // and renderZBuffer, this assign of null will end up leaving
                    // the reference count at 0 for them, and will cause them to
                    // be freed.  For the Axiom code, I'm just going to leave them
                    // alone, and do the proper dispose calls in the devicenotreset
                    // clause.

                    renderSurface = null;
                    // need to release if swap chain
                    if (!isSwapChain)
                    {
                        renderZBuffer = null;
                    }
                    else
                    {
                        // Do I need to dispose of the ZBuffer here?
                        // SAFE_RELEASE (mpRenderZBuffer);
                        if (renderZBuffer != null)
                        {
                            renderZBuffer.Dispose();
                            renderZBuffer = null;
                        }
                    }
#endif
                    Thread.Sleep(50);
                    return;
                }
                else
                {
                    if (status != (int)Microsoft.DirectX.Direct3D.ResultCode.Success &&
                        status != (int)Microsoft.DirectX.Direct3D.ResultCode.DeviceNotReset)
                    {
                        // I've encountered some unexpected device state
                        // Ogre would just continue, but I want to make sure I notice this.
                        throw new Exception(string.Format("Unknown Device State: {0}", status));
                    }
                    // FIXME: Ogre doesn't do these two Dispose calls here.
                    if (renderSurface != null)
                    {
                        log.Info("Disposing of render surface");
                        renderSurface.Dispose();
                        renderSurface = null;
                    }
                    if (renderZBuffer != null)
                    {
                        log.Info("Disposing of render zbuffer");
                        renderZBuffer.Dispose();
                        renderZBuffer = null;
                    }

                    log.InfoFormat("In D3DRenderWindow.Update, calling rs.RestoreLostDevice(); status = {0}", status);
                    // device lost, and we can reset
                    rs.RestoreLostDevice();

                    // Still lost?
                    if (rs.DeviceLost)
                    {
                        // Wait a while
                        Thread.Sleep(50);
                        return;
                    }

                    if (!isSwapChain)
                    {
                        log.Info("In D3DRenderWindow.Update, re-querying buffers");
                        // re-qeuery buffers
                        renderSurface = device.GetRenderTarget(0);
                        renderZBuffer = device.DepthStencilSurface;
                        // release immediately so we don't hog them
                        // mpRenderSurface->Release();
                        // mpRenderZBuffer->Release();
                    }
                    else
                    {
                        log.Info("In D3DRenderWindow.Update, isSwapChain is true, changing viewport dimensions");
                        // Update dimensions incase changed
                        foreach (Axiom.Core.Viewport vp in viewportList)
                        {
                            vp.UpdateDimensions();
                        }
                        // Actual restoration of surfaces will happen in
                        // D3D9RenderSystem.RestoreLostDevice when it calls
                        // CreateD3DResources for each secondary window
                    }
                }
            }
            base.Update();
        }
 protected override D3D.Texture _GetTexture(D3D.Device device, int index)
 {
     return(D3D.Texture.FromBitmap(device, _GetTextureAsBitmap(index), 0, D3D.Pool.Managed));
 }
Exemple #19
0
 public MeshObject(D3D.Device dev, Stream stream)
 {
     this.FillMesh(dev, stream);
 }
Exemple #20
0
        public bool InitializeGraphics()
        {
            try
            {
                DisplayMode displayMode = Microsoft.DirectX.Direct3D.Manager.Adapters.Default.CurrentDisplayMode;

                PresentParameters presentParams = new PresentParameters();

                presentParams.BackBufferHeight = clientArea.Height;
                presentParams.BackBufferWidth = clientArea.Width;
                presentParams.PresentationInterval = PresentInterval.Immediate;
                presentParams.SwapEffect = SwapEffect.Discard;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;
                presentParams.BackBufferCount = 1;

                if (IsWindowMode)
                {
                    presentParams.Windowed = true;
                    presentParams.BackBufferFormat = displayMode.Format;
                }
                else
                {
                    presentParams.Windowed = false;
                    presentParams.FullScreenRefreshRateInHz = 75;
                    presentParams.BackBufferFormat = Format.A8R8G8B8;
                }

                //  Set our device renderstates
                device = new Microsoft.DirectX.Direct3D.Device(
                    Microsoft.DirectX.Direct3D.Manager.Adapters.Default.Adapter,
                    Microsoft.DirectX.Direct3D.DeviceType.Hardware, this,
                    CreateFlags.HardwareVertexProcessing, presentParams);

                device.RenderState.ZBufferEnable = true;
                device.RenderState.CullMode = Cull.CounterClockwise;
                device.RenderState.DitherEnable = false;
                device.RenderState.SpecularEnable = false;
                device.RenderState.Lighting = true;
                device.RenderState.FillMode = FillMode.Solid;
                device.RenderState.AntiAliasedLineEnable = true;
                device.RenderState.MultiSampleAntiAlias = true;
                device.RenderState.DitherEnable = true;
                device.RenderState.NormalizeNormals = true;
                device.RenderState.SpecularEnable = true;
                device.RenderState.ShadeMode = ShadeMode.Gouraud;

                this.InitializeSprites();

                d3d_scene = new D3DSceneManager();

                device.DeviceReset += new EventHandler(device_DeviceReset);
                this.device_DeviceReset(device, null);

                return true;
            }
            catch (DirectXException dxe)
            {
                MessageBox.Show("Could not initialize Direct3D.  " + dxe.Message + "  This game will exit.");
                Application.Exit();
                return false;
            }
        }
Exemple #21
0
        public override void render(float elapsedTime)
        {
            motionBlurFlag = (bool)GuiController.Instance.Modifiers["motionBlurFlag"];
            TgcTexture texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Pista\\pistaCarreras.png");

            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;


            //pantalla De Inicio
            if (flagInicio == 0)
            {
                //Actualizar valores cargados en modifiers

                /*sprite.Position = (Vector2)GuiController.Instance.Modifiers["position"];
                 * sprite.Scaling = (Vector2)GuiController.Instance.Modifiers["scaling"];
                 * sprite.Rotation = FastMath.ToRad((float)GuiController.Instance.Modifiers["rotation"]);
                 */
                //Iniciar dibujado de todos los Sprites de la escena (en este caso es solo uno)
                GuiController.Instance.Drawer2D.beginDrawSprite();
                sprite.render();
                //Finalizar el dibujado de Sprites
                GuiController.Instance.Drawer2D.endDrawSprite();
                flagInicio = jugador.verSiAprietaSpace();
                textIngreseTeclaSombra.render();
                textIngreseTecla.render();
                musica.verSiCambioMP3();
            }
            else
            {
                //Para contar el tiempo desde que preciona la barra espaciadora y comienza el juego
                if (primerRenderDelJuegoAndando == true)
                {
                    this.horaInicio             = DateTime.Now;
                    primerRenderDelJuegoAndando = false;
                }
                //Todo lo referente a lo que debe hacer el IA
                autoIA.elapsedTime = elapsedTime;
                autoIA.establecerVelocidadMáximaEn((float)GuiController.Instance.Modifiers["velocidadMaxima"] * 1.02f);

                if (colision.getTiempoQueChoco() == 0)
                {
                    jugadorIA.jugar(trayectoDeIA[0].Center, meshAutoIA.Position);
                }

                meshAutoIA.Rotation = new Vector3(0f, autoIA.rotacion, 0f);
                jugadorIA.setRotacion(meshAutoIA.Rotation);

                meshAutoIA.moveOrientedY(-autoIA.velocidad * elapsedTime);
                //Fin movimiento de auto IA

                //Le paso el elapsed time al auto porque sus metodos no deben depender de los FPS
                auto.elapsedTime = elapsedTime;

                //Varío la velocidad Máxima del vehículo con el modifier "velocidadMáxima"
                auto.establecerVelocidadMáximaEn((float)GuiController.Instance.Modifiers["velocidadMaxima"]);

                //El jugador envia mensajes al auto dependiendo de que tecla presiono
                //Se pone un tiempo para que luego de chocar 2 autos, estos no puedan ingresar movimiento (sólo se mueve por inercia)
                if (colision.getTiempoQueChoco() == 0)
                {
                    jugador.jugar(cantidadDeNitro);
                }
                else
                {
                    colision.setTiempoQueChoco(colision.getTiempoQueChoco() - (8 * elapsedTime));
                    if (colision.getTiempoQueChoco() < 0)
                    {
                        colision.setTiempoQueChoco(0);
                    }
                }

                //Transfiero la rotacion del auto abstracto al mesh, y su obb
                autoMesh.Rotation = new Vector3(0f, auto.rotacion, 0f);
                oBBAuto.Center    = autoMesh.Position;
                oBBAuto.setRotation(autoMesh.Rotation);
                meshAutoIA.Rotation = new Vector3(0f, autoIA.rotacion, 0f);
                oBBAutoIa.Center    = meshAutoIA.Position;
                oBBAutoIa.setRotation(meshAutoIA.Rotation);


                //Calculo de giro de la rueda
                rotacionVertical -= auto.velocidad * elapsedTime / 60;

                //Calculo el movimiento del mesh dependiendo de la velocidad del auto
                autoMesh.moveOrientedY(-auto.velocidad * elapsedTime);
                //Detección de colisiones
                //Hubo colisión con un objeto. Guardar resultado y abortar loop.



                //Si hubo alguna colisión, hacer esto:
                if (huboColision(oBBAuto))
                {
                    autoMesh.moveOrientedY(20 * auto.velocidad * elapsedTime); //Lo hago "como que rebote un poco" para no seguir colisionando
                    auto.velocidad = -(auto.velocidad * 0.3f);                 //Lo hago ir atrás un tercio de velocidad de choque
                }
                if (huboColision(oBBAutoIa))
                {
                    meshAutoIA.moveOrientedY(20 * autoIA.velocidad * elapsedTime); //Lo hago "como que rebote un poco" para no seguir colisionando
                    autoIA.velocidad = -(autoIA.velocidad * 0.3f);                 //Lo hago ir atrás un tercio de velocidad de choque
                }

                //Colisión entre los autos
                for (int i = 0; i < 4; i++)
                {
                    float ro, alfa_rueda;
                    float posicion_xA1;
                    float posicion_yA1;
                    float posicion_xA2;
                    float posicion_yA2;

                    ro = FastMath.Sqrt(dx[i] * dxAColision[i] + dyAColision[i] * dyAColision[i]);

                    alfa_rueda = FastMath.Asin(dxAColision[i] / ro);
                    if (i == 0 || i == 2)
                    {
                        alfa_rueda += FastMath.PI;
                    }
                    posicion_xA1 = FastMath.Sin(alfa_rueda + auto.rotacion) * ro;
                    posicion_yA1 = FastMath.Cos(alfa_rueda + auto.rotacion) * ro;

                    posicion_xA2 = FastMath.Sin(alfa_rueda + autoIA.rotacion) * ro;
                    posicion_yA2 = FastMath.Cos(alfa_rueda + autoIA.rotacion) * ro;

                    obbsAuto[i].Position = (new Vector3(posicion_xA1, 15.5f, posicion_yA1) + autoMesh.Position);

                    obbsOtroAuto[i].Position = (new Vector3(posicion_xA2, 15.5f, posicion_yA2) + meshAutoIA.Position);
                }

                colision.colisionEntreAutos(obbsAuto, obbsOtroAuto, jugador, auto, autoIA, autoMesh, meshAutoIA, elapsedTime);

                //Cosas sobre derrape
                int direcGiroDerrape = 0;

                if (auto.velocidad > 1500 && (jugador.estaGirandoDerecha() || jugador.estaGirandoIzquierda()))
                {
                    if (jugador.estaGirandoIzquierda())
                    {
                        direcGiroDerrape = -1;
                    }
                    else if (jugador.estaGirandoDerecha())
                    {
                        direcGiroDerrape = 1;
                    }

                    autoMesh.Rotation = new Vector3(0f, auto.rotacion + (direcGiroDerrape * anguloDerrape), 0f);
                    oBBAuto.setRotation(new Vector3(autoMesh.Rotation.X, autoMesh.Rotation.Y + (direcGiroDerrape * anguloDerrape / 2), autoMesh.Rotation.Z));


                    if (anguloDerrape <= anguloMaximoDeDerrape)
                    {
                        anguloDerrape += velocidadDeDerrape * elapsedTime;
                    }
                }
                else
                {
                    direcGiroDerrape = 0;
                    anguloDerrape    = 0;
                }
                //Fin derrape

                //Posiciono las ruedas
                for (int i = 0; i < 4; i++)
                {
                    float ro, alfa_rueda;
                    float posicion_x;
                    float posicion_y;
                    ro = FastMath.Sqrt(dx[i] * dx[i] + dy[i] * dy[i]);

                    alfa_rueda = FastMath.Asin(dx[i] / ro);
                    if (i == 0 || i == 2)
                    {
                        alfa_rueda += FastMath.PI;
                    }
                    posicion_x = FastMath.Sin(alfa_rueda + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * ro;
                    posicion_y = FastMath.Cos(alfa_rueda + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * ro;

                    ruedas[i].Position = (new Vector3(posicion_x, 15.5f, posicion_y) + autoMesh.Position);
                    //Si no aprieta para los costados, dejo la rueda derecha (por ahora, esto se puede modificar)
                    if (input.keyDown(Key.Left) || input.keyDown(Key.A) || input.keyDown(Key.Right) || input.keyDown(Key.D))
                    {
                        ruedas[i].Rotation = new Vector3(rotacionVertical, auto.rotacion + auto.rotarRueda(i) + (anguloDerrape * direcGiroDerrape), 0f);
                    }
                    else
                    {
                        ruedas[i].Rotation = new Vector3(rotacionVertical, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                    }
                }

                //comienzo humo
                float rohumo, alfa_humo;
                float posicion_xhumo;
                float posicion_yhumo;
                rohumo = FastMath.Sqrt(-19f * -19f + 126f * 126f);

                alfa_humo      = FastMath.Asin(-19f / rohumo);
                posicion_xhumo = FastMath.Sin(alfa_humo + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * rohumo;
                posicion_yhumo = FastMath.Cos(alfa_humo + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * rohumo;

                humo.Position = (new Vector3(posicion_xhumo, 15.5f, posicion_yhumo) + autoMesh.Position);
                //Si no aprieta para los costados, dejo la rueda derecha (por ahora, esto se puede modificar)
                if (input.keyDown(Key.Left) || input.keyDown(Key.A) || input.keyDown(Key.Right) || input.keyDown(Key.D))
                {
                    humo.Rotation = new Vector3(0f, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                }
                else
                {
                    humo.Rotation = new Vector3(0f, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                }
                //fin de humo
                fuego.Position = humo.Position;
                fuego.Rotation = humo.Rotation;
                //fin fuego

                cantidadDeNitro += 0.5f * elapsedTime;
                cantidadDeNitro  = FastMath.Min(cantidadDeNitro, 100f);
                if (auto.nitro)
                {
                    cantidadDeNitro -= 7 * elapsedTime;
                    cantidadDeNitro  = FastMath.Max(cantidadDeNitro, 0f);
                    if (cantidadDeNitro > 1)
                    {
                        humo.Enabled  = false;
                        fuego.Enabled = false;
                    }
                }
                else
                {
                    humo.Enabled  = false;
                    fuego.Enabled = false;
                }
                tiempoHumo   += elapsedTime;
                humo.UVOffset = new Vector2(0.9f, tiempoHumo);
                humo.updateValues();
                fuego.UVOffset = new Vector2(0.9f, tiempoHumo);
                fuego.updateValues();

                if (tiempoHumo > 50f)
                {
                    tiempoHumo = 0f;
                }
                autoMeshPrevX = autoMesh.Position.X;
                autoMeshPrevZ = autoMesh.Position.Z;

                //Lineas de Frenado
                if (jugador.estaFrenandoDeMano())
                {
                    lineaDeFrenado[0].addTrack(new Vector3(ruedaDerechaDelanteraMesh.Position.X, 0, ruedaDerechaDelanteraMesh.Position.Z));
                    lineaDeFrenado[1].addTrack(new Vector3(ruedaDerechaTraseraMesh.Position.X, 0, ruedaDerechaTraseraMesh.Position.Z));
                    lineaDeFrenado[2].addTrack(new Vector3(ruedaIzquierdaDelanteraMesh.Position.X, 0, ruedaIzquierdaDelanteraMesh.Position.Z));
                    lineaDeFrenado[3].addTrack(new Vector3(ruedaIzquierdaTraseraMesh.Position.X, 0, ruedaIzquierdaTraseraMesh.Position.Z));
                }
                if (jugador.dejoDeFrenarDeMano())
                {
                    for (int i = 0; i < lineaDeFrenado.Length; i++)
                    {
                        lineaDeFrenado[i].endTrack();
                    }
                }

                for (int i = 0; i < lineaDeFrenado.Length; i++)
                {
                    lineaDeFrenado[i].render();
                    lineaDeFrenado[i].pasoDelTiempo(elapsedTime);
                }

                //Dibujo el reflejo de la luz en el auto
                reflejo.Render();

                //////Camara///////

                if (jugador.estaMirandoHaciaAtras())
                {
                    GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 200, -500);
                    GuiController.Instance.ThirdPersonCamera.Target    = autoMesh.Position;
                    GuiController.Instance.ThirdPersonCamera.RotationY = auto.rotacion;
                }
                else
                {
                    coheficienteCamara = jugador.verSiCambiaCamara();
                    GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 100 + (coheficienteCamara), 900 - (coheficienteCamara) * 4);
                    GuiController.Instance.ThirdPersonCamera.Target    = autoMesh.Position;
                    GuiController.Instance.ThirdPersonCamera.RotationY = auto.rotacion;
                }

                //La camara no rota exactamente a la par del auto, hay un pequeño retraso
                //GuiController.Instance.ThirdPersonCamera.RotationY += 5 * (auto.rotacion - prevCameraRotation) * elapsedTime;
                //Ajusto la camara a menos de 360 porque voy a necesitar hacer calculos entre angulos
                while (prevCameraRotation > 360)
                {
                    prevCameraRotation -= 360;
                }
                prevCameraRotation = GuiController.Instance.ThirdPersonCamera.RotationY;

                ///////Musica/////////
                jugador.verSiModificaMusica(musica);

                //Dibujar objeto principal
                //Siempre primero hacer todos los cálculos de lógica e input y luego al final dibujar todo (ciclo update-render)
                foreach (TgcMesh mesh in scenePista.Meshes)
                {
                    mesh.Enabled = (TgcCollisionUtils.classifyFrustumAABB(GuiController.Instance.Frustum, mesh.BoundingBox) != TgcCollisionUtils.FrustumResult.OUTSIDE);
                }
                if (motionBlurFlag)
                {
                    motionBlur.update(elapsedTime);
                    motionBlur.motionBlurRender(elapsedTime, HighResolutionTimer.Instance.FramesPerSecond, auto.velocidad, 0);
                }
                else
                {
                    foreach (TgcMesh mesh in scenePista.Meshes)
                    {
                        mesh.Technique = "DefaultTechnique";
                        mesh.render();
                    }
                }

                //Mostrar al auto IA
                meshAutoIA.render();

                //Muestro el punto siguiente
                trayecto[0].render();
                //mostrar el auto manejado por el humano
                autoMesh.render();

                for (int i = 0; i < 4; i++)
                {
                    ruedas[i].render();
                }

                humo.render();
                fuego.render();

                //Colision con puntos de control, tanto de persona como IA
                for (int i = 0; i < trayecto.Count; i++)
                {
                    //Pregunto si colisiona con un punto de control activado. Lo sé, feo.
                    if ((i == 0) && TgcCollisionUtils.testPointCylinder(oBBAuto.Position, trayecto[i].BoundingCylinder))
                    {
                        TgcCylinder cilindroModificado = new TgcCylinder(trayecto[i].Center, 130, 30);

                        if (contadorDeActivacionesDePuntosDeControl != (posicionesPuntosDeControl.Count * 3))
                        {
                            trayecto.RemoveAt(i);
                            trayecto.Add(cilindroModificado);
                            contadorDeActivacionesDePuntosDeControl++;
                            textPuntosDeControlAlcanzados.Text = "Puntos De Control Alcanzados = " + contadorDeActivacionesDePuntosDeControl.ToString();
                            textTiempo.Text = (Convert.ToDouble(textTiempo.Text) + 3).ToString();
                        }
                        else
                        {
                            gano             = true;
                            textGanaste.Text = "Ganaste y obtuviste un puntaje de  " + textTiempo.Text + " puntos";
                            textGanaste.render();
                            auto.estatico();
                            //Para el IA
                            autoIA.estatico();
                        }
                    }
                }
                for (int i = 0; i < trayectoDeIA.Count; i++)
                {
                    //Pregunto si colisiona con un punto de control activado
                    if ((i == 0) && TgcCollisionUtils.testPointCylinder(meshAutoIA.Position, trayectoDeIA[i].BoundingCylinder))
                    {
                        TgcCylinder cilindroModificado = new TgcCylinder(trayectoDeIA[i].Center, 130, 30);

                        if (contadorDeActivacionesDePuntosDeControlDeIA != (posicionesPuntosDeControlDeIA.Count * 3))
                        {
                            trayectoDeIA.RemoveAt(i);
                            trayectoDeIA.Add(cilindroModificado);
                            contadorDeActivacionesDePuntosDeControlDeIA++;
                        }
                        else
                        {
                            gano             = true;
                            textGanaste.Text = "Ganó la máquina :P  ";
                            textGanaste.render();
                            //Para el IA
                            autoIA.estatico();
                            auto.estatico();
                        }
                    }
                }

                textPosicionDelAutoActual.Text = autoMesh.Position.ToString();

                //Renderizar los tres textos

                textoVelocidad.mostrarVelocidad(auto.velocidad / 10).render(); //renderiza la velocidad

                textPuntosDeControlAlcanzados.render();
                textPosicionDelAutoActual.render();

                //Cosas del tiempo
                tiempo.incrementarTiempo(this, elapsedTime, (bool)GuiController.Instance.Modifiers["jugarConTiempo"]);

                //Actualizo y dibujo el relops
                if ((bool)GuiController.Instance.Modifiers["jugarConTiempo"])
                {
                    if ((DateTime.Now.Subtract(this.horaInicio).TotalSeconds) > segundosAuxiliares)
                    {
                        if (Convert.ToDouble(textTiempo.Text) == 0)
                        {
                            textPerdiste.Text = "Perdiste y lograste " + contadorDeActivacionesDePuntosDeControl.ToString() + " puntos de control";
                            textPerdiste.render();
                            auto.estatico();
                            //Para el IA
                            autoIA.estatico();
                        }
                        else if (gano == true)
                        {
                        }
                        else
                        {
                            this.textTiempo.Text = (Convert.ToDouble(textTiempo.Text) - 1).ToString();
                            segundosAuxiliares++;
                        }
                    }
                }
                emisorHumo.update(elapsedTime, GuiController.Instance.CurrentCamera.getLookAt(), auto.rotacion, autoMesh.Position, anguloDerrape, direcGiroDerrape, auto.nitro && (cantidadDeNitro > 1), auto.velocidad);
                emisorHumo.render(GuiController.Instance.CurrentCamera.getPosition());
                textTiempo.render();
                stringTiempo.render();
                contadorDeFrames++;

                hud.render(auto.velocidad, cantidadDeNitro);
            }//cierra el if de que no esta en pantalla inicio
            textFPS.Text = "            FPS: " + HighResolutionTimer.Instance.FramesPerSecond.ToString();
            textFPS.render();
        }
Exemple #22
0
        public override void init()
        {
            hud = new HUD();
            hud.init();
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;
            //Crear Sprite
            sprite         = new TgcSprite();
            sprite.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Inicio\\imagenInicio.jpg");

            //Ubicarlo centrado en la pantalla
            Size screenSize  = GuiController.Instance.Panel3d.Size;
            Size textureSize = sprite.Texture.Size;

            sprite.Position = new Vector2(0, 0);
            sprite.Scaling  = new Vector2((float)screenSize.Width / textureSize.Width, (float)screenSize.Height / textureSize.Height + 0.01f);

            //Texturas para particulas
            texturaHumo  = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Particulas\\Textures\\humo.png");
            texturaFuego = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Particulas\\Textures\\fuego.png");

            Vector3 centerHumo = new Vector3(0, 0, 0);
            Vector3 sizeHumo   = new Vector3(7, 3, 10);

            humo = TgcBox.fromSize(centerHumo, sizeHumo, texturaHumo);
            humo.AlphaBlendEnable = true;
            fuego = TgcBox.fromSize(centerHumo, sizeHumo, texturaFuego);
            fuego.AlphaBlendEnable = true;
            cantidadDeNitro        = 100f;

            // cosas del tiempo
            tiempoTrans        = 100f; //tiempo transcurrido desde el defasaje de rotacion de camara y rotacion del mesh
            segundosAuxiliares = 1;
            //En este ejemplo primero cargamos una escena 3D entera.
            TgcSceneLoader loader = new TgcSceneLoader();

            //Luego cargamos otro modelo aparte que va a hacer el objeto que controlamos con el teclado
            TgcScene scene1 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\autoRojo-TgcScene.xml");
            TgcScene scene2 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\Auto_Rueda_Derecha-TgcScene.xml");
            TgcScene scene3 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\Auto_Rueda_Derecha-TgcScene.xml");
            TgcScene scene4 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\Auto_Rueda_Izquierda-TgcScene.xml");
            TgcScene scene5 = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\Auto_Rueda_Izquierda-TgcScene.xml");

            scenePista = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\pistaentera-TgcScene.xml");
            TgcScene sceneAutoIA = loader.loadSceneFromFile(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\autoVerde-TgcScene.xml");

            //cargo obbs
            objetosColisionables = new List <TgcObb>();

            /*  Esto de aca comentado sirve para cuando se agregan nuevos meshes a pistaentera-TgcScene.xml entonces
             * obtiene su OBB de los AABB de los meshes, esta comentado porque el archivo .xml esta actualizado
             * y aparte detiene mucho su inicio
             * foreach (TgcMesh mesh in scenePista.Meshes)
             * {
             *    if (mesh.Name.Contains("borde") || mesh.Name.Contains("col") || mesh.Name.Contains("Patrullero"))
             *    {
             *        Vector3[] vertices = mesh.getVertexPositions();
             *        objetosColisionables.Add(TgcObb.computeFromPoints(vertices));
             *    }
             * }
             * guardarObbs(objetosColisionables);*/
            objetosColisionables = cargarObbObjetos();
            posteDeSemaforoOBB   = cargarobbParticular(new Vector3(-1193.647f, -649.2448f, 948.8185f), new Vector3(-1147f, 596.6053f, 1051.182f));
            objetosColisionables.Add(posteDeSemaforoOBB);

            //Solo nos interesa el primer modelo de estas escenas
            autoMesh = scene1.Meshes[0];
            ruedaDerechaDelanteraMesh   = scene2.Meshes[0];
            ruedaDerechaTraseraMesh     = scene3.Meshes[0];
            ruedaIzquierdaDelanteraMesh = scene4.Meshes[0];
            ruedaIzquierdaTraseraMesh   = scene5.Meshes[0];

            //creo el mesh del auto de IA
            meshAutoIA = sceneAutoIA.Meshes[0];
            //creo la lista de ruedas
            ruedas = new List <TgcViewer.Utils.TgcSceneLoader.TgcMesh> {
                ruedaDerechaDelanteraMesh, ruedaDerechaTraseraMesh, ruedaIzquierdaDelanteraMesh, ruedaIzquierdaTraseraMesh
            };

            //creo la lineas de frenado
            for (int i = 0; i < 4; i++)
            {
                lineaDeFrenado[i] = new LineaDeFrenado(12, 25, 3, 250, Color.Black);
            }


            //posicion del auto
            autoMesh.Position = new Vector3(-278f, 0f, 281f);

            //posiciones relativas al auto
            dx = new List <float> {
                45, -45, -45, 45
            };
            dy = new List <float> {
                -61, 71, -61, 71
            };

            //posiciones relativas al auto para los box de colision entre autos
            dxAColision = new List <float> {
                20, -20, -20, 20
            };
            dyAColision = new List <float> {
                -35, 45, -35, 45
            };

            //posiciono al autoIA
            meshAutoIA.Position = new Vector3(211f, 0f, 216f);

            //Vamos a utilizar la cámara en 3ra persona para que siga al objeto principal a medida que se mueve
            GuiController.Instance.ThirdPersonCamera.Enable = true;

            GuiController.Instance.ThirdPersonCamera.RotationY = 300;
            GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 200, 500);
            GuiController.Instance.BackgroundColor = Color.Black;// Black;


            //Le asigno su oriented bounding box que me permite rotar la caja de colisiones (no así bounding box)
            oBBAuto   = TgcObb.computeFromAABB(autoMesh.BoundingBox);
            oBBAutoIa = TgcObb.computeFromAABB(meshAutoIA.BoundingBox);

            //creo al auto y al jugador
            auto    = new Auto(110, ruedas);
            jugador = new Jugador(auto);

            //creo al auto del IA y al IA
            autoIA    = new Auto(110, ruedas);
            jugadorIA = new IA(autoIA, new Vector3(0, 0, 0));

            //Inicializo el circuito, tanto para la persona como para la IA
            posicionesPuntosDeControl = new List <Vector3> {
                new Vector3(360, 20, 2634),
                new Vector3(-1040, 20, 5524), new Vector3(-1749, 20, 11113),
                new Vector3(-4484, 20, 14460), new Vector3(-7377, 20, 16890), new Vector3(-12790, 20, 17407),
                new Vector3(-15308, 20, 12649), new Vector3(-15153, 20, 8531), new Vector3(-16068, 20, 7030),
                new Vector3(-16342, 20, 4149), new Vector3(-16222, 20, -1083), new Vector3(-14986, 20, -3020),
                new Vector3(-15734, 20, -8568), new Vector3(-15281, 20, -12097), new Vector3(-12022, 20, -15335),
                new Vector3(-6142, 20, -14446), new Vector3(-4411, 20, -11766), new Vector3(-2016, 20, -8940),
                new Vector3(-1287, 20, -4142), new Vector3(20, 20, -2566)
            };


            posicionesPuntosDeControlDeIA = new List <Vector3> {
                new Vector3(360, 20, 2634),
                new Vector3(-1040, 20, 5524), new Vector3(-1749, 20, 11113),
                new Vector3(-4484, 20, 14460), new Vector3(-7377, 20, 16890), new Vector3(-12790, 20, 17407),
                new Vector3(-15308, 20, 12649), new Vector3(-15153, 20, 8531), new Vector3(-16068, 20, 7030),
                new Vector3(-16342, 20, 4149), new Vector3(-16222, 20, -1083), new Vector3(-14986, 20, -3020),
                new Vector3(-15734, 20, -8568), new Vector3(-15281, 20, -12097), new Vector3(-12022, 20, -15335),
                new Vector3(-6142, 20, -14446), new Vector3(-4411, 20, -11766), new Vector3(-2016, 20, -8940),
                new Vector3(-1287, 20, -4142), new Vector3(20, 20, -2566)
            };

            for (int i = 0; i < posicionesPuntosDeControl.Count; i++)
            {
                TgcCylinder unCilindro = new TgcCylinder(posicionesPuntosDeControl[i], 130, 30);
                trayecto.Add(unCilindro);
                unCilindro = new TgcCylinder(posicionesPuntosDeControlDeIA[i], 130, 30);
                trayectoDeIA.Add(unCilindro);
            }


            //Asigno los obb que me permiten detectar las colisiones entre los autos
            obbsAuto.Add(TgcBox.fromSize(new Vector3(autoMesh.Position.X - 100, 15, autoMesh.Position.Z + 100), new Vector3(65, 65, 65), texturaFuego));
            obbsAuto.Add(TgcBox.fromSize(new Vector3(autoMesh.Position.X - 100, 15, autoMesh.Position.Z - 100), new Vector3(65, 65, 65), texturaHumo));
            obbsAuto.Add(TgcBox.fromSize(new Vector3(autoMesh.Position.X + 100, 15, autoMesh.Position.Z + 100), new Vector3(65, 65, 65), texturaFuego));
            obbsAuto.Add(TgcBox.fromSize(new Vector3(autoMesh.Position.X + 100, 15, autoMesh.Position.Z - 100), new Vector3(65, 65, 65), texturaFuego));

            obbsOtroAuto.Add(TgcBox.fromSize(new Vector3(meshAutoIA.Position.X - 100, 15, meshAutoIA.Position.Z + 100), new Vector3(65, 65, 65), texturaFuego));
            obbsOtroAuto.Add(TgcBox.fromSize(new Vector3(meshAutoIA.Position.X - 100, 15, meshAutoIA.Position.Z - 100), new Vector3(65, 65, 65), texturaHumo));
            obbsOtroAuto.Add(TgcBox.fromSize(new Vector3(meshAutoIA.Position.X + 100, 15, meshAutoIA.Position.Z + 100), new Vector3(65, 65, 65), texturaFuego));
            obbsOtroAuto.Add(TgcBox.fromSize(new Vector3(meshAutoIA.Position.X + 100, 15, meshAutoIA.Position.Z - 100), new Vector3(65, 65, 65), texturaFuego));

            /////////////TEXTOS///////////////////////

            textPuntosDeControlAlcanzados          = new TgcText2d();
            textPuntosDeControlAlcanzados.Position = new Point(0, 50);
            textPuntosDeControlAlcanzados.Text     = "Puntos De Control Alcanzados = ";
            textPuntosDeControlAlcanzados.Color    = Color.White;

            textFPS          = new TgcText2d();
            textFPS.Position = new Point((screenSize.Width / (-2)), 0);
            textFPS.Text     = "FPS: ";
            textFPS.Color    = Color.Yellow;

            textGanaste          = new TgcText2d();
            textGanaste.Position = new Point(0, 200);
            textGanaste.Color    = Color.LightGreen;

            textPerdiste          = new TgcText2d();
            textPerdiste.Position = new Point(0, 200);
            textPerdiste.Text     = "Perdiste y lograste ";
            textPerdiste.Color    = Color.Red;
            textPerdiste.Size     = new Size(900, 700);

            textPosicionDelAutoActual          = new TgcText2d();
            textPosicionDelAutoActual.Text     = "Posicion del auto actual = ";
            textPosicionDelAutoActual.Color    = Color.White;
            textPosicionDelAutoActual.Position = new Point(100, 450);

            this.horaInicio     = DateTime.Now;
            textTiempo          = new TgcText2d();
            textTiempo.Position = new Point(screenSize.Width / 2 - 50, 20);
            textTiempo.Text     = "10";
            textTiempo.changeFont(new System.Drawing.Font("TimesNewRoman", 23, FontStyle.Bold | FontStyle.Bold));
            textTiempo.Color = Color.Red;

            stringTiempo          = new TgcText2d();
            stringTiempo.Position = new Point(screenSize.Width / 2 - 130, 20);
            stringTiempo.Text     = "Tiempo: ";
            stringTiempo.changeFont(new System.Drawing.Font("TimesNewRoman", 23, FontStyle.Bold | FontStyle.Bold));
            stringTiempo.Color = Color.Red;

            textIngreseTecla          = new TgcText2d();
            textIngreseTecla.Text     = " Utilize las flechas o W,A,S,D para moverse. \n Shift o control izquierdo para activar el nitro \n M para cambiar la camara \n TAB mirar para atrás \n Ingrese barra espaciadora para comenzar ";
            textIngreseTecla.Position = new Point(150, 290);
            textIngreseTecla.Align    = TgcText2d.TextAlign.LEFT;
            textIngreseTecla.changeFont(new System.Drawing.Font("TimesNewRoman", 23, FontStyle.Bold | FontStyle.Bold));
            textIngreseTecla.Color = Color.White;

            textIngreseTeclaSombra          = new TgcText2d();
            textIngreseTeclaSombra.Text     = " Utilize las flechas o W,A,S,D para moverse. \n Shift o control izquierdo para activar el nitro \n M para cambiar la camara \n TAB mirar para atrás \n Ingrese barra espaciadora para comenzar ";
            textIngreseTeclaSombra.Position = new Point(149, 288);
            textIngreseTeclaSombra.Align    = TgcText2d.TextAlign.LEFT;
            textIngreseTeclaSombra.changeFont(new System.Drawing.Font("TimesNewRoman", 23, FontStyle.Bold | FontStyle.Bold));
            textIngreseTeclaSombra.Color = Color.Black;

            textoVelocidad.inicializarTextoVelocidad(auto.velocidad);
            ///////////////MODIFIERS//////////////////
            GuiController.Instance.Modifiers.addFloat("velocidadMaxima", 1000, 7000, 1800f);
            GuiController.Instance.Modifiers.addBoolean("jugarConTiempo", "jugar con tiempo:", true);
            GuiController.Instance.Modifiers.addBoolean("motionBlurFlag", "Motion Blur", false);
            //////////////Reflejo de luz en auto////////////////
            reflejo = new ReflejoLuzEnAuto(autoMesh);


            //contador de puntos de control
            contadorDeActivacionesDePuntosDeControl     = 0;
            contadorDeActivacionesDePuntosDeControlDeIA = 0;
            //flag de victoria
            gano = false;

            List <TgcMesh> autoIAList = new List <TgcMesh>();

            autoIAList.Add(meshAutoIA);

            //motionBlur = new MotionBlur(scenePista.Meshes);
            //motionBlur.motionBlurInit(0);
            musica.inicializar();

            motionBlur = new MotionBlur(scenePista.Meshes);
            motionBlur.motionBlurInit(0);

            emisorHumo = new EmisorHumo();
            emisorHumo.crearQuads(20);
        }
Exemple #23
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Initialized)
            {
                return;
            }

            var presentParams = new PresentParameters
            {
                Windowed               = true,
                SwapEffect             = SwapEffect.Discard,
                AutoDepthStencilFormat = DepthFormat.D16,
                EnableAutoDepthStencil = true,
                PresentationInterval   = PresentInterval.One
            };

            var enumerator = Manager.Adapters.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var adapterInfo = enumerator.Current as AdapterInformation;

                var d3dDeviceCaps = Manager.GetDeviceCaps(adapterInfo.Adapter, DeviceType.Hardware);

                var flags = d3dDeviceCaps.DeviceCaps.SupportsHardwareTransformAndLight ?
                            CreateFlags.HardwareVertexProcessing :
                            CreateFlags.SoftwareVertexProcessing;

                Device = new Direct3D.Device(adapterInfo.Adapter, d3dDeviceCaps.DeviceType, this, flags, presentParams);

                if (Device != null)
                {
                    break;
                }
            }

            Device.DeviceReset += new EventHandler(OnResetDevice);
            OnResetDevice(Device, null);

            // TODO: load instances here...

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

            Camera = new RenderCamera(this)
            {
                Speed             = 0.005f,
                Position          = new Vector3(),
                VerticalRadians   = 6.161014f,
                HorizontalRadians = 3.14159f
            };

            Camera.ComputePosition();

            RenderTimer = new Timer
            {
                Interval = 10
            };

            RenderTimer.Tick += OnRender;
            RenderTimer.Start();

            Initialized = true;
        }
Exemple #24
0
 /// <summary>
 /// 初始化场景
 /// </summary>
 public Scene(Microsoft.DirectX.Direct3D.Device device)
 {
     this.d3dDevice = device;
     arrLayer       = new List <Layer>();
 }
Exemple #25
0
        public void viewGrid(Gosub.Direct3d d3d, Microsoft.DirectX.Direct3D.Device dx,
                             occupancygrid grid)
        {
            bool ground_plane_drawn = false;

            mCellMesh = new AutoMesh(d3d, Mesh.Box(dx, 1, 1, 1));

            //show the grid cells
            for (int z = grid.dimension - 1; z >= 0; z--)
            {
                int plane_hits = 0;
                for (int x = 1; x < grid.dimension - 1; x++)
                {
                    for (int y = 1; y < grid.dimension - 1; y++)
                    {
                        if (grid.display_cell[x, y, z])
                        {
                            plane_hits++;
                            occupancyGridCell c = grid.cell[x, y, z];
                            int r = 0;
                            int g = 0;
                            int b = 255;
                            if (c != null)
                            {
                                r = c.colour[0];
                                g = c.colour[1];
                                b = c.colour[2];
                            }

                            dx.Transform.World = Matrix.Translation(-grid.dimension / 2, -grid.dimension / 2, -grid.dimension / 2) //Center model
                                                                                                                                   //* Matrix.Scaling(1, 1, 1) // Make it bigger
                                                                                                                                   //* Matrix.RotationYawPitchRoll(0, 0, 0)
                                                 * Matrix.Translation(grid.dimension - 1 - x, y, z)
                                                 * Matrix.RotationYawPitchRoll(0, tilt, 0);                                        // Then move it where you want

                            dx.Material = GraphicsUtility.InitMaterial(Color.FromArgb(r, g, b));

                            mCellMesh.M.DrawSubset(0);
                        }


                        //for (int z = 0; z < grid.dimension; z++)
                        {
                            if (z == grid.dimension / 2)
                            {
                                if ((x == 1) || (x == grid.dimension - 2) || (y == 1) || (y == grid.dimension - 2))
                                {
                                    dx.Transform.World = Matrix.Translation(-grid.dimension / 2, -grid.dimension / 2, -grid.dimension / 2) //Center model
                                                         * Matrix.Translation(x, y, z)
                                                         * Matrix.RotationYawPitchRoll(0, tilt, 0);                                        // Then move it where you want

                                    dx.Material = GraphicsUtility.InitMaterial(Color.Green);
                                    mCellMesh.M.DrawSubset(0);
                                }
                            }
                        }
                    }
                }

                if ((plane_hits > 30) && (!ground_plane_drawn))
                {
                    ground_plane_drawn = true;
                    for (int x = 1; x < grid.dimension - 1; x++)
                    {
                        for (int y = 1; y < grid.dimension - 1; y++)
                        {
                            if (grid.empty[x, y])
                            {
                                //occupancyGridCell c = grid.cell[x, y, z];
                                int r = 0;
                                int g = 0;
                                int b = 255;

                                dx.Transform.World = Matrix.Translation(-grid.dimension / 2, -grid.dimension / 2, -grid.dimension / 2) //Center model
                                                                                                                                       //* Matrix.Scaling(1, 1, 1) // Make it bigger
                                                                                                                                       //* Matrix.RotationYawPitchRoll(0, 0, 0)
                                                     * Matrix.Translation(grid.dimension - 1 - x, y, z)
                                                     * Matrix.RotationYawPitchRoll(0, tilt, 0);                                        // Then move it where you want

                                dx.Material = GraphicsUtility.InitMaterial(Color.FromArgb(r, g, b));

                                mCellMesh.M.DrawSubset(0);
                            }
                        }
                    }
                }
            }
        }
Exemple #26
0
 /// <summary>
 /// Occurs once after DirectX has been initialized for the first time.
 /// Setup AutoMesh's, AutoVertexBuffer's, and AutoTexture's here.
 /// </summary>
 private void mD3d_DxLoaded(Gosub.Direct3d d3d, Microsoft.DirectX.Direct3D.Device dx)
 {
 }
Exemple #27
0
 protected abstract D3D.Texture _GetTexture(D3D.Device device, int index);
Exemple #28
0
        public Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(bool generateMipmaps, GraphicsDevice graphicsDevice)
        {
            int textureWidth = Width;
            int textureHeight = Height;

#if FRB_MDX


            if (!Math.MathFunctions.IsPowerOfTwo(textureWidth) ||
                !Math.MathFunctions.IsPowerOfTwo(textureHeight))
            {
                if (graphicsDevice.DeviceCaps.TextureCaps.SupportsPower2)
                {
                    textureHeight = Math.MathFunctions.NextPowerOfTwo(textureHeight);
                    textureWidth = Math.MathFunctions.NextPowerOfTwo(textureWidth);
                }
            }

#endif

            if (textureWidth != Width || textureHeight != Height)
            {

                float ratioX = width / (float)textureWidth;
                float ratioY = height / (float)textureHeight;

                if (textureHeight * textureWidth > mStaticData.Length)
                {
                    mStaticData = new Color[textureHeight * textureWidth];
                }
                for (int y = 0; y < textureHeight; y++)
                {
                    for (int x = 0; x < textureWidth; x++)
                    {
                        //try
                        {
                            int sourcePixelX = (int)(x * ratioX);
                            int sourcePixelY = (int)(y * ratioY);

                            // temporary for testing
                            mStaticData[y * textureWidth + x] =
                                mData[((int)(sourcePixelY * Width) + (int)(sourcePixelX))];
                        }
                        //catch
                        //{
                        //    int m = 3;
                        //}
                    }
                }

#if FRB_MDX

                // Even though the texture's bigger, give it a smaller size so that 
                // pixel size stuff works right.
                Microsoft.Xna.Framework.Graphics.Texture2D textureToReturn = ToTexture2D(mStaticData, textureWidth, textureHeight);

                textureToReturn.Width = Width;
                textureToReturn.Height = Height;

                return textureToReturn;
#else
                return ToTexture2D(mStaticData, textureWidth, textureHeight, generateMipmaps, graphicsDevice);
#endif
            }
            else
            {
                return ToTexture2D(mData, textureWidth, textureHeight, generateMipmaps, graphicsDevice);

            }
        }
        protected void RigidBody_Clone(AnimatTools.Framework.DataObject doOriginal, bool bCutData, AnimatTools.Framework.DataObject doRoot)
        {
            RigidBody_DX doOrigBody = (RigidBody_DX) doOriginal;

            m_d3dDevice = doOrigBody.m_d3dDevice;
            m_v3Rotation = new Microsoft.DirectX.Vector3(doOrigBody.m_v3Rotation.X, doOrigBody.m_v3Rotation.Y, doOrigBody.m_v3Rotation.Z);
            m_v3Direction = new Microsoft.DirectX.Vector3(doOrigBody.m_v3Direction.X, doOrigBody.m_v3Direction.Y, doOrigBody.m_v3Direction.Z);

            m_mtxOrientation = Util_DX.CloneMatrix(doOrigBody.m_mtxOrientation);
            m_mtxTranslation = Util_DX.CloneMatrix(doOrigBody.m_mtxTranslation);

            m_d3dMaterial.Ambient = doOrigBody.m_d3dMaterial.Ambient;
            m_d3dMaterial.Diffuse = doOrigBody.m_d3dMaterial.Diffuse;
            m_d3dTransparentMaterial.Ambient = doOrigBody.m_d3dTransparentMaterial.Ambient;
            m_d3dTransparentMaterial.Diffuse = doOrigBody.m_d3dTransparentMaterial.Diffuse;

            m_snXLocalLocation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snXLocalLocation.Clone(this, bCutData, doRoot);
            m_snYLocalLocation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snYLocalLocation.Clone(this, bCutData, doRoot);
            m_snZLocalLocation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snZLocalLocation.Clone(this, bCutData, doRoot);

            m_snXWorldLocation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snXWorldLocation.Clone(this, bCutData, doRoot);
            m_snYWorldLocation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snYWorldLocation.Clone(this, bCutData, doRoot);
            m_snZWorldLocation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snZWorldLocation.Clone(this, bCutData, doRoot);

            m_snXRotation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snXRotation.Clone(this, bCutData, doRoot);
            m_snYRotation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snYRotation.Clone(this, bCutData, doRoot);
            m_snZRotation = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snZRotation.Clone(this, bCutData, doRoot);
        }
        //Get rectangular collision data for eash frame of animation in the texture array
        public CollisionRectAccess(Direct3D.Device ParentDevice, Direct3D.Texture[] ParentTextures, Direct3D.CustomVertex.PositionTextured[] ParentVerticies)
        {
            this.RectangleMatrix = new ArrayList();

            //The alpha color. this is the part that will be transparent.
            // the mask color is not used because the alpha blending replaces
            // the mask color with the alpha color (usually transparent black).
            const uint TRANSPARENT_BLACK = 0x00000000;

            //Holds texture size and pixels
            Direct3D.SurfaceDescription TextureDetails;
            uint[,] TexturePixels;

            //Holds texture width and height in pixels and floats
            int   WidthInPixels, HeightInPixels;
            float WidthInFloats, HeightInFloats;
            float PixelSizeInFloats;

            //Holds a sprite's rect sides in pixels
            int SmallestXPixel, SmallestYPixel, LargestXPixel, LargestYPixel;

            //Holds a rect in floats
            float SmallestXFloat, SmallestYFloat, LargestXFloat, LargestYFloat;

            //for each frame of animation
            for (int f = 0; f < ParentTextures.Length; f++)
            {
                //Get texture dimentions and create an array of its pixels
                TextureDetails = ParentTextures[f].GetLevelDescription(0);
                TexturePixels  = (uint[, ])ParentTextures[f].LockRectangle(typeof(uint), 0, Direct3D.LockFlags.ReadOnly, TextureDetails.Height, TextureDetails.Width);

                //Get size of texture in pixels and floats
                WidthInPixels     = TextureDetails.Width;
                HeightInPixels    = TextureDetails.Height;
                WidthInFloats     = ParentVerticies[2].X - ParentVerticies[3].X;
                HeightInFloats    = ParentVerticies[1].Y - ParentVerticies[3].Y;
                PixelSizeInFloats = ((WidthInFloats / WidthInPixels) + (HeightInFloats / HeightInPixels)) * 0.5f;

                //create default values for the sides
                SmallestXPixel = WidthInPixels;
                SmallestYPixel = HeightInPixels;
                LargestXPixel  = 0;
                LargestYPixel  = 0;

                //Get the largest and smallest points in the texture that contain something
                for (int y = 0; y < HeightInPixels; y++)
                {
                    for (int x = 0; x < WidthInPixels; x++)
                    {
                        if (TexturePixels[y, x] > TRANSPARENT_BLACK)
                        {
                            if (x > LargestXPixel)
                            {
                                LargestXPixel = x;
                            }
                            else if (x < SmallestXPixel)
                            {
                                SmallestXPixel = x;
                            }

                            if (y > LargestYPixel)
                            {
                                LargestYPixel = y;
                            }
                            else if (y < SmallestYPixel)
                            {
                                SmallestYPixel = y;
                            }
                        }
                    }
                }

                //Get proper data if values weren't found
                if (SmallestXPixel > LargestXPixel || SmallestYPixel > LargestYPixel)
                {
                    SmallestXPixel = 0;
                    SmallestYPixel = 0;
                    LargestXPixel  = 0;
                    LargestYPixel  = 0;
                }

                //convert the sides in pixels to the sides in floats
                SmallestXFloat = SmallestXPixel * PixelSizeInFloats;
                SmallestYFloat = SmallestYPixel * PixelSizeInFloats;
                LargestXFloat  = LargestXPixel * PixelSizeInFloats;
                LargestYFloat  = LargestYPixel * PixelSizeInFloats;

                //Convert the sides to start from the center of the sprite
                // instead of the top left corner
                SmallestXFloat = (WidthInFloats * 0.5f) - SmallestXFloat;
                SmallestYFloat = (HeightInFloats * 0.5f) - SmallestYFloat;
                LargestXFloat  = (WidthInFloats * 0.5f) - (WidthInFloats - LargestXFloat);
                LargestYFloat  = (HeightInFloats * 0.5f) - (HeightInFloats - LargestYFloat);

                //record the sides in  floats
                float[] RectangleCollisions = { SmallestXFloat, SmallestYFloat, LargestXFloat, LargestYFloat };
                this.RectangleMatrix.Add(RectangleCollisions);

                ParentTextures[f].UnlockRectangle(0);
            }
        }
 public void OnDeviceReset(object sender, EventArgs e)
 {
     device = sender as Microsoft.DirectX.Direct3D.Device;
 }
Exemple #32
0
 public virtual void Draw(Direct3D.Device graphics)
 {
 }
        private void InitDirect3D()
        {
            Direct3D.PresentParameters presentParams;
            presentParams = new Direct3D.PresentParameters();

            presentParams.Windowed               = windowed;
            presentParams.EnableAutoDepthStencil = true;
            presentParams.AutoDepthStencilFormat = Direct3D.DepthFormat.D16;

            if(windowed)
            {
                presentParams.SwapEffect = Direct3D.SwapEffect.Copy;
            }
            else
            {
                presentParams.SwapEffect       = Direct3D.SwapEffect.Flip;
                presentParams.BackBufferFormat = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Format;
                presentParams.BackBufferWidth  = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Width;
                presentParams.BackBufferHeight = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Height;
                presentParams.FullScreenRefreshRateInHz = Direct3D.PresentParameters.DefaultPresentRate;
                presentParams.PresentationInterval      = Direct3D.PresentInterval.One;
            }

            Direct3D.DeviceType deviceType = Direct3D.DeviceType.Hardware;

            // If the hardware doesn't support shaders, emulate them with the reference rasterizer
            Direct3D.Caps caps = Direct3D.Manager.GetDeviceCaps(0, Direct3D.DeviceType.Hardware);
            if(caps.VertexShaderVersion < new System.Version(1, 1) || caps.PixelShaderVersion < new System.Version(1, 1))
            {
                string msg = "The hardware does not support the required shader version (VS " + caps.VertexShaderVersion.ToString() + " PS " + caps.PixelShaderVersion.ToString() + "). Switching to the Reference Rasterizer.";
                System.Windows.Forms.MessageBox.Show(null,
                                                     msg,
                                                     "Shaders unsupported");
                deviceType = Direct3D.DeviceType.Reference;
            }

            device = new Direct3D.Device(0,
                                         deviceType,
                                         this,
                                         Direct3D.CreateFlags.SoftwareVertexProcessing,
                                         presentParams);

            device.DeviceReset += new System.EventHandler(this.OnDeviceReset);

            Direct3D.ShaderFlags shaderFlags = Direct3D.ShaderFlags.None;
            #if (DEBUG)
            shaderFlags |= Direct3D.ShaderFlags.Debug;
            #endif

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream stream;

            Direct3D.GraphicsStream gs;
            stream = assembly.GetManifestResourceStream("_6_ShaderAsm.VertexShader.vsh");
            gs = Direct3D.ShaderLoader.FromStream(stream, null, shaderFlags);
            vertexShader = new Direct3D.VertexShader(device, gs);
            gs.Close();
            stream.Close();

            stream = assembly.GetManifestResourceStream("_6_ShaderAsm.PixelShader.psh");
            gs = Direct3D.ShaderLoader.FromStream(stream, null, shaderFlags);
            pixelShader = new Direct3D.PixelShader(device, gs);
            gs.Close();
            stream.Close();

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

            OnDeviceReset(device, null);
        }
Exemple #34
0
        public static AGT_SpriteManager Load(string library_path, List <string> images, System.Windows.Forms.Control dialog, Microsoft.DirectX.Direct3D.Device VideoDevice)
        {
            try
            {
                List <string>     names          = new List <string>();
                AGT_SpriteManager sprite_manager = new AGT_SpriteManager(VideoDevice);

                Assembly image_lib = Assembly.LoadFile(library_path);

                StreamReader s = new StreamReader(image_lib.GetManifestResourceStream("ImageLibrary.mf"));

                while (!s.EndOfStream)
                {
                    names.Add(s.ReadLine());
                }
                s.Close();

                for (int i = 0; i < names.Count; i++)
                {
                    if (images.Contains(names[i]))
                    {
                        string[] texture_name = names[i].Split(':');
                        if (dialog is AGT_SceneLoadDialog)
                        {
                            ((AGT_SceneLoadDialog)dialog).UpdateStatusBar(string.Format("Loading {0} ...", texture_name[0]), i + 1, names.Count);
                        }
                        if (dialog is AGT_SplashDialog)
                        {
                            ((AGT_SplashDialog)dialog).UpdateStatusBar(string.Format("Loading {0} ...", texture_name[0]), i + 1, names.Count);
                        }
                        using (Bitmap b = new Bitmap(image_lib.GetManifestResourceStream(texture_name[0])))
                        {
                            AGT_SpriteId id = sprite_manager.AddResource(texture_name[0], b, 0, 0, 0, bool.Parse(texture_name[1]));
                            sprite_manager.SetCenter(id, (float)(b.Width * .5f), (float)(b.Height * .5f), 0f);
                        }
                    }
                }

                return(sprite_manager);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.StackTrace, e.Message);
            }
            return(null);
        }
Exemple #35
0
 public void OnResetDevice(object sender, EventArgs e)
 {
     D3D.Device device = (D3D.Device)sender;
 }
Exemple #36
0
    /// <summary>
    /// Initialize the device objects
    /// </summary>
    /// <param name="dev">The grpahics device used to initialize</param>
    public void InitializeDeviceObjects(Device dev)
    {
        if (dev != null)
        {
            // Set up our events
            dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }

        // Keep a local copy of the device
        device        = dev;
        textureState0 = device.TextureState[0];
        textureState1 = device.TextureState[1];
        samplerState0 = device.SamplerState[0];
        renderState   = device.RenderState;

        // Create a bitmap on which to measure the alphabet
        Bitmap   bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g   = Graphics.FromImage(bmp);

        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;

        // Establish the font and texture size
        textureScale = 1.0f;          // Draw fonts into texture without scaling

        // Calculate the dimensions for the smallest power-of-two texture which
        // can hold all the printable characters
        textureWidth = textureHeight = 128;
        for (;;)
        {
            try {
                // Measure the alphabet
                PaintAlphabet(g, true);
            }
            catch (System.InvalidOperationException) {
                // Scale up the texture size and try again
                textureWidth  *= 2;
                textureHeight *= 2;
                continue;
            }

            break;
        }

        // If requested texture is too big, use a smaller texture and smaller font,
        // and scale up when rendering.
        Direct3D.Caps d3dCaps = device.DeviceCaps;

        // If the needed texture is too large for the video card...
        if (textureWidth > d3dCaps.MaxTextureWidth)
        {
            // Scale the font size down to fit on the largest possible texture
            textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
            textureWidth = textureHeight = d3dCaps.MaxTextureWidth;

            for (;;)
            {
                // Create a new, smaller font
                ourFontHeight = (int)Math.Floor(ourFontHeight * textureScale);
                systemFont    = new System.Drawing.Font(systemFont.Name, ourFontHeight, systemFont.Style);

                try {
                    // Measure the alphabet
                    PaintAlphabet(g, true);
                }
                catch (System.InvalidOperationException) {
                    // If that still doesn't fit, scale down again and continue
                    textureScale *= 0.9F;
                    continue;
                }

                break;
            }
        }

        // Release the bitmap used for measuring and create one for drawing
        bmp.Dispose();
        bmp                 = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        g                   = Graphics.FromImage(bmp);
        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;

        // Draw the alphabet
        PaintAlphabet(g, false);

        // Create a new texture for the font from the bitmap we just created
        fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
        RestoreDeviceObjects(null, null);
    }
Exemple #37
0
        /// <summary>
        ///     Saves the window contents to a stream.
        /// </summary>
        /// <param name="stream">Stream to write the window contents to.</param>
        public override void Save(Stream stream, PixelFormat requestedFormat)
        {
            D3D.Device  device = driver.Device;
            DisplayMode mode   = device.DisplayMode;

            SurfaceDescription desc = new SurfaceDescription();

            desc.Width  = mode.Width;
            desc.Height = mode.Height;
            desc.Format = Format.A8R8G8B8;

            // create a temp surface which will hold the screen image
            Surface surface = device.CreateOffscreenPlainSurface(
                mode.Width, mode.Height, Format.A8R8G8B8, Pool.SystemMemory);

            // get the entire front buffer.  This is SLOW!!
            device.GetFrontBufferData(0, surface);

            // if not fullscreen, the front buffer contains the entire desktop image.  we need to grab only the portion
            // that contains our render window
            if (!IsFullScreen)
            {
                // whatever our target control is, we need to walk up the chain and find the parent form
                Form form = windowHandle.FindForm();

                // get the actual screen location of the form
                System.Drawing.Rectangle rect = form.RectangleToScreen(form.ClientRectangle);

                desc.Width  = width;
                desc.Height = height;
                desc.Format = Format.A8R8G8B8;

                // create a temp surface that is sized the same as our target control
                Surface tmpSurface = device.CreateOffscreenPlainSurface(rect.Width, rect.Height, Format.A8R8G8B8, Pool.Default);

                // copy the data from the front buffer to the window sized surface
                device.UpdateSurface(surface, rect, tmpSurface);

                // dispose of the prior surface
                surface.Dispose();

                surface = tmpSurface;
            }

            int pitch;

            // lock the surface to grab the data
            GraphicsStream graphStream = surface.LockRectangle(LockFlags.ReadOnly | LockFlags.NoSystemLock, out pitch);

            // create an RGB buffer
            byte[] buffer = new byte[width * height * 3];

            int offset = 0, line = 0, count = 0;

            // gotta copy that data manually since it is in another format (sheesh!)
            unsafe {
                byte *data = (byte *)graphStream.InternalData;

                for (int y = 0; y < desc.Height; y++)
                {
                    line = y * pitch;

                    for (int x = 0; x < desc.Width; x++)
                    {
                        offset = x * 4;

                        int pixel = line + offset;

                        // Actual format is BRGA for some reason
                        buffer[count++] = data[pixel + 2];
                        buffer[count++] = data[pixel + 1];
                        buffer[count++] = data[pixel + 0];
                    }
                }
            }

            surface.UnlockRectangle();

            // dispose of the surface
            surface.Dispose();

            // gotta flip the image real fast
            Image image = Image.FromDynamicImage(buffer, width, height, PixelFormat.R8G8B8);

            image.FlipAroundX();

            // write the data to the stream provided
            stream.Write(image.Data, 0, image.Data.Length);
        }
 public PollAccess(Direct3D.Device ParentDevice, string TextureLocation, float NewX, float NewY, float NewZ, int NewWidth, int NewHeight, int NewSheetWidth, int NewSheetHeight, Color NewMaskColor, uint CollisionRectWidth, uint CollisionRectHeight, PollType NewTypeOfPoll)
     : base(ParentDevice, TextureLocation, NewX, NewY, NewZ, NewWidth, NewHeight, NewSheetWidth, NewSheetHeight, NewMaskColor, CollisionRectWidth, CollisionRectHeight)
 {
     this.TypeOfPoll = NewTypeOfPoll;
 }
        public bool InitMdx()
        {
            Dev = new Device(MdxRender.DeviceInfo.default_adapter, DeviceType.Hardware,
                             MdxRender.DeviceInfo.renderWin, MdxRender.DeviceInfo.flags, MdxRender.DeviceInfo.pp);

            MdxRender.SM    = new ShaderManager();
            MdxRender.MM    = new ModelManager();
            MdxRender.Input = new InputManager();
            SelectTool.InitializeHandleModel();
            SelectionBox.Initialize();
            ProjectManager.MapSpawns.InitDebug();
            ShaderBase.InitializeDebug();
            mapViewButton = new RenderButton();
            //mapViewButton.Width = MdxRender.DeviceInfo.renderWin.Width;
            //mapViewButton.Height = MdxRender.DeviceInfo.renderWin.Height;
            mapViewButton.Initialize(35, 35, 15, 40);

            //set up lights that don't work
            SetupLights();

            whiteMaterial         = new Material();
            whiteMaterial.Ambient = Color.White;
            whiteMaterial.Diffuse = Color.White;
            //whiteMaterial.Emissive = Color.White;

            //Set up texture filtering to get rid of blocky uglies
            MdxRender.Dev.SamplerState[0].MagFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[0].MinFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[0].MipFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[1].MagFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[1].MinFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[1].MipFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[2].MagFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[2].MinFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[2].MipFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[3].MagFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[3].MinFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[3].MipFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[4].MagFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[4].MinFilter = TextureFilter.Linear;
            MdxRender.Dev.SamplerState[4].MipFilter = TextureFilter.Linear;

            MdxRender.Dev.RenderState.AlphaFunction = Compare.GreaterEqual;
            MdxRender.Dev.SetRenderState(RenderStates.ReferenceAlpha, 0x80);
            //UpdateGammaCorrection();

            //disable vsync, might get some tearing
            MdxRender.Dev.PresentationParameters.PresentationInterval = PresentInterval.Immediate;

            MdxRender.lightmapDebugger          = new GrenLightmapDebug();
            MdxRender.Dev.RenderState.PointSize = 10.0f;

            MdxRender.Dev.RenderState.CullMode      = Cull.CounterClockwise;
            MdxRender.Dev.RenderState.ZBufferEnable = true;
            MdxRender.Dev.DeviceResizing           += new System.ComponentModel.CancelEventHandler(device_DeviceResizing);
            MdxRender.Dev.DeviceReset += new EventHandler(device_DeviceReset);

            //Device.IsUsingEventHandlers = false;

            // Initialize the font
            m_fontFPS  = new D3D.Font(Dev, new Font("Arial", 12, FontStyle.Bold));
            consoleFPS = new D3D.Font(Dev, new Font("Arial", 10, FontStyle.Bold));

            // Initialize the camera placement and orientation
            Camera = new Camera();
            Camera.SetLookAt(new Vector3(-18, 0, 0), new Vector3());

            PreviewManager.Debug_LoadTestMesh();
            m_ready = true;

            return(false);
        }
        public BackgroundAccess(Direct3D.Device NewParentDevice)
        {
            float PlatformWidthInFloats = SpaceAndTime.LengthFrom2DTo3D(64.0f);
            float CurrColmn             = 2.0f;

            this.Platforms = new ArrayList();
            SpriteAccess TemplatePlatform = new SpriteAccess(NewParentDevice, GameConfig.Files.Platform, 2.0f - (-1 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -1.4f, SpaceAndTime.SpriteZLocation, 64, 64, 64, 64, Color.FromArgb(0x00, 0x00, 0xFF, 0x00), 0, 0);

            this.Platforms.Add(TemplatePlatform);
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -1.4f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (1 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -1.4f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (6 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -1.4f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (7 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -1.4f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (8 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -1.4f, SpaceAndTime.SpriteZLocation));

            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (-1 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (1 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (2.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (3.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (4.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (6 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (8 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), -.1f, SpaceAndTime.SpriteZLocation));

            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (-.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (0.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (1.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (3.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (5.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (6.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));
            this.Platforms.Add(new SpriteAccess(TemplatePlatform, 2.0f - (7.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), 1.2f, SpaceAndTime.SpriteZLocation));

            //Set location of platforms
            foreach (SpriteAccess CurrPlatform in this.Platforms)
            {
                CurrPlatform.Location = GameConfig.Locations.Platforms;
            }

            //polls
            float        CurrPollY  = 0.46f;
            SpriteAccess PollTop    = new SpriteAccess(NewParentDevice, GameConfig.Files.PollTop, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, 64, 64, 64, 64, Color.FromArgb(0x00, 0x00, 0xFF, 0x00), 0, 0);
            SpriteAccess PollCenter = new SpriteAccess(NewParentDevice, GameConfig.Files.PollCenter, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, 64, 64, 64, 64, Color.FromArgb(0x00, 0x00, 0xFF, 0x00), 0, 0);
            SpriteAccess PollBottom = new SpriteAccess(NewParentDevice, GameConfig.Files.PollBottom, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, 64, 64, 64, 64, Color.FromArgb(0x00, 0x00, 0xFF, 0x00), 0, 0);

            this.Polls = new ArrayList();
            this.Polls.Add(new PollAccess(PollTop, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Top));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, CurrColmn, CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollBottom, 2.0f - (0 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Bottom));

            CurrPollY = 0.46f;
            this.Polls.Add(new PollAccess(PollTop, 2.0f - (7 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Top));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (7 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (7 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollBottom, 2.0f - (7 * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Bottom));

            CurrPollY = 1.76f;
            this.Polls.Add(new PollAccess(PollTop, 2.0f - (2.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Top));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (2.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (2.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollBottom, 2.0f - (2.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Bottom));

            CurrPollY = 1.76f;
            this.Polls.Add(new PollAccess(PollTop, 2.0f - (4.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Top));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (4.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollCenter, 2.0f - (4.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Center));

            CurrPollY -= PlatformWidthInFloats;
            this.Polls.Add(new PollAccess(PollBottom, 2.0f - (4.5f * SpaceAndTime.LengthFrom2DTo3D(64.0f)), CurrPollY, SpaceAndTime.SpriteZLocation, PollType.Bottom));

            //Set location of polls
            foreach (SpriteAccess CurrPoll in this.Polls)
            {
                CurrPoll.Location = GameConfig.Locations.Polls;
            }

            Direct3D.Device ParentDevice = NewParentDevice;
        }
 public bool InitializeGraphics()
 {
     try
     {
         presentParams.Windowed=true; // We don't want to run fullscreen
         presentParams.SwapEffect = SwapEffect.Discard; // Discard the frames
         presentParams.EnableAutoDepthStencil = true; // Turn on a Depth stencil
         presentParams.AutoDepthStencilFormat = DepthFormat.D16; // And the stencil format
         device = new Direct3D.Device(0, DeviceType.Hardware,
             this.BuildPanel, CreateFlags.SoftwareVertexProcessing, presentParams); //Create a device
         device.DeviceReset += new System.EventHandler(this.OnResetDevice);
         this.OnCreateDevice(device, null);
         this.OnResetDevice(device, null);
         pause = false;
         return true;
     }
     catch (DirectXException)
     {
         // Catch any errors and return a failure
         return false;
     }
 }
Exemple #42
0
        /// <summary>
        /// Initializes the Managed Direct3D Wrapper.
        /// </summary>
        /// <param name="renderWindow">Window to render to.</param>
        /// <param name="screenWidth">Width of the screen in pixels.</param>
        /// <param name="screenHeight">Height of the screen in pixels.</param>
        /// <param name="isWindowed">Is the application windowed or not (!!ALWAYS PASS true FOR NOW!!).</param>
        /// <param name="vsync">Should the renderer wait for a vsync before drawing?</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool InitManagedDirect3D(System.Windows.Forms.Control renderWindow, int screenWidth, int screenHeight, bool isWindowed, bool vsync)
        {
            try
            {
                // Now  setup our D3D present parameters
                presentParams = new PresentParameters();
                presentParams.BackBufferWidth           = screenWidth;
                presentParams.BackBufferHeight          = screenHeight;
                presentParams.BackBufferFormat          = (isWindowed) ? Format.Unknown : Format.R5G6B5;
                presentParams.BackBufferCount           = 1;
                presentParams.MultiSample               = MultiSampleType.None;
                presentParams.MultiSampleQuality        = 0;
                presentParams.SwapEffect                = SwapEffect.Copy;// Discard;
                presentParams.DeviceWindow              = renderWindow;
                presentParams.Windowed                  = isWindowed;
                presentParams.EnableAutoDepthStencil    = false;
                presentParams.FullScreenRefreshRateInHz = 0;
                presentParams.PresentationInterval      = (vsync) ? PresentInterval.Default : PresentInterval.Immediate;

                device = new Device(0, DeviceType.Hardware, renderWindow,
                                    CreateFlags.HardwareVertexProcessing, presentParams);
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create D3D Device", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            try
            {
                sprite = new Microsoft.DirectX.Direct3D.Sprite(device);
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Sprite object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            try
            {
                line = new Microsoft.DirectX.Direct3D.Line(device);

                line.Antialias = true;
                line.Width     = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Line Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            try
            {
                fontDescription.FaceName = "arial";
                fontDescription.Quality  = FontQuality.Default;
                fontDescription.Weight   = FontWeight.Bold;

                font = new Microsoft.DirectX.Direct3D.Font(device, fontDescription);

                line.Antialias = true;
                line.Width     = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the font Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            return(true);
        }
Exemple #43
0
        private void InitDirect3D()
        {
            Direct3D.PresentParameters presentParams;
            presentParams = new Direct3D.PresentParameters();

            presentParams.Windowed = windowed;
            if(windowed)
            {
                presentParams.SwapEffect = Direct3D.SwapEffect.Copy;
            }
            else
            {
                presentParams.SwapEffect       = Direct3D.SwapEffect.Flip;
                presentParams.BackBufferFormat = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Format;
                presentParams.BackBufferWidth  = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Width;
                presentParams.BackBufferHeight = Direct3D.Manager.Adapters.Default.CurrentDisplayMode.Height;
                presentParams.FullScreenRefreshRateInHz = Direct3D.PresentParameters.DefaultPresentRate;
                presentParams.PresentationInterval      = Direct3D.PresentInterval.One;
            }

            device = new Direct3D.Device(0,
                                         Direct3D.DeviceType.Hardware,
                                         this,
                                         Direct3D.CreateFlags.SoftwareVertexProcessing,
                                         presentParams);
        }
    /// <summary>
    /// Initialize the device objects
    /// </summary>
    /// <param name="dev">The grpahics device used to initialize</param>
    public void InitializeDeviceObjects(Device dev)
    {
        if (dev != null) {
            // Set up our events
            dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }

        // Keep a local copy of the device
        device = dev;
        textureState0 = device.TextureState[0];
        textureState1 = device.TextureState[1];
        samplerState0 = device.SamplerState[0];
        renderState = device.RenderState;

        // Create a bitmap on which to measure the alphabet
        Bitmap bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(bmp);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast = 0;

        // Establish the font and texture size
        textureScale  = 1.0f; // Draw fonts into texture without scaling

        // Calculate the dimensions for the smallest power-of-two texture which
        // can hold all the printable characters
        textureWidth = textureHeight = 128;
        for (;;) {
            try {
                // Measure the alphabet
                PaintAlphabet(g, true);
            }
            catch (System.InvalidOperationException) {
                // Scale up the texture size and try again
                textureWidth *= 2;
                textureHeight *= 2;
                continue;
            }

            break;
        }

        // If requested texture is too big, use a smaller texture and smaller font,
        // and scale up when rendering.
        Direct3D.Caps d3dCaps = device.DeviceCaps;

        // If the needed texture is too large for the video card...
        if (textureWidth > d3dCaps.MaxTextureWidth) {
            // Scale the font size down to fit on the largest possible texture
            textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
            textureWidth = textureHeight = d3dCaps.MaxTextureWidth;

            for(;;) {
                // Create a new, smaller font
                ourFontHeight = (int) Math.Floor(ourFontHeight * textureScale);
                systemFont = new System.Drawing.Font(systemFont.Name, ourFontHeight, systemFont.Style);

                try {
                    // Measure the alphabet
                    PaintAlphabet(g, true);
                }
                catch (System.InvalidOperationException) {
                    // If that still doesn't fit, scale down again and continue
                    textureScale *= 0.9F;
                    continue;
                }

                break;
            }
        }

        // Release the bitmap used for measuring and create one for drawing
        bmp.Dispose();
        bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        g = Graphics.FromImage(bmp);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast = 0;

        // Draw the alphabet
        PaintAlphabet(g, false);

        // Create a new texture for the font from the bitmap we just created
        fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
        RestoreDeviceObjects(null, null);
    }
Exemple #45
0
        internal static Microsoft.Xna.Framework.Graphics.Texture2D ToTexture2D(Color[] pixelData, int textureWidth, int textureHeight, bool generateMipmaps, GraphicsDevice graphicsDevice)
        {
#if FRB_XNA
            // Justin Johnson - May 18, 2012 - Added XNA support for mipmap creation on generated textures
            int mipLevelWidth;
            int mipLevelHeight;
            int mipTotalPixels;
            int mipYCoordinate;
            int mipXCoordinate;
            int sourceXCoordinate;
            int sourceYCoordinate;
            int sourcePixelIndex;
            Color[] mipLevelData;
#if XNA4
            Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight, generateMipmaps, SurfaceFormat.Color);
#else
            // Victor Chelaru
            // May 22, 2011
            // Not sure what the
            // additional arguments
            // should be here, but the
            // code wasn't compiling with
            // the code as written for XNA4.
            // So I removed soem of the args to
            // make it compile - we probably don't 
            // care as much for XNA 3.1 since 4.0 is 
            // the newest.
            Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight);
#endif
            // creates texture for each mipmap level (level count defined automatically)
            if (generateMipmaps)
            {
                for (int i = 0; i < texture.LevelCount; i++)
                {
                    if (i == 0)
                    {
                        mipLevelData = pixelData;
                    }
                    else
                    {
                        // Scale previous texture to 50% size
                        // Since mipmaps are usually blended, interpolation is not necessary: point sampling only for speed
                        mipLevelWidth = textureWidth / 2;
                        mipLevelWidth = System.Math.Max(mipLevelWidth, 1);

                        mipLevelHeight = textureHeight / 2;
                        mipLevelHeight = System.Math.Max(mipLevelHeight, 1);

                        mipTotalPixels = mipLevelWidth * mipLevelHeight;
                        mipLevelData = new Color[mipTotalPixels];

                        for (int mipPixelIndex = 0; mipPixelIndex < mipTotalPixels; mipPixelIndex++)
                        {
                            mipYCoordinate = (int)System.Math.Floor(mipPixelIndex / (double)mipLevelWidth);
                            mipXCoordinate = mipPixelIndex - (mipYCoordinate * mipLevelWidth);
                            sourceYCoordinate = mipYCoordinate * 2;
                            sourceXCoordinate = mipXCoordinate * 2;
                            sourcePixelIndex = System.Math.Min(sourceYCoordinate * textureWidth + sourceXCoordinate, pixelData.Length - 1);
                            mipLevelData[mipPixelIndex] = pixelData[sourcePixelIndex];
                        }

                        pixelData = mipLevelData;
                        textureWidth = mipLevelWidth;
                        textureHeight = mipLevelHeight;
                    }
#if (XNA4) || WINDOWS_8
                    texture.SetData<Color>(i, null, mipLevelData, 0, mipLevelData.Length);
#else
                    texture.SetData<Color>(i, null, mipLevelData, 0, mipLevelData.Length, SetDataOptions.Discard);
#endif
                }
            }
            else
            {
                texture.SetData<Color>(pixelData);
            }

#elif FRB_MDX
            // Justin Johnson - May 18, 2012 - I did not change this at all when I updated this method
            if (textureHeight > FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureHeight ||
                textureWidth > FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureWidth)
            {
                throw new InvalidOperationException("The resolution of the to-be-created Texture2D " +
                    "is too large.  The desired resolution is " + textureWidth + " by " + textureHeight + "." +
                    "The largest supported resolution is " +
                    FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureWidth + " by " +
                    FlatRedBallServices.GraphicsDevice.DeviceCaps.MaxTextureHeight + ".");
            }

            Microsoft.Xna.Framework.Graphics.Texture2D texture = new Microsoft.Xna.Framework.Graphics.Texture2D();
            texture.texture = new Microsoft.DirectX.Direct3D.Texture(
                FlatRedBallServices.GraphicsDevice,
                textureWidth,
                textureHeight,
                0,
                0,
                Microsoft.DirectX.Direct3D.Format.A8R8G8B8,
                Microsoft.DirectX.Direct3D.Pool.Managed);


            texture.Width = textureWidth;
            texture.Height = textureHeight;


            uint[,] textureData = (uint[,])texture.texture.LockRectangle(
                typeof(uint),
                0,
                Microsoft.DirectX.Direct3D.LockFlags.None,
                textureWidth, textureHeight);


            int pixelY = 0;
            for (int pixelX = 0; pixelX < textureWidth; pixelX++)
            {
                for (pixelY = 0; pixelY < textureHeight; pixelY++)
                {
                    // Vic says:  I used to have the mData line say:
                    // mData[pixelY * width + pixelX]... but that didn't
                    // work I inverted it and it works fine now.  Not sure 
                    // why, but this works so oh well.
                    textureData[pixelX, pixelY] = (uint)
                        pixelData[pixelX * textureHeight + pixelY].ToArgb();
                }
            }

            texture.texture.UnlockRectangle(0);
#else
            // Justin Johnson - May 18, 2012 - not sure if any other devices support mipmapping and to what level. Fall back to no mipmaps
            Texture2D texture = new Texture2D(FlatRedBallServices.GraphicsDevice, textureWidth, textureHeight);
            texture.SetData<Color>(pixelData);
#endif
            return texture;
        }
Exemple #46
0
        public void InitializeGraphics()
        {
            PresentParameters presentParms = new PresentParameters();
            presentParms.Windowed = true;
            presentParms.SwapEffect = SwapEffect.Discard;

            // * Benyt default adapteren (=0)
            renderDevice = new DXGraphicsDevice(0, DeviceType.Hardware, renderSurface, CreateFlags.SoftwareVertexProcessing, presentParms);

            dxSprite = new Sprite(renderDevice);
        }
Exemple #47
0
        /// <summary>
        /// Setup the Direct3D Device
        /// </summary>
        /// <param name="thisForm"></param>
        //public static void SetupD3D(OpenSebJ.frmVideoRender thisForm)
        public static void SetupD3D(System.Windows.Forms.Form thisForm)
        {
            // Set the clientForm to the form initating the D3D interface
            clientForm = thisForm;

            // Required so that we can get a pointer to the monitor that the DX graphics are being drawn to.
            adapterInfo = Manager.Adapters.Default;


            // From the Allocator code - not sure of the effect
            // TODO determine if required..
            //Device.IsUsingEventHandlers = false;

            // Setup DirectX device
            PresentParameters presentParams = new PresentParameters();

            // Always use windowed mode for debugging and fullscreen for the presentation.
            presentParams.Windowed = true;

            presentParams.PresentationInterval = PresentInterval.Default;
            presentParams.BackBufferFormat     = Format.X8R8G8B8;
            presentParams.BackBufferWidth      = clientForm.Width;
            presentParams.BackBufferHeight     = clientForm.Height;

            //Needs to specifically be set for full screen
            //presentParams.BackBufferWidth = 800;
            //presentParams.BackBufferHeight = 600;

            // Default to triple buffering for performance gain,
            // if we are low on video memory and use multisampling, 1 is ok too.
            presentParams.BackBufferCount = 2;

            // Discard back buffer when swapping, its faster
            presentParams.SwapEffect = SwapEffect.Discard;

            presentParams.MultiSample = MultiSampleType.None;

            presentParams.MultiSampleQuality = 0;


            // Picked off another example
            presentParams.PresentFlag = PresentFlag.Video;

            // Use a Z-Buffer with 32 bit if possible
            presentParams.EnableAutoDepthStencil = true;
            presentParams.AutoDepthStencilFormat = DepthFormat.D24X8;

            // For windowed, default to PresentInterval.Immediate which will
            // wait not for the vertical retrace period to prevent tearing,
            // but may introduce tearing. For full screen, default to
            // PresentInterval.Default which will wait for the vertical retrace
            // period to prevent tearing.
            presentParams.PresentationInterval = PresentInterval.Immediate;

            // Try setting up the device. There can be a few problems when going with full screen
            // using the event render - needs further investigation
            try
            {
                device = new Device(0, DeviceType.Hardware, clientForm, CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice, presentParams);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }


            //Setup the view matrix to look at the complete sceen
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0.0f, 0.0f, -4.0f),
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f));

            float aspectRatio = (float)clientForm.Width / (float)clientForm.Height;
            float fieldOfView = (float)Math.PI / 2.0f;
            float nearPlane   = 1.0f;
            float farPlane    = 100.0f;


            // Apply the view projection matrix to see everything
            device.Transform.Projection = Matrix.PerspectiveFovLH(fieldOfView, aspectRatio, nearPlane, farPlane);
        }
Exemple #48
0
        public override void update(float elapsedTime)
        {
            cSoldados      = ControladorJuego.getInstance().soldados;
            PosicionActual = this.mesh3.Position;
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;
            this.mesh3.move(direccion * velocidad * elapsedTime);

            float distancia;

            distancia = calcularDistancia(posicionInicial, this.PosicionActual);

            foreach (Soldado Sold in cSoldados)
            {
                if (calcularColisionPersonaje(mesh3, Sold.mesh) && explota < 3)
                {
                    explotando = true;
                    ExplotoX   = Sold.mesh.Position.X;
                    ExplotoZ   = Sold.mesh.Position.Z;
                    break;
                }
            }

            if (explota >= 3)
            {
                explotando = false;
                explota    = 0;
            }

            if (explotando)
            {
                explota += elapsedTime;
            }

            foreach (Soldado Sold in cSoldados)
            {
                if (Sold.vive())
                {
                    if (!calcularColisionPersonaje(mesh3, Sold.mesh))
                    {
                        this.mesh3.move(direccion * velocidad * elapsedTime);
                    }
                    else
                    {
                        acerto      = true;
                        meshSoldado = Sold;
                        Sold.matar();

                        i++;
                        break;
                    }
                }
            }
            // Cuando el misil le da a un soldado lo mata y deja rastros de fuego
            if (acerto && meshSoldado.Persigue)
            {
                Random r = new Random(DateTime.Now.Millisecond);
                meshSoldado.matar();

                meshSoldado.mesh.rotateZ(250);

                meshSoldado.Persigue = false;
                acerto = false;
            }
            //Elimino la bola al colisionar con el terreno
            List <TgcMesh> meshesTerreno = ControladorJuego.getInstance().Escenario.terreno.Meshes;


            //meshSoldado.moveOrientedY(8);
            // meshSoldado.Position = new Vector3(meshSoldado.Position.X, meshSoldado.Position.Y + 15, meshSoldado.Position.Z) * elapsedTime;
            //
            //meshSoldado.p
            //meshSoldado.Position = new Vector3 (meshSoldado.Position.X, meshSoldado.Position.Y, meshSoldado.Position.Z);
            acerto = false;
        }
 internal D3DGpuProgramManager(D3D.Device device)
 {
     this.device = device;
 }
        public WallAccess(Direct3D.Device NewGameDevice,
                          GameEngine.ShaderLevel NewCardShaderLevel,
                          DirectX.Matrix NewViewMatrix,
                          DirectX.Matrix NewProjectionMatrix)
        {
            GameDevice       = NewGameDevice;
            CardShaderLevel  = NewCardShaderLevel;
            ViewMatrix       = NewViewMatrix;
            ProjectionMatrix = NewProjectionMatrix;

            // Load Shader Effects From Files
            WallEffect           = Direct3D.Effect.FromFile(GameDevice, GameConfig.Files.WallFx, null, null, Direct3D.ShaderFlags.None, null);
            WallEffect.Technique = "WallLight_1_1";

            PipeEffect           = Direct3D.Effect.FromFile(GameDevice, GameConfig.Files.PipeFx, null, null, Direct3D.ShaderFlags.None, null);
            PipeEffect.Technique = "PipeLight_1_1";

            // Load Mesh From File
            WallMesh = Direct3D.Mesh.FromFile(GameConfig.Files.WallMesh, Direct3D.MeshFlags.Managed, GameDevice, out WallMtrl);
            PipeMesh = Direct3D.Mesh.FromFile(GameConfig.Files.PipeMesh, Direct3D.MeshFlags.Managed, GameDevice, out PipeMtrl);

            // Load Wall Textures
            if ((WallMtrl != null) && (WallMtrl.Length > 0))
            {
                WallMaterials = new Direct3D.Material[WallMtrl.Length];
                WallTextures  = new Direct3D.Texture[WallMtrl.Length];

                for (int i = 0; i < WallMtrl.Length; i++)
                {
                    WallMaterials[i] = WallMtrl[i].Material3D;
                    if ((WallMtrl[i].TextureFilename != null) && (WallMtrl[i].TextureFilename != string.Empty))
                    {
                        WallTextures[i] = Direct3D.TextureLoader.FromFile(GameDevice, @"..\..\Resources\" + WallMtrl[i].TextureFilename);
                    }
                }
            }

            // Load Pipe Textures
            if ((PipeMtrl != null) && (PipeMtrl.Length > 0))
            {
                PipeMaterials = new Direct3D.Material[PipeMtrl.Length];
                PipeTextures  = new Direct3D.Texture[PipeMtrl.Length];

                for (int i = 0; i < PipeMtrl.Length; i++)
                {
                    PipeMaterials[i] = PipeMtrl[i].Material3D;
                    if ((PipeMtrl[i].TextureFilename != null) && (PipeMtrl[i].TextureFilename != string.Empty))
                    {
                        PipeTextures[i] = Direct3D.TextureLoader.FromFile(GameDevice, @"..\..\Resources\" + PipeMtrl[i].TextureFilename);
                    }
                }
            }

            // Set wall mesh location
            WallWorldMatrix = DirectX.Matrix.RotationYawPitchRoll(3.12f, 0.0f, 0.0f) * DirectX.Matrix.Translation(15, -75, -425);
            PipeWorldMatrix = DirectX.Matrix.RotationYawPitchRoll(3.20f, -0.1f, 0.0f) * DirectX.Matrix.Translation(-145, 15, -375);

            // Set Wall Shader Parameters
            DirectX.Matrix WorldViewProjMatrix = WallWorldMatrix * ViewMatrix * ProjectionMatrix;
            WallEffect.SetValue("WorldViewProj", WorldViewProjMatrix);
            WallEffect.SetValue("WorldMatrix", WallWorldMatrix);
            WallEffect.SetValue("DiffuseDirection", new DirectX.Vector4(1.0f, 1.0f, 1.0f, 0.0f));

            // Set Pipe Shader Parameters
            WorldViewProjMatrix = PipeWorldMatrix * ViewMatrix * ProjectionMatrix;
            PipeEffect.SetValue("WorldViewProj", WorldViewProjMatrix);
            PipeEffect.SetValue("WorldMatrix", PipeWorldMatrix);
            PipeEffect.SetValue("DiffuseDirection", new DirectX.Vector4(1.0f, 1.0f, 1.0f, 0.0f));
        }
        public void InitialiseGraphics(bool wireframe = false)
        {
            //Lighting in Initialise

            PresentParameters pp = new PresentParameters();
            pp.Windowed = true;
            pp.SwapEffect = SwapEffect.Discard;
            pp.EnableAutoDepthStencil = true;
            pp.AutoDepthStencilFormat = DepthFormat.D16;
            pp.DeviceWindowHandle = this.Handle;

            device = new Microsoft.DirectX.Direct3D.Device(0,Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp);
            if (wireframe)
            {
               	device.RenderState.FillMode = FillMode.WireFrame;
            }
            device.DeviceReset += new EventHandler(this.OnDeviceReset);

            OnDeviceReset(device, null);

            float x = (float)Math.Cos(rot);
            float z = (float)Math.Sin(rot);
            device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 50f);
            device.Transform.View = Matrix.LookAtLH(new Vector3(x, currentZoom, z), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            device.RenderState.Lighting = true;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Diffuse = Color.White;
            device.Lights[0].Direction = new Vector3(-x, -6, -z);
            device.Lights[0].Position = new Vector3(x, 6, z);
            device.Lights[0].Enabled = true;
            initialised = true;
        }
Exemple #52
0
    /// <summary>
    /// Initialize the device objects
    /// </summary>
    /// <param name="dev">The grpahics device used to initialize</param>
    public void InitializeDeviceObjects(Device dev)
    {
        if (dev != null)
        {
            // Set up our events
            dev.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
        }

        // Keep a local copy of the device
        device        = dev;
        textureState0 = device.TextureState[0];
        textureState1 = device.TextureState[1];
        samplerState0 = device.SamplerState[0];
        renderState   = device.RenderState;

        // Establish the font and texture size
        textureScale = 1.0f;  // Draw fonts into texture without scaling

        // Large fonts need larger textures
        if (ourFontHeight > 60)
        {
            textureWidth = textureHeight = 2048;
        }
        else if (ourFontHeight > 30)
        {
            textureWidth = textureHeight = 1024;
        }
        else if (ourFontHeight > 15)
        {
            textureWidth = textureHeight = 512;
        }
        else
        {
            textureWidth = textureHeight = 256;
        }

        // If requested texture is too big, use a smaller texture and smaller font,
        // and scale up when rendering.
        Direct3D.Caps d3dCaps = device.DeviceCaps;

        if (textureWidth > d3dCaps.MaxTextureWidth)
        {
            textureScale = (float)d3dCaps.MaxTextureWidth / (float)textureWidth;
            textureWidth = textureHeight = d3dCaps.MaxTextureWidth;
        }

        Bitmap   bmp = new Bitmap(textureWidth, textureHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        Graphics g   = Graphics.FromImage(bmp);

        g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        g.TextContrast      = 0;


        string str;
        float  x    = 0;
        float  y    = 0;
        Point  p    = new Point(0, 0);
        Size   size = new Size(0, 0);

        // Calculate the spacing between characters based on line height
        size = g.MeasureString(" ", systemFont).ToSize();
        x    = spacingPerChar = (int)Math.Ceiling(size.Height * 0.3);

        for (char c = (char)32; c < (char)127; c++)
        {
            str = c.ToString();
            // We need to do some things here to get the right sizes.  The default implemententation of MeasureString
            // will return a resolution independant size.  For our height, this is what we want.  However, for our width, we
            // want a resolution dependant size.
            Size resSize = g.MeasureString(str, systemFont).ToSize();
            size.Height = resSize.Height + 1;

            // Now the Resolution independent width
            if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats
            {
                resSize    = g.MeasureString(str, systemFont, p, StringFormat.GenericTypographic).ToSize();
                size.Width = resSize.Width;
            }
            else
            {
                size.Width = resSize.Width;
            }

            if ((x + size.Width + spacingPerChar) > textureWidth)
            {
                x  = spacingPerChar;
                y += size.Height;
            }

            if (c != ' ') // We need the special case here because a space has a 0 width in GenericTypoGraphic stringformats
            {
                g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y), StringFormat.GenericTypographic);
            }
            else
            {
                g.DrawString(str, systemFont, Brushes.White, new Point((int)x, (int)y));
            }
            textureCoords[c - 32, 0] = ((float)(x + 0 - spacingPerChar)) / textureWidth;
            textureCoords[c - 32, 1] = ((float)(y + 0 + 0)) / textureHeight;
            textureCoords[c - 32, 2] = ((float)(x + size.Width + spacingPerChar)) / textureWidth;
            textureCoords[c - 32, 3] = ((float)(y + size.Height + 0)) / textureHeight;

            x += size.Width + (2 * spacingPerChar);
        }

        // Create a new texture for the font from the bitmap we just created
        fontTexture = Texture.FromBitmap(device, bmp, 0, Pool.Managed);
        RestoreDeviceObjects(null, null);
    }
        /// <summary>
        /// Initializes the Managed Texture Manager.
        /// </summary>
        /// <param name="device">Direct3D device.</param>
        /// <param name="sprite">Sprite device.</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool InitManagedTextureManager(Microsoft.DirectX.Direct3D.Device device, Microsoft.DirectX.Direct3D.Sprite sprite)
        {
            this.device = device;
            this.sprite = sprite;
            this.textures = new System.Collections.ArrayList();

            return (device != null && sprite != null);
        }
        /// Initializes the DirectX environment.
        private void InitializeEnvironment()
        {
            GraphicsDeviceInfo deviceInfo = this.settings.DeviceInfo;

            this.windowed = this.settings.IsWindowed;

            // Set up the presentation parameters
            BuildPresentParametersFromSettings();

            if (deviceInfo.Caps.PrimitiveMiscCapabilities.IsNullReference)
            {
                // Warn user about null ref device that can't render anything
                //TODO: implement
            }

            CreateFlags createFlags = new CreateFlags();

            if (this.settings.VertexProcessingType == VertexProcessingType.Software)
            {
                createFlags = CreateFlags.SoftwareVertexProcessing;
            }
            else if (this.settings.VertexProcessingType == VertexProcessingType.Mixed)
            {
                createFlags = CreateFlags.MixedVertexProcessing;
            }
            else if (this.settings.VertexProcessingType == VertexProcessingType.Hardware)
            {
                createFlags = CreateFlags.HardwareVertexProcessing;
            }
            else if (this.settings.VertexProcessingType == VertexProcessingType.PureHardware)
            {
                createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice;
            }

            try
            {
                // Create the device
                this.localDevice = new D3D.Device(this.settings.AdapterOrdinal, this.settings.DevType, this.owner.Handle, createFlags, this.parameters);

                // Cache our local objects
                //this.renderState = this.localDevice.RenderState;
                //this.sampleState = this.localDevice.SamplerState;
                //this.textureStates = this.localDevice.TextureState;
                // When moving from fullscreen to windowed mode, it is important to
                // adjust the window size after recreating the device rather than
                // beforehand to ensure that you get the window size you want.  For
                // example, when switching from 640x480 fullscreen to windowed with
                // a 1000x600 window on a 1024x768 desktop, it is impossible to set
                // the window size to 1000x600 until after the display mode has
                // changed to 1024x768, because windows cannot be larger than the
                // desktop.
                if (this.windowed)
                {
                    // Make sure main window isn't topmost, so error message is visible
                    System.Drawing.Size currentClientSize = this.owner.ClientSize;
                    this.owner.Size       = this.owner.ClientSize;
                    this.owner.ClientSize = currentClientSize;
                    this.owner.SendToBack();
                    this.owner.BringToFront();
                }

                BehaviorFlags behaviorFlags = new BehaviorFlags(createFlags);
                this.localDevice.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects);
                // Initialize the app's device-dependent objects
                try
                {
                    //InitializeDeviceObjects();
                    RestoreDeviceObjects(null, null);
                    this.active = true;
                    return;
                }
                catch
                {
                    this.localDevice.Dispose();
                    this.localDevice = null;
                    return;
                }
            }
            catch
            {
                // If that failed, fall back to the reference rasterizer
                if (deviceInfo.DevType == D3D.DeviceType.Hardware)
                {
                    if (FindBestWindowedMode(false, true))
                    {
                        this.windowed = true;
                        // Make sure main window isn't topmost, so error message is visible
                        System.Drawing.Size currentClientSize = this.owner.ClientSize;
                        this.owner.Size       = this.owner.ClientSize;
                        this.owner.ClientSize = currentClientSize;
                        this.owner.SendToBack();
                        this.owner.BringToFront();

                        // Let the user know we are switching from HAL to the reference rasterizer
                        //HandleSampleException( null, ApplicationMessage.WarnSwitchToRef);

                        InitializeEnvironment();
                    }
                }
            }
        }
        /// <summary>
        /// Initializes the Managed Direct3D Wrapper.
        /// 
        /// This overload is designed for displaying a diferent resolution then the controls size.
        /// </summary>
        /// <param name="renderWindow">Window to render to.</param>
        /// <param name="screenWidth">Width of the screen in pixels.</param>
        /// <param name="screenHeight">Height of the screen in pixels.</param>
        /// <param name="vsync">Should the renderer wait for a vsync before drawing?</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool InitManagedDirect3D(System.Windows.Forms.Control renderWindow, int screenWidth, int screenHeight, bool vsync)
        {
            try
            {
                // Now  setup our D3D present parameters
                presentParams = new PresentParameters();
                presentParams.BackBufferWidth = screenWidth;
                presentParams.BackBufferHeight = screenHeight;
                //taking out the option for fullscreen mode
                //presentParams.BackBufferFormat = (isWindowed) ? Format.Unknown : Format.R5G6B5;
                presentParams.BackBufferFormat = Format.Unknown;
                presentParams.BackBufferCount = 1;
                presentParams.MultiSample = MultiSampleType.None;
                presentParams.MultiSampleQuality = 0;
                presentParams.SwapEffect = SwapEffect.Copy;// Discard;
                presentParams.DeviceWindow = renderWindow;
                //taking out the option for fullscreen mode
                //presentParams.Windowed = isWindowed;
                presentParams.Windowed = true;
                presentParams.EnableAutoDepthStencil = false;
                presentParams.FullScreenRefreshRateInHz = 0;
                presentParams.PresentationInterval = (vsync) ? PresentInterval.Default : PresentInterval.Immediate;

                // only Create if we haven't done so already
                if(device == null)
                device = new Device(0, DeviceType.Hardware, renderWindow,
                        CreateFlags.HardwareVertexProcessing, presentParams);

                //Create the SwapChain
            lSwapChains.Add(new ManagedSwapChain(device, presentParams));
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create D3D Device", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            try
            {
                sprite = new Microsoft.DirectX.Direct3D.Sprite(device);
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Sprite object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            try
            {
                line = new Microsoft.DirectX.Direct3D.Line(device);

                line.Antialias = true;
                line.Width = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Line Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            try
            {
                fontDescription.FaceName = "arial";
                fontDescription.Quality = FontQuality.Default;
                fontDescription.Weight = FontWeight.Bold;

                font = new Microsoft.DirectX.Direct3D.Font(device, fontDescription);

                line.Antialias = true;
                line.Width = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the font Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            return true;
        }
 //Sprite with it's own texture
 public PlayableCharacterAccess(Direct3D.Device ParentDevice, string TextureLocation, float NewX, float NewY, float NewZ, int NewWidth, int NewHeight, int NewSheetWidth, int NewSheetHeight, Color NewMaskColor, uint CollisionRectWidth, uint CollisionRectHeight)
     : base(ParentDevice, TextureLocation, NewX, NewY, NewZ, NewWidth, NewHeight, NewSheetWidth, NewSheetHeight, NewMaskColor, CollisionRectWidth, CollisionRectHeight)
 {
     this.Initialize();
 }
        private void Initialize()
        {
            try {
                //Common DirectX setup calls...
                PresentParameters presentParams = new PresentParameters();
                presentParams.Windowed = true;
                presentParams.SwapEffect = SwapEffect.Discard;
                presentParams.BackBufferFormat = Format.Unknown;
                presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                presentParams.EnableAutoDepthStencil = true;

                // Store the default adapter
                int adapterOrdinal = D3D.Manager.Adapters.Default.Adapter;
                CreateFlags flags = CreateFlags.SoftwareVertexProcessing;

                // Check to see if we can use a pure hardware device
                D3D.Caps caps = D3D.Manager.GetDeviceCaps(adapterOrdinal, D3D.DeviceType.Hardware);

                // Do we support hardware vertex processing?
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                    // Replace the software vertex processing
                    flags = CreateFlags.HardwareVertexProcessing;

                device = new D3D.Device(0, D3D.DeviceType.Hardware, this, flags, presentParams);
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                OnResetDevice(device, null);

                //Space Donuts setup
                donutTexture = TextureLoader.FromFile(device, MediaUtilities.FindFile(TileSetFileName), 1024, 1024,
                    1, 0,Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.Point, (unchecked((int)0xff000000)));

                donutTileSet = new TileSet(donutTexture, 0, 0, 6, 5, 32, 32);
                pyramidTileSet = new TileSet(donutTexture, 0, 384, 4, 10, 16, 16);
                sphereTileSet = new TileSet(donutTexture, 0, 512, 2, 20, 8, 8);
                cubeTileSet = new TileSet(donutTexture, 0, 544, 2, 20, 8, 8);
                shipTileSet = new TileSet(donutTexture, 0, 576, 4, 10, 16, 16);
                nixiesTileSet = new TileSet(donutTexture, 0, 832, 1, 14, 8, 8);
                bulletTileSet = new TileSet(donutTexture, 304, 832, 1, 1, 8, 2);

                //set up DirectInput keyboard device...
                kbd = new DI.Device(SystemGuid.Keyboard);
                kbd.SetCooperativeLevel(this,
                    DI.CooperativeLevelFlags.Background | DI.CooperativeLevelFlags.NonExclusive);
                kbd.Acquire();

                soundHandler = new SoundHandler(this);

                sm.OnCollisionDetected += new SpriteManager.HandleCollision(this.CollisionHandler);

                hrt.Start();
            }
            catch (DirectXException e) {
                Console.WriteLine("Exception is " + e.ErrorString);
                // Catch any errors and return a failure
            }
        }
        public D3DTextureManager(D3D.Device device)
        {
            this.device = device;

            is32Bit = true;
        }
        public Form1()
        {
            InitializeComponent();
            this.Text = GetUniqueKey(20);
            //Make the window's border completely transparant
            SetWindowLong(this.Handle, GWL_EXSTYLE,
                    (IntPtr)(GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));

            //Set the Alpha on the Whole Window to 255 (solid)
            SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA);

            //Init DirectX
            //This initializes the DirectX device. It needs to be done once.
            //The alpha channel in the backbuffer is critical.
            D3D.PresentParameters presentParameters = new D3D.PresentParameters();
            presentParameters.Windowed = true;
            presentParameters.SwapEffect = D3D.SwapEffect.Discard;
            presentParameters.BackBufferFormat = D3D.Format.A8R8G8B8;

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

            line = new D3D.Line(this.device);
            font = new D3D.Font(device, new System.Drawing.Font("Tahoma", 9, FontStyle.Regular));

            Thread dx = new Thread(new ThreadStart(this.dxThread));
            dx.IsBackground = true;
            dx.Start();
        }
Exemple #60
0
 public void updateViewMatrix(Microsoft.DirectX.Direct3D.Device d3dDevice)
 {
     d3dDevice.Transform.View = viewMatrix;
 }