private void importAssetMenuItem_Click(object sender, EventArgs e)
        {
            // Show Import Dialog
            ImportDialog dialog = new ImportDialog();

            dialog.Icon = Icon;
            dialog.ShowDialog();
            if (dialog.Cancelled)
            {
                return;
            }

            // Create new asset element with given name
            AssetElement ae = new AssetElement();

            ae.FromXml(dialog.Asset.ToXml());

            // Add asset to selected model
            TreeNode       modelNode = mainTreeView.SelectedNode;
            ModelComponent model     = ((ModelForm)mainTreeView.SelectedNode.Tag).Model;

            model.Assets.Add(ae);

            // Refresh to add node
            UpdateModelNode(model, modelNode.Parent);
        }
Beispiel #2
0
        public void DrawModel(GameTime gameTime)
        {
            CameraComponent camComp = ComponentManager.Instance.GetEntityComponent <CameraComponent>(ComponentManager.Instance.GetEntityWithTag("camera", SceneManager.Instance.GetActiveSceneEntities()));

            foreach (Entity ent in ComponentManager.Instance.GetAllEntitiesWithCertainComp <ModelComponent>())
            {
                ModelComponent     modComp           = ComponentManager.Instance.GetEntityComponent <ModelComponent>(ent);
                TransformComponent transComp         = ComponentManager.Instance.GetEntityComponent <TransformComponent>(ent);
                Matrix[]           chopperTransforms = new Matrix[modComp.Model.Bones.Count];
                modComp.Model.CopyAbsoluteBoneTransformsTo(chopperTransforms);
                float radius = GetMaxMeshRadius(modComp);
                foreach (ModelMesh mesh in modComp.Model.Meshes)
                {
                    foreach (BasicEffect e in mesh.Effects)
                    {
                        e.World = GetParentTransform(modComp, mesh.ParentBone) * transComp.CalcMatrix;

                        e.View       = camComp.View;
                        e.Projection = camComp.Proj;

                        e.EnableDefaultLighting();
                        e.PreferPerPixelLighting = true;
                        foreach (EffectPass pass in e.CurrentTechnique.Passes)
                        {
                            pass.Apply();
                            mesh.Draw();
                        }
                    }
                }
            }
        }
        private void typeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // First, disable / enable script function based on selection
            ScheduleEvaluatorType current = (ScheduleEvaluatorType)(typeComboBox.SelectedItem);

            if (current != ScheduleEvaluatorType.scripted)
            {
                evalFunctionTextbox.Enabled = false;
            }
            else
            {
                evalFunctionTextbox.Enabled = true;
            }

            // Then, write changes and register event
            ModelComponent before = (ModelComponent)Model.Clone();

            Model.ScheduleEvaluator.Type = current;
            ModelComponent after = (ModelComponent)Model.Clone();

            if (_mManager != null && before.ToXml() != after.ToXml())
            {
                _mManager.RegisterEvent(before, after, Model, "Change Type");
            }
        }
        private void addAssetMenuItem_Click(object sender, EventArgs e)
        {
            // Get asset name from dialog
            TextboxDialog dialog = new TextboxDialog("Create new asset", "New asset name");

            dialog.ShowDialog();
            if (dialog.Cancelled)
            {
                return;
            }

            // Create new asset element with given name
            AssetElement ae = new AssetElement();

            ae.Name = dialog.StringValue;

            // Add asset to selected model
            TreeNode       modelNode = mainTreeView.SelectedNode;
            ModelComponent model     = ((ModelForm)mainTreeView.SelectedNode.Tag).Model;

            model.Assets.Add(ae);

            // Refresh to add node
            UpdateModelNode(model, modelNode.Parent);
            TreeNode newNode = getNodeFromElement(ae);

            mainTreeView.SelectedNode = newNode;
            PicassoSubform newForm = (PicassoSubform)newNode.Tag;

            newForm.Show();
        }
        private void luaFilesAddButton_Click(object sender, EventArgs e)
        {
            // Check for pre-existing script
            foreach (LuaFileElement script in Model.Lua.Files)
            {
                if (script.Src == luaFilesAddTextbox.Text)
                {
                    MessageBox.Show("That script has already been entered.");
                    luaFilesAddTextbox.Text = "";
                    return;
                }
            }

            // Add script name to list control and handle, and empty box; register event
            ModelComponent before  = (ModelComponent)Model.Clone();
            string         newItem = luaFilesAddTextbox.Text;

            luaFilesListbox.Items.Add(newItem);
            luaFilesAddTextbox.Text = "";
            LuaFileElement newScript = new LuaFileElement();

            newScript.Src = newItem;
            Model.Lua.Files.Add(newScript);
            ModelComponent after = (ModelComponent)Model.Clone();

            _mManager.RegisterEvent(before, after, Model, "Add Script");
        }
        private void isScripted_CheckedChanged(object sender, EventArgs e)
        {
            // First, disable / enable scripting options based on value
            if (isScripted.Checked)
            {
                luaFilesAddButton.Enabled    = true;
                luaFilesAddTextbox.Enabled   = true;
                luaFilesLabel.Enabled        = true;
                luaFilesListbox.Enabled      = true;
                luaFilesRemoveButton.Enabled = true;
            }
            else
            {
                luaFilesAddButton.Enabled    = false;
                luaFilesAddTextbox.Enabled   = false;
                luaFilesLabel.Enabled        = false;
                luaFilesListbox.Enabled      = false;
                luaFilesRemoveButton.Enabled = false;
            }

            // Then, write and register changes
            ModelComponent before = (ModelComponent)Model.Clone();

            Model.Lua.IsScriptingEnabled = isScripted.Checked;
            ModelComponent after = (ModelComponent)Model.Clone();

            _mManager.RegisterEvent(before, after, Model, "Scripted");
        }
Beispiel #7
0
            public SliderModelWrapper(SliderConstraintDesc desc, Pivot pivot, Graphics.GraphicsDevice graphicsDevice)
                : base(pivot, graphicsDevice)
            {
                var sphere = GetSphere(graphicsDevice).ToMeshDraw();
                var pipe   = GetCylinder(graphicsDevice).ToMeshDraw();
                var tip    = GetCone(graphicsDevice).ToMeshDraw();

                lastLowerAngularLimit = -desc.Limit.LowerAngularLimit;
                lastUpperAngularLimit = desc.Limit.UpperAngularLimit;
                var limitLower = GetLimitDisc(graphicsDevice, lastLowerAngularLimit).ToMeshDraw();
                var limitUpper = GetLimitDisc(graphicsDevice, lastUpperAngularLimit).ToMeshDraw();
                var material   = GetMaterial(graphicsDevice, pivot == Pivot.A ? OrangeUniformColor : PurpleUniformColor);
                var material2  = GetMaterial(graphicsDevice, pivot == Pivot.A ? OrangeNegUniformColor : PurpleNegUniformColor);

                limitMaterial = GetMaterial(graphicsDevice, LimitColor);

                AddModelEntity("Center", sphere, material);

                var xRotation = Quaternion.RotationZ(-MathUtil.PiOverTwo); // Yup rotated towards X

                AddModelEntity("X", pipe, material, xRotation);
                AddModelEntity("Xend", tip, material, position: CylinderLength / 2f * Vector3.UnitX, rotation: xRotation);

                var zRotation = Quaternion.RotationX(MathUtil.PiOverTwo); // Yup rotated towards Z

                AddModelEntity("Zend", tip, material2, position: CylinderRadius * 4f *Vector3.UnitZ, rotation: zRotation);

                lowerAngulerLimit = AddModelEntity("LowerAngularLimit", limitLower, limitMaterial, Quaternion.RotationZ(-MathUtil.PiOverTwo) * Quaternion.RotationX(-MathUtil.PiOverTwo)).Get <ModelComponent>();
                upperAngularLimit = AddModelEntity("UpperAngularLimit", limitUpper, limitMaterial, Quaternion.RotationZ(MathUtil.PiOverTwo) * Quaternion.RotationX(MathUtil.PiOverTwo)).Get <ModelComponent>();

                lowerLinearLimit = AddModelEntity("LowerLinearLimit", sphere, limitMaterial);
                upperLinearLimit = AddModelEntity("UpperLinearLimit", sphere, limitMaterial);

                Update(desc);
            }
Beispiel #8
0
            public ConeModelWrapper(ConeTwistConstraintDesc desc, Pivot pivot, Graphics.GraphicsDevice graphicsDevice)
                : base(pivot, graphicsDevice)
            {
                var sphere = GetSphere(graphicsDevice).ToMeshDraw();
                var pipe   = GetCylinder(graphicsDevice).ToMeshDraw();
                var tip    = GetCone(graphicsDevice).ToMeshDraw();

                lastLimitZ = desc.Limit.SetLimit ? desc.Limit.SwingSpanZ : MathF.PI;
                lastLimitY = desc.Limit.SetLimit ? desc.Limit.SwingSpanY : MathF.PI;
                lastLimitT = desc.Limit.SetLimit ? 2 * desc.Limit.TwistSpan : 2 * MathF.PI;
                var limitZ    = GetLimitDisc(graphicsDevice, lastLimitZ).ToMeshDraw();
                var limitY    = GetLimitDisc(graphicsDevice, lastLimitY).ToMeshDraw();
                var limitT    = GetLimitDisc(graphicsDevice, lastLimitT).ToMeshDraw();
                var material  = GetMaterial(graphicsDevice, pivot == Pivot.A ? OrangeUniformColor : PurpleUniformColor);
                var material2 = GetMaterial(graphicsDevice, pivot == Pivot.A ? OrangeNegUniformColor : PurpleNegUniformColor);

                limitMaterial = GetMaterial(graphicsDevice, LimitColor);

                AddModelEntity("Center", sphere, material);

                var xRotation = Quaternion.RotationAxis(Vector3.UnitZ, -MathUtil.PiOverTwo); // Yup rotated towards X

                AddModelEntity("X", pipe, material, xRotation);
                AddModelEntity("Xend", tip, material, position: CylinderLength / 2f * Vector3.UnitX, rotation: xRotation);

                var zRotation = Quaternion.RotationAxis(Vector3.UnitX, MathUtil.PiOverTwo); // Yup rotated towards Z

                AddModelEntity("Zend", tip, material2, position: CylinderRadius * 4f *Vector3.UnitZ, rotation: zRotation);

                this.limitZ = AddModelEntity("LimitZ", limitZ, limitMaterial, Quaternion.RotationY(MathF.PI + (lastLimitZ / 2f)), position: new Vector3(CylinderLength / 2, 0, 0)).Get <ModelComponent>();
                this.limitY = AddModelEntity("LimitY", limitY, limitMaterial, Quaternion.RotationY(MathF.PI + (lastLimitY / 2f)) * Quaternion.RotationX(-MathUtil.PiOverTwo), position: new Vector3(CylinderLength / 2, 0, 0)).Get <ModelComponent>();
                this.limitT = AddModelEntity("LimitT", limitT, limitMaterial, Quaternion.RotationZ(MathUtil.PiOverTwo) * Quaternion.RotationX(MathUtil.PiOverTwo - lastLimitT / 2f)).Get <ModelComponent>();

                Update(desc);
            }
        public unsafe void TestComponentAccess()
        {
            var entity = new Entity();

            entity.AddChild(new Entity("child1")
            {
                new LightComponent()
            });

            var modelComponent = new ModelComponent();

            var compiledUpdate = UpdateEngine.Compile(typeof(Entity), new List <UpdateMemberInfo>
            {
                new UpdateMemberInfo("[ModelComponent.Key]", 0),
                new UpdateMemberInfo("child1[LightComponent.Key].Intensity", 0),
            });

            var testData = new TestData[] { 32.0f };

            fixed(TestData *dataPtr = testData)
            {
                UpdateEngine.Run(entity, compiledUpdate, (IntPtr)dataPtr, new[] { new UpdateObjectData(modelComponent) });
            }

            Assert.That(entity.Get(ModelComponent.Key), Is.EqualTo(modelComponent));
            Assert.That(entity.GetChild(0).Get(LightComponent.Key).Intensity, Is.EqualTo(32.0f));
        }
        public static void Render(BasicEffect be, ModelComponent mc, Matrix world)
        {
            if (!mc.IsActive)
            {
                return;
            }

            Matrix[] transforms = new Matrix[mc.Model.Bones.Count];
            mc.Model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in mc.Model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    //effect.EnableDefaultLighting();
                    effect.View       = be.View;
                    effect.Projection = be.Projection;
                    effect.World      = transforms[mesh.ParentBone.Index] * world;

                    effect.AmbientLightColor = new Vector3(1f, 0, 0);
                    effect.CurrentTechnique.Passes[0].Apply();
                    mesh.Draw();
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// Updates the positions of an entity, including any models and bounding shapes attached.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="translation"></param>
        public static void TransformEntity(Entity entity, Matrix translation, bool threadSafety)
        {
            TransformComponent transformComponent = null;
            ModelComponent     modelComponent     = null;

            if (threadSafety)
            {
                transformComponent = ComponentManager.Instance.ConcurrentGetComponentOfEntity <TransformComponent>(entity);
                modelComponent     = ComponentManager.Instance.ConcurrentGetComponentOfEntity <ModelComponent>(entity);
            }
            else
            {
                transformComponent = ComponentManager.Instance.GetComponentOfEntity <TransformComponent>(entity);
                modelComponent     = ComponentManager.Instance.GetComponentOfEntity <ModelComponent>(entity);
            }

            if (transformComponent != null)
            {
                transformComponent.Position = translation.Translation;

                if (modelComponent != null)
                {
                    modelComponent.World = translation;
                }
                TransformBoundingShapes(entity, translation, threadSafety);
            }
        }
Beispiel #12
0
        public override void Start()
        {
            // VertexPositionNormalTexture is the layout that the engine uses in the shaders
            var vBuffer = Xenko.Graphics.Buffer.Vertex.New(GraphicsDevice, new VertexPositionNormalTexture[]
            {
                new VertexPositionNormalTexture(new Vector3(0.015f, 0.015f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),  //Top Left.
                new VertexPositionNormalTexture(new Vector3(-0.015f, -0.015f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)) //Bottom right.
            });

            MeshDraw meshDraw = new MeshDraw
            {
                PrimitiveType = PrimitiveType.LineStrip, // Tell the GPU that this is a line.
                VertexBuffers = new[] { new VertexBufferBinding(vBuffer, VertexPositionNormalTexture.Layout, vBuffer.ElementCount) },
                DrawCount     = vBuffer.ElementCount
            };

            Mesh mesh = new Mesh();

            mesh.Draw = meshDraw;

            Model model = new Model();

            model.Add(mesh);
            m_DotMesh = new ModelComponent(model);

            m_Dot = new Entity();
            m_Dot.Add(m_DotMesh);
            this.Entity.AddChild(m_Dot);
            Destroy();
        }
Beispiel #13
0
        private void m_RockTwo()
        {
            // VertexPositionNormalTexture is the layout that the engine uses in the shaders
            var vBuffer = Xenko.Graphics.Buffer.Vertex.New(GraphicsDevice, new VertexPositionNormalTexture[]
            {
                new VertexPositionNormalTexture(new Vector3(2.9f, 1.5f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(1.4f, 2.9f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(0.0f, 1.5f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(-1.5f, 2.9f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(-2.9f, 1.5f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(-2.2f, 0.0f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(-2.9f, -1.5f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(-0.7f, -2.9f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(1.4f, -2.9f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(2.9f, -1.4f, 0), new Vector3(0, 1, 1), new Vector2(0, 0)),
                new VertexPositionNormalTexture(new Vector3(2.9f, 1.5f, 0), new Vector3(0, 1, 1), new Vector2(0, 0))
            });

            MeshDraw meshDraw = new MeshDraw
            {
                PrimitiveType = PrimitiveType.LineStrip, // Tell the GPU that this is a line.
                VertexBuffers = new[] { new VertexBufferBinding(vBuffer, VertexPositionNormalTexture.Layout, vBuffer.ElementCount) },
                DrawCount     = vBuffer.ElementCount
            };

            Mesh mesh = new Mesh();

            mesh.Draw = meshDraw;

            Model model = new Model();

            model.Add(mesh);
            m_RockMesh = new ModelComponent(model);
        }
Beispiel #14
0
 public static void SetMeshTransform(ref ModelComponent model, int bone, Matrix t)
 {
     if (model.meshTransforms.ContainsKey(bone))
     {
         model.meshTransforms[bone] = t;
     }
 }
        /// <summary>
        /// Clones a <see cref="ModelComponent"/>s <see cref="Material"/> if required;
        /// </summary>
        /// <param name="modelComponent"></param>
        /// <param name="materialIndex"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">If <paramref name="modelComponent"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="materialIndex"/> is less than 0 or greater than <see cref="ModelComponent.GetMaterialCount"/> and not in <see cref="ModelComponent.Materials"/>.</exception>
        private static Material GetMaterialCopy(this ModelComponent modelComponent, int materialIndex)
        {
            if (modelComponent == null)
            {
                throw new ArgumentNullException(nameof(modelComponent));
            }

            if (!IsValidMaterialIndex(modelComponent, materialIndex))
            {
                throw new ArgumentOutOfRangeException(nameof(materialIndex));
            }

            var material = modelComponent.GetMaterial(materialIndex);

            if (material is ModelComponentMaterialCopy copy && copy.ModelComponent == modelComponent)
            {
                return(material);
            }

            var materialCopy = new ModelComponentMaterialCopy()
            {
                ModelComponent = modelComponent,
            };

            MaterialExtensions.CopyProperties(material, materialCopy);

            modelComponent.Materials[materialIndex] = materialCopy;

            return(materialCopy);
        }
Beispiel #16
0
 public void ChangeBoneTransform(ModelComponent modelComp, int boneIndex, Matrix t)
 {
     lock (modelComp)
     {
         modelComp.model.Bones[boneIndex].Transform = t * modelComp.model.Bones[boneIndex].Transform;
     }
 }
Beispiel #17
0
 public void Update(float dt)
 {
     if (!mAdd)
     {
         TransformComponent tc = mObject.GetComponent <TransformComponent>();
         ModelComponent     mc = mObject.GetComponent <ModelComponent>();
         CPlusPlusInterface.AddMovingBoxCollider(mObject.GetName(),
                                                 tc.mPosition,
                                                 tc.mScale,
                                                 tc.mRotation,
                                                 mc.mModel.Model,
                                                 mPassable,
                                                 mTag);
         mAdd = true;
     }
     else
     {
         TransformComponent tc = mObject.GetComponent <TransformComponent>();
         ModelComponent     mc = mObject.GetComponent <ModelComponent>();
         CPlusPlusInterface.UpdateMovingBoxCollider(mObject.GetName(),
                                                    tc.mPosition,
                                                    tc.mScale,
                                                    tc.mRotation,
                                                    mc.mModel.Model,
                                                    mPassable,
                                                    mTag);
     }
 }
Beispiel #18
0
        private static Vector3 getBounds(Entity e, out Vector3 center)
        {
            ModelComponent mc = e.Get <ModelComponent>();

            center = new Vector3();
            if (mc == null || mc.Model == null || mc.Model.Meshes.Count <= 0f)
            {
                return(Vector3.Zero);
            }

            Vector3 biggest = new Vector3(0.05f, 0.05f, 0.05f);
            int     count   = mc.Model.Meshes.Count;

            for (int i = 0; i < count; i++)
            {
                Xenko.Rendering.Mesh m  = mc.Model.Meshes[i];
                BoundingBox          bb = m.BoundingBox;
                Vector3 extent          = bb.Extent;
                if (extent.X > biggest.X)
                {
                    biggest.X = extent.X;
                }
                if (extent.Y > biggest.Y)
                {
                    biggest.Y = extent.Y;
                }
                if (extent.Z > biggest.Z)
                {
                    biggest.Z = extent.Z;
                }
                center += bb.Center;
            }
            center /= count;
            return(biggest * e.Transform.WorldScale());
        }
        public unsafe void TestComponentAccess()
        {
            var entity = new Entity();

            entity.AddChild(new Entity("child1")
            {
                new LightComponent()
            });

            var modelComponent = new ModelComponent();

            var compiledUpdate = UpdateEngine.Compile(typeof(Entity), new List<UpdateMemberInfo>
            {
                new UpdateMemberInfo("[ModelComponent.Key]", 0),
                new UpdateMemberInfo("child1[LightComponent.Key].Intensity", 0),
            });

            var testData = new TestData[] { 32.0f };

            fixed (TestData* dataPtr = testData)
            {
                UpdateEngine.Run(entity, compiledUpdate, (IntPtr)dataPtr, new[] { new UpdateObjectData(modelComponent) });
            }

            Assert.That(entity.Get(ModelComponent.Key), Is.EqualTo(modelComponent));
            Assert.That(entity.GetChild(0).Get(LightComponent.Key).Intensity, Is.EqualTo(32.0f));
        }
Beispiel #20
0
        public unsafe void TestComponentAccess()
        {
            var entity = new Entity();

            entity.AddChild(new Entity("child1")
            {
                new LightComponent()
            });

            var modelComponent = new ModelComponent();

            var compiledUpdate = UpdateEngine.Compile(typeof(Entity), new List <UpdateMemberInfo>
            {
                new UpdateMemberInfo("[ModelComponent]", 0),
                new UpdateMemberInfo("child1[LightComponent.Key].Intensity", 0), // Keep key just for backward comp, we will remove it
            });

            var testData = new TestData[] { 32.0f };

            fixed(TestData *dataPtr = testData)
            {
                UpdateEngine.Run(entity, compiledUpdate, (IntPtr)dataPtr, new[] { new UpdateObjectData(modelComponent) });
            }

            Assert.Equal(modelComponent, entity.Get <ModelComponent>());
            Assert.Equal(32.0f, entity.GetChild(0).Get <LightComponent>().Intensity);
        }
Beispiel #21
0
        /// <summary>
        /// Loads the specified root <paramref name="entities"/> into the content scene.
        /// </summary>
        /// <param name="entities">A collection of entities to load into the content scene.</param>
        /// <param name="sceneId">The identifier of the scene the given <paramref name="entities"/> belong to.</param>
        /// <remarks>
        /// If <paramref name="sceneId"/> is <see cref="Guid.Empty"/>, the provided <paramref name="entities"/> will be loaded
        /// into the <see cref="EntityHierarchyEditorGame.ContentScene"/>; otherwise, they will be loaded into a separate child scene.
        /// </remarks>
        public void LoadEntities([ItemNotNull, NotNull]  IEnumerable <Entity> entities, Guid sceneId)
        {
            if (entities == null)
            {
                throw new ArgumentNullException(nameof(entities));
            }
            if (sceneId == Guid.Empty)
            {
                throw new InvalidOperationException($"{nameof(sceneId)} cannot be {nameof(Guid.Empty)}.");
            }

            EnsureContentScene();

            var scene = GetScene(sceneId);

            scene.Entities.AddRange(entities);

            foreach (Entity e in entities)
            {
                ModelComponent mc = e.Get <ModelComponent>();
                if (mc != null)
                {
                    mc.ForceModelUpdateCount = int.MaxValue;
                }
            }
        }
Beispiel #22
0
        public void Update()
        {
            float rotation = 0.1f;

            Quaternion q;

            Quaternion quaternion = Quaternion.CreateFromRotationMatrix(Matrix.CreateRotationY(rotation));

            quaternion.Normalize();

            ModelComponent chopper = ComponentManager.GetComponent <ModelComponent>(1);

            foreach (ModelMesh mesh in chopper.model.Meshes)
            {
                if (mesh.ParentBone.Index == 3 || mesh.ParentBone.Index == 1)
                {
                    q = mesh.ParentBone.Transform.Rotation * quaternion;
                    q.Normalize();
                    mesh.ParentBone.Transform = Matrix.CreateFromQuaternion(q)
                                                * Matrix.CreateTranslation(mesh.ParentBone.Transform.Translation);
                }

                if (rotation >= MathHelper.TwoPi)
                {
                    rotation -= MathHelper.TwoPi;
                }
            }
        }
        public static Entity NewBlock(Vector3 positionValues, Texture2D texture, string typeName)
        {
            Entity block = EntityFactory.NewEntity(typeName);

            TransformComponent transformComponent = new TransformComponent(block, new Vector3(x: positionValues.X, y: positionValues.Y, z: positionValues.Z));
            ModelComponent     modelComponent     = new ModelComponent(block, AssetManager.Instance.GetContent <Model>("Models/block2"));

            modelComponent.World = Matrix.CreateWorld(transformComponent.Position, Vector3.Forward, Vector3.Up);
            TextureComponent   textureComponent   = new TextureComponent(block, texture);
            CollisionComponent collisionComponent = new CollisionComponent(block, new BoxVolume(EntityFactory.CreateBoundingBox(modelComponent.Model)));

            LightComponent  lightComponent  = new LightComponent(block, new Vector3(0, 7, -5), Color.White.ToVector4(), 10f, Color.Blue.ToVector4(), 0.2f, Color.White.ToVector4(), 1000f);
            EffectComponent effectComponent = new EffectComponent(block, AssetManager.Instance.GetContent <Effect>("Shading"));

            BlockComponent blockComponent = new BlockComponent(block);

            ComponentManager.Instance.AddComponentToEntity(block, transformComponent);
            ComponentManager.Instance.AddComponentToEntity(block, modelComponent);
            ComponentManager.Instance.AddComponentToEntity(block, textureComponent);
            ComponentManager.Instance.AddComponentToEntity(block, collisionComponent, typeof(CollisionComponent));
            ComponentManager.Instance.AddComponentToEntity(block, blockComponent);
            ComponentManager.Instance.AddComponentToEntity(block, effectComponent);
            ComponentManager.Instance.AddComponentToEntity(block, lightComponent);

            TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            TransformHelper.SetBoundingBoxPos(collisionComponent, transformComponent);
            //EntityFactory.AddBoundingBoxChildren((BoxVolume)collisionComponent);

            return(block);
        }
        public static Entity NewBasePlayer(String model, int gamePadIndex, Vector3 transformPos, Texture2D texture, String typeName)
        {
            Entity             player             = EntityFactory.NewEntity(typeName);
            TransformComponent transformComponent = new TransformComponent(player, transformPos);
            ModelComponent     modelComponent     = new ModelComponent(player, AssetManager.Instance.GetContent <Model>(model));
            VelocityComponent  velocityComponent  = new VelocityComponent(player);
            CollisionComponent collisionComponent = new CollisionComponent(player, new BoxVolume(EntityFactory.CreateBoundingBox(modelComponent.Model)));
            PlayerComponent    playerComponent    = new PlayerComponent(player);
            FrictionComponent  frictionComponent  = new FrictionComponent(player);
            TextureComponent   textureComponent   = new TextureComponent(player, texture);
            GravityComponent   gravityComponent   = new GravityComponent(player);
            EffectComponent    effectComponent    = new EffectComponent(player, AssetManager.Instance.GetContent <Effect>("Shading"));

            ComponentManager.Instance.AddComponentToEntity(player, modelComponent);
            ComponentManager.Instance.AddComponentToEntity(player, transformComponent);
            ComponentManager.Instance.AddComponentToEntity(player, velocityComponent);
            ComponentManager.Instance.AddComponentToEntity(player, collisionComponent, typeof(CollisionComponent));
            ComponentManager.Instance.AddComponentToEntity(player, playerComponent);
            ComponentManager.Instance.AddComponentToEntity(player, frictionComponent);
            ComponentManager.Instance.AddComponentToEntity(player, textureComponent);
            ComponentManager.Instance.AddComponentToEntity(player, gravityComponent);
            ComponentManager.Instance.AddComponentToEntity(player, effectComponent);

            TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            TransformHelper.SetBoundingBoxPos(collisionComponent, transformComponent);

            //TransformHelper.SetInitialModelPos(modelComponent, transformComponent);
            //TransformHelper.SetInitialBoundingSpherePos(collisionComponent, transformComponent);

            return(player);
        }
        public void Update(GameTime gameTime)
        {
            if (_observers.Count != 0)
            {
                List <Entity> entities = ComponentManager.Instance.GetAllEntitiesWithComponentType <Collision3Dcomponent>();

                foreach (var entity1 in entities)
                {
                    foreach (var entity2 in entities)
                    {
                        if (entity1 == entity2)
                        {
                            continue;
                        }

                        ModelComponent model1 = ComponentManager.Instance.GetEntityComponent <ModelComponent>(entity1);
                        ModelComponent model2 = ComponentManager.Instance.GetEntityComponent <ModelComponent>(entity2);

                        var sphere1 = model1.Sphere;
                        var sphere2 = model2.Sphere;

                        if (sphere1.Intersects(sphere2))
                        {
                            Notify(entity1, entity2);
                        }
                    }
                }
            }
        }
Beispiel #26
0
 public static void RemoveMeshTransform(ref ModelComponent model, int bone)
 {
     if (model.meshTransforms.ContainsKey(bone))
     {
         model.meshTransforms.Remove(bone);
     }
 }
Beispiel #27
0
        private bool addUnit()
        {
            // Get the player who owns this building.
            ModelComponent temp = building.Parent;

            while (!(temp is PlayerComponent))
            {
                temp = temp.Parent;
            }
            PlayerComponent player = (PlayerComponent)temp;

            // Get the Gameworld.
            while (!(temp is GameModel))
            {
                temp = temp.Parent;
            }
            GameModel model = (GameModel)temp;

            // Get the CellComponent to insert into.
            CellComponent insertCell = findEmptyNeighborCell(model);

            if (insertCell == null)
            {
                return(false);                // No empty CellComponent.
            }

            // Add Unit to the Map.
            UnitComponent unit = new UnitComponent(stats);

            unit.PointLocation = new PointF(insertCell.X + 0.5f, insertCell.Y + 0.5f);

            // Add Unit to the Player who owns the building.
            player.GetUnitList().AddChild(unit);
            return(true);
        }
Beispiel #28
0
        public EntityLink LinkEntity(Entity linkedEntity, ModelComponent modelComponent, string boneName)
        {
            var modelEntityData = matchingEntities[modelComponent.Entity];
            var nodeIndex       = modelEntityData.ModelComponent.ModelViewHierarchy.Nodes.IndexOf(x => x.Name == boneName);

            var entityLink = new EntityLink {
                Entity = linkedEntity, ModelComponent = modelComponent, NodeIndex = nodeIndex
            };

            if (nodeIndex == -1)
            {
                return(entityLink);
            }

            linkedEntity.Transform.isSpecialRoot = true;
            linkedEntity.Transform.UseTRS        = false;

            if (modelEntityData.Links == null)
            {
                modelEntityData.Links = new List <EntityLink>();
            }

            modelEntityData.Links.Add(entityLink);

            return(entityLink);
        }
Beispiel #29
0
        public override void Start()
        {
            base.Start();
            float size = Main.instance.RandomMinMax(0.003666f, 0.00666f);
            // VertexPositionNormalTexture is the layout that the engine uses in the shaders
            var vBuffer = Stride.Graphics.Buffer.Vertex.New(GraphicsDevice, new VertexPositionNormalTexture[]
            {
                new VertexPositionNormalTexture(new Vector3(0, -size, 0), new Vector3(0, 1, 1), new Vector2(0, 0)), //Top Left.
                new VertexPositionNormalTexture(new Vector3(0, size, 0), new Vector3(0, 1, 1), new Vector2(0, 0))   //Bottom right.
            });

            MeshDraw meshDraw = new MeshDraw
            {
                PrimitiveType = PrimitiveType.LineStrip, // Tell the GPU that this is a line.
                VertexBuffers = new[] { new VertexBufferBinding(vBuffer, VertexPositionNormalTexture.Layout, vBuffer.ElementCount) },
                DrawCount     = vBuffer.ElementCount
            };

            Mesh mesh = new Mesh();

            mesh.Draw = meshDraw;

            Model model = new Model();

            model.Add(mesh);
            lineMesh = new ModelComponent(model);
            line     = new Entity();
            line.Add(lineMesh);
            Entity.AddChild(line);
            Destroy();
        }
Beispiel #30
0
        public void Draw(BasicEffect effect, GameTime gametime)
        {
            List <ulong> models = ComponentManager.GetAllEntitiesWithComp <ModelComponent>();

            foreach (ulong mC in models)
            {
                ModelComponent     m          = ComponentManager.GetComponent <ModelComponent>(mC);
                CameraComponent    camera     = ComponentManager.GetComponent <CameraComponent>(mC);
                TransformComponent transform  = ComponentManager.GetComponent <TransformComponent>(mC);
                Matrix[]           transforms = new Matrix[m.model.Bones.Count];

                Matrix worldMatrix = Matrix.CreateScale(0.05f, 0.05f, 0.05f) *
                                     Matrix.CreateFromQuaternion(transform.qRot) *
                                     Matrix.CreateTranslation(transform.position);


                m.model.CopyAbsoluteBoneTransformsTo(transforms);

                for (int index = 0; index < m.model.Meshes.Count; index++)
                {
                    ModelMesh mesh = m.model.Meshes[index];
                    foreach (BasicEffect be in mesh.Effects)
                    {
                        be.EnableDefaultLighting();
                        be.PreferPerPixelLighting = true;

                        be.World      = mesh.ParentBone.Transform * m.chopperMeshWorldMatrices[index] * worldMatrix;
                        be.View       = camera.viewMatrix;
                        be.Projection = camera.projectionMatrix;
                    }
                    mesh.Draw();
                }
            }
        }
        private void HandleInitNetworkInformation(NetIncomingMessage inc)
        {
            var cm = ComponentManager.Instance;

            var nrOfPlayers = inc.ReadInt32();

            for (var i = 0; i < nrOfPlayers; i++)
            {
                var player = new PlayerComponent();
                inc.ReadAllProperties(player);

                var e = EntityFactory.Instance.NewEntity();

                cm.AddComponentToEntity(e, player);
                cm.AddComponentToEntity(e, new TransformComponent());
                cm.AddComponentToEntity(e, new LapComponent());

                var modelComp = new ModelComponent(_engine.LoadContent <Model>("kart"), true, false, false)
                {
                    staticModel = false
                };

                //ModelRenderSystem.AddMeshTransform(ref modelComp, 1, Matrix.CreateRotationY(0.2f));
                //ModelRenderSystem.AddMeshTransform(ref modelComp, 3, Matrix.CreateRotationY(0.5f));
                cm.AddComponentToEntity(e, modelComp);

                SceneManager.Instance.AddEntityToSceneOnLayer("Game", 3, e);
            }
        }
 /// <summary>
 /// Select an entity to allow for the giving of commands.
 /// </summary>
 /// <param name="component">The Entity to select</param>
 public void SelectEntity(ModelComponent component)
 {
     if (component is UnitComponent || component is Building)
     {
         selectedEntities.Add(component);
         component.Selected = true;
         if (SelectionStateChanged != null)
         {
             SelectionStateChangedArgs e = new SelectionStateChangedArgs();
             e.SelectedEntities = selectedEntities;
             SelectionStateChanged(this, e);
         }
     }
 }
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            //instantiate the components and add them to this.Components
            Vector3 cameraPosition = new Vector3(0, -3, 15);
            Vector3 targetPosition = new Vector3(0, -3, 0);
            Vector3 upVector = Vector3.UnitY;
            string backgroundImage = "background-chain";
            cameraComponent = new CameraComponent(this, cameraPosition, targetPosition, upVector, backgroundImage);
            this.Components.Add(cameraComponent);

            bool showMouse = true;
            inputComponent = new InputComponent(this, showMouse);
            this.Components.Add(inputComponent);

            modelComponent = new ModelComponent(this);
            this.Components.Add(modelComponent);
        }
 public UnitAttackedEnemyArgs(ModelComponent target)
 {
     this.target = target;
 }