예제 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="s"></param>
        /// <param name="pf"></param>
        /// <param name="surf"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public int GetIntPixel(Sdl.SDL_Surface s, Sdl.SDL_PixelFormat pf, IntPtr surf, int x, int y)
        {
            IntPtr ptr   = new IntPtr(s.pixels.ToInt32() + (y * s.pitch) + (x * pf.BytesPerPixel)); //* bytesPerPixel);
            int    value = 0;

            switch (pf.BytesPerPixel)
            {
            case 1:
                value = Marshal.ReadByte(ptr);
                break;

            case 2:
                value = Marshal.ReadInt16(ptr);
                break;

            case 3:
                value = MarshalHelper.ReadInt24(ptr);
                break;

            case 4:
                //value = Marshal.ReadInt32(ptr);
                break;
                //default:
                //throw new SdlException(Events.StringManager.GetString("UnknownBytesPerPixel", CultureInfo.CurrentUICulture));
            }
            return(value);
        }
예제 #2
0
        public void CreateRGBSurfaceAndFree()
        {
            int    rmask         = 0x00000000;
            int    gmask         = 0x00ff0000;
            int    bmask         = 0x0000ff00;
            int    amask         = 0x000000ff;
            IntPtr surfacePtr    = VideoSetup();
            IntPtr rgbSurfacePtr = Sdl.SDL_CreateRGBSurface(
                flags,
                width,
                height,
                bpp,
                rmask,
                gmask,
                bmask,
                amask);

            Sdl.SDL_Surface rgbSurface =
                (Sdl.SDL_Surface)Marshal.PtrToStructure(rgbSurfacePtr, typeof(Sdl.SDL_Surface));
            Assert.IsTrue(rgbSurface.w == width);
            Assert.IsTrue(rgbSurface.h == height);
            //Sdl.SDL_FreeSurface(surfacePtr);
            Sdl.SDL_FreeSurface(rgbSurfacePtr);
            //Sdl.SDL_FreeSurfaceInternal(rgbSurfacePtr);
            Assert.AreEqual(IntPtr.Zero, rgbSurfacePtr);
            Sdl.SDL_FreeSurface(surfacePtr);
        }
예제 #3
0
 internal Surface(IntPtr surface)
 {
     this.surfacePtrs[0] = surface;
     this.surface        = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.SurfacePtr(), typeof(Sdl.SDL_Surface));
     this.pixelFormat    = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(this.surface.format, typeof(Sdl.SDL_PixelFormat));
     this.SourceColorKey = Color.Magenta;
     this.ResetClipRect();
     this.currentSurfaceCount++;
 }
예제 #4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="w"></param>
 /// <param name="h"></param>
 /// <param name="newbpp"></param>
 public Surface(int w, int h, int newbpp)
 {
     bpp = newbpp;
     this.surfacePtrs[0] = Sdl.SDL_CreateRGBSurface(flags, w, h, bpp, 0, 0, 0, 0);
     this.surface        = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.SurfacePtr(), typeof(Sdl.SDL_Surface));
     pixelFormat         = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(this.surface.format, typeof(Sdl.SDL_PixelFormat));
     this.ResetClipRect();
     this.currentSurfaceCount++;
 }
예제 #5
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="filename"></param>
 public Surface(string filename)
 {
     this.surfacePtrs[0] = Tao.Sdl.SdlImage.IMG_Load(filename);
     this.surface        = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.SurfacePtr(), typeof(Sdl.SDL_Surface));
     this.pixelFormat    = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(this.surface.format, typeof(Sdl.SDL_PixelFormat));
     this.SourceColorKey = Color.Magenta;
     this.ResetClipRect();
     this.currentSurfaceCount++;
     this._filename = filename;
 }
예제 #6
0
        private int checkMask(Surface source, Sdl.SDL_Rect r, Color fill)
        {
            int col, pink1, pink2;

            String curSig   = "mask" + fill.ToArgb();
            int    curIndex = -1;

            for (int i = 1; i <= currentSurfaceCount; i++)
            {
                if (surfaceSignatures[i] == curSig)
                {
                    curIndex = i;
                }
            }

            if (curIndex == -1)
            {
                curIndex = currentSurfaceCount;
                surfacePtrs[curIndex] = Sdl.SDL_CreateRGBSurface(flags, r.w, r.h, bpp, 0, 0, 0, 0);

                Sdl.SDL_Surface maskSurf = (Sdl.SDL_Surface)Marshal.PtrToStructure(surfacePtrs[curIndex], typeof(Sdl.SDL_Surface));
                col = Sdl.SDL_MapRGB(maskSurf.format, fill.R, fill.G, fill.B);

                pink1 = Sdl.SDL_MapRGB(source.surface.format, 255, 0, 255);
                pink2 = Sdl.SDL_MapRGB(maskSurf.format, 255, 0, 255);

                drect = new Sdl.SDL_Rect(0, 0, 1, 1);
                for (int xx = 0; xx < maskSurf.w; xx++)
                {
                    for (int yy = 0; yy < maskSurf.h; yy++)
                    {
                        drect.x = (short)xx;
                        drect.y = (short)yy;
                        if (this.GetIntPixel(source.SurfacePtr(), xx, yy) != pink1)
                        {
                            Sdl.SDL_FillRect(surfacePtrs[curIndex], ref drect, col);
                        }
                        else
                        {
                            Sdl.SDL_FillRect(surfacePtrs[curIndex], ref drect, pink2);
                        }
                    }
                }
                Tao.Sdl.Sdl.SDL_SetColorKey(surfacePtrs[curIndex], Sdl.SDL_SRCCOLORKEY | Sdl.SDL_RLEACCEL, pink1);
                surfaceSignatures[curIndex] = curSig;
                currentSurfaceCount++;
                Console.WriteLine("Created a new one at: " + curIndex + ", sig: " + curSig);
            }
            return(curIndex);
        }
예제 #7
0
        public void SDL_MapRGBA()
        {
            IntPtr surfacePtr = VideoSetup();

            Sdl.SDL_Surface surface =
                (Sdl.SDL_Surface)Marshal.PtrToStructure(surfacePtr, typeof(Sdl.SDL_Surface));
            surfaceFormatPtr = surface.format;
            Sdl.SDL_PixelFormat surfaceFormat =
                (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(surfaceFormatPtr, typeof(Sdl.SDL_PixelFormat));
            int result = Sdl.SDL_MapRGBA(surfaceFormatPtr, 255, 255, 0, 0);

            Assert.AreEqual(surfaceFormat.BitsPerPixel, 16);
            Assert.AreEqual(result, 65504);
            Sdl.SDL_FreeSurface(surfacePtr);
        }
예제 #8
0
        public override void EndScreenDeviceChange(string screenDeviceName, int clientWidth, int clientHeight)
        {
            this.screenDeviceName = screenDeviceName;
            OnScreenDeviceNameChanged();

            int flags = Sdl.SDL_OPENGL;

            if (willBeFullScreen)
            {
                flags |= Sdl.SDL_FULLSCREEN;
            }

            int           bitsPerPixel = 0;
            SurfaceFormat format;

            if (game.GraphicsDevice == null)
            {
                // TODO This cast should be tested against MS XNA
                GraphicsDeviceManager graphicsManager = (GraphicsDeviceManager)game.Services.GetService(typeof(IGraphicsDeviceManager));
                format = graphicsManager.PreferredBackBufferFormat;
            }
            else
            {
                format = game.GraphicsDevice.PresentationParameters.BackBufferFormat;
            }

            if (format == SurfaceFormat.Color || format == SurfaceFormat.Bgr32 || format == SurfaceFormat.Rgba32)
            {
                bitsPerPixel = 32;
            }
            // TODO add support for other surface formats

            IntPtr sdlSurfacePtr = Sdl.SDL_SetVideoMode(clientWidth, clientHeight, bitsPerPixel, flags);

            if (sdlSurfacePtr != IntPtr.Zero)
            {
                sdlSurface = (Sdl.SDL_Surface)Marshal.PtrToStructure(sdlSurfacePtr, typeof(Sdl.SDL_Surface));
            }

#warning SDL 1.2 doesn't support getting the window position, only the dimensions
            clientBounds.Width  = clientWidth;
            clientBounds.Height = clientHeight;

            OnClientSizeChanged();

            inTransition = false;
        }
        public void initFromSurface(IntPtr surf)
        {
            // Marshal in info
            Sdl.SDL_Surface managedSurf = (Sdl.SDL_Surface)Marshal.PtrToStructure(surf, typeof(Sdl.SDL_Surface));
            width  = managedSurf.w;
            height = managedSurf.h;

            IntPtr format = managedSurf.format;

            Sdl.SDL_PixelFormat managedFormat = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(format, typeof(Sdl.SDL_PixelFormat));

            if (managedFormat.BytesPerPixel == 4)
            {
                if (managedFormat.Rmask == 0x000000ff)
                {
                    texture_format = Gl.GL_RGBA;
                }
                else
                {
                    texture_format = Gl.GL_BGRA;
                }
            }
            else if (managedFormat.BytesPerPixel == 3)
            {
                if (managedFormat.Rmask == 0x000000ff)
                {
                    texture_format = Gl.GL_RGB;
                }
                else
                {
                    texture_format = Gl.GL_BGR;
                }
            }
            else
            {
                throw new Exception("Only true color textures supported.");
            }

            Gl.glGenTextures(1, out handle);
            Gl.glBindTexture(Gl.GL_TEXTURE_2D, handle);
            // Nearest neighbor scaling
            Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_NEAREST);
            Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_NEAREST);

            // Load texture data into video memory
            Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, managedFormat.BytesPerPixel, width, height, 0, texture_format, Gl.GL_UNSIGNED_BYTE, managedSurf.pixels);
        }
예제 #10
0
        static IntPtr veraSmall;                                              //The pointer to the font
        #endregion

        static void Draw()
        {
            Sdl.SDL_FillRect(screen, ref screenArea, 0);                                           //Clear for next draw cycle
            screenData = (Sdl.SDL_Surface)Marshal.PtrToStructure(screen, typeof(Sdl.SDL_Surface)); //Put the screen data in its place

            switch (Adventurer.gameState)
            {
            case GameState.OpeningMenu:
                Draw_Opening();
                break;

            case GameState.NameSelect:
                Draw_Name();
                break;

            case GameState.CreatureSelect:
                Draw_CreatureSel();
                break;

            case GameState.HelpMenu:
                Draw_Help();
                break;

            case GameState.MainGame:
                Draw_Main();
                break;

            case GameState.InventoryMenu:
                Draw_Inventory();
                break;

            case GameState.HealthMenu:
                Draw_Health();
                break;

            case GameState.WaitForPosition:
                Draw_GetPos();
                break;

            case GameState.EscapeMenu:
                Draw_Escape();
                break;
            }

            Sdl.SDL_Flip(screen); //Update screen
        } //Draws things to the screen
예제 #11
0
        public void SDL_GetRGB()
        {
            int    pixel      = 65504;
            IntPtr surfacePtr = VideoSetup();
            byte   r;
            byte   g;
            byte   b;

            Sdl.SDL_Surface surface =
                (Sdl.SDL_Surface)Marshal.PtrToStructure(surfacePtr, typeof(Sdl.SDL_Surface));
            surfaceFormatPtr = surface.format;
            //Sdl.SDL_PixelFormat surfaceFormat =
            //    (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(surfaceFormatPtr, typeof(Sdl.SDL_PixelFormat));
            Sdl.SDL_GetRGB(pixel, surfaceFormatPtr, out r, out g, out b);
            Assert.AreEqual(r, 255);
            Assert.AreEqual(g, 255);
            Assert.AreEqual(b, 0);
            Sdl.SDL_FreeSurface(surfacePtr);
        }
예제 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="pf"></param>
        public Surface(int w, int h, IntPtr pf)
        {
            if (pf == IntPtr.Zero)
            {
                this.surfacePtrs[0] = Sdl.SDL_CreateRGBSurface(flags, w, h, bpp, 0, 0, 0, 0);
                this.surface        = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.SurfacePtr(), typeof(Sdl.SDL_Surface));
                pixelFormat         = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(this.surface.format, typeof(Sdl.SDL_PixelFormat));
            }
            else
            {
                pixelFormat         = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(pf, typeof(Sdl.SDL_PixelFormat));
                this.surfacePtrs[0] = Sdl.SDL_CreateRGBSurface(flags, w, h, bpp, pixelFormat.Rmask, pixelFormat.Gmask, pixelFormat.Bmask, pixelFormat.Amask);
                this.surface        = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.SurfacePtr(), typeof(Sdl.SDL_Surface));
            }

            this.SourceColorKey = Color.Magenta;
            this.ResetClipRect();
            this.currentSurfaceCount++;
        }
예제 #13
0
        public Video()
        {
            m_Screen     = Sdl.SDL_SetVideoMode(640, 512, 32, (Sdl.SDL_SWSURFACE | Sdl.SDL_DOUBLEBUF | Sdl.SDL_ANYFORMAT));
            m_ScreenSurf = (Sdl.SDL_Surface)Marshal.PtrToStructure(m_Screen, typeof(Sdl.SDL_Surface));
            Sdl.SDL_PixelFormat format = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(m_ScreenSurf.format, typeof(Sdl.SDL_PixelFormat));

            for (int i = 0; i < 512; i++)
            {
                int b = ((i) & 0x7) * 0x49 >> 1;
                int r = ((i >> 3) & 0x7) * 0x49 >> 1;
                int g = ((i >> 6) & 0x7) * 0x49 >> 1;

                PALETTE[i] =
                    (r << format.Rshift & format.Rmask) |
                    (g << format.Gshift & format.Gmask) |
                    (b << format.Bshift & format.Bmask);
            }
            m_ScreenSurf.pitch /= 4;

            Sdl.SDL_WM_SetCaption("TurboSharp", null);

            m_VRAM      = new ushort[0x10000];
            m_SAT       = new SpriteAttribute[0x40];
            m_VCE       = new ushort[0x200];
            m_VCE_Index = 0;

            for (int i = 0; i < 0x40; i++)
            {
                m_SAT[i] = new SpriteAttribute();
            }

            m_RenderLine = 0;
            m_DoSAT_DMA  = false;
            m_WaitingIRQ = false;

            m_VCE_DotClock  = DotClock.MHZ_5;
            m_VDC_Increment = 1;

            m_VDC_BSY = false;  // We don't halt the CPU
        }
예제 #14
0
        /// <summary>
        /// Sets widow icon, with transparency where color matches sample point if
        /// mask is enabled. According to SDL documentation icon should be set
        /// before first call to SDL_SetVideoMode which occurs during the openGL
        /// initialization procedure when initializing GraphicsComponent.
        ///
        /// Image must be a 32x32 256 color bmp. In gimp this is is achieved by
        /// setting mode to indexed.
        /// </summary>
        /// <param name="file">Relative path from content folder</param>
        /// <param name="makeMask">Rather or not to generate a mask</param>
        /// <param name="mSample_x">X coordinate referenced to determine alpha</param>
        /// <param name="mSample_y">Y coordinate referenced to determine alpha</param>
        public void SetIcon(string file, bool makeMask = false, int mSample_x = 0, int mSample_y = 0)
        {
            // initialize SDL System (SDL must be started before can set WM icon, but normally would
            // not be before initialize is called)
            initializeSDLSystem();

            Debug.WriteLine("Setup Game Icon (should be before first call to SDL_SetVideoMode");
            //Set the icon of the game window
            IntPtr icon = Sdl.SDL_LoadBMP(file);

            byte[] mask = null;

            if (makeMask)
            {
                // Get image data from internal native struct to generate mask
                Sdl.SDL_Surface img = (Sdl.SDL_Surface)Marshal.PtrToStructure(icon, typeof(Sdl.SDL_Surface));

                int    len    = img.h * img.w;
                byte[] pixels = new byte[len];

                Marshal.Copy(img.pixels, pixels, 0, len);

                // reference used to determine if pixel is alpha, scanline for pixels
                // is img.w
                byte alpha_ref = pixels[mSample_x + mSample_y * img.w];

                // Generate mask, 8 pixels packed per byte most significant digit
                // leftmost pixel. Pixel is one byte (image indexed, 256 colored)
                mask = new byte[len / 8];
                for (int i = 0; i < len; i++)
                {
                    if (pixels[i] != pixels[0])
                    {
                        mask[i / 8] |= (byte)(1 << (7 - (i % 8)));
                    }
                }
            }

            Sdl.SDL_WM_SetIcon(icon, mask);
        }
예제 #15
0
        /*
         * Creates a window, initializes OpenGl settings, and updates the current height and width of the window.
         */
        private void initializeOpenGL()
        {
            //Center the window
            Sdl.SDL_putenv("SDL_VIDEO_CENTERED=center");

            //Create the window
            Debug.WriteLine("SDL_SetVideoMode Called");
            vidSurface = Sdl.SDL_SetVideoMode(((fullscreen) ? 1 : windowWidth), ((fullscreen) ? 0 : windowHeight), 32, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF | Sdl.SDL_HWSURFACE | ((fullscreen) ? Sdl.SDL_FULLSCREEN : 0));
            if (vidSurface == null)
            {
                throw new Exception("Error, could not set video mode.");
            }

            //Marshal in surface to obtain info
            Sdl.SDL_Surface managedSurface = (Sdl.SDL_Surface)Marshal.PtrToStructure(vidSurface, typeof(Sdl.SDL_Surface));
            pixFmt = managedSurface.format;

            //Current Dimensions of the window.
            this.width  = (short)managedSurface.w;
            this.height = (short)managedSurface.h;
            camera.setView();

            //Settings
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DOUBLEBUFFER, 1);
            Gl.glEnable(Gl.GL_TEXTURE_2D);
            Gl.glClearColor(0, 0, 0, 1);
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
            Gl.glViewport(0, 0, width, height);
            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glLoadIdentity();
            Gl.glOrtho(0.0f, width, height, 0.0f, -1.0f, 1.0f);
            Gl.glMatrixMode(Gl.GL_MODELVIEW);
            Gl.glLoadIdentity();
            Gl.glEnable(Gl.GL_BLEND);
            Gl.glDisable(Gl.GL_DEPTH_TEST);
            Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
        }
예제 #16
0
파일: Font.cs 프로젝트: spech66/LightFireCS
        public void Render(string text, Color color, Rect rect, FontVAlign vAlign, FontHAlign hAlign)
        {
            if (text == "")
            {
                return;
            }

            Sdl.SDL_Color sdlColor = new Sdl.SDL_Color();
            sdlColor.r = color.r;
            sdlColor.g = color.g;
            sdlColor.b = color.b;

            int w, h;

            IntPtr surfaceP = SdlTtf.TTF_RenderText_Solid(font, text, sdlColor);

            Sdl.SDL_Surface surface = (Sdl.SDL_Surface)Marshal.PtrToStructure(surfaceP, typeof(Sdl.SDL_Surface));

            double wT = System.Math.Pow(2, System.Math.Ceiling(System.Math.Log(surface.w) / System.Math.Log(2)));

            w = (int)(wT + 0.5);
            double hT = System.Math.Pow(2, System.Math.Ceiling(System.Math.Log(surface.h) / System.Math.Log(2)));

            h = (int)(hT + 0.5);

            IntPtr surfaceP2 = Sdl.SDL_CreateRGBSurface(0, w, h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, unchecked ((int)0xff000000));

            Sdl.SDL_Surface surface2 = (Sdl.SDL_Surface)Marshal.PtrToStructure(surfaceP2, typeof(Sdl.SDL_Surface));

            Sdl.SDL_BlitSurface(surfaceP, ref surface.clip_rect, surfaceP2, ref surface2.clip_rect);
            Sdl.SDL_Surface surface3 = (Sdl.SDL_Surface)Marshal.PtrToStructure(surfaceP2, typeof(Sdl.SDL_Surface));

            int texture = 0;

            //Gl.glGenTextures(1, new int[] { texture });
            int[] textureAr = new int[1];
            Gl.glGenTextures(1, textureAr);
            texture = textureAr[0];

            Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture);
            Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, Gl.GL_RGBA, w, h, Gl.GL_BGRA, Gl.GL_UNSIGNED_BYTE, surface3.pixels);

            Gl.glColor3ub(255, 255, 255);

            double x1, x2;
            double y1, y2;

            if (vAlign == FontVAlign.Left)
            {
                x1 = rect.X1;
                x2 = rect.X1 + w;
            }
            else if (vAlign == FontVAlign.Center)
            {
                double rX   = (rect.X2 - rect.X1) / 2 + rect.X1;
                double wMod = (surface3.w - surface.w) / 2;
                x1 = rX - surface3.w / 2 + wMod;
                x2 = rX + surface3.w / 2 + wMod;
            }
            else               /* Right */
            {
                x1 = rect.X2 - w;
                x2 = rect.X1;
            }

            if (hAlign == FontHAlign.Top)
            {
                y1 = rect.Y1;
                y2 = rect.Y1 + h;
            }
            else if (hAlign == FontHAlign.Middle)
            {
                double rY   = (rect.Y2 - rect.Y1) / 2 + rect.Y1;
                double hMod = (surface3.h - surface.h) / 2;
                y1 = rY - surface3.h / 2 + hMod;
                y2 = rY + surface3.h / 2 + hMod;
            }
            else               /* Bottom */
            {
                y1 = rect.Y2 - h;
                y2 = rect.Y2;
            }

            Gl.glBegin(Gl.GL_QUADS);
            Gl.glTexCoord2f(0.0f, 0.0f);    Gl.glVertex2d(x1, y1);
            Gl.glTexCoord2f(0.0f, 1.0f);    Gl.glVertex2d(x1, y2);
            Gl.glTexCoord2f(1.0f, 1.0f);    Gl.glVertex2d(x2, y2);
            Gl.glTexCoord2f(1.0f, 0.0f);    Gl.glVertex2d(x2, y1);
            Gl.glEnd();

            size.X1 = surface.w;
            size.Y1 = surface.h;

            Sdl.SDL_FreeSurface(surfaceP);
            Sdl.SDL_FreeSurface(surfaceP2);
            Gl.glDeleteTextures(1, new int[] { texture });
            TextureManager.Get().SetTexture("");
        }
예제 #17
0
        static void Main()
        {
            Sdl.SDL_Init(Sdl.SDL_INIT_VIDEO);

            g_pDisplaySurface = Sdl.SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, Sdl.SDL_DOUBLEBUF);
            g_DisplaySurface  = (Sdl.SDL_Surface)Marshal.PtrToStructure(g_pDisplaySurface, typeof(Sdl.SDL_Surface));

            Init();


            Sdl.SDL_ShowCursor(0);

            for (; ;)
            {
                if (Sdl.SDL_PollEvent(out g_Event) == 0)
                {
                    DoFrame();
                    Sdl.SDL_Flip(g_pDisplaySurface);

                    int forward = 0;
                    int strafe  = 0;

                    int    numkeys;
                    byte[] keys = Sdl.SDL_GetKeyState(out numkeys);
                    if (keys[Sdl.SDLK_w] != 0)
                    {
                        forward = 10;
                    }
                    if (keys[Sdl.SDLK_a] != 0)
                    {
                        strafe = -10;
                    }
                    if (keys[Sdl.SDLK_s] != 0)
                    {
                        forward = -10;
                    }
                    if (keys[Sdl.SDLK_d] != 0)
                    {
                        strafe = 10;
                    }

                    int  x, y;
                    byte state = Sdl.SDL_GetMouseState(out x, out y);

                    Voxlap.dpoint3d vec = new Voxlap.dpoint3d()
                    {
                        x = forward * or.ifo.x + strafe * or.ist.x,
                        y = forward * or.ifo.y + strafe * or.ist.y,
                        z = 0
                    };

                    or.ipo = Voxlap.ClipMove(or.ipo, vec, 8.0);

                    //or.ipo.x += forward * or.ifo.x;
                    //or.ipo.y += forward * or.ifo.y;

                    //or.ipo.x += strafe * or.ist.x;
                    //or.ipo.y += strafe * or.ist.y;
                }
                else
                {
                    if (g_Event.type == Sdl.SDL_MOUSEMOTION)
                    {
                        or.ifo = TodPoint3d(Voxlap.Rotate(
                                                ToPoint3d(or.ifo),
                                                new Voxlap.point3d()
                        {
                            z = 1
                        },
                                                (float)g_Event.motion.xrel / 100f));

                        or.ihe = TodPoint3d(Voxlap.Rotate(
                                                ToPoint3d(or.ihe),
                                                new Voxlap.point3d()
                        {
                            z = 1
                        },
                                                (float)g_Event.motion.xrel / 100f));

                        or.ist = TodPoint3d(Voxlap.Rotate(
                                                ToPoint3d(or.ist),
                                                new Voxlap.point3d()
                        {
                            z = 1
                        },
                                                (float)g_Event.motion.xrel / 100f));


                        float newangle = vertAngle + (float)-g_Event.motion.yrel / 100f;

                        if (newangle < Math.PI / 2 && newangle > -Math.PI / 2)
                        {
                            or.ifo = TodPoint3d(Voxlap.Rotate(
                                                    ToPoint3d(or.ifo),
                                                    ToPoint3d(or.ist),
                                                    (float)-g_Event.motion.yrel / 100f));

                            or.ihe = TodPoint3d(Voxlap.Rotate(
                                                    ToPoint3d(or.ihe),
                                                    ToPoint3d(or.ist),
                                                    (float)-g_Event.motion.yrel / 100f));

                            or.ist = TodPoint3d(Voxlap.Rotate(
                                                    ToPoint3d(or.ist),
                                                    ToPoint3d(or.ist),
                                                    (float)-g_Event.motion.yrel / 100f));

                            vertAngle = newangle;
                        }

                        Sdl.SDL_EventState(Sdl.SDL_MOUSEMOTION, Sdl.SDL_IGNORE);
                        Sdl.SDL_WarpMouse(SCREEN_WIDTH >> 1, SCREEN_HEIGHT >> 1);
                        Sdl.SDL_EventState(Sdl.SDL_MOUSEMOTION, Sdl.SDL_ENABLE);
                    }

                    if (g_Event.type == Sdl.SDL_MOUSEBUTTONDOWN)
                    {
                        if (g_Event.button.button == Sdl.SDL_BUTTON_WHEELUP)
                        {
                            or.ipo.z -= 10;
                        }

                        if (g_Event.button.button == Sdl.SDL_BUTTON_WHEELDOWN)
                        {
                            or.ipo.z += 10;
                        }
                    }

                    if (g_Event.type == Sdl.SDL_KEYDOWN)
                    {
                        if (g_Event.key.keysym.sym == Sdl.SDLK_ESCAPE)
                        {
                            break;
                        }
                    }

                    if (g_Event.type == Sdl.SDL_QUIT)
                    {
                        break;
                    }
                }
            }

            Sdl.SDL_Quit();
        }
예제 #18
0
        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="buf"></param>
        //public void SetPixels(Int32[] buf)
        //{
        //    Sdl.SDL_LockSurface(this.surfacePtrs[0]);
        //    Marshal.Copy(buf, 0, new IntPtr(this.surface.pixels.ToInt32()), buf.Length);
        //    Sdl.SDL_UnlockSurface(this.surfacePtrs[0]);
        //    /*
        //    try
        //    {
        //        int bytesPerPixel = this.pixelFormat.BytesPerPixel;
        //        //int pixels = this.surface.pixels.ToInt32() + point.X * bytesPerPixel;
        //        int pitch = this.surface.pitch;
        //        if (bytesPerPixel == 4)
        //        {
        //            //the buffer for a row of pixels.
        //            //Int32[] buffer = new Int32[colors.GetLength(0)];
        //            DateTime d = DateTime.Now;
        //            /*for (short x = 0; x < colors.GetLength(0); x++)
        //            {
        //                //gets only the pixels in the row that are required.
        //                for (short y = 0; y < colors.GetLength(1); y++)
        //                {
        //                    //converts the pixel to a color value.
        //                    //buffer[x] = Sdl.SDL_MapRGB(this.surface.format, colors[x, y].R, colors[x, y].G, colors[x, y].B);
        //                    SdlGfx.pixelRGBA(this.surfacePtrs[0], x, y, colors[x, y].R, colors[x, y].G, colors[x, y].B, 255);
        //                }
        //                //then copies them to the image.
        //                //Marshal.Copy(buffer, 0, new IntPtr(pixels + (y + point.Y) * pitch), buffer.Length);

        //            }

        //            Marshal.Copy(buf, 0, new IntPtr(pixels), buf.Length);
        //            Console.WriteLine((DateTime.Now - d).TotalMilliseconds + "ms");
        //        }
        //        else if (bytesPerPixel == 3)
        //        {
        //            //the buffer for a row of pixels.
        //            Int32[] buffer = new Int32[colors.GetLength(0)];
        //            for (int y = 0; y < colors.GetLength(1); ++y)
        //            {
        //                //gets only the pixels in the row that are required.
        //                for (int x = 0; x < buffer.Length; ++x)
        //                {
        //                    //converts the pixel to a color value.
        //                    buffer[x] = Sdl.SDL_MapRGB(this.surface.format, colors[x, y].R, colors[x, y].G, colors[x, y].B);
        //                }
        //                //then copies them to the image.
        //                MarshalHelper.CopyInt24(buffer, 0, new IntPtr(pixels + (y + point.Y) * pitch), buffer.Length);
        //            }
        //        }
        //        else if (bytesPerPixel == 2)
        //        {
        //            //the buffer for a row of pixels.
        //            Int16[] buffer = new Int16[colors.GetLength(0)];
        //            for (int y = 0; y < colors.GetLength(1); ++y)
        //            {
        //                //gets only the pixels in the row that are required.
        //                for (int x = 0; x < buffer.Length; ++x)
        //                {
        //                    //converts the pixel to a color value.
        //                    buffer[x] = (short)Sdl.SDL_MapRGB(this.surface.format, colors[x, y].R, colors[x, y].G, colors[x, y].B);
        //                }
        //                //then copies them to the image.
        //                Marshal.Copy(buffer, 0, new IntPtr(pixels + (y + point.Y) * pitch), buffer.Length);
        //            }
        //        }
        //        else if (bytesPerPixel == 1)
        //        {
        //            //the buffer for a row of pixels.
        //            Byte[] buffer = new Byte[colors.GetLength(0)];
        //            for (int y = 0; y < colors.GetLength(1); ++y)
        //            {
        //                //gets only the pixels in the row that are required.
        //                for (int x = 0; x < buffer.Length; ++x)
        //                {
        //                    //converts the pixel to a color value.
        //                    buffer[x] = (byte)Sdl.SDL_MapRGB(this.surface.format, colors[x, y].R, colors[x, y].G, colors[x, y].B);
        //                }
        //                //then copies them to the image.
        //                Marshal.Copy(buffer, 0, new IntPtr(pixels + (y + point.Y) * pitch), buffer.Length);
        //            }
        //        }
        //    }
        //    finally
        //    {
        //        Sdl.SDL_UnlockSurface(this.surfacePtrs[0]);
        //    }*/
        //}

        /// <summary>
        ///
        /// </summary>
        public void BuildNightImage()
        {
            /*byte[] src = new byte[16],src2 = new byte[16], dst = new byte[16];
             * for (int i = 0; i < 16; i++)
             * {
             *  src[i] = (byte)i;
             *  src2[i] = 4;
             * }
             * SdlGfx.SDL_imageFilterDiv(src, src2, dst, 16);*/


            if (this.pixelFormat.BytesPerPixel < 3)
            {
                this.mask           = Sdl.SDL_CreateRGBSurface(flags, this.surface.w, this.surface.h, bpp, 0, 0, 0, 0);
                surface             = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.mask, typeof(Sdl.SDL_Surface));
                this.surfacePtrs[0] = Sdl.SDL_ConvertSurface(this.surfacePtrs[0], surface.format, flags);
                surface             = (Sdl.SDL_Surface)Marshal.PtrToStructure(this.surfacePtrs[0], typeof(Sdl.SDL_Surface));
                pixelFormat         = (Sdl.SDL_PixelFormat)Marshal.PtrToStructure(surface.format, typeof(Sdl.SDL_PixelFormat));
                Sdl.SDL_FreeSurface(this.mask);
            }

            Sdl.SDL_LockSurface(this.surfacePtrs[0]);
            try
            {
                int bytesPerPixel = this.pixelFormat.BytesPerPixel;
                int pixels        = this.surface.pixels.ToInt32();// +point.X * bytesPerPixel;
                int pitch         = this.surface.pitch;
                //These 3 �if� blocks are a perfect candidate for generics unfortunately C#
                //does not have the required constrains for this case. So I�m reduced to copying code.

                /*if (bytesPerPixel == 4)
                 * {
                 *  //the buffer for a row of pixels.
                 *  Int32[] buffer = new Int32[colors.GetLength(0)];
                 *  for (int y = 0; y < colors.GetLength(1); ++y)
                 *  {
                 *      //gets only the pixels in the row that are required.
                 *      for (int x = 0; x < buffer.Length; ++x)
                 *      {
                 *          //converts the pixel to a color value.
                 *          buffer[x] = GetColorValue(colors[x, y]);
                 *      }
                 *      //then copies them to the image.
                 *      Marshal.Copy(buffer, 0, new IntPtr(pixels + (y + point.Y) * pitch), buffer.Length);
                 *  }
                 * }
                 * else*/
                if (bytesPerPixel >= 3)
                {
                    //the buffer for a row of pixels.
                    Int32[] buffer = new Int32[this.surface.w], original = new Int32[this.surface.w];
                    for (int y = 0; y < this.surface.h; ++y)
                    {
                        if (bytesPerPixel == 3)
                        {
                            MarshalHelper.CopyInt24(new IntPtr(pixels + y * pitch), original, 0, buffer.Length);
                        }
                        else
                        {
                            Marshal.Copy(new IntPtr(pixels + y * pitch), original, 0, buffer.Length);
                        }
                        //gets only the pixels in the row that are required.
                        for (int x = 0; x < buffer.Length; ++x)
                        {
                            //converts the pixel to a color value.
                            Int32 lower24 = original[x] & 0x00FFFFFF;

                            if (lower24 == Sdl.SDL_MapRGB(this.surface.format, 8, 0, 0))
                            {
                                buffer[x] = (Int32)(original[x] & 0xFF000000) | (Int32)Sdl.SDL_MapRGB(this.surface.format, 255, 8, 8);
                            }
                            else
                            if (lower24 == Sdl.SDL_MapRGB(this.surface.format, 0, 8, 0))
                            {
                                buffer[x] = (Int32)(original[x] & 0xFF000000) | (Int32)Sdl.SDL_MapRGB(this.surface.format, 252, 243, 148);
                            }
                            else
                            if (lower24 == Sdl.SDL_MapRGB(this.surface.format, 0, 0, 8))
                            {
                                buffer[x] = (Int32)(original[x] & 0xFF000000) | (Int32)Sdl.SDL_MapRGB(this.surface.format, 255, 227, 99);
                            }
                            else
                            {
                                buffer[x] = (Int32)(original[x] & 0xFF000000) | (Int32)((original[x] & 0x00FCFCFC) >> 2);        // pix /= 4
                            }
                            if (x == 0 && y == 0)
                            {
                                this.colorKey = buffer[x];
                            }
                        }
                        //then copies them to the image.
                        if (bytesPerPixel == 3)
                        {
                            MarshalHelper.CopyInt24(buffer, 0, new IntPtr(pixels + y * pitch), buffer.Length);
                        }
                        else
                        {
                            Marshal.Copy(buffer, 0, new IntPtr(pixels + y * pitch), buffer.Length);
                        }
                    }
                }
                else if (bytesPerPixel == 2)
                {
                    /*//the buffer for a row of pixels.
                     * Int16[] buffer = new Int16[colors.GetLength(0)];
                     * for (int y = 0; y < colors.GetLength(1); ++y)
                     * {
                     *  //gets only the pixels in the row that are required.
                     *  for (int x = 0; x < buffer.Length; ++x)
                     *  {
                     *      //converts the pixel to a color value.
                     *      buffer[x] = (Int16)GetColorValue(colors[x, y]);
                     *  }
                     *  //then copies them to the image.
                     *  Marshal.Copy(buffer, 0, new IntPtr(pixels + (y + point.Y) * pitch), buffer.Length);
                     * }*/
                }
                else if (bytesPerPixel == 1)
                {
                    //the buffer for a row of pixels.
                    byte[] buffer = new byte[this.surface.w];
                    for (int y = 0; y < this.surface.h; ++y)
                    {
                        Marshal.Copy(new IntPtr(pixels + y * pitch), buffer, 0, buffer.Length);
                        //gets only the pixels in the row that are required.
                        for (int x = 0; x < buffer.Length; ++x)
                        {
                            //converts the pixel to a color value.
                            darken16((byte)Sdl.SDL_MapRGB(this.surface.format, 8, 0, 0),
                                     (byte)Sdl.SDL_MapRGB(this.surface.format, 0, 8, 0),
                                     (byte)Sdl.SDL_MapRGB(this.surface.format, 0, 0, 8),
                                     (byte)Sdl.SDL_MapRGB(this.surface.format, 255, 8, 8),
                                     (byte)Sdl.SDL_MapRGB(this.surface.format, 252, 243, 148),
                                     (byte)Sdl.SDL_MapRGB(this.surface.format, 255, 227, 99),
                                     0x33, ref buffer[x]);

                            if (x == 0 && y == 0)
                            {
                                this.colorKey = buffer[x];
                            }
                        }
                        //then copies them to the image.
                        Marshal.Copy(buffer, 0, new IntPtr(pixels + y * pitch), buffer.Length);
                    }
                }
                else
                {
                    //throw new SdlException(Events.StringManager.GetString("UnknownBytesPerPixel", CultureInfo.CurrentUICulture));
                }
            }
            finally
            {
                Sdl.SDL_UnlockSurface(this.surfacePtrs[0]);
            }
        }
예제 #19
0
        internal static void Main(string[] args)
        {
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                /// general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                /// Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                /// non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            SetPackageLookupDirectories();
            // command line arguments
            bool[] SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length != 0 && Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) == -1)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            // application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (Sdl.SDL_Init(Sdl.SDL_INIT_VIDEO) != 0)
            {
                MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // initialize sdl window
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DOUBLEBUFFER, 1);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DEPTH_SIZE, 16);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_RED_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_GREEN_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_BLUE_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_ALPHA_SIZE, 8);
            Sdl.SDL_ShowCursor(Sdl.SDL_ENABLE);
            // icon
            {
                string File = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.bmp");
                if (System.IO.File.Exists(File))
                {
                    IntPtr Bitmap = Sdl.SDL_LoadBMP(File);
                    if (Bitmap != null)
                    {
                        Sdl.SDL_Surface Surface  = (Sdl.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(Bitmap, typeof(Sdl.SDL_Surface));
                        int             ColorKey = Sdl.SDL_MapRGB(Surface.format, 0, 0, 255);
                        Sdl.SDL_SetColorKey(Bitmap, Sdl.SDL_SRCCOLORKEY, ColorKey);
                        Sdl.SDL_WM_SetIcon(Bitmap, null);
                    }
                }
            }
            // initialize camera
            ResetCamera();
            // create window
            Renderer.ScreenWidth  = 960;
            Renderer.ScreenHeight = 600;
            int    Bits  = 32;
            IntPtr video = Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF);

            if (video != IntPtr.Zero)
            {
                // create window
                Sdl.SDL_WM_SetCaption(Application.ProductName, null);
                // anisotropic filtering
                string[] Extensions = Gl.glGetString(Gl.GL_EXTENSIONS).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                for (int i = 0; i < Extensions.Length; i++)
                {
                    if (string.Compare(Extensions[i], "GL_EXT_texture_filter_anisotropic", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        float n; Gl.glGetFloatv(Gl.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, out n);
                        Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n);
                        break;
                    }
                }
                if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0)
                {
                    Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                    Interface.CurrentOptions.AnisotropicFilteringLevel   = 0;
                    Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering;
                }
                else
                {
                    Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum;
                    Interface.CurrentOptions.Interpolation             = TextureManager.InterpolationMode.TrilinearMipmapped;
                }
                // module initialization
                Renderer.Initialize();
                Renderer.InitializeLighting();
                Sdl.SDL_GL_SwapBuffers();
                Fonts.Initialize();
                UpdateViewport();
                // command line arguments
                for (int i = 0; i < args.Length; i++)
                {
                    if (!SkipArgs[i] && System.IO.File.Exists(args[i]))
                    {
                        try {
                            ObjectManager.UnifiedObject o = ObjectManager.LoadObject(args[i], System.Text.Encoding.UTF8, ObjectManager.ObjectLoadMode.Normal, false, false, false);
                            ObjectManager.CreateObject(o, new World.Vector3D(0.0, 0.0, 0.0), new World.Transformation(0.0, 0.0, 0.0), new World.Transformation(0.0, 0.0, 0.0), true, 0.0, 0.0, 25.0, 0.0);
                        } catch (Exception ex) {
                            Interface.AddMessage(Interface.MessageType.Critical, false, "Unhandled error (" + ex.Message + ") encountered while processing the file " + args[i] + ".");
                        }
                        Array.Resize <string>(ref Files, Files.Length + 1);
                        Files[Files.Length - 1] = args[i];
                    }
                }
                ObjectManager.InitializeVisibility();
                ObjectManager.FinishCreatingObjects();
                ObjectManager.UpdateVisibility(0.0, true);
                ObjectManager.UpdateAnimatedWorldObjects(0.01, true);
                UpdateCaption();
                LastTicks = Sdl.SDL_GetTicks();
                // loop
                while (!Quit)
                {
                    int    ticks       = Sdl.SDL_GetTicks();
                    double timeElapsed = 0.001 * (double)(ticks - LastTicks);
                    if (timeElapsed < 0.0001)
                    {
                        timeElapsed = 0.0001;
                    }
                    LastTicks = ticks;
                    DateTime time = DateTime.Now;
                    Game.SecondsSinceMidnight = (double)(3600 * time.Hour + 60 * time.Minute + time.Second) + 0.001 * (double)time.Millisecond;
                    ObjectManager.UpdateAnimatedWorldObjects(timeElapsed, false);
                    ProcessEvents();
                    if (ReducedMode)
                    {
                        System.Threading.Thread.Sleep(125);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(1);
                    }
                    bool updatelight = false;
                    bool keep        = false;
                    // rotate x
                    if (RotateX == 0)
                    {
                        double d = (1.0 + Math.Abs(RotateXSpeed)) * timeElapsed;
                        if (RotateXSpeed >= -d & RotateXSpeed <= d)
                        {
                            RotateXSpeed = 0.0;
                        }
                        else
                        {
                            RotateXSpeed -= (double)Math.Sign(RotateXSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (1.0 + 1.0 - 1.0 / (1.0 + RotateXSpeed * RotateXSpeed)) * timeElapsed;
                        double m = 1.0;
                        RotateXSpeed += (double)RotateX * d;
                        if (RotateXSpeed < -m)
                        {
                            RotateXSpeed = -m;
                        }
                        else if (RotateXSpeed > m)
                        {
                            RotateXSpeed = m;
                        }
                    }
                    if (RotateXSpeed != 0.0)
                    {
                        double cosa = Math.Cos(RotateXSpeed * timeElapsed);
                        double sina = Math.Sin(RotateXSpeed * timeElapsed);
                        World.Rotate(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z, 0.0, 1.0, 0.0, cosa, sina);
                        World.Rotate(ref World.AbsoluteCameraUp.X, ref World.AbsoluteCameraUp.Y, ref World.AbsoluteCameraUp.Z, 0.0, 1.0, 0.0, cosa, sina);
                        World.Rotate(ref World.AbsoluteCameraSide.X, ref World.AbsoluteCameraSide.Y, ref World.AbsoluteCameraSide.Z, 0.0, 1.0, 0.0, cosa, sina);
                        keep = true;
                    }
                    // rotate y
                    if (RotateY == 0)
                    {
                        double d = (1.0 + Math.Abs(RotateYSpeed)) * timeElapsed;
                        if (RotateYSpeed >= -d & RotateYSpeed <= d)
                        {
                            RotateYSpeed = 0.0;
                        }
                        else
                        {
                            RotateYSpeed -= (double)Math.Sign(RotateYSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (1.0 + 1.0 - 1.0 / (1.0 + RotateYSpeed * RotateYSpeed)) * timeElapsed;
                        double m = 1.0;
                        RotateYSpeed += (double)RotateY * d;
                        if (RotateYSpeed < -m)
                        {
                            RotateYSpeed = -m;
                        }
                        else if (RotateYSpeed > m)
                        {
                            RotateYSpeed = m;
                        }
                    }
                    if (RotateYSpeed != 0.0)
                    {
                        double cosa = Math.Cos(RotateYSpeed * timeElapsed);
                        double sina = Math.Sin(RotateYSpeed * timeElapsed);
                        World.Rotate(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z, World.AbsoluteCameraSide.X, World.AbsoluteCameraSide.Y, World.AbsoluteCameraSide.Z, cosa, sina);
                        World.Rotate(ref World.AbsoluteCameraUp.X, ref World.AbsoluteCameraUp.Y, ref World.AbsoluteCameraUp.Z, World.AbsoluteCameraSide.X, World.AbsoluteCameraSide.Y, World.AbsoluteCameraSide.Z, cosa, sina);
                        keep = true;
                    }
                    // move x
                    if (MoveX == 0)
                    {
                        double d = (2.5 + Math.Abs(MoveXSpeed)) * timeElapsed;
                        if (MoveXSpeed >= -d & MoveXSpeed <= d)
                        {
                            MoveXSpeed = 0.0;
                        }
                        else
                        {
                            MoveXSpeed -= (double)Math.Sign(MoveXSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveXSpeed * MoveXSpeed)) * timeElapsed;
                        double m = 25.0;
                        MoveXSpeed += (double)MoveX * d;
                        if (MoveXSpeed < -m)
                        {
                            MoveXSpeed = -m;
                        }
                        else if (MoveXSpeed > m)
                        {
                            MoveXSpeed = m;
                        }
                    }
                    if (MoveXSpeed != 0.0)
                    {
                        World.AbsoluteCameraPosition.X += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.X;
                        World.AbsoluteCameraPosition.Y += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.Y;
                        World.AbsoluteCameraPosition.Z += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.Z;
                        keep = true;
                    }
                    // move y
                    if (MoveY == 0)
                    {
                        double d = (2.5 + Math.Abs(MoveYSpeed)) * timeElapsed;
                        if (MoveYSpeed >= -d & MoveYSpeed <= d)
                        {
                            MoveYSpeed = 0.0;
                        }
                        else
                        {
                            MoveYSpeed -= (double)Math.Sign(MoveYSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveYSpeed * MoveYSpeed)) * timeElapsed;
                        double m = 25.0;
                        MoveYSpeed += (double)MoveY * d;
                        if (MoveYSpeed < -m)
                        {
                            MoveYSpeed = -m;
                        }
                        else if (MoveYSpeed > m)
                        {
                            MoveYSpeed = m;
                        }
                    }
                    if (MoveYSpeed != 0.0)
                    {
                        World.AbsoluteCameraPosition.X += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.X;
                        World.AbsoluteCameraPosition.Y += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.Y;
                        World.AbsoluteCameraPosition.Z += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.Z;
                        keep = true;
                    }
                    // move z
                    if (MoveZ == 0)
                    {
                        double d = (2.5 + Math.Abs(MoveZSpeed)) * timeElapsed;
                        if (MoveZSpeed >= -d & MoveZSpeed <= d)
                        {
                            MoveZSpeed = 0.0;
                        }
                        else
                        {
                            MoveZSpeed -= (double)Math.Sign(MoveZSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveZSpeed * MoveZSpeed)) * timeElapsed;
                        double m = 25.0;
                        MoveZSpeed += (double)MoveZ * d;
                        if (MoveZSpeed < -m)
                        {
                            MoveZSpeed = -m;
                        }
                        else if (MoveZSpeed > m)
                        {
                            MoveZSpeed = m;
                        }
                    }
                    if (MoveZSpeed != 0.0)
                    {
                        World.AbsoluteCameraPosition.X += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.X;
                        World.AbsoluteCameraPosition.Y += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.Y;
                        World.AbsoluteCameraPosition.Z += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.Z;
                        keep = true;
                    }
                    // lighting
                    if (LightingRelative == -1)
                    {
                        LightingRelative = (double)LightingTarget;
                        updatelight      = true;
                    }
                    if (LightingTarget == 0)
                    {
                        if (LightingRelative != 0.0)
                        {
                            LightingRelative -= 0.5 * timeElapsed;
                            if (LightingRelative < 0.0)
                            {
                                LightingRelative = 0.0;
                            }
                            updatelight = true;
                            keep        = true;
                        }
                    }
                    else
                    {
                        if (LightingRelative != 1.0)
                        {
                            LightingRelative += 0.5 * timeElapsed;
                            if (LightingRelative > 1.0)
                            {
                                LightingRelative = 1.0;
                            }
                            updatelight = true;
                            keep        = true;
                        }
                    }
                    // continue
                    if (ReducedMode)
                    {
                        ReducedModeEnteringTime = ticks + 3000;
                    }
                    else
                    {
                        if (keep)
                        {
                            ReducedModeEnteringTime = ticks + 3000;
                        }
                        else if (ticks > ReducedModeEnteringTime)
                        {
                            ReducedMode = true;
                            World.AbsoluteCameraSide.Y = 0.0;
                            World.Normalize(ref World.AbsoluteCameraSide.X, ref World.AbsoluteCameraSide.Y, ref World.AbsoluteCameraSide.Z);
                            World.Normalize(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z);
                            World.AbsoluteCameraUp = World.Cross(World.AbsoluteCameraDirection, World.AbsoluteCameraSide);
                        }
                    }
                    if (updatelight)
                    {
                        Renderer.OptionAmbientColor.R = (byte)Math.Round(32.0 + 128.0 * LightingRelative * (2.0 - LightingRelative));
                        Renderer.OptionAmbientColor.G = (byte)Math.Round(32.0 + 128.0 * 0.5 * (LightingRelative + LightingRelative * (2.0 - LightingRelative)));
                        Renderer.OptionAmbientColor.B = (byte)Math.Round(32.0 + 128.0 * LightingRelative);
                        Renderer.OptionDiffuseColor.R = (byte)Math.Round(32.0 + 128.0 * LightingRelative);
                        Renderer.OptionDiffuseColor.G = (byte)Math.Round(32.0 + 128.0 * LightingRelative);
                        Renderer.OptionDiffuseColor.B = (byte)Math.Round(32.0 + 128.0 * Math.Sqrt(LightingRelative));
                        Renderer.InitializeLighting();
                    }
                    Renderer.RenderScene();
                    Sdl.SDL_GL_SwapBuffers();
                }
                // quit
                TextureManager.UnuseAllTextures();
                Sdl.SDL_Quit();
            }
            else
            {
                MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
예제 #20
0
        internal static void Main(string[] args)
        {
            Interface.CurrentOptions.UseSound = true;
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                /// general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                /// Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                /// non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            SetPackageLookupDirectories();
            // command line arguments
            bool[] SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            // application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (Sdl.SDL_Init(Sdl.SDL_INIT_VIDEO) != 0)
            {
                MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            // initialize sdl window
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DOUBLEBUFFER, 1);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DEPTH_SIZE, 16);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_RED_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_GREEN_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_BLUE_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_ALPHA_SIZE, 8);
            Sdl.SDL_ShowCursor(Sdl.SDL_ENABLE);
            // icon
            if (Program.CurrentPlatform == Platform.Windows)
            {
                string File = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.bmp");
                if (System.IO.File.Exists(File))
                {
                    IntPtr Bitmap = Sdl.SDL_LoadBMP(File);
                    if (Bitmap != null)
                    {
                        Sdl.SDL_Surface Surface  = (Sdl.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(Bitmap, typeof(Sdl.SDL_Surface));
                        int             ColorKey = Sdl.SDL_MapRGB(Surface.format, 0, 0, 255);
                        Sdl.SDL_SetColorKey(Bitmap, Sdl.SDL_SRCCOLORKEY, ColorKey);
                        Sdl.SDL_WM_SetIcon(Bitmap, null);
                    }
                }
            }
            // initialize camera
            ResetCamera();
            World.BackgroundImageDistance = 600.0;
            World.ForwardViewingDistance  = 600.0;
            World.BackwardViewingDistance = 0.0;
            World.ExtraViewingDistance    = 50.0;
            // create window
            Renderer.ScreenWidth  = 960;
            Renderer.ScreenHeight = 600;
            int    Bits  = 32;
            IntPtr video = Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF);

            if (video != IntPtr.Zero)
            {
                // create window
                Sdl.SDL_WM_SetCaption(Application.ProductName, null);
                // anisotropic filtering
                string[] Extensions = Gl.glGetString(Gl.GL_EXTENSIONS).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                for (int i = 0; i < Extensions.Length; i++)
                {
                    if (string.Compare(Extensions[i], "GL_EXT_texture_filter_anisotropic", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        float n; Gl.glGetFloatv(Gl.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, out n);
                        Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n);
                        break;
                    }
                }
                if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0)
                {
                    Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                    Interface.CurrentOptions.AnisotropicFilteringLevel   = 0;
                    Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering;
                }
                else
                {
                    Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum;
                    Interface.CurrentOptions.Interpolation             = TextureManager.InterpolationMode.TrilinearMipmapped;
                }
                Interface.CurrentOptions.TransparencyMode = Renderer.TransparencyMode.Sharp;
                // module initialization
                Renderer.Initialize();
                Renderer.InitializeLighting();
                SoundManager.Initialize();
                Gl.glClearColor(0.75f, 0.75f, 0.75f, 1.0f);
                Sdl.SDL_GL_SwapBuffers();
                Fonts.Initialize();
                UpdateViewport();
                // loop
                bool processCommandLineArgs = true;
                while (!Quit)
                {
                    ProcessEvents();
                    int    a           = Sdl.SDL_GetTicks();
                    double TimeElapsed = 0.001 * (double)(a - LastTicks);
                    if (CpuReducedMode)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(1);
                        if (ReducedModeEnteringTime == 0)
                        {
                            ReducedModeEnteringTime = a + 2500;
                        }
                        if (World.CameraAlignmentDirection.Position.X != 0.0 | World.CameraAlignmentDirection.Position.Y != 0.0 | World.CameraAlignmentDirection.Position.Z != 0.0 | World.CameraAlignmentDirection.Pitch != 0.0 | World.CameraAlignmentDirection.Yaw != 0.0 | World.CameraAlignmentDirection.Roll != 0.0 | World.CameraAlignmentDirection.TrackPosition != 0.0 | World.CameraAlignmentDirection.Zoom != 0.0)
                        {
                            ReducedModeEnteringTime = a + 2500;
                        }
                        else if (a > ReducedModeEnteringTime & CpuAutomaticMode)
                        {
                            ReducedModeEnteringTime = 0;
                            CpuReducedMode          = true;
                        }
                    }
                    DateTime d = DateTime.Now;
                    Game.SecondsSinceMidnight = (double)(3600 * d.Hour + 60 * d.Minute + d.Second) + 0.001 * (double)d.Millisecond;
                    ObjectManager.UpdateAnimatedWorldObjects(TimeElapsed, false);
                    World.UpdateAbsoluteCamera(TimeElapsed);
                    ObjectManager.UpdateVisibility(World.CameraTrackFollower.TrackPosition + World.CameraCurrentAlignment.Position.Z);
                    TextureManager.Update(TimeElapsed);
                    SoundManager.Update(TimeElapsed);
                    Renderer.RenderScene(TimeElapsed);
                    Sdl.SDL_GL_SwapBuffers();
                    LastTicks = a;
                    // command line arguments
                    if (processCommandLineArgs)
                    {
                        processCommandLineArgs = false;
                        for (int i = 0; i < args.Length; i++)
                        {
                            if (!SkipArgs[i] && System.IO.File.Exists(args[i]))
                            {
                                CurrentlyLoading = true;
                                Renderer.RenderScene(0.0);
                                Sdl.SDL_GL_SwapBuffers();
                                CurrentRoute = args[i];
                                LoadRoute();
                                CurrentlyLoading = false;
                                UpdateCaption();
                                break;
                            }
                        }
                    }
                }
                // quit
                TextureManager.UnuseAllTextures();
                SoundManager.Deinitialize();
                Sdl.SDL_Quit();
            }
            else
            {
                MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }