Exemplo n.º 1
0
        public override void Load()
        {
            _font        = SceneManager.GameFontLibrary.GetFirstOrDefault("selected");
            _fontDrawing = new QFontDrawing();
            SceneManager.RemoveScene(ParentScene);
            SceneManager.ScreenCamera.ExtraScale = 0;
            SceneManager.ScreenCamera.Scale      = SceneManager.ScreenCamera.TargetScale = new Vector2(1, 1);

            //save song to db
            string dbFile = Path.Combine(SceneManager.Directories["AppData"].FullName, (string)SceneManager.GameSettings["DatabaseFile"]);

            // Need to check for old version of database
            try
            {
                SaveHighScore(dbFile);
            }
            catch (Exception ex)
            {
                // this is an old version of the database, delete the file and try again
                try
                {
                    File.Delete(dbFile);
                }
                catch (Exception) { }
            }

            // This shouldn't fail, because we checked for old version of the database
            SaveHighScore(dbFile);

            UpdateText();
            Loaded = true;
        }
Exemplo n.º 2
0
        protected override void OnLoad(EventArgs e)
        {
            World = new World(128, 16, 128);
            Player player = new Player(World, Matrix4.CreatePerspectiveFieldOfView((float)MathHelper.DegreesToRadians(45.0), 1.0f * Width / Height, 0.1f, 300.0f),
                                       new Vector3(10, 200, 10), 0, 0);

            World.Player = player;

            CursorVisible = false;

            KeyDown += new EventHandler <KeyboardKeyEventArgs>(KeyDownAction);

            droidSans  = new QFont("assets/fonts/DroidSansMono.ttf", 18, new QuickFont.Configuration.QFontBuilderConfiguration(false));
            fontDrawer = new QFontDrawing();

            GL.ClearColor(0.2f, 0.4f, 1.0f, 1.0f);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);

            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line); // Wire Frame Mode
            //GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Point); // Point Mode
            //GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill); // Default Fill Mode

            World.PreLoad();

            Atlas = new TextureAtlas(32, 32, 16);

            Atlas.AddImage("starhide.dirt", "assets/dirt.png");
            Atlas.AddImage("starhide.grass", "assets/grass.png");



            base.OnLoad(e);
        }
Exemplo n.º 3
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GL.ClearColor(1, 1, 1, 1);

            FontDrawing = new QFontDrawing();
            MainFont    = new QFont("Tahoma", 16, new QFontBuilderConfiguration());

            // load the rooms
            var rooms = Directory.GetFiles(@"Content\Rooms", "*.txt", SearchOption.AllDirectories)
                        .Select(path => RoomLoader.Load(path))
                        .ToList();
            var items = Directory.GetFiles(@"Content\Items", "*.txt", SearchOption.AllDirectories)
                        .SelectMany(path => ItemLoader.Load(path).Select(w => w.itemtemplate))
                        .ToList();

            // build the map
            const int mapw = 75, maph = 25;

            Map = new Map(mapw, maph, rooms, new Random());

            // and the terrain renderer
            TerrainRenderer = new TerrainRenderer(Map)
            {
                ViewMatrix = Matrix4.CreateTranslation(2, 2, 0) * Matrix4.CreateScale(.1f)
            };
        }
Exemplo n.º 4
0
        public UIManager()
        {
            Debug.Log(Engine.Instance.ClientRectangle.Top.ToString());
            Debug.Log(Engine.Instance.Width / 2 + " : " + Engine.Instance.Height / 2);
            _drawing        = new QFontDrawing();
            _myFont         = new QFont("OpenSans.ttf", 15 / (Engine.Instance.Width / Engine.Instance.Height), new QFontBuilderConfiguration(true));
            RendeTextOption = new QFontRenderOptions {
                WordWrap = true,
                Colour   = Color.White, DropShadowActive = false
            };

            /*
             *
             * _drawing.DrawingPrimitives.Clear();
             * _drawing.Print(_myFont, "text1", new OpenTK.Vector3(Engine.Instance.Width / 2, Engine.Instance.Height / 2, 0), QFontAlignment.Centre);
             * // draw with options
             * var textOpts = new QFontRenderOptions()
             * {
             *  Colour = Color.FromArgb(new Color4(0.8f, 0.1f, 0.1f, 1.0f).ToArgb()),
             *  DropShadowActive = true
             * };
             * SizeF size = _drawing.Print(_myFont, "text2", pos2, FontAlignment.Left, textOpts);
             *
             * var dp = new QFontDrawingPimitive(_myFont2);
             * size = dp.Print(text, new Vector3(bounds.X, Height - yOffset, 0), new SizeF(maxWidth, float.MaxValue), alignment);
             * drawing.DrawingPimitiveses.Add(dp);*/

            // after all changes do update buffer data and extend it's size if needed.
            //_drawing.RefreshBuffers();
        }
Exemplo n.º 5
0
        public override void Load()
        {
            _bodyFont   = SceneManager.GameFontLibrary.GetFirstOrDefault("largebody");
            _headerFont = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Menu);

            _fontDrawing = new QFontDrawing();
            _fontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix;

            _headerSize = _headerFont.Font.Measure(_headerText);

            _bodyTextWidth = 0.75f;
            _bodyText1Size = _bodyFont.Font.Measure(_bodyText1, _bodyTextWidth * WindowWidth, QFontAlignment.Centre);
            _bodyText2Size = _bodyFont.Font.Measure(_bodyText2, _bodyTextWidth * WindowWidth, QFontAlignment.Centre);
            _bodyListSize  = _bodyFont.Font.Measure(_bodyList, _bodyTextWidth * WindowWidth, QFontAlignment.Left);

            ServiceLocator.Settings["FirstRun"] = false;

            var    informationalVersionAttribute = System.Reflection.Assembly.GetExecutingAssembly().CustomAttributes.FirstOrDefault(cad => cad.AttributeType == typeof(System.Reflection.AssemblyInformationalVersionAttribute));
            string tag = ((string)informationalVersionAttribute.ConstructorArguments.First().Value).Split(' ')[0].Split(':')[1];

            if (tag.Length > 1)
            {
                ServiceLocator.Settings["GetAlphaReleases"] = true;
            }

            Loaded = true;
        }
Exemplo n.º 6
0
        public static void InitializeResources()
        {
            if (Freetype6Loaded)
            {
                var builderConfig = new QFontBuilderConfiguration(true)
                {
                    ShadowConfig =
                    {
                        BlurRadius = 2,
                        BlurPasses = 1,
                        Type       = ShadowType.Blurred
                    },
                    TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                    Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
                };

                NormalFont = new QFont("C:\\Windows\\Fonts\\segoeui.ttf", 10,
                                       builderConfig);

                SmallFont = new QFont("C:\\Windows\\Fonts\\segoeui.ttf", 8,
                                      builderConfig);

                MonoFont = new QFont("C:\\Windows\\Fonts\\consola.ttf", 10,
                                     builderConfig);

                TextRenderer = new QFontDrawing();
            }


            UIShader = ProgramFactory.Create <UIShaderProgram>();

            UIShader.Use();
            UIShader.Opacity.Set(1f);
        }
Exemplo n.º 7
0
        /// <summary>Load resources here.</summary>
        /// <param name="e">Not used.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.Keyboard.KeyDown += KeyDown;
            drawing          = new QFontDrawing();
            controlsDrawing  = new QFontDrawing();
            controlsTextOpts = new QFontRenderOptions()
            {
                Colour = Color.FromArgb(new Color4(0.8f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true
            };

            heading2        = new QFont("woodenFont.qfont", new QFontConfiguration(addDropShadow: true), 1.0f);
            heading2Options = new QFontRenderOptions()
            {
                Colour = Color.White, DropShadowActive = true
            };

            var builderConfig = new QFontBuilderConfiguration(addDropShadow: true);

            builderConfig.ShadowConfig.blurRadius  = 2; //reduce blur radius because font is very small
            builderConfig.ShadowConfig.blurPasses  = 1;
            builderConfig.ShadowConfig.Type        = ShadowType.Blurred;
            builderConfig.TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit; //best render hint for this font
            builderConfig.Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic;
            mainText        = new QFont("Fonts/times.ttf", 14, builderConfig);
            mainTextOptions = new QFontRenderOptions()
            {
                DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f
            };

            _benchmarkResults = new QFont("Fonts/times.ttf", 14, builderConfig);

            heading1 = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true));

            controlsText = new QFont("Fonts/HappySans.ttf", 32, new QFontBuilderConfiguration(true));

            codeText = new QFont("Fonts/Comfortaa-Regular.ttf", 12, new QFontBuilderConfiguration());

            heading1Options = new QFontRenderOptions()
            {
                Colour = Color.FromArgb(new Color4(0.2f, 0.2f, 0.2f, 1.0f).ToArgb()), DropShadowActive = true
            };
            _processedText  = QFontDrawingPrimitive.ProcessText(mainText, mainTextOptions, preProcessed, new SizeF(Width - 40, -1), QFontAlignment.Left);
            codeTextOptions = new QFontRenderOptions()
            {
                Colour = Color.FromArgb(new Color4(0.0f, 0.0f, 0.4f, 1.0f).ToArgb())
            };

            monoSpaced        = new QFont("Fonts/Anonymous.ttf", 10, new QFontBuilderConfiguration());
            monoSpacedOptions = new QFontRenderOptions()
            {
                Colour = Color.FromArgb(new Color4(0.1f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true
            };

            GL.ClearColor(Color4.CornflowerBlue);
        }
Exemplo n.º 8
0
        public override void Load()
        {
            SceneManager.GameWindow.Cursor = MouseCursor.Empty;

            _stage = new Stage(this.SceneManager);
            _stage.ShaderProgram = _shaderProgram;

            _loadingFontRenderOptions = new QFontRenderOptions();
            _loadingFontRenderOptions.DropShadowActive = true;
            _loadingFont        = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Heading);
            _loadingFontDrawing = new QFontDrawing();
            _loadingFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix;
            _loadingText         = QFontDrawingPrimitive.ProcessText(_loadingFont.Font, _loadingFontRenderOptions, "Loading", new SizeF(200, -1), QFontAlignment.Centre);
            _loadingTextPosition = CalculateTextPosition(new Vector3((float)SceneManager.GameWindow.Width / 2, SceneManager.GameWindow.Height / 2, 0f), _loadingText);

            _songText = QFontDrawingPrimitive.ProcessText(_loadingFont.Font, _loadingFontRenderOptions, _song.SongBase.Identifier, new SizeF(SceneManager.GameWindow.Width - 40, -1), QFontAlignment.Centre);

            //Get difficulty options
            DifficultyOptions dOptions;

            switch ((DifficultyLevels)SceneManager.GameSettings["DifficultyLevel"])
            {
            case DifficultyLevels.Easy:
                dOptions = DifficultyOptions.Easy;
                break;

            case DifficultyLevels.Medium:
                dOptions = DifficultyOptions.Medium;
                break;

            case DifficultyLevels.Hard:
                dOptions = DifficultyOptions.Hard;
                break;

            case DifficultyLevels.Ultra:
                dOptions = DifficultyOptions.Ultra;
                break;

            case DifficultyLevels.Ninja:
                dOptions = DifficultyOptions.Ninja;
                break;

            default:
                //shouldn't happen
                throw new Exception("Invalid difficulty level specified");
            }

            var progress = new Progress <string>(status =>
            {
                _loadingStatus = status;
            });

            _loadTask = Task.Factory.StartNew(() => _stage.LoadAsync(_song, _audioCorrection, _maxAudioVolume, progress, _centerPolygon, _player, dOptions, (DifficultyLevels)SceneManager.GameSettings["DifficultyLevel"]));

            Loaded = true;
        }
Exemplo n.º 9
0
        public void Initialize()
        {
            c          = new Container(8, 8, 14);
            t          = new Tetromino();
            t.Position = new Vector3(4, 12, 4);

            _myFont           = new QFont(@"C:\Users\Asus\Desktop\arial.ttf", 20, new QFontBuilderConfiguration(true));
            _drawing          = new QFontDrawing();
            _projectionMatrix = Matrix4.CreateOrthographicOffCenter(0, Settings.CURRENT_WIN_WIDTH, 0, Settings.CURRENT_WIN_HEIGHT
                                                                    , -1.0f, 1.0f);
        }
Exemplo n.º 10
0
        public Stage(SceneManager sceneManager)
        {
            SceneManager = sceneManager;

            MultiplierFont        = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Menu);
            MultiplierFontDrawing = new QFontDrawing();
            MultiplierFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix;

            ScoreFontDrawing = new QFontDrawing();
            ScoreFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix;

            _stageAudio = new StageAudio();
        }
Exemplo n.º 11
0
        public Text(string fileName)
            : base(fileName)

        {
            //var file = Resources.GetFile(ImageRootPath + Name);
            //Bitmap image = new Bitmap(file);

            //TextureID = GL.GenTexture();

            //GL.BindTexture(TextureTarget.Texture2D, TextureID);

            //BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            //    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            //GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
            //    OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

            //image.UnlockBits(data);

            //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
            //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
            //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            //GL.TextureParameter((int)TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);



            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            //reduce blur radius because font is very small
            //best render hint for this font

            drawing         = new QFontDrawing();
            mainText        = new QFont(fontRootPath + fileName + ".ttf", 14, builderConfig);
            mainTextOptions = new QFontRenderOptions {
                DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f
            };
            processedText = QFontDrawingPrimitive.ProcessText(mainText, mainTextOptions, "Basldfgjwoietghwoifhewohfoiewuew", new SizeF(400 - 40, -1), QFontAlignment.Left);
        }
        private void Start()
        {
            _drawing        = new QFontDrawing();
            RendeTextOption = new QFontRenderOptions
            {
                WordWrap          = true,
                Colour            = Color.Black,
                DropShadowActive  = false,
                ClippingRectangle = GetRectangle
            };

            Pos     = new Vector3(GetRectangle.X, GetRectangle.Y + (GetRectangle.Height / 2), 0);
            MaxSize = new SizeF(GetRectangle.Width, GetRectangle.Height);
        }
        public SplashScreen()
        {
            _SplashScreen = this;
            HasError      = false;
            IsShowing     = true;

            _drawing        = new QFontDrawing();
            _font           = new QFont("OpenSans.ttf", 15 / (Window.Instance.Width / Window.Instance.Height), new QFontBuilderConfiguration(true));
            RendeTextOption = new QFontRenderOptions
            {
                WordWrap         = true,
                Colour           = Color.Black,
                DropShadowActive = false
            };

            GL.ClearColor(Color4.White);

            _Shader  = new Shader(AssetsManager.LoadShader("Assets/Shaders/", "UI"));
            _texture = new Texture(AssetsManager.LoadImage("Assets/Images/", "Darkcomsoft_New", "png"), TextureMinFilter.Linear, TextureMagFilter.Linear);
            CreateMesh();

            IBO = GL.GenBuffer();
            VAO = GL.GenVertexArray();

            vbo = GL.GenBuffer();
            dbo = GL.GenBuffer();
            tbo = GL.GenBuffer();

            GL.BindBuffer(BufferTarget.ElementArrayBuffer, IBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, _mesh._indices.Length * sizeof(int), _mesh._indices, BufferUsageHint.StaticDraw);

            GL.BindVertexArray(VAO);

            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, _mesh._vertices.Length * Vector3.SizeInBytes, _mesh._vertices, BufferUsageHint.StaticDraw);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.EnableVertexAttribArray(0);

            //Colors
            GL.BindBuffer(BufferTarget.ArrayBuffer, dbo);
            GL.BufferData(BufferTarget.ArrayBuffer, _mesh._Colors.Length * sizeof(float), _mesh._Colors, BufferUsageHint.StaticDraw);
            GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, 0, 0);
            GL.EnableVertexAttribArray(1);

            //Texture
            GL.BindBuffer(BufferTarget.ArrayBuffer, tbo);
            GL.BufferData(BufferTarget.ArrayBuffer, _mesh._texCoords.Length * Vector2.SizeInBytes, _mesh._texCoords, BufferUsageHint.StaticDraw);
            GL.VertexAttribPointer(2, 2, VertexAttribPointerType.Float, false, 0, 0);
            GL.EnableVertexAttribArray(2);
        }
Exemplo n.º 14
0
        static void OnLoad()
        {
            drawing = new QFontDrawing();

            var builderConfig = new QFontBuilderConfiguration(addDropShadow: true);

            builderConfig.ShadowConfig.blurRadius  = 2; //reduce blur radius because font is very small
            builderConfig.ShadowConfig.blurPasses  = 1;
            builderConfig.ShadowConfig.Type        = ShadowType.Blurred;
            builderConfig.TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit; //best render hint for this font
            mainText        = new QFont("Fonts/times.ttf", 56, builderConfig);
            mainTextOptions = new QFontRenderOptions()
            {
                DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f
            };
        }
Exemplo n.º 15
0
        public Control(ShaderProgram program,
                       Vector3 position, Vector3 rotation, Vector3 scaling,
                       Dictionary <int, Control> controls, Dictionary <int, AModel> models, Menu menu,
                       int width, int height, int windowWidth, int windowHeight,
                       Matrix4 projection, string text = "", string fontLocation = "arial")
        {
            ID           = TotalID++;
            Width        = width;
            Height       = height;
            WindowWidth  = windowWidth;
            WindowHeight = windowHeight;
            // Create model.
            Models = new Dictionary <string, Model>
            {
                { "Default", new Model(program, position, rotation, scaling) },
                { "Focused", new Model(program, position, rotation, scaling) },
                { "Hovering", new Model(program, position, rotation, scaling) }
            };
            foreach (var model in Models.Values)
            {
                models.Add(model.ID, model);
            }
            // Text assignments
            Text             = text;
            ProjectionMatrix = projection;
            LabelDrawing     = new QFontDrawing();
            // Text Config.
            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            LabelFont = new QFont(@"Resources\Fonts\" + fontLocation + ".ttf", 8, builderConfig);
            // Buffer text.
            PrintText(position);
            State = ControlState.Normal;
            // Add this control to dictionaries.
            controls.Add(ID, this);
            menu.Add(this);
        }
Exemplo n.º 16
0
        public override void Load()
        {
            SceneManager.GameWindow.Cursor = MouseCursor.Default;

            // Remap keypad enter to normal enter
            InputSystem.KeyRemappings.Add(Key.KeypadEnter, Key.Enter);

            _gameVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            // Choose correct version directive because OSX is dumb
            string version = "#version 130";

            if (PlatformDetection.RunningPlatform() == Platform.MacOSX)
            {
                version = "#version 150";
            }

            // Load shaders
            var vert = new Shader(Path.Combine(SceneManager.Directories["Shaders"].FullName, "simple.vs"), version);
            var frag = new Shader(Path.Combine(SceneManager.Directories["Shaders"].FullName, "simple.fs"), version);

            _shaderProgram = new ShaderProgram();
            _shaderProgram.Load(vert, frag);

            _player                      = new Player();
            _player.Position             = new PolarVector(1.5 * (Math.PI / 3) - _player.Length * 0.5f, _player.Position.Radius);
            _player.ShaderProgram        = _shaderProgram;
            _centerPolygon               = new PolarPolygon(Enumerable.Repeat(true, 6).ToList(), new PolarVector(0.5, 0), 50, 80, 0);
            _centerPolygon.ShaderProgram = _shaderProgram;

            _menuFont        = SceneManager.GameFontLibrary.GetFirstOrDefault("menuworld");
            _menuFontDrawing = new QFontDrawing();
            _menuFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.WorldModelViewProjection;
            _menuRenderOptions = new QFontRenderOptions {
                DropShadowActive = true, Colour = Color.White
            };

            _versionFont = SceneManager.GameFontLibrary.GetFirstOrDefault("versiontext");

            var guiRenderer = new Gwen.Renderer.OpenTK();
            var skin        = new TexturedBase(guiRenderer, Path.Combine(SceneManager.Directories["Images"].FullName, "DefaultSkin.png"));

            skin.DefaultFont = new Gwen.Font(guiRenderer, SceneManager.FontPath, 30);
            _GUIComponents   = new GUIComponentContainer(guiRenderer, skin);

            Loaded = true;
        }
Exemplo n.º 17
0
        private static void Window_Load(object sender, EventArgs e)
        {
            Console.WriteLine("Program Started!");
            Console.WriteLine("Running at {0} FPS", startFrequency);

            GL.Viewport(0, 0, windowWidth, windowHeight);
            GL.ClearColor(Color4.Black);

            font    = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true));
            drawing = new QFontDrawing();

            drawing.DrawingPrimitives.Clear();

            window.WindowBorder = WindowBorder.Fixed;

            OnLoad?.Invoke(); //If OnLoad != null then invoke it
        }
Exemplo n.º 18
0
        private TFontServer()
        {
            drawing          = new QFontDrawing();
            defaultFontNames = new List <string>()
            {
                TimesNewRoman, Arial, Consolas
            };

            Fonts                = new Dictionary <string, QFont>();
            DefaultFonts         = new Dictionary <string, QFont>();
            BuilderConfiguration = new QFontBuilderConfiguration(true)
            {
                ShadowConfig             = { BlurRadius = 1, BlurPasses = 1, Type = ShadowType.Blurred },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };
        }
Exemplo n.º 19
0
        public OpenTK(bool restoreRenderState = true)
            : base()
        {
            m_Vertices   = new Vertex[MaxVerts];
            m_VertexSize = Marshal.SizeOf(m_Vertices[0]);
            //m_StringCache = new Dictionary<PrintedTextKey, QFontDrawingPrimitive>();
            m_StringCache               = new StringCache();
            m_Graphics                  = Graphics.FromImage(new Bitmap(1024, 1024, PixelFormat.Format32bppArgb));
            m_StringFormat              = new StringFormat(StringFormat.GenericTypographic);
            m_StringFormat.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
            m_RestoreRenderState        = restoreRenderState;
            m_FontDrawing               = new QFontDrawing();

            guiShader = new GLShader();
            guiShader.Load("gui");

            CreateBuffers();
        }
Exemplo n.º 20
0
        public static void Font_Init()
        {
            Font_Free();

            FPS_FontDrawing = new QFontDrawing();

            var FontBuilderConfig = new QFontBuilderConfiguration(true);

            FontBuilderConfig.ShadowConfig.blurRadius = 2;
            FontBuilderConfig.ShadowConfig.blurPasses = 1;
            FontBuilderConfig.ShadowConfig.Type       = ShadowType.Blurred;
            //FontBuilderConfig.TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit;

            string FPS_FontPath = Engine.CombinePaths(Settings.Paths.EngineFonts, @"LCD\LCD.ttf");

            FPS_Font = new QFont(FPS_FontPath, 24f, FontBuilderConfig);
            //FPS_Font = new QFont(new Font("Lucida Console", 24f, FontStyle.Regular), FontBuilderConfig);

            FPS_Font_Options = new QFontRenderOptions();
            FPS_Font_Options.DropShadowActive = true;
            FPS_Font_Options.Colour           = Color.Yellow;
        }
Exemplo n.º 21
0
        public DirectoryBrowser(SceneManager parentSceneManager, ChooseSongScene parentScene)
        {
            _parentManager        = parentSceneManager;
            _parentScene          = parentScene;
            _fileSystemCollection = new List <IFileSystem>();
            _fileSystemEntries    = new List <FileBrowserEntry>();

            _unselectedFont = _parentManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Body);
            _selectedFont   = _parentManager.GameFontLibrary.GetFirstOrDefault("selected");
            _searchFont     = _parentManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Heading);

            _qfontDrawing = new QFontDrawing();

            Resize(_parentManager.Width, _parentManager.Height);

            EntrySeparator = new FileBrowserEntry
            {
                Path      = "./",
                Name      = "--------------------",
                EntryType = FileBrowserEntryType.Separator
            };
        }
Exemplo n.º 22
0
        public static void InitializeResources()
        {
            NormalFont = new QFont("C:\\Windows\\Fonts\\segoeui.ttf", 10,
                                   new QFontBuilderConfiguration(true));

            SmallFont = new QFont("C:\\Windows\\Fonts\\segoeui.ttf", 8,
                                  new QFontBuilderConfiguration(true));

            MonoFont = new QFont("C:\\Windows\\Fonts\\consola.ttf", 10,
                                 new QFontBuilderConfiguration(true));

            TextRenderer = new QFontDrawing();
            UIShader     = ProgramFactory.Create <UIShaderProgram>();

            UIShader.Use();
            UIShader.Opacity.Set(1f);

            VAO = new VertexArray();
            VBO = new Buffer <VertVT>();
            VAO.Bind();
            VAO.BindAttribute(UIShader.Position, VBO);
            VAO.BindAttribute(UIShader.TexCoord, VBO, 12);
        }
Exemplo n.º 23
0
        /// <summary>
        /// The default Constructor.
        /// </summary>
        public SceneManager(GameWindow gameWindow, Camera camera, FontLibrary fontLibrary, string fontPath, IDirectoryHandler directoryHandler, IGameSettings gameSettings, ValueWrapper <bool> debug)
        {
            GameWindow      = gameWindow;
            SceneList       = new List <Scene>();
            _scenesToAdd    = new List <Scene>();
            _scenesToRemove = new List <Scene>();

            Directories = directoryHandler;

            FontPath        = fontPath;
            GameFontLibrary = fontLibrary;
            DefaultFont     = GameFontLibrary.GetFirstOrDefault(GameFontType.Default);
            FontDrawing     = new QFontDrawing();
            FontDrawing.ProjectionMatrix = camera.ScreenProjectionMatrix;

            ScreenCamera              = camera;
            ScreenCamera.Center       = Vector2.Zero;
            ScreenCamera.MaximumScale = new Vector2(10000, 10000);

            GameSettings = gameSettings;

            Debug = debug;
        }
Exemplo n.º 24
0
        public void initializeGL()
        {
            GL.ClearColor(Color4.White);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit);
            // Blending
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
            // Z-buffer
            GL.ClearDepth(1.0f);
            GL.DepthMask(true);
            GL.DepthFunc(DepthFunction.Lequal);
            GL.Enable(EnableCap.DepthTest);
            // Stencil
            GL.ClearStencil(0);
            GL.Enable(EnableCap.StencilTest);
            GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);
            // Smoothing
            GL.Enable(EnableCap.PolygonSmooth);
            GL.Enable(EnableCap.LineSmooth);
            GL.Hint(HintTarget.PolygonSmoothHint, HintMode.Nicest);
            GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);
            GL.Hint(HintTarget.PointSmoothHint, HintMode.Nicest);
            // Sizes
            GL.PointSize(DrawOptions.pointSize);
            GL.LineWidth(DrawOptions.lineWidth);
            // Defining all the colors for further selection
            availableColors_ = new List <Color4>()
            {
                Color4.Blue, Color4.Green, Color4.DarkOrange,
                Color4.Red, Color4.SaddleBrown, Color4.Purple,
                Color4.DarkBlue, Color4.DarkCyan, Color4.Chocolate
            };
            selection_         = new Dictionary <string, List <uint> >();
            sequenceSelection_ = new List <string>();
            selectionColor_    = Color4.HotPink;
            // Update drawing constants
            DrawOptions.update(glControl_.Width, glControl_.Height);
            // Transformations
            location_         = Vector3.Zero;
            modelTranslation_ = Matrix4.Identity;
            modelScale_       = Matrix4.CreateScale(DrawOptions.defaultScale, DrawOptions.defaultScale, 1.0f);
            modelRotation_    = Matrix4.Identity;
            view_             = Matrix4.Identity;
            projection_       = Matrix4.CreateOrthographic(glControl_.Width, glControl_.Height, DrawOptions.zNear, DrawOptions.zFar);
            // Markers
            isShowNodeMarkers = true;
            // Fonts
            isShowNodeNames = false;
            fontDrawing_    = new QFontDrawing();
            var builderConfig = new QFontBuilderConfiguration(true)
            {
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            font_ = new QFont("Optima", 8, builderConfig);
            fontRenderOptions_ = new QFontRenderOptions()
            {
                Colour           = Color.Black,
                DropShadowActive = false,
                CharacterSpacing = 0.1f
            };
            // Compiling the shader
            shader_ = new Shader(shaderPath_ + "shaders/shader.vert", shaderPath_ + "shaders/shader.frag");
            // Lighting
            isLighting = true;
            shader_.SetVector3("light.ambient", LightingOptions.lightAmbient);
            shader_.SetVector3("light.diffuse", LightingOptions.lightDiffuse);
            shader_.SetVector3("light.specular", LightingOptions.lightSpecular);
            // Light attenuation constants
            shader_.SetFloat("light.constant", LightingOptions.lightConstant);
            shader_.SetFloat("light.linear", LightingOptions.lightLinear);
            shader_.SetFloat("light.quadratic", LightingOptions.lightQuadratic);
            // Material
            shader_.SetVector3("material.ambient", LightingOptions.materialAmbient);
            shader_.SetVector3("material.diffuse", LightingOptions.materialDiffuse);
            shader_.SetVector3("material.specular", LightingOptions.materialSpecular);
            shader_.SetFloat("material.shininess", LightingOptions.materialShininess);
            // Coordinate system
            coordinateSystem_                 = new CoordinateSystem();
            coordinateSystem_.font            = font_;
            coordinateSystem_.shader          = shader_;
            coordinateSystemOrigin_           = new Vector3(DrawOptions.originSystemX, DrawOptions.originSystemY, DrawOptions.originSystemZ);
            coordinateSystemScaleTranslation_ = Matrix4.CreateScale(DrawOptions.defaultScale, DrawOptions.defaultScale, 1.0f) * Matrix4.CreateTranslation(coordinateSystemOrigin_);
            // Viewport
            prevControlWidth_  = glControl_.Width;
            prevControlHeight_ = glControl_.Height;
        }
Exemplo n.º 25
0
        public ButtonBackup(ShaderProgram program, string text, Color4 colour,
                            int x, int y, int width, int height, int windowWidth, int windowHeight,
                            Matrix4 projection, Func <Task> execDelegate,
                            LayoutAlign layoutAlign = LayoutAlign.TopRight, string fontLocation = "arial")
            : base(program)
        {
            LayoutAlign  = layoutAlign;
            WindowWidth  = windowWidth;
            WindowHeight = windowHeight;
            switch (LayoutAlign)
            {
            case LayoutAlign.TopRight:
                X      = x;
                Y      = WindowHeight - y;
                Width  = width;
                Height = -height;
                break;

            case LayoutAlign.TopLeft:
                X      = WindowWidth - x;
                Y      = WindowHeight - y;
                Width  = width;
                Height = -height;
                break;

            case LayoutAlign.BottomRight:
                X      = x;
                Y      = y;
                Width  = width;
                Height = -height;
                break;

            case LayoutAlign.BottomLeft:
                X      = WindowWidth - x;
                Y      = y;
                Width  = width;
                Height = -height;
                break;

            default:
                X      = x;
                Y      = y;
                Width  = width;
                Height = height;
                break;
            }
            // Create model, then populate button positional data to that model data.
            Vertices = new Vertex[] {
                new Vertex(// Top left
                    new Vector3(X, Y, 0.0f),
                    colour,
                    new Vector2(0.0f, 0.0f)),
                new Vertex(// Top right
                    new Vector3(X + Width, Y, 0.0f),
                    colour,
                    new Vector2(1.0f, 0.0f)),
                new Vertex(// Bottom right
                    new Vector3(X + Width, Y + Height, 0.0f),
                    colour,
                    new Vector2(1.0f, 1.0f)),
                new Vertex(// Bottom left
                    new Vector3(X, Y + Height, 0.0f),
                    colour,
                    new Vector2(0.0f, 1.0f))
            };
            Indices = new int[]
            {
                0, 1, 2,
                0, 3, 2
            };
            Text             = text;
            State            = ButtonState.NotPressed;
            ProjectionMatrix = projection;
            ExecDelegate     = execDelegate;
            // Configure text
            LabelDrawing = new QFontDrawing();
            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            LabelFont = new QFont(@"Resources\Fonts\" + fontLocation + ".ttf", 12, builderConfig);
            // Buffer text.
            LabelDrawing.DrawingPrimitives.Clear();
            LabelDrawing.Print(LabelFont, Text,
                               new Vector3(X + (Width / 2), Y, 0.0f),
                               new SizeF(Width, Height), QFontAlignment.Centre, new QFontRenderOptions()
            {
                WordWrap = false
            });
            LabelDrawing.RefreshBuffers();
        }
Exemplo n.º 26
0
        public override void Load()
        {
            _optionsFont    = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Heading);
            _valueFont      = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Heading);
            _optionsDrawing = new QFontDrawing();
            _optionsDrawing.ProjectionMatrix = SceneManager.ScreenCamera.ScreenProjectionMatrix;

            _options = new List <OptionBase>();

            var audioCorrection   = (float)SceneManager.GameSettings["AudioCorrection"] * 1000f;
            var vol               = (float)Math.Round((float)SceneManager.GameSettings["MaxAudioVolume"] * 100);
            var currentDifficulty = (DifficultyLevels)SceneManager.GameSettings["DifficultyLevel"];
            var analytics         = (bool)ServiceLocator.Settings["Analytics"];
            var windowMode        = (string)ServiceLocator.Settings["WindowState"];
            var colourMode        = (ColourMode)ServiceLocator.Settings["ColourMode"];

            _options.Add(new NumericOption
            {
                FriendlyName = "Volume",
                SettingName  = "MaxAudioVolume",
                Minimum      = 0.0f,
                Maximum      = 100.0f,
                Scale        = 100.0f,
                Round        = true,
                Step         = 1.0f,
                Value        = vol
            });

            _options.Add(new NumericOption
            {
                FriendlyName = "Audio Correction (ms)",
                SettingName  = "AudioCorrection",
                Minimum      = -1000.0f,
                Maximum      = 1000.0f,
                Scale        = 1000.0f,
                Round        = true,
                Step         = 2.0f,
                Value        = audioCorrection
            });

            _options.Add(new EnumOption <DifficultyLevels>
            {
                FriendlyName = "Difficulty",
                SettingName  = "DifficultyLevel",
                Values       = Enum.GetNames(typeof(DifficultyLevels)).ToList(),
                CurrentIndex = Enum.GetNames(typeof(DifficultyLevels)).ToList().IndexOf(currentDifficulty.ToString())
            });

            _options.Add(new BoolOption
            {
                FriendlyName = "Analytics",
                SettingName  = "Analytics",
                Value        = analytics
            });

            var windowModes = new List <string> {
                WindowState.Fullscreen.ToString(), WindowState.Normal.ToString()
            };

            _options.Add(new StringOption
            {
                FriendlyName     = "Window Mode",
                SettingName      = "WindowState",
                Values           = windowModes,
                CurrentIndex     = windowModes.IndexOf(windowMode),
                CallbackFunction = (s) => SceneManager.GameWindow.WindowState = (WindowState)Enum.Parse(typeof(WindowState), s)
            });

            _options.Add(new EnumOption <ColourMode>
            {
                FriendlyName = "Colour Mode",
                SettingName  = "ColourMode",
                Values       = Enum.GetNames(typeof(ColourMode)).ToList(),
                CurrentIndex = Enum.GetNames(typeof(ColourMode)).ToList().IndexOf(colourMode.ToString())
            });

            foreach (var op in _options)
            {
                op.Sanitise();
            }
            Loaded = true;
        }
Exemplo n.º 27
0
        public LabelBackup(ShaderProgram program, string text, Color4 colour, Color4 highlightColour,
                           int x, int y, int width, int height, int windowWidth, int windowHeight,
                           Matrix4 projection,
                           LayoutAlign layoutAlign = LayoutAlign.TopRight, string fontLocation = "arial")
            : base(program)
        {
            LayoutAlign  = layoutAlign;
            WindowWidth  = windowWidth;
            WindowHeight = windowHeight;
            switch (LayoutAlign)
            {
            case LayoutAlign.TopRight:
                Position = new Vector3(x, WindowHeight - y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            case LayoutAlign.TopLeft:
                Position = new Vector3(WindowWidth - x, WindowHeight - y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            case LayoutAlign.BottomRight:
                Position = new Vector3(x, y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            case LayoutAlign.BottomLeft:
                Position = new Vector3(WindowWidth - x, y, 0.0f);
                Width    = width;
                Height   = -height;
                break;

            default:
                Position = new Vector3(x, y, 0.0f);
                Width    = width;
                Height   = height;
                break;
            }
            // Create model, then populate button positional data to that model data.
            Vertices = new Vertex[] {
                new Vertex(// Top left
                    new Vector3(0.0f, 0.0f, 0.0f),
                    colour,
                    new Vector2(0.0f, 0.0f)),
                new Vertex(// Top right
                    new Vector3(Width, 0.0f, 0.0f),
                    colour,
                    new Vector2(1.0f, 0.0f)),
                new Vertex(// Bottom right
                    new Vector3(Width, Height, 0.0f),
                    colour,
                    new Vector2(1.0f, 1.0f)),
                new Vertex(// Bottom left
                    new Vector3(0.0f, Height, 0.0f),
                    colour,
                    new Vector2(0.0f, 1.0f))
            };
            Indices = new int[]
            {
                0, 1, 2,
                0, 3, 2
            };
            float  highlightSize = Height / 10;
            Square centreSquare  = new Square(
                highlightSize,                // The X coord
                highlightSize,                // The Y coord
                Width - (highlightSize / 2),  // The Width
                Height - (highlightSize / 2), // The Height
                colour,                       // The colour of the box
                0);                           // The indexer start point.
            Square topSquare = new Square(
                0.0f,
                0.0f,
                Width - highlightSize,
                highlightSize,
                highlightColour,
                centreSquare.Vertices.Count);
            Square rightSquare = new Square(
                Width - highlightSize,
                0.0f,
                highlightSize,
                Height - highlightSize,
                highlightColour,
                centreSquare.Vertices.Count + topSquare.Vertices.Count);
            Square bottomSquare = new Square(0.0f,
                                             Height - highlightSize,
                                             Width - highlightSize,
                                             highlightSize,
                                             highlightColour,
                                             centreSquare.Vertices.Count + topSquare.Vertices.Count + rightSquare.Vertices.Count);
            Square leftSquare = new Square(0.0f,
                                           highlightSize,
                                           highlightSize,
                                           Height - highlightSize,
                                           highlightColour,
                                           centreSquare.Vertices.Count + topSquare.Vertices.Count + rightSquare.Vertices.Count + bottomSquare.Vertices.Count);

            // Text update
            Text = text;
            // Matrix update
            ProjectionMatrix = projection;
            // Configure text.
            LabelDrawing = new QFontDrawing();
            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            LabelFont = new QFont(@"Resources\Fonts\" + fontLocation + ".ttf", 8, builderConfig);
            // Buffer text.
            LabelDrawing.DrawingPrimitives.Clear();
            LabelDrawing.Print(LabelFont, Text, new Vector3(
                                   Position.X + (Width / 2), Position.Y, 1.0f), QFontAlignment.Centre);
            LabelDrawing.RefreshBuffers();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates the image on an OpenGL 2D texture and returns it's OpenGL handle.
        /// This function creates and destroys all the OpenGL objects it uses except the texture and framebuffer.
        /// </summary>
        /// <param name="singular">The singular form of the word</param>
        /// <param name="plural">The plural form of the word</param>
        /// <param name="imagePath">The path to the image showing the word to use</param>
        /// <param name="fbo">The framebuffer object that was used to render to the returned texture, still with the texture attached in color0</param>
        /// <param name="WIDTH">The width of the texture</param>
        /// <param name="HEIGHT">The height of the texture</param>
        static int MakeAllImage(String singular, String plural, String imagePath, out int fbo, out int WIDTH, out int HEIGHT)
        {
#if LOG_DATA
            DataLogger.Log("[ImageManager] MakeAllImage was called", LoggingMode.Message);
#endif

            WIDTH = 800;
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusDstAlpha);

#if LOG_DATA
            DataLogger.Log(String.Concat("[ImageManager] Loading bitmap from \"", imagePath, "\""), LoggingMode.Message);
#endif
            Bitmap bitmap = new Bitmap(imagePath);

            #region CalculateTextColor
#if LOG_DATA
            DataLogger.Log("[ImageManager] Calculating text color", LoggingMode.Message);
#endif
            //calculate whether to make the *noise text* black or white based on the colors on the image.
            float diffX = bitmap.Width / (float)COLOR_CALCULATOR_SAMPLE_FREQ;
            float diffY = bitmap.Height / (float)COLOR_CALCULATOR_SAMPLE_FREQ;

            int grayscaleTotal = 0;
            for (float x = (bitmap.Width - bitmap.Width / COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ) / 2f; x < bitmap.Width; x += diffX)
            {
                for (float y = (bitmap.Height - bitmap.Height / COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ) / 2f; y < bitmap.Height; y += diffY)
                {
                    Color c = bitmap.GetPixel((int)x, (int)y);
                    grayscaleTotal += c.R;
                    grayscaleTotal += c.G;
                    grayscaleTotal += c.B;
                }
            }
            bool isBlack = grayscaleTotal / (COLOR_CALCULATOR_SAMPLE_FREQ * COLOR_CALCULATOR_SAMPLE_FREQ * 3) > 127;
#if LOG_DATA
            DataLogger.Log("[ImageManager] Text color: " + (isBlack ? "black" : "white"), LoggingMode.Message);
#endif
            #endregion

            #region LoadQFont
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading QFont data", LoggingMode.Message);
#endif
            QFontShadowConfiguration shadowConfig = new QFontShadowConfiguration()
            {
                Type       = ShadowType.Expanded,
                BlurRadius = 2,
            };
            QFontBuilderConfiguration qconfig = new QFontBuilderConfiguration(true)
            {
                SuperSampleLevels        = 4,
                TextGenerationRenderHint = TextGenerationRenderHint.AntiAlias,
            };
            QFont              qfont = new QFont(new FreeTypeFont(FONT_LOCATION, 144, FontStyle.Regular), qconfig);
            QFontDrawing       qdraw = new QFontDrawing();
            QFontRenderOptions opts  = new QFontRenderOptions()
            {
                CharacterSpacing = 0.06f,
                Colour           = Color.Black,
            };
            ProcessedText text        = QFontDrawingPrimitive.ProcessText(qfont, opts, plural + " be like", new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Left);
            SizeF         topTextSize = qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts);

            qdraw.RefreshBuffers();

            #endregion

            int topHeight = 40 + (int)(topTextSize.Height + 0.5f);
            HEIGHT = WIDTH * bitmap.Height / bitmap.Width + topHeight;

#if LOG_DATA
            DataLogger.Log(String.Concat("[ImageManager] WIDTH=", WIDTH, " HEIGHT=", HEIGHT, " topHeight=", topHeight), LoggingMode.Message);
#endif

            #region GenVBO
#if LOG_DATA
            DataLogger.Log("[ImageManager] Generating VBO and VAO", LoggingMode.Message);
#endif
            float[] vboData = new float[]
            {
                0, 0, 0, 0, 1,
                0, 1, 0, 0, 0,
                1, 0, 0, 1, 1,
                1, 1, 0, 1, 0
            };
            int vbo = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, vboData.Length * 4, vboData, BufferUsageHint.StaticDraw);
            int vao = GL.GenVertexArray();
            GL.BindVertexArray(vao);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 20, 0);
            GL.EnableVertexAttribArray(0);
            GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 20, 12);
            GL.EnableVertexAttribArray(1);
            #endregion

            #region LoadTexture
#if LOG_DATA
            DataLogger.Log("[ImageManager] Generating texture for image", LoggingMode.Message);
#endif
            int tex = GL.GenTexture();
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, tex);
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading texture pixels from bitmap", LoggingMode.Message);
#endif
            BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, bits.Scan0);
            bitmap.UnlockBits(bits);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            #endregion

            #region LoadShaderProgram
#if LOG_DATA
            DataLogger.Log("[ImageManager] Creating shaders", LoggingMode.Message);
#endif
            int vs = GL.CreateShader(ShaderType.VertexShader);
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading vertex shader from " + VERTEX_SHADER_LOCATION, LoggingMode.Message);
#endif
            GL.ShaderSource(vs, File.ReadAllText(VERTEX_SHADER_LOCATION));
            GL.CompileShader(vs);
            int tmp;
            GL.GetShader(vs, ShaderParameter.CompileStatus, out tmp);
#if LOG_DATA
            if (tmp != 1)
            {
                DataLogger.Log("[ImageManager] Vertex shader compilation failed", LoggingMode.Error);
            }
            DataLogger.Log("[ImageManager] Vertex Shader Info Log: ", LoggingMode.Message);
            DataLogger.Log(GL.GetShaderInfoLog(vs), LoggingMode.RawData);
            DataLogger.Log("[ImageManager] [END OF VERTEX SHADER INFO LOG]", LoggingMode.Message);
#endif
            if (tmp != 1)
            {
                throw new Exception("Vertex Shader compilation failed. Process can't continue.");
            }

            int fs = GL.CreateShader(ShaderType.FragmentShader);
#if LOG_DATA
            DataLogger.Log("[ImageManager] Loading fragment shader from " + FRAGMENT_SHADER_LOCATION, LoggingMode.Message);
#endif
            GL.ShaderSource(fs, File.ReadAllText(FRAGMENT_SHADER_LOCATION));
            GL.CompileShader(fs);
            GL.GetShader(fs, ShaderParameter.CompileStatus, out tmp);
#if LOG_DATA
            if (tmp != 1)
            {
                DataLogger.Log("[ImageManager] Fragment shader compilation failed", LoggingMode.Error);
            }
            DataLogger.Log("[ImageManager] Fragment Shader Info Log: ", LoggingMode.Message);
            DataLogger.Log(GL.GetShaderInfoLog(fs), LoggingMode.RawData);
            DataLogger.Log("[ImageManager] [END OF FRAGMENT SHADER INFO LOG]", LoggingMode.Message);
#endif
            if (tmp != 1)
            {
                throw new Exception("Fragment Shader compilation failed. Process can't continue.");
            }

#if LOG_DATA
            DataLogger.Log("[ImageManager] Performing OpenGL program creation commands", LoggingMode.Message);
#endif
            int program = GL.CreateProgram();
            GL.AttachShader(program, vs);
            GL.AttachShader(program, fs);
            GL.BindAttribLocation(program, 0, "vPosition");
            GL.BindAttribLocation(program, 1, "vTexCoords");
            GL.LinkProgram(program);
            GL.DetachShader(program, vs);
            GL.DetachShader(program, fs);
            GL.DeleteProgram(vs);
            GL.DeleteProgram(fs);
            int texUniformLoc  = GL.GetUniformLocation(program, "tex");
            int projUniformLoc = GL.GetUniformLocation(program, "Proj");
            GL.UseProgram(program);
            GL.GetProgram(program, GetProgramParameterName.LinkStatus, out tmp);

#if LOG_DATA
            if (tmp != 1)
            {
                DataLogger.Log("[ImageManager] GL Program linking failed", LoggingMode.Error);
            }
            DataLogger.Log("[ImageManager] GL Program Info Log: ", LoggingMode.Message);
            DataLogger.Log(GL.GetProgramInfoLog(program), LoggingMode.RawData);
            DataLogger.Log("[ImageManager] [END OF GL PROGRAM INFO LOG]", LoggingMode.Message);
            DataLogger.Log("[ImageManager] Just a friendly reminder that GL PROGRAM refers to a OpenGL Shader Program with attached shaders", LoggingMode.Message);
#endif
            if (tmp != 1)
            {
                throw new Exception("Program linking failed. Process can't continue.");
            }
            #endregion

            #region MakeResultTextureFramebuffer
#if LOG_DATA
            DataLogger.Log("[ImageManager] Generating Framebuffer & Texture for rendering", LoggingMode.Message);
#endif
            int resultTex = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, resultTex);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, WIDTH, HEIGHT, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            fbo = GL.GenFramebuffer();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, resultTex, 0);
            if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete)
            { //error
#if LOG_DATA
                DataLogger.Log("[ImageManager] Framebuffer creation failed", LoggingMode.Error);
#endif
                throw new Exception("Framebuffer creation failed. Process can't continue.");
            }

            #endregion

            #region Drawing
#if LOG_DATA
            DataLogger.Log("[ImageManager] Performing OpenGL draw commands", LoggingMode.Message);
#endif
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo);
            GL.ClearColor(1f, 1f, 1f, 1f);
            GL.Clear(ClearBufferMask.ColorBufferBit);

            GL.UseProgram(program);
            Matrix4 mat = Matrix4.CreateOrthographicOffCenter(0, 1, 0, 1, -1, 1);
            GL.UniformMatrix4(projUniformLoc, false, ref mat);
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, tex);
            GL.Uniform1(texUniformLoc, 0);

            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BindVertexArray(vao);
            GL.Viewport(0, 0, WIDTH, HEIGHT - topHeight);
            GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);

            GL.Viewport(0, HEIGHT - topHeight, WIDTH, topHeight);
            qdraw.ProjectionMatrix = Matrix4.CreateTranslation(TEXT_BORDER_SPACE, topTextSize.Height + TEXT_BORDER_SPACE, 0) * Matrix4.CreateOrthographicOffCenter(0, WIDTH, 0, topHeight, -1, 1);
            qdraw.Draw();

            GL.Viewport(0, 0, WIDTH, HEIGHT - topHeight);

            opts.DropShadowActive = true;
            opts.DropShadowColour = Color.White;
            opts.DropShadowOffset = Vector2.Zero;//new Vector2(-0.12f, 0.12f);
            text = QFontDrawingPrimitive.ProcessText(qfont, opts, String.Concat("*", singular, " noises*"), new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Centre);
            SizeF noiseTextSize = qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts);
            float textScale     = Math.Min((WIDTH - TEXT_BORDER_SPACE * 4) / noiseTextSize.Width, (HEIGHT - TEXT_BORDER_SPACE * 4) / noiseTextSize.Height);

#if LOG_DATA
            DataLogger.Log("[ImageManager] Updating QFont size (disposing and reloading)", LoggingMode.Message);
#endif
            qfont.Dispose();
            qconfig.ShadowConfig = shadowConfig;
            qfont = new QFont(new FreeTypeFont(FONT_LOCATION, 144 * textScale, FontStyle.Regular), qconfig);

            qdraw.DrawingPrimitives.Clear();
            opts.Colour           = isBlack ? Color.Black : Color.White;
            opts.DropShadowColour = isBlack ? Color.White : Color.Black;
            text = QFontDrawingPrimitive.ProcessText(qfont, opts, String.Concat("*", singular, " noises*"), new SizeF(WIDTH - TEXT_BORDER_SPACE * 2, 99999f), QFontAlignment.Centre);
            qdraw.Print(qfont, text, new Vector3(0, 0, 0), opts);
            qdraw.ProjectionMatrix = Matrix4.CreateTranslation(WIDTH / 2f, noiseTextSize.Height * textScale / 2f + (HEIGHT - topHeight) / 2f, 0f) * Matrix4.CreateOrthographicOffCenter(0, WIDTH, 0, HEIGHT - topHeight, -1, 1);
            qdraw.RefreshBuffers();
            qdraw.Draw();
#if LOG_DATA
            DataLogger.Log("[ImageManager] Done drawing", LoggingMode.Success);
#endif
            #endregion

            #region Disposing
#if LOG_DATA
            DataLogger.Log("[ImageManager] Disposing MakeAllImage resources", LoggingMode.Message);
#endif
            bitmap.Dispose();
            qfont.Dispose();
            qdraw.Dispose();

            GL.DeleteProgram(program);
            GL.DeleteTexture(tex);
            GL.DeleteBuffer(vbo);
            GL.DeleteVertexArray(vao);
            #endregion

#if LOG_DATA
            DataLogger.Log("[ImageManager] MakeAllImage is done. Returning texture and framebuffer data", LoggingMode.Message);
#endif
            return(resultTex);
        }
Exemplo n.º 29
0
        /// <summary>Load resources here.</summary>
        /// <param name="e">Not used.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _drawing          = new QFontDrawing();
            _controlsDrawing  = new QFontDrawing();
            _controlsTextOpts = new QFontRenderOptions {
                Colour = Color.FromArgb(new Color4(0.8f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true
            };

            _heading2        = new QFont("woodenFont.qfont", new QFontConfiguration(true));
            _heading2Options = new QFontRenderOptions {
                Colour = Color.White, DropShadowActive = true
            };

            var builderConfig = new QFontBuilderConfiguration(true)
            {
                ShadowConfig =
                {
                    BlurRadius = 2,
                    BlurPasses = 1,
                    Type       = ShadowType.Blurred
                },
                TextGenerationRenderHint = TextGenerationRenderHint.ClearTypeGridFit,
                Characters = CharacterSet.General | CharacterSet.Japanese | CharacterSet.Thai | CharacterSet.Cyrillic
            };

            //reduce blur radius because font is very small
            //best render hint for this font
            _mainText        = new QFont("Fonts/times.ttf", 14, builderConfig);
            _mainTextOptions = new QFontRenderOptions {
                DropShadowActive = true, Colour = Color.White, WordSpacing = 0.5f
            };

            _benchmarkResults = new QFont("Fonts/times.ttf", 14, builderConfig);

            _heading1 = new QFont("Fonts/HappySans.ttf", 72, new QFontBuilderConfiguration(true));

            _controlsText = new QFont("Fonts/HappySans.ttf", 32, new QFontBuilderConfiguration(true));

            _codeText = new QFont("Fonts/Comfortaa-Regular.ttf", 12, new QFontBuilderConfiguration());

            _heading1Options = new QFontRenderOptions {
                Colour = Color.FromArgb(new Color4(0.2f, 0.2f, 0.2f, 1.0f).ToArgb()), DropShadowActive = true
            };
            _processedText   = QFontDrawingPrimitive.ProcessText(_mainText, _mainTextOptions, _preProcessed, new SizeF(Width - 40, -1), QFontAlignment.Left);
            _codeTextOptions = new QFontRenderOptions {
                Colour = Color.FromArgb(new Color4(0.0f, 0.0f, 0.4f, 1.0f).ToArgb())
            };

            _monoSpaced        = new QFont("Fonts/Anonymous.ttf", 10, new QFontBuilderConfiguration());
            _monoSpacedOptions = new QFontRenderOptions {
                Colour = Color.FromArgb(new Color4(0.1f, 0.1f, 0.1f, 1.0f).ToArgb()), DropShadowActive = true
            };

            // loop through some installed fonts and load them
            var ifc = new InstalledFontCollection();

            _installedFonts = new List <QFont>();

            foreach (var fontFamily in ifc.Families)
            {
                // Don't load too many fonts
                if (_installedFonts.Count > 15)
                {
                    break;
                }

                _installedFonts.Add(new QFont(fontFamily.Name, 14, new QFontBuilderConfiguration()));
            }

            GL.ClearColor(Color4.CornflowerBlue);
        }
Exemplo n.º 30
0
        public CoordinateSystem()
        {
            double triangleHeight  = tetraSide * Math.Sqrt(3.0 / 2.0);
            float  halfSideTetra   = (float)(tetraSide / 2.0);
            float  heightTriangle1 = (float)(triangleHeight * 1.0 / 3.0);
            float  heightTriangle2 = (float)(triangleHeight * 2.0 / 3.0);

            // Vertices
            float[] vertices =
            {
                0.0f,                                         0.0f,                     0.0f,  0.0f,  0.0f,  0.0f, // Origin
                // Axes
                lengthAxis,                                   0.0f,                     0.0f,  0.0f,  0.0f,  0.0f, // X-end
                0.0f,                     lengthAxis,                                   0.0f,  0.0f,  0.0f,  0.0f, // Y-end
                0.0f,                                         0.0f, lengthAxis,                0.0f,  0.0f,  0.0f, // Z-end
                // Tetrahedron at the end of X axis
                lengthAxis + heightTetra,                     0.0f,                     0.0f,  0.0f,  0.0f,  0.0f, // Peak
                lengthAxis,                       -heightTriangle1,           -halfSideTetra,  0.0f,  0.0f,  0.0f, // Left
                lengthAxis,                       -heightTriangle1, halfSideTetra,             0.0f,  0.0f,  0.0f, // Right
                lengthAxis,               heightTriangle2,                              0.0f,  0.0f,  0.0f,  0.0f, // Up
                // Tetrahedron at the end of Y axis
                0.0f,                     lengthAxis + heightTetra,                     0.0f,  0.0f,  0.0f,  0.0f, // Peak
                -heightTriangle1,         lengthAxis,                         -halfSideTetra,  0.0f,  0.0f,  0.0f, // Left
                -heightTriangle1,         lengthAxis,               halfSideTetra,             0.0f,  0.0f,  0.0f, // Right
                heightTriangle2,          lengthAxis,                                   0.0f,  0.0f,  0.0f,  0.0f, // Up
                // Tetrahedron at the end of Z axis
                0.0f,                                         0.0f, lengthAxis + heightTetra,  0.0f,  0.0f,  0.0f, // Peak
                -heightTriangle1,                   -halfSideTetra, lengthAxis,                0.0f,  0.0f,  0.0f, // Left
                -heightTriangle1,         halfSideTetra,            lengthAxis,                0.0f,  0.0f,  0.0f, // Right
                heightTriangle2,                              0.0f, lengthAxis,                0.0f,  0.0f,  0.0f, // Up
                // Box
                // XZ
                0.0f,                     sideBox,                                      0.0f,  0.0f, -1.0f,  0.0f,
                sideBox,                  sideBox,                                      0.0f,  0.0f, -1.0f,  0.0f,
                sideBox,                  sideBox,                  sideBox,                   0.0f, -1.0f,  0.0f,
                0.0f,                     sideBox,                  sideBox,                   0.0f, -1.0f,  0.0f,
                // XY
                0.0f,                                         0.0f, sideBox,                   0.0f,  0.0f, -1.0f,
                sideBox,                                      0.0f, sideBox,                   0.0f,  0.0f, -1.0f,
                // YZ
                sideBox,                                      0.0f,                     0.0f, -1.0f,  0.0f, 0.0f
            };
            vertexBuffer = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBuffer);
            GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StaticDraw);
            // Axes buffer
            uint[] axesIndices =
            {
                0, 1, // X
                0, 2, // Y
                0, 3  // Z
            };
            axesBuffer = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, axesBuffer);
            GL.BufferData(BufferTarget.ElementArrayBuffer, axesIndices.Length * sizeof(uint), axesIndices, BufferUsageHint.StaticDraw);
            // Tetrahedra
            tetrahedronBuffers = new int[3];
            // Base indices for X axis
            uint[] tetraIndices =
            {
                4, 5, 7,
                4, 6, 7,
                4, 5, 6,
                5, 6, 7
            };
            int nInd = tetraIndices.Length;

            for (uint iAxis = 0; iAxis != 3; ++iAxis)
            {
                tetrahedronBuffers[iAxis] = GL.GenBuffer();
                GL.BindBuffer(BufferTarget.ElementArrayBuffer, tetrahedronBuffers[iAxis]);
                GL.BufferData(BufferTarget.ElementArrayBuffer, nInd * sizeof(uint), tetraIndices, BufferUsageHint.StaticDraw);
                for (int i = 0; i != nInd; ++i)
                {
                    tetraIndices[i] += 4;
                }
            }
            // Box
            uint[] boxIndices =
            {
                16, 17, 18, 19,
                18, 19, 20, 21,
                17, 18, 21, 22,
            };
            boxBuffer = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, boxBuffer);
            GL.BufferData(BufferTarget.ElementArrayBuffer, boxIndices.Length * sizeof(uint), boxIndices, BufferUsageHint.StaticDraw);
            // Fonts
            fontRenderOptions = new QFontRenderOptions();
            fontDrawing       = new QFontDrawing();
        }