当前位置: 首页>>代码示例>>C#>>正文


C# Entity.GetOrCreate方法代码示例

本文整理汇总了C#中System.Entity.GetOrCreate方法的典型用法代码示例。如果您正苦于以下问题:C# Entity.GetOrCreate方法的具体用法?C# Entity.GetOrCreate怎么用?C# Entity.GetOrCreate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Entity的用法示例。


在下文中一共展示了Entity.GetOrCreate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: LoadContent

        protected override async Task LoadContent()
        {
            await base.LoadContent();

            var knightModel = Asset.Load<Model>("knight Model");
            knight = new Entity { new ModelComponent { Model = knightModel } };
            knight.Transform.Position = new Vector3(0, 0f, 0f);
            var animationComponent = knight.GetOrCreate<AnimationComponent>();
            animationComponent.Animations.Add("Run", Asset.Load<AnimationClip>("knight Run"));
            animationComponent.Animations.Add("Idle", Asset.Load<AnimationClip>("knight Idle"));

            // We will test both non-optimized and optimized clips
            megalodonClip = CreateModelChangeAnimation(new ProceduralModelDescriptor(new CubeProceduralModel { Size = Vector3.One, MaterialInstance = { Material = knightModel.Materials[0].Material } }).GenerateModel(Services));
            knightOptimizedClip = CreateModelChangeAnimation(Asset.Load<Model>("knight Model"));
            knightOptimizedClip.Optimize();

            animationComponent.Animations.Add("ChangeModel1", megalodonClip);
            animationComponent.Animations.Add("ChangeModel2", knightOptimizedClip);

            Scene.Entities.Add(knight);

            camera = new TestCamera();
            CameraComponent = camera.Camera;
            Script.Add(camera);

            LightingKeys.EnableFixedAmbientLight(GraphicsDevice.Parameters, true);
            GraphicsDevice.Parameters.Set(EnvironmentLightKeys.GetParameterKey(LightSimpleAmbientKeys.AmbientLight, 0), (Color3)Color.White);

            camera.Position = new Vector3(6.0f, 2.5f, 1.5f);
            camera.SetTarget(knight, true);
        }
开发者ID:h78hy78yhoi8j,项目名称:xenko,代码行数:31,代码来源:AnimatedModelTests.cs

示例2: LoadContent

        protected override async Task LoadContent()
        {
            await base.LoadContent();

            var knightModel = Content.Load<Model>("knight Model");
            knight = new Entity { new ModelComponent { Model = knightModel } };
            knight.Transform.Position = new Vector3(0, 0f, 0f);
            var animationComponent = knight.GetOrCreate<AnimationComponent>();
            animationComponent.Animations.Add("Run", Content.Load<AnimationClip>("knight Run"));
            animationComponent.Animations.Add("Idle", Content.Load<AnimationClip>("knight Idle"));

            // We will test both non-optimized and optimized clips
            megalodonClip = CreateModelChangeAnimation(new ProceduralModelDescriptor(new CubeProceduralModel { Size = Vector3.One, MaterialInstance = { Material = knightModel.Materials[0].Material } }).GenerateModel(Services));
            knightOptimizedClip = CreateModelChangeAnimation(Content.Load<Model>("knight Model"));
            knightOptimizedClip.Optimize();

            animationComponent.Animations.Add("ChangeModel1", megalodonClip);
            animationComponent.Animations.Add("ChangeModel2", knightOptimizedClip);

            Scene.Entities.Add(knight);

            camera = new TestCamera();
            CameraComponent = camera.Camera;
            Script.Add(camera);

            camera.Position = new Vector3(6.0f, 2.5f, 1.5f);
            camera.SetTarget(knight, true);
        }
开发者ID:cg123,项目名称:xenko,代码行数:28,代码来源:AnimatedModelTests.cs

示例3: Bind

        public override void Bind(Entity result, Main main, bool creating = false)
        {
            Transform transform = result.GetOrCreate<Transform>("Transform");
            PhysicsBlock physics = result.GetOrCreate<PhysicsBlock>();
            physics.Size.Value = Vector3.One;
            physics.Editable = false;
            ModelInstance model = result.GetOrCreate<ModelInstance>();
            model.Editable = false;

            physics.Add(new TwoWayBinding<Matrix>(transform.Matrix, physics.Transform));

            Property<string> soundCue = result.GetOrMakeProperty<string>("CollisionSoundCue", false);
            soundCue.Serialize = false;

            model.Add(new Binding<Matrix>(model.Transform, transform.Matrix));

            const float volumeMultiplier = 0.1f;

            physics.Add(new CommandBinding<Collidable, ContactCollection>(physics.Collided, delegate(Collidable collidable, ContactCollection contacts)
            {
                float volume = contacts[contacts.Count - 1].NormalImpulse * volumeMultiplier;
                if (volume > 0.1f && soundCue.Value != null)
                {
                    Sound sound = Sound.PlayCue(main, soundCue, transform.Position, volume, 0.05f);
                    if (sound != null)
                        sound.GetProperty("Pitch").Value = 1.0f;
                }
            }));

            this.SetMain(result, main);

            Property<bool> valid = result.GetOrMakeProperty<bool>("Valid", false);
            valid.Serialize = false;

            Property<string> type = result.GetOrMakeProperty<string>("Type", true);
            type.Set = delegate(string value)
            {
                Map.CellState state;
                if (WorldFactory.StatesByName.TryGetValue(value, out state))
                {
                    state.ApplyToBlock(result);
                    valid.Value = true;
                }

                type.InternalValue = value;
            };
        }
开发者ID:kernelbitch,项目名称:Lemma,代码行数:47,代码来源:SceneryBlockFactory.cs

示例4: Bind

		public override void Bind(Entity entity, Main main, bool creating = false)
		{
			Transform mapTransform = entity.GetOrCreate<Transform>("MapTransform");
			mapTransform.Selectable.Value = false;
			Transform transform = entity.GetOrCreate<Transform>("Transform");
			VoxelFill voxelFill = entity.GetOrCreate<VoxelFill>("VoxelFill");
			voxelFill.Add(new CommandBinding(voxelFill.Delete, entity.Delete));

			Sound.AttachTracker(entity, voxelFill.RumblePosition);

			this.InternalBind(entity, main, creating, mapTransform, true);

			if (main.EditorEnabled)
			{
				Voxel voxel = entity.Get<Voxel>();

				Action refreshMapTransform = delegate()
				{
					Entity parent = voxelFill.Target.Value.Target;
					if (parent != null && parent.Active)
					{
						Voxel staticMap = parent.Get<Voxel>();
						if (staticMap == null)
							mapTransform.Matrix.Value = transform.Matrix;
						else
						{
							mapTransform.Position.Value = staticMap.GetAbsolutePosition(staticMap.GetRelativePosition(staticMap.GetCoordinate(transform.Matrix.Value.Translation)) - new Vector3(0.5f) + staticMap.Offset + voxel.Offset.Value);
							Matrix parentOrientation = staticMap.Transform;
							parentOrientation.Translation = Vector3.Zero;
							mapTransform.Quaternion.Value = Quaternion.CreateFromRotationMatrix(parentOrientation);
						}
					}
					else
						mapTransform.Matrix.Value = transform.Matrix;
				};

				entity.Add(new NotifyBinding(refreshMapTransform, transform.Matrix, voxel.Offset, voxelFill.Target));
				refreshMapTransform();
			}

			entity.Add("Enabled", voxelFill.Enabled);
			entity.Add("Enable", voxelFill.Enable);
			entity.Add("Disable", voxelFill.Disable);
			entity.Add("IntervalMultiplier", voxelFill.IntervalMultiplier);
			entity.Add("BlockLifetime", voxelFill.BlockLifetime);
		}
开发者ID:dsmo7206,项目名称:Lemma,代码行数:46,代码来源:VoxelFillFactory.cs

示例5: Bind

		public override void Bind(Entity entity, Main main, bool creating = false)
		{
			entity.CannotSuspendByDistance = true;
			Transform transform = entity.GetOrCreate<Transform>("Transform");
			Transform mapTransform = entity.GetOrCreate<Transform>("MapTransform");
			mapTransform.Selectable.Value = false;
			StaticSlider slider = entity.GetOrCreate<StaticSlider>("StaticSlider");
			Factory.Get<VoxelFactory>().InternalBind(entity, main, creating, mapTransform);
			slider.Add(new TwoWayBinding<Matrix>(mapTransform.Matrix, slider.Transform));
			slider.Add(new Binding<Matrix>(slider.EditorTransform, transform.Matrix));

			Voxel voxel = entity.Get<Voxel>();
			slider.Add(new Binding<Vector3>(voxel.LinearVelocity, slider.LinearVelocity));

			Sound.AttachTracker(entity, voxel.Transform);
			SoundKiller.Add(entity, AK.EVENTS.STOP_ALL_OBJECT);

			if (main.EditorEnabled)
				entity.Add(new Binding<Matrix>(entity.GetOrCreate<SliderCommon>("SliderCommon").OriginalTransform, voxel.Transform));

			entity.Add("Forward", slider.Forward);
			entity.Add("Backward", slider.Backward);
			entity.Add("OnHitMax", slider.OnHitMax);
			entity.Add("OnHitMin", slider.OnHitMin);

			entity.Add("Direction", slider.Direction);
			entity.Add("Minimum", slider.Minimum);
			entity.Add("Maximum", slider.Maximum);
			entity.Add("Speed", slider.Speed);
			entity.Add("Goal", slider.Goal);
			entity.Add("StartAtMinimum", slider.StartAtMinimum);
			entity.Add("EnablePhysics", voxel.EnablePhysics);
			entity.Add("Position", slider.Position, new PropertyEntry.EditorData { Readonly = true });
			entity.Add("MovementLoop", slider.MovementLoop, new PropertyEntry.EditorData { Options = WwisePicker.Get(main) });
			entity.Add("MovementStop", slider.MovementStop, new PropertyEntry.EditorData { Options = WwisePicker.Get(main) });

			entity.Add("UVRotation", voxel.UVRotation);
			entity.Add("UVOffset", voxel.UVOffset);

			if (main.EditorEnabled)
				this.attachEditorComponents(entity, main);
		}
开发者ID:dsmo7206,项目名称:Lemma,代码行数:42,代码来源:StaticSliderFactory.cs

示例6: New

            public object New(Type type)
            {
                // Create a new root entity, and make sure transformation component is created
                var rootEntity = new Entity();
                rootEntity.Name = "Root";
                rootEntity.GetOrCreate(TransformComponent.Key);

                return new EntityAsset
                {
                    Hierarchy =
                    {
                        Entities = { rootEntity },
                        RootEntity = rootEntity.Id,
                    }
                };
            }
开发者ID:dejavvu,项目名称:paradox,代码行数:16,代码来源:EntityAsset.cs

示例7: GenerateRotationGizmo

        public Entity GenerateRotationGizmo()
        {
            var entity = new Entity("RotationGizmo");
            entity.Set(TransformationComponent.Key, new TransformationComponent());

            // TODO: Factorize some of this code with GenerateTranslationGizmo?
            var gizmoActions = new[] { GizmoAction.RotationX, GizmoAction.RotationY, GizmoAction.RotationZ };
            var orientationMatrices = new[] { Matrix.Identity, Matrix.RotationZ((float)Math.PI * 0.5f), Matrix.RotationY(-(float)Math.PI * 0.5f) };
            var colors = new[] { Color.Green, Color.Blue, Color.Red };

            var albedoMaterial = new ShaderMixinSource()
                {
                    "AlbedoDiffuseBase",
                    "AlbedoSpecularBase",
                    new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorFixed", MaterialKeys.DiffuseColor)),
                    new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values!
                };

            for (int axis = 0; axis < 3; ++axis)
            {
                // Rendering
                var circleEffectMeshData = new EffectMeshData();
                circleEffectMeshData.Parameters = new ParameterCollection();
                circleEffectMeshData.MeshData = MeshDataHelper.CreateCircle(20.0f, 32, colors[axis]);
                circleEffectMeshData.EffectData = new EffectData("Gizmo") { AlbedoMaterial = albedoMaterial };

                var circleEntity = new Entity("ArrowCone");
                circleEntity.GetOrCreate(ModelComponent.Key).SubMeshes.Add(circleEffectMeshData);
                circleEntity.Set(TransformationComponent.Key, TransformationMatrix.CreateComponent(orientationMatrices[axis]));

                circleEntity.Set(GizmoColorKey, colors[axis]);
                circleEntity.Set(GizmoActionKey, gizmoActions[axis]);

                entity.GetOrCreate(TransformationComponent.Key).Children.Add(circleEntity.GetOrCreate(TransformationComponent.Key));
            }

            return entity;
        }
开发者ID:h78hy78yhoi8j,项目名称:xenko,代码行数:38,代码来源:PickingSystem.cs

示例8: SaveScene2

        //[XenkoScript(ScriptFlags.AssemblyStartup)]
        public static async Task SaveScene2(EngineContext engineContext)
        {
            var assetManager = new AssetManager(new AssetSerializerContextGenerator(engineContext.PackageManager));

            var entity = new Entity();
            var meshComponent = entity.GetOrCreate(ModelComponent.Key);
            meshComponent.SubMeshes.Add(new EffectMeshData { MeshData = new SubMeshData { DrawCount = 321 } });
            var entities = new[] { entity };

            throw new NotImplementedException();
            //var convertedEntities = assetManager.Convert<EntityGroup, IList<Entity>>(entities, "/data/package_scene.hotei#");
            //assetManager.Save(convertedEntities);

            //var contents = ParameterContainerExtensions.EnumerateContentData(convertedEntities).ToArray();
            //var sceneText = ParameterContainerExtensions.ConvertToText(contents[0]);
            //File.WriteAllText("current_scene.txt", sceneText);

            //ParameterContainerExtensions.ConvertFromText(engineContext, sceneText, "/data/package_scene_copy.hotei#/root");
            //var convertedEntities2 = assetManager.Load<EntityGroup>("/data/package_scene_copy.hotei#");
        }
开发者ID:h78hy78yhoi8j,项目名称:xenko,代码行数:21,代码来源:ScriptSceneSerialization.cs

示例9: Bind

		public static void Bind(Entity entity, Main main, Func<BEPUphysics.Entities.Entity, BEPUphysics.Entities.Entity, Vector3, Vector3, Vector3, ISpaceObject> createJoint, bool allowRotation, bool creating = false, bool directional = true)
		{
			Transform mapTransform = entity.GetOrCreate<Transform>("MapTransform");
			mapTransform.Selectable.Value = false;

			Transform transform = entity.GetOrCreate<Transform>("Transform");

			Factory.Get<DynamicVoxelFactory>().InternalBind(entity, main, creating, mapTransform);

			DynamicVoxel map = entity.Get<DynamicVoxel>();

			Components.Joint jointData = entity.GetOrCreate<Components.Joint>("Joint");

			Action refreshMapTransform = delegate()
			{
				Entity parent = jointData.Parent.Value.Target;
				if (parent != null && parent.Active)
				{
					Voxel staticMap = parent.Get<Voxel>();
					jointData.Coord.Value = staticMap.GetCoordinate(transform.Matrix.Value.Translation);
					mapTransform.Position.Value = staticMap.GetAbsolutePosition(staticMap.GetRelativePosition(jointData.Coord) - new Vector3(0.5f) + staticMap.Offset + map.Offset.Value);
					if (allowRotation)
					{
						if (main.EditorEnabled)
							mapTransform.Quaternion.Value = transform.Quaternion;
					}
					else
					{
						Matrix parentOrientation = staticMap.Transform;
						parentOrientation.Translation = Vector3.Zero;
						mapTransform.Quaternion.Value = Quaternion.CreateFromRotationMatrix(parentOrientation);
					}
				}
				else
					mapTransform.Matrix.Value = transform.Matrix;
			};

			if (main.EditorEnabled)
				entity.Add(new NotifyBinding(refreshMapTransform, transform.Matrix, transform.Quaternion, map.Offset, jointData.Parent));

			ISpaceObject joint = null;
			CommandBinding jointDeleteBinding = null, parentPhysicsUpdateBinding = null;
			NotifyBinding parentStaticMoveBinding = null;

			Action updateJoint = null;

			Action rebuildJoint = null;
			rebuildJoint = delegate()
			{
				if (jointDeleteBinding != null)
					entity.Remove(jointDeleteBinding);
				jointDeleteBinding = null;

				if (parentPhysicsUpdateBinding != null)
					entity.Remove(parentPhysicsUpdateBinding);
				parentPhysicsUpdateBinding = null;

				updateJoint();
			};

			updateJoint = delegate()
			{
				if (joint != null)
				{
					if (joint.Space != null)
						main.Space.Remove(joint);
					joint = null;
				}
				if (parentStaticMoveBinding != null)
				{
					entity.Remove(parentStaticMoveBinding);
					parentStaticMoveBinding = null;
				}

				Entity parent = jointData.Parent.Value.Target;

				if (main.EditorEnabled)
					refreshMapTransform();
				else if (parent != null && parent.Active)
				{
					Voxel parentStaticMap = parent.Get<Voxel>();

					//map.PhysicsEntity.Position = mapTransform.Position;
					if (!allowRotation)
						map.PhysicsEntity.Orientation = mapTransform.Quaternion;

					if (jointData.Direction != Direction.None)
					{
						Vector3 relativeLineAnchor = parentStaticMap.GetRelativePosition(jointData.Coord) - new Vector3(0.5f) + parentStaticMap.Offset + map.Offset;
						Vector3 lineAnchor = parentStaticMap.GetAbsolutePosition(relativeLineAnchor);
						DynamicVoxel parentDynamicMap = parent.Get<DynamicVoxel>();
						joint = createJoint(map.PhysicsEntity, parentDynamicMap == null ? null : parentDynamicMap.PhysicsEntity, lineAnchor, parentStaticMap.GetAbsoluteVector(jointData.Direction.Value.GetVector()), parentStaticMap.GetAbsolutePosition(jointData.Coord));
						main.Space.Add(joint);
						map.PhysicsEntity.ActivityInformation.Activate();

						if (parentDynamicMap != null && parentPhysicsUpdateBinding == null)
						{
							parentPhysicsUpdateBinding = new CommandBinding(parentDynamicMap.PhysicsUpdated, updateJoint);
							entity.Add(parentPhysicsUpdateBinding);
						}
//.........这里部分代码省略.........
开发者ID:dsmo7206,项目名称:Lemma,代码行数:101,代码来源:JointFactory.cs

示例10: Bind


//.........这里部分代码省略.........
            result.Add(new CommandBinding<int>(input.MouseScrolled, () => editor.MapEditMode && !input.GetKey(Keys.LeftAlt), delegate(int delta)
            {
                editor.BrushSize.Value = Math.Max(1, editor.BrushSize.Value + delta);
            }));

            addCommand("Propagate current material", new PCInput.Chord { Modifier = Keys.LeftShift, Key = Keys.E }, () => editor.MapEditMode, editor.PropagateMaterial);
            addCommand("Sample current material", new PCInput.Chord { Modifier = Keys.LeftShift, Key = Keys.Q }, () => editor.MapEditMode, editor.SampleMaterial);
            addCommand("Delete current material", new PCInput.Chord { Modifier = Keys.LeftShift, Key = Keys.X }, () => editor.MapEditMode, editor.DeleteMaterial);

            editor.Add(new Binding<Vector2>(editor.Mouse, input.Mouse, () => !input.EnableLook));

            Camera camera = main.Camera;

            Property<float> cameraDistance = new Property<float> { Value = 10.0f };
            scroller.Add(new Binding<bool>(scroller.EnableScroll, x => !x, input.GetKey(Keys.LeftAlt)));
            input.Add(new CommandBinding<int>(input.MouseScrolled, () => input.GetKey(Keys.LeftAlt), delegate(int delta)
            {
                if (timelineScroller.Highlighted && !editor.MapEditMode)
                {
                    float newScale = Math.Max(timelines.Scale.Value.X + delta * 6.0f, timelineScroller.Size.Value.X / timelines.Size.Value.X);
                    Matrix absoluteTransform = timelines.GetAbsoluteTransform();
                    float x = input.Mouse.Value.X + ((absoluteTransform.Translation.X - input.Mouse.Value.X) * (newScale / timelines.Scale.Value.X));
                    timelines.Position.Value = new Vector2(x, 0.0f);
                    timelines.Scale.Value = new Vector2(newScale, 1.0f);
                }
                else
                    cameraDistance.Value = Math.Max(5, cameraDistance.Value + delta * -2.0f);
            }));
            input.Add(new Binding<bool>(input.EnableLook, () => editor.MapEditMode || (input.MiddleMouseButton && editor.TransformMode.Value == Editor.TransformModes.None), input.MiddleMouseButton, editor.MapEditMode, editor.TransformMode));
            input.Add(new Binding<Vector3, Vector2>(camera.Angles, x => new Vector3(-x.Y, x.X, 0.0f), input.Mouse, () => input.EnableLook));
            input.Add(new Binding<bool>(main.IsMouseVisible, x => !x, input.EnableLook));
            editor.Add(new Binding<Vector3>(camera.Position, () => editor.Position.Value - (camera.Forward.Value * cameraDistance), editor.Position, input.Mouse, cameraDistance));

            PointLight editorLight = result.GetOrCreate<PointLight>("EditorLight");
            editorLight.Serialize = false;
            editorLight.Editable = false;
            editorLight.Shadowed.Value = false;
            editorLight.Add(new Binding<float>(editorLight.Attenuation, x => x * 2.0f, cameraDistance));
            editorLight.Color.Value = Vector3.One;
            editorLight.Add(new Binding<Vector3>(editorLight.Position, main.Camera.Position));
            editorLight.Enabled.Value = false;

            ui.PopupCommands.Add(new EditorUI.PopupCommand
            {
                Description = "Toggle editor light",
                Enabled = () => editor.SelectedEntities.Count == 0 && !editor.MapEditMode,
                Action = new Command { Action = () => editorLight.Enabled.Value = !editorLight.Enabled },
            });

            editor.Add(new CommandBinding(input.RightMouseButtonDown, () => !ui.PopupVisible && !editor.MapEditMode && !input.EnableLook && editor.TransformMode.Value == Editor.TransformModes.None, delegate()
            {
                // We're not editing a map
                // And we're not transforming entities
                // So we must be selecting / deselecting entities
                bool multiselect = input.GetKey(Keys.LeftShift);

                Vector2 mouse = input.Mouse;
                Microsoft.Xna.Framework.Graphics.Viewport viewport = main.GraphicsDevice.Viewport;
                Vector3 ray = Vector3.Normalize(viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1), camera.Projection, camera.View, Matrix.Identity) - viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0), camera.Projection, camera.View, Matrix.Identity));

                Entity closestEntity;
                Transform closestTransform;
                this.raycast(main, ray, out closestEntity, out closestTransform);

                if (closestEntity != null)
                {
开发者ID:kernelbitch,项目名称:Lemma,代码行数:67,代码来源:EditorFactory.cs

示例11: Attach

		public static void Attach(Main main, Entity entity, Player player, AnimatedModel model, FPSInput input, Phone phone, Property<bool> enableWalking, Property<bool> phoneActive, Property<bool> noteActive)
		{
			UIRenderer phoneUi = entity.GetOrCreate<UIRenderer>("PhoneUI");
			model["Phone"].Speed = model["VRPhone"].Speed = model["Note"].Speed = model["VRNote"].Speed = 0.25f;

			const float phoneWidth = 200.0f;

			phoneUi.RenderTargetBackground.Value = Microsoft.Xna.Framework.Color.White;
			phoneUi.RenderTargetSize.Value = new Point((int)phoneWidth, (int)(phoneWidth * 2.0f));
			phoneUi.Serialize = false;
			phoneUi.Enabled.Value = false;
#if VR
			if (main.VR)
				phoneUi.Reticle.Tint.Value = new Color(0.0f, 0.0f, 0.0f);
#endif

			Model phoneModel = entity.GetOrCreate<Model>("PhoneModel");
			phoneModel.Filename.Value = "Models\\phone";
			phoneModel.Color.Value = new Vector3(0.13f, 0.13f, 0.13f);
			phoneModel.Serialize = false;
			phoneModel.Enabled.Value = false;

			Property<Matrix> phoneBone = model.GetBoneTransform("Phone");
			phoneModel.Add(new Binding<Matrix>(phoneModel.Transform, () => phoneBone.Value * model.Transform, phoneBone, model.Transform));

			Model screen = entity.GetOrCreate<Model>("Screen");
			screen.Filename.Value = "Models\\plane";
			screen.Add(new Binding<Microsoft.Xna.Framework.Graphics.RenderTarget2D>(screen.GetRenderTarget2DParameter("Diffuse" + Model.SamplerPostfix), phoneUi.RenderTarget));
			screen.Add(new Binding<Matrix>(screen.Transform, x => Matrix.CreateTranslation(0.015f, 0.0f, 0.0f) * x, phoneModel.Transform));
			screen.Serialize = false;
			screen.Enabled.Value = false;

			PointLight phoneLight = entity.Create<PointLight>();
			phoneLight.Serialize = false;
			phoneLight.Enabled.Value = false;
			phoneLight.Attenuation.Value = 0.5f;
			phoneLight.Add(new Binding<Vector3, Matrix>(phoneLight.Position, x => x.Translation, screen.Transform));

			PointLight noteLight = entity.Create<PointLight>();
			noteLight.Serialize = false;
			noteLight.Enabled.Value = false;
			noteLight.Attenuation.Value = 1.0f;
			noteLight.Color.Value = new Vector3(0.3f);
			noteLight.Add(new Binding<Vector3>(noteLight.Position, () => Vector3.Transform(new Vector3(0.25f, 0.0f, 0.0f), phoneBone.Value * model.Transform), phoneBone, model.Transform));

			const float screenScale = 0.0007f;
			screen.Scale.Value = new Vector3(1.0f, (float)phoneUi.RenderTargetSize.Value.Y * screenScale, (float)phoneUi.RenderTargetSize.Value.X * screenScale);

			// Transform screen space mouse position into 3D, then back into the 2D space of the phone UI
			Property<Matrix> screenTransform = new Property<Matrix>();
			screen.Add(new Binding<Matrix>(screenTransform, () => Matrix.CreateScale(screen.Scale) * screen.Transform, screen.Scale, screen.Transform));
			phoneUi.Setup3D(screenTransform);

			// Phone UI

			const float padding = 8.0f;
			const float messageWidth = phoneWidth - padding * 2.0f;

			Func<Property<Color>, string, float, Container> makeButton = delegate(Property<Color> color, string text, float width)
			{
				Container bg = new Container();
				bg.Tint.Value = color;
				bg.PaddingBottom.Value = bg.PaddingLeft.Value = bg.PaddingRight.Value = bg.PaddingTop.Value = padding * 0.5f;
				bg.Add(new Binding<Color>(bg.Tint, () => bg.Highlighted ? new Color(color.Value.ToVector4() + new Vector4(0.2f, 0.2f, 0.2f, 0.0f)) : color, bg.Highlighted, color));

				TextElement msg = new TextElement();
				msg.Name.Value = "Text";
				msg.FontFile.Value = main.Font;
				msg.Text.Value = text;
				msg.WrapWidth.Value = width;
				bg.Children.Add(msg);
				return bg;
			};

			Action<Container, float> centerButton = delegate(Container button, float width)
			{
				TextElement text = (TextElement)button.Children[0];
				text.AnchorPoint.Value = new Vector2(0.5f, 0);
				text.Add(new Binding<Vector2>(text.Position, x => new Vector2(x.X * 0.5f, padding), button.Size));
				button.ResizeHorizontal.Value = false;
				button.ResizeVertical.Value = false;
				button.Size.Value = new Vector2(width, 36.0f * main.FontMultiplier);
			};

			Func<UIComponent, bool, Container> makeAlign = delegate(UIComponent component, bool right)
			{
				Container container = new Container();
				container.Opacity.Value = 0.0f;
				container.PaddingBottom.Value = container.PaddingLeft.Value = container.PaddingRight.Value = container.PaddingTop.Value = 0.0f;
				container.ResizeHorizontal.Value = false;
				container.Size.Value = new Vector2(messageWidth, 0.0f);
				component.AnchorPoint.Value = new Vector2(right ? 1.0f : 0.0f, 0.0f);
				component.Position.Value = new Vector2(right ? messageWidth : 0.0f, 0.0f);
				container.Children.Add(component);
				return container;
			};

			Property<Color> incomingColor = new Property<Color> { Value = new Color(0.0f, 0.0f, 0.0f, 1.0f) };
			Property<Color> outgoingColor = new Property<Color> { Value = new Color(0.0f, 0.175f, 0.35f, 1.0f) };
			Property<Color> alternateSenderColor = new Property<Color> { Value = new Color(0.25f, 0.0f, 0.25f, 1.0f) };
//.........这里部分代码省略.........
开发者ID:dsmo7206,项目名称:Lemma,代码行数:101,代码来源:PhoneNote.cs

示例12: Bind

        public override void Bind(Entity result, Main main, bool creating = false)
        {
            PointLight light = result.GetOrCreate<PointLight>("PointLight");
            light.Serialize = false;

            const float defaultLightAttenuation = 15.0f;
            light.Attenuation.Value = defaultLightAttenuation;

            Transform transform = result.GetOrCreate<Transform>("Transform");
            light.Add(new Binding<Vector3>(light.Position, transform.Position));

            VoxelChaseAI chase = result.GetOrCreate<VoxelChaseAI>("VoxelChaseAI");

            chase.Filter = delegate(Map.CellState state)
            {
                return state.ID == 0 ? VoxelChaseAI.Cell.Empty : VoxelChaseAI.Cell.Filled;
            };

            chase.Add(new TwoWayBinding<Vector3>(transform.Position, chase.Position));
            result.Add(new CommandBinding(chase.Delete, result.Delete));

            Sound sound = result.GetOrCreate<Sound>("LoopSound");
            sound.Serialize = false;
            sound.Cue.Value = "Orb Loop";
            sound.Is3D.Value = true;
            sound.IsPlaying.Value = true;
            sound.Add(new Binding<Vector3>(sound.Position, chase.Position));
            Property<float> volume = sound.GetProperty("Volume");
            Property<float> pitch = sound.GetProperty("Pitch");

            const float defaultVolume = 0.5f;
            volume.Value = defaultVolume;

            AI ai = result.GetOrCreate<AI>();

            Model model = result.GetOrCreate<Model>();
            model.Add(new Binding<Matrix>(model.Transform, transform.Matrix));
            model.Filename.Value = "Models\\sphere";
            model.Editable = false;
            model.Serialize = false;

            const float defaultModelScale = 0.25f;
            model.Scale.Value = new Vector3(defaultModelScale);

            model.Add(new Binding<Vector3, string>(model.Color, delegate(string state)
            {
                switch (state)
                {
                    case "Alert":
                        return new Vector3(1.5f, 1.5f, 0.5f);
                    case "Chase":
                        return new Vector3(1.5f, 0.5f, 0.5f);
                    case "Levitating":
                        return new Vector3(2.0f, 1.0f, 0.5f);
                    case "Idle":
                        return new Vector3(1.0f, 1.0f, 1.0f);
                    default:
                        return new Vector3(0.0f, 0.0f, 0.0f);
                }
            }, ai.CurrentState));

            Random random = new Random();
            result.Add(new Updater
            {
                delegate(float dt)
                {
                    float source = ((float)random.NextDouble() - 0.5f) * 2.0f;
                    model.Scale.Value = new Vector3(defaultModelScale * (1.0f + (source * 0.5f)));
                    light.Attenuation.Value = defaultLightAttenuation * (1.0f + (source * 0.05f));
                }
            });

            model.Add(new Binding<bool, string>(model.Enabled, x => x != "Exploding", ai.CurrentState));

            light.Add(new Binding<Vector3>(light.Color, model.Color));

            Agent agent = result.GetOrCreate<Agent>();
            agent.Add(new Binding<Vector3>(agent.Position, chase.Position));

            Property<int> operationalRadius = result.GetOrMakeProperty<int>("OperationalRadius", true, 100);

            AI.Task checkOperationalRadius = new AI.Task
            {
                Interval = 2.0f,
                Action = delegate()
                {
                    bool shouldBeActive = (chase.Position.Value - main.Camera.Position).Length() < operationalRadius;
                    if (shouldBeActive && ai.CurrentState == "Suspended")
                        ai.CurrentState.Value = "Idle";
                    else if (!shouldBeActive && ai.CurrentState != "Suspended")
                        ai.CurrentState.Value = "Suspended";
                },
            };

            const float sightDistance = 30.0f;
            const float hearingDistance = 15.0f;

            ai.Add(new AI.State
            {
                Name = "Idle",
//.........这里部分代码省略.........
开发者ID:kernelbitch,项目名称:Lemma,代码行数:101,代码来源:LevitatorFactory.cs

示例13: InternalBind

        public void InternalBind(Entity result, Main main, bool creating = false, Transform transform = null)
        {
            if (transform == null)
                transform = result.GetOrCreate<Transform>("Transform");

            result.CannotSuspend = false;

            Map map = result.Get<Map>();

            // Apply the position and orientation components to the map
            map.Add(new TwoWayBinding<Matrix>(transform.Matrix, map.Transform));

            map.Add(new CommandBinding(map.CompletelyEmptied, delegate()
            {
                if (!main.EditorEnabled)
                    result.Delete.Execute();
            }));

            Entity world = main.Get("World").FirstOrDefault();

            map.Chunks.ItemAdded += delegate(int index, Map.Chunk chunk)
            {
                Dictionary<int, bool> models = new Dictionary<int, bool>();

                Action<Map.CellState> createModel = delegate(Map.CellState state)
                {
                    if (state.ID == 0)
                        return; // 0 = empty

                    DynamicModel<Map.MapVertex> model = new DynamicModel<Map.MapVertex>(Map.MapVertex.VertexDeclaration);
                    model.EffectFile.Value = "Effects\\Environment";
                    model.Lock = map.Lock;
                    state.ApplyTo(model);

                    /*
                    ModelAlpha debug = new ModelAlpha { Serialize = false };
                    debug.Alpha.Value = 0.01f;
                    debug.DrawOrder.Value = 11; // In front of water
                    debug.Color.Value = new Vector3(1.0f, 0.8f, 0.6f);
                    debug.Filename.Value = "Models\\alpha-box";
                    debug.CullBoundingBox.Value = false;
                    debug.DisableCulling.Value = true;
                    debug.Add(new Binding<Matrix>(debug.Transform, delegate()
                    {
                        BoundingBox box = model.BoundingBox;
                        return Matrix.CreateScale(box.Max - box.Min) * Matrix.CreateTranslation((box.Max + box.Min) * 0.5f) * transform.Matrix;
                    }, transform.Matrix, model.BoundingBox));
                    result.Add(debug);
                    */

                    model.Add(new Binding<Matrix>(model.Transform, transform.Matrix));

                    Vector3 min = new Vector3(chunk.X, chunk.Y, chunk.Z);
                    Vector3 max = min + new Vector3(map.ChunkSize);

                    model.Add(new Binding<Vector3>(model.GetVector3Parameter("Offset"), map.Offset));

                    Map.CellState s = state;

                    if (!s.ShadowCast)
                        model.UnsupportedTechniques.Add(new[] { Technique.Shadow, Technique.PointLightShadow });

                    model.Add(new ListBinding<Map.MapVertex, Map.Box>
                    (
                        model.Vertices,
                        chunk.Boxes,
                        delegate(Map.Box box)
                        {
                            Map.MapVertex[] vertices = new Map.MapVertex[box.Surfaces.Where(x => x.HasArea).Count() * 4];
                            int i = 0;
                            foreach (Map.Surface surface in box.Surfaces)
                            {
                                if (surface.HasArea)
                                {
                                    Array.Copy(surface.Vertices, 0, vertices, i, 4);
                                    i += 4;
                                }
                            }
                            return vertices;
                        },
                        x => x.Type == s
                    ));

                    result.Add(model);

                    // We have to create this binding after adding the model to the entity
                    // Because when the model loads, it automatically calculates a bounding box for it.
                    model.Add(new Binding<BoundingBox, Vector3>(model.BoundingBox, x => new BoundingBox(min - x, max - x), map.Offset));

                    models[state.ID] = true;
                };

                chunk.Boxes.ItemAdded += delegate(int i, Map.Box box)
                {
                    if ((!box.Type.Invisible || main.EditorEnabled) && !models.ContainsKey(box.Type.ID))
                        createModel(box.Type);
                };

                chunk.Boxes.ItemChanged += delegate(int i, Map.Box oldBox, Map.Box newBox)
                {
//.........这里部分代码省略.........
开发者ID:kernelbitch,项目名称:Lemma,代码行数:101,代码来源:MapFactory.cs

示例14: Bind

        public override void Bind(Entity result, Main main, bool creating = false)
        {
            PointLight light = result.GetOrCreate<PointLight>("PointLight");
            light.Serialize = false;

            const float defaultLightAttenuation = 15.0f;
            light.Attenuation.Value = defaultLightAttenuation;

            Transform transform = result.GetOrCreate<Transform>("Transform");
            light.Add(new Binding<Vector3>(light.Position, transform.Position));

            VoxelChaseAI chase = result.GetOrCreate<VoxelChaseAI>("VoxelChaseAI");

            chase.Filter = delegate(Map.CellState state)
            {
                return state.ID == 0 ? VoxelChaseAI.Cell.Empty : VoxelChaseAI.Cell.Filled;
            };

            chase.Add(new TwoWayBinding<Vector3>(transform.Position, chase.Position));
            result.Add(new CommandBinding(chase.Delete, result.Delete));

            Sound sound = result.GetOrCreate<Sound>("LoopSound");
            sound.Serialize = false;
            sound.Cue.Value = "Orb Loop";
            sound.Is3D.Value = true;
            sound.IsPlaying.Value = true;
            sound.Add(new Binding<Vector3>(sound.Position, chase.Position));
            Property<float> volume = sound.GetProperty("Volume");
            Property<float> pitch = sound.GetProperty("Pitch");

            const float defaultVolume = 0.5f;
            volume.Value = defaultVolume;

            AI ai = result.GetOrCreate<AI>();

            Model model = result.GetOrCreate<Model>();
            model.Add(new Binding<Matrix>(model.Transform, transform.Matrix));
            model.Filename.Value = "Models\\sphere";
            model.Editable = false;
            model.Serialize = false;

            const float defaultModelScale = 0.25f;
            model.Scale.Value = new Vector3(defaultModelScale);

            model.Add(new Binding<Vector3, string>(model.Color, delegate(string state)
            {
                switch (state)
                {
                    case "Alert":
                        return new Vector3(1.5f, 1.5f, 0.5f);
                    case "Chase":
                        return new Vector3(1.5f, 0.5f, 0.5f);
                    case "Explode":
                        return new Vector3(2.0f, 1.0f, 0.5f);
                    case "Idle":
                        return new Vector3(1.0f, 1.0f, 1.0f);
                    default:
                        return new Vector3(0.0f, 0.0f, 0.0f);
                }
            }, ai.CurrentState));

            Random random = new Random();
            result.Add(new Updater
            {
                delegate(float dt)
                {
                    float source = ((float)random.NextDouble() - 0.5f) * 2.0f;
                    model.Scale.Value = new Vector3(defaultModelScale * (1.0f + (source * 0.5f)));
                    light.Attenuation.Value = defaultLightAttenuation * (1.0f + (source * 0.05f));
                }
            });

            model.Add(new Binding<bool, string>(model.Enabled, x => x != "Exploding", ai.CurrentState));

            light.Add(new Binding<Vector3>(light.Color, model.Color));

            Agent agent = result.GetOrCreate<Agent>();
            agent.Add(new Binding<Vector3>(agent.Position, chase.Position));

            Property<int> operationalRadius = result.GetOrMakeProperty<int>("OperationalRadius", true, 100);

            AI.Task checkOperationalRadius = new AI.Task
            {
                Interval = 2.0f,
                Action = delegate()
                {
                    bool shouldBeActive = (chase.Position.Value - main.Camera.Position).Length() < operationalRadius;
                    if (shouldBeActive && ai.CurrentState == "Suspended")
                        ai.CurrentState.Value = "Idle";
                    else if (!shouldBeActive && ai.CurrentState != "Suspended")
                        ai.CurrentState.Value = "Suspended";
                },
            };

            const float sightDistance = 30.0f;
            const float hearingDistance = 15.0f;

            ai.Add(new AI.State
            {
                Name = "Idle",
//.........这里部分代码省略.........
开发者ID:kernelbitch,项目名称:Lemma,代码行数:101,代码来源:OrbFactory.cs

示例15: Bind

        public static void Bind(Entity result, Main main, Func<BEPUphysics.Entities.Entity, BEPUphysics.Entities.Entity, Vector3, Vector3, Vector3, ISpaceObject> createJoint, bool allowRotation, bool creating = false)
        {
            Transform mapTransform = result.GetOrCreate<Transform>("MapTransform");

            Transform transform = result.GetOrCreate<Transform>("Transform");

            Factory.Get<DynamicMapFactory>().InternalBind(result, main, creating, mapTransform);

            DynamicMap map = result.Get<DynamicMap>();

            Property<Entity.Handle> parentMap = result.GetOrMakeProperty<Entity.Handle>("Parent");
            Property<Map.Coordinate> coord = result.GetOrMakeProperty<Map.Coordinate>("Coord");
            Property<Direction> dir = result.GetOrMakeProperty<Direction>("Direction", true);

            Action refreshMapTransform = delegate()
            {
                Entity parent = parentMap.Value.Target;
                if (parent != null)
                {
                    if (!parent.Active)
                        parent = null;
                    else
                    {
                        Map staticMap = parent.Get<Map>();
                        coord.Value = staticMap.GetCoordinate(transform.Position);
                        mapTransform.Position.Value = staticMap.GetAbsolutePosition(staticMap.GetRelativePosition(coord) - new Vector3(0.5f) + staticMap.Offset + map.Offset);
                        if (!allowRotation)
                            mapTransform.Orientation.Value = parent.Get<Transform>().Orientation;
                    }
                }
                else
                    mapTransform.Matrix.Value = transform.Matrix;
            };
            if (main.EditorEnabled)
                result.Add(new NotifyBinding(refreshMapTransform, transform.Matrix, map.Offset));

            ISpaceObject joint = null;
            CommandBinding jointDeleteBinding = null, physicsUpdateBinding = null;

            Action rebuildJoint = null;
            rebuildJoint = delegate()
            {
                if (joint != null)
                {
                    if (joint.Space != null)
                        main.Space.Remove(joint);
                    result.Remove(jointDeleteBinding);
                    if (physicsUpdateBinding != null)
                        result.Remove(physicsUpdateBinding);
                    physicsUpdateBinding = null;
                    joint = null;
                    jointDeleteBinding = null;
                }

                Entity parent = parentMap.Value.Target;

                if (main.EditorEnabled)
                {
                    refreshMapTransform();
                    return;
                }

                if (parent != null)
                {
                    if (!parent.Active)
                        parent = null;
                    else
                    {
                        Map staticMap = parent.Get<Map>();

                        map.PhysicsEntity.Position = mapTransform.Position;
                        if (!allowRotation)
                            map.PhysicsEntity.Orientation = mapTransform.Quaternion;

                        if (dir != Direction.None && !main.EditorEnabled)
                        {
                            Vector3 relativeLineAnchor = staticMap.GetRelativePosition(coord) - new Vector3(0.5f) + staticMap.Offset + map.Offset;
                            Vector3 lineAnchor = staticMap.GetAbsolutePosition(relativeLineAnchor);
                            DynamicMap dynamicMap = parent.Get<DynamicMap>();
                            joint = createJoint(map.PhysicsEntity, dynamicMap == null ? null : dynamicMap.PhysicsEntity, map.PhysicsEntity.Position, staticMap.GetAbsoluteVector(dir.Value.GetVector()), lineAnchor);
                            main.Space.Add(joint);
                            map.PhysicsEntity.ActivityInformation.Activate();

                            if (dynamicMap != null)
                            {
                                physicsUpdateBinding = new CommandBinding(dynamicMap.PhysicsUpdated, rebuildJoint);
                                result.Add(physicsUpdateBinding);
                            }

                            jointDeleteBinding = new CommandBinding(parent.Delete, delegate()
                            {
                                parentMap.Value = null;
                            });
                            result.Add(jointDeleteBinding);
                        }
                    }
                }
            };
            result.Add(new NotifyBinding(rebuildJoint, parentMap));
            result.Add(new CommandBinding(result.Delete, delegate()
//.........这里部分代码省略.........
开发者ID:kernelbitch,项目名称:Lemma,代码行数:101,代码来源:JointFactory.cs


注:本文中的System.Entity.GetOrCreate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。