예제 #1
0
        protected override void OnLoad()
        {
            base.OnLoad();

            // initialize and bind framebuffer
            _framebuffer = new Framebuffer();
            _framebuffer.Bind(FramebufferTarget.Framebuffer);

            // initialize a renderbuffer and bind it to the depth attachment
            // to support depth testing while rendering to the texture
            _depthBuffer = new Renderbuffer();
            _depthBuffer.Init(RenderbufferStorage.DepthComponent, FramebufferWidth, FramebufferHeight);
            _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, _depthBuffer);

            // initialize texture and bind it to the color attachment
            _texture = new Texture2D(SizedInternalFormat.Rgba8, FramebufferWidth, FramebufferHeight, 1);
            _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, _texture);
            Framebuffer.Unbind(FramebufferTarget.Framebuffer);

            // initialize shaders
            _colorProgram   = ProgramFactory.Create <SimpleColorProgram>();
            _textureProgram = ProgramFactory.Create <SimpleTextureProgram>();

            // initialize demonstration geometry
            _cube = ShapeBuilder.CreateColoredCube(_colorProgram.InPosition, _colorProgram.InColor);
            _quad = ShapeBuilder.CreateTexturedQuad(_textureProgram.InPosition, _textureProgram.InTexCoord);

            // set camera position
            ActiveCamera.Position = new Vector3(0, 0, 3);

            // enable depth testing
            GL.Enable(EnableCap.DepthTest);
        }
예제 #2
0
        private IProgram Load(string name)
        {
            IProgram program = ProgramFactory.Load(name);

            programs[name] = program;
            return(program);
        }
        protected override void OnLoad()
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create <GravityProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();

            // create and bind transform feedback object
            _feedback = new TransformFeedback();
            _feedback.Bind();

            // Writing to a buffer while reading from it is not allowed
            // so we need two buffer objects here, which can be achieved by using the BufferPod<T> type.
            // It contains two buffers, Ping and Pong, to simplify this process.
            _buffers = new BufferPod <Particle>();
            InitializeParticles(_particleCount);

            // enable point sprite rendering
            GL.Enable(EnableCap.PointSprite);
            // enable modification of the point sprite size from the program (vertex shader in this case)
            GL.Enable(EnableCap.ProgramPointSize);
            // enable depth testing
            GL.Enable(EnableCap.DepthTest);
            // set a nice clear color
            GL.ClearColor(Color.Black);

            // set a nice camera angle
            Camera.DefaultState.Position = new Vector3(0, 2, -8);
            Camera.ResetToDefault();
        }
예제 #4
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);
        }
예제 #5
0
        public static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
            }
            else
            {
                var logger       = new LoggerService();
                var jSONManager  = new JSONManagerService();
                var inputManager = new InputManagerService(logger);

                var json         = (JObject)jSONManager.Read("./Data/Programs.json");
                var programsList = json["Programs"].ToObject <string[]>();
                var lastIndex    = programsList.Length - 1;
                var count        = 0;

                logger.Log("Design Patterns in .Net Core C#.\n");
                logger.Log($"Select an option between {0} and {lastIndex}:\n");

                foreach (var item in programsList)
                {
                    logger.Log($"{count}: {programsList[count++]}");
                }

                var response    = inputManager.RequestInt(min: 0, max: lastIndex);
                var programName = programsList[response];

                var programFactory = new ProgramFactory(logger);

                var program = programFactory.Create(programName);
                program.Run();

                Console.ReadKey();
            }
        }
예제 #6
0
 private void OnLoad(object sender, EventArgs e)
 {
     // maximize window
     WindowState = WindowState.Maximized;
     // load program
     _programOdd   = ProgramFactory.Create <GeodesicProgramOdd>();
     _programEqual = ProgramFactory.Create <GeodesicProgram>();
     _program      = _programOdd;
     // create icosahedron and set model matrix
     _modelMatrix = Matrix4.CreateScale(1);
     _icosahedron = new Icosahedron(5);
     _icosahedron.UpdateBuffers();
     // bind it to an vao
     _vao = new VertexArray();
     _vao.Bind();
     _vao.BindElementBuffer(_icosahedron.IndexBuffer);
     _vao.BindAttribute(_program.Position, _icosahedron.VertexBuffer);
     // set some reasonable default state
     GL.ClearColor(Color4.Black);
     GL.Enable(EnableCap.DepthTest);
     // backface culling is done in the tesselation control shader
     GL.Enable(EnableCap.CullFace);
     GL.CullFace(CullFaceMode.Back);
     GL.PatchParameter(PatchParameterInt.PatchVertices, 3);
     // lighting stuff
     _deferredRenderer = new DeferredRenderer();
     // enable controls
     _variableHandler.Enable(this);
 }
예제 #7
0
        protected override void OnLoad()
        {
            base.OnLoad();
            // load texture from file
            using (var bitmap = new Bitmap("Data/Textures/crate.png"))
            {
                BitmapTexture.CreateCompatible(bitmap, out _texture);
                _texture.LoadBitmap(bitmap);
            }

            // initialize shaders
            _textureProgram = ProgramFactory.Create <SimpleTextureProgram>();

            // initialize cube object and base view matrix
            _objectView = _baseView = Matrix4.Identity;

            // initialize demonstration geometry
            _cube = ShapeBuilder.CreateTexturedCube(_textureProgram.InPosition, _textureProgram.InTexCoord);

            // Enable culling, our cube vertices are defined inside out, so we flip them
            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Back);

            // initialize camera position
            ActiveCamera.Position = new Vector3(0, 0, 4);

            // set nice clear color
            GL.ClearColor(Color.MidnightBlue);

            _stopwatch.Restart();
        }
예제 #8
0
파일: Sprite.cs 프로젝트: kroltan/SmallTK
        private void GenerateMesh(int width, int height)
        {
            if (_initialized)
            {
                Dispose();
            }

            _sampler = new Sampler();
            _sampler.SetWrapMode(TextureWrapMode.Clamp);

            _program = ProgramFactory.Create <SpriteShaderProgram>();

            var w = width / 2;
            var h = height / 2;

            var vertices = new[] {
                new Vertex(-w, h, 0, 0, 0),
                new Vertex(w, h, 0, 1, 0),
                new Vertex(-w, -h, 0, 0, 1),
                new Vertex(w, -h, 0, 1, 1)
            };

            _vbo = new Buffer <Vertex>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            _vao = new VertexArray();
            _vao.Bind();
            _vao.BindAttribute(_program.InPosition, _vbo);
            _vao.BindAttribute(_program.InTexCoord, _vbo, 12);
            _initialized = true;
        }
예제 #9
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create <ExampleProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create vertices for a triangle
            var vertices = new[] { new Vector3(-1, -1, 0), new Vector3(1, -1, 0), new Vector3(0, 1, 0) };

            // create buffer object and upload vertex data
            _vbo = new Buffer <Vector3>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();
            // set up binding of the shader variable to the buffer object
            _vao.BindAttribute(_program.InPosition, _vbo);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0, 0, 3);
            Camera.ResetToDefault();

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
예제 #10
0
 public DeferredRenderer()
 {
     _directionalProgram = ProgramFactory.Create <DirectionalLightProgram>();
     _pointProgram       = ProgramFactory.Create <PointLightProgram>();
     _quad = new Quad();
     _quad.UpdateBuffers();
     _vaoFullScreenQuad = new VertexArray();
     _vaoFullScreenQuad.Bind();
     _vaoFullScreenQuad.BindAttribute(_directionalProgram.Position, _quad.VertexBuffer);
 }
예제 #11
0
        protected override void OnLoad()
        {
            base.OnLoad();
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create <SimpleColorProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();


            //arbitrary black box to load mesh data
            string   jsonString = File.ReadAllText("./Data/Meshes/OpenTK.fakeformat");
            MeshData meshData   = JsonSerializer.Deserialize <MeshData>(jsonString);


            Buffer <uint> IndexBuffer = new Buffer <uint>();

            IndexBuffer.Init(BufferTarget.ElementArrayBuffer, meshData.Indices.Select(index => index - 1).ToArray());

            Buffer <Vector3> VertBuffer = new Buffer <Vector3>();

            VertBuffer.Init(BufferTarget.ArrayBuffer, Enumerable.Range(0, meshData.Vertices.Count / 3).Select(a => new Vector3(meshData.Vertices[a * 3], meshData.Vertices[a * 3 + 1], meshData.Vertices[a * 3 + 2])).ToArray());

            //a bit of a hack, i wanted the mesh to have some visual depth.
            //the only reason this works is I just happen to know the Z coordinate for the mesh is in a certain range
            //other meshes will either look stupid or just throw exceptions because the color values are out of range
            Buffer <uint> ColorBuffer = new Buffer <uint>();

            ColorBuffer.Init(BufferTarget.ArrayBuffer, VertBuffer.Content.Select(vertex => (uint)Color.FromArgb((int)(vertex.Z * 500) + 100, (int)(vertex.Z * 500) + 100, (int)(vertex.Z * 500) + 100).ToArgb()).ToArray());


            mesh = new DynamicShape()
                   .WithVertexAttrib(_program.InPosition, VertBuffer)
                   .WithVertexAttrib(_program.InColor, ColorBuffer)
                   .WithElementBuffer(IndexBuffer)
                   .WithDisposeFunction(() => {
                VertBuffer?.Dispose();
                IndexBuffer?.Dispose();
                ColorBuffer?.Dispose();
            })
                   .SetDrawFunction((VAO) => {
                VAO.DrawElements(PrimitiveType.Triangles, IndexBuffer.ElementCount);
            });

            // set camera position
            ActiveCamera.Position = new Vector3(0, 0, 3);

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);

            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Back);
        }
예제 #12
0
        public static List <Program> GetPrograms()
        {
            List <Program> allPrograms = new List <Program>();

            using (Models.TrackerContext trackerDatabase = new Models.TrackerContext())
            {
                var programs = trackerDatabase.Programs.ToList();
                programs.ForEach(p => { allPrograms.Add(ProgramFactory.Create_Client_From_Database(p)); });
            }

            return(allPrograms);
        }
예제 #13
0
 public static void InitializeResources()
 {
     ColorShader     = ProgramFactory.Create <ColorShaderProgram>();
     WireframeShader = ProgramFactory.Create <WireframeShaderProgram>();
     ModelShader     = ProgramFactory.Create <ModelShaderProgram>();
     ModelShader.Use();
     ModelShader.LightCount.Set(0);
     ModelShader.Lights.Set(new LightInfo[0]);
     WireframeShader2     = ProgramFactory.Create <WireframeShader2Program>();
     StudConnectionShader = ProgramFactory.Create <StudConnectionShaderProgram>();
     SimpleTextureShader  = ProgramFactory.Create <SimpleTextureShaderProgram>();
     GridShader           = ProgramFactory.Create <GridShaderProgram>();
 }
예제 #14
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize and bind framebuffer
            _framebuffer = new Framebuffer();
            _framebuffer.Bind(FramebufferTarget.Framebuffer);

            // initialize a renderbuffer and bind it to the depth attachment
            // to support depth testing while rendering to the texture
            _depthBuffer = new Renderbuffer();
            _depthBuffer.Init(RenderbufferStorage.DepthComponent, FramebufferWidth, FramebufferHeight);
            _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, _depthBuffer);

            // initialize texture and bind it to the color attachment
            _texture = new Texture2D(SizedInternalFormat.Rgba8, FramebufferWidth, FramebufferHeight, 1);
            _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, _texture);
            Framebuffer.Unbind(FramebufferTarget.Framebuffer);

            // initialize demonstration geometry
            _cube = new ColorCube();
            _cube.UpdateBuffers();
            _quad = new TexturedQuad();
            _quad.UpdateBuffers();

            // initialize shaders
            _colorProgram   = ProgramFactory.Create <SimpleColorProgram>();
            _textureProgram = ProgramFactory.Create <SimpleTextureProgram>();

            // set up vertex attributes for the cube
            _cubeVao = new VertexArray();
            _cubeVao.Bind();
            _cubeVao.BindAttribute(_colorProgram.InPosition, _cube.VertexBuffer);
            _cubeVao.BindAttribute(_colorProgram.InColor, _cube.ColorBuffer);
            _cubeVao.BindElementBuffer(_cube.IndexBuffer);

            // set up vertex attributes for the quad
            _quadVao = new VertexArray();
            _quadVao.Bind();
            _quadVao.BindAttribute(_textureProgram.InPosition, _quad.VertexBuffer);
            _quadVao.BindAttribute(_textureProgram.InTexCoord, _quad.TexCoordBuffer);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0, 0, 3);
            Camera.ResetToDefault();

            // enable depth testing
            GL.Enable(EnableCap.DepthTest);
        }
예제 #15
0
        private void _run()
        {
            var         factory = new ProgramFactory(_options);
            var         runner  = new ProgramRunner();
            RuntimeInfo ri;

            while ((ri = _stats.Add()) != null)
            {
                var smallSeed = Interlocked.Increment(ref _seed);
                var bigSeed   = BinaryUtils.GenerateSeed(smallSeed);
                var p         = factory.GenProgram(bigSeed);
                runner.WriteProgram(p);
                runner.ExecuteProgram(ri);
                ri.Seed = BinaryUtils.ByteArrayToString(bigSeed);
                Progress?.Invoke(this, EventArgs.Empty);
            }
        }
예제 #16
0
        protected override void OnLoad()
        {
            // load textures into array
            for (var i = 0; i < _stateTextures.Length; i++)
            {
                using (var bitmap = new Bitmap(Path.Combine("Data/Textures/", _stateTextures[i])))
                {
                    bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    if (_textureArray == null)
                    {
                        BitmapTexture.CreateCompatible(bitmap, out _textureArray, _stateTextures.Length, 1);
                    }
                    _textureArray.LoadBitmap(bitmap, i);
                }
            }
            // initialize buffer
            var field = new Minefield[FieldWidth * FieldHeight];

            for (var i = 0; i < field.Length; i++)
            {
                field[i] = new Minefield(i % FieldWidth, i / FieldHeight, i % _stateTextures.Length);
            }
            _buffer = new Buffer <Minefield>();
            _buffer.Init(BufferTarget.ArrayBuffer, field);
            // load program
            _gridProgram = ProgramFactory.Create <TextureGridProgram>();
            _gridProgram.Use();
            // bind the texture and set uniform
            _gridProgram.TextureData.BindTexture(TextureUnit.Texture0, _textureArray);
            // set up vertex array and attributes
            _vao = new VertexArray();
            _vao.Bind();
            _vao.BindAttribute(_gridProgram.InPosition, _buffer);
            _vao.BindAttribute(_gridProgram.InTexture, _buffer, 8);
            // set nice clear color
            GL.ClearColor(Color.MidnightBlue);
            // initialize camera position
            Camera.DefaultState.Position = new Vector3(0, 5, 15);
            Camera.ResetToDefault();
        }
예제 #17
0
 protected override void OnLoad()
 {
     // initialize shader
     _program = ProgramFactory.Create <SkyboxProgram>();
     // initialize cube shape
     _cube = new Cube();
     _cube.UpdateBuffers();
     // initialize vertex array and attributes
     _vao = new VertexArray();
     _vao.Bind();
     _vao.BindAttribute(_program.InPosition, _cube.VertexBuffer);
     _vao.BindElementBuffer(_cube.IndexBuffer);
     // create cubemap texture and load all faces
     for (var i = 0; i < 6; i++)
     {
         using (var bitmap = new Bitmap(string.Format("Data/Textures/city{0}.jpg", i)))
         {
             bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
             if (_skybox == null)
             {
                 BitmapTexture.CreateCompatible(bitmap, out _skybox, 1);
             }
             _skybox.LoadBitmap(bitmap, i);
         }
     }
     // activate shader and bind texture to it
     _program.Use();
     _program.Texture.BindTexture(TextureUnit.Texture0, _skybox);
     // enable seamless filtering to reduce artifacts at the edges of the cube faces
     GL.Enable(EnableCap.TextureCubeMapSeamless);
     // cull front faces because we are inside the cube
     // this is not really necessary but removes some artifacts when the user leaves the cube
     // which should be impossible for a real skybox, but in this demonstration it is possible by zooming out
     GL.Enable(EnableCap.CullFace);
     GL.CullFace(CullFaceMode.Front);
     // set a nice clear color
     GL.ClearColor(Color.MidnightBlue);
 }
예제 #18
0
        protected override void OnLoad()
        {
            // load texture from file
            using (var bitmap = new Bitmap("Data/Textures/crate.png"))
            {
                BitmapTexture.CreateCompatible(bitmap, out _texture);
                _texture.LoadBitmap(bitmap);
            }

            // initialize shaders
            _textureProgram = ProgramFactory.Create <SimpleTextureProgram>();

            // initialize cube object and base view matrix
            _objectView = _baseView = Matrix4.Identity;

            // initialize demonstration geometry
            _cube = new TexturedCube();
            _cube.UpdateBuffers();

            // set up vertex attributes for the quad
            _cubeVao = new VertexArray();
            _cubeVao.Bind();
            _cubeVao.BindAttribute(_textureProgram.InPosition, _cube.VertexBuffer);
            _cubeVao.BindAttribute(_textureProgram.InTexCoord, _cube.TexCoordBuffer);

            // Enable culling, our cube vertices are defined inside out, so we flip them
            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Back);

            // initialize camera position
            Camera.DefaultState.Position = new Vector3(0, 0, 4);
            Camera.ResetToDefault();

            // set nice clear color
            GL.ClearColor(Color.MidnightBlue);

            _stopwatch.Restart();
        }
예제 #19
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);
        }
예제 #20
0
        static int Main(string[] args)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

            int    threads                  = 1;
            int    count                    = 1000;
            long   seed                     = DateTime.UtcNow.Ticks;
            bool   objective                = false;
            bool   useCustomOptions         = false;
            double runtimeTarget            = 0.01; //10 ms
            double runtimeWeight            = 3e+7;
            double percentileWeight         = 500.0;
            double entropyWeight            = 1000.0;
            double linesOfCodeWeight        = 0.05;
            double halsteadDifficultyWeight = 0.5;
            double percentile               = 0.999;
            double entropyLimit             = 512;
            double evalTestWeightValidity   = 20.0;
            double evalTestWeightRuntime    = 40.0;
            bool   verbose                  = false;
            int    timeout                  = -1;
            bool   evalTest                 = false;
            bool   help                     = false;
            Uri    runnerUri                = new Uri("http://localhost:18111");
            bool   debug                    = false;
            string outfile                  = null;

            ProgramOptions customOptions = new ProgramOptions();

            customOptions.Initialize();
            Action <string> coValidate = (string s) =>
            {
                if (!useCustomOptions)
                {
                    throw new InvalidOperationException($"The option {s} must be preceded by --customOptions");
                }
            };

            OptionSet p = new OptionSet()
                          .Add("threads=", (int i) => threads         = i)
                          .Add("count=", (int i) => count             = i)
                          .Add("seed=", (long i) => seed              = i)
                          .Add("timeout=", (int i) => timeout         = 1000 * i)
                          .Add("objective", s => objective            = true)
                          .Add("customOptions", s => useCustomOptions = true)
                          .Add("verbose", s => verbose = true)
                          .Add("runtimeTarget=", (double d) => runtimeTarget         = d)
                          .Add("runtimeWeight=", (double d) => runtimeWeight         = d)
                          .Add("percentileWeight=", (double d) => percentileWeight   = d)
                          .Add("percentile=", (double d) => percentile               = d)
                          .Add("entropyWeight=", (double d) => entropyWeight         = d)
                          .Add("entropyLimit=", (double d) => entropyLimit           = d)
                          .Add("linesOfCodeWeight=", (double d) => linesOfCodeWeight = d)
                          .Add("halsteadDifficultyWeight=", (double d) => halsteadDifficultyWeight = d)
                          .Add("evalTest", s => evalTest = true)
                          .Add("evalTestWeightValidity=", (double d) => evalTestWeightValidity = d)
                          .Add("evalTestWeightRuntime=", (double d) => evalTestWeightRuntime   = d)
                          .Add("help|h", s => help          = true)
                          .Add("runnerUri=", s => runnerUri = new Uri(s))
                          .Add("debug", s => debug          = true)
                          .Add("outfile=", s => outfile     = s);


            foreach (var prop in typeof(ProgramOptions).GetProperties())
            {
                var pt = prop.PropertyType;
                if (pt.BaseType != null && pt.BaseType.IsGenericType && pt.BaseType.GetGenericTypeDefinition() == typeof(RandomTable <>))
                {
                    var itemType  = pt.BaseType.GetGenericArguments()[0];
                    var instance  = prop.GetValue(customOptions);
                    var addMethod = pt.BaseType.GetMethod("Add", new Type[] { itemType, typeof(double) });
                    foreach (var fld in itemType.GetFields(BindingFlags.Static | BindingFlags.Public))
                    {
                        string optionName = "XML_" + prop.Name + "_" + fld.Name;
                        //Console.WriteLine($"Adding option --{optionName}");
                        p.Add(optionName + "=", (double w) =>
                        {
                            coValidate(optionName);
                            addMethod.Invoke(instance, new object[] { fld.GetValue(null), w });
                        });
                    }
                }
                else if (pt == typeof(Interval))
                {
                    var    instance      = prop.GetValue(customOptions);
                    var    minProp       = pt.GetProperty(nameof(Interval.Min));
                    string optionNameMin = "XML_" + prop.Name + "_" + nameof(Interval.Min);
                    //Console.WriteLine($"Adding option --{optionNameMin}");
                    p.Add(optionNameMin + "=", (int i) =>
                    {
                        coValidate(optionNameMin);
                        minProp.SetValue(instance, i);
                    });
                    var    rangeProp       = pt.GetProperty(nameof(Interval.Span));
                    string optionNameRange = "XML_" + prop.Name + "_" + nameof(Interval.Span);
                    //Console.WriteLine($"Adding option --{optionNameRange}");
                    p.Add(optionNameRange + "=", (int i) =>
                    {
                        coValidate(optionNameRange);
                        rangeProp.SetValue(instance, i);
                    });
                }
                else
                {
                    string optionName = "XML_" + prop.Name;
                    //Console.WriteLine($"Adding option --{optionName}");
                    if (pt == typeof(int))
                    {
                        p.Add(optionName + "=", (int i) =>
                        {
                            coValidate(optionName);
                            prop.SetValue(customOptions, i);
                        });
                    }
                    if (pt == typeof(double))
                    {
                        p.Add(optionName + "=", (double d) =>
                        {
                            coValidate(optionName);
                            prop.SetValue(customOptions, d);
                        });
                    }
                    if (pt == typeof(bool))
                    {
                        p.Add(optionName + "=", (bool b) =>
                        {
                            coValidate(optionName);
                            prop.SetValue(customOptions, b);
                        });
                    }
                }
            }

            var unknown = p.Parse(args);

            if (help)
            {
                p.WriteOptionDescriptions(Console.Out);
                return(0);
            }

            /*if (unknown.Any())
             * {
             *  Console.WriteLine($"Unknown option '{unknown.First()}'");
             *  return 1;
             * }*/

            var options = useCustomOptions ? customOptions : ProgramOptions.FromXml();

            if (count == 1 && outfile != null && outfile.Length == 64 && outfile.All(c => "0123456789abcdef".Contains(c)))
            {
                var factory = new ProgramFactory(options);
                var pr      = factory.GenProgram(BinaryUtils.StringToByteArray(outfile));
                using (var file = System.IO.File.CreateText(outfile + ".js"))
                    pr.WriteTo(file);

                var runner = Run.ProgramRunnerBase.FromUri(runnerUri);
                runner.WriteProgram(pr);
                var ri = runner.ExecuteProgram();
                Console.WriteLine(ri.Output);
                Console.WriteLine($"Success = {ri.Success}");
                return(0);
            }

            var stats = MakeStats(threads, count, timeout, seed, options, objective, evalTest, runnerUri);

            if (objective)
            {
                if (stats != null && stats.IsComplete)
                {
                    var runtime1     = runtimeWeight * (stats.Runtime.Average - runtimeTarget) * (stats.Runtime.Average - runtimeTarget);
                    var runtime2     = percentileWeight * stats.Runtime.GetPercentile(percentile);
                    var entropy      = entropyWeight / Math.Max(1, stats.OutputEntropy - entropyLimit);
                    var loc          = -linesOfCodeWeight * stats.LinesOfCode.Average;
                    var halstead     = -halsteadDifficultyWeight * stats.HalsteadDifficulty.Average;
                    var evalWeakness = 0.0;

                    if (evalTest)
                    {
                        evalWeakness = evalTestWeightValidity / Math.Max(0.05, 1.0 - stats.SyntaxErrorValidity) - evalTestWeightRuntime * stats.SyntaxErrorRuntime;
                    }

                    if (verbose)
                    {
                        Console.WriteLine($"Runtime: {runtime1:0.000}");
                        Console.WriteLine($"Percentile: {runtime2:0.000}");
                        Console.WriteLine($"Entropy: {entropy:0.000}");
                        Console.WriteLine($"Lines of code: {loc:0.000}");
                        Console.WriteLine($"Halstead: {halstead:0.000}");
                        if (evalTest)
                        {
                            Console.WriteLine($"EvalWeakness: {evalWeakness:0.000}");
                        }
                    }

                    Console.WriteLine(runtime1 + runtime2 + entropy + loc + halstead + evalWeakness);
                }
                else
                {
                    Console.WriteLine(int.MaxValue);
                }
                return(0);
            }
            else if (stats != null && stats.IsComplete)
            {
                Console.WriteLine(stats.ToString(verbose, debug));
                return(0);
            }
            else
            {
                return(1);
            }
        }
예제 #21
0
 public void ClearProgram()
 {
     this.p = null;
 }
예제 #22
0
 public SpawnNode(ProgramFactory p)
     : base()
 {
     this.p = p;
 }
예제 #23
0
 public SpawnNode()
     : base()
 {
     p = null;
 }
예제 #24
0
        //public static Buffer<StudGridCell> StudGridBuffer { get; private set; }

        #endregion

        public static void InitializeResources()
        {
            ColorShader          = ProgramFactory.Create <ColorShaderProgram>();
            WireframeShader      = ProgramFactory.Create <WireframeShaderProgram>();
            ModelShader          = ProgramFactory.Create <ModelShaderProgram>();
            WireframeShader2     = ProgramFactory.Create <WireframeShader2Program>();
            StudConnectionShader = ProgramFactory.Create <StudConnectionShaderProgram>();
            SimpleTextureShader  = ProgramFactory.Create <SimpleTextureShaderProgram>();

            BoundingBoxBufffer = new IndexedVertexBuffer <Vector3>();
            var box = BBox.FromCenterSize(Vector3.Zero, Vector3.One);

            BoundingBoxBufffer.SetVertices(box.GetCorners());
            var bboxIndices = new List <int>();

            for (int i = 0; i < 4; i++)
            {
                bboxIndices.Add((i * 2));
                bboxIndices.Add((i * 2) + 1);
                bboxIndices.Add((i * 2));
                bboxIndices.Add(((i + 1) * 2) % 8);
                bboxIndices.Add((i * 2) + 1);
                bboxIndices.Add((((i + 1) * 2) + 1) % 8);
            }

            BoundingBoxBufffer.SetIndices(bboxIndices);

            //StudGridBuffer = new Buffer<StudGridCell>();


            CollisionMaterial = new MaterialInfo
            {
                Diffuse   = new Vector4(1f, 0.05f, 0.05f, 1f),
                Specular  = new Vector3(1f),
                Shininess = 2f
            };

            ConnectionMaterial = new MaterialInfo
            {
                Diffuse   = new Vector4(0.95f, 0.95f, 0.05f, 1f),
                Specular  = new Vector3(1f),
                Shininess = 2f
            };

            MaleConnectorMaterial = new MaterialInfo
            {
                Diffuse   = new Vector4(0.05f, 0.05f, 0.95f, 1f),
                Specular  = new Vector3(1f),
                Shininess = 2f
            };

            FemaleConnectorMaterial = new MaterialInfo
            {
                Diffuse   = new Vector4(0.05f, 0.95f, 0.05f, 1f),
                Specular  = new Vector3(1f),
                Shininess = 2f
            };

            WireframeColor        = new Vector4(0, 0, 0, 1f);
            WireframeColorAlt     = new Vector4(0.85f, 0.85f, 0.85f, 1f);
            SelectionOutlineColor = new Vector4(1f);
        }
예제 #25
0
        private void OnLoad(object sender, EventArgs e)
        {
            // load texture from file
            using (var bitmap = new Bitmap("Data/Textures/checker.jpg"))
            {
                BitmapTexture.CreateCompatible(bitmap, out _texture);
                _texture.LoadBitmap(bitmap);
            }
            _texture.GenerateMipMaps();

            // initialize sampler
            _sampler = new Sampler();
            _sampler.SetWrapMode(TextureWrapMode.Repeat);

            // create vertex data for a big plane
            const int a        = 10;
            const int b        = 10;
            var       vertices = new[]
            {
                new Vertex(-a, 0, -a, 0, 0),
                new Vertex(a, 0, -a, b, 0),
                new Vertex(-a, 0, a, 0, b),
                new Vertex(a, 0, a, b, b)
            };

            // create buffer object and upload vertex data
            _vbo = new Buffer <Vertex>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // initialize shader
            _program = ProgramFactory.Create <SimpleTextureProgram>();
            // activate shader program
            _program.Use();
            // bind sampler
            _sampler.Bind(TextureUnit.Texture0);
            // bind texture
            _program.Texture.BindTexture(TextureUnit.Texture0, _texture);
            // which is equivalent to
            //_program.Texture.Set(TextureUnit.Texture0);
            //_texture.Bind(TextureUnit.Texture0);

            // set up vertex array and attributes
            _vao = new VertexArray();
            _vao.Bind();
            // memory layout of our data is XYZUVXYZUV...
            // the buffer abstraction knows the total size of one "pack" of vertex data
            // and if a vertex attribute is bound without further arguments the first N elements are taken from each pack
            // where N is provided via the VertexAttribAttribute on the program property:
            _vao.BindAttribute(_program.InPosition, _vbo);
            // if data should not be taken from the start of each pack, the offset must be given in bytes
            // to reach the texture coordinates UV the XYZ coordinates must be skipped, that is 3 floats, i.e. an offset of 12 bytes is needed
            _vao.BindAttribute(_program.InTexCoord, _vbo, 12);
            // if needed all the available arguments can be specified manually, e.g.
            //_vao.BindAttribute(_program.InTexCoord, _vbo, 2, VertexAttribPointerType.Float, Marshal.SizeOf(typeof(Vertex)), 12, false);

            // set default camera
            Camera.DefaultState.Position = new Vector3(0, 0.5f, 3);
            Camera.ResetToDefault();

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
예제 #26
0
        protected override void OnLoad()
        {
            VSync = VSyncMode.Off;

            // Check for necessary capabilities:
            var extensions = GL.GetString(StringName.Extensions);

            if (!GL.GetString(StringName.Extensions).Contains("GL_ARB_shading_language"))
            {
                throw new NotSupportedException(String.Format("This example requires OpenGL 2.0. Found {0}. Aborting.",
                                                              GL.GetString(StringName.Version).Substring(0, 3)));
            }

            if (!extensions.Contains("GL_ARB_texture_compression") ||
                !extensions.Contains("GL_EXT_texture_compression_s3tc"))
            {
                throw new NotSupportedException("This example requires support for texture compression. Aborting.");
            }

            var temp = new int[1];

            GL.GetInteger(GetPName.MaxTextureImageUnits, out temp[0]);
            Trace.WriteLine(temp[0] + " TMU's for Fragment Shaders found. (2 required)");

            GL.GetInteger(GetPName.MaxVaryingFloats, out temp[0]);
            Trace.WriteLine(temp[0] + " varying floats between VS and FS allowed. (6 required)");

            GL.GetInteger(GetPName.MaxVertexUniformComponents, out temp[0]);
            Trace.WriteLine(temp[0] + " uniform components allowed in Vertex Shader. (6 required)");

            GL.GetInteger(GetPName.MaxFragmentUniformComponents, out temp[0]);
            Trace.WriteLine(temp[0] + " uniform components allowed in Fragment Shader. (11 required)");
            Trace.WriteLine("");

            // load textures
            TextureLoaderParameters.MagnificationFilter = TextureMagFilter.Linear;
            TextureLoaderParameters.MinificationFilter  = TextureMinFilter.LinearMipmapLinear;
            TextureLoaderParameters.WrapModeS           = TextureWrapMode.ClampToBorder;
            TextureLoaderParameters.WrapModeT           = TextureWrapMode.ClampToBorder;
            TextureLoaderParameters.EnvMode             = TextureEnvMode.Modulate;

            uint          handle;
            TextureTarget target;

            ImageDDS.LoadFromDisk(TextureDiffuseHeightFilename, out handle, out target);
            _textureDiffuseHeight = TextureFactory.AquireTexture2D((int)handle);
            Trace.WriteLine("Loaded " + TextureDiffuseHeightFilename + " with handle " + handle + " as " + target);

            ImageDDS.LoadFromDisk(TextureNormalGlossFilename, out handle, out target);
            _textureNormalGloss = TextureFactory.AquireTexture2D((int)handle);
            Trace.WriteLine("Loaded " + TextureNormalGlossFilename + " with handle " + handle + " as " + target);

            Trace.WriteLine("End of Texture Loading. GL Error: " + GL.GetError());
            Trace.WriteLine("");

            // initialize buffer
            var normal   = Vector3.UnitZ;
            var tangent  = Vector3.UnitX;
            var vertices = new[]
            {
                new Vertex
                {
                    Position = new Vector3(-1, -1, 0),
                    TexCoord = new Vector2(0, 0),
                    Normal   = normal,
                    Tangent  = tangent
                },
                new Vertex
                {
                    Position = new Vector3(1, -1, 0),
                    TexCoord = new Vector2(1, 0),
                    Normal   = normal,
                    Tangent  = tangent
                },
                new Vertex
                {
                    Position = new Vector3(-1, 1, 0),
                    TexCoord = new Vector2(0, 1),
                    Normal   = normal,
                    Tangent  = tangent
                },
                new Vertex
                {
                    Position = new Vector3(1, 1, 0),
                    TexCoord = new Vector2(1, 1),
                    Normal   = normal,
                    Tangent  = tangent
                }
            };

            _buffer = new Buffer <Vertex>();
            _buffer.Init(BufferTarget.ArrayBuffer, vertices);

            // load shader
            _program = ProgramFactory.Create <ParallaxProgram>();
            _program.Use();

            // set up vertex array
            _vao = new VertexArray();
            _vao.Bind();
            // bind vertex attributes
            // the buffer layout is defined by the Vertex struct:
            //   data X Y Z NX NY NZ TX TY TZ  U  V *next vertex*
            // offset 0 4 8 12 16 20 24 28 32 36 40      44
            // having to work with offsets could be prevented by using seperate buffer objects for each attribute,
            // but that might reduce performance and can get annoying as well.
            // performance increase could also be achieved by improving coherent read access
            // by padding the struct so that each attribute begins at a multiple of 16 bytes, i.e. 4-floats
            // because the GPU can then read all 4 floats at once. I did not do that here to keep it simple.
            _vao.BindAttribute(_program.InPosition, _buffer);
            _vao.BindAttribute(_program.InNormal, _buffer, 12);
            _vao.BindAttribute(_program.InTangent, _buffer, 24);
            _vao.BindAttribute(_program.InTexCoord, _buffer, 36);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0, 0, 3);
            Camera.ResetToDefault();

            // set state
            GL.ClearColor(0.2f, 0f, 0.4f, 0f);
            GL.PointSize(10f);
            GL.Disable(EnableCap.Dither);
            GL.FrontFace(FrontFaceDirection.Ccw);
            GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill);
            GL.PolygonMode(MaterialFace.Back, PolygonMode.Line);
        }
예제 #27
0
        private void _run(CancellationToken token)
        {
            var factory = new ProgramFactory(_options);
            //var defaultRunner = new ProgramRunner();
            //var runnerNode = new ExternalProgramRunner("node", @"..\fast-eval.js");
            //var runnerXS = new ExternalProgramRunner(@"..\moddable\build\bin\win\release\xst.exe");
            var         runner = ProgramRunnerBase.FromUri(_runnerUri);
            RuntimeInfo ri;

            while (!token.IsCancellationRequested && (ri = _stats.Add()) != null)
            {
                var smallSeed = Interlocked.Increment(ref _seed);
                var bigSeed   = BinaryUtils.GenerateSeed(smallSeed);
                ri.Seed = BinaryUtils.ByteArrayToString(bigSeed);
                var p = factory.GenProgram(bigSeed);
                runner.WriteProgram(p);
                runner.ExecuteProgram(ri);
                if (!ri.Success)
                {
                    throw new InvalidProgramException();
                }

                /*bool retry = true;
                 * while (!ri.Success && retry)
                 * {
                 *  Console.WriteLine($"Error with seed {ri.Seed}");
                 *  retry = false;
                 *  runner.WriteProgram(p);
                 *  runner.ExecuteProgram(ri);
                 * }
                 * if (ri.Success)
                 * {
                 *  Console.WriteLine($"Success with seed {ri.Seed}");
                 * }
                 * else
                 * {
                 *  Console.WriteLine(ri.Output);
                 * }*/
                /*runnerXS.WriteProgram(p);
                 * var xs = runnerXS.ExecuteProgram();
                 * xs.Output = xs.Output.Replace("\r", "");
                 * if(!(ri.MatchXS = ri.Output == xs.Output))
                 * {
                 *  Console.WriteLine($"Outputs differ with seed {ri.Seed}");
                 *  var xsLines = xs.Output.Split('\n');
                 *  var riLines = ri.Output.Split('\n');
                 *  if(xsLines.Length != riLines.Length)
                 *  {
                 *      Console.WriteLine("NODE:");
                 *      Console.WriteLine(ri.Output);
                 *      Console.WriteLine("--------------------");
                 *      Console.WriteLine("XS:");
                 *      Console.WriteLine(xs.Output);
                 *      Console.WriteLine("--------------------");
                 *      throw new InvalidProgramException("Number of lines differ");
                 *  }
                 *  for(int i = 0; i < xsLines.Length; ++i)
                 *  {
                 *      if(xsLines[i] != riLines[i])
                 *      {
                 *          Console.WriteLine($"NODE: {riLines[i]}");
                 *          Console.WriteLine($"XS: {xsLines[i]}");
                 *      }
                 *  }
                 * }*/
                if (_evalTest)
                {
                    runner.WriteProgram(new SyntaxErrorProgram(p));
                    var se = new RuntimeInfo()
                    {
                        CyclomaticComplexity = -1
                    };
                    runner.ExecuteProgram(se);
                    ri.MatchSyntaxError   = (se.Output == ri.Output);
                    ri.SyntaxErrorRuntime = se.Runtime / ri.Runtime;
                }
                Progress?.Invoke(this, EventArgs.Empty);
            }
        }
예제 #28
0
 public ProgramFactoryTest()
 {
     _programFactory = new ProgramFactory(new LoggerService());
 }