예제 #1
0
        private readonly ConstantsBuffer <float> constants; //alas, lack of root constants

        public CompressToSwap(ContentArchive content, float gamma = 2.2f) : base(
                content.Load <GLSLContent>(@"PostProcessing\CompressToSwap.glvs").Source,
                content.Load <GLSLContent>(@"PostProcessing\CompressToSwap.glfs").Source
                )
        {
            Gamma     = gamma;
            constants = new ConstantsBuffer <float>(BufferTarget.UniformBuffer, debugName: "CompressToSwap Constants");
        }
예제 #2
0
 public GlyphRenderer(ContentArchive content, int maximumGlyphsPerDraw = 2048) : base(
         content.Load <GLSLContent>(@"UI\RenderGlyphs.glvs").Source,
         content.Load <GLSLContent>(@"UI\RenderGlyphs.glfs").Source
         )
 {
     instances       = new StructuredBuffer <GlyphInstance>(BufferTarget.ShaderStorageBuffer, maximumGlyphsPerDraw, "Glyph Instances");
     indices         = new IndexBuffer(Helpers.GetQuadIndices(maximumGlyphsPerDraw), "Glyph Indices");
     vertexConstants = new ConstantsBuffer <VertexConstants>(BufferTarget.UniformBuffer, debugName: "Glyph Renderer Vertex Constants");
 }
예제 #3
0
 public MeshRenderer(MeshCache meshCache, ContentArchive content, int maximumInstancesPerDraw = 2048) : base(
         content.Load <GLSLContent>(@"ShapeDrawing\RenderMeshes.glvs").Source,
         content.Load <GLSLContent>(@"ShapeDrawing\RenderMeshes.glfs").Source
         )
 {
     this.meshCache  = meshCache;
     instances       = new StructuredBuffer <MeshInstance>(BufferTarget.ShaderStorageBuffer, maximumInstancesPerDraw, $"Mesh Instances");
     vertexConstants = new ConstantsBuffer <RasterizedVertexConstants>(BufferTarget.UniformBuffer, debugName: $"Mesh Renderer Vertex Constants");
 }
예제 #4
0
        public RasterizedRenderer(ContentArchive content, string shaderPath, int maximumInstancesPerDraw = 2048) : base(
                content.Load <GLSLContent>($"{shaderPath}.glvs").Source,
                content.Load <GLSLContent>($"{shaderPath}.glfs").Source
                )
        {
            string instanceTypeName = typeof(TInstance).Name;

            instances       = new StructuredBuffer <TInstance>(BufferTarget.ShaderStorageBuffer, maximumInstancesPerDraw, $"{instanceTypeName} Instances");
            vertexConstants = new ConstantsBuffer <RasterizedVertexConstants>(BufferTarget.UniformBuffer, debugName: $"{instanceTypeName} Renderer Vertex Constants");
        }
예제 #5
0
        public RayTracedRenderer(ContentArchive content, string shaderPath, int maximumInstancesPerDraw = 2048) : base(
                content.Load <GLSLContent>($"{shaderPath}.glvs").Source,
                content.Load <GLSLContent>($"{shaderPath}.glfs").Source
                )
        {
            var instanceTypeName = typeof(TInstance).Name;

            instances       = new StructuredBuffer <TInstance>(BufferTarget.ShaderStorageBuffer, maximumInstancesPerDraw, $"{instanceTypeName} Instances");
            indices         = new IndexBuffer(Helpers.GetBoxIndices(maximumInstancesPerDraw), $"{instanceTypeName} AABB Indices");
            vertexConstants = new ConstantsBuffer <RayTracedVertexConstants>(BufferTarget.UniformBuffer, debugName: $"{instanceTypeName} Renderer Vertex Constants");
            pixelConstants  = new ConstantsBuffer <RayTracedPixelConstants>(BufferTarget.UniformBuffer, debugName: $"{instanceTypeName} Renderer Pixel Constants");
        }
예제 #6
0
        public DemoHarness(GameLoop loop, ContentArchive content,
                           Controls?controls = null)
        {
            this.loop    = loop;
            this.content = content;
            timeSamples  = new SimulationTimeSamples(512, loop.Pool);
            if (controls == null)
            {
                this.controls = Controls.Default;
            }

            var fontContent = content.Load <FontContent>(@"Content\Carlito-Regular.ttf");

            font = new Font(loop.Surface.Device, loop.Surface.Context, fontContent);

            timingGraph = new Graph(new GraphDescription
            {
                BodyLineColor                 = new Vector3(1, 1, 1),
                AxisLabelHeight               = 16,
                AxisLineRadius                = 0.5f,
                HorizontalAxisLabel           = "Frames",
                VerticalAxisLabel             = "Time (ms)",
                VerticalIntervalValueScale    = 1e3f,
                VerticalIntervalLabelRounding = 2,
                BackgroundLineRadius          = 0.125f,
                IntervalTextHeight            = 12,
                IntervalTickRadius            = 0.25f,
                IntervalTickLength            = 6f,
                TargetHorizontalTickCount     = 5,
                HorizontalTickTextPadding     = 0,
                VerticalTickTextPadding       = 3,

                LegendMinimum    = new Vector2(20, 200),
                LegendNameHeight = 12,
                LegendLineLength = 7,

                TextColor = new Vector3(1, 1, 1),
                Font      = font,

                LineSpacingMultiplier = 1f,

                ForceVerticalAxisMinimumToZero = true
            });
            timingGraph.AddSeries("Total", new Vector3(1, 1, 1), 0.75f, timeSamples.Simulation);
            timingGraph.AddSeries("Pose Integrator", new Vector3(0, 0, 1), 0.25f, timeSamples.PoseIntegrator);
            timingGraph.AddSeries("Sleeper", new Vector3(0.5f, 0, 1), 0.25f, timeSamples.Sleeper);
            timingGraph.AddSeries("Broad Update", new Vector3(1, 1, 0), 0.25f, timeSamples.BroadPhaseUpdate);
            timingGraph.AddSeries("Collision Test", new Vector3(0, 1, 0), 0.25f, timeSamples.CollisionTesting);
            timingGraph.AddSeries("Narrow Flush", new Vector3(1, 0, 1), 0.25f, timeSamples.NarrowPhaseFlush);
            timingGraph.AddSeries("Solver", new Vector3(1, 0, 0), 0.5f, timeSamples.Solver);

            timingGraph.AddSeries("Body Opt", new Vector3(1, 0.5f, 0), 0.125f, timeSamples.BodyOptimizer);
            timingGraph.AddSeries("Constraint Opt", new Vector3(0, 0.5f, 1), 0.125f, timeSamples.ConstraintOptimizer);
            timingGraph.AddSeries("Batch Compress", new Vector3(0, 0.5f, 0), 0.125f, timeSamples.BatchCompressor);

            demoSet = new DemoSet();
            demo    = demoSet.Build(0, content, loop.Camera, loop.Surface);

            OnResize(loop.Window.Resolution);
        }
예제 #7
0
        public Renderer(RenderSurface surface)
        {
            Surface = surface;
            ContentArchive content;

            using (var stream = GetType().Assembly.GetManifestResourceStream("DemoRenderer.DemoRenderer.contentarchive"))
            {
                content = ContentArchive.Load(stream);
            }
            Shapes           = new ShapesExtractor(looper, pool);
            SphereRenderer   = new RayTracedRenderer <SphereInstance>(content, @"ShapeDrawing\RenderSpheres");
            CapsuleRenderer  = new RayTracedRenderer <CapsuleInstance>(content, @"ShapeDrawing\RenderCapsules");
            CylinderRenderer = new RayTracedRenderer <CylinderInstance>(content, @"ShapeDrawing\RenderCylinders");
            BoxRenderer      = new BoxRenderer(content);
            TriangleRenderer = new TriangleRenderer(content);
            MeshRenderer     = new MeshRenderer(Shapes.MeshCache, content);
            Lines            = new LineExtractor(pool, looper);
            LineRenderer     = new LineRenderer(content);
            Background       = new BackgroundRenderer(content);
            CompressToSwap   = new CompressToSwap(content);

            ImageRenderer  = new ImageRenderer(content);
            ImageBatcher   = new ImageBatcher(pool);
            GlyphRenderer  = new GlyphRenderer(content);
            TextBatcher    = new TextBatcher();
            UILineRenderer = new UILineRenderer(content);
            UILineBatcher  = new UILineBatcher();

            OnResize();
        }
예제 #8
0
        private static void Main()
        {
            if (!false) // Run in the background
            {
                using (var simulation = new WalkerDemo())
                {
                    var start = System.DateTime.UtcNow;
                    simulation.RunPhysics(canContinue: () => (System.DateTime.UtcNow - start).TotalSeconds < -5); // Run for a few secs
                }
            }

            ContentArchive content;

            using (var stream = typeof(Demos.DemoHarness).Assembly.GetManifestResourceStream("Demos.Demos.contentarchive"))
            {
                content = ContentArchive.Load(stream);
            }

            using (var window = new DemoEngine.Window("SharpNeat Walker", new Int2((int)(DisplayDevice.Default.Width * 0.75f), (int)(DisplayDevice.Default.Height * 0.75f)), WindowMode.Windowed))
                using (var loop = new GameLoop(window))
                {
                    var harness = new DemoHarness(loop, content, customDemoSet: new DemoSet().AddOption <WalkerDemo>());
                    loop.Run(harness);
                }

            /*var loop = new GameLoop(window);
             * var demo = new DemoHarness(loop, content, customDemoSet: new DemoSet().AddOption<Walker>());
             * loop.Run(demo);
             * loop.Dispose();*/
        }
예제 #9
0
 public static ContentArchive GetDemosContentArchive()
 {
     using (var stream = typeof(Demos.Demos.FountainStressTestDemo).Assembly.GetManifestResourceStream("Demos.Demos.contentarchive"))
     {
         return(ContentArchive.Load(stream));
     }
 }
        public static Dictionary <string, ContentElement> Load(Stream stream)
        {
            using (var reader = new BinaryReader(stream))
            {
                try
                {
                    var cache        = new Dictionary <string, ContentElement>();
                    var contentCount = reader.ReadInt32();

                    for (int i = 0; i < contentCount; ++i)
                    {
                        var path = reader.ReadString();
                        var lastModifiedTimestamp = reader.ReadInt64();
                        var contentType           = (ContentType)reader.ReadInt32();
                        var content = ContentArchive.Load(contentType, reader);
                        cache.Add(path, new ContentElement {
                            LastModifiedTimestamp = lastModifiedTimestamp, Content = content
                        });
                    }
                    return(cache);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Content build cache load failed; may be corrupted. Assuming fresh build. Message:");
                    Console.WriteLine(e.Message);
                    return(new Dictionary <string, ContentElement>());
                }
            }
        }
예제 #11
0
        //Loads a mesh into memory, then returns a key you can use to access that mesh from the dictionary
        public static int LoadMesh(string ContentName, Vector3 Scale)
        {
            //Make sure the manager has been initialized first
            if (MeshArchive == null || MemoryPool == null)
            {
                MessageLog.Print("ERROR: MeshManager has not been initialized yet, initialize it first before trying to load meshes into memory.");
                return(-1);
            }

            //Make sure there isnt already a mesh loaded with this name
            if (LoadedMeshNames.Contains(ContentName))
            {
                MessageLog.Print("Theres already a mesh loaded by the name of " + ContentName + ".");
                return(-1);
            }

            //Load the meshes content from the archive and build a new Mesh object with its information
            var MeshContent = MeshArchive.Load <MeshContent>(ContentName);

            MemoryPool.Take <Triangle>(MeshContent.Triangles.Length, out var Triangles);
            for (int i = 0; i < MeshContent.Triangles.Length; i++)
            {
                Triangles[i] = new Triangle(MeshContent.Triangles[i].A, MeshContent.Triangles[i].B, MeshContent.Triangles[i].C);
            }
            Mesh MeshObject = new Mesh(Triangles, Scale, MemoryPool);

            //Store the new mesh object into the dictionary with the others
            int MeshKey = ++NextMeshKey;

            LoadedMeshes.Add(MeshKey, MeshObject);
            return(MeshKey);
        }
예제 #12
0
        RenderableImage CreateRewardImage(string rewardImagePath, ContentArchive content, RenderSurface surface)
        {
            var textureContent = content.Load <Texture2DContent>(rewardImagePath);

            return(new RenderableImage(
#if !OPENGL
                       surface.Device, surface.Context,
#endif
                       textureContent, debugName: Path.GetFileNameWithoutExtension(rewardImagePath)
                       ));
        }
예제 #13
0
        static void Main(string[] args)
        {
            //OperatorCodegenTests.Test();
            //ConstraintDescriptionMappingTests.Test();
            //CollidablePairComparerTests.Test();
            //HeadlessDemo.Simple();
            //BatchedCollisionTests.Test();
            //TypeIdCodeGenTests.Test();
            //DeterminismTest.Test();
            //return;
            //ScalarWideTests.Test();
            //DenseFlagTests.Test();
            //VirtualOverheadTest.Test();
            //TreeTest.Test();
            //ReinterpretVectorRepro.Test();
            //TriangularTests.Test();
            //LocalsinitCodegen.Test();
            //InterlockedOverheadTests.Test();
            //LocalsinitCodegen.Test();
            //AutoTester.Test();
            //BallSocketConvergenceTests.Test();
            //MemoryResizeTests.Test();
            //DisposeTests.Test();
            //ConstraintCacheOptimizationTests.Test();
            //SortTest.Test();
            //SpanCodegenTests.Test();
            //IntertreeThreadingTests.Test();
            //return;

            //Console.ReadKey();
            var window = new Window("pretty cool multicolored window",
                                    new Int2((int)(DisplayDevice.Default.Width * 0.75f), (int)(DisplayDevice.Default.Height * 0.75f)), WindowMode.Windowed);
            var            loop = new GameLoop(window);
            ContentArchive content;

            using (var stream = new MemoryStream(Resources.Content))
            {
                content = ContentArchive.Load(stream);
            }
            //var fontContent = content.Load<FontContent>(@"Content\Courier Prime Sans.ttf");
            var fontContent = content.Load <FontContent>(@"Content\Carlito-Regular.ttf");
            var font        = new Font(loop.Surface.Device, loop.Surface.Context, fontContent);
            var demo        = new DemoHarness(window, loop.Input, loop.Camera, font);

            loop.Run(demo);
            loop.Dispose();
            window.Dispose();
        }
예제 #14
0
        static void Main(string[] args)
        {
            var            window = new Window("pretty cool multicolored window", new Int2((int)(DisplayDevice.Default.Width * 0.75f), (int)(DisplayDevice.Default.Height * 0.75f)), WindowMode.Windowed);
            var            loop   = new GameLoop(window);
            ContentArchive content;

            using (var stream = typeof(Program).Assembly.GetManifestResourceStream("bepuphysics2_for_nelalen.Demos.contentarchive"))
            {
                content = ContentArchive.Load(stream);
            }
            var demo = new DemoHarness(loop, content);

            loop.Run(demo);
            loop.Dispose();
            window.Dispose();
        }
예제 #15
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-5f, 5.5f, 5f);
            camera.Yaw      = MathHelper.Pi / 4;
            camera.Pitch    = MathHelper.Pi * 0.15f;

            var filters = new BodyProperty <DeformableCollisionFilter>();

            Simulation = Simulation.Create(BufferPool, new DeformableCallbacks {
                Filters = filters
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var   meshContent = content.Load <MeshContent>("Content\\newt.obj");
            float cellSize    = 0.1f;

            DumbTetrahedralizer.Tetrahedralize(meshContent.Triangles, cellSize, BufferPool,
                                               out var vertices, out var vertexSpatialIndices, out var cellVertexIndices, out var tetrahedraVertexIndices);
            var weldSpringiness   = new SpringSettings(30f, 0);
            var volumeSpringiness = new SpringSettings(30f, 1);

            for (int i = 0; i < 5; ++i)
            {
                NewtDemo.CreateDeformable(Simulation, new Vector3(i * 3, 5 + i * 1.5f, 0), Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathF.PI * (i * 0.55f)), 1f, cellSize, weldSpringiness, volumeSpringiness, i, filters, ref vertices, ref vertexSpatialIndices, ref cellVertexIndices, ref tetrahedraVertexIndices);
            }

            BufferPool.Return(ref vertices);
            vertexSpatialIndices.Dispose(BufferPool);
            BufferPool.Return(ref cellVertexIndices);
            BufferPool.Return(ref tetrahedraVertexIndices);

            Simulation.Bodies.Add(BodyDescription.CreateConvexDynamic(new Vector3(0, 100, -.5f), 10, Simulation.Shapes, new Sphere(5)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(1500, 1, 1500)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -1.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Sphere(3)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.25f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(RigidPose.Identity, bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 1f), new BodyActivityDescription(0.01f));

            DemoMeshHelper.LoadModel(content, BufferPool, "Content\\newt.obj", new Vector3(20), out var mesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(200, 0.5f, 120), Quaternion.CreateFromAxisAngle(Vector3.UnitY, -3 * MathHelper.PiOver4), new CollidableDescription(Simulation.Shapes.Add(mesh), 0.1f)));
        }
예제 #16
0
        private bool StartServer(string ServerIP)
        {
            //Display a message to the console indicating the server is not being started
            MessageLog.Print("Starting server on " + ServerIP);

            //Before connecting to the server we need to load the connection settings from the .xml config file, start by loading the file into memory
            XmlDocument ConnectionSettings = new XmlDocument();

            ConnectionSettings.Load("SQLConnectionSettings.xml");

            //Extract all the required values from the file and store each of their into their own variables
            int    NetworkPort        = Convert.ToInt32(ConnectionSettings.DocumentElement.SelectSingleNode("/root/NetworkPort").InnerText);
            string WindowsServiceName = ConnectionSettings.DocumentElement.SelectSingleNode("/root/WindowsServiceName").InnerText;
            string Username           = ConnectionSettings.DocumentElement.SelectSingleNode("/root/Username").InnerText;
            string Password           = ConnectionSettings.DocumentElement.SelectSingleNode("/root/Password").InnerText;

            //Load all the existing game items from the exported text file
            ItemInfoDatabase.LoadItemList("Content/MasterItemList.txt");
            ItemManager.InitializeItemManager();

            //Start listening for new network client connections
            ConnectionManager.Initialize(ServerIP);

            //Open a new window for rendering so we can see whats going on while the server is up
            ApplicationWindow = new Window("Swaelo Server 2.0", new Int2(1024, 768), WindowMode.Windowed); // new Int2(1700, 100), WindowMode.Windowed);
            LogicLoop         = new GameLoop(ApplicationWindow);

            //Load in the contents needed for the scene to run
            ContentArchive Content;

            using (var Stream = typeof(Program).Assembly.GetManifestResourceStream("Server.Content.ServerContents.contentarchive"))
                Content = ContentArchive.Load(Stream);

            //Initialize the game world simulation
            World = new GameWorld(LogicLoop, Content);

            return(true);
        }
예제 #17
0
        static void Main(string[] args)
        {
            //ConstraintDescriptionMappingTests.Test();
            //Console.ReadKey();

            var window = new Window("pretty cool multicolored window",
                                    new Int2((int)(DisplayDevice.Default.Width * 0.75f), (int)(DisplayDevice.Default.Height * 0.75f)), WindowMode.Windowed);
            var            loop = new GameLoop(window);
            ContentArchive content;

            using (var stream = new MemoryStream(Resources.Content))
            {
                content = ContentArchive.Load(stream);
            }
            //var fontContent = content.Load<FontContent>(@"Content\Courier Prime Sans.ttf");
            var fontContent = content.Load <FontContent>(@"Content\Carlito-Regular.ttf");
            var font        = new Font(loop.Surface.Device, loop.Surface.Context, fontContent);
            var demo        = new DemoHarness(window, loop.Input, loop.Camera, font);

            loop.Run(demo);
            loop.Dispose();
            window.Dispose();
        }
예제 #18
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(25f, 1.5f, 15f);
            camera.Yaw      = 3 * MathHelper.Pi / 4;
            camera.Pitch    = 0;// MathHelper.Pi * 0.15f;

            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var meshContent = content.Load <MeshContent>("Content\\newt.obj");

            //This is actually a pretty good example of how *not* to make a convex hull shape.
            //Generating it directly from a graphical data source tends to have way more surface complexity than needed,
            //and it tends to have a lot of near-but-not-quite-coplanar surfaces which can make the contact manifold less stable.
            //Prefer a simpler source with more distinct features, possibly created with an automated content-time tool.
            var points = new QuickList <Vector3>(meshContent.Triangles.Length * 3, BufferPool);

            for (int i = 0; i < meshContent.Triangles.Length; ++i)
            {
                ref var triangle = ref meshContent.Triangles[i];
                //resisting the urge to just reinterpret the memory
                points.AllocateUnsafely() = triangle.A * new Vector3(1, 1.5f, 1);
                points.AllocateUnsafely() = triangle.B * new Vector3(1, 1.5f, 1);
                points.AllocateUnsafely() = triangle.C * new Vector3(1, 1.5f, 1);
            }
예제 #19
0
 public BackgroundRenderer(ContentArchive content) : base(
         content.Load <GLSLContent>(@"Background\RenderBackground.glvs").Source,
         content.Load <GLSLContent>(@"Background\RenderBackground.glfs").Source
         ) =>
예제 #20
0
        //Constructor which sets up the whole game world scene
        public GameWorld(GameLoop Loop, ContentArchive Content)
        {
            //Store references from the GameLoop class
            ApplicationWindow = Loop.Window;
            UserInput         = Loop.Input;

            //Assign the camera reference
            ObservationCamera.SetCamera(Loop);

            this.Content = Content;
            TimeSamples  = new SimulationTimeSamples(512, Loop.Pool);
            UserControls = Controls.Default;

            //Load font from the content archive
            var FontContent = Content.Load <FontContent>(@"Carlito-Regular.ttf");

            UIFont = new Font(Loop.Surface.Device, Loop.Surface.Context, FontContent);

            //Position the camera
            ObservationCamera.PositionCamera(new Vector3(2.7f, 6.48f, 9.76f));
            ObservationCamera.FaceCamera(0.269f, 0.15899f);

            //Setup character controller and world simulation
            BufferPool       = new BufferPool();
            ThreadDispatcher = new SimpleThreadDispatcher(Environment.ProcessorCount);
            World            = Simulation.Create(BufferPool, new CharacterNarrowphaseCallbacks(new CharacterControllers(BufferPool)), new ScenePoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            //Initialize the mesh loader
            MeshManager.Initialize(Content, BufferPool);

            //Load in the numbers display the direction of the X/Z axes
            AxisMarkers.LoadModels();
            AxisMarkers.AddModels(World);

            //Load in the PVP arena
            ArenaMeshHandle = MeshManager.LoadMesh(@"Arena.obj", new Vector3(1));
            //Define its starting position and location
            Vector3    ArenaPosition = new Vector3(29.82f, 3.62f, 0.94f);
            Quaternion ArenaRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), Trig.DegreesToRadians(180));

            //Use those to add it into the world
            MeshManager.AddStatic(World, ArenaMeshHandle, ArenaPosition, ArenaRotation);

            //Place the jumping cubes
            World.Statics.Add(new StaticDescription(new Vector3(1.299f, 2.3f, -31.24f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));
            World.Statics.Add(new StaticDescription(new Vector3(-26.56f, 2.3f, -35.2f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));
            World.Statics.Add(new StaticDescription(new Vector3(-33.12f, 2.3f, -21.65f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));
            World.Statics.Add(new StaticDescription(new Vector3(-26.05f, 2.3f, -9.38f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));
            World.Statics.Add(new StaticDescription(new Vector3(-10.31f, 2.3f, -5.62f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));
            World.Statics.Add(new StaticDescription(new Vector3(1.94f, 2.3f, -15.88f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));
            World.Statics.Add(new StaticDescription(new Vector3(-11.3f, 2.3f, -37.44f), new CollidableDescription(World.Shapes.Add(new Box(5, 5, 5)), 0.1f)));

            //Place a ground plane to walk on
            World.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(World.Shapes.Add(new Box(100, 1, 100)), 0.1f)));

            //Setup the command executor
            CommandInputField.Initialize();

            //Make sure the window size is correct relative to the current resolution
            OnResize(ApplicationWindow.Resolution);
        }
예제 #21
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-10, 0, -10);
            //camera.Yaw = MathHelper.Pi ;
            camera.Yaw = MathHelper.Pi * 3f / 4;
            //camera.Pitch = MathHelper.PiOver2 * 0.999f;
            Simulation = Simulation.Create(BufferPool, new TestCallbacks());
            //Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            var box     = new Box(1f, 3f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 1;
            const int height       = 3;
            const int length       = 1;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(3, 3, 3) * new Vector3(i, j, k);// + new Vector3(-width * 1.5f, 1.5f, -length * 1.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.01f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = BepuUtilities.Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        //Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }
            //Simulation.Bodies.Add(new BodyDescription
            //{
            //    Activity = new BodyActivityDescription(-1),
            //    Pose = new RigidPose(new Vector3(1, 2.999f, 0), BepuUtilities.Quaternion.CreateFromYawPitchRoll(0, 0, -0.00001f)),
            //    Collidable = new CollidableDescription(capsuleIndex, 1),
            //    LocalInertia = capsuleInertia
            //});
            Simulation.Bodies.Add(new BodyDescription
            {
                Activity     = new BodyActivityDescription(-1),
                Pose         = new RigidPose(new Vector3(0, 0, 0), BepuUtilities.Quaternion.Identity),
                Collidable   = new CollidableDescription(boxIndex, .1f),
                LocalInertia = boxInertia
            });
            Simulation.Bodies.Add(new BodyDescription
            {
                Activity     = new BodyActivityDescription(-1),
                Pose         = new RigidPose(new Vector3(1, 3, 0), BepuUtilities.Quaternion.Identity),
                Collidable   = new CollidableDescription(boxIndex, .1f),
                LocalInertia = new BodyInertia()
            });

            var meshContent = content.Load <MeshContent>(@"Content\box.obj");

            //BufferPool.Take<Triangle>(meshContent.Triangles.Length, out var triangles);
            //for (int i = 0; i < meshContent.Triangles.Length; ++i)
            //{
            //    triangles[i] = new Triangle(meshContent.Triangles[i].A, meshContent.Triangles[i].B, meshContent.Triangles[i].C);
            //}
            //var meshShape = new Mesh(triangles.Slice(0, meshContent.Triangles.Length), new Vector3(5, 1, 5), BufferPool);
            BufferPool.Take <Triangle>(2, out var triangles);
            for (int i = 2; i < 4; ++i)
            {
                triangles[i - 2] = new Triangle(meshContent.Triangles[i].A, meshContent.Triangles[i].B, meshContent.Triangles[i].C);
            }
            var meshShape        = new Mesh(triangles.Slice(0, 2), new Vector3(5, 1, 5), BufferPool);
            var staticShapeIndex = Simulation.Shapes.Add(meshShape);

            for (int i = 0; i < 1; ++i)
            {
                var staticDescription = new StaticDescription
                {
                    Collidable = new CollidableDescription(staticShapeIndex, 0.1f),
                    Pose       = new RigidPose
                    {
                        Position    = new Vector3(i * 10, -10, 0),
                        Orientation = BepuUtilities.Quaternion.Identity
                                      //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(1 + i, i * j % 10, -10 + -j)), (i ^ j) * 0.5f * (MathHelper.PiOver4))
                                      //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(0, 0, 1)), MathHelper.Pi)
                    }
                };
                Simulation.Statics.Add(staticDescription);
            }
        }