Beispiel #1
0
        /// <summary>
        /// This event will be fired immediately after the Direct3D device has been
        /// reset, which will happen after a lost device scenario. This is the best location to
        /// create Pool.Default resources since these resources need to be reloaded whenever
        /// the device is lost. Resources created here should be released in the OnLostDevice
        /// event.
        /// </summary>
        private void OnResetDevice(object sender, DeviceEventArgs e)
        {
            SurfaceDescription desc = e.BackBufferDescription;

            // Create a sprite to help batch calls when drawing many lines of text
            textSprite = new Sprite(e.Device);

            // Reset items
            for (int i = 0; i < MaxNumberLights; i++)
            {
                lightControl[i].OnResetDevice(desc);
            }

            // Setup the camera's projection parameters
            float aspectRatio = (float)desc.Width / (float)desc.Height;

            camera.SetProjectionParameters((float)Math.PI / 4, aspectRatio, 0.1f, 5000.0f);
            camera.SetWindow(desc.Width, desc.Height);
            camera.SetButtonMasks((int)MouseButtonMask.Left, (int)MouseButtonMask.Wheel, (int)MouseButtonMask.Middle);

            // Setup UI locations
            hud.SetLocation(desc.Width - 170, 0);
            hud.SetSize(170, 170);
            sampleUi.SetLocation(desc.Width - 170, desc.Height - 300);
            sampleUi.SetSize(170, 300);
        }
Beispiel #2
0
        /// <summary>
        /// Create a file based normap map
        /// </summary>
        void CreateFileBasedNormalMap()
        {
            Texture fileBasedSource = null;

            try
            {
                // Load the texture from a file
                fileBasedSource = GraphicsUtility.CreateTexture(device, "earthbump.bmp", Format.A8R8G8B8);
                SurfaceDescription desc = fileBasedSource.GetLevelDescription(0);
                fileBasedNormalMap = new Texture(device, desc.Width, desc.Height, fileBasedSource.LevelCount, 0, Format.A8R8G8B8, Pool.Managed);
                TextureLoader.ComputeNormalMap(fileBasedNormalMap, fileBasedSource, 0, Channel.Red, 1.0f);
            }
            catch
            {
                SampleException e = new MediaNotFoundException();
                HandleSampleException(e, ApplicationMessage.ApplicationMustExit);
                throw e;
            }
            finally
            {
                if (fileBasedSource != null)
                {
                    fileBasedSource.Dispose();
                }
            }
        }
Beispiel #3
0
        private unsafe void CreateDirectDrawDeviceAndPrimarySurface()
        {
            Type         type;
            FieldInfo    fieldInfo;
            IDirectDraw7 directDraw;

            SurfaceDescription surfaceDesc = new SurfaceDescription();

            device = new Device();
            device.SetCooperativeLevel(this, CooperativeLevelFlags.FullscreenExclusive);
            device.SetDisplayMode(1280, 1024, 16, 0, false);

            type       = device.GetType();
            directDraw = (IDirectDraw7)type.InvokeMember("m_lpUM", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, device, new object [] {});

//      fieldInfo = type.GetField("m_lpUM", BindingFlags.NonPublic | BindingFlags.GetField);
//      unmanagedDevice = (IntPtr) fieldInfo.GetValue(device);

            surfaceDesc.SurfaceCaps.PrimarySurface = true;
            surfaceDesc.SurfaceCaps.Flip           = true;
            surfaceDesc.SurfaceCaps.Complex        = true;
            surfaceDesc.BackBufferCount            = 1;

            primarySurface = new Surface(surfaceDesc, device);

            type             = primarySurface.GetType();
            fieldInfo        = type.GetField("m_lpUM");
            unmanagedSurface = (IntPtr)fieldInfo.GetValue(primarySurface);
        }
Beispiel #4
0
        /// <summary>
        /// This event will be fired immediately after the Direct3D device has been
        /// reset, which will happen after a lost device scenario. This is the best location to
        /// create Pool.Default resources since these resources need to be reloaded whenever
        /// the device is lost. Resources created here should be released in the OnLostDevice
        /// event.
        /// </summary>
        private void OnResetDevice(object sender, DeviceEventArgs e)
        {
            bbufferDesc = e.BackBufferDescription;
            // Create a sprite to help batch calls when drawing many lines of text
            textSprite = new Sprite(e.Device);

            // Setup the camera's projection parameters
            float aspectRatio = (float)bbufferDesc.Width / (float)bbufferDesc.Height;

            camera.SetProjectionParameters((float)Math.PI / 4, aspectRatio, 0.1f, 1000.0f);
            camera.SetWindow(bbufferDesc.Width, bbufferDesc.Height);

            // Setup UI locations
            hud.SetLocation(bbufferDesc.Width - 170, 0);
            hud.SetSize(170, 170);
            sampleUi.SetLocation(bbufferDesc.Width - 170, bbufferDesc.Height - 350);
            sampleUi.SetSize(170, 300);

            batchSprite = new Sprite(e.Device);

            //set up the static gameboard
            UpdateVisibleTiles();

            movingSprite.SetScreenSize(bbufferDesc.Width, bbufferDesc.Height);
        }
Beispiel #5
0
            public ViewModel(TrackObjectBase track, TrackMapPreparationRenderer renderer)
            {
                Track    = track;
                Renderer = renderer;
                Renderer.SetFilter(this);

                Surfaces = SurfaceDescription.LoadAll(Path.Combine(track.DataDirectory, "surfaces.ini")).ToList();

                _save = new SaveHelper <SaveableData>(".TrackMapRendererTools:" + track.Id, () => new SaveableData {
                    Filter            = Filter,
                    IgnoreCase        = FilterIgnoreCase,
                    UseFxaa           = UseFxaa,
                    Scale             = Scale,
                    Margin            = Margin,
                    AiLaneWidth       = AiLaneWidth,
                    AiLaneActualWidth = AiLaneActualWidth,
                }, o => {
                    if (o.Filter == null)
                    {
                        UpdateFilter(Surfaces.Where(x => x.ShouldBeVisibleOnMap()));
                    }
                    else
                    {
                        Filter = o.Filter;
                    }

                    FilterIgnoreCase  = o.IgnoreCase;
                    UseFxaa           = o.UseFxaa;
                    Scale             = o.Scale;
                    Margin            = o.Margin;
                    AiLaneWidth       = o.AiLaneWidth;
                    AiLaneActualWidth = o.AiLaneActualWidth;
                }, storage: CacheStorage.Storage);
                _save.Initialize();
            }
Beispiel #6
0
        public override void render()
        {
            BRenderDevice.getDevice().SetRenderState(RenderStates.AlphaBlendEnable, true);
            BRenderDevice.getDevice().SetRenderState(RenderStates.SourceBlend, (int)Microsoft.DirectX.Direct3D.Blend.SourceAlpha);
            BRenderDevice.getDevice().SetRenderState(RenderStates.DestinationBlend, (int)Microsoft.DirectX.Direct3D.Blend.InvSourceAlpha);

            Texture            mask = TerrainGlobals.getTerrainFrontEnd().getSelectedMaskTexture();
            SurfaceDescription sd   = mask.GetLevelDescription(0);

            float validRadius             = sd.Width / 2;
            List <BTerrainQuadNode> nodes = new List <BTerrainQuadNode>();
            int closestX = 0;
            int closestZ = 0;

            {
                // in this node, find the CLOSEST vertex to this actual position.
                BTerrainEditor.findClosestVertex(ref closestX, ref closestZ, ref TerrainGlobals.getEditor().mBrushIntersectionPoint, TerrainGlobals.getEditor().mBrushIntersectionNode);

                TerrainGlobals.getTerrain().getQuadNodeRoot().getTileBoundsIntersection(nodes, (int)(closestX - validRadius),
                                                                                        (int)(closestX + validRadius),
                                                                                        (int)(closestZ - validRadius),
                                                                                        (int)(closestZ + validRadius));
            }
            for (int i = 0; i < nodes.Count; i++)
            {
                nodes[i].renderCursor();
            }


            BRenderDevice.getDevice().SetRenderState(RenderStates.AlphaBlendEnable, false);
        }
        protected override void OnPaint(PaintEventArgs pe)
        {
            if ((this.m_FormRenderFrame.Device != null) && (this.m_FormRenderFrame.Texture != null) && (this.Visible) && (this.WindowState != FormWindowState.Minimized))
            {
                try {
                    this.m_FormRenderFrame.Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1F, 0);

                    SurfaceDescription surfaceDescription = this.m_FormRenderFrame.Texture.GetLevelDescription(0);
                    Size size = new Size(surfaceDescription.Width, surfaceDescription.Height);

                    Size targetSize = new Size(Math.Max(1, (Int32)((Single)size.Width * this.m_ZoomFactor)), Math.Max(1, (Int32)((Single)size.Height * this.m_ZoomFactor)));
                    if (this.Size != targetSize)
                    {
                        this.Size = targetSize;
                    }

                    this.m_FormRenderFrame.Device.BeginScene();

                    Sprite sprite = new Sprite(this.m_FormRenderFrame.Device);
                    sprite.Begin(SpriteFlags.None);
                    sprite.Draw2D(this.m_FormRenderFrame.Texture, new Rectangle(new Point(0, 0), size), new SizeF(((Single)size.Width * this.m_ZoomFactor), ((Single)size.Height * this.m_ZoomFactor)), new PointF(0F, 0F), Color.FromArgb(255, 255, 255, 255));
                    sprite.End();
                    sprite.Dispose();

                    this.m_FormRenderFrame.Device.EndScene();
                    this.m_FormRenderFrame.Device.Present();
                } catch {
                }
            }
        }
Beispiel #8
0
        //这个贴图创建过程只考虑了透明色,没有考虑alpha贴图
        private unsafe void CreateSingleTextureFromPicInfo(Device device, int idx)
        {
            TextureInfo pic = abi.textureinfos[idx];

            texture[idx] = new Texture(device, pic.width, pic.height, 0, 0, Format.A8R8G8B8, Pool.Managed);
            Texture t = texture[idx];

            SurfaceDescription s = t.GetLevelDescription(0);
            uint *pData          = (uint *)t.LockRectangle(0, LockFlags.None).InternalData.ToPointer();

            int pos = 0;

            for (int i = 0; i < s.Width; i++)
            {
                for (int j = 0; j < s.Height; j++)
                {
                    int  pal   = pic.data[pos++];
                    uint color = pic.palette[pal];

                    if (color == 0xffff00ff)                     //transparent key color! ARGB透明色:0xffff00ff
                    {
                        *pData++ = (uint)0x0;
                    }
                    else
                    {
                        *pData++ = (uint)color;
                    }
                }
            }

            t.UnlockRectangle(0);
        }
        /// <summary>
        /// Sets the data of the new image to be played.
        /// </summary>
        /// <param name="locator">Resource locator of the image item.</param>
        /// <param name="mediaItemTitle">Title of the image item.</param>
        /// <param name="rotation">Rotation of the image.</param>
        /// <param name="flipX">Flipping in horizontal direction.</param>
        /// <param name="flipY">Flipping in vertical direction.</param>
        public void SetMediaItemData(IResourceLocator locator, string mediaItemTitle, RightAngledRotation rotation, bool flipX, bool flipY)
        {
            if (locator == null)
            {
                lock (_syncObj)
                {
                    DisposeTexture();
                    _currentLocator = null;
                    return;
                }
            }

            Texture          texture;
            ImageInformation imageInformation;

            using (IResourceAccessor ra = locator.CreateAccessor())
            {
                IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor;
                if (fsra == null)
                {
                    return;
                }
                using (Stream stream = fsra.OpenRead())
                    using (Stream tmpImageStream = ImageUtilities.ResizeImage(stream, ImageFormat.MemoryBmp, MAX_TEXTURE_DIMENSION, MAX_TEXTURE_DIMENSION))
                        texture = Texture.FromStream(SkinContext.Device, tmpImageStream, (int)tmpImageStream.Length, 0, 0, 1, Usage.None,
                                                     Format.A8R8G8B8, Pool.Default, Filter.None, Filter.None, 0, out imageInformation);
            }
            lock (_syncObj)
            {
                ReloadSettings();
                _state = PlayerState.Active;

                DisposeTexture();
                _currentLocator = locator;
                _mediaItemTitle = mediaItemTitle;
                _texture        = texture;
                _rotation       = rotation;
                _flipX          = flipX;
                _flipY          = flipY;
                SurfaceDescription desc = _texture.GetLevelDescription(0);
                _textureMaxUV = new SizeF(imageInformation.Width / (float)desc.Width, imageInformation.Height / (float)desc.Height);

                // Reset animation
                _animator.Initialize();

                if (_slideShowTimer != null)
                {
                    _slideShowTimer.Change(_slideShowImageDuration, TS_INFINITE);
                }
                else
                {
                    CheckTimer();
                }
                _playbackStartTime = DateTime.Now;
                if (_pauseTime.HasValue)
                {
                    _pauseTime = _playbackStartTime;
                }
            }
        }
Beispiel #10
0
        private void CreateSurfaces()
        {
            SurfaceDescription desc = new SurfaceDescription();
            SurfaceCaps        caps = new SurfaceCaps();

            localClipper        = new Clipper(localDevice);
            localClipper.Window = owner;

            desc.SurfaceCaps.PrimarySurface = true;
            if (null != surfacePrimary)
            {
                surfacePrimary.Dispose();
            }
            surfacePrimary         = new Surface(desc, localDevice);
            surfacePrimary.Clipper = localClipper;

            desc.Clear();
            desc.SurfaceCaps.OffScreenPlain = true;
            desc.Width  = surfacePrimary.SurfaceDescription.Width;
            desc.Height = surfacePrimary.SurfaceDescription.Height;

            if (null != surfaceSecondary)
            {
                surfaceSecondary.Dispose();
            }
            surfaceSecondary           = new Surface(desc, localDevice);
            surfaceSecondary.FillStyle = 0;
        }
Beispiel #11
0
        //-----------------------------------------------------------------------------
        // Name: RenderFullScreenQuad()
        // Desc: Render a quad at the specified tranformed depth
        //-----------------------------------------------------------------------------
        private void RenderFullScreenQuad(float fDepth)
        {
            ScreenVertex[] aVertices = new ScreenVertex[4];

            SurfaceDescription pBackBufferSurfaceDesc = device.GetBackBuffer(0, 0, BackBufferType.Mono).Description;

            aVertices[0].pos = new Vector4(-0.5f, -0.5f, fDepth, fDepth);
            aVertices[1].pos = new Vector4((float)pBackBufferSurfaceDesc.Width - 0.5f, -0.5f, fDepth, fDepth);
            aVertices[2].pos = new Vector4(-0.5f, (float)pBackBufferSurfaceDesc.Height - 0.5f, fDepth, fDepth);
            aVertices[3].pos = new Vector4((float)pBackBufferSurfaceDesc.Width - 0.5f, (float)pBackBufferSurfaceDesc.Height - 0.5f, fDepth, fDepth);

            aVertices[0].tCurr = new Vector2(0.0f, 0.0f);
            aVertices[1].tCurr = new Vector2(1.0f, 0.0f);
            aVertices[2].tCurr = new Vector2(0.0f, 1.0f);
            aVertices[3].tCurr = new Vector2(1.0f, 1.0f);

            for (int i = 0; i < 4; i++)
            {
                aVertices[i].tBack    = aVertices[i].tCurr;
                aVertices[i].tBack.X += (1.0f / (float)pBackBufferSurfaceDesc.Width);
                aVertices[i].tBack.Y += (1.0f / (float)pBackBufferSurfaceDesc.Height);
                aVertices[i].fSize    = 0.0f;
            }

            device.VertexFormat = ScreenVertexFormat;
            device.DrawUserPrimitives(PrimitiveType.TriangleStrip, 2, aVertices);
        }
Beispiel #12
0
        /// <summary>
        /// This event will be fired immediately after the Direct3D device has been
        /// reset, which will happen after a lost device scenario. This is the best location to
        /// create Pool.Default resources since these resources need to be reloaded whenever
        /// the device is lost. Resources created here should be released in the OnLostDevice
        /// event.
        /// </summary>
        private void OnResetDevice(object sender, DeviceEventArgs e)
        {
            SurfaceDescription desc = e.BackBufferDescription;

            // Create a sprite to help batch calls when drawing many lines of text
            textSprite = new Sprite(e.Device);

            // Generate the enhanced mesh
            GenerateEnhancedMesh(e.Device, numberSegments);

            // Set the fill mode
            if (isWireframe)
            {
                e.Device.RenderState.FillMode = FillMode.WireFrame;
            }
            else
            {
                e.Device.RenderState.FillMode = FillMode.Solid;
            }

            // Setup the camera's projection parameters
            float aspectRatio = (float)desc.Width / (float)desc.Height;

            camera.SetProjectionParameters((float)Math.PI / 4, aspectRatio, 0.1f, 1000.0f);
            camera.SetWindow(desc.Width, desc.Height);

            // Setup UI locations
            hud.SetLocation(desc.Width - 170, 0);
            hud.SetSize(170, 170);
            sampleUi.SetLocation(desc.Width - 170, desc.Height - 350);
            sampleUi.SetSize(170, 300);
        }
Beispiel #13
0
 /// <summary>
 /// 获得Icon纹理对象
 /// </summary>
 /// <param name="device">d3d对象</param>
 /// <param name="textureFileName">图片的路径</param>
 public IconTexture(Device device, string textureFileName)
 {
     //判断图片路径是否为空
     if ((textureFileName != null) && textureFileName.Length > 0)
     {
         //判断是否是GDI支持的图片,若是,则用GDI读成Image或Bitmap对象,再转换为纹理,速度会快
         if (ImageHelper.IsGdiSupportedImageFormat(textureFileName))
         {
             //转换为Texture对象
             using (Image image = ImageHelper.LoadImage(textureFileName))
                 LoadImage(device, image);
         }
         else
         {
             //只能用DirectX读取的对象
             Texture = ImageHelper.LoadIconTexture(textureFileName);
             using (Surface s = Texture.GetSurfaceLevel(0))
             {
                 SurfaceDescription desc = s.Description;
                 Width  = desc.Width;
                 Height = desc.Height;
             }
         }
     }
 }
Beispiel #14
0
        protected void UpdateTexture(string url)
        {
            lock (_imageSync)
            {
                var imageData = Utils.DownloadImage(url);
                _texture = ContentManager.Instance.GetTexture(imageData, _itemTitle);
                if (_texture == null)
                {
                    return;
                }
                if (!_texture.IsAllocated)
                {
                    _texture.Allocate();
                }
                if (!_texture.IsAllocated)
                {
                    return;
                }

                SurfaceDescription desc = _texture.Texture.GetLevelDescription(0);
                _textureMaxUv = new SizeF(_texture.Width / (float)desc.Width, _texture.Height / (float)desc.Height);

                // Reset animation
                _animator.Initialize();

                _state = PlayerState.Active;
            }
        }
        public override void Initialize(DrawArgs drawArgs)
        {
            this.isInitialized = true;

            m_drawingFont = drawArgs.CreateFont(m_fontDescription);

            //Validate URL

            /*
             * if(System.Text.RegularExpressions.Regex.IsMatch(m_placenameBaseUrl, "(http|ftp|https)://([/w-]+/.)+(/[/w- ./?%&=]*)?"))
             * {
             *  this.isInitialized = true;
             * }
             */
            //Generate Initial File List
            //WorldWindWFSPlacenameFile root_file = new WorldWindWFSPlacenameFile(m_placenameBaseUrl, m_typename, m_labelfield);
            //m_placenameFileList = new ArrayList(root_file.SplitPlacenameFiles());

            //TODO:Download and validate capabitilities

            if (m_iconFilePath != null)
            {
                m_iconTexture = ImageHelper.LoadIconTexture(m_iconFilePath);

                using (Surface s = m_iconTexture.GetSurfaceLevel(0))
                {
                    SurfaceDescription desc = s.Description;
                    m_spriteSize = new System.Drawing.Rectangle(0, 0, desc.Width, desc.Height);
                }

                m_sprite = new Sprite(drawArgs.device);
            }
        }
        public PixelDataProvider(int width, int height, int numChannels, Device device, Usage usage)
            : base()
        {
            Format pf = Format.X8R8G8B8;
            switch (numChannels)
            {
                case 1:
                    pf = Format.A8;
                    break;
                case 3:
                    pf = Format.R8G8B8;
                    break;
                case 4:
                    pf = Format.X8R8G8B8;
                    break;
                case 8:
                    pf = Format.A16B16G16R16;
                    break;
            }
            //TODO: how to find out which Formats are supported??
            //device.DeviceCaps.TextureCaps
            if (pf == Format.R8G8B8)
                pf = Format.X8R8G8B8;

            //RenderToSurface sf = new RenderToSurface(device, width, height, pf, false, null);
            //this._tx = new Texture(device, width, height, 1, Usage.RenderTarget, pf, Pool.Default); // Pool.Managed doesn't work with Usage.RenderTarget
            Pool pool = Pool.Managed;
            if (usage == Usage.RenderTarget)
                pool = Pool.Default;

            this._tx = new Texture(device, width, height, 1, usage, pf, pool);
            //this._sd = this._tx.GetLevelDescription(0);
            this._surf = this._tx.GetSurfaceLevel(0); //AOAO
            this._sd = this._surf.Description;
        }
Beispiel #17
0
        /// <summary>
        /// This event will be fired immediately after the Direct3D device has been
        /// reset, which will happen after a lost device scenario. This is the best location to
        /// create Pool.Default resources since these resources need to be reloaded whenever
        /// the device is lost. Resources created here should be released in the OnLostDevice
        /// event.
        /// </summary>
        private void OnResetDevice(object sender, DeviceEventArgs e)
        {
            SurfaceDescription desc = e.BackBufferDescription;

            // Create a sprite to help batch calls when drawing many lines of text
            textSprite = new Sprite(e.Device);

            // Set effect variables as needed
            effect.SetValue("g_MaterialAmbientColor", new ColorValue(0.35f, 0.35f, 0.35f, 0));
            effect.SetValue("g_MaterialDiffuseColor", WhiteColor);

            // To read or write to D3DX effect variables we can use the string name
            // instead of using handles, however it improves perf to use handles since then
            // D3DX won't have to spend time doing string compares
            techniqueHandle   = effect.GetTechnique("RenderScene");
            timeHandle        = effect.GetParameter(null, "g_fTime");
            worldHandle       = effect.GetParameter(null, "g_mWorld");
            worldViewHandle   = effect.GetParameter(null, "g_mWorldViewProjection");
            meshTextureHandle = effect.GetParameter(null, "g_MeshTexture");

            // Setup the camera's projection parameters
            float aspectRatio = (float)desc.Width / (float)desc.Height;

            camera.SetProjectionParameters((float)Math.PI / 4, aspectRatio, 0.1f, 1000.0f);
            camera.SetWindow(desc.Width, desc.Height);

            // Setup UI locations
            hud.SetLocation(desc.Width - 170, 0);
            hud.SetSize(170, 170);
        }
Beispiel #18
0
        protected void UpdateTexture(string url)
        {
            lock (_imageSync)
            {
                var imageData = Utils.DownloadImage(url);
                _texture = ContentManager.Instance.GetTexture(imageData, _itemTitle);
                if (_texture == null)
                {
                    return;
                }
                if (!_texture.IsAllocated)
                {
                    _texture.Allocate();
                }
                if (!_texture.IsAllocated)
                {
                    return;
                }

                //ImagePlayerSettings settings = ServiceRegistration.Get<ISettingsManager>().Load<ImagePlayerSettings>() ?? new ImagePlayerSettings();
                _animator = STILL_IMAGE_ANIMATION; //settings.UseKenBurns ? new KenBurnsAnimator() : STILL_IMAGE_ANIMATION;
                SurfaceDescription desc = _texture.Texture.GetLevelDescription(0);
                _textureMaxUv = new SizeF(_texture.Width / (float)desc.Width, _texture.Height / (float)desc.Height);

                // Reset animation
                _animator.Initialize();

                _state = PlayerState.Active;
            }
        }
Beispiel #19
0
        internal void SetTexture(int[,] optimizedArray, Bitmap hiResBitmap)
        {
            lock (this)
            {
                if (optimizedTexture == null || optimizedTexture.Disposed)
                {
                    return;                     // something went wrong
                }

                int w = optimizedArray.GetLength(1);
                int h = optimizedArray.GetLength(0);

                SurfaceDescription sd = optimizedTexture.GetLevelDescription(0);
                if (w != sd.Width || h != sd.Height)                // Out-of-date texture? (Didn't call SetBaseTexture first?)
                {
                    return;
                }

                byte[,] optimizedtextureArray = (byte[, ])optimizedTexture.LockRectangle(typeof(byte), 0, LockFlags.None, new int[] { h, w });
                int wLevel = optimizedtextureArray.GetLength(1);
                int hLevel = optimizedtextureArray.GetLength(0);
                for (int j = 0; j < hLevel; j++)
                {
                    for (int i = 0; i < wLevel; i++)
                    {
                        optimizedtextureArray[j, i] = (byte)(optimizedArray[j, i]);
                    }
                }
                optimizedTexture.UnlockRectangle(0);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Restore all the surfaces, and redraw the sprite surfaces.
        /// </summary>
        void RestoreSurfaces()
        {
            SurfaceDescription description = new SurfaceDescription();

            displayDevice.RestoreAllSurfaces();

            // No need to re-create the surface, just re-draw it.
            text.ColorFill(9);
            text.DrawText(0, 0, textHelp, false);

            // We need to release and re-load, and set the palette again to
            // redraw the bitmap on the surface.  Otherwise, GDI will not
            // draw the bitmap on the surface with the correct palette.
            pal.Dispose();
            pal           = null;
            pal           = new Palette(displayDevice, bitmapFileName);
            front.Palette = pal;

            // Release and re-load the sprite bitmap.
            surfaceLogo.Dispose();
            surfaceLogo = new Surface(bitmapFileName, description, displayDevice);
            ColorKey ck = new ColorKey();

            surfaceLogo.SetColorKey(ColorKeyFlags.SourceDraw, ck);

            return;
        }
Beispiel #21
0
        private void SetManagedDevice(IntPtr unmanagedDevice)
        {
            // Start by freeing everything
            FreeResources();

            // Create a managed Device from the unmanaged pointer
            // The constructor don't call IUnknown.AddRef but the "destructor" seem to call IUnknown.Release
            // Direct3D seem to be happier with that according to the DirectX log
            Marshal.AddRef(unmanagedDevice);
            this.unmanagedDevice = unmanagedDevice;
            device = new Device(unmanagedDevice);

            // Create helper objects to draw over the video
            sprite  = new Sprite(device);
            gdiFont = new System.Drawing.Font("Tahoma", 15);
            d3dFont = new Direct3D.Font(device, gdiFont);

            // Load a bitmap (the spider) from embedded resources. This is a png file with alpha transparency
            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DirectShowLib.Sample.redspider.png"))
            {
                spiderTex = TextureLoader.FromStream(device, stream, D3DX.Default, D3DX.Default, D3DX.Default, D3DX.Default, Usage.None, Format.A8R8G8B8, Pool.Default, Filter.None, Filter.None, 0);
                SurfaceDescription spiderDesc = spiderTex.GetLevelDescription(0);
                spiderSize = new Size(spiderDesc.Width, spiderDesc.Height);
            }
        }
        public override unsafe void SetPixels(System.Collections.Hashtable coordsAndColors)
        {
            SurfaceDescription sd = this.m_tx.GetLevelDescription(0);
            int nPitch;

            //uint* pData = (uint*)this.m_tx.LockRectangle(0,
            //	LockFlags.None, out nPitch).InternalData.ToPointer();
            uint[,] data = (uint[, ]) this.m_tx.LockRectangle(typeof(uint), 0,
                                                              LockFlags.None, sd.Width, sd.Height);

            System.Collections.IDictionaryEnumerator en = coordsAndColors.GetEnumerator();
            while (en.MoveNext())
            {
                Point pnt = (Point)en.Key;
                data[pnt.X, pnt.Y] = (uint)((Color)en.Value).ToArgb();
            }

//			for (int x = 0; x < sd.Width; x++)
//			{
//				for (int y = 0; y < sd.Height; y++)
//					data[x,y] = (uint)Color.FromArgb(100,200,233).ToArgb();
//			}

            this.m_tx.UnlockRectangle(0);
        }
        protected void UpdateTexture(ImageItem item)
        {
            lock (imageSync)
            {
                itemTitle = item.ImageId;
                texture   = ContentManager.Instance.GetTexture(item.ImageData, item.ImageId);
                if (texture == null)
                {
                    return;
                }
                if (!texture.IsAllocated)
                {
                    texture.Allocate();
                }
                if (!texture.IsAllocated)
                {
                    return;
                }

                //ImagePlayerSettings settings = ServiceRegistration.Get<ISettingsManager>().Load<ImagePlayerSettings>() ?? new ImagePlayerSettings();
                animator = STILL_IMAGE_ANIMATION; //settings.UseKenBurns ? new KenBurnsAnimator() : STILL_IMAGE_ANIMATION;
                SurfaceDescription desc = texture.Texture.GetLevelDescription(0);
                textureMaxUV = new SizeF(texture.Width / (float)desc.Width, texture.Height / (float)desc.Height);

                // Reset animation
                animator.Initialize();

                state = PlayerState.Active;
            }
        }
Beispiel #24
0
        }         // CarregarModelo().fim

        // ---]

        // [---
        private void ModificarTextura(Texture textura)
        {
            // Gerador de números aleatórios
            Random sorteio = new Random();

            // Componentes rgb para montar depois a cor final
            byte r, g, b;

            // Obtém a descrição da textura
            SurfaceDescription desc = textura.GetLevelDescription(0);

            // Obtém a área de dados da textura
            uint[,] cores;
            cores = (uint[, ])textura.LockRectangle(typeof(uint), 0,
                                                    LockFlags.None, desc.Width, desc.Height);

            // Escreve uma cor aleatória em cada ponto da textura
            for (int linha = 0; linha < desc.Width; linha++)
            {
                for (int coluna = 0; coluna < desc.Height; coluna++)
                {
                    // Produz uma cor aleatória
                    r = (byte)sorteio.Next(255);
                    g = (byte)sorteio.Next(255);
                    b = (byte)sorteio.Next(255);
                    Color cor = Color.FromArgb(r, g, b);

                    // Escreve a cor na área de dados da textura
                    cores[linha, coluna] = (uint)cor.ToArgb();
                } // endfor coluna
            }     // endfor linha

            // Libera a textura para o sistema\placa de vídeo
            textura.UnlockRectangle(0);
        } // ModificarTextura().fim
Beispiel #25
0
        void MemoryRender(Bitmap buffer)
        {
            BitmapData bmpData = default(BitmapData);

            try
            {
                bmpData = buffer.LockBits
                          (
                    new Rectangle()
                {
                    Width  = buffer.Width,
                    Height = buffer.Height
                },
                    ImageLockMode.ReadWrite,
                    buffer.PixelFormat
                          );

                SurfaceDescription surfaceDesc =
                    new SurfaceDescription(bmpData.Width, bmpData.Height, pixelSize, ( ushort )(bmpData.Stride / pixelSize), bmpData.Scan0);

                if (ClearEveryFrame)
                {
                    new MemoryFiller(surfaceDesc).Fill(BackgroundColor);
                }

                render(new DisplayController(surfaceDesc));
            }
            finally
            {
                if (bmpData != null)
                {
                    buffer.UnlockBits(bmpData);
                }
            }
        }
Beispiel #26
0
        protected override bool BeginRenderBrushOverride(PrimitiveBuffer primitiveContext, RenderContext renderContext)
        {
            ISlimDXVideoPlayer player;

            if (!GetPlayer(out player))
            {
                return(false);
            }

            if (!RefreshEffectParameters(player))
            {
                return(false);
            }

            lock (player.SurfaceLock)
            {
                Surface playerSurface = player.Surface;
                if (playerSurface == null)
                {
                    return(false);
                }
                DeviceEx           device      = SkinContext.Device;
                SurfaceDescription desc        = playerSurface.Description;
                SurfaceDescription?textureDesc = _texture == null ? new SurfaceDescription?() : _texture.GetLevelDescription(0);
                if (!textureDesc.HasValue || textureDesc.Value.Width != desc.Width || textureDesc.Value.Height != desc.Height)
                {
                    TryDispose(ref _texture);
                    _texture = new Texture(device, desc.Width, desc.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
                }
                using (Surface target = _texture.GetSurfaceLevel(0))
                    device.StretchRectangle(playerSurface, target, TextureFilter.None);
            }
            return(_imageContext.StartRender(renderContext, _scaledVideoSize, _texture, _videoTextureClip, BorderColor.ToArgb(), _lastFrameData));
        }
Beispiel #27
0
        public void Allocate(int width, int height, Usage usage, Format format)
        {
            bool free;

            lock (_syncObj)
                free = width != _size.Width || height != _size.Height || usage != _usage || format != _format;
            if (free)
            {
                Free();
            }
            lock (_syncObj)
            {
                if (_texture != null)
                {
                    return;
                }

                _size.Width  = width;
                _size.Height = height;
                _usage       = usage;
                _format      = format;

                // Note that it doesn't seem to be possible to create a texture with multisample surfaces inside. So rendering to that texture
                // won't provide multisample antialiasing.
                _texture  = new Texture(GraphicsDevice.Device, width, height, 1, usage, format, Pool.Default);
                _surface0 = _texture.GetSurfaceLevel(0);

                SurfaceDescription desc = _texture.GetLevelDescription(0);
                _maxU = _size.Width / ((float)desc.Width);
                _maxV = _size.Height / ((float)desc.Height);
            }
            AllocationChanged(AllocationSize);
            KeepAlive();
        }
        public void Run(OpsContext context, OpsStatement statement)
        {
            TexFormatArgs args = statement.Arguments as TexFormatArgs;

            ArrayList containers = statement.GetContent(context);

            OpsConsole.WriteLine("Changing texture formats to " + args.Format);

            foreach (OpsTexture container in containers)
            {
                if (container.Texture is Texture)
                {
                    Texture            oldTexture = container.Texture as Texture;
                    SurfaceDescription sd         = oldTexture.GetLevelDescription(0);

                    container.Texture = OpsTextureHelper.CloneTexture(oldTexture, sd.Width, sd.Height, oldTexture.LevelCount, args.Format, Usage.None, Filter.Triangle | Filter.Dither | (container.SRGB?Filter.Srgb:0), Pool.Managed);
                }
                else if (container.Texture is VolumeTexture)
                {
                    VolumeTexture     oldTexture = container.Texture as VolumeTexture;
                    VolumeDescription vd         = oldTexture.GetLevelDescription(0);

                    container.Texture = OpsTextureHelper.CloneVolume(oldTexture, vd.Width, vd.Height, vd.Depth, oldTexture.LevelCount, args.Format, Usage.None, Filter.Triangle | Filter.Dither | (container.SRGB?Filter.Srgb:0), Pool.Managed);
                }
                else if (container.Texture is CubeTexture)
                {
                    CubeTexture        oldTexture = container.Texture as CubeTexture;
                    SurfaceDescription sd         = oldTexture.GetLevelDescription(0);

                    container.Texture = OpsTextureHelper.CloneCube(oldTexture, sd.Width, oldTexture.LevelCount, args.Format, Usage.None, Filter.Triangle | Filter.Dither | (container.SRGB?Filter.Srgb:0), Pool.Managed);
                }
            }
        }
Beispiel #29
0
        public void UpdateTexture(Device device, string textureFileName)
        {
            if ((textureFileName != null) && textureFileName.Length > 0)
            {
                if (textureFileName.ToLower().StartsWith("http://") && BaseSavePath != null)
                {
                    // download it
                    try
                    {
                        Uri uri = new Uri(textureFileName);

                        // Set the subdirectory path to the hostname and replace . with _
                        string savePath = uri.Host;
                        savePath = savePath.Replace('.', '_');

                        // build the save file name from the component pieces
                        savePath = BaseSavePath + @"\" + savePath + uri.AbsolutePath;
                        savePath = savePath.Replace('/', '\\');

                        // Offline check
                        if (!World.Settings.WorkOffline)
                        {
                            WorldWind.Net.WebDownload webDownload = new WorldWind.Net.WebDownload(textureFileName);
                            webDownload.DownloadType = WorldWind.Net.DownloadType.Unspecified;
                            webDownload.DownloadFile(savePath);
                        }

                        // reset the texture file name for later use.
                        textureFileName = savePath;
                    }
                    catch { }
                }
            }

            // Clear old texture - don't know if this is necessary so commented out for the moment
            //if (Texture != null)
            //{
            //    Texture.Dispose();
            //}

            if (ImageHelper.IsGdiSupportedImageFormat(textureFileName))
            {
                // Load without rescaling source bitmap
                using (Image image = ImageHelper.LoadImage(textureFileName))
                    LoadImage(device, image);
            }
            else
            {
                // Only DirectX can read this file, might get upscaled depending on input dimensions.
                Texture = ImageHelper.LoadIconTexture(textureFileName);
                // Read texture level 0 size
                using (Surface s = Texture.GetSurfaceLevel(0))
                {
                    SurfaceDescription desc = s.Description;
                    Width  = desc.Width;
                    Height = desc.Height;
                }
            }
        }
 public PixelDataProvider(Texture tx)
     : base()
 {
     this._tx = tx;
     //this._sd = this._tx.GetLevelDescription(0);
     this._surf = this._tx.GetSurfaceLevel(0); //AOAO
     this._sd   = this._surf.Description;
 }
Beispiel #31
0
        /// <summary>
        /// Constructs a texture.
        /// </summary>
        /// <param name="width">Maximum x offset.</param>
        /// <param name="height">Maximum y offset.</param>
        public TextureMap(BaseTexture texture)
        {
            SurfaceDescription _info = ((Texture)texture).GetSurfaceLevel(0).Description;

            this.Width          = (int)(_info.Width * Interfaces.Rendering.Radiosity.RadiosityHelper.LightmapScale);
            this.Height         = (int)(_info.Height * Interfaces.Rendering.Radiosity.RadiosityHelper.LightmapScale);
            this.m_shadowBitmap = new double[Width, Height, 3];
        }
 public PixelDataProvider(Texture tx)
     : base()
 {
     this._tx = tx;
     //this._sd = this._tx.GetLevelDescription(0);
     this._surf = this._tx.GetSurfaceLevel(0); //AOAO
     this._sd = this._surf.Description;
 }
		/// <summary>
		/// This method creates the primary and secondary surfaces
		/// </summary>
		public void CreateSurfaces()
		{
			// Every surface needs a description
			// This is where you set the parameters for the surface
			SurfaceDescription desc = new SurfaceDescription();
  
			// This is the clipper for the primary surface
			// -> connect it to the target control
			Clipper graphicsClipper = new Clipper(graphicsDevice);
			graphicsClipper.Window = target;

			// First we want to create a primary surface
			desc.SurfaceCaps.PrimarySurface = true;

#if !windowed
			// In release mode, we enable flipping, set the complex
			// flag and tell the surface that we will use one back
			// buffer
			desc.SurfaceCaps.Flip = true;
			desc.SurfaceCaps.Complex = true;
			desc.BackBufferCount = 1;
#endif

			// Create the surface
			surfacePrimary = new Surface(desc, graphicsDevice);
			srcRect = new Rectangle(0,0,target.Width,target.Height);

			// Attach clipper to the surface
			surfacePrimary.Clipper = graphicsClipper;

			// To build the secondary surface, we need 
			// a new description -> clear all values
			desc.Clear();

#if windowed
			// In debug mode, we simply copy the primary surfaces
			// dimensions and create a offscreenplain secondary
			// surface
			desc.Width = surfacePrimary.SurfaceDescription.Width;
			desc.Height = surfacePrimary.SurfaceDescription.Height;
			desc.SurfaceCaps.OffScreenPlain = true;
			surfaceSecondary = new Surface(desc, this.graphicsDevice);
#else
			// In release mode, we set the backbuffer flag to true
			// and retrieve a backbuffer surface from the primary
			// surface
			desc.SurfaceCaps.BackBuffer = true;
			surfaceSecondary = surfacePrimary.GetAttachedSurface(desc.SurfaceCaps);
#endif

			//surfaceSecondary.Clipper=graphicsClipper;
		} 
Beispiel #34
0
 private static void DrawAliens()
 {
     TransAlien[] aliens = AIUnits.GetTransAliens();
     Drawing.OurSprite.Begin(SpriteFlags.AlphaBlend);
     foreach (TransAlien alien in aliens)
     {
         Temp = Textures.aliens[alien.Model.X][alien.Model.Y].GetLevelDescription(0);
         Pos = new Vector3(alien.Pozition.X - WorkSpace.Space.X - Temp.Width / 2 + WorkSpace.DX, alien.Pozition.Y - WorkSpace.Space.Y - Temp.Height / 2 + WorkSpace.DY, 1);
         Rect = new Rectangle(0, 0, Temp.Width, Temp.Height);
         Tr = Matrix.Translation(Pos.X + Temp.Width / 2.0f, Pos.Y + Temp.Height / 2.0f, 1);
         Drawing.OurSprite.Transform = Matrix.Invert(Tr) * Matrix.RotationZ(alien.Angle) * Tr;
         Drawing.OurSprite.Draw(Textures.aliens[alien.Model.X][alien.Model.Y], Rect, new Vector3(0, 0, 0), Pos, Color.White);
     }
     Drawing.OurSprite.End();
 }
Beispiel #35
0
 public static void DrawUISelectedObj()
 {
     if (InformationWindow.IsShow)
     {
         Drawing.OurSprite.Begin(SpriteFlags.AlphaBlend);
         Temp = Textures.infoRads.Get(InformationWindow.GetRadSelectedObj()).GetLevelDescription(0);
         Point pos = InformationWindow.GetPosSelectedObj();
         Drawing.OurSprite.Draw2D(Textures.infoRads.Get(InformationWindow.GetRadSelectedObj()), Point.Empty, 0, new Point(pos.X - WorkSpace.Space.X - Temp.Width / 2 + WorkSpace.DX, pos.Y - WorkSpace.Space.Y - Temp.Height / 2 + WorkSpace.DY), Color.White);
         if ((InformationWindow.GetTypeSelectedObj() == "Building") || (InformationWindow.GetTypeSelectedObj() == "Tower"))
         {
             Drawing.OurSprite.Draw2D(Textures.radVisibl, Point.Empty, 0, new Point(pos.X - WorkSpace.Space.X - ConstrPanelControl.TextureRadVisiblSize / 2, pos.Y - WorkSpace.Space.Y - ConstrPanelControl.TextureRadVisiblSize / 2), Color.White);
             if (InformationWindow.GetFireRadSelectedObj() != "")
             {
                 string frad = InformationWindow.GetFireRadSelectedObj();
                 Temp = Textures.radAttack.Get(frad).GetLevelDescription(0);
                 Drawing.OurSprite.Draw2D(Textures.radAttack.Get(frad), Point.Empty, 0, new Point(pos.X - WorkSpace.Space.X - Temp.Width / 2, pos.Y - WorkSpace.Space.Y - Temp.Height / 2), Color.White);
             }
         }
         Drawing.OurSprite.End();
     }
 }
Beispiel #36
0
        /// <summary>
        /// Gets Surface from bitmap file.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="pathToBitmap"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static Surface LoadBitmap(
            Device device,
            string pathToBitmap,
            int width,
            int height)
        {
            Surface result = null;
            var image = new Bitmap(pathToBitmap);
            if(File.Exists(pathToBitmap))
            {
                var surfaceDescription = new SurfaceDescription
                                             {
                                                 Width = image.Width,
                                                 Height = image.Height,
                                                 SurfaceCaps = {OffScreenPlain = true}
                                             };

                result = new Surface(pathToBitmap, surfaceDescription, device);
            }

            return result;
        }
        /// <summary>
        /// Inits DirectDraw and map.
        /// </summary>
        public void InitDraw()
        {
            _map = new Map(this, MAP_WIDTH_CELLS, MAP_HEIGHT_CELLS);
            var clipper = new Clipper {Window = _parentControl};
            _renderRect = new Rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            _mapRect = new Rectangle(
                0,
                MAP_TOP_BORDER_OFFSET,
                MAP_WIDTH_CELLS * CELL_SIZE,
                MAP_HEIGHT_CELLS * CELL_SIZE);

            _fDirectDraw = new Device();
            _fDirectDraw.SetCooperativeLevel(_parentControl, CooperativeLevelFlags.Normal);

            //            _fDirectDraw.SetCooperativeLevel(_parentControl, CooperativeLevelFlags.FullscreenExclusive);
            //            _fDirectDraw.SetDisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT, BIT_DEPTH, 0, false);

            var ddPrimarySurfaceDesc = new SurfaceDescription
                                           {
                                               SurfaceCaps = new SurfaceCaps
                                                                 {
                                                                     PrimarySurface = true,
                                                                     VideoMemory = true
                                                                 }
                                           };

            _fPrimarySurface = new Surface(ddPrimarySurfaceDesc, _fDirectDraw)
                                   {
                                       Clipper = clipper
                                   };

            var ddBackSurfaceDesc = new SurfaceDescription
                                    {
                                        SurfaceCaps =
                                            {
                                                OffScreenPlain = true,
                                                VideoMemory = true
                                            },
                                        Width = _renderRect.Width,
                                        Height = _renderRect.Height
                                    };

            _backSurface = new Surface(ddBackSurfaceDesc, _fDirectDraw);

            var ddSurfaceDesc2 = new SurfaceDescription
            {
                SurfaceCaps =
                {
                    OffScreenPlain = true,
                    VideoMemory = true
                },
                Width = MAP_WIDTH_CELLS * CELL_SIZE,
                Height = MAP_HEIGHT_CELLS * CELL_SIZE
            };
            MapSurface = new Surface(ddSurfaceDesc2, _fDirectDraw);

            BackSurface.ColorFill(Color.Black);
        }
Beispiel #38
0
        private void RenderSun(DrawArgs drawArgs)
        {
            Point3d sunPosition = -SunCalculator.GetGeocentricPosition(TimeKeeper.CurrentTimeUtc);

            Point3d sunSpherical = MathEngine.CartesianToSpherical(sunPosition.X, sunPosition.Y, sunPosition.Z);
            sunPosition = MathEngine.SphericalToCartesian(
                Angle.FromRadians(sunSpherical.Y),
                Angle.FromRadians(sunSpherical.Z),
                150000000000);

            Point3d sunVector = new Point3d(sunPosition.X, sunPosition.Y, sunPosition.Z);

            Frustum viewFrustum = new Frustum();

            float aspectRatio = (float)drawArgs.WorldCamera.Viewport.Width / drawArgs.WorldCamera.Viewport.Height;
            Matrix4d projectionMatrix = Matrix4d.PerspectiveFovRH(drawArgs.WorldCamera.Fov.Radians, aspectRatio, 1000.0, 300000000000);

            viewFrustum.Update(
                Matrix4d.Multiply(drawArgs.WorldCamera.AbsoluteWorldMatrix,
                Matrix4d.Multiply(drawArgs.WorldCamera.AbsoluteViewMatrix,
                    projectionMatrix)));

            if (!viewFrustum.ContainsPoint(sunVector))
                return;

            Point3d translationVector = new Point3d(
                (sunPosition.X - drawArgs.WorldCamera.ReferenceCenter.X),
                (sunPosition.Y - drawArgs.WorldCamera.ReferenceCenter.Y),
                (sunPosition.Z - drawArgs.WorldCamera.ReferenceCenter.Z));

            Point3d projectedPoint = drawArgs.WorldCamera.Project(translationVector);

            if (m_sunTexture == null)
            {
                m_sunTexture = ImageHelper.LoadTexture(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\Data\\sun.dds");
                m_sunSurfaceDescription = m_sunTexture.GetLevelDescription(0);
            }

            if (m_sprite == null)
            {
                m_sprite = new Sprite(drawArgs.device);
            }

            m_sprite.Begin(SpriteFlags.AlphaBlend);

            // Render icon
            float xscale = (float)m_sunWidth / m_sunSurfaceDescription.Width;
            float yscale = (float)m_sunHeight / m_sunSurfaceDescription.Height;
            m_sprite.Transform = Matrix.Scaling(xscale, yscale, 0);

            m_sprite.Transform *= Matrix.Translation((float)projectedPoint.X, (float)projectedPoint.Y, 0);
            m_sprite.Draw(m_sunTexture,
                new Vector3(m_sunSurfaceDescription.Width >> 1, m_sunSurfaceDescription.Height >> 1, 0),
                Vector3.Empty,
                System.Drawing.Color.FromArgb(253, 253, 200).ToArgb());

            // Reset transform to prepare for text rendering later
            m_sprite.Transform = Matrix.Identity;
            m_sprite.End();
        }
Beispiel #39
0
 /// <summary>
 /// Creates a new DDGraphic.
 /// </summary>
 /// <param name="file">File path of a graphic.</param>
 /// <param name="frameSize">Size of this DDGraphics frames.</param>
 /// <param name="desc">SurfaceDescription of this DDGraphic.</param>
 /// <param name="gameSurface">DDGameSurface this DDGraphic is to be created for.</param>
 public DDGraphic(string file, Size frameSize, SurfaceDescription desc, DDGameSurface gameSurface)
     : base(file, desc, gameSurface.Device)
 {
     _initGraphic(frameSize, -1);
 }
Beispiel #40
0
 private static void DrawExplosions()
 {
     Drawing.OurSprite.Begin(SpriteFlags.AlphaBlend);
     for (int i = 0; i < Explosions.AllExplosions.Count; i++)
     {
         Temp = Textures.allExplosions[Explosions.AllExplosions[i].Type][Explosions.AllExplosions[i].GetStageType()][Explosions.AllExplosions[i].Stage - 1].GetLevelDescription(0);
         Pos = new Vector3(Explosions.AllExplosions[i].X - WorkSpace.Space.X - Temp.Width / 2.0f + WorkSpace.DX, Explosions.AllExplosions[i].Y - WorkSpace.Space.Y - Temp.Height / 2.0f + WorkSpace.DY, 1);
         Rect = new Rectangle(0, 0, Temp.Width, Temp.Height);
         Tr = Matrix.Translation(Pos.X + Temp.Width / 2.0f, Pos.Y + Temp.Height / 2.0f, 1);
         Drawing.OurSprite.Transform = Matrix.Invert(Tr) * Matrix.RotationZ(Explosions.AllExplosions[i].Angle) * Tr;
         Drawing.OurSprite.Draw(Textures.allExplosions[Explosions.AllExplosions[i].Type][Explosions.AllExplosions[i].GetStageType()][Explosions.AllExplosions[i].Stage - 1], Rect, new Vector3(0, 0, 0), Pos, Color.White);
     }
     Drawing.OurSprite.End();
 }
Beispiel #41
0
 private static void DrawMinerals()
 {
     TransMineral[] minerals = AIUnits.GetTransMinerals();
     Drawing.OurSprite.Begin(SpriteFlags.AlphaBlend);
     foreach(TransMineral mineral in minerals)
     {
         Temp = Textures.minerals[mineral.T1][mineral.T2][mineral.T3].GetLevelDescription(0);
         Pos = new Vector3(mineral.Pozition.X - WorkSpace.Space.X - Temp.Width / 2 + WorkSpace.DX, mineral.Pozition.Y - WorkSpace.Space.Y - Temp.Height / 2 + WorkSpace.DY, 1);
         Rect = new Rectangle(0, 0, Temp.Width, Temp.Height);
         Tr = Matrix.Translation(Pos.X + Temp.Width / 2.0f, Pos.Y + Temp.Height / 2.0f, 1);
         Drawing.OurSprite.Transform = Matrix.Invert(Tr) * Matrix.RotationZ(mineral.Angle) * Tr;
         Drawing.OurSprite.Draw(Textures.minerals[mineral.T1][mineral.T2][mineral.T3], Rect, new Vector3(0, 0, 0), Pos, Color.White);
     }
     Drawing.OurSprite.End();
 }
Beispiel #42
0
        private void Initialize3DEnvironment()
        {
            DisplayAdapter adapterInfo = graphicsSettings.DisplayAdapter;
            DisplayDevice deviceInfo = graphicsSettings.DisplayDevice;

            isWindowed = graphicsSettings.IsWindowed;

            // Prepare window for possible windowed/fullscreen change
            // AdjustWindowForChange();

            // Set up the presentation parameters
            RefreshPresentParameters();

            if(deviceInfo.Caps.PrimitiveMiscCaps.IsNullReference)
            {
                // Warn user about null ref device that can't render anything
                throw new ApplicationException("null reference device");
            }

            CreateFlags createFlags = new CreateFlags();
            switch(graphicsSettings.VertexProcessingType)
            {
                case VertexProcessingType.Software:
                    createFlags = CreateFlags.SoftwareVertexProcessing;
                    break;
                case VertexProcessingType.Mixed:
                    createFlags = CreateFlags.MixedVertexProcessing;
                    break;
                case VertexProcessingType.Hardware:
                    createFlags = CreateFlags.HardwareVertexProcessing;
                    break;
                case VertexProcessingType.PureHardware:
                    createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice;
                    break;
                default:
                    throw new ApplicationException("Unable to determine vertex processing method.");
            }

            // Create the device
            device = new Device(graphicsSettings.AdapterOrdinal,
                graphicsSettings.DisplayDevice.DeviceType,
                this.viewport,
                createFlags,
                this.presentParameters);

            if( device != null )
            {
                // Cache our local objects
                renderStates = device.RenderState;
                samplerStates = device.SamplerState;
                textureStates = device.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(graphicsSettings.IsWindowed && (this.viewport is System.Windows.Forms.Form))
                {
                    // Make sure main window isn't topmost, so error message is visible
                    this.viewport.Location = new System.Drawing.Point(rectWindowBounds.Left, rectWindowBounds.Top);
                    this.viewport.Size = new System.Drawing.Size(( rectWindowBounds.Right - rectWindowBounds.Left ), ( rectWindowBounds.Bottom - rectWindowBounds.Top));
                }

                // Store device Caps
                graphicsCaps = device.DeviceCaps;
                behavior = createFlags;

                // Store render target surface desc
                Surface BackBuffer = device.GetBackBuffer(0,0, BackBufferType.Mono);
                backBufferDesc = BackBuffer.Description;
                BackBuffer.Dispose();
                BackBuffer = null;

                // Set up the fullscreen cursor
                if(showFullScreenCursor && !graphicsSettings.IsWindowed)
                {
                    System.Windows.Forms.Cursor ourCursor = this.viewport.Cursor;
                    device.SetCursor(ourCursor, true);
                    device.ShowCursor(true);
                }

                // Confine cursor to fullscreen window
                if(clipFullScreenCursor)
                {
                    if (!isWindowed)
                    {
                        System.Drawing.Rectangle rcWindow = this.viewport.ClientRectangle;
                    }
                }

                // Setup the event handlers for our device
                device.DeviceLost += InvalidateDeviceObjects;
                device.DeviceReset += RestoreDeviceObjects;
                device.Disposing += DeleteDeviceObjects;
                device.DeviceResizing += new CancelEventHandler(EnvironmentResized);

                // Initialize the app's device-dependent objects
                try
                {
                    if(InitDeviceObjects != null)
                        InitDeviceObjects(null, null);

                    if(RestoreDeviceObjects != null)
                        RestoreDeviceObjects(null, null);

                    return;
                }
                catch
                {
                    // Cleanup before we try again
                    if(InvalidateDeviceObjects != null)
                        InvalidateDeviceObjects(null, null);

                    if(DeleteDeviceObjects != null)
                        DeleteDeviceObjects(null, null);

                    device.Dispose();
                    device = null;

                    if(this.viewport.Disposing)
                        return;
                }
            }

            //	HACK: removed fallback to reference rasterizer
            /*
            // If that failed, fall back to the reference rasterizer
            if( deviceInfo.DevType == Direct3D.DeviceType.Hardware )
            {
                if (FindBestWindowedMode(false, true))
                {
                    isWindowed = true;
                    if(viewport is System.Windows.Forms.Form)
                    {
                        // Make sure main window isn't topmost, so error message is visible
                        this.viewport.Location = new System.Drawing.Point(windowBoundsRect.Left, windowBoundsRect.Top);
                        this.viewport.Size = new System.Drawing.Size(( windowBoundsRect.Right - windowBoundsRect.Left ), ( windowBoundsRect.Bottom - windowBoundsRect.Top));
                        //AdjustWindowForChange();
                    }

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

                    Initialize3DEnvironment();
                }
            }
            */
        }
        private bool isDXT1a(SurfaceDescription sd, byte[] data)
        {
            int blocks = (sd.Width * sd.Height) >> 4;

            for (int i = 0; i != blocks; ++i) {
                int k = 128 + 8 * i;
                uint c0 = (uint)(data[k + 0] | (data[k + 1] << 8));
                uint c1 = (uint)(data[k + 2] | (data[k + 3] << 8));
                uint b = (uint)(data[k + 4] | (data[k + 5] << 8) | (data[k + 6] << 16) | (data[k + 7] << 24));

                if (c0 <= c1 && ((b & 0x55555555) & (b >> 1)) != 0)
                    return true;
            }

            return false;
        }
Beispiel #44
0
        private static void DrawTowers()
        {
            TransTower[] towers = AIUnits.GetTransTowers();
            Drawing.OurSprite.Begin(SpriteFlags.AlphaBlend);
            foreach(TransTower tower in towers)
            {
                // Base
                Temp = Textures.constrTowerBase[tower.TBaseIndex].GetLevelDescription(0);
                Pos = new Vector3(tower.Pozition.X - WorkSpace.Space.X - Temp.Width / 2.0f + WorkSpace.DX, tower.Pozition.Y - WorkSpace.Space.Y - Temp.Height / 2.0f + WorkSpace.DY, 1);
                Rect = new Rectangle(0, 0, Temp.Width, Temp.Height);
                Tr = Matrix.Translation(Pos.X + Temp.Width / 2.0f, Pos.Y + Temp.Height / 2.0f, 1);
                Drawing.OurSprite.Transform = Matrix.Invert(Tr) * Matrix.RotationZ(tower.Angle) * Tr;
                Drawing.OurSprite.Draw(Textures.constrTowerBase[tower.TBaseIndex], Rect, new Vector3(0, 0, 0), Pos, Color.White);

                // Turret
                Temp = Textures.constrTowerTurrets[tower.TTurretIndex].GetLevelDescription(0);
                Pos = new Vector3(tower.Pozition.X - WorkSpace.Space.X - Temp.Width / 2.0f + WorkSpace.DX, tower.Pozition.Y - WorkSpace.Space.Y - Temp.Height / 2.0f + WorkSpace.DY, 1);
                Rect = new Rectangle(0, 0, Temp.Width, Temp.Height);
                Tr = Matrix.Translation(Pos.X + Temp.Width / 2.0f, Pos.Y + Temp.Height / 2.0f, 1);
                Drawing.OurSprite.Transform = Matrix.Invert(Tr) * Matrix.RotationZ(tower.TurretAngle) * Tr;
                Drawing.OurSprite.Draw(Textures.constrTowerTurrets[tower.TTurretIndex], Rect, new Vector3(0, 0, 0), Pos, Color.White);
            }
            Drawing.OurSprite.End();
        }
		private void m_RefreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
            try
            {
                if (isUpdating)
                    return;

                isUpdating = true;

                if (m_ImageUri == null)
                    return;

                if (m_ImageUri.ToLower().StartsWith("http://"))
                {
                    bool forceDownload = false;
                    if (m_SaveFilePath == null)
                    {
                        // TODO: hack, need to get the correct cache directory
                        m_SaveFilePath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\Cache\\PictureBoxImages\\temp";
                        forceDownload = true;
                    }
                    System.IO.FileInfo saveFile = new System.IO.FileInfo(m_SaveFilePath);

                    if (forceDownload || !saveFile.Exists || (m_RefreshTime > 0 && saveFile.LastWriteTime.Subtract(System.DateTime.Now) > TimeSpan.FromSeconds(m_RefreshTime)))
                    {
                        //download it
                        try
                        {
                            WorldWind.Net.WebDownload webDownload = new WorldWind.Net.WebDownload(m_ImageUri);
                            webDownload.DownloadType = WorldWind.Net.DownloadType.Unspecified;

                            if (!saveFile.Directory.Exists)
                                saveFile.Directory.Create();

                            webDownload.DownloadFile(m_SaveFilePath);
                        }
                        catch { }
                    }
                }
                else
                {
                    m_SaveFilePath = m_ImageUri;
                }

                if (m_ImageTexture != null && !m_ImageTexture.Disposed)
                {
                    m_ImageTexture.Dispose();
                    m_ImageTexture = null;
                }

                if (!System.IO.File.Exists(m_SaveFilePath))
                {
                    displayText = "Image Not Found";
                    return;
                }

                if (LoadAsUncompressed)
                {
                    m_ImageTexture = TextureLoader.FromFile(DrawArgs.Device, m_SaveFilePath, 0, 0, 1, 0, Format.Unknown, Pool.Managed, Filter.None, Filter.None, 0);
                }
                else
                {
                    m_ImageTexture = ImageHelper.LoadTexture(m_SaveFilePath);
                }
                m_surfaceDescription = m_ImageTexture.GetLevelDescription(0);

                int width = ClientSize.Width;
                int height = ClientSize.Height;

                if (ClientSize.Width == 0)
                {
                    width = m_surfaceDescription.Width;
                }
                if (ClientSize.Height == 0)
                {
                    height = m_surfaceDescription.Height;
                }

                if (ParentWidget is Widgets.Form && SizeParentToImage)
                {
                    Widgets.Form parentForm = (Widgets.Form)ParentWidget;
                    parentForm.ClientSize = new System.Drawing.Size(width, height + parentForm.HeaderHeight);
                }
                else if(SizeParentToImage)
                {
                    ParentWidget.ClientSize = new System.Drawing.Size(width, height);
                }
                

                ClientSize = new System.Drawing.Size(width, height);
                m_currentImageUri = m_ImageUri;

                IsLoaded = true;
                isUpdating = false;
                displayText = null;
                if (m_RefreshTime == 0 && m_RefreshTimer.Enabled)
                    m_RefreshTimer.Stop();

            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
		}
        private void CreateSurfaces()
        {
            SurfaceDescription desc = new SurfaceDescription();
            SurfaceCaps caps = new SurfaceCaps();

            localClipper = new Clipper(localDevice);
            localClipper.Window = owner;

            desc.SurfaceCaps.PrimarySurface = true;
            if (null != surfacePrimary)
                surfacePrimary.Dispose();
            surfacePrimary = new Surface(desc, localDevice);
            surfacePrimary.Clipper = localClipper;

            desc.Clear();
            desc.SurfaceCaps.OffScreenPlain = true;
            desc.Width = surfacePrimary.SurfaceDescription.Width;
            desc.Height = surfacePrimary.SurfaceDescription.Height;

            if (null != surfaceSecondary)
                surfaceSecondary.Dispose();
            surfaceSecondary = new Surface(desc, localDevice);
            surfaceSecondary.FillStyle = 0;
        }
Beispiel #47
0
		/// <summary>
		/// Initialises the overlay with the specified Boundings
		/// </summary>
		public void Initialise() {
			mDevice = new Device();
			mDevice.SetCooperativeLevel( null, CooperativeLevelFlags.Normal ); //Only a overlay..

			//Create Primary
			SurfaceDescription desc = new SurfaceDescription();
			desc.SurfaceCaps.PrimarySurface = true;
			mPrimary = new Surface( desc, mDevice );

			//Create buffer
			desc = new SurfaceDescription();
			desc.Width = Boundings.Width;
			desc.Height = Boundings.Height;
			desc.BackBufferCount = 1;
			desc.SurfaceCaps.Flip = true;
			desc.SurfaceCaps.Overlay = true;
			desc.SurfaceCaps.Complex = true;
			desc.SurfaceCaps.VideoMemory = true;

			//Try which pixelformat works
			do {
				try {
					desc.PixelFormatStructure = GetPixelFormat( mPixelFormat );
					mBuffer = new Surface( desc, mDevice );
				} catch( InvalidPixelFormatException ) {
					mPixelFormat++;
				} catch( DirectXException ex ) {
					System.Diagnostics.Debug.WriteLine( ex );
					mBuffer = null;
					break;
				}
			} while( mBuffer == null && Enum.IsDefined( typeof( EPixelFormat ), mPixelFormat ) ); //Stop if a valid format is found or no one is left

			if( mBuffer == null || Enum.IsDefined( typeof( EPixelFormat ), mPixelFormat ) == false ) {
				mPixelFormat = EPixelFormat.RGB32; // reset Format
				mBuffer = null;
				throw new GraphicsException( "Could not create overlay - Either your graphic card does not support any of the available pixelformats or overlays in general." );
			}

			//Create backbuffer
			SurfaceCaps caps = new SurfaceCaps();
			caps.BackBuffer = true;
			mBackBuffer = mBuffer.GetAttachedSurface( caps );

			//Create rendertarget
			//Bitmap works on every graphicscard, a RGB-Surface wont
			mRenderTarget = new Bitmap( Boundings.Width, Boundings.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb );

			CreateFlags();
		}
        /// <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 PixelDataProvider(Surface sf)
     : base()
 {
     this._surf = sf;
     this._sd = sf.Description;
 }
Beispiel #50
0
 public DeviceEventArgs(Device d, SurfaceDescription desc)
 {
     Device = d;
     BackBufferDescription = desc;
 }
Beispiel #51
0
 /// <summary>Called when the device has been reset</summary>
 public void OnResetDevice(SurfaceDescription desc)
 {
     arc.SetWindow(desc.Width, desc.Height);
 }
Beispiel #52
0
		/// <summary>
		/// Create an AutoTexture
		/// </summary>
		public AutoTexture(Direct3d d3d, Texture texture)
		{
			mTexture = texture;
			mD3d = d3d;
			mSurfDesc = mTexture.GetLevelDescription(0);
			d3d.DxLost += new Direct3d.DxDirect3dDelegate(d3d_DxLost);
			d3d.DxRestore += new Direct3d.DxDirect3dDelegate(d3d_DxRestore);
		}
Beispiel #53
0
 /// <summary>
 /// Creates a new DDGraphic.
 /// </summary>
 /// <param name="stream">Stream where the graphic is located.</param>
 /// <param name="frameSize">Size of this DDGraphics frames.</param>
 /// <param name="desc">SurfaceDescription of this DDGraphic.</param>
 /// <param name="gameSurface">DDGameSurface this DDGraphic is to be created for.</param>
 public DDGraphic(Stream stream, Size frameSize, SurfaceDescription desc, DDGameSurface gameSurface)
     : base(stream, desc, gameSurface.Device)
 {
     _initGraphic(frameSize, -1);
 }
Beispiel #54
0
        public override void Initialize(DrawArgs drawArgs)
        {
            try {
                m_Sprite = new Sprite(drawArgs.Device);
                if (m_IconFilePath != null
                    && File.Exists(m_IconFilePath)) {
                    m_IconTexture = ImageHelper.LoadIconTexture(m_IconFilePath);
                    m_IconTextureDescription = m_IconTexture.GetLevelDescription(0);
                }
                loadShapeFile(m_ShapeFilePath);

                if ((m_ShapeTileArgs.ShowLabels && m_ShapeTileArgs.DataKey != null)
                    || m_IconTexture != null) {
                    foreach (ShapeFileRecord record in m_ShapeTileArgs.ShapeRecords) {
                        if (record.Value != null) {
                            if (record.Point != null) {
                                Shapefile_Point p = new Shapefile_Point();
                                p.X = record.Point.X;
                                p.Y = record.Point.Y;
                                p.Tag = record.Value;
                                m_LabelList.Add(p);
                            }
                            else if (record.MultiPoint != null) {
                                Shapefile_Point p = new Shapefile_Point();
                                p.X = 0.5*(record.MultiPoint.BoundingBox.West + record.MultiPoint.BoundingBox.East);
                                p.Y = 0.5*(record.MultiPoint.BoundingBox.North + record.MultiPoint.BoundingBox.South);
                                p.Tag = record.Value;
                                m_LabelList.Add(p);
                            }
                            else if (record.PolyLine != null) {
                                Shapefile_Point p = new Shapefile_Point();
                                p.X = 0.5*(record.PolyLine.BoundingBox.West + record.PolyLine.BoundingBox.East);
                                p.Y = 0.5*(record.PolyLine.BoundingBox.North + record.PolyLine.BoundingBox.South);
                                p.Tag = record.Value;
                                m_LabelList.Add(p);
                            }
                            else if (record.Polygon != null) {
                                Shapefile_Point p = new Shapefile_Point();
                                p.X = 0.5*(record.Polygon.BoundingBox.West + record.Polygon.BoundingBox.East);
                                p.Y = 0.5*(record.Polygon.BoundingBox.North + record.Polygon.BoundingBox.South);
                                p.Tag = record.Value;
                                m_LabelList.Add(p);
                            }
                        }
                    }
                }
            }
            catch (Exception ex) {
                Log.Write(ex);
            }
            finally {
                Inited = true;
            }
        }
Beispiel #55
0
 /// <summary>
 /// Creates a new DDGraphic.
 /// </summary>
 /// <param name="file">File path of a graphic.</param>
 /// <param name="transColor">Transparency color to use (0x00RRGGBB format)</param>
 /// <param name="desc">SurfaceDescription of this DDGraphic.</param>
 /// <param name="gameSurface">DDGameSurface this DDGraphic is to be created for.</param>
 public DDGraphic(string file, int transColor, SurfaceDescription desc, DDGameSurface gameSurface)
     : base(file, desc, gameSurface.Device)
 {
     _initGraphic(Size.Empty, transColor);
 }
Beispiel #56
0
 private static void DrawBuildings()
 {
     TransBuilding[] buidings = AIUnits.GetTransBuildings();
     Drawing.OurSprite.Begin(SpriteFlags.AlphaBlend);
     foreach (TransBuilding building in buidings)
     {
         Temp = Textures.constrBuildings[building.TBuildingIndex].GetLevelDescription(0);
         Pos = new Vector3(building.Pozition.X - WorkSpace.Space.X - Temp.Width / 2.0f + WorkSpace.DX, building.Pozition.Y - WorkSpace.Space.Y - Temp.Height / 2.0f + WorkSpace.DY, 1);
         Rect = new Rectangle(0, 0, Temp.Width, Temp.Height);
         Tr = Matrix.Translation(Pos.X + Temp.Width / 2.0f, Pos.Y + Temp.Height / 2.0f, 1);
         Drawing.OurSprite.Transform = Matrix.Invert(Tr) * Matrix.RotationZ(building.Angle) * Tr;
         Drawing.OurSprite.Draw(Textures.constrBuildings[building.TBuildingIndex], Rect, new Vector3(0, 0, 0), Pos, Color.White);
     }
     Drawing.OurSprite.End();
 }
Beispiel #57
0
        private void m_RefreshTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isUpdating) {
                return;
            }

            isUpdating = true;

            if (m_ImageUri == null) {
                return;
            }

            if (m_ImageUri.ToLower().StartsWith("http://")) {
                if (m_SaveFilePath == null) {
                    return;
                }

                //download it
                try {
                    WebDownload webDownload = new WebDownload(m_ImageUri);
                    webDownload.DownloadType = DownloadType.Unspecified;

                    FileInfo saveFile = new FileInfo(m_SaveFilePath);
                    if (!saveFile.Directory.Exists) {
                        saveFile.Directory.Create();
                    }

                    webDownload.DownloadFile(m_SaveFilePath);
                }
                catch {}
            }
            else {
                m_SaveFilePath = m_ImageUri;
            }

            if (m_ImageTexture != null
                && !m_ImageTexture.Disposed) {
                m_ImageTexture.Dispose();
                m_ImageTexture = null;
            }

            if (!File.Exists(m_SaveFilePath)) {
                displayText = "Image Not Found";
                return;
            }

            m_ImageTexture = ImageHelper.LoadTexture(m_SaveFilePath);
            m_surfaceDescription = m_ImageTexture.GetLevelDescription(0);

            int width = ClientSize.Width;
            int height = ClientSize.Height;

            if (ClientSize.Width == 0) {
                width = m_surfaceDescription.Width;
            }
            if (ClientSize.Height == 0) {
                height = m_surfaceDescription.Height;
            }

            if (ParentWidget is Form) {
                Form parentForm = (Form) ParentWidget;
                parentForm.ClientSize = new Size(width, height + parentForm.HeaderHeight);
            }
            else {
                ParentWidget.ClientSize = new Size(width, height);
            }

            ClientSize = new Size(width, height);

            IsLoaded = true;
            isUpdating = false;
            displayText = null;
            if (m_RefreshTime == 0) {
                m_RefreshTimer.Stop();
            }
        }