protected override void OnLoad() { var contentManager = _services.GetInstance<ContentManager>(); // ----- Graphics // Load a graphics model and add it to the scene for rendering. _modelNode = contentManager.Load<ModelNode>("Ship/Ship").Clone(); _modelNode.PoseWorld = new Pose(Vector3F.Zero, Matrix33F.CreateRotationY(-ConstantsF.PiOver2)); var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); // ----- Collision Detection // Create a collision object and add it to the collision domain. // Load collision shape from a separate model (created using the CollisionShapeProcessor). var shape = contentManager.Load<Shape>("Ship/Ship_CollisionModel"); // Create a GeometricObject (= Shape + Pose + Scale). _geometricObject = new GeometricObject(shape, _modelNode.PoseWorld); // Create a collision object and add it to the collision domain. _collisionObject = new CollisionObject(_geometricObject); // Important: We do not need detailed contact information when a collision // is detected. The information of whether we have contact or not is sufficient. // Therefore, we can set the type to "Trigger". This increases the performance // dramatically. _collisionObject.Type = CollisionObjectType.Trigger; // Add the collision object to the collision domain of the game. var collisionDomain = _services.GetInstance<CollisionDomain>(); collisionDomain.CollisionObjects.Add(_collisionObject); }
public ManualMeshRenderSample(Microsoft.Xna.Framework.Game game) : base(game) { SampleFramework.IsMouseVisible = false; var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService) { RenderCallback = Render, }; GraphicsService.Screens.Insert(0, delegateGraphicsScreen); // Add a custom game object which controls the camera. _cameraObject = new CameraObject(Services); GameObjectService.Objects.Add(_cameraObject); _scene = new Scene(); SceneSample.InitializeDefaultXnaLights(_scene); // For advanced users: Set this flag if you want to analyze the imported opaque data of // effect bindings. EffectBinding.KeepOpaqueData = true; _model = ContentManager.Load<ModelNode>("Dude/Dude").Clone(); var meshNode = _model.GetSubtree().OfType<MeshNode>().First(); meshNode.ScaleLocal = new Vector3F(1, 2, 1); var mesh = meshNode.Mesh; var timeline = new TimelineClip(mesh.Animations.Values.First()) { Duration = TimeSpan.MaxValue, LoopBehavior = LoopBehavior.Cycle, }; AnimationService.StartAnimation(timeline, (IAnimatableProperty)meshNode.SkeletonPose); }
public RedSquareObject(Vector3F position) { _position = position; _color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f); var graphicsService = ServiceLocator.Current.GetInstance<IGraphicsService>(); var screen = ((GameScreen)graphicsService.Screens["Default"]); var contentManager = ServiceLocator.Current.GetInstance<ContentManager>(); _model = contentManager.Load<ModelNode>("redSquare").Clone(); screen.Scene.Children.Add(_model); _model.PoseWorld = new Pose(_position); foreach (var meshNode in _model.GetSubtree().OfType<MeshNode>()) { Mesh mesh = meshNode.Mesh; foreach (var material in mesh.Materials) { var effectBinding = material["Default"]; effectBinding.Set("DiffuseColor", _color); ((BasicEffectBinding)effectBinding).LightingEnabled = false; } } InUse = true; }
public ConvexHullSample(Microsoft.Xna.Framework.Game game) : base(game) { // Add basic force effects. Simulation.ForceEffects.Add(new Gravity()); Simulation.ForceEffects.Add(new Damping()); // Add a ground plane. RigidBody groundPlane = new RigidBody(new PlaneShape(Vector3F.UnitY, 0)) { Name = "GroundPlane", // Names are not required but helpful for debugging. MotionType = MotionType.Static, }; Simulation.RigidBodies.Add(groundPlane); // Load model and add it to the graphics scene. _saucerModelNode = ContentManager.Load<ModelNode>("Saucer2/saucer").Clone(); GraphicsScreen.Scene.Children.Add(_saucerModelNode); // Create rigid body for this model. // The tag contains the collision shape (created in the content processor). Shape saucerShape = (Shape)_saucerModelNode.UserData; _saucerBody = new RigidBody(saucerShape) { Pose = new Pose(new Vector3F(0, 2, 0), RandomHelper.Random.NextQuaternionF()) }; Simulation.RigidBodies.Add(_saucerBody); }
protected override void OnLoad() { var contentManager = ServiceLocator.Current.GetInstance<ContentManager>(); var graphicsService = ServiceLocator.Current.GetInstance<IGraphicsService>(); var screen = ((BasicScreen)graphicsService.Screens["Default"]); _model = contentManager.Load<ModelNode>(_modelFile); _model = _model.Clone(); foreach (var meshNode in _model.GetSubtree().OfType<MeshNode>()) { Mesh mesh = meshNode.Mesh; foreach (var material in mesh.Materials) { var effectBinding = material["Default"]; effectBinding.Set("DiffuseColor", new Vector4(1.0f, 1.0f, 1.0f, 1)); ((BasicEffectBinding)effectBinding).LightingEnabled = false; } } screen.Scene.Children.Add(_model); _model.PoseWorld = new DigitalRune.Geometry.Pose(new Vector3F(0.0f, 0.0f, 0.0f)); base.OnLoad(); }
public AttachmentSample(Microsoft.Xna.Framework.Game game) : base(game) { var modelNode = ContentManager.Load<ModelNode>("Marine/PlayerMarine"); _meshNode = modelNode.GetSubtree().OfType<MeshNode>().First().Clone(); SampleHelper.EnablePerPixelLighting(_meshNode); GraphicsScreen.Scene.Children.Add(_meshNode); // Play a looping 'Idle' animation. var animations = _meshNode.Mesh.Animations; var idleAnimation = animations["Idle"]; var loopingAnimation = new AnimationClip<SkeletonPose>(idleAnimation) { LoopBehavior = LoopBehavior.Cycle, Duration = TimeSpan.MaxValue, }; var animationController = AnimationService.StartAnimation(loopingAnimation, (IAnimatableProperty)_meshNode.SkeletonPose); animationController.UpdateAndApply(); animationController.AutoRecycle(); // Add weapon model to the scene graph under the node of the marine mesh. _weaponModelNode = ContentManager.Load<ModelNode>("Marine/Weapon/WeaponMachineGun").Clone(); _meshNode.Children = new SceneNodeCollection(); _meshNode.Children.Add(_weaponModelNode); }
// OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { // Load model. var contentManager = _services.GetInstance<ContentManager>(); _modelNode = contentManager.Load<ModelNode>("Ground/Ground").Clone(); _modelNode.ScaleLocal = new Vector3F(0.5f); foreach (var node in _modelNode.GetSubtree()) { // Disable the CastsShadows flag for ground meshes. No need to render // this model into the shadow map. (This also avoids any shadow acne on // the ground model.) node.CastsShadows = false; // If models will never move, set the IsStatic flag. This gives the engine // more room for optimizations. Additionally, some effects, like certain // decals, may only affect static geometry. node.IsStatic = true; } // Add model node to scene graph. var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); // Create rigid body. _rigidBody = new RigidBody(new PlaneShape(Vector3F.UnitY, 0)) { MotionType = MotionType.Static, }; // Add rigid body to the physics simulation. var simulation = _services.GetInstance<Simulation>(); simulation.RigidBodies.Add(_rigidBody); }
// OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { // Load model. var contentManager = _services.GetInstance<ContentManager>(); _modelNode = contentManager.Load<ModelNode>(_assetName).Clone(); // Optional: Create rigid body using the triangle mesh of the model. if (_addRigidBody) CreateRigidBody(); _modelNode.ScaleLocal = _scale; _modelNode.PoseLocal = _pose; foreach (var node in _modelNode.GetSubtree()) { node.CastsShadows = _castsShadows; // If models will never move, set the IsStatic flag. This gives the engine // more room for optimizations. Additionally, some effects, like certain // decals, may only affect static geometry. node.IsStatic = true; } // Add model node to scene graph. var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); }
protected override void OnLoad() { var contentManager = _services.GetInstance<ContentManager>(); // ----- Graphics // Load graphics model (created using the ModelWithCollisionMeshProcessor). var sharedModelNode = contentManager.Load<ModelNode>("Saucer/saucer"); // Let's create a clone because we do not want to change the shared Saucer // instance stored in the content manager. _modelNode = sharedModelNode.Clone(); _modelNode.PoseWorld = new Pose(Vector3F.Zero, Matrix33F.CreateRotationY(-ConstantsF.PiOver2)); // The collision shape is stored in the UserData. var shape = (Shape)_modelNode.UserData; // Add model to the scene for rendering. var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); // ----- Collision Detection // Create a collision object and add it to the collision domain. _geometricObject = new GeometricObject(shape, _modelNode.PoseWorld); _collisionObject = new CollisionObject(_geometricObject); // Important: We do not need detailed contact information when a collision // is detected. The information of whether we have contact or not is sufficient. // Therefore, we can set the type to "Trigger". This increases the performance // dramatically. _collisionObject.Type = CollisionObjectType.Trigger; var collisionDomain = _services.GetInstance<CollisionDomain>(); collisionDomain.CollisionObjects.Add(_collisionObject); }
public RibbonSample(Microsoft.Xna.Framework.Game game) : base(game) { GraphicsScreen.DrawReticle = true; GameObjectService.Objects.Add(new GrabObject(Services)); // Load a sphere model. _modelNode = ContentManager.Load<ModelNode>("Particles/Sphere").Clone(); GraphicsScreen.Scene.Children.Add(_modelNode); // Add gravity and damping to the physics simulation. Simulation.ForceEffects.Add(new Gravity()); Simulation.ForceEffects.Add(new Damping()); // Create a rigid body for the sphere. _rigidBody = new RigidBody(new SphereShape(0.5f)) { Pose = new Pose(new Vector3F(-3, 0, 0)), LinearVelocity = new Vector3F(10, 10, -3f), }; Simulation.RigidBodies.Add(_rigidBody); _particleSystem = RibbonEffect.Create(ContentManager); ParticleSystemService.ParticleSystems.Add(_particleSystem); _particleSystemNode = new ParticleSystemNode(_particleSystem); GraphicsScreen.Scene.Children.Add(_particleSystemNode); }
private void SetRandomColorAndAlpha(ModelNode model) { var randomColor3F = RandomHelper.Random.NextVector3F(0, 4); // Desaturate random color to avoid eye cancer. ;-) float luminance = Vector3F.Dot(randomColor3F, GraphicsHelper.LuminanceWeights); var randomColor = (Vector3)InterpolationHelper.Lerp(new Vector3F(luminance), randomColor3F, 0.5f); var randomAlpha = MathHelper.Clamp(RandomHelper.Random.NextFloat(0, 5), 0, 1); // Change the values of all effect parameters "InstanceColor" and "InstanceAlpha": foreach (MeshNode meshNode in model.GetDescendants().OfType<MeshNode>()) { foreach (MaterialInstance materialInstance in meshNode.MaterialInstances) { foreach (EffectBinding effectBinding in materialInstance.EffectBindings) { if (effectBinding.ParameterBindings.Contains("InstanceColor")) effectBinding.Set("InstanceColor", randomColor); if (effectBinding.ParameterBindings.Contains("InstanceAlpha")) effectBinding.Set("InstanceAlpha", randomAlpha); } } } }
// OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { // ----- Create prototype of a lava ball: // Use a sphere for physics simulation. _bodyPrototype = new RigidBody(new SphereShape(0.5f)); // Load the graphics model. var content = _services.GetInstance<ContentManager>(); _modelPrototype = content.Load<ModelNode>("LavaBall/LavaBall").Clone(); // Attach a point light to the model. The light projects the glowing lava // veins (cube map texture) onto the environment. _pointLight = new PointLight { Color = new Vector3F(1, 1, 1), DiffuseIntensity = 2, SpecularIntensity = 2, Range = 1.5f, Attenuation = 0.5f, Texture = content.Load<TextureCube>("LavaBall/LavaCubeMap"), }; var pointLightNode = new LightNode(_pointLight); _modelPrototype.Children.Add(pointLightNode); // Get the emissive color binding of the material because the emissive color // will be animated. // The model contains one mesh node with a single material. var meshNode = (MeshNode)_modelPrototype.Children[0]; var mesh = meshNode.Mesh; var material = mesh.Materials[0]; // The material contains several effect bindings. The "EmissiveColor" is applied // in the "Material" pass. // (For reference see material definition file: Samples\Media\LavaBall\Lava.drmat) _emissiveColorBinding = (ConstParameterBinding<Vector3>)material["Material"].ParameterBindings["EmissiveColor"]; // Use the animation service to animate glow intensity of the lava. var animationService = _services.GetInstance<IAnimationService>(); // Create an AnimatableProperty<float>, which stores the animation value. _glowIntensity = new AnimatableProperty<float>(); // Create sine animation and play the animation back-and-forth. var animation = new SingleFromToByAnimation { From = 0.3f, To = 3.0f, Duration = TimeSpan.FromSeconds(1), EasingFunction = new SineEase { Mode = EasingMode.EaseInOut }, }; var clip = new AnimationClip<float> { Animation = animation, Duration = TimeSpan.MaxValue, LoopBehavior = LoopBehavior.Oscillate }; animationService.StartAnimation(clip, _glowIntensity).AutoRecycle(); }
// OnUnload() is called when the GameObject is removed from the IGameObjectService. protected override void OnUnload() { // Remove model and rigid body. _modelNode.Parent.Children.Remove(_modelNode); _modelNode.Dispose(false); _modelNode = null; _rigidBody.Simulation.RigidBodies.Remove(_rigidBody); _rigidBody = null; }
// OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { var contentManager = _services.GetInstance<ContentManager>(); // A rusty barrel with multiple levels of detail (LODs). _rigidBody = new RigidBody(new CylinderShape(0.35f, 1)); _modelNode0 = contentManager.Load<ModelNode>("Barrel/Barrel").Clone(); SampleHelper.EnablePerPixelLighting(_modelNode0); // Mark the LOD nodes with UserFlags = 1. _modelNode0.GetDescendants() .OfType<LodGroupNode>() .SelectMany(lodGroupNode => lodGroupNode.Levels) .Select(level => level.Node) .ForEach(node => { node.UserFlags = 1; }); // Add a second model where each LOD has a different color. _modelNode1 = contentManager.Load<ModelNode>("Barrel/Barrel_Colored").Clone(); SampleHelper.EnablePerPixelLighting(_modelNode1); // Mark the LOD nodes with UserFlags = 2. _modelNode1.GetDescendants() .OfType<LodGroupNode>() .SelectMany(lodGroupNode => lodGroupNode.Levels) .Select(level => level.Node) .ForEach(node => { node.UserFlags = 2; }); // Set a random pose. var randomPosition = new Vector3F( RandomHelper.Random.NextFloat(-10, 10), RandomHelper.Random.NextFloat(2, 5), RandomHelper.Random.NextFloat(-10, 0)); _rigidBody.Pose = new Pose(randomPosition, RandomHelper.Random.NextQuaternionF()); _modelNode0.PoseWorld = _rigidBody.Pose; _modelNode1.PoseWorld = _rigidBody.Pose; // Add rigid body to physics simulation and models to scene. var simulation = _services.GetInstance<Simulation>(); simulation.RigidBodies.Add(_rigidBody); var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode0); scene.Children.Add(_modelNode1); }
public ContentPipelineHeightFieldSample(Microsoft.Xna.Framework.Game game) : base(game) { // Add basic force effects. Simulation.ForceEffects.Add(new Gravity()); Simulation.ForceEffects.Add(new Damping()); // Load height field model and add it to the graphics scene. _heightFieldModelNode = ContentManager.Load<ModelNode>("HeightField/TerrainHeights").Clone(); GraphicsScreen.Scene.Children.Add(_heightFieldModelNode); // The UserData contains the collision shape of type HeightField. HeightField heightField = (HeightField)_heightFieldModelNode.UserData; _heightFieldModelNode.PoseWorld = new Pose(new Vector3F(-heightField.WidthX / 2, 0, -heightField.WidthZ / 2)); // Create rigid body. _heightFieldBody = new RigidBody(heightField, null, null) { MotionType = MotionType.Static, Pose = _heightFieldModelNode.PoseWorld, // The PhysicsSample class should not draw the height field. UserData = "NoDraw", }; Simulation.RigidBodies.Add(_heightFieldBody); // Distribute a few spheres and boxes across the landscape. SphereShape sphereShape = new SphereShape(0.5f); for (int i = 0; i < 30; i++) { Vector3F position = RandomHelper.Random.NextVector3F(-30, 30); position.Y = 20; RigidBody body = new RigidBody(sphereShape) { Pose = new Pose(position) }; Simulation.RigidBodies.Add(body); } BoxShape boxShape = new BoxShape(1, 1, 1); for (int i = 0; i < 30; i++) { Vector3F position = RandomHelper.Random.NextVector3F(-30, 30); position.Y = 20; RigidBody body = new RigidBody(boxShape) { Pose = new Pose(position) }; Simulation.RigidBodies.Add(body); } }
protected override void OnLoad() { var contentManager = ServiceLocator.Current.GetInstance<ContentManager>(); var graphicsService = ServiceLocator.Current.GetInstance<IGraphicsService>(); var simulation = ServiceLocator.Current.GetInstance<Simulation>(); var screen = ((GameScreen)graphicsService.Screens["Default"]); _model = contentManager.Load<ModelNode>("square").Clone(); screen.Scene.Children.Add(_model); _model.PoseWorld = new Pose(_position); ChangeColor(); base.OnLoad(); }
public TechniqueBindingSample(Microsoft.Xna.Framework.Game game) : base(game) { SampleFramework.IsMouseVisible = false; _graphicsScreen = new DeferredGraphicsScreen(Services); _graphicsScreen.DrawReticle = true; GraphicsService.Screens.Insert(0, _graphicsScreen); Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer); Services.Register(typeof(IScene), null, _graphicsScreen.Scene); // Add gravity and damping to the physics Simulation. Simulation.ForceEffects.Add(new Gravity()); Simulation.ForceEffects.Add(new Damping()); // Add a custom game object which controls the camera. var cameraGameObject = new CameraObject(Services); GameObjectService.Objects.Add(cameraGameObject); _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode; // More standard objects. GameObjectService.Objects.Add(new GrabObject(Services)); GameObjectService.Objects.Add(new ObjectCreatorObject(Services)); GameObjectService.Objects.Add(new StaticSkyObject(Services)); GameObjectService.Objects.Add(new GroundObject(Services)); // Tell the graphics service how to treat effect techniques which use // the "RepeatParameter" annotation. _repeatTechniqueInterpreter = new RepeatTechniqueInterpreter(); GraphicsService.EffectInterpreters.Insert(0, _repeatTechniqueInterpreter); _repeatTechniqueBinder = new RepeatTechniqueBinder(); GraphicsService.EffectBinders.Insert(0, _repeatTechniqueBinder); // Load model. _modelNode = ContentManager.Load<ModelNode>("Fur2/FurBall").Clone(); _rigidBody = new RigidBody(new SphereShape(0.5f)); // Set a random pose. _rigidBody.Pose = new Pose(new Vector3F(0, 1, 0), RandomHelper.Random.NextQuaternionF()); _modelNode.PoseWorld = _rigidBody.Pose; // Add rigid body to physics simulation and model to scene. Simulation.RigidBodies.Add(_rigidBody); _graphicsScreen.Scene.Children.Add(_modelNode); }
public ObjectMotionBlurSample(Microsoft.Xna.Framework.Game game) : base(game) { _objectMotionBlur = new ObjectMotionBlur(GraphicsService) { NumberOfSamples = 11, SoftenEdges = true, }; GraphicsScreen.PostProcessors.Add(_objectMotionBlur); // ----- 2 cubes that will be animated in this class. var cube = ContentManager.Load<ModelNode>("MetalGrateBox/MetalGrateBox"); _movingCube = cube.Clone(); GraphicsScreen.Scene.Children.Add(_movingCube); _rotatingCube = cube.Clone(); GraphicsScreen.Scene.Children.Add(_rotatingCube); }
public DebugRendererSample(Microsoft.Xna.Framework.Game game) : base(game) { SampleFramework.IsMouseVisible = false; var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService) { RenderCallback = Render, }; GraphicsService.Screens.Insert(0, delegateGraphicsScreen); // Add a custom game object which controls the camera. _cameraObject = new CameraObject(Services); GameObjectService.Objects.Add(_cameraObject); // Load a sprite font. var spriteFont = UIContentManager.Load<SpriteFont>("UI Themes/BlendBlue/Default"); // Create a new debug renderer. _debugRenderer = new DebugRenderer(GraphicsService, spriteFont) { DefaultColor = Color.White, }; // A normal XNA model. _xnaModel = ContentManager.Load<Model>("Saucer3/saucer"); // A DigitalRune model. _modelNode = ContentManager.Load<ModelNode>("Dude/Dude").Clone(); _modelNode.PoseLocal = new Pose(new Vector3F(6, 0, -7)); // Create a geometric object with a height field shape. var numberOfSamplesX = 20; var numberOfSamplesZ = 20; var samples = new float[numberOfSamplesX * numberOfSamplesZ]; for (int z = 0; z < numberOfSamplesZ; z++) for (int x = 0; x < numberOfSamplesX; x++) samples[z * numberOfSamplesX + x] = 1.0f + (float)(Math.Cos(z / 2f) * Math.Sin(x / 2f) * 1.0f); HeightField heightField = new HeightField(0, 0, 120, 120, samples, numberOfSamplesX, numberOfSamplesZ); _geometricObject = new GeometricObject(heightField, new Pose(new Vector3F(5, 0, -5))) { Scale = new Vector3F(0.01f, 0.05f, 0.02f), }; }
public override void LoadContent() { _model = _graphicsService.Content.Load<ModelNode>("testmodel").Clone(); // Let's loop through the mesh nodes of the model: foreach (var meshNode in _model.GetSubtree().OfType<MeshNode>()) { // Each MeshNode references a Mesh. Mesh mesh = meshNode.Mesh; // The mesh consists of several submeshes and several materials - usually // one material per submesh, but several submeshes could reference the same // materials. // Let's loop through the materials of this mesh. foreach (var material in mesh.Materials) { // A material is a collection of EffectBindings - one EffectBinding for each // render pass. For example, a complex game uses several render passes, like // a pre-Z pass, a G-buffer pass, a shadow map pass, a deferred material pass, // etc.In simple games there is only one pass which is called "Default". var effectBinding = material["Default"]; // An EffectBinding references an Effect (the XNA Effect class) and it has // "parameter bindings" and "technique bindings". These bindings select the // values for the shader parameters when the mesh node is rendered. // Let's change the binding for the DiffuseColor of the shader to give tank // a red color. //effectBinding.Set("DiffuseColor", new Vector4(1, 0.7f, 0.7f, 1)); // The tank uses the default effect binding which is a BasicEffectBinding - this // effect binding uses the XNA BasicEffect. // In this sample we do not define any lights, therefore we disable the lighting // in the shader. ((BasicEffectBinding)effectBinding).LightingEnabled = false; } } base.LoadContent(); }
public ConvexDecompositionSample(Microsoft.Xna.Framework.Game game) : base(game) { SampleFramework.IsMouseVisible = false; GraphicsScreen.ClearBackground = true; GraphicsScreen.BackgroundColor = Color.CornflowerBlue; SetCamera(new Vector3F(3, 3, 3), 0.8f, -0.6f); // Load model. _modelNode = ContentManager.Load<ModelNode>("Saucer/Saucer").Clone(); // Combine all meshes of the model into a single TriangleMesh. TriangleMesh mesh = new TriangleMesh(); foreach (var meshNode in _modelNode.GetChildren().OfType<MeshNode>()) { var childMesh = MeshHelper.ToTriangleMesh(meshNode.Mesh); childMesh.Transform(meshNode.PoseWorld * Matrix44F.CreateScale(meshNode.ScaleWorld)); mesh.Add(childMesh); } // Start convex decomposition on another thread. _convexDecomposition = new ConvexDecomposition(); _convexDecomposition.ProgressChanged += OnProgressChanged; _convexDecomposition.AllowedConcavity = 0.8f; _convexDecomposition.IntermediateVertexLimit = 65536; _convexDecomposition.VertexLimit = 64; // 0 gives optimal results but is the slowest. Small positive values improve // speed but the result might be less optimal. _convexDecomposition.SmallIslandBoost = 0.02f; _convexDecomposition.SampleTriangleCenters = true; _convexDecomposition.SampleTriangleVertices = true; // Experimental multithreading. Enable at own risk ;-) _convexDecomposition.EnableMultithreading = true; _convexDecomposition.DecomposeAsync(mesh); }
// OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { var contentManager = _services.GetInstance<ContentManager>(); _modelNode = contentManager.Load<ModelNode>(_assetName).Clone(); _modelNode.PoseWorld = _defaultPose; SampleHelper.EnablePerPixelLighting(_modelNode); var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); // Create looping animation. var meshNode = (MeshNode)_modelNode.Children[0]; // The dude model has a single mesh node as its child. var animations = meshNode.Mesh.Animations; var animationClip = new AnimationClip<SkeletonPose>(animations.Values.First()) { LoopBehavior = LoopBehavior.Cycle, // Repeat animation... Duration = TimeSpan.MaxValue, // ...forever. }; // Start animation. var animationService = _services.GetInstance<IAnimationService>(); AnimationController = animationService.StartAnimation(animationClip, (IAnimatableProperty)meshNode.SkeletonPose); AnimationController.UpdateAndApply(); }
public ContentPipelineMeshSample(Microsoft.Xna.Framework.Game game) : base(game) { // Add basic force effects. Simulation.ForceEffects.Add(new Gravity()); Simulation.ForceEffects.Add(new Damping()); // Add a ground plane. RigidBody groundPlane = new RigidBody(new PlaneShape(Vector3F.UnitY, 0)) { Name = "GroundPlane", // Names are not required but helpful for debugging. MotionType = MotionType.Static, }; Simulation.RigidBodies.Add(groundPlane); // ----- Load triangle mesh model. var sharedModelNode = ContentManager.Load<ModelNode>("Saucer/saucer"); // Let's create a clone because we do not want to change the shared Saucer // instance stored in the content manager. _modelNode = sharedModelNode.Clone(); _modelNode.PoseWorld = new Pose(new Vector3F(0, 2, -5), Matrix33F.CreateRotationY(MathHelper.ToRadians(-30))); _modelNode.ScaleLocal = new Vector3F(8); // The UserData contains the collision shape of type TriangleMeshShape. TriangleMeshShape triangleMesh = (TriangleMeshShape)_modelNode.UserData; // Add model node to graphics scene. GraphicsScreen.Scene.Children.Add(_modelNode); // Create rigid body. // We explicitly specify a mass frame. We can use any mass frame for static bodies (because // static bodies are effectively treated as if they have infinite mass). If we do not specify // a mass frame in the rigid body constructor, the constructor will automatically compute an // approximate mass frame (which can take some time for large meshes). _rigidBody = new RigidBody(triangleMesh, new MassFrame(), null) { MotionType = MotionType.Static, Pose = _modelNode.PoseWorld, Scale = _modelNode.ScaleWorld, // The PhysicsSample class should not draw the height field. UserData = "NoDraw", }; Simulation.RigidBodies.Add(_rigidBody); // Distribute a few spheres and boxes across the triangle mesh. SphereShape sphereShape = new SphereShape(0.5f); for (int i = 0; i < 40; i++) { Vector3F position = RandomHelper.Random.NextVector3F(-15, 10); position.Y = RandomHelper.Random.NextFloat(20, 40); RigidBody body = new RigidBody(sphereShape) { Pose = new Pose(position) }; Simulation.RigidBodies.Add(body); } BoxShape boxShape = new BoxShape(1, 1, 1); for (int i = 0; i < 40; i++) { Vector3F position = RandomHelper.Random.NextVector3F(-15, 10); position.Y = RandomHelper.Random.NextFloat(20, 40); RigidBody body = new RigidBody(boxShape) { Pose = new Pose(position) }; Simulation.RigidBodies.Add(body); } }
public SceneSample(Microsoft.Xna.Framework.Game game) : base(game) { SampleFramework.IsMouseVisible = false; var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService) { RenderCallback = Render, }; GraphicsService.Screens.Insert(0, delegateGraphicsScreen); // Add a custom game object which controls the camera. _cameraObject = new CameraObject(Services); GameObjectService.Objects.Add(_cameraObject); // Create a new empty scene. _scene = new Scene(); // Add the camera node to the scene. _scene.Children.Add(_cameraObject.CameraNode); // Load a model. This model uses the DigitalRune Model Processor. Several XML // files (*.drmdl and *.drmat) in the folder of dude.fbx define the materials and other properties. // The DigitalRune Model Processor also imports the animations of the dude model. var model = ContentManager.Load<ModelNode>("Dude/Dude"); // Add two clones of the model to the scene. _model0 = model.Clone(); _model1 = model.Clone(); _scene.Children.Add(_model0); _scene.Children.Add(_model1); // The dude model contains a single mesh node. var meshNode0 = (MeshNode)_model0.Children[0]; var meshNode1 = (MeshNode)_model1.Children[0]; // The imported animation data (skeleton and animations) is stored with the mesh. var animations = meshNode0.Mesh.Animations; // The MeshNodes of skinned models has a SkeletonPose which can be animated. // Let's start the first animation. var timeline0 = new TimelineClip(animations.Values.First()) { LoopBehavior = LoopBehavior.Cycle, // Loop animation... Duration = TimeSpan.MaxValue, // ...forever. }; _animationController0 = AnimationService.StartAnimation(timeline0, (IAnimatableProperty)meshNode0.SkeletonPose); _animationController0.UpdateAndApply(); var timeline1 = new TimelineClip(animations.Values.First()) { LoopBehavior = LoopBehavior.Cycle, Duration = TimeSpan.MaxValue, // Start second animation at a different animation time to add some variety. Delay = TimeSpan.FromSeconds(-1), }; _animationController1 = AnimationService.StartAnimation(timeline1, (IAnimatableProperty)meshNode1.SkeletonPose); _animationController1.UpdateAndApply(); // Add some lights to the scene which have the same properties as the lights // of BasicEffect.EnableDefaultLighting(). InitializeDefaultXnaLights(_scene); _meshRenderer = new MeshRenderer(); var spriteFont = UIContentManager.Load<SpriteFont>("UI Themes/BlendBlue/Default"); _debugRenderer = new DebugRenderer(GraphicsService, spriteFont); }
//-------------------------------------------------------------- #region Creation & Cleanup //-------------------------------------------------------------- public VehicleObject(IServiceLocator services) { _services = services; Name = "Vehicle"; _inputService = _services.GetInstance<IInputService>(); _simulation = _services.GetInstance<Simulation>(); // Load models for rendering. var contentManager = _services.GetInstance<ContentManager>(); _vehicleModelNode = contentManager.Load<ModelNode>("Car/Car").Clone(); _wheelModelNodes = new ModelNode[4]; _wheelModelNodes[0] = contentManager.Load<ModelNode>("Car/Wheel").Clone(); _wheelModelNodes[1] = _wheelModelNodes[0].Clone(); _wheelModelNodes[2] = _wheelModelNodes[0].Clone(); _wheelModelNodes[3] = _wheelModelNodes[0].Clone(); // Add wheels under the car model node. _vehicleModelNode.Children.Add(_wheelModelNodes[0]); _vehicleModelNode.Children.Add(_wheelModelNodes[1]); _vehicleModelNode.Children.Add(_wheelModelNodes[2]); _vehicleModelNode.Children.Add(_wheelModelNodes[3]); // ----- Create the chassis of the car. // The Vehicle needs a rigid body that represents the chassis. This can be any shape (e.g. // a simple BoxShape). In this example we will build a convex polyhedron from the car model. // 1. Extract the vertices from the car model. // The car model has ~10,000 vertices. It consists of a MeshNode for the glass // parts and a MeshNode "Car" for the chassis. var meshNode = _vehicleModelNode.GetDescendants() .OfType<MeshNode>() .First(mn => mn.Name == "Car"); var mesh = MeshHelper.ToTriangleMesh(meshNode.Mesh); // Apply the transformation of the mesh node. mesh.Transform(meshNode.PoseWorld * Matrix44F.CreateScale(meshNode.ScaleWorld)); // 2. (Optional) Create simplified convex hull from mesh. // We could also skip this step and directly create a convex polyhedron from the mesh using // var chassisShape = new ConvexPolyhedron(mesh.Vertices); // However, the convex polyhedron would still have 500-600 vertices. // We can reduce the number of vertices by using the GeometryHelper. // Create a convex hull for mesh with max. 64 vertices. Additional, shrink the hull by 4 cm. var convexHull = GeometryHelper.CreateConvexHull(mesh.Vertices, 64, -0.04f); // 3. Create convex polyhedron shape using the vertices of the convex hull. var chassisShape = new ConvexPolyhedron(convexHull.Vertices.Select(v => v.Position)); // (Note: Building convex hulls and convex polyhedra are time-consuming. To save loading time // we should build the shape in the XNA content pipeline. See other DigitalRune Physics // Samples.) // The mass properties of the car. We use a mass of 800 kg. var mass = MassFrame.FromShapeAndMass(chassisShape, Vector3F.One, 800, 0.1f, 1); // Trick: We artificially modify the center of mass of the rigid body. Lowering the center // of mass makes the car more stable against rolling in tight curves. // We could also modify mass.Inertia for other effects. var pose = mass.Pose; pose.Position.Y -= 0.5f; // Lower the center of mass. pose.Position.Z = -0.5f; // The center should be below the driver. // (Note: The car model is not exactly centered.) mass.Pose = pose; // Material for the chassis. var material = new UniformMaterial { Restitution = 0.1f, StaticFriction = 0.2f, DynamicFriction = 0.2f }; var chassis = new RigidBody(chassisShape, mass, material) { Pose = new Pose(new Vector3F(0, 2, 0)), // Start position UserData = "NoDraw", // (Remove this line to render the collision model.) }; // ----- Create the vehicle. Vehicle = new Vehicle(_simulation, chassis); // Add 4 wheels. Vehicle.Wheels.Add(new Wheel { Offset = new Vector3F(-0.9f, 0.6f, -2.0f), Radius = 0.36f, SuspensionRestLength = 0.55f, MinSuspensionLength = 0.25f, Friction = 2 }); // Front left Vehicle.Wheels.Add(new Wheel { Offset = new Vector3F(0.9f, 0.6f, -2.0f), Radius = 0.36f, SuspensionRestLength = 0.55f, MinSuspensionLength = 0.25f, Friction = 2 }); // Front right Vehicle.Wheels.Add(new Wheel { Offset = new Vector3F(-0.9f, 0.6f, 0.98f), Radius = 0.36f, SuspensionRestLength = 0.55f, MinSuspensionLength = 0.25f, Friction = 1.8f });// Back left Vehicle.Wheels.Add(new Wheel { Offset = new Vector3F(0.9f, 0.6f, 0.98f), Radius = 0.36f, SuspensionRestLength = 0.55f, MinSuspensionLength = 0.25f, Friction = 1.8f }); // Back right // Vehicles are disabled per default. This way we can create the vehicle and the simulation // objects are only added when needed. Vehicle.Enabled = false; }
private void InitializeGraphicsScreen() { Debug.Assert(GraphicsScreens.Count == 0, "Reset graphics screens before calling InitializeGraphicsScreen()."); var services = Document.Editor.Services; var graphicsService = services.GetInstance<IGraphicsService>().ThrowIfMissing(); // Initialize graphics screens. var graphicsScreen = UseDeferredLighting ? (GraphicsScreen)new DeferredGraphicsScreen(services) : new BasicGraphicsScreen(services); GraphicsScreens.Add(graphicsScreen); GraphicsScreens.Add(new DebugGraphicsScreen(services)); // Add default lighting. var scene = UseDeferredLighting ? ((DeferredGraphicsScreen)graphicsScreen).Scene : ((BasicGraphicsScreen)graphicsScreen).Scene; GameHelper.AddLights(scene); // Add a ground plane (useful for orientation and to check model shadows). if (_groundModelNode == null) { var content = services.GetInstance<ContentManager>().ThrowIfMissing(); _groundModelNode = content.Load<ModelNode>("DigitalRune.Editor.Game/Models/Misc/GroundPlane/GroundPlane").Clone(); } _groundModelNode.IsEnabled = ShowGroundPlane; scene.Children.Add(_groundModelNode); // Add camera. if (CameraNode == null) { var projection = new PerspectiveProjection(); projection.SetFieldOfView( ConstantsF.PiOver4, graphicsService.GraphicsDevice.Viewport.AspectRatio, 0.1f, 10000.0f); CameraNode = new CameraNode(new Camera(projection)) { Name = "CameraPerspective", }; } if (UseDeferredLighting) ((DeferredGraphicsScreen)graphicsScreen).ActiveCameraNode = CameraNode; else ((BasicGraphicsScreen)graphicsScreen).CameraNode = CameraNode; }
// OnUnload() is called when the GameObject is removed from the IGameObjectService. protected override void OnUnload() { // Remove the model from the scene. _modelNode.Parent.Children.Remove(_modelNode); _modelNode.Dispose(false); _modelNode = null; // Remove rigid bodies from simulation. var simulation = _floorRigidBody.Simulation; simulation.RigidBodies.Remove(_floorRigidBody); simulation.RigidBodies.Remove(_leftWallRigidBody); simulation.RigidBodies.Remove(_rightWallRigidBody); simulation.RigidBodies.Remove(_backWallRigidBody); simulation.RigidBodies.Remove(_frontWallRigidBody); _floorRigidBody = null; _leftWallRigidBody = null; _rightWallRigidBody = null; _backWallRigidBody = null; _frontWallRigidBody = null; }
// OnLoad() is called when the GameObject is added to the IGameObjectService. protected override void OnLoad() { // Load sandbox model. var contentManager = _services.GetInstance<ContentManager>(); _modelNode = contentManager.Load<ModelNode>("Sandbox/Sandbox").Clone(); foreach (var node in _modelNode.GetSubtree()) { // Disable the CastsShadows flag. The inside of the box should be fully lit. node.CastsShadows = false; // If models will never move, set the IsStatic flag. This gives the engine // more room for optimizations. Additionally, some effects, like certain // decals, may only affect static geometry. node.IsStatic = true; } // Add the "Sandbox" model to the scene. var scene = _services.GetInstance<IScene>(); scene.Children.Add(_modelNode); // Create rigid bodies for the sides of the sandbox. _floorRigidBody = new RigidBody(new PlaneShape(new Vector3F(0, 1, 0), 0)) { Name = "Floor", MotionType = MotionType.Static, }; _floorRigidBody.CollisionObject.CollisionGroup = 1; _leftWallRigidBody = new RigidBody(new PlaneShape(new Vector3F(1, 0, 0), -10)) { Name = "WallLeft", MotionType = MotionType.Static, }; _leftWallRigidBody.CollisionObject.CollisionGroup = 1; _rightWallRigidBody = new RigidBody(new PlaneShape(new Vector3F(-1, 0, 0), -10)) { Name = "WallRight", MotionType = MotionType.Static, }; _rightWallRigidBody.CollisionObject.CollisionGroup = 1; _backWallRigidBody = new RigidBody(new PlaneShape(new Vector3F(0, 0, 1), -10)) { Name = "WallBack", MotionType = MotionType.Static, }; _backWallRigidBody.CollisionObject.CollisionGroup = 1; _frontWallRigidBody = new RigidBody(new PlaneShape(new Vector3F(0, 0, -1), -10)) { Name = "WallFront", MotionType = MotionType.Static, }; _frontWallRigidBody.CollisionObject.CollisionGroup = 1; // Add rigid bodies to simulation. var simulation = _services.GetInstance<Simulation>(); simulation.RigidBodies.Add(_floorRigidBody); simulation.RigidBodies.Add(_leftWallRigidBody); simulation.RigidBodies.Add(_rightWallRigidBody); simulation.RigidBodies.Add(_backWallRigidBody); simulation.RigidBodies.Add(_frontWallRigidBody); }
// OnUnload() is called when the GameObject is removed from the IGameObjectService. protected override void OnUnload() { // Remove models from scene. foreach (var model in _models) { model.Parent.Children.Remove(_modelPrototype); model.Dispose(false); } // Remove rigid bodies from physics simulation. foreach (var body in _bodies) body.Simulation.RigidBodies.Remove(body); _models.Clear(); _bodies.Clear(); // Remove prototype. _modelPrototype.Dispose(false); _modelPrototype = null; _bodyPrototype = null; // Stop animation. var animationService = _services.GetInstance<IAnimationService>(); animationService.StopAnimation(_glowIntensity); _glowIntensity = null; }
private void StartDudeAnimation(ModelNode dude) { // The dude model contains a single mesh node. var meshNode = (MeshNode)dude.Children[0]; // The imported animation data (skeleton and animations) is stored with the mesh. var animations = meshNode.Mesh.Animations; // The MeshNodes of skinned models has a SkeletonPose which can be animated. // Let's start the first animation. var timeline0 = new TimelineClip(animations.Values.First()) { LoopBehavior = LoopBehavior.Cycle, // Loop animation... Duration = TimeSpan.MaxValue, // ...forever. }; _animationController = AnimationService.StartAnimation(timeline0, (IAnimatableProperty)meshNode.SkeletonPose); _animationController.UpdateAndApply(); }