コード例 #1
0
ファイル: Slider.cs プロジェクト: tammukul/Lemma
        public override void Start()
        {
            if (!this.main.EditorEnabled)
            {
                if (this.StartAtMinimum)
                {
                    this.StartAtMinimum.Value = false;
                    Transform transform = this.Entity.GetOrCreate <Transform>("MapTransform");
                    transform.Selectable.Value = false;
                    DynamicVoxel map = this.Entity.Get <DynamicVoxel>();
                    transform.Position.Value = map.GetAbsolutePosition(new Voxel.Coord().Move(this.Direction, this.Minimum));
                }

                Action stopMovement = delegate()
                {
                    if (this.main.TotalTime > 0.1f && this.MovementStop.Value != 0)
                    {
                        AkSoundEngine.PostEvent(this.MovementStop, this.Entity);
                    }
                    else
                    {
                        AkSoundEngine.PostEvent(AK.EVENTS.STOP_ALL_OBJECT, this.Entity);
                    }
                    this.soundPlaying = false;
                };
                this.Add(new CommandBinding(this.OnHitMax, stopMovement));
                this.Add(new CommandBinding(this.OnHitMin, stopMovement));
            }
        }
コード例 #2
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Components.Joint joint   = entity.GetOrCreate <Components.Joint>("Joint");
            Spinner          spinner = entity.GetOrCreate <Spinner>("Spinner");

            spinner.Add(new Binding <Direction>(spinner.Direction, joint.Direction));

            JointFactory.Bind(entity, main, spinner.CreateJoint, true, creating);
            DynamicVoxel voxel = entity.Get <DynamicVoxel>();

            voxel.KineticFriction.Value = voxel.StaticFriction.Value = 0;

            entity.Add("On", spinner.On);
            entity.Add("Off", spinner.Off);
            entity.Add("Forward", spinner.Forward);
            entity.Add("Backward", spinner.Backward);
            entity.Add("HitMax", spinner.HitMax);
            entity.Add("HitMin", spinner.HitMin);

            entity.Add("Direction", joint.Direction);
            entity.Add("Minimum", spinner.Minimum);
            entity.Add("Maximum", spinner.Maximum);
            entity.Add("Locked", spinner.Locked);
            entity.Add("Speed", spinner.Speed);
            entity.Add("Goal", spinner.Goal);
            entity.Add("Servo", spinner.Servo);
            entity.Add("CannotSuspendByDistance", entity.Get <DynamicVoxel>().CannotSuspendByDistance);
        }
コード例 #3
0
ファイル: Slider.cs プロジェクト: schmittens/Lemma
        private void updateMaterial()
        {
            if (!this.main.EditorEnabled)
            {
                DynamicVoxel map = this.Entity.Get <DynamicVoxel>();
                if (map != null)
                {
                    bool active = this.Locked && (!this.Servo || (this.Servo && this.Goal.Value != this.Minimum.Value));

                    Voxel.State desired   = active ? Voxel.States.SliderPowered : Voxel.States.Slider;
                    Voxel.t     currentID = map[0, 0, 0].ID;
                    if (currentID != desired.ID & (currentID == Voxel.t.Slider || currentID == Voxel.t.SliderPowered))
                    {
                        List <Voxel.Coord> coords = map.GetContiguousByType(new[] { map.GetBox(0, 0, 0) }).SelectMany(x => x.GetCoords()).ToList();
                        map.Empty(coords, true, true, null, false);
                        foreach (Voxel.Coord c in coords)
                        {
                            map.Fill(c, desired);
                        }
                        map.Regenerate();
                    }
                    map.PhysicsEntity.ActivityInformation.Activate();
                }
            }
        }
コード例 #4
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            base.Bind(entity, main, creating);
            DynamicVoxel map = entity.Get <DynamicVoxel>();

            entity.Add("IsAffectedByGravity", map.IsAffectedByGravity);
            entity.Add("IsAlwaysActive", map.IsAlwaysActive);
            entity.Add("CannotSuspendByDistance", map.CannotSuspendByDistance);

            const float volumeMultiplier = 0.005f;

            float lastCollision = 0.0f;

            map.Add(new CommandBinding <Collidable, ContactCollection>(map.Collided, delegate(Collidable collidable, ContactCollection contacts)
            {
                ContactInformation contact = contacts[contacts.Count - 1];
                float volume = contact.NormalImpulse * volumeMultiplier;
                float now    = main.TotalTime;
                if (volume > 0.1f && now > lastCollision + 0.3f)
                {
                    // TODO: figure out Wwise volume parameter
                    uint cue = map[contact.Contact.Position - (contact.Contact.Normal * 0.25f)].RubbleEvent;
                    AkSoundEngine.PostEvent(cue, entity);
                    lastCollision = now;
                    if (PlayerFactory.Instance != null)
                    {
                        PlayerFactory.Instance.Get <CameraController>().Shake.Execute(contact.Contact.Position, volume);
                    }
                }
            }));
        }
コード例 #5
0
        public override void Start()
        {
            if (!this.main.EditorEnabled)
            {
                if (this.StartAtMinimum)
                {
                    this.StartAtMinimum.Value = false;
                    Transform transform = this.Entity.GetOrCreate <Transform>("MapTransform");
                    transform.Selectable.Value = false;
                    DynamicVoxel map = this.Entity.Get <DynamicVoxel>();
                    transform.Position.Value = map.GetAbsolutePosition(new Voxel.Coord().Move(this.Direction, this.Minimum));
                }

                this.Add(new SetBinding <int>(this.Goal, delegate(int value)
                {
                    if (this.joint != null)
                    {
                        Vector3 separation = this.joint.Limit.AnchorB - this.joint.Limit.AnchorA;
                        float x            = Vector3.Dot(separation, this.joint.Limit.Axis);
                        if (Math.Abs(x - this.Goal) > 0.1f)
                        {
                            AkSoundEngine.PostEvent(this.MovementLoop, this.Entity);
                        }
                    }
                }));
                Action stopMovement = delegate()
                {
                    AkSoundEngine.PostEvent(this.MovementStop, this.Entity);
                };
                this.Add(new CommandBinding(this.OnHitMax, stopMovement));
                this.Add(new CommandBinding(this.OnHitMin, stopMovement));
            }
        }
コード例 #6
0
ファイル: VoxelRip.cs プロジェクト: schmittens/Lemma
        public static void Consolidate(Main main, DynamicVoxel voxel, float interval = 1.0f)
        {
            int   maxDistance  = 12;
            Voxel closestVoxel = null;

            Voxel.Coord closestCoord = new Voxel.Coord();
            foreach (Voxel m in Voxel.ActivePhysicsVoxels)
            {
                if (m == voxel)
                {
                    continue;
                }

                Voxel.Coord relativeCoord = m.GetCoordinate(voxel.Transform.Value.Translation);
                Voxel.Coord?closestFilled = m.FindClosestFilledCell(relativeCoord, maxDistance);
                if (closestFilled != null)
                {
                    maxDistance  = Math.Min(Math.Abs(relativeCoord.X - closestFilled.Value.X), Math.Min(Math.Abs(relativeCoord.Y - closestFilled.Value.Y), Math.Abs(relativeCoord.Z - closestFilled.Value.Z)));
                    closestVoxel = m;
                    closestCoord = closestFilled.Value;
                }
            }

            if (closestVoxel != null)
            {
                VoxelRip.Consolidate(main, voxel, closestVoxel, closestCoord, interval);
            }
        }
コード例 #7
0
ファイル: Slider.cs プロジェクト: schmittens/Lemma
 public override void Start()
 {
     if (!this.main.EditorEnabled && this.StartAtMinimum)
     {
         this.StartAtMinimum.Value = false;
         Transform transform = this.Entity.GetOrCreate <Transform>("MapTransform");
         transform.Selectable.Value = false;
         DynamicVoxel map = this.Entity.Get <DynamicVoxel>();
         transform.Position.Value = map.GetAbsolutePosition(new Voxel.Coord().Move(this.Direction, this.Minimum));
     }
 }
コード例 #8
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Slider slider = entity.GetOrCreate <Slider>("Slider");

            JointFactory.Bind(entity, main, slider.CreateJoint, false, creating);

            Components.Joint joint = entity.GetOrCreate <Components.Joint>("Joint");
            slider.Add(new Binding <Direction>(slider.Direction, joint.Direction));

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

            voxel.KineticFriction.Value = voxel.StaticFriction.Value = 0;
            AkGameObjectTracker.Attach(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("MovementLoop", slider.MovementLoop, new PropertyEntry.EditorData {
                Options = WwisePicker.Get(main)
            });
            entity.Add("MovementStop", slider.MovementStop, new PropertyEntry.EditorData {
                Options = WwisePicker.Get(main)
            });
            entity.Add("Direction", joint.Direction);
            entity.Add("Minimum", slider.Minimum);
            entity.Add("Maximum", slider.Maximum);
            entity.Add("Locked", slider.Locked);
            entity.Add("Speed", slider.Speed);
            entity.Add("Goal", slider.Goal);
            entity.Add("Servo", slider.Servo);
            entity.Add("StartAtMinimum", slider.StartAtMinimum);
            entity.Add("MaxForce", slider.MaxForce);

            entity.Add("UVRotation", voxel.UVRotation);
            entity.Add("UVOffset", voxel.UVOffset);
            entity.Add("CannotSuspendByDistance", voxel.CannotSuspendByDistance);
        }
コード例 #9
0
        public override void Awake()
        {
            base.Awake();
            this.Serialize         = false;
            this.EnabledWhenPaused = false;
            this.Apply.Action      = delegate(float verticalAcceleration) { this.apply(verticalAcceleration, false); };

            // Damage the player if they hit something too hard
            this.Collided.Action = delegate(BEPUphysics.BroadPhaseEntries.Collidable other, ContactCollection contacts)
            {
                DynamicVoxel map = other.Tag as DynamicVoxel;
                if (map != null)
                {
                    float force           = contacts[contacts.Count - 1].NormalImpulse;
                    float threshold       = map.Dangerous ? 20.0f : 50.0f;
                    float playerLastSpeed = Vector3.Dot(this.lastLinearVelocity, Vector3.Normalize(-contacts[contacts.Count - 1].Contact.Normal)) * 2.5f;
                    if (force > threshold + playerLastSpeed + 4.0f)
                    {
                        this.PhysicsDamage.Execute((force - threshold - playerLastSpeed) * 0.04f);
                    }
                }
            };
        }
コード例 #10
0
ファイル: SpinnerFactory.cs プロジェクト: tammukul/Lemma
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Components.Joint joint   = entity.GetOrCreate <Components.Joint>("Joint");
            Spinner          spinner = entity.GetOrCreate <Spinner>("Spinner");

            spinner.Add(new Binding <Direction>(spinner.Direction, joint.Direction));

            JointFactory.Bind(entity, main, spinner.CreateJoint, true, creating);
            DynamicVoxel voxel = entity.Get <DynamicVoxel>();

            voxel.KineticFriction.Value = voxel.StaticFriction.Value = 0;

            if (main.EditorEnabled)
            {
                spinner.Add(new Binding <Quaternion, Matrix>(spinner.OriginalRotation, x => Quaternion.CreateFromRotationMatrix(x), voxel.Transform));
            }

            entity.Add("Forward", spinner.Forward);
            entity.Add("Backward", spinner.Backward);
            entity.Add("HitMax", spinner.HitMax);
            entity.Add("HitMin", spinner.HitMin);
            entity.Add("MovementLoop", spinner.MovementLoop, new PropertyEntry.EditorData {
                Options = WwisePicker.Get(main)
            });
            entity.Add("MovementStop", spinner.MovementStop, new PropertyEntry.EditorData {
                Options = WwisePicker.Get(main)
            });

            entity.Add("Direction", joint.Direction);
            entity.Add("Minimum", spinner.Minimum);
            entity.Add("Maximum", spinner.Maximum);
            entity.Add("Locked", spinner.Locked);
            entity.Add("Speed", spinner.Speed);
            entity.Add("Goal", spinner.Goal);
            entity.Add("Servo", spinner.Servo);
            entity.Add("CannotSuspendByDistance", entity.Get <DynamicVoxel>().CannotSuspendByDistance);
        }
コード例 #11
0
ファイル: SliderFactory.cs プロジェクト: schmittens/Lemma
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Slider slider = entity.GetOrCreate <Slider>("Slider");

            JointFactory.Bind(entity, main, slider.CreateJoint, false, creating);

            Components.Joint joint = entity.GetOrCreate <Components.Joint>("Joint");
            slider.Add(new Binding <Direction>(slider.Direction, joint.Direction));

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

            voxel.KineticFriction.Value = voxel.StaticFriction.Value = 0;

            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", joint.Direction);
            entity.Add("Minimum", slider.Minimum);
            entity.Add("Maximum", slider.Maximum);
            entity.Add("Locked", slider.Locked);
            entity.Add("Speed", slider.Speed);
            entity.Add("Goal", slider.Goal);
            entity.Add("Servo", slider.Servo);
            entity.Add("StartAtMinimum", slider.StartAtMinimum);
            entity.Add("MaxForce", slider.MaxForce);

            entity.Add("UVRotation", voxel.UVRotation);
            entity.Add("UVOffset", voxel.UVOffset);
            entity.Add("CannotSuspendByDistance", voxel.CannotSuspendByDistance);
        }
コード例 #12
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            base.Bind(entity, main, creating);
            DynamicVoxel map = entity.Get <DynamicVoxel>();

            entity.Add("IsAffectedByGravity", map.IsAffectedByGravity);
            entity.Add("IsAlwaysActive", map.IsAlwaysActive);
            entity.Add("CannotSuspendByDistance", map.CannotSuspendByDistance);

            const float volumeMultiplier = 0.05f;

            float lastCollision = 0.0f;

            map.Add(new CommandBinding <Collidable, ContactCollection>(map.Collided, delegate(Collidable collidable, ContactCollection contacts)
            {
                if (map.PhysicsEntity.LinearVelocity.Length() > 3.0f ||
                    map.PhysicsEntity.AngularVelocity.Length() > 1.0f)
                {
                    ContactInformation contact = contacts[contacts.Count - 1];
                    float volume = contact.RelativeVelocity.Length() * volumeMultiplier;
                    float now    = main.TotalTime;
                    if (volume > 0.2f && now > lastCollision + 0.1f)
                    {
                        uint id = Sound.RegisterTemp(contact.Contact.Position);
                        AkSoundEngine.PostEvent(AK.EVENTS.PLAY_PHYSICS_SLAM, id);
                        AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.PHYSICS_SLAM_SIZE, Math.Min(volume * 100.0f, 100.0f), id);
                        AkSoundEngine.UnregisterTemp(id);
                        lastCollision = now;
                        if (PlayerFactory.Instance != null)
                        {
                            PlayerFactory.Instance.Get <CameraController>().Shake.Execute(contact.Contact.Position, volume);
                        }
                    }
                }
            }));
        }
コード例 #13
0
ファイル: BouncerFactory.cs プロジェクト: tammukul/Lemma
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Bouncer bouncer = entity.GetOrCreate <Bouncer>("Bouncer");

            JointFactory.Bind(entity, main, bouncer.CreateJoint, false, creating, false);

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

            bouncer.Add(new Binding <Entity.Handle>(bouncer.Parent, joint.Parent));
            bouncer.Add(new Binding <Voxel.Coord>(bouncer.Coord, joint.Coord));

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

            voxel.KineticFriction.Value = voxel.StaticFriction.Value = 0;

            bouncer.Add(new CommandBinding(voxel.PhysicsUpdated, delegate()
            {
                bouncer.PhysicsUpdated.Execute(voxel.PhysicsEntity.Mass, voxel.PhysicsEntity.Volume);
            }));

            entity.Add("UVRotation", voxel.UVRotation);
            entity.Add("UVOffset", voxel.UVOffset);
            entity.Add("CannotSuspendByDistance", voxel.CannotSuspendByDistance);
        }
コード例 #14
0
	/*
	 * If this voxel has already delcared an intention, remove it from the dict
	 *		if new intention doesn't work out, it will just get added back
	 * Check to see if this intention is possible
	 * 		if not, convert this into a Stay
	 * 		exception, if this voxel has already been moved by another, i don't want to override that intention, must merge it
	 *
	 * if this voxel will be moving, check to see if there's anything on top that will need to come along.
	 */
	private void DeclareVoxelIntention (DynamicVoxel vox, DynamicVoxel motivator, Vector3 intendedPos, Voxel.IntentionDelegate intendedFunc, bool involvesMovement, int priority, bool forceIntention)
	{
		Debug.Log ("Declare Voxel Intention " + vox + " pos: " + intendedPos + " func: " + intendedFunc);
		Vector3 oldIntendedPos = vox.GetIntendedPosition ();
		if (intendedNextPositions.ContainsKey (oldIntendedPos) && intendedNextPositions [oldIntendedPos] == vox) {
			intendedNextPositions.Remove (oldIntendedPos);
		}

		if (involvesMovement && !forceIntention) {
			bool valid = positionPossibleNextStep (vox, intendedPos);
			if (!valid) {
				intendedPos = vox.position;
				vox.HoldForStep ();
				intendedFunc = vox.Stay;
				priority = 0;
				involvesMovement = false;
			}
		}

		vox.SetIntention (motivator, intendedPos, priority, intendedFunc, involvesMovement);

		intendedPos = vox.GetIntendedPosition ();

		if (intendedNextPositions.ContainsKey (intendedPos) && intendedNextPositions [intendedPos] != vox) {
			ResolveConflict (vox, intendedNextPositions [intendedPos], intendedPos);
		} else {
			intendedNextPositions.Add (vox.GetIntendedPosition (), vox);
		}

		if (involvesMovement) {
//			Debug.Log("involvesMovement true");
			Vector3 abovePos = vox.position + Vector3.up;
			Voxel voxAbove = Level.Instance.GetVoxel (abovePos);
//			Debug.Log("voxAbove at pos " + (abovePos) + " ==  null " + (voxAbove == null));

			if (voxAbove != null) {
				DynamicVoxel dynVoxAbove = voxAbove.GetComponent<DynamicVoxel> ();
				if (dynVoxAbove != null) {
//					Debug.Log (dynVoxAbove + " is above " + vox + " and will be moved with it");
					dynVoxAbove.HoldForStep ();
					DeclareVoxelIntention (dynVoxAbove, vox, intendedPos + Vector3.up, dynVoxAbove.MoveDirection (intendedPos - vox.position), true, priority, false);
				}
			}
		}
	}
コード例 #15
0
ファイル: Level.cs プロジェクト: mbhuet/MastersProject
	public void AddDynamicVoxel(DynamicVoxel vox){
		dynamicVoxels.Add (vox);
	}
コード例 #16
0
ファイル: Level.cs プロジェクト: mbhuet/MastersProject
	public void RemoveDynamicVoxel(DynamicVoxel vox){
		if(dynamicVoxels.Contains(vox))
			dynamicVoxels.Add (vox);
	}
コード例 #17
0
        private static void explode(Main main, Voxel map, Voxel.Coord coord, Vector3 pos, int radius, float physicsRadius)
        {
            float distanceToCamera = (main.Camera.Position.Value - pos).Length();

            // Kaboom
            Sound.PostEvent(distanceToCamera < physicsRadius * 1.5f ? AK.EVENTS.PLAY_EXPLOSION_CLOSE : AK.EVENTS.PLAY_EXPLOSION, pos);

            Entity lightEntity = Factory.Get <PointLightFactory>().CreateAndBind(main);

            lightEntity.Serialize = false;
            PointLight light = lightEntity.Get <PointLight>();

            light.Color.Value       = new Vector3(1.3f, 1.1f, 0.9f);
            light.Attenuation.Value = 20.0f;
            light.Position.Value    = pos;
            lightEntity.Add(new Animation
                            (
                                new Animation.FloatMoveTo(light.Attenuation, 0.0f, 1.0f),
                                new Animation.Execute(light.Delete)
                            ));
            main.Add(lightEntity);

            SmokeFactory smokeFactory = Factory.Get <SmokeFactory>();

            for (int i = 0; i < 5; i++)
            {
                Entity smoke = smokeFactory.CreateAndBind(main);
                smoke.Get <Transform>().Position.Value = pos;
                main.Add(smoke);
            }

            ParticleEmitter.Emit(main, "Smoke", pos, physicsRadius * 0.4f, 250);

            Entity player = PlayerFactory.Instance;

            if (player != null && player.Active)
            {
                player.Get <CameraController>().Shake.Execute(pos, 50.0f);
            }

            const float physicsImpulse         = 70.0f;
            const float minPlayerDamage        = 0.1f;
            const float playerDamageMultiplier = 2.0f;

            // Remove the cells
            BlockFactory blockFactory = Factory.Get <BlockFactory>();

            foreach (Voxel m in Voxel.ActiveVoxels.ToList())
            {
                List <Voxel.Coord> removals = new List <Voxel.Coord>();

                Voxel.Coord c           = m.GetCoordinate(pos);
                Vector3     relativePos = m.GetRelativePosition(c);

                Quaternion quat = m.Entity.Get <Transform>().Quaternion;

                for (Voxel.Coord x = c.Move(Direction.NegativeX, radius - 1); x.X < c.X + radius; x.X++)
                {
                    for (Voxel.Coord y = x.Move(Direction.NegativeY, radius - 1); y.Y < c.Y + radius; y.Y++)
                    {
                        for (Voxel.Coord z = y.Move(Direction.NegativeZ, radius - 1); z.Z < c.Z + radius; z.Z++)
                        {
                            Voxel.State s = m[z];
                            if (s.ID == 0 || s.Permanent)
                            {
                                continue;
                            }

                            Vector3 cellPos = m.GetRelativePosition(z);
                            if ((cellPos - relativePos).Length() < radius - 1)
                            {
                                removals.Add(z);
                                if (random.NextDouble() > 0.5)
                                {
                                    Entity    block          = blockFactory.CreateAndBind(main);
                                    Transform blockTransform = block.Get <Transform>();
                                    blockTransform.Position.Value   = m.GetAbsolutePosition(cellPos);
                                    blockTransform.Quaternion.Value = Quaternion.CreateFromYawPitchRoll(((float)random.NextDouble() - 0.5f) * 2.0f * (float)Math.PI, ((float)random.NextDouble() - 0.5f) * 2.0f * (float)Math.PI, ((float)random.NextDouble() - 0.5f) * 2.0f * (float)Math.PI);
                                    s.ApplyToBlock(block);
                                    main.Add(block);
                                }
                            }
                        }
                    }
                }
                if (removals.Count > 0)
                {
                    m.Empty(removals);
                    m.Regenerate();
                }
            }

            // Damage the player
            if (player != null && player.Active)
            {
                Vector3 toPlayer = player.Get <Transform>().Position - pos;
                float   d        = toPlayer.Length();
                if (d < physicsRadius)
                {
                    float attenuation = 1.0f;
                    if (d > 0)
                    {
                        Voxel.GlobalRaycast(pos, toPlayer / d, d, delegate(int x, Voxel.t c)
                        {
                            Voxel.State s = Voxel.States.All[c];
                            if (s.Permanent)
                            {
                                attenuation = 0.0f;
                                return(true);
                            }
                            else if (s.Hard)
                            {
                                attenuation -= 0.6f;
                            }
                            else
                            {
                                attenuation -= 0.35f;
                            }
                            return(false);
                        });
                        attenuation = Math.Max(0, attenuation);
                    }
                    player.Get <Agent>().Damage.Execute(attenuation * (minPlayerDamage + (1.0f - (d / physicsRadius)) * playerDamageMultiplier));
                }
            }

            // Apply impulse to dynamic maps
            foreach (Voxel m in Voxel.ActiveVoxels)
            {
                DynamicVoxel dm = m as DynamicVoxel;
                if (dm == null)
                {
                    continue;
                }

                Vector3 toMap         = dm.Transform.Value.Translation - pos;
                float   distanceToMap = toMap.Length();
                toMap /= distanceToMap;

                toMap *= Math.Max(0.0f, 1.0f - (distanceToMap / physicsRadius)) * Math.Min(200.0f, dm.PhysicsEntity.Mass) * physicsImpulse;

                dm.PhysicsEntity.ApplyImpulse(dm.Transform.Value.Translation + new Vector3(((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f), toMap);
            }

            // Apply impulse to physics blocks
            foreach (Entity b in main.Get("Block"))
            {
                PhysicsBlock block         = b.Get <PhysicsBlock>();
                Vector3      fromExplosion = b.Get <Transform>().Position.Value - pos;
                float        distance      = fromExplosion.Length();
                if (distance > 0.0f && distance < physicsRadius)
                {
                    float blend = 1.0f - (distance / physicsRadius);
                    block.Box.LinearVelocity  += fromExplosion * blend * 10.0f / distance;
                    block.Box.AngularVelocity += new Vector3(((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f) * blend;
                }
            }
        }
コード例 #18
0
        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;

            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;
                }

                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);
                        }

                        if (jointDeleteBinding == null)
                        {
                            jointDeleteBinding = new CommandBinding(parent.Delete, delegate()
                            {
                                jointData.Parent.Value = null;
                            });
                            entity.Add(jointDeleteBinding);
                        }
                    }
                }
            };
            entity.Add(new CommandBinding(map.PhysicsUpdated, updateJoint));
            entity.Add(new NotifyBinding(rebuildJoint, jointData.Parent));
            entity.Add(new CommandBinding(entity.Delete, delegate()
            {
                if (joint != null && joint.Space != null)
                {
                    main.Space.Remove(joint);
                    joint = null;
                }
            }));

            entity.Add(new CommandBinding(map.OnSuspended, delegate()
            {
                if (joint != null && joint.Space != null)
                {
                    main.Space.Remove(joint);
                }
            }));
            entity.Add(new CommandBinding(map.OnResumed, delegate()
            {
                if (joint != null && joint.Space == null)
                {
                    main.Space.Add(joint);
                }
            }));

            entity.Add(new PostInitialization {
                rebuildJoint
            });

            if (main.EditorEnabled)
            {
                JointFactory.attachEditorComponents(entity, main, directional);
            }
        }
コード例 #19
0
ファイル: Level.cs プロジェクト: mbhuet/MastersProject
	public void MarkTempForDestruction(DynamicVoxel tempVox){
		tempsToDestroy.Add (tempVox);
	}
コード例 #20
0
ファイル: VoxelRip.cs プロジェクト: dsmo7206/Lemma
		public static void Consolidate(Main main, DynamicVoxel voxel, float interval = 1.0f)
		{
			int maxDistance = 12;
			Voxel closestVoxel = null;
			Voxel.Coord closestCoord = new Voxel.Coord();
			foreach (Voxel m in Voxel.ActivePhysicsVoxels)
			{
				if (m == voxel)
					continue;

				Voxel.Coord relativeCoord = m.GetCoordinate(voxel.Transform.Value.Translation);
				Voxel.Coord? closestFilled = m.FindClosestFilledCell(relativeCoord, maxDistance);
				if (closestFilled != null)
				{
					maxDistance = Math.Min(Math.Abs(relativeCoord.X - closestFilled.Value.X), Math.Min(Math.Abs(relativeCoord.Y - closestFilled.Value.Y), Math.Abs(relativeCoord.Z - closestFilled.Value.Z)));
					closestVoxel = m;
					closestCoord = closestFilled.Value;
				}
			}

			if (closestVoxel != null)
				VoxelRip.Consolidate(main, voxel, closestVoxel, closestCoord, interval);
		}
コード例 #21
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            PointLight light = entity.GetOrCreate <PointLight>("PointLight");

            light.Serialize = false;

            const float defaultLightAttenuation = 15.0f;

            light.Attenuation.Value = defaultLightAttenuation;

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

            light.Add(new Binding <Vector3>(light.Position, transform.Position));

            if (!main.EditorEnabled)
            {
                AkGameObjectTracker.Attach(entity);
                SoundKiller.Add(entity, AK.EVENTS.STOP_GLOWSQUARE);
                entity.Add(new PostInitialization
                {
                    delegate()
                    {
                        AkSoundEngine.PostEvent(AK.EVENTS.PLAY_GLOWSQUARE, entity);
                        AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_GLOWSQUARE_PITCH, -1.0f, entity);
                    }
                });
            }

            AI ai = entity.GetOrCreate <AI>("AI");

            ModelAlpha model = entity.GetOrCreate <ModelAlpha>();

            model.Add(new Binding <Matrix>(model.Transform, transform.Matrix));
            model.Filename.Value  = "AlphaModels\\box";
            model.Serialize       = false;
            model.DrawOrder.Value = 15;

            RaycastAIMovement movement  = entity.GetOrCreate <RaycastAIMovement>("Movement");
            Levitator         levitator = entity.GetOrCreate <Levitator>("Levitator");

            const float defaultModelScale = 1.0f;

            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));

                default:
                    return(new Vector3(1.0f, 1.0f, 1.0f));
                }
            }, ai.CurrentState));

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

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

            Agent agent = entity.GetOrCreate <Agent>();

            agent.Add(new Binding <Vector3>(agent.Position, transform.Position));

            RaycastAI raycastAI = entity.GetOrCreate <RaycastAI>("RaycastAI");

            raycastAI.Add(new TwoWayBinding <Vector3>(transform.Position, raycastAI.Position));
            raycastAI.Add(new Binding <Quaternion>(transform.Quaternion, raycastAI.Orientation));

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

            AI.Task updatePosition = new AI.Task
            {
                Action = delegate()
                {
                    raycastAI.Update();
                },
            };

            ai.Add(new AI.AIState
            {
                Name  = "Suspended",
                Tasks = new[] { checkOperationalRadius, },
            });

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

            ai.Add(new AI.AIState
            {
                Name  = "Idle",
                Enter = delegate(AI.AIState previous)
                {
                    AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_GLOWSQUARE_PITCH, -1.0f, entity);
                },
                Tasks = new[]
                {
                    checkOperationalRadius,
                    updatePosition,
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            raycastAI.Move(new Vector3(((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f));
                        }
                    },
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player");
                            if (a != null)
                            {
                                ai.CurrentState.Value = "Alert";
                            }
                        },
                    },
                },
            });

            ai.Add(new AI.AIState
            {
                Name  = "Alert",
                Enter = delegate(AI.AIState previous)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.STOP_GLOWSQUARE, entity);
                },
                Exit = delegate(AI.AIState next)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_GLOWSQUARE, entity);
                },
                Tasks = new[]
                {
                    checkOperationalRadius,
                    updatePosition,
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            if (ai.TimeInCurrentState > 3.0f)
                            {
                                ai.CurrentState.Value = "Idle";
                            }
                            else
                            {
                                Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player");
                                if (a != null)
                                {
                                    ai.TargetAgent.Value  = a.Entity;
                                    ai.CurrentState.Value = "Chase";
                                }
                            }
                        },
                    },
                },
            });

            AI.Task checkTargetAgent = new AI.Task
            {
                Action = delegate()
                {
                    Entity target = ai.TargetAgent.Value.Target;
                    if (target == null || !target.Active)
                    {
                        ai.TargetAgent.Value  = null;
                        ai.CurrentState.Value = "Idle";
                    }
                },
            };

            // Levitate

            const int levitateRipRadius = 4;

            Func <bool> tryLevitate = delegate()
            {
                Entity voxelEntity = raycastAI.Voxel.Value.Target;
                if (voxelEntity == null)
                {
                    return(false);
                }

                Voxel       map       = voxelEntity.Get <Voxel>();
                Voxel.Coord?candidate = map.FindClosestFilledCell(raycastAI.Coord, 3);

                if (!candidate.HasValue)
                {
                    return(false);
                }

                if (VoxelRip.Go(map, candidate.Value, levitateRipRadius, delegate(List <DynamicVoxel> spawnedMaps)
                {
                    foreach (DynamicVoxel spawnedMap in spawnedMaps)
                    {
                        if (spawnedMap[candidate.Value] != Voxel.States.Empty)
                        {
                            levitator.LevitatingVoxel.Value = spawnedMap.Entity;
                            break;
                        }
                    }
                }))
                {
                    levitator.GrabCoord.Value = candidate.Value;
                    return(true);
                }

                return(false);
            };

            Action delevitateMap = delegate()
            {
                Entity levitatingMapEntity = levitator.LevitatingVoxel.Value.Target;
                if (levitatingMapEntity == null || !levitatingMapEntity.Active)
                {
                    return;
                }

                DynamicVoxel dynamicMap = levitatingMapEntity.Get <DynamicVoxel>();
                VoxelRip.Consolidate(main, dynamicMap);
            };

            // Chase AI state

            ai.Add(new AI.AIState
            {
                Name  = "Chase",
                Enter = delegate(AI.AIState previous)
                {
                    AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_GLOWSQUARE_PITCH, 0.0f, entity);
                },
                Tasks = new[]
                {
                    checkOperationalRadius,
                    checkTargetAgent,
                    new AI.Task
                    {
                        Interval = 0.35f,
                        Action   = delegate()
                        {
                            raycastAI.Move(ai.TargetAgent.Value.Target.Get <Transform>().Position.Value - transform.Position);
                        }
                    },
                    updatePosition,
                    new AI.Task
                    {
                        Interval = 0.1f,
                        Action   = delegate()
                        {
                            Entity target          = ai.TargetAgent.Value.Target;
                            Vector3 targetPosition = target.Get <Transform>().Position;
                            if ((targetPosition - transform.Position).Length() < 15.0f)
                            {
                                if (tryLevitate())
                                {
                                    ai.CurrentState.Value = "Levitating";
                                }
                            }
                        }
                    }
                },
            });

            Action findNextPosition = delegate()
            {
                movement.LastPosition.Value = transform.Position.Value;
                float   radius = 5.0f;
                Vector3 center = ai.TargetAgent.Value.Target.Get <Transform>().Position;
                Vector3 candidate;
                do
                {
                    candidate = center + new Vector3((float)this.random.NextDouble() - 0.5f, (float)this.random.NextDouble(), (float)this.random.NextDouble() - 0.5f) * radius;
                    radius   += 1.0f;
                }while (!RaycastAI.DefaultPositionFilter(candidate));

                movement.NextPosition.Value  = candidate;
                movement.PositionBlend.Value = 0.0f;
            };

            ai.Add(new AI.AIState
            {
                Name  = "Levitating",
                Enter = delegate(AI.AIState previous)
                {
                    findNextPosition();
                },
                Exit = delegate(AI.AIState next)
                {
                    delevitateMap();
                    levitator.LevitatingVoxel.Value = null;

                    //volume.Value = defaultVolume;
                    //pitch.Value = 0.0f;
                },
                Tasks = new[]
                {
                    checkTargetAgent,
                    new AI.Task
                    {
                        Action = delegate()
                        {
                            //volume.Value = 1.0f;
                            //pitch.Value = 1.0f;
                            Entity levitatingMapEntity = levitator.LevitatingVoxel.Value.Target;
                            if (levitatingMapEntity == null || !levitatingMapEntity.Active || ai.TimeInCurrentState.Value > 8.0f)
                            {
                                Entity voxel = raycastAI.Voxel.Value.Target;
                                if (voxel != null && voxel.Active)
                                {
                                    raycastAI.Coord.Value = raycastAI.LastCoord.Value = voxel.Get <Voxel>().GetCoordinate(transform.Position);
                                }
                                raycastAI.Move(new Vector3(((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f));
                                ai.CurrentState.Value = "Alert";
                                return;
                            }

                            DynamicVoxel dynamicMap = levitatingMapEntity.Get <DynamicVoxel>();

                            movement.PositionBlend.Value += (main.ElapsedTime.Value / 1.0f);
                            if (movement.PositionBlend > 1.0f)
                            {
                                findNextPosition();
                            }

                            transform.Position.Value = Vector3.Lerp(movement.LastPosition, movement.NextPosition, movement.PositionBlend);

                            Vector3 grabPoint = dynamicMap.GetAbsolutePosition(levitator.GrabCoord);
                            Vector3 diff      = transform.Position.Value - grabPoint;
                            if (diff.Length() > 15.0f)
                            {
                                ai.CurrentState.Value = "Chase";
                                return;
                            }

                            diff *= (float)Math.Sqrt(dynamicMap.PhysicsEntity.Mass) * 0.5f;
                            dynamicMap.PhysicsEntity.ApplyImpulse(ref grabPoint, ref diff);
                        },
                    },
                },
            });

            this.SetMain(entity, main);
        }
コード例 #22
0
ファイル: VoxelRip.cs プロジェクト: dsmo7206/Lemma
		public static void Consolidate(Main main, DynamicVoxel voxel, Voxel targetVoxel, Voxel.Coord targetCoord, float interval = 1.0f)
		{
			if (targetVoxel != null)
			{
				// Combine this map with the other one

				Direction x = targetVoxel.GetRelativeDirection(voxel.GetAbsoluteVector(Vector3.Right));
				Direction y = targetVoxel.GetRelativeDirection(voxel.GetAbsoluteVector(Vector3.Up));
				Direction z = targetVoxel.GetRelativeDirection(voxel.GetAbsoluteVector(Vector3.Backward));

				if (x.IsParallel(y))
					x = y.Cross(z);
				else if (y.IsParallel(z))
					y = x.Cross(z);

				Voxel.Coord offset = new Voxel.Coord();
				float closestCoordDistance = float.MaxValue;
				Vector3 closestCoordPosition = targetVoxel.GetAbsolutePosition(targetCoord);
				lock (voxel.MutationLock)
				{
					foreach (Voxel.Coord c in voxel.Chunks.SelectMany(c => c.Boxes).SelectMany(b => b.GetCoords()))
					{
						float distance = (voxel.GetAbsolutePosition(c) - closestCoordPosition).LengthSquared();
						if (distance < closestCoordDistance)
						{
							closestCoordDistance = distance;
							offset = c;
						}
					}
				}
				Vector3 toLevitatingMap = voxel.Transform.Value.Translation - targetVoxel.GetAbsolutePosition(targetCoord);
				offset = offset.Move(voxel.GetRelativeDirection(-toLevitatingMap));

				Quaternion orientation = Quaternion.CreateFromRotationMatrix(voxel.Transform.Value);

				EffectBlockFactory blockFactory = Factory.Get<EffectBlockFactory>();

				int index = 0;
				List<Voxel.Coord> coords;
				lock (voxel.MutationLock)
					coords = voxel.Chunks.SelectMany(c => c.Boxes).SelectMany(b => b.GetCoords()).ToList();
				Voxel.Coord camera = voxel.GetCoordinate(main.Camera.Position);
				foreach (Voxel.Coord c in coords.OrderBy(c2 => new Vector3(c2.X - camera.X, c2.Y - camera.Y, c2.Z - camera.Z).LengthSquared()))
				{
					Voxel.Coord offsetFromCenter = c.Move(-offset.X, -offset.Y, -offset.Z);
					Voxel.Coord targetCoord2 = new Voxel.Coord();
					targetCoord2.SetComponent(x, offsetFromCenter.GetComponent(Direction.PositiveX));
					targetCoord2.SetComponent(y, offsetFromCenter.GetComponent(Direction.PositiveY));
					targetCoord2.SetComponent(z, offsetFromCenter.GetComponent(Direction.PositiveZ));
					targetCoord2 = targetCoord2.Move(targetCoord.X, targetCoord.Y, targetCoord.Z);
					if (targetVoxel[targetCoord2].ID == 0)
					{
						Entity blockEntity = blockFactory.CreateAndBind(main);
						c.Data.ApplyToEffectBlock(blockEntity.Get<ModelInstance>());
						EffectBlock effectBlock = blockEntity.Get<EffectBlock>();
						effectBlock.Offset.Value = targetVoxel.GetRelativePosition(targetCoord2);
						effectBlock.DoScale = false;
						effectBlock.StartPosition = voxel.GetAbsolutePosition(c);
						effectBlock.StartOrientation = orientation;
						effectBlock.TotalLifetime = (0.05f + (index * 0.0075f)) * interval;
						effectBlock.Setup(targetVoxel.Entity, targetCoord2, c.Data.ID);
						main.Add(blockEntity);
						index++;
					}
				}

				// Delete the map
				voxel.Entity.Delete.Execute();
			}
		}
コード例 #23
0
ファイル: VoxelRip.cs プロジェクト: schmittens/Lemma
        public static void Consolidate(Main main, DynamicVoxel voxel, Voxel targetVoxel, Voxel.Coord targetCoord, float interval = 1.0f)
        {
            if (targetVoxel != null)
            {
                // Combine this map with the other one

                Direction x = targetVoxel.GetRelativeDirection(voxel.GetAbsoluteVector(Vector3.Right));
                Direction y = targetVoxel.GetRelativeDirection(voxel.GetAbsoluteVector(Vector3.Up));
                Direction z = targetVoxel.GetRelativeDirection(voxel.GetAbsoluteVector(Vector3.Backward));

                if (x.IsParallel(y))
                {
                    x = y.Cross(z);
                }
                else if (y.IsParallel(z))
                {
                    y = x.Cross(z);
                }

                Voxel.Coord offset = new Voxel.Coord();
                float       closestCoordDistance = float.MaxValue;
                Vector3     closestCoordPosition = targetVoxel.GetAbsolutePosition(targetCoord);
                foreach (Voxel.Coord c in voxel.Chunks.SelectMany(c => c.Boxes).SelectMany(b => b.GetCoords()))
                {
                    float distance = (voxel.GetAbsolutePosition(c) - closestCoordPosition).LengthSquared();
                    if (distance < closestCoordDistance)
                    {
                        closestCoordDistance = distance;
                        offset = c;
                    }
                }
                Vector3 toLevitatingMap = voxel.Transform.Value.Translation - targetVoxel.GetAbsolutePosition(targetCoord);
                offset = offset.Move(voxel.GetRelativeDirection(-toLevitatingMap));

                Quaternion orientation = Quaternion.CreateFromRotationMatrix(voxel.Transform.Value);

                EffectBlockFactory blockFactory = Factory.Get <EffectBlockFactory>();

                int index = 0;
                List <Voxel.Coord> coords = voxel.Chunks.SelectMany(c => c.Boxes).SelectMany(b => b.GetCoords()).ToList();
                Voxel.Coord        camera = voxel.GetCoordinate(main.Camera.Position);
                foreach (Voxel.Coord c in coords.OrderBy(c2 => new Vector3(c2.X - camera.X, c2.Y - camera.Y, c2.Z - camera.Z).LengthSquared()))
                {
                    Voxel.Coord offsetFromCenter = c.Move(-offset.X, -offset.Y, -offset.Z);
                    Voxel.Coord targetCoord2     = new Voxel.Coord();
                    targetCoord2.SetComponent(x, offsetFromCenter.GetComponent(Direction.PositiveX));
                    targetCoord2.SetComponent(y, offsetFromCenter.GetComponent(Direction.PositiveY));
                    targetCoord2.SetComponent(z, offsetFromCenter.GetComponent(Direction.PositiveZ));
                    targetCoord2 = targetCoord2.Move(targetCoord.X, targetCoord.Y, targetCoord.Z);
                    if (targetVoxel[targetCoord2].ID == 0)
                    {
                        Entity blockEntity = blockFactory.CreateAndBind(main);
                        c.Data.ApplyToEffectBlock(blockEntity.Get <ModelInstance>());
                        EffectBlock effectBlock = blockEntity.Get <EffectBlock>();
                        effectBlock.Offset.Value     = targetVoxel.GetRelativePosition(targetCoord2);
                        effectBlock.DoScale          = false;
                        effectBlock.StartPosition    = voxel.GetAbsolutePosition(c);
                        effectBlock.StartOrientation = orientation;
                        effectBlock.TotalLifetime    = (0.05f + (index * 0.0075f)) * interval;
                        effectBlock.Setup(targetVoxel.Entity, targetCoord2, c.Data.ID);
                        main.Add(blockEntity);
                        index++;
                    }
                }

                // Delete the map
                voxel.Entity.Delete.Execute();
            }
        }
コード例 #24
0
ファイル: Spawner.cs プロジェクト: Educational-Repos/Lemma
        public void Update(float dt)
        {
            // Spawn an editor or a player if needed
            if (this.main.EditorEnabled)
            {
                this.main.Renderer.InternalGamma.Value = 0.0f;
                this.main.Renderer.Brightness.Value    = 0.0f;
                if (this.editor == null || !this.editor.Active)
                {
                    this.editor = Factory.Get <EditorFactory>().CreateAndBind(this.main);
                    FPSInput.RecenterMouse();
                    this.editor.Get <Editor>().Position.Value = this.lastEditorPosition;
                    this.editor.Get <FPSInput>().Mouse.Value  = this.lastEditorMouse;
                    this.StartSpawnPoint.Value     = this.lastEditorSpawnPoint;
                    this.StartSpawnPointGUID.Value = this.lastEditorSpawnPointGUID;
                    this.main.Add(this.editor);
                }
                else
                {
                    this.lastEditorPosition = this.editor.Get <Editor>().Position;
                    this.lastEditorMouse    = this.editor.Get <FPSInput>().Mouse;
                }
            }
            else
            {
                if (this.main.MapFile.Value == null || !this.CanSpawn || CameraStop.CinematicActive)
                {
                    return;
                }

                this.editor = null;

                bool createPlayer = PlayerFactory.Instance == null;

                if (this.mapJustLoaded)
                {
                    if (!createPlayer)
                    {
                        // We just loaded a save game
                        this.main.Renderer.InternalGamma.Value = 0.0f;
                        this.main.Renderer.Brightness.Value    = 0.0f;
                        this.PlayerSpawned.Execute();
                        this.respawnTimer = 0;
                    }
                }
                else if (createPlayer)
                {
                    if (this.respawnTimer == 0)
                    {
                        this.main.AddComponent(new Animation(this.FlashAnimation()));
                    }

                    if (this.respawnTimer > this.RespawnInterval)
                    {
                        bool spawnFound = false;

                        RespawnLocation foundSpawnLocation         = default(RespawnLocation);
                        Vector3         foundSpawnAbsolutePosition = Vector3.Zero;

                        if (string.IsNullOrEmpty(this.StartSpawnPoint) && this.StartSpawnPointGUID == 0)
                        {
                            // Look for an autosaved spawn point
                            Entity playerData = PlayerDataFactory.Instance;
                            if (playerData != null)
                            {
                                ListProperty <RespawnLocation> respawnLocations = playerData.Get <PlayerData>().RespawnLocations;
                                int   supportedLocations = 0;
                                float lowerLimit         = Factory.Get <LowerLimitFactory>().GetLowerLimit();
                                while (respawnLocations.Length > 0)
                                {
                                    RespawnLocation respawnLocation  = respawnLocations[respawnLocations.Length - 1];
                                    Entity          respawnMapEntity = respawnLocation.Map.Target;
                                    if (respawnMapEntity != null && respawnMapEntity.Active)
                                    {
                                        Voxel   respawnMap  = respawnMapEntity.Get <Voxel>();
                                        Vector3 absolutePos = respawnMap.GetAbsolutePosition(respawnLocation.Coordinate);
                                        if (respawnMap.Active &&
                                            absolutePos.Y > lowerLimit &&
                                            respawnMap.GetAbsoluteVector(respawnMap.GetRelativeDirection(Direction.PositiveY).GetVector()).Y > 0.5f &&
                                            Agent.Query(absolutePos, 0.0f, 20.0f) == null &&
                                            Rift.Query(absolutePos) == null &&
                                            Zone.CanSpawnAt(absolutePos))
                                        {
                                            Voxel.State state = respawnMap[respawnLocation.Coordinate];
                                            if (state != Voxel.States.Empty && state != Voxel.States.Infected && state != Voxel.States.HardInfected && state != Voxel.States.Floater)
                                            {
                                                supportedLocations++;
                                                DynamicVoxel dynamicMap = respawnMap as DynamicVoxel;
                                                if (dynamicMap == null || absolutePos.Y > respawnLocation.OriginalPosition.Y - 1.0f)
                                                {
                                                    Voxel.GlobalRaycastResult hit = Voxel.GlobalRaycast(absolutePos + new Vector3(0, 1, 0), Vector3.Up, 2);
                                                    if (hit.Voxel == null)
                                                    {
                                                        // We can spawn here
                                                        spawnFound                 = true;
                                                        foundSpawnLocation         = respawnLocation;
                                                        foundSpawnAbsolutePosition = absolutePos;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (supportedLocations >= 40 || (spawnFound && (foundSpawnAbsolutePosition - this.lastPlayerPosition).Length() > this.RespawnDistance))
                                    {
                                        if (supportedLocations > 3)                                         // We should try to spawn the player back at least a few steps
                                        {
                                            break;
                                        }
                                    }

                                    respawnLocations.RemoveAt(respawnLocations.Length - 1);
                                }
                            }
                        }

                        if (spawnFound)
                        {
                            // Spawn at an autosaved location
                            if (createPlayer)
                            {
                                this.spawn();
                            }
                            Vector3 absolutePos = foundSpawnLocation.Map.Target.Get <Voxel>().GetAbsolutePosition(foundSpawnLocation.Coordinate);
                            PlayerFactory.Instance.Get <Transform>().Position.Value = this.main.Camera.Position.Value = absolutePos + new Vector3(0, spawnHeightOffset, 0);

                            FPSInput.RecenterMouse();
                            PlayerFactory.Instance.Get <FPSInput>().Mouse.Value = new Vector2(foundSpawnLocation.Rotation, 0);
                        }
                        else
                        {
                            // Spawn at a spawn point
                            PlayerSpawn spawn       = null;
                            Entity      spawnEntity = null;
                            if (this.StartSpawnPointGUID != 0)
                            {
                                spawnEntity = this.main.GetByGUID(this.StartSpawnPointGUID);
                                if (spawnEntity != null)
                                {
                                    spawn = spawnEntity.Get <PlayerSpawn>();
                                }
                                this.lastEditorSpawnPointGUID  = this.StartSpawnPointGUID;
                                this.StartSpawnPointGUID.Value = 0;
                            }
                            else if (!string.IsNullOrEmpty(this.StartSpawnPoint.Value))
                            {
                                spawnEntity = this.main.GetByID(this.StartSpawnPoint);
                                if (spawnEntity != null)
                                {
                                    spawn = spawnEntity.Get <PlayerSpawn>();
                                }
                                this.lastEditorSpawnPoint  = this.StartSpawnPoint;
                                this.StartSpawnPoint.Value = null;
                            }

                            if (spawnEntity == null)
                            {
                                spawn       = PlayerSpawn.FirstActive();
                                spawnEntity = spawn == null ? null : spawn.Entity;
                            }

                            if (spawnEntity != null)
                            {
                                Vector3 pos = spawnEntity.Get <Transform>().Position;
                                main.Camera.Position.Value = pos;
                                WorldFactory.Instance.Get <World>().UpdateZones();
                                Voxel.GlobalRaycastResult hit = Voxel.GlobalRaycast(pos + new Vector3(0, 2, 0), Vector3.Down, 8, null, false, true);
                                if (hit.Voxel == null)
                                {
                                    // There is nowhere to spawn. Reload the map.
                                    this.respawnTimer = 0;
                                    IO.MapLoader.Load(this.main, this.main.MapFile);
                                    return;
                                }
                                else
                                {
                                    if (createPlayer)
                                    {
                                        this.spawn();
                                    }
                                    pos = hit.Position + new Vector3(0, spawnHeightOffset, 0);
                                    PlayerFactory.Instance.Get <Transform>().Position.Value = this.main.Camera.Position.Value = pos;

                                    if (spawn != null)
                                    {
                                        spawn.IsActivated.Value = true;
                                        FPSInput.RecenterMouse();
                                        PlayerFactory.Instance.Get <FPSInput>().Mouse.Value = new Vector2(spawn.Rotation, 0);
                                        spawn.OnSpawn.Execute();
                                    }
                                }
                            }
                        }

                        // When the player teleports to a new map, show the number of orbs and notes on that map
                        // If mapJustLoaded is true, we just loaded a save game
                        if (this.main.TotalTime < Spawner.DefaultRespawnInterval * 2 && !this.mapJustLoaded)
                        {
                            WorldFactory.Instance.Add(new Animation
                                                      (
                                                          new Animation.Delay(1.5f),
                                                          new Animation.Execute(delegate()
                            {
                                int notes = Note.UncollectedCount;
                                if (notes > 0)
                                {
                                    this.main.Menu.HideMessage(WorldFactory.Instance, this.main.Menu.ShowMessageFormat(WorldFactory.Instance, notes == 1 ? "\\one note" : "\\note count", notes), 3.0f);
                                }

                                int orbs = Collectible.ActiveCount;
                                if (orbs > 0)
                                {
                                    this.main.Menu.HideMessage(WorldFactory.Instance, this.main.Menu.ShowMessageFormat(WorldFactory.Instance, orbs == 1 ? "\\one orb" : "\\orb count", orbs), 3.0f);
                                }
                            })
                                                      ));
                        }

                        WorldFactory.Instance.Add(new Animation(this.EndFlashAnimation()));
                        this.respawnTimer = 0;

                        this.PlayerSpawned.Execute();

                        this.RespawnInterval = Spawner.DefaultRespawnInterval;
                        this.RespawnDistance = Spawner.DefaultRespawnDistance;
                    }
                    else
                    {
                        this.respawnTimer += dt;
                    }
                }
                else
                {
                    this.lastPlayerPosition = PlayerFactory.Instance.Get <Transform>().Position;
                }
            }
            this.mapJustLoaded = false;
        }
コード例 #25
0
	private void ResolveConflict (DynamicVoxel voxA, DynamicVoxel voxB, Vector3 disputedPos)
	{
//		Debug.Log ("Conflict between " + voxA + " and " + voxB + " over " + disputedPos);
		intendedNextPositions.Remove (disputedPos);

		int voxAPriority = voxA.GetIntentionPriority ();
		int voxBPriority = voxB.GetIntentionPriority ();

		//EAUAl priority, no one gets to move
		if (voxAPriority == voxBPriority) {
//			Debug.Log ("Equal Priority " + voxAPriority + ", no one moves");

			voxA.HoldForStep ();
			voxB.HoldForStep ();
			DeclareVoxelIntention (voxA, voxB, voxA.position, voxA.Stay, true, 0, true);
			DeclareVoxelIntention (voxB, voxA, voxB.position, voxB.Stay, true, 0, true);

		} else if (voxAPriority < voxBPriority) {
//			Debug.Log (voxA + " has priority.");

			DeclareVoxelIntention (voxA, voxA, disputedPos, voxA.GetIntendedMoveFunc (), true, voxAPriority, true);
			voxB.HoldForStep ();
			DeclareVoxelIntention (voxB, voxA, voxB.position, voxB.Stay, true, 0, true);

		} else if (voxBPriority < voxAPriority) {
//			Debug.Log (voxB + " has priority.");

			DeclareVoxelIntention (voxB, voxB, disputedPos, voxB.GetIntendedMoveFunc (), true, voxBPriority, true);
			voxA.HoldForStep ();
			DeclareVoxelIntention (voxA, voxB, voxA.position, voxA.Stay, true, 0, true);
		}	
	}