コード例 #1
0
ファイル: SimpleSimulation.cs プロジェクト: aidint/SimExpert
        public override Statistics run()
        {
            Environment env = new Environment();

            //dist
            List<double> valueList = new List<double>() { 1, 2, 3, 4, 5 };
            List<double> distribution = new List<double>() { 0.5, 0.6, 0.7, 0.8, 1.0 };
            Discrete d = new Discrete(valueList, distribution);
            //dist1
            Uniform n = new Uniform(1, 3);
            Distribution dist = new Distribution(d);
            Distribution dist1 = new Distribution(n);

            Create c = new Create(env, 0, 20, dist);

            Dispose di = new Dispose(env, 1);

            Queue q = new Queue(env, 3);
            q.Capacity = 1;
            Resource r = new Resource(env, 2, 1, dist1, q);

            c.Next_AID.Add("First", 2);
            r.Next_AID.Add("First", 1);

            env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Setup_Simulation();
            return env.Simulate();
        }
コード例 #2
0
 public Matrix4 this[Uniform uniform]
 {
     set
     {
         BufferUniformData(uniform, value);
     }
 }
コード例 #3
0
        private void BufferUniformData(Uniform uniform, ref Matrix4 matrix4)
        {
            if(!Uniforms.ContainsKey((int)uniform)) throw new ArgumentOutOfRangeException();

            var layout = Uniforms[(int)uniform];

            GL.BindBuffer(BufferTarget.UniformBuffer, buffer);
            GL.BufferSubData(BufferTarget.UniformBuffer, layout.Offset, layout.Size, ref matrix4);
            GL.BindBuffer(BufferTarget.UniformBuffer, 0);
            OpenGL.ReportError();
        }
コード例 #4
0
ファイル: UniformTests.cs プロジェクト: klipto/Uncertainty
 public void Uniform_Bernoulli_Sample()
 {
     // arrange
     Uncertain<double> X = new Uniform<double>(1.0, 3.0);
     Uncertain<double> Y = new Uniform<double>(4.0, 5.0);
     var Z = X > Y;
     var sampler = Sampler.Create(Z);
     foreach (var p in sampler.Take(100))
     {
         // act
         bool s = p.Value;
         // assert
         Assert.IsFalse(s);
     }
 }
コード例 #5
0
ファイル: Mesh.cs プロジェクト: prepare/SharpBgfx
        public unsafe void Submit (byte viewId, Program program, Matrix4x4* transform, RenderStateGroup renderStateGroup, IUniformGroup uniforms, Texture texture, Uniform textureSampler) {
            foreach (var group in groups) {
                if (uniforms != null)
                    uniforms.SubmitPerDrawUniforms();

                if (texture != null)
                    Bgfx.SetTexture(0, textureSampler, texture);

                Bgfx.SetTransform((float*)transform);
                Bgfx.SetIndexBuffer(group.IndexBuffer);
                Bgfx.SetVertexBuffer(group.VertexBuffer);
                Bgfx.SetRenderState(renderStateGroup.State, (int)renderStateGroup.BlendFactorRgba);
                Bgfx.SetStencil(renderStateGroup.FrontFace, renderStateGroup.BackFace);
                Bgfx.Submit(viewId, program);
            }
        }
コード例 #6
0
ファイル: Chain.cs プロジェクト: aidint/SimExpert
        public void run()
        {
            Environment env = new Environment();

            //
            List<double> valueList = new List<double>() { 1, 2, 3, 4, 5 };
            List<double> distribution = new List<double>() { 0.5, 0.6, 0.7, 0.8, 1.0 };
            Discrete discrete = new Discrete(valueList, distribution, 0);
            //
            Uniform uniform = new Uniform(1, 3, 0);
            Distribution CreateDist = new Distribution(discrete);
            Distribution ResDist = new Distribution(uniform);

            Create c = new Create(env, 0, 4, CreateDist);

            Dispose dispose = new Dispose(env, 10);

            Queue q = new Queue(env, 5);
            q.Capacity = 10;
            Resource r = new Resource(env, 1, 1, ResDist, q);

            Queue q2 = new Queue(env, 6);
            q2.Capacity = 10;
            Resource r2 = new Resource(env, 2, 1, ResDist, q2);

            Queue q3 = new Queue(env, 7);
            q3.Capacity = 10;
            Resource r3 = new Resource(env, 3, 1, ResDist, q3);

            Queue q4 = new Queue(env, 8);
            q4.Capacity = 10;
            Resource r4 = new Resource(env, 4, 1, ResDist, q4);

            c.Next_AID.Add("First", 1);
            r.Next_AID.Add("First", 2);
            r2.Next_AID.Add("First", 3);
            r3.Next_AID.Add("First", 4);
            r4.Next_AID.Add("First", 2);

            env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Setup_Simulation(TimeSpan.FromSeconds(300));
            env.Simulate();
        }
コード例 #7
0
ファイル: Uniforms.cs プロジェクト: prepare/SharpBgfx
    public Uniforms()
    {
        parametersHandle = new Uniform("u_params", UniformType.Vector4);
        ambientHandle = new Uniform("u_ambient", UniformType.Vector4);
        diffuseHandle = new Uniform("u_diffuse", UniformType.Vector4);
        specularHandle = new Uniform("u_specular_shininess", UniformType.Vector4);
        colorHandle = new Uniform("u_color", UniformType.Vector4);
        lightPosRadiusHandle = new Uniform("u_lightPosRadius", UniformType.Vector4, MaxLights);
        lightRgbInnerRHandle = new Uniform("u_lightRgbInnerR", UniformType.Vector4, MaxLights);

        LightPosRadius = new Vector4[MaxLights];
        LightColor = new Vector4[MaxLights];
        for (int i = 0; i < MaxLights; i++) {
            LightPosRadius[i] = new Vector4(0.0f, 0.0f, 0.0f, 1.0f);
            LightColor[i] = new Vector4(1.0f);
        }

        Color = new Vector4(1.0f);
    }
コード例 #8
0
ファイル: UniformTests.cs プロジェクト: klipto/Uncertainty
 public void Uniform_Bernoulli_Conditional()
 {
     // arrange
     Uncertain<double> X = new Uniform<double>(1.0, 3.0);
     Uncertain<double> Y = new Uniform<double>(4.0, 5.0);
     // act
     if ((X > Y).Pr()) {
         Assert.Fail("X > Y evaluates true, incorrectly");
     }
     if ((Y < X).Pr()) {
         Assert.Fail("Y < X evaluates true, incorrectly");
     }
     if (!(Y > X).Pr()) {
         Assert.Fail("Y > X evaluates false, incorrectly");
     }
     if (!(X < Y).Pr()) {
         Assert.Fail("X < Y evaluates false, incorrectly");
     }
 }
コード例 #9
0
ファイル: AbleBaker.cs プロジェクト: aidint/SimExpert
        public override Statistics run()
        {
            Environment env = new Environment();

            //dist for Create
            Uniform CreateDist = new Uniform(1, 5);

            //dist for Able
            Uniform AbleDist = new Uniform(4, 6);

            //dist for Baker
            Uniform BakerDist = new Uniform(2, 5);

            Distribution DistCreate = new Distribution(CreateDist);
            Distribution DistAble = new Distribution(AbleDist);
            Distribution DistBaker = new Distribution(BakerDist);

            Create create = new Create(env, 0, 100, DistCreate);

            Dispose dispose = new Dispose(env, 10);

            Queue SharedQueue = new Queue(env, 3);

            Resource Able = new Resource(env, 1, 1, DistAble, SharedQueue);

            Resource Baker = new Resource(env, 2, 1, DistBaker, SharedQueue);

            Decide decide = new Decide(env, 5);
            //Condition
            EQCond cond = new EQCond(0, Able, Actor.StateType.Idle);
            decide.AddCondition(cond, Able.AID);
            decide.AddElse(Baker.AID);

            create.Next_AID.Add("First", 5);
            Able.Next_AID.Add("First", 10);
            Baker.Next_AID.Add("First", 10);

            env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0);

            env.Setup_Simulation();
            return env.Simulate();
        }
コード例 #10
0
ファイル: SimpleProbShare.cs プロジェクト: aidint/SimExpert
        public void run()
        {
            Environment env = new Environment();

            //dist
            List<double> valueList = new List<double>() { 1, 2, 3, 4, 5 };
            List<double> distribution = new List<double>() { 0.5, 0.6, 0.7, 0.8, 1.0 };
            Discrete d = new Discrete(valueList, distribution, 0);
            //dist1
            Uniform n = new Uniform(1, 3, 0);
            Distribution dist = new Distribution(d);
            Distribution dist1 = new Distribution(n);

            Create c = new Create(env, 0, 10000, dist,null,new List<double>(){0.3,0.8,1.0});

            Dispose di = new Dispose(env, 1);

            Queue q = new Queue(env, 3);
            q.Capacity = 1;
            Resource r = new Resource(env, 2, 1, dist1, q);

            Queue q2 = new Queue(env,5);
            q2.Capacity = 1;
            Resource r2 = new Resource(env, 6, 1, dist1, q2);

            Queue q3 = new Queue(env, 10);
            q3.Capacity = 1;
            Resource r3 = new Resource(env, 7, 1, dist1, q3);

            c.Next_AID.Add("First", 2);
            c.Next_AID.Add("Second", 6);
            c.Next_AID.Add("Third", 7);

            r.Next_AID.Add("First", 1);
            r2.Next_AID.Add("First", 1);
            r3.Next_AID.Add("First", 1);

            env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Setup_Simulation();
            env.Simulate();
        }
コード例 #11
0
ファイル: SimpleSharedQueue.cs プロジェクト: aidint/SimExpert
        public void run()
        {
            Environment env = new Environment();

            //dist
            Uniform d = new Uniform(1, 1, 0);

            //dist1
            Uniform n = new Uniform(5, 5, 0);
            Distribution dist = new Distribution(d);
            Distribution dist1 = new Distribution(n);

            Create c = new Create(env, 0, 10, dist);

            Dispose di = new Dispose(env, 10);

            Queue q = new Queue(env, 3);
            q.Capacity = 10;
            Resource r = new Resource(env, 1, 1, dist1, q);

            Queue q2 = new Queue(env, 4);
            q2.Capacity = 5;
            Resource r2 = new Resource(env, 2, 1, dist1, q);

            Decide de = new Decide(env, 5);
            //Condition
            EQCond cond = new EQCond(0, r, Actor.StateType.Busy);
            de.AddCondition(cond, r2.AID);
            de.AddElse(r.AID);

            c.Next_AID.Add("First", 5);
            r.Next_AID.Add("First", 10);
            r2.Next_AID.Add("First", 10);

            env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Setup_Simulation();
            env.Simulate();
            ///////
        }
コード例 #12
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return new ModelViewPerspectiveMatrixUniform(uniform);
 }
コード例 #13
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new ModelZToClipCoordinatesUniform(uniform));
 }
コード例 #14
0
    static unsafe void RunCompute(Sample sample, bool indirectSupported)
    {
        // build vertex layouts
        var quadLayout = new VertexLayout();

        quadLayout.Begin()
        .Add(VertexAttributeUsage.Position, 2, VertexAttributeType.Float)
        .End();

        var computeLayout = new VertexLayout();

        computeLayout.Begin()
        .Add(VertexAttributeUsage.TexCoord0, 4, VertexAttributeType.Float)
        .End();

        // static quad data
        var vb = new VertexBuffer(MemoryBlock.FromArray(QuadVertices), quadLayout);
        var ib = new IndexBuffer(MemoryBlock.FromArray(QuadIndices));

        // create compute buffers
        var currPositionBuffer0 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);
        var currPositionBuffer1 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);
        var prevPositionBuffer0 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);
        var prevPositionBuffer1 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite);

        // load shaders
        var particleProgram        = ResourceLoader.LoadProgram("vs_particle", "fs_particle");
        var initInstancesProgram   = ResourceLoader.LoadProgram("cs_init_instances");
        var updateInstancesProgram = ResourceLoader.LoadProgram("cs_update_instances");

        // indirect rendering support
        var  indirectProgram = SharpBgfx.Program.Invalid;
        var  indirectBuffer  = IndirectBuffer.Invalid;
        bool useIndirect     = false;

        if (indirectSupported)
        {
            indirectProgram = ResourceLoader.LoadProgram("cs_indirect");
            indirectBuffer  = new IndirectBuffer(2);
            useIndirect     = true;
        }

        // setup params uniforms
        var paramData = new ParamsData {
            TimeStep          = 0.0157f,
            DispatchSize      = 32,
            Gravity           = 0.109f,
            Damping           = 0.25f,
            ParticleIntensity = 0.64f,
            ParticleSize      = 0.279f,
            BaseSeed          = 57,
            ParticlePower     = 3.5f,
            InitialSpeed      = 3.2f,
            InitialShape      = 1,
            MaxAccel          = 100.0f
        };

        // have the compute shader run initialization
        var u_params = new Uniform("u_params", UniformType.Vector4, 3);

        Bgfx.SetUniform(u_params, &paramData, 3);
        Bgfx.SetComputeBuffer(0, prevPositionBuffer0, ComputeBufferAccess.Write);
        Bgfx.SetComputeBuffer(1, currPositionBuffer0, ComputeBufferAccess.Write);
        Bgfx.Dispatch(0, initInstancesProgram, MaxParticleCount / ThreadGroupUpdateSize);

        // start the frame clock
        var clock = new Clock();

        clock.Start();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // tick the clock
            var elapsed = clock.Frame();
            var time    = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/24-NBody");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: N-body simulation with compute shaders using buffers.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // fill the indirect buffer if we're using it
            if (useIndirect)
            {
                Bgfx.SetUniform(u_params, &paramData, 3);
                Bgfx.SetComputeBuffer(0, indirectBuffer, ComputeBufferAccess.Write);
                Bgfx.Dispatch(0, indirectProgram);
            }

            // update particle positions
            Bgfx.SetComputeBuffer(0, prevPositionBuffer0, ComputeBufferAccess.Read);
            Bgfx.SetComputeBuffer(1, currPositionBuffer0, ComputeBufferAccess.Read);
            Bgfx.SetComputeBuffer(2, prevPositionBuffer1, ComputeBufferAccess.Write);
            Bgfx.SetComputeBuffer(3, currPositionBuffer1, ComputeBufferAccess.Write);
            Bgfx.SetUniform(u_params, &paramData, 3);
            if (useIndirect)
            {
                Bgfx.Dispatch(0, updateInstancesProgram, indirectBuffer, 1);
            }
            else
            {
                Bgfx.Dispatch(0, updateInstancesProgram, paramData.DispatchSize);
            }

            // ping-pong the buffers for next frame
            Swap(ref currPositionBuffer0, ref currPositionBuffer1);
            Swap(ref prevPositionBuffer0, ref prevPositionBuffer1);

            // view transforms for particle rendering
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -45.0f), -Vector3.UnitZ, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 4, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 10000.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // draw the particles
            Bgfx.SetVertexBuffer(vb);
            Bgfx.SetIndexBuffer(ib);
            Bgfx.SetInstanceDataBuffer(currPositionBuffer0, 0, paramData.DispatchSize * ThreadGroupUpdateSize);
            Bgfx.SetRenderState(RenderState.ColorWrite | RenderState.BlendAdd | RenderState.DepthTestAlways);
            if (useIndirect)
            {
                Bgfx.Submit(0, particleProgram, indirectBuffer);
            }
            else
            {
                Bgfx.Submit(0, particleProgram);
            }

            // done with frame
            Bgfx.Frame();
        }

        // cleanup
        if (indirectSupported)
        {
            indirectProgram.Dispose();
            indirectBuffer.Dispose();
        }

        u_params.Dispose();
        currPositionBuffer0.Dispose();
        currPositionBuffer1.Dispose();
        prevPositionBuffer0.Dispose();
        prevPositionBuffer1.Dispose();
        updateInstancesProgram.Dispose();
        initInstancesProgram.Dispose();
        particleProgram.Dispose();
        ib.Dispose();
        vb.Dispose();
    }
コード例 #15
0
 public unsafe void SetUniform(Uniform uniform, ParameterType type, int arraySize, void *valueData)
 {
     SetUniform(uniform, type, arraySize, (IntPtr)valueData);
 }
コード例 #16
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new WindowToWorldNearPlaneUniform(uniform));
 }
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new ViewportOrthographicMatrixUniform(uniform));
 }
コード例 #18
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new PixelSizePerDistanceUniform(uniform));
 }
コード例 #19
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return new OrthographicMatrixUniform(uniform);
 }
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new ViewportTransformationMatrixUniform(uniform));
 }
コード例 #21
0
ファイル: Font.cs プロジェクト: LongJohnCoder/NMSMV
        private void loadHieroFont(StreamReader fnt_sr, Bitmap img_data)
        {
            string texFilePath = "";

            while (!fnt_sr.EndOfStream)
            {
                string   line = fnt_sr.ReadLine();
                string[] sp;



                if (line.StartsWith("info"))
                {
                    sp = line.Split(new string[] { "info=", "face=", "size=", "bold=",
                                                   "italic=", "charset=", "unicode=",
                                                   "stretchH=", "smooth=", "aa=",
                                                   "padding=", "spacing=" }, StringSplitOptions.None);

                    Name = sp[1].Trim(' ').Trim('\"');
                    int.TryParse(sp[2], out Size);
                }
                else if (line.StartsWith("common"))
                {
                    sp = line.Split(new string[] { "common=", "lineHeight=", "base=", "scaleW=",
                                                   "scaleH=", "pages=", "packed=" }, StringSplitOptions.None);

                    int.TryParse(sp[1], out lineHeight);
                    int.TryParse(sp[2], out baseHeight);
                    int.TryParse(sp[3], out texWidth);
                    int.TryParse(sp[4], out texHeight);
                }
                else if (line.StartsWith("page"))
                {
                    sp = line.Split(new string[] { "page id=", "file=" }, StringSplitOptions.None);

                    texFilePath = sp[2].Trim(' ').Trim('\"');
                }
                else if (line.StartsWith("chars"))
                {
                    continue;
                }
                else if (line.StartsWith("char"))
                {
                    sp = line.Split(new string[] { "char id=", "x=", "y=", "width=", "height=",
                                                   "xoffset=", "yoffset=", "xadvance=", "page=", "chnl=" }, StringSplitOptions.None);

                    Symbol s = new Symbol();
                    int    char_id;
                    int.TryParse(sp[1].Trim(' '), out char_id);
                    s.symbol = char.ConvertFromUtf32(char_id);
                    int.TryParse(sp[2].Trim(' '), out s.x_pos);
                    int.TryParse(sp[3].Trim(' '), out s.y_pos);
                    int.TryParse(sp[4].Trim(' '), out s.width);
                    int.TryParse(sp[5].Trim(' '), out s.height);
                    int.TryParse(sp[6].Trim(' '), out s.x_origin);
                    int.TryParse(sp[7].Trim(' '), out s.y_origin);
                    int.TryParse(sp[8].Trim(' '), out s.advance);


                    symbols[s.symbol] = s;
                }
            }

            //Generate texture
            Texture tex = new Texture();

            tex.target = TextureTarget.Texture2DArray;
            tex.texID  = genGLTexture(img_data);

            //Generate Sampler
            Sampler sampl = new Sampler();

            sampl.Name            = "mpCustomPerMaterial.gDiffuseMap";
            sampl.texUnit         = new MyTextureUnit(sampl.Name);
            sampl.texUnit.texUnit = TextureUnit.Texture0;
            sampl.tex             = tex;

            //Generate Font Material
            material = new Material();
            material.PSamplers[sampl.Name] = sampl;
            Uniform uf = new Uniform("size");

            uf.Vec.X = Size;
            material.CustomPerMaterialUniforms["size"] = uf;
        }
コード例 #22
0
 public override void Set(Uniform uniform)
 {
     ((Uniform <int>)uniform).Value = _textureUnit;
 }
コード例 #23
0
        public TriangleMeshTerrainTile(Context context, TerrainTile tile)
        {
            ShaderProgram silhouetteSP = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.SilhouetteVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.SilhouetteGS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.SilhouetteFS.glsl"));

            Uniform <float> fillDistance = (Uniform <float>)silhouetteSP.Uniforms["u_fillDistance"];

            fillDistance.Value            = 1.5f;
            _silhouetteHeightExaggeration = (Uniform <float>)silhouetteSP.Uniforms["u_heightExaggeration"];

            ShaderProgram sp = Device.CreateShaderProgram(
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.TerrainVS.glsl"),
                EmbeddedResources.GetText("OpenGlobe.Scene.Terrain.TriangleMeshTerrainTile.TerrainFS.glsl"));

            _tileMinimumHeight = tile.MinimumHeight;
            _tileMaximumHeight = tile.MaximumHeight;

            _heightExaggeration = (Uniform <float>)sp.Uniforms["u_heightExaggeration"];
            _minimumHeight      = (Uniform <float>)sp.Uniforms["u_minimumHeight"];
            _maximumHeight      = (Uniform <float>)sp.Uniforms["u_maximumHeight"];
            HeightExaggeration  = 1;

            ///////////////////////////////////////////////////////////////////

            Mesh mesh = new Mesh();

            mesh.PrimitiveType         = PrimitiveType.Triangles;
            mesh.FrontFaceWindingOrder = WindingOrder.Counterclockwise;

            int numberOfPositions = tile.Resolution.X * tile.Resolution.Y;
            VertexAttributeDoubleVector3 positionsAttribute = new VertexAttributeDoubleVector3("position", numberOfPositions);
            IList <Vector3D>             positions          = positionsAttribute.Values;

            mesh.Attributes.Add(positionsAttribute);

            int numberOfPartitionsX    = tile.Resolution.X - 1;
            int numberOfPartitionsY    = tile.Resolution.Y - 1;
            int numberOfIndices        = (numberOfPartitionsX * numberOfPartitionsY) * 6;
            IndicesUnsignedInt indices = new IndicesUnsignedInt(numberOfIndices);

            mesh.Indices = indices;

            //
            // Positions
            //
            Vector2D lowerLeft    = tile.Extent.LowerLeft;
            Vector2D toUpperRight = tile.Extent.UpperRight - lowerLeft;

            int heightIndex = 0;

            for (int y = 0; y <= numberOfPartitionsY; ++y)
            {
                double deltaY   = y / (double)numberOfPartitionsY;
                double currentY = lowerLeft.Y + (deltaY * toUpperRight.Y);

                for (int x = 0; x <= numberOfPartitionsX; ++x)
                {
                    double deltaX   = x / (double)numberOfPartitionsX;
                    double currentX = lowerLeft.X + (deltaX * toUpperRight.X);
                    positions.Add(new Vector3D(currentX, currentY, tile.Heights[heightIndex++]));
                }
            }

            //
            // Indices
            //
            int rowDelta = numberOfPartitionsX + 1;
            int i        = 0;

            for (int y = 0; y < numberOfPartitionsY; ++y)
            {
                for (int x = 0; x < numberOfPartitionsX; ++x)
                {
                    indices.AddTriangle(new TriangleIndicesUnsignedInt(i, i + 1, rowDelta + (i + 1)));
                    indices.AddTriangle(new TriangleIndicesUnsignedInt(i, rowDelta + (i + 1), rowDelta + i));
                    i += 1;
                }
                i += 1;
            }

            _drawState = new DrawState();
            _drawState.RenderState.FacetCulling.FrontFaceWindingOrder = mesh.FrontFaceWindingOrder;
            _drawState.ShaderProgram = sp;
            _drawState.VertexArray   = context.CreateVertexArray(mesh, sp.VertexAttributes, BufferHint.StaticDraw);

            _silhouetteDrawState = new DrawState();
            _silhouetteDrawState.RenderState.FacetCulling.Enabled = false;
            _silhouetteDrawState.RenderState.DepthMask            = false;
            _silhouetteDrawState.VertexArray   = _drawState.VertexArray;
            _silhouetteDrawState.ShaderProgram = silhouetteSP;

            _primitiveType = mesh.PrimitiveType;

            _clearColor         = new ClearState();
            _clearColor.Buffers = ClearBuffers.ColorBuffer;

            //
            // Only depth needs to be cleared but include stencil for speed.
            //
            _clearDepthStencil         = new ClearState();
            _clearDepthStencil.Buffers = ClearBuffers.DepthBuffer | ClearBuffers.StencilBuffer;
        }
コード例 #24
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new CameraEyeUniform(uniform));
 }
コード例 #25
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.Vsync);

        // enable debug text
        Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

        // load shaders
        var programTextureLighting = ResourceLoader.LoadProgram("vs_stencil_texture_lighting", "fs_stencil_texture_lighting");
        var programColorLighting   = ResourceLoader.LoadProgram("vs_stencil_color_lighting", "fs_stencil_color_lighting");
        var programColorTexture    = ResourceLoader.LoadProgram("vs_stencil_color_texture", "fs_stencil_color_texture");
        var programColorBlack      = ResourceLoader.LoadProgram("vs_stencil_color", "fs_stencil_color_black");
        var programTexture         = ResourceLoader.LoadProgram("vs_stencil_texture", "fs_stencil_texture");

        // load meshes
        var bunnyMesh  = ResourceLoader.LoadMesh("bunny.bin");
        var columnMesh = ResourceLoader.LoadMesh("column.bin");
        var hplaneMesh = new Mesh(MemoryBlock.FromArray(StaticMeshes.HorizontalPlane), PosNormalTexcoordVertex.Layout, StaticMeshes.PlaneIndices);
        var vplaneMesh = new Mesh(MemoryBlock.FromArray(StaticMeshes.VerticalPlane), PosNormalTexcoordVertex.Layout, StaticMeshes.PlaneIndices);

        // load textures
        var figureTex     = ResourceLoader.LoadTexture("figure-rgba.dds");
        var flareTex      = ResourceLoader.LoadTexture("flare.dds");
        var fieldstoneTex = ResourceLoader.LoadTexture("fieldstone-rgba.dds");

        // create uniforms
        var colorTextureHandle = new Uniform("u_texColor", UniformType.Int1);
        var uniforms           = new Uniforms();

        uniforms.SubmitConstUniforms();

        // light colors
        uniforms.LightColor = new[] {
            new Vector4(1.0f, 0.7f, 0.2f, 0.0f), // yellow
            new Vector4(0.7f, 0.2f, 1.0f, 0.0f), // purple
            new Vector4(0.2f, 1.0f, 0.7f, 0.0f), // cyan
            new Vector4(1.0f, 0.4f, 0.2f, 0.0f)  // orange
        };

        // camera
        var camera = new Camera(60.0f, sample.WindowWidth, sample.WindowHeight, 0.1f, 100.0f);

        camera.Position = new Vector3(0.0f, 18.0f, -40.0f);

        // start the frame clock
        var clock = new Clock();

        clock.Start();

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // tick the clock
            var elapsed = clock.Frame();
            var time    = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/13-Stencil");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Stencil reflections.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // clear the background
            Bgfx.SetViewClear(BaseId, ClearTargets.Color | ClearTargets.Depth | ClearTargets.Stencil, 0x30303000);
            Bgfx.SetViewRect(BaseId, 0, 0, sample.WindowWidth, sample.WindowHeight);
            Bgfx.Touch(BaseId);

            // set view params for each pass
            var viewMtx = camera.GetViewMatrix();
            var projMtx = camera.GetProjectionMatrix();
            for (byte i = PassId0; i <= PassId4; i++)
            {
                Bgfx.SetViewRect(i, 0, 0, sample.WindowWidth, sample.WindowHeight);
                Bgfx.SetViewTransform(i, (float *)&viewMtx, (float *)&projMtx);
            }

            // first pass - draw ground plane
            var floorMtx = FloorTransform;
            hplaneMesh.Submit(PassId0, programColorBlack, &floorMtx, StateGroups[PrebuiltRenderState.StencilReflectionCraftStencil], uniforms);

            // second pass - reflected objects
            Bgfx.SetViewClear(PassId1, ClearTargets.Depth, 0);
            uniforms.AmbientPass  = true;
            uniforms.LightingPass = true;
            uniforms.Color        = new Vector4(0.70f, 0.65f, 0.60f, 0.8f);
            uniforms.LightCount   = LightCount;

            // light positions
            var lightPositions  = new Vector4[LightCount];
            var reflectedLights = new Vector4[LightCount];
            for (int i = 0; i < lightPositions.Length; i++)
            {
                var v3 = new Vector3(
                    (float)Math.Sin(time * 1.1 + i * 0.03 + i * 1.07 * Math.PI / 2) * 20.0f,
                    8.0f + (1.0f - (float)Math.Cos(time * 1.5 + i * 0.29 + 1.49f * Math.PI / 2)) * 4.0f,
                    (float)Math.Cos(time * 1.3 + i * 0.13 + i * 1.79 * Math.PI / 2) * 20.0f
                    );

                lightPositions[i]  = new Vector4(v3, 15.0f);
                reflectedLights[i] = new Vector4(Vector3.Transform(v3, ReflectionTransform), 15.0f);
            }

            uniforms.LightPosRadius = reflectedLights;
            var bunnyMtx =
                Matrix4x4.CreateScale(5) *
                Matrix4x4.CreateRotationY(time - 1.56f) *
                Matrix4x4.CreateTranslation(0.0f, 2.0f, 0.0f);
            var reflectedBunnyMtx = bunnyMtx * ReflectionTransform;
            bunnyMesh.Submit(PassId1, programColorLighting, &reflectedBunnyMtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawReflected], uniforms);

            for (int i = 0; i < 4; i++)
            {
                var mtx = ColumnTransforms[i] * ReflectionTransform;
                columnMesh.Submit(PassId1, programColorLighting, &mtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawReflected], uniforms);
            }

            // third pass - blend the plane and reflections
            uniforms.LightPosRadius = lightPositions;
            hplaneMesh.Submit(PassId2, programTextureLighting, &floorMtx, StateGroups[PrebuiltRenderState.StencilReflectionBlendPlane], uniforms, fieldstoneTex, colorTextureHandle);

            // fourth pass - draw the solid objects
            bunnyMesh.Submit(PassId3, programColorLighting, &bunnyMtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawScene], uniforms);
            for (int i = 0; i < 4; i++)
            {
                var mtx = ColumnTransforms[i];
                columnMesh.Submit(PassId3, programColorLighting, &mtx, StateGroups[PrebuiltRenderState.StencilReflectionDrawScene], uniforms);
            }

            // fifth pass - draw the lights as objects
            for (int i = 0; i < LightCount; i++)
            {
                var c = uniforms.LightColor[i];
                uniforms.Color = new Vector4(c.X, c.Y, c.Z, 0.8f);

                var p   = lightPositions[i];
                var mtx = Matrix4x4.CreateScale(1.5f) * Matrix4x4.CreateBillboard(new Vector3(p.X, p.Y, p.Z), camera.Position, Vector3.UnitY, -Vector3.UnitZ);
                vplaneMesh.Submit(PassId4, programColorTexture, &mtx, StateGroups[PrebuiltRenderState.CustomBlendLightTexture], uniforms, flareTex, colorTextureHandle);
            }

            // advance to the next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            Bgfx.Frame();
        }

        // clean up
        bunnyMesh.Dispose();
        columnMesh.Dispose();
        hplaneMesh.Dispose();
        vplaneMesh.Dispose();

        figureTex.Dispose();
        fieldstoneTex.Dispose();
        flareTex.Dispose();

        programTextureLighting.Dispose();
        programColorLighting.Dispose();
        programColorTexture.Dispose();
        programColorBlack.Dispose();
        programTexture.Dispose();

        colorTextureHandle.Dispose();
        uniforms.Dispose();

        Bgfx.Shutdown();
    }
コード例 #26
0
ファイル: ShaderLoader.cs プロジェクト: Richy19/ultraSandbox
 public void insertUniform(Uniform uni, ref Vector3 value)
 {
     int location = locations[(int)uni];
     if (location != -1)
         GL.Uniform3(location, ref value);
 }
コード例 #27
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return new ViewMatrixUniform(uniform);
 }
コード例 #28
0
ファイル: ShaderLoader.cs プロジェクト: Richy19/ultraSandbox
 internal void insertUniform(Uniform uni, ref Vector2 value)
 {
     int location = locations[(int)uni];
     if (location != -1)
         GL.Uniform2(location, ref value);
 }
コード例 #29
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new ModelMatrixUniform(uniform));
 }
コード例 #30
0
        private void Compile(string source)
        {
            int vertex   = source.IndexOf("#vertex", StringComparison.Ordinal);
            int geometry = source.IndexOf("#geometry", StringComparison.Ordinal);
            int fragment = source.IndexOf("#fragment", StringComparison.Ordinal);

            if (vertex == -1)
            {
                throw new CKGLException("Shader source must contain a vertex shader definition.");
            }

            bool hasGeometryDefinition = geometry != -1;
            bool hasFragmentDefinition = fragment != -1;

            if (geometry != -1)
            {
                throw new CKGLException("WebGL 2.0 does not support Geometry Shaders.");
            }

            string vertSource = hasGeometryDefinition
                                                                ? source.Substring(vertex, geometry - vertex)
                                                                : hasFragmentDefinition
                                                                        ? source.Substring(vertex, fragment - vertex)
                                                                        : source.Substring(vertex);

            //string geomSource = hasGeometryDefinition
            //					? hasFragmentDefinition
            //						? source.Substring(geometry, fragment - geometry)
            //						: source.Substring(geometry)
            //					: "";
            string fragSource = hasFragmentDefinition
                                                                ? source.Substring(fragment)
                                                                : "";

            // Debug
            //Output.WriteLine($"\nVertex Shader:\n{vertSource}");
            //Output.WriteLine($"\nGeometry Shader:\n{geomSource}");
            //Output.WriteLine($"\nFragment Shader:\n{fragSource}");

            // Create the shaders and compile them
            Retyped.dom.WebGLShader vertID = GL.createShader(GL.VERTEX_SHADER);
            //Output.WriteLine(vertSource.Replace("#vertex", ShaderIncludes.Vertex));
            CompileShader(vertID, ConvertVertex(vertSource.Replace("#vertex", ShaderIncludes.Vertex)));

            //Retyped.dom.WebGLShader geomID = null;
            //if (hasGeometryDefinition)
            //{
            //	geomID = GL.createShader(GL.GEOMETRY_SHADER);
            //	//Output.WriteLine(geomSource.Replace("#geometry", ShaderIncludes.Geometry));
            //	CompileShader(geomID, ConvertGeometry(geomSource.Replace("#geometry", ShaderIncludes.Geometry)));
            //}

            Retyped.dom.WebGLShader fragID = null;
            if (hasFragmentDefinition)
            {
                fragID = GL.createShader(GL.FRAGMENT_SHADER);
                //Output.WriteLine(fragSource.Replace("#fragment", ShaderIncludes.Fragment));
                CompileShader(fragID, ConvertFragment(fragSource.Replace("#fragment", ShaderIncludes.Fragment)));
            }

            // Create the program and attach the shaders to it
            shader = GL.createProgram();
            GL.attachShader(shader, vertID);
            //if (hasGeometryDefinition)
            //	GL.attachShader(shader, geomID);
            if (hasFragmentDefinition)
            {
                GL.attachShader(shader, fragID);
            }

            // WebGL 1.0 only - Automatically bind attributes based on layout qualifiers
            try
            {
                string[] lines = vertSource.Split('\n');

                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].Contains("layout(location") && (lines[i].Contains("in ") || lines[i].Contains("attribute ")))
                    {
                        string[] line     = lines[i].Replace("layout(location =", "").Replace("layout(location=", "").Replace(";", " ").Trim().Split(' ');
                        int      attribID = int.Parse(line[0].Substring(0, line[0].Length - 1).Trim());
                        string   name     = line[3].Trim();
                        //Output.WriteLine($"Shader - Bind Attribute | id: {attribID}, {name} ({line[2]})"); // Debug
                        GL.bindAttribLocation(shader, attribID, name);
                    }
                }
            }
            catch (Exception e)
            {
                Output.WriteLine($"WebGL 1.0 - Automatic Shader Attribute binding failed: {e.Message}");
            }

            // Link the program and check for errors
            GL.linkProgram(shader);
            bool linkStatus = (bool)GL.getProgramParameter(shader, GL.LINK_STATUS);

            if (!linkStatus)
            {
                throw new CKGLException("Program link error: " + GL.getProgramInfoLog(shader));
            }

            // Validate the program and check for errors
            GL.validateProgram(shader);
            bool validateStatus = (bool)GL.getProgramParameter(shader, GL.VALIDATE_STATUS);

            if (!validateStatus)
            {
                throw new CKGLException("Program validate error: " + GL.getProgramInfoLog(shader));
            }

            // Once linked, we can detach and delete the shaders
            GL.detachShader(shader, vertID);
            GL.deleteShader(vertID);
            //if (hasGeometryDefinition)
            //{
            //	GL.detachShader(shader, geomID);
            //	GL.deleteShader(geomID);
            //}
            if (hasFragmentDefinition)
            {
                GL.detachShader(shader, fragID);
                GL.deleteShader(fragID);
            }

            // Get all the uniforms the shader has and store their information
            int numUniforms = (int)GL.getProgramParameter(shader, GL.ACTIVE_UNIFORMS);

            for (int i = 0; i < numUniforms; ++i)
            {
                var    uniformInfo = GL.getActiveUniform(shader, i);
                string name        = uniformInfo.name;
                uint   type        = uniformInfo.type;
                int    count       = uniformInfo.size;
                if (count > 0 && name != null)
                {
                    if (count > 1)
                    {
                        name = name.Substring(0, name.LastIndexOf('['));
                        string arrName;
                        for (int n = 0; n < count; ++n)
                        {
                            arrName = $"{name}[{n}]";
                            WebGLUniformLocation loc = GL.getUniformLocation(shader, arrName);
                            //Output.WriteLine($"index:{i} name:{arrName} type:{type} loc:{loc} count:{count}");
                            var uniform = new Uniform(i, arrName, type, loc);
                            uniforms.Add(arrName, uniform);
                        }
                    }
                    else
                    {
                        WebGLUniformLocation loc = GL.getUniformLocation(shader, name);
                        //Output.WriteLine($"index:{i} name:{name} type:{type} loc:{loc} count:{count}");
                        var uniform = new Uniform(i, name, type, loc);
                        uniforms.Add(name, uniform);
                    }
                }
            }
        }
コード例 #31
0
ファイル: ShaderLoader.cs プロジェクト: Richy19/ultraSandbox
 internal void insertGenUniform(Uniform uniform, object uniObj)
 {
     if (uniObj.GetType() == typeof(float))
     {
         float tmpValue = (float)uniObj;
         insertUniform(uniform, ref tmpValue);
         return;
     }
     if (uniObj.GetType() == typeof(Vector2))
     {
         Vector2 tmpValue = (Vector2)uniObj;
         insertUniform(uniform, ref tmpValue);
         return;
     }
     if (uniObj.GetType() == typeof(Vector3))
     {
         Vector3 tmpValue = (Vector3)uniObj;
         insertUniform(uniform, ref tmpValue);
         return;
     }
     if (uniObj.GetType() == typeof(Matrix4))
     {
         Matrix4 tmpValue = (Matrix4)uniObj;
         insertUniform(uniform, ref tmpValue);
         return;
     }
     throw new Exception("unable to assigin Uniform");
 }
コード例 #32
0
        private static void Main(string[] args)
        {
            //var minScore = float.Parse(args[0], NumberStyles.Float, null);
            var minScore = 0.9f;

            const int   imageSize    = 28;
            var         layers       = new[] { 128, 64, 10 };
            const int   batchSize    = 100;
            const int   maxEpoch     = 10;
            const float learningRate = 0.1f;
            const float weightDecay  = 1e-2f;

            var trainIter = new MXDataIter("MNISTIter")
                            .SetParam("image", "./mnist_data/train-images-idx3-ubyte")
                            .SetParam("label", "./mnist_data/train-labels-idx1-ubyte")
                            .SetParam("batch_size", batchSize)
                            .SetParam("flat", 1)
                            .CreateDataIter();
            var valIter = new MXDataIter("MNISTIter")
                          .SetParam("image", "./mnist_data/t10k-images-idx3-ubyte")
                          .SetParam("label", "./mnist_data/t10k-labels-idx1-ubyte")
                          .SetParam("batch_size", batchSize)
                          .SetParam("flat", 1)
                          .CreateDataIter();

            var net = Mlp(layers);

            var ctx = Context.Cpu();  // Use GPU for training

            var dictionary = new Dictionary <string, NDArray>();

            dictionary["X"]     = new NDArray(new Shape(batchSize, imageSize * imageSize), ctx);
            dictionary["label"] = new NDArray(new Shape(batchSize), ctx);
            // Let MXNet infer shapes of other parameters such as weights
            net.InferArgsMap(ctx, dictionary, dictionary);

            // Initialize all parameters with uniform distribution U(-0.01, 0.01)
            var initializer = new Uniform(0.01f);

            foreach (var arg in dictionary)
            {
                // arg.first is parameter name, and arg.second is the value
                initializer.Operator(arg.Key, arg.Value);
            }

            // Create sgd optimizer
            var opt = OptimizerRegistry.Find("sgd");

            opt.SetParam("rescale_grad", 1.0 / batchSize)
            .SetParam("lr", learningRate)
            .SetParam("wd", weightDecay);
            var lrSch = new UniquePtr <LRScheduler>(new FactorScheduler(5000, 0.1f));

            opt.SetLearningRateScheduler(lrSch);

            // Create executor by binding parameters to the model
            using (var exec = net.SimpleBind(ctx, dictionary))
            {
                var argNames = net.ListArguments();

                float score = 0;
                // Start training

                var sw = new Stopwatch();
                for (var iter = 0; iter < maxEpoch; ++iter)
                {
                    var samples = 0;
                    trainIter.Reset();

                    sw.Restart();
                    while (trainIter.Next())
                    {
                        samples += batchSize;
                        var dataBatch = trainIter.GetDataBatch();
                        // Data provided by DataIter are stored in memory, should be copied to GPU first.
                        dataBatch.Data.CopyTo(dictionary["X"]);
                        dataBatch.Label.CopyTo(dictionary["label"]);
                        // CopyTo is imperative, need to wait for it to complete.
                        NDArray.WaitAll();

                        // Compute gradients
                        exec.Forward(true);
                        exec.Backward();
                        // Update parameters
                        for (var i = 0; i < argNames.Count; ++i)
                        {
                            if (argNames[i] == "X" || argNames[i] == "label")
                            {
                                continue;
                            }

                            var weight = exec.ArgmentArrays[i];
                            var grad   = exec.GradientArrays[i];
                            opt.Update(i, weight, grad);
                        }
                    }

                    sw.Stop();

                    var acc = new Accuracy();
                    valIter.Reset();
                    while (valIter.Next())
                    {
                        var dataBatch = valIter.GetDataBatch();
                        dataBatch.Data.CopyTo(dictionary["X"]);
                        dataBatch.Label.CopyTo(dictionary["label"]);
                        NDArray.WaitAll();
                        // Only forward pass is enough as no gradient is needed when evaluating
                        exec.Forward(false);
                        acc.Update(dataBatch.Label, exec.Outputs[0]);
                    }

                    var duration = sw.ElapsedMilliseconds / 1000.0;
                    var message  = $"Epoch: {iter} {samples / duration} samples/sec Accuracy: {acc.Get()}";
                    Logging.LG(message);
                    score = acc.Get();
                }

                MXNet.MXNotifyShutdown();
                var ret = score >= minScore ? 0 : 1;
                Console.WriteLine($"{ret}");
            }
        }
コード例 #33
0
ファイル: NativeMethods.cs プロジェクト: prepare/SharpBgfx
 public static extern ushort bgfx_get_shader_uniforms(ushort handle, Uniform[] uniforms, ushort max);
コード例 #34
0
 public CascadedShadowUniforms(GLProgram program, Sampler2DArray sampler) : base(program)
 {
     using (program.Scope())
         csmShadowMap &= sampler;
 }
コード例 #35
0
ファイル: Program3D.cs プロジェクト: NinZine/playscript-mono
		private void buildUniformList()
		{
			// clear internal lists
			mUniforms.Clear();
			mVertexUniformLookup  = new Uniform[MaxUniforms];
			mFragmentUniformLookup = new Uniform[MaxUniforms];
			mSamplerUniforms.Clear();
			mSamplerUsageMask = 0;

			int numActive = 0;
			GL.GetProgram(mProgramId, ProgramParameter.ActiveUniforms, out numActive);
			for (int i=0; i < numActive; i++)
			{
				// create new uniform
				var uniform = new Uniform();

				int length;
				var name = new StringBuilder(1024);

				GL.GetActiveUniform(mProgramId, i, name.MaxCapacity, out length, out uniform.Size, out uniform.Type, name);
				uniform.Name 	 = name.ToString();

#if PLATFORM_MONOTOUCH || PLATFORM_MONOMAC
				uniform.Location = GL.GetUniformLocation (mProgramId, uniform.Name );
#elif PLATFORM_MONODROID
				uniform.Location = GL.GetUniformLocation (mProgramId, name);
#endif
				// remove array [x] from names
				int indexBracket = uniform.Name.IndexOf('[');
				if (indexBracket >= 0) {
					uniform.Name = uniform.Name.Substring(0, indexBracket);
				}

				// determine register count for uniform
				switch (uniform.Type)
				{
				case ActiveUniformType.FloatMat2: uniform.RegCount = 2; break;
				case ActiveUniformType.FloatMat3: uniform.RegCount = 3; break;
				case ActiveUniformType.FloatMat4: uniform.RegCount = 4; break;
				default:
					uniform.RegCount = 1; // 1 by default
					break;
				}

				// multiple regcount by size
				uniform.RegCount *= uniform.Size;

				// add uniform to program list
				mUniforms.Add(uniform);

				if (uniform.Name == "vcPositionScale")
				{
					mPositionScale = uniform;
				} else if (uniform.Name.StartsWith("vc"))
				{
					// vertex uniform
					uniform.RegIndex = int.Parse (uniform.Name.Substring(2));
					// store in vertex lookup table
					mVertexUniformLookup[uniform.RegIndex] = uniform;
				}
				else if (uniform.Name.StartsWith("fc"))
				{
					// fragment uniform
					uniform.RegIndex = int.Parse (uniform.Name.Substring(2));
					// store in fragment lookup table
					mFragmentUniformLookup[uniform.RegIndex] = uniform;
				}
				else if (uniform.Name.StartsWith("sampler"))
				{
					// sampler uniform
					uniform.RegIndex = int.Parse (uniform.Name.Substring(7));
					// add to list of sampler uniforms
					mSamplerUniforms.Add (uniform);

					// set sampler usage mask for this sampler uniform
					for (int reg=0; reg < uniform.RegCount; reg++) {
						mSamplerUsageMask |= (1 << (uniform.RegIndex + reg));
					}
				}

				if (Verbose) {
					Console.WriteLine ("{0} name:{1} type:{2} size:{3} location:{4}", i, uniform.Name, uniform.Type, uniform.Size, uniform.Location);
				}
			}
		}
コード例 #36
0
ファイル: FormParametrs.cs プロジェクト: aquaphoenix1/DP
        private void ButtonOK_Click(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = textBox1.Text.Replace('.', ',');
                textBox2.Text = textBox2.Text.Replace('.', ',');
                int countIntervals = int.Parse(textBoxCountIntervals.Text);

                double[] array = new double[formMain.network.CountNeurons];
                switch (comboBoxDistribution.SelectedItem.ToString())
                {
                case "Арксинус":
                {
                    array = new Arcsinus(Double.Parse(textBox1.Text), Int32.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Arcsinus", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Экспоненциальное":
                {
                    array = new ExponentialOneway(Double.Parse(textBox1.Text), Int32.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Exponential", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Лаплас":
                {
                    array = new Laplas(Double.Parse(textBox1.Text), Double.Parse(textBox2.Text), Int32.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Laplas", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Нормальное":
                {
                    array = new Normal(Double.Parse(textBox1.Text), Double.Parse(textBox2.Text), Int32.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Normal", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Релей":
                {
                    array = new Relei(Double.Parse(textBox1.Text), Int32.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Relei", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Симпсон":
                {
                    array = new Simpson(Double.Parse(textBox1.Text), Double.Parse(textBox2.Text), Int32.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Simpson", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Коши":
                {
                    array = new Koshi(Double.Parse(textBox1.Text), Double.Parse(textBox2.Text), int.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Koshi", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Равномерный":
                {
                    array = new Uniform(Double.Parse(textBox1.Text), Double.Parse(textBox2.Text), int.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Uniform", true, countIntervals);
                    CloseForm();
                    break;
                }

                case "Вейбулл":
                {
                    array = new Veibull(Double.Parse(textBox1.Text), Double.Parse(textBox2.Text), int.Parse(textBoxCount.Text)).Generate();

                    formMain.Generate(array, "Veibul", true, countIntervals);
                    CloseForm();
                    break;
                }
                }
            }
            catch
            {
                MessageBox.Show("Проверьте правильность введенных данных");
            }
        }
コード例 #37
0
 private void ImplInitialize(string name)
 {
     this.Uniform = new Uniform(name, UniformType.Vector4);
 }
コード例 #38
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new HighResolutionSnapScaleUniform(uniform));
 }
コード例 #39
0
 public unsafe void SetUniform(Uniform uniform, ParameterType type, int arraySize, ArraySegment <byte> valueData)
 {
     fixed(byte *pData = valueData.Array)
     SetUniform(uniform, type, arraySize, (IntPtr)(pData + valueData.Offset));
 }
コード例 #40
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return new ModelZToClipCoordinatesUniform(uniform);
 }
コード例 #41
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return new CameraEyeLowUniform(uniform);
 }
コード例 #42
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new InverseViewportDimensionsUniform(uniform));
 }
コード例 #43
0
        public void QuantileBin1DTest()
        {
            var path = NUnit.Framework.TestContext.CurrentContext.TestDirectory + "\\TestResult\\QuantileBin1DTest\\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var filename = path + "QuantileBin1DTest.log";

            try
            {
                using (StreamWriter writer = new StreamWriter(filename))
                {
                    var argv = new String[] { "100", "L" };

                    /*
                     * Get the number of examples from the first argument
                     */
                    int numExamples = 0;
                    try
                    {
                        numExamples = int.Parse(argv[0]);
                    }
                    catch (Exception e)
                    {
                        Assert.Inconclusive("Unable to parse input line count argument");
                        Assert.Inconclusive(e.Message);
                    }
                    writer.WriteLine("Got numExamples=" + numExamples);

                    /*
                     * Get N from the second argument
                     */
                    long N = 0;
                    try
                    {
                        if (argv[1].Equals("L"))
                        {
                            N = long.MaxValue;
                        }
                        else if (argv[1].Equals("I"))
                        {
                            N = (long)int.MaxValue;
                        }
                        else
                        {
                            N = long.Parse(argv[1]);
                        }
                    }
                    catch (Exception e)
                    {
                        Assert.Inconclusive("Error parsing flag for N");
                        Assert.Inconclusive(e.Message);
                    }
                    writer.WriteLine("Got N=" + N);

                    /*
                     * Set up the QuantileBin1D object
                     */
                    DRand         rand   = new DRand(new DateTime());
                    QuantileBin1D qAccum = new QuantileBin1D(false,
                                                             N,
                                                             1e-4,
                                                             1e-3,
                                                             200,
                                                             rand,
                                                             false,
                                                             false,
                                                             2);

                    DynamicBin1D dbin = new DynamicBin1D();

                    /*
                     * Use a new random number generator to generate numExamples
                     * random gaussians, and add them to the QuantileBin1D
                     */
                    Uniform dataRand = new Uniform(new DRand(7757));
                    for (int i = 1; i <= numExamples; i++)
                    {
                        double gauss = dataRand.NextDouble();
                        qAccum.Add(gauss);
                        dbin.Add(gauss);
                    }

                    /*
                     * print out the percentiles
                     */
                    //DecimalFormat fmt = new DecimalFormat("0.00");
                    writer.WriteLine();
                    //int step = 1;
                    int step = 10;
                    for (int i = 1; i < 100;)
                    {
                        double percent  = ((double)i) * 0.01;
                        double quantile = qAccum.Quantile(percent);

                        writer.WriteLine(percent.ToString("0.00") + "  " + quantile + ",  " + dbin.Quantile(percent) + ",  " + (dbin.Quantile(percent) - quantile));
                        i = i + step;
                    }
                }
            }
            catch (IOException x)
            {
                using (StreamWriter writer = new StreamWriter(filename))
                {
                    writer.Write(x.StackTrace);
                }
            }
        }
コード例 #44
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return(new Wgs84HeightUniform(uniform));
 }
コード例 #45
0
ファイル: Engine.cs プロジェクト: LongJohnCoder/NMSMV
        private void rt_SpecularTestScene()
        {
            //Once the new scene has been loaded,
            //Initialize Palettes
            Palettes.set_palleteColors();

            //Clear Systems
            actionSys.CleanUp();
            animationSys.CleanUp();

            //Clear Resources
            resMgr.Cleanup();
            resMgr.Init();
            RenderState.activeResMgr = resMgr;
            ModelProcGen.procDecisions.Clear();

            RenderState.rootObject  = null;
            RenderState.activeModel = null;
            //Clear Gizmos
            RenderState.activeGizmo = null;

            //Clear RenderStats
            RenderStats.ClearStats();


            //Stop animation if on
            bool animToggleStatus = RenderState.renderSettings.ToggleAnimations;

            RenderState.renderSettings.ToggleAnimations = false;

            //Setup new object
            Scene scene = new Scene();

            scene.name = "DEFAULT SCENE";


            //ADd Lights
            Light l = new Light();

            l.Name          = "Light 1";
            l.localPosition = new Vector3(0.2f, 0.2f, -2.0f);
            l.Color         = new MVector4(1.0f, 1.0f, 1.0f, 1.0f);
            l.Intensity     = 100.0f;
            l.falloff       = ATTENUATION_TYPE.QUADRATIC;
            Common.RenderState.activeResMgr.GLlights.Add(l);
            scene.children.Add(l);

            Light l1 = new Light();

            l1.Name          = "Light 2";
            l1.localPosition = new Vector3(0.2f, -0.2f, -2.0f);
            l1.Color         = new MVector4(1.0f, 1.0f, 1.0f, 1.0f);
            l1.Intensity     = 100.0f;
            l1.falloff       = ATTENUATION_TYPE.QUADRATIC;
            Common.RenderState.activeResMgr.GLlights.Add(l1);
            scene.children.Add(l1);

            Light l2 = new Light();

            l2.Name          = "Light 3";
            l2.localPosition = new Vector3(-0.2f, 0.2f, -2.0f);
            l2.Color         = new MVector4(1.0f, 1.0f, 1.0f, 1.0f);
            Common.RenderState.activeResMgr.GLlights.Add(l2);
            l2.Intensity = 100.0f;
            l2.falloff   = ATTENUATION_TYPE.QUADRATIC;
            scene.children.Add(l2);

            Light l3 = new Light();

            l3.Name          = "Light 4";
            l3.localPosition = new Vector3(-0.2f, -0.2f, -2.0f);
            l3.Color         = new MVector4(1.0f, 1.0f, 1.0f, 1.0f);
            Common.RenderState.activeResMgr.GLlights.Add(l3);
            l3.Intensity = 100.0f;
            l3.falloff   = ATTENUATION_TYPE.QUADRATIC;
            scene.children.Add(l3);

            //Generate a Sphere and center it in the scene
            Model sphere = new Mesh();

            sphere.Name   = "Test Sphere";
            sphere.parent = scene;
            sphere.setParentScene(scene);
            MeshMetaData sphere_metadata = new MeshMetaData();


            int bands = 80;

            sphere_metadata.batchcount          = bands * bands * 6;
            sphere_metadata.batchstart_graphics = 0;
            sphere_metadata.vertrstart_graphics = 0;
            sphere_metadata.vertrend_graphics   = (bands + 1) * (bands + 1) - 1;
            sphere_metadata.indicesLength       = DrawElementsType.UnsignedInt;

            sphere.meshVao      = new GLMeshVao(sphere_metadata);
            sphere.meshVao.type = TYPES.MESH;
            sphere.meshVao.vao  = (new GMDL.Primitives.Sphere(new Vector3(), 2.0f, 40)).getVAO();


            //Sphere Material
            Material mat = new Material();

            mat.Name = "default_scn";

            Uniform uf = new Uniform();

            uf.Name     = "gMaterialColourVec4";
            uf.Values   = new libMBIN.NMS.Vector4f();
            uf.Values.x = 1.0f;
            uf.Values.y = 0.0f;
            uf.Values.z = 0.0f;
            uf.Values.t = 1.0f;
            mat.Uniforms.Add(uf);

            uf          = new Uniform();
            uf.Name     = "gMaterialParamsVec4";
            uf.Values   = new libMBIN.NMS.Vector4f();
            uf.Values.x = 0.15f; //Roughness
            uf.Values.y = 0.0f;
            uf.Values.z = 0.2f;  //Metallic
            uf.Values.t = 0.0f;
            mat.Uniforms.Add(uf);

            mat.init();
            resMgr.GLmaterials["test_mat1"] = mat;
            sphere.meshVao.material         = mat;
            sphere.instanceId = GLMeshBufferManager.addInstance(ref sphere.meshVao, sphere); //Add instance

            scene.children.Add(sphere);

            //Explicitly add default light to the rootObject
            scene.children.Add(resMgr.GLlights[0]);

            scene.updateLODDistances();
            scene.update(); //Refresh all transforms
            scene.setupSkinMatrixArrays();

            //Save scene path to resourcemanager
            RenderState.activeResMgr.GLScenes["TEST_SCENE_1"] = scene; //Use input path

            //Populate RenderManager
            renderMgr.populate(scene);

            //Clear Instances
            renderMgr.clearInstances();
            scene.updateMeshInfo(); //Update all mesh info

            scene.selected         = 1;
            RenderState.rootObject = scene;
            //RenderState.activeModel = root; //Set the new scene as the new activeModel


            //Reinitialize gizmos
            RenderState.activeGizmo = new TranslationGizmo();

            //Restart anim worker if it was active
            RenderState.renderSettings.ToggleAnimations = animToggleStatus;
        }
コード例 #46
0
ファイル: Laws.cs プロジェクト: Hindi/C3P0GitHub
 /// <summary>
 /// Set values returned by the discreteUniforme function <br/>
 /// Only one set can be used at a time, because this project assumes it is used as a unique game mechanic
 /// </summary>
 /// <param name="valuesList">The list containing all values</param>
 public static void setUniformValues(double[] valuesList)
 {
     uniform = new Uniform(valuesList);
 }
コード例 #47
0
ファイル: Program.cs プロジェクト: miquik/leviatan-game
            void IMustInit.Init(GL gl)
            {
                P	= gl.CreateProgram();

                gl.AttachShader(P,VShader.S);
                gl.AttachShader(P,FShader.S);

                gl.LinkProgram(P);

                ////////////////////////////////////////////////////////////////

                int ACount	= 0;
                gl.GetProgramiv(P,ACTIVE_ATTRIBUTES,&ACount);
                if(ACount >= 0)
                {
                    uint i	= 0;
                    while(i < ACount)
                    {
                        uint T;
                        int Lng,Sze;
                        sbyte* pName	= stackalloc sbyte[64];
                        gl.GetActiveAttrib(P,i,64,&Lng,&Sze,&T,pName);

                        int Location	= gl.GetAttribLocation(P,pName);
                        if(Location >= 0)
                        {
                            string AName	= new string(pName);
                            Attributes[AName]	= new Attribute(Location,AName);
                        }
                        i++;
                    }
                }

                int UCount	= 0;
                gl.GetProgramiv(P,ACTIVE_UNIFORMS,&UCount);
                if(UCount >= 0)
                {
                    uint i	= 0;
                    while(i < UCount)
                    {
                        int Lng,Sze;
                        uint T;
                        sbyte* pName	= stackalloc sbyte[64];
                        gl.GetActiveUniform(P,i,64,&Lng,&Sze,&T,pName);

                        int Location	= gl.GetUniformLocation(P,pName);
                        if(Location >= 0)
                        {
                            string UName	= new string(pName);
                            Uniforms[UName]	= new Uniform(gl,Location,UName);
                        }

                        i++;
                    }
                }
            }
コード例 #48
0
    public Equipment Generate()
    {
        Uniform uniform = Resources.Load("Prefabs/Equipment/Uniform/" + uniformName) as Uniform;

        return(uniform);
    }
コード例 #49
0
 public override DrawAutomaticUniform Create(Uniform uniform)
 {
     return new InverseViewportDimensionsUniform(uniform);
 }
コード例 #50
0
ファイル: UniformTests.cs プロジェクト: klipto/Uncertainty
 public void Uniform_Sample()
 {
     // arrange
     double Start = 4.0, End = 6.0;
     Uncertain<double> X = new Uniform<double>(Start, End);
     var sampler = Sampler.Create(X);
     foreach(var p in sampler.Take(100))
     {
         double s = p.Value;
         // assert
         Assert.IsTrue(s >= Start && s <= End);
     }
 }
コード例 #51
0
ファイル: ShaderLoader.cs プロジェクト: Richy19/ultraSandbox
 public void insertUniform(Uniform uni, ref float value)
 {
     int location = locations[(int)uni];
     if (location != -1)
         GL.Uniform1(location, 1, ref value);
 }
コード例 #52
0
 public void UpdateLightSpaceMatrix(Camera camera, DirectionalLight light)
 {
     lightSpaceMatrix &= light.CameraToShadowProjection(camera);
 }
コード例 #53
0
ファイル: ShaderLoader.cs プロジェクト: Richy19/ultraSandbox
 public void insertUniform(Uniform uni, ref Matrix4 value)
 {
     int location = locations[(int)uni];
     if (location != -1)
         GL.UniformMatrix4(location, false, ref value);
 }
コード例 #54
0
 public ShadowUniforms(GLProgram program, Sampler2D sampler) : base(program)
 {
     using (program.Scope())
         shadowMap &= sampler;
 }
コード例 #55
0
ファイル: ShaderLoader.cs プロジェクト: Richy19/ultraSandbox
 internal void insertUniform(Uniform uni, ref int value)
 {
     int location = locations[(int)uni];
     if (location != -1)
         GL.Uniform1(location, 1, ref value);
 }
コード例 #56
0
ファイル: UniformTests.cs プロジェクト: klipto/Uncertainty
 public void Uniform_BNN_Sample()
 {
     // arrange
     Uncertain<double> X = new Uniform<double>(1.0, 3.0);
     Uncertain<double> Y = new Uniform<double>(4.0, 5.0);
     Uncertain<double> Z = from x in X from y in Y select x + y;
     var sampler = Sampler.Create(Z);
     // act
     foreach (var p in sampler.Take(100))
     {
         // act
         double s = p.Value;
         // assert
         Assert.IsTrue(s >= 1.0 && s <= 8.0);
     }
 }
コード例 #57
0
		private void buildUniformList()
		{
			// clear internal lists
			mUniforms.Clear();
			mVertexUniformLookup  = new Uniform[512];
			mFragmentUniformLookup = new Uniform[512];

			int numActive = 0;
			GL.GetProgram(mProgramId, ProgramParameter.ActiveUniforms, out numActive);
			for (int i=0; i < numActive; i++)
			{
				// create new uniform
				var uniform = new Uniform();

				int length;
				var name = new StringBuilder(1024);
				GL.GetActiveUniform(mProgramId, i, name.MaxCapacity, out length, out uniform.Size, out uniform.Type, name);
				uniform.Name 	 = name.ToString();
				uniform.Location = GL.GetUniformLocation (mProgramId, uniform.Name );

				// determine register count for uniform
				switch (uniform.Type)
				{
				case ActiveUniformType.FloatMat2: uniform.RegCount = 2; break;
				case ActiveUniformType.FloatMat3: uniform.RegCount = 3; break;
				case ActiveUniformType.FloatMat4: uniform.RegCount = 4; break;
				default:
					uniform.RegCount = 1; // 1 by default
					break;
				}

				// multiple regcount by size
				uniform.RegCount *= uniform.Size;

				// add uniform to program list
				mUniforms.Add(uniform);

				if (uniform.Name.StartsWith("vc"))
				{
					// vertex uniform
					uniform.RegIndex = int.Parse (uniform.Name.Substring(2));
					// store in vertex lookup table
					mVertexUniformLookup[uniform.RegIndex] = uniform;
				}
				else if (uniform.Name.StartsWith("fc"))
				{
					// fragment uniform
					uniform.RegIndex = int.Parse (uniform.Name.Substring(2));
					// store in fragment lookup table
					mFragmentUniformLookup[uniform.RegIndex] = uniform;
				}

				Console.WriteLine ("{0} name:{1} type:{2} size:{3} location:{4}", i, uniform.Name, uniform.Type, uniform.Size, uniform.Location);
			}
		}
コード例 #58
0
        private void buildUniformList()
        {
            // clear internal lists
            mUniforms.Clear();
            mVertexUniformLookup   = new Uniform[512];
            mFragmentUniformLookup = new Uniform[512];
            mSamplerUniforms.Clear();

            int numActive = 0;

            GL.GetProgram(mProgramId, ProgramParameter.ActiveUniforms, out numActive);
            for (int i = 0; i < numActive; i++)
            {
                // create new uniform
                var uniform = new Uniform();

                int length;
                var name = new StringBuilder(1024);
                GL.GetActiveUniform(mProgramId, i, name.MaxCapacity, out length, out uniform.Size, out uniform.Type, name);
                uniform.Name     = name.ToString();
                uniform.Location = GL.GetUniformLocation(mProgramId, uniform.Name);

                // determine register count for uniform
                switch (uniform.Type)
                {
                case ActiveUniformType.FloatMat2: uniform.RegCount = 2; break;

                case ActiveUniformType.FloatMat3: uniform.RegCount = 3; break;

                case ActiveUniformType.FloatMat4: uniform.RegCount = 4; break;

                default:
                    uniform.RegCount = 1;                     // 1 by default
                    break;
                }

                // multiple regcount by size
                uniform.RegCount *= uniform.Size;

                // add uniform to program list
                mUniforms.Add(uniform);

                if (uniform.Name.StartsWith("vc"))
                {
                    // vertex uniform
                    uniform.RegIndex = int.Parse(uniform.Name.Substring(2));
                    // store in vertex lookup table
                    mVertexUniformLookup[uniform.RegIndex] = uniform;
                }
                else if (uniform.Name.StartsWith("fc"))
                {
                    // fragment uniform
                    uniform.RegIndex = int.Parse(uniform.Name.Substring(2));
                    // store in fragment lookup table
                    mFragmentUniformLookup[uniform.RegIndex] = uniform;
                }
                else if (uniform.Name.StartsWith("sampler"))
                {
                    // sampler uniform
                    uniform.RegIndex = int.Parse(uniform.Name.Substring(7));
                    // add to list of sampler uniforms
                    mSamplerUniforms.Add(uniform);
                }

                // Console.WriteLine ("{0} name:{1} type:{2} size:{3} location:{4}", i, uniform.Name, uniform.Type, uniform.Size, uniform.Location);
            }
        }
コード例 #59
0
        public override void Set(Uniform uniform)
        {
 	        ((Uniform<int>)uniform).Value = _textureUnit;
        }
コード例 #60
0
 public void UpdateLightSpaceMatrices(Camera camera, DirectionalLight light)
 {
     viewLightMatrices &= light.CameraToCsmProjections(camera, MapCount);
 }