Exemple #1
0
    /// <summary>
    /// Construct a new AudioEmitter3D.  This will automatically start the specified sound playing.
    /// </summary>
    /// <param name="parentObj">The GameObj3D this sound is attached to.  You may specify "null".</param>
    /// <param name="sound">The sound to play.  You may specify "null".</param>
    public AudioEmitter3D(GameObj3D parentObj, string sound, Vector3? offset)
    {
        m_parentObj = parentObj;
        m_offset = Vector3.Zero;
        if (null != offset)
        {
            m_offset = (Vector3)offset;
        }

        //set up the emitter
        m_emitter = new AudioEmitter();
        Matrix objMat = Matrix.Identity;
        if (null != parentObj)
        {
            objMat = m_parentObj.GetMatrix();
        }
        m_emitter.Forward = objMat.Forward;
        m_emitter.Up = objMat.Up;
        m_emitter.Position = Vector3.Transform(m_offset, objMat);
        m_emitter.Velocity = Vector3.Zero;

        m_oldPos = m_emitter.Position;

        m_sound.Invalidate();

        if (null != sound)
            PlaySound(sound);
    }
 //Call this method to play a sound
 public void SoundPlayer(string name, AudioListener listener, AudioEmitter emitter)
 {
     foreach (Sound sound in AllSounds)
     {
         if (sound.Name == name)
         {
             if (sound.Type == "SoundEffect")
                 sound.PlaySound();
             if (sound.Type == "SoundEffect3D")
                 sound.Play3DSound(listener, emitter);
             if (sound.Type == "LoopedEffect")
                 sound.PlaySound();
         }
     }
 }
Exemple #3
0
        protected virtual void Start()
        {
            // Events callback
            m_FPController.PreJumpEvent   += CameraBraceForJump;
            m_FPController.JumpEvent      += CameraJump;
            m_FPController.LandingEvent   += CameraLanding;
            m_FPController.VaultEvent     += Vault;
            m_FPController.GettingUpEvent += Vault;

            m_HealthController.ExplosionEvent += GrenadeExplosion;
            m_HealthController.HitEvent       += Hit;

            // Input buttons
            m_LeanRight = InputManager.FindButton("Lean Right");
            m_LeanLeft  = InputManager.FindButton("Lean Left");
            m_RunButton = InputManager.FindButton("Run");

            // AudioSources
            m_PlayerGenericSource = AudioManager.Instance.RegisterSource("[AudioEmitter] Generic", transform.root);
        }
Exemple #4
0
        public void Play3D(string id, AudioListener listener, AudioEmitter emitter)
        {
            id = id.Trim();

            if (dictionary.ContainsKey(id))
            {
                Cue cue = dictionary[id];
                SoundEffectInstance soundEffectInstance = dictionary[id].SoundEffect.CreateInstance();

                soundEffectInstance.Volume   = cue.Volume;
                soundEffectInstance.Pitch    = cue.Pitch;
                soundEffectInstance.Pan      = cue.Pan;
                soundEffectInstance.IsLooped = cue.IsLooped;
                soundEffectInstance.Apply3D(listener, emitter);
                soundEffectInstance.Play();

                //store in order to support later pause and stop functionality
                listInstances2D.Add(new KeyValuePair <string, SoundEffectInstance>(id, soundEffectInstance));
            }
        }
Exemple #5
0
        public static void Initialize()
        {
            musicVolume = 1f;
            soundVolume = 1f;

            muted = false;

            sfxInstances = new List <Sfx3D>();

            //soundEffect = SoundEffect.FromStream(File.OpenRead(G.exeDir + "\\Content\\Sounds\\flashlight_on.wav"));
            //sfx = new SoundEffect(File.ReadAllBytes(G.exeDir + "\\Content\\Sounds\\flashlight_on.wav"), 44100, AudioChannels.Stereo);
            emitter  = new AudioEmitter();
            listener = new AudioListener();

            cameraTransform = Matrix.Identity;

            musicInstances = new List <Music>();

            //PlaySound3D("flashlight_on", new Vector3(10f,0,0));
        }
Exemple #6
0
        private void UpdateSoundEffectPack(SoundEffectPack _pack)
        {
            AudioEmitter emitter = _pack.m_audioEmiiter;

            emitter.Position = m_gameObject.AbsPosition + Offset;
            VelocityEstimator velocityEstimator =
                m_gameObject.GetComponent(typeof(VelocityEstimator).ToString())
                as VelocityEstimator;

            if (velocityEstimator != null)
            {
                emitter.Velocity = velocityEstimator.Velocity;
            }

            Camera camera = Mgr <Camera> .Singleton;

            _pack.UpdateListener(camera.CameraPosition, camera.Forward,
                                 camera.Up, camera.Velocity);
            _pack.ApplyUpdate();
        }
 //Call this method to play a sound
 public void SoundPlayer(string name, AudioListener listener, AudioEmitter emitter)
 {
     foreach (Sound sound in AllSounds)
     {
         if (sound.Name == name)
         {
             if (sound.Type == "SoundEffect")
             {
                 sound.PlaySound();
             }
             if (sound.Type == "SoundEffect3D")
             {
                 sound.Play3DSound(listener, emitter);
             }
             if (sound.Type == "LoopedEffect")
             {
                 sound.PlaySound();
             }
         }
     }
 }
Exemple #8
0
        public void Play(SoundEffect se, Vector2 position)
        {
            if (se == null)
            {
                return;
            }
            SoundEffectInstance inst = se.CreateInstance();

            AudioEmitter ae = new AudioEmitter();

            ae.Position = new Vector3(position.X, position.Y, 0);

            AudioListener al = new AudioListener();

            al.Position = new Vector3(level.getClientPlayer().Position.X, level.getClientPlayer().Position.Y, 0);

            inst.Apply3D(al, ae);
            inst.Play();

            sounds.Add(inst);
        }
Exemple #9
0
        /// <summary>
        /// Trova un emitter di tipo SFX libero. Se non esiste lo crea.
        /// </summary>
        /// <returns>Un AudioEmitter libero.</returns>
        private AudioEmitter FindFreeSFXEmitter()
        {
            for (int i = 0; i < emittersList.Count - 1; i++)
            {
                if (emittersList[i].Type == EmitterType.sfx)
                {
                    if (!emittersList[i].Source.isPlaying)
                    {
                        return(emittersList[i]);
                    }
                }
            }

            AudioEmitter newEmitter = new AudioEmitter {
                Type = EmitterType.sfx, Source = this.gameObject.AddComponent <AudioSource>()
            };

            newEmitter.Source.volume = 1.0f;
            emittersList.Add(newEmitter);
            return(emittersList[emittersList.Count - 1]);
        }
Exemple #10
0
        public void Play3DSound(SoundEffectInstance e, Vector3 position)
        {
            AudioListener al = new AudioListener();

            al.Forward  = Vector3.Normalize(currentCamera.LookAt - currentCamera.Position);
            al.Up       = Vector3.Normalize(currentCamera.ObjUp);
            al.Position = currentCamera.Position;
            AudioEmitter ae = new AudioEmitter();

            ae.Position = (position - currentCamera.Position) + currentCamera.Position;
            //ae.Position = position;

            e.Apply3D(al, ae);
            //if (e.State == SoundState.Stopped)
            //{
            if (Vector3.Distance(currentCamera.Position, position) <= GameConsts.SoundDistance)
            {
                e.Play();
            }
            //}
        }
Exemple #11
0
        public void PlaySound(string _soundName, Vector3 _position,
                              Vector3 _forward, Vector3 _up, Vector3 _velocity,
                              float _randomVolumeRange = 0.0f, float _randomPitchRange = 0.0f)
        {
            SoundEffect soundEffect = Mgr <CatProject> .Singleton.contentManger.Load <SoundEffect>
                                          (_soundName);

            // get from limit
            if (!GetSoundFromLimit(_soundName))
            {
                return;
            }

            SoundEffectInstance soundEffectInstance = soundEffect.CreateInstance();

            soundEffectInstance.Pitch =
                _randomPitchRange * 2.0f * ((float)m_random.NextDouble() - 0.5f);

            soundEffectInstance.Volume = 1.0f -
                                         _randomVolumeRange * (float)m_random.NextDouble();
            AudioEmitter  audioEmitter  = new AudioEmitter();
            AudioListener audioListener = new AudioListener();

            audioListener.Position    = Mgr <Camera> .Singleton.CameraPosition;
            audioListener.Forward     = Mgr <Camera> .Singleton.Forward;
            audioListener.Up          = Mgr <Camera> .Singleton.Up;
            audioListener.Velocity    = Mgr <Camera> .Singleton.Velocity;
            audioEmitter.DopplerScale = 10.0f;
            audioEmitter.Position     = _position;
            audioEmitter.Forward      = _forward;
            audioEmitter.Up           = _up;
            audioEmitter.Velocity     = _velocity;
            soundEffectInstance.Apply3D(audioListener, audioEmitter);
            SoundEffectPack soundEffectPack =
                new SoundEffectPack(_soundName, soundEffectInstance,
                                    audioEmitter, audioListener);

            m_soundBank.Add(soundEffectPack);
            soundEffectInstance.Play();
        }
Exemple #12
0
        public CSound(SoundEffect sound, bool isLooped, AudioListener listener = null, AudioEmitter emitter = null, float delay = 0f, float volume = 1f, float pitch = 0f, float pan = 0f)
        {
            this._sound = sound;

            this._soundInstance     = _sound.CreateInstance();
            _soundInstance.IsLooped = isLooped; // Only for sound instance

            this._delay = delay;

            this._soundInstance.Volume = volume;
            this._soundInstance.Pitch  = pitch;
            this._soundInstance.Pan    = pan;

            this._audioListener = listener;
            this._audioEmitter  = emitter;

            // If we want to place the sound in the 3D world
            if (_audioEmitter != null && _audioListener != null)
            {
                _soundInstance.Apply3D(_audioListener, _audioEmitter);
            }
        }
        protected virtual void EventDispatcher_Sound3DChanged(EventData eventData)
        {
            //control 3D sounds through events
            if (eventData.EventType != EventActionType.OnStopAll)
            {
                string cueName = eventData.AdditionalParameters[0] as string;

                if (eventData.EventType == EventActionType.OnPlay)
                {
                    //what object generated the sound?
                    AudioEmitter audioEmitter = eventData.AdditionalParameters[1] as AudioEmitter;
                    this.Play3DCue(cueName, audioEmitter);
                }
                else if (eventData.EventType == EventActionType.OnPause)
                {
                    this.Pause3DCue(cueName);
                }
                else if (eventData.EventType == EventActionType.OnResume)
                {
                    this.Resume3DCue(cueName);
                }
                else if (eventData.EventType == EventActionType.OnStop)
                {
                    this.Stop3DCue(cueName, AudioStopOptions.Immediate);
                }
            }
            else //OnStopAll - notice that the AdditionalParameters[0] parameter is now used to send the stop option (vs. above where it sent the cue name). be careful!
            {
                //since we can only pass refereneces in AdditionalParameters and AudioStopOption is an enum (i.e. a primitive type) then we need to hack the code a little
                if ((int)eventData.AdditionalParameters[0] == 0)
                {
                    this.StopAll3DCues(AudioStopOptions.Immediate);
                }
                else
                {
                    this.StopAll3DCues(AudioStopOptions.AsAuthored);
                }
            }
        }
Exemple #14
0
        SoundEffectInstance Play(SoundEffect sf, AudioEmitter emitter, float volume, float pitch, bool loop)
        {
            unsafe
            {
                //MXF.Vector3* tempPointer1 = (MXF.Vector3*)(&listener);
                //this.Listener.Position = *tempPointer1;

                //MXF.Vector3* tempPointer2 = (MXF.Vector3*)(&emitter);
                //this.Emitter.Position = *tempPointer2;

                //this.Listener.Position = *tempPointer1;
                //this.Emitter.Position = *tempPointer2;
                SoundEffectInstance inst = sf.CreateInstance();
                inst.Apply3D(listener, emitter);
                inst.Volume   = volume;
                inst.Pitch    = pitch;
                inst.IsLooped = loop;

                //return sf.Play3D(listener, emitter, volume * Volume, pitch, loop);
                inst.Play();
                return(inst);
            }
        }
Exemple #15
0
    /// <summary>
    /// Attempts to play the sound with 3D effects.
    /// Returns a Handle to the AudioCue that gets played.
    /// </summary>
    /// <param name="soundName">The name of the sound to play.</param>
    public AudioHandle PlaySound3D(String soundName, AudioEmitter emitter)
    {
        AudioHandle handle = m_cuePool.Allocate();
        AudioCue    cue    = m_cuePool.GetItem(handle);

        if (null != cue)
        {
            System.Diagnostics.Debug.Assert(cue.m_state == AudioCue.State.AVAILABLE);
            System.Diagnostics.Debug.Assert(cue.m_cue == null);
            cue.SetUp(m_soundBank, soundName);
            cue.m_cue.Apply3D(m_listener, emitter);
            cue.Play();
#if AUDIO_DEBUG
            ++m_numPlaying;
            ++m_numPlayed;
        }
        else
        {
            ++m_numFailed;
#endif
        }
        return(handle);
    }
Exemple #16
0
    void UpdateDominant()
    {
        AudioEmitter dom = null;

        foreach (GameObject audioEmitter in audioEmitters)
        {
            if (dom == null)
            {
                dom = audioEmitter.GetComponent <AudioEmitter>();
            }
            else
            {
                if (dom.priority <= audioEmitter.GetComponent <AudioEmitter>().priority)
                {
                    if (dom.dampenToPercent >= audioEmitter.GetComponent <AudioEmitter>().dampenToPercent)
                    {
                        dom = audioEmitter.GetComponent <AudioEmitter>();
                    }
                }
            }
        }
        dominant = dom;
    }
        public UnitEntity(int id, String name, GameClassConfig classcfg, int modelHair, int modelFace, int maxHP, int maxSP, GameMain game, ContentManager content, GraphicsDeviceManager graphics, SpriteBatch spriteBatch, SpriteFont charNameFont, SpriteFont charDamageFont, Texture2D whiteRect, GameModelBank modelBank, GameItemBank itemBank, AudioSystem audioSystem, ParticlePreset particleManager)
        {
            this.id             = id;
            name                = name.Replace("'58'", ":");
            name                = name.Replace("'59'", ";");
            name                = name.Replace("'32'", " ");
            name                = name.Replace("'39'", "'");
            this.name           = name;
            this.game           = game;
            this.content        = content;
            this.graphics       = graphics;
            this.spriteBatch    = spriteBatch;
            this.classcfg       = classcfg;
            this.modelBank      = modelBank;
            this.itemBank       = itemBank;
            this.charNameFont   = charNameFont;
            this.charDamageFont = charDamageFont;
            this.whiteRect      = whiteRect;
            short modelKey = classcfg.modelID;

            model = new GameModelNode(content, modelBank);
            model.Load(modelKey);
            model.Rotation = modelBank.getModelRotation(modelKey);
            model.Position = modelBank.getModelPosition(modelKey);
            model.Scale    = modelBank.getModelScale(modelKey);
            model.playClip((short)state, true);
            this.maxHP           = this.curHP = maxHP;
            this.maxSP           = this.curSP = maxSP;
            this.audioEmitter    = new AudioEmitter();
            this.audioSystem     = audioSystem;
            this.particleManager = particleManager;
            for (int i = 0; i < listDamageSize; ++i)
            {
                listDamageValue[i] = -1;
                listDamageTime[i]  = -1;
            }
        }
        protected virtual void Start()
        {
            // References
            m_FPController               = GetComponent <FirstPersonCharacterController>();
            m_BloodSplashEffect          = GetComponentInChildren <BloodSplashEffect>();
            m_FPController.LandingEvent += FallDamage;

            // Audio Sources
            m_PlayerHealthSource = AudioManager.Instance.RegisterSource("[AudioEmitter] CharacterHealth", transform.root);
            m_PlayerBreathSource = AudioManager.Instance.RegisterSource("[AudioEmitter] CharacterGeneric", transform.root);

            // Body parts
            for (int i = 0, bodyPartsCount = m_BodyParts.Count; i < bodyPartsCount; i++)
            {
                if (!m_BodyParts[i])
                {
                    continue;
                }

                m_BodyParts[i].Init(this);
                m_TotalVitality += m_BodyParts[i].Vitality;
            }
            m_CurrentVitality = m_TotalVitality;
        }
        /// <summary>
        /// Plays the draw animation.
        /// </summary>
        public void Draw()
        {
            if (!m_Animator)
            {
                return;
            }

            if (!m_Draw)
            {
                return;
            }

            if (m_DrawAnimation.Length == 0)
            {
                return;
            }

            // Normalizes the playing speed.
            m_Animator.speed = 1;

            m_Animator.Play(m_DrawAnimation);
            m_PlayerBodySource = AudioManager.Instance.RegisterSource("[AudioEmitter] CharacterBody", m_FPController.transform.root, spatialBlend: 0);
            m_PlayerBodySource.ForcePlay(m_DrawSound, m_DrawVolume);
        }
Exemple #20
0
        private static void PlaySound(string cueName, Vector2 sourceTilePos)
        {
            try
            {
                SoundBank soundBank = ModEntry.GetHelper().Reflection.GetField <SoundBank>(Game1.soundBank as SoundBankWrapper, "soundBank").GetValue();

                Cue           cue      = soundBank.GetCue(cueName);
                AudioListener listener = new AudioListener
                {
                    Position = new Vector3(Game1.player.Position, 0)
                };
                AudioEmitter emitter = new AudioEmitter
                {
                    Position = new Vector3(sourceTilePos * Game1.tileSize, 0)
                };

                cue.Apply3D(listener, emitter);
                cue.Play();
            }
            catch (System.Exception e)
            {
                ModEntry.Log("Error while playing sound: " + e.Message);
            }
        }
        public override void Update(GameTime gameTime)
        {
            if (m_screen.IsActive)
            {
                m_killTime -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

            //if ((float)gameTime.TotalGameTime.TotalSeconds > m_killTime)
            if (m_killTime < 0.0f)
            {
                bDead = true;
                // Cue c = Game1.Audio.PlaySound("sfx_cannonball_hit_water");
                Cue c = Game1.Audio.GetCue("sfx_cannonball_hit_water");

                AudioListener al = new AudioListener();
                al.Position = new Vector3(m_screen.Player.Position, 0);
                al.Up       = Vector3.Backward;
                al.Forward  = Vector3.Up;

                AudioEmitter ae = new AudioEmitter();
                ae.Position = new Vector3(Position, 0);
                ae.Up       = Vector3.Backward;
                ae.Forward  = Vector3.Up;

                c.Apply3D(al, ae);
                Game1.Audio.PlayCue(c);
                c.SetVariable("Distance", (m_screen.Player.Position - Position).Length());

                Watersplash w = new Watersplash(Game);
                w.Initialize(10, Position, true);

                //Game1.Audio.SetParameter("sfx_cannonball_hit_water", "Distance", (m_screen.Player.Position - Position).Length());
            }



            m_obb.Orientation = Rotation;
            m_obb.Center      = Position;
            m_obb.CalculateAxis();

            for (Actor a = Actors.First.Value; a != null; a = a.NextActor)
            {
                if (a is PDVehicle)
                {
                    if (a != Owner)
                    {
                        if ((a as PDVehicle).Obb.TestOBBOBB(Obb))
                        {
                            SpriteEffect e = new EffectCannonFire(Game);
                            e.Initialize(10, Position, true);

                            bDead = true;

                            // Cue c = Game1.Audio.PlaySound("sfx_cannonball_hit");
                            Cue           c  = Game1.Audio.GetCue("sfx_cannonball_hit");
                            AudioListener al = new AudioListener();
                            al.Position = new Vector3(m_screen.Player.Position, 0);
                            al.Up       = Vector3.Backward;
                            al.Forward  = Vector3.Up;

                            AudioEmitter ae = new AudioEmitter();
                            ae.Position = new Vector3(Position, 0);
                            ae.Up       = Vector3.Backward;
                            ae.Forward  = Vector3.Up;

                            c.Apply3D(al, ae);
                            Game1.Audio.PlayCue(c);
                            c.SetVariable("Distance", (m_screen.Player.Position - Position).Length());
                            // Game1.Audio.SetParameter("sfx_cannonball_hit", "Distance", (m_screen.Player.Position - Position).Length());

                            // Damage target
                            (a as PDVehicle).Damage(Damage);
                        }
                    }
                }
            }

            base.Update(gameTime);
        }
 public void PlayCue(string name, AudioListener listener, AudioEmitter emitter)
 {
     soundBank.PlayCue(name, listener, emitter);
 }
        public void TestApply3D()
        {
            var list = new AudioListener();
            var emit = new AudioEmitter();
            var monoInst = continousMonoSoundEffect.CreateInstance();
            var stereoInst = continousStereoSoundEffect.CreateInstance();
            monoInst.IsLooped = true;
            stereoInst.IsLooped = true;

            ////////////////////////////////////////////////////////////////////////////////////////
            // 1. Check that Apply3D for an Disposed instance throw the 'ObjectDisposedException'
            var dispInst = monoSoundEffect.CreateInstance();
            dispInst.Dispose();
            Assert.Throws<ObjectDisposedException>(() => dispInst.Apply3D(list, emit), "SoundEffectInstance.Apply3D did not throw the 'ObjectDisposedException' when called from a disposed object.");

            ////////////////////////////////////////////////////////////////////////////////////////
            // 2. Check that Apply3D with null arguments throw the 'ArgumentNullException'
            Assert.Throws<ArgumentNullException>(() => monoInstance.Apply3D(null, emit), "SoundEffectInstance.Apply3D did not throw the 'ArgumentNullException' with a null listener.");
            Assert.Throws<ArgumentNullException>(() => monoInstance.Apply3D(list, null), "SoundEffectInstance.Apply3D did not throw the 'ArgumentNullException' with a null emitter.");
           
            /////////////////////////////////////////////////////////////////////////////////////////////
            // 3. Check that the sound is not modified when applying 3D at same position with mono sound
            monoInst.Play();
            Utilities.Sleep(1000);
            monoInst.Apply3D(list, emit);
            Utilities.Sleep(1000);
            monoInst.Stop();
            Utilities.Sleep(1000);
            
            ///////////////////////////////////////////////////////////////////////////////////
            // 4. Check that Apply3D throws InvalidOperationException when used on stereo sound
            Assert.Throws<InvalidOperationException>(() => stereoInst.Apply3D(list, emit), "InvalidOperationException has not been thrown when used on stereo-sound.");
            
            /////////////////////////////////////////////////////
            // 5. Check that mono signal attenuate with distance
            monoInst.Play();
            var currentDist = 0f;
            while (currentDist < 5)
            {
                emit.Position = new Vector3(0, 0, currentDist);
                monoInst.Apply3D(list, emit);

                currentDist += 0.01f;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            
            ////////////////////////////////////////////////////////////////////////////////
            // 6. Check that signal do not attenuate when we move both emitter and listener
            monoInst.Play();
            currentDist = 0f;
            while (currentDist < 5)
            {
                emit.Position = new Vector3(0, 0, currentDist);
                list.Position = new Vector3(0, 0, currentDist);
                monoInst.Apply3D(list, emit);
            
                currentDist += 0.01f;
            
                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            
            //////////////////////////////////////////////////////////////////////////////////////
            // 7. Check that attenuation increase/decrease when modifying DistaceScale parameter
            monoInst.Play();
            var currentScale = 2f;
            list.Position = Vector3.Zero;
            emit.Position = Vector3.One;
            while (currentScale > 0.01f )
            {
                emit.DistanceScale = currentScale;
                monoInst.Apply3D(list, emit);
            
                currentScale -= 0.005f;
            
                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            
            ////////////////////////////////////////////////////////////////////////////////////////////////
            // 8. Check that mono the localization works properly by turning the emiter around the listener
            // Should start from the front, go to the right, go to the back, go to the left, and finnaly go back to the front.
            monoInst.Play();
            var angle = 0f;
            emit.DistanceScale = 1;
            while (angle > -2*(float)Math.PI)
            {
                const float Offset = (float) Math.PI / 2;
                emit.Position = new Vector3((float)Math.Cos(angle + Offset), 0, (float)Math.Sin(angle + Offset));
            
                monoInst.Apply3D(list, emit);
            
                angle -= 0.005f;
            
                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 9. Check that the sound frequency is modified properly when object move away and goes back to the listener (doppler effect)
            monoInst.Play();
            var speed = 0f;
            const float SpeedLimit = 500f;
            var sign = 1f;
            emit.Position = new Vector3(0,0,1);
            while (speed > -SpeedLimit)
            {
                emit.Velocity = new Vector3(0,0,speed);
            
                monoInst.Apply3D(list, emit);
            
                speed += sign * 0.005f * SpeedLimit;
            
                if (speed > SpeedLimit)
                {
                    sign = -1f;
                    speed = 0;
                }
            
                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 10. Check that the sound frequency is not modified when both objects move away at same speed (doppler effect)
            monoInst.Play();
            speed = 0f;
            while (speed < SpeedLimit)
            {
                emit.Velocity = new Vector3(0, 0, speed);
                list.Velocity = new Vector3(0, 0, speed);
            
                monoInst.Apply3D(list, emit);
            
                speed += 0.005f * SpeedLimit;
                
                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(600);
            
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 11. Check the doppler effect influence is modified properly when DopplerScale changes (should increase)
            monoInst.Play();
            var dopplerScale = 0.1f;
            emit.Position = new Vector3(0, 0, 1);
            emit.Velocity = new Vector3(0, 0, 10);
            list.Velocity = Vector3.Zero;
            while (dopplerScale < 50f)
            {
                emit.DopplerScale = dopplerScale;
            
                monoInst.Apply3D(list, emit);
            
                dopplerScale *= 1.01f;
            
                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            emit.DopplerScale = 1;

            /////////////////////////////////////////////////////////
            // 12. Check that Apply3D does not perturb Volume value.
            var contInst = continousMonoSoundEffect.CreateInstance();
            contInst.IsLooped = true;
            contInst.Play();
            var volume = 1f;
            sign = -1f;
            while (volume <= 1f)
            {
                contInst.Volume = volume;
                contInst.Apply3D(new AudioListener(), new AudioEmitter());
                Assert.AreEqual(MathUtil.Clamp(volume, 0f, 1f), contInst.Volume, "Volume of continous sound is not what it should be.");
            
                volume += sign * 0.01f;

                if (volume < 0)
                    sign = 1f;

                Utilities.Sleep(10);
            }
            contInst.Stop();
            Utilities.Sleep(1000);

            ////////////////////////////////////////////////
            // 13. Check that Apply3D reset the Pan value.
            contInst.Play();
            contInst.Pan = 1;
            Utilities.Sleep(1000);
            contInst.Apply3D(new AudioListener(), new AudioEmitter { Position = new Vector3(-1,0,0)});
            Assert.AreEqual(0, contInst.Pan, "The Pan value has not been reset.");
            Utilities.Sleep(1000);
            contInst.Stop();

            contInst.Dispose();
            stereoInst.Dispose();
        }
Exemple #24
0
        public override void Update(GameTime gameTime)
        {
            // Set the correct animation based on Velocity/Throttle & Rotation

            // Lean percentage that increases when you hold down turning and normalizes when you don't
            // The Lean percentage is adjusted by velocity/throttle so that you can't lean hard with low velocity

            if (m_health <= 0)
            {
                bDead = true;
                // Cue c = Game1.Audio.PlaySound("sfx_ship_sink");
                Cue           c  = Game1.Audio.GetCue("sfx_ship_sink");
                AudioListener al = new AudioListener();
                al.Position = new Vector3(m_screen.Player.Position, 0);
                al.Up       = Vector3.Backward;
                al.Forward  = Vector3.Up;

                AudioEmitter ae = new AudioEmitter();
                ae.Position = new Vector3(Position, 0);
                ae.Up       = Vector3.Backward;
                ae.Forward  = Vector3.Up;

                c.Apply3D(al, ae);
                Game1.Audio.PlayCue(c);


                c.SetVariable("Distance", (Screen.Player.Position - Position).Length());

                Wreckage w = new Wreckage(Game);
                w.Initialize(m_gold, Silk, Spices, Leather, Rum, Iron, Coal, Rope, Tools);
                w.Position = Position;

                for (int i = 0; i < 10; i++)
                {
                    EffectCannonFire a = new EffectCannonFire(Game);
                    a.Initialize(10, Position + new Vector2(Game1.Rand.Next(-40, 40), Game1.Rand.Next(-40, 40)), true);
                }

                for (int i = 0; i < 10; i++)
                {
                    Watersplash a = new Watersplash(Game);
                    a.Initialize(10, Position + new Vector2(Game1.Rand.Next(-40, 40), Game1.Rand.Next(-40, 40)), true);
                }

                int n = Game1.Rand.Next(0, GameplayScreen.m_waypoints.Length);

                int type = Game1.Rand.Next(0, 4);

                PDVehicle v = null;

                switch (type)
                {
                case 0:
                    v = new PDVBritish(Game, m_screen);
                    v.Initialize();
                    v.SetDefaultGraphics(ref GameplayScreen.m_tShipBritish);
                    break;

                case 1:
                    v = new PDVChinese(Game, m_screen);
                    v.Initialize();
                    v.SetDefaultGraphics(ref GameplayScreen.m_tShipChinese);
                    break;

                case 2:
                    v = new PDVPersian(Game, m_screen);
                    v.Initialize();
                    v.SetDefaultGraphics(ref GameplayScreen.m_tShipPersian);
                    break;

                case 3:
                    v = new PDVSpanish(Game, m_screen);
                    v.Initialize();
                    v.SetDefaultGraphics(ref GameplayScreen.m_tShipSpanish);
                    break;
                }

                v.Position         = GameplayScreen.m_waypoints[n];
                v.ThrottleMax      = 40;
                v.ThrottleDecrease = 100;
                v.bTurnInPlace     = true;


                return;
            }



            for (int i = 0; i < Screen.m_islands.Count; i++)
            {
                if (Screen.m_islands[i].Hitbox != null)
                {
                    for (int j = 0; j < Screen.m_islands[i].Hitbox.Length; j++)
                    {
                        if (Screen.m_islands[i].Hitbox[j].TestOBBOBB(Obb))
                        {
                            // Cue c = Game1.Audio.PlaySound("sfx_ship_collide");
                            Cue           c  = Game1.Audio.GetCue("sfx_ship_collide");
                            AudioListener al = new AudioListener();
                            al.Position = new Vector3(m_screen.Player.Position, 0);
                            al.Up       = Vector3.Backward;
                            al.Forward  = Vector3.Up;

                            AudioEmitter ae = new AudioEmitter();
                            ae.Position = new Vector3(Position, 0);
                            ae.Up       = Vector3.Backward;
                            ae.Forward  = Vector3.Up;

                            c.Apply3D(al, ae);
                            Game1.Audio.PlayCue(c);


                            c.SetVariable("Distance", (Screen.Player.Position - Position).Length());


                            Vector2 v = Obb.Center - Screen.m_islands[i].Hitbox[j].Center;
                            v.Normalize();

                            Heading  = v;
                            Rotation = (float)Math.Atan2(Heading.Y, Heading.X);
                            Throttle = 100;
                            break;
                        }
                    }
                }
            }



            // Throttle -= ThrottleDecrease * (float)gameTime.ElapsedGameTime.TotalSeconds * 0.25f;

            float velMod = 0.0f;

            if (Throttle > 0.001f)
            {
                velMod = Throttle / ThrottleMax;
            }

            m_leanValue = MathHelper.Clamp(m_leanValue * velMod, -1.0f, 1.0f);

            int index = (int)Math.Round(m_leanValue * 4.0f) + 4;

            if (m_gfx != null)
            {
                if ((m_gfx as Animation).ActiveAnimationSet.Name != m_animTable[index])
                {
                    int currentFrame = (m_gfx as Animation).ActiveAnimationSet.nActiveFrame;
                    (m_gfx as Animation).SetActiveSet(m_animTable[index], currentFrame);
                }
            }


            if (m_bFiring)
            {
                if (m_nextShot < gameTime.TotalGameTime.TotalSeconds)
                {
                    Fire(gameTime);
                    m_nextShot += m_tTimeBetweenShots;

                    if (m_cannonsReady <= 0)
                    {
                        m_bFiring = false;
                    }
                }
            }
            else
            {
                Reload(gameTime);
            }



            m_obb.Orientation = Rotation;
            m_obb.Center      = Position;
            m_obb.CalculateAxis();

            m_shadow.Position = Position;
            m_shadow.Rotation = Rotation;

            m_hpBar.Position = Position;
            m_hpBar.Update(gameTime);
            m_hpBar.Scale = new Vector2(m_health / m_maxHealth, 1);

            m_hpBarBG.Position = Position;

            m_hpBarBG.Update(gameTime);



            if (m_tNextWaterTrail < gameTime.TotalGameTime.TotalSeconds)
            {
                if (Throttle > 10.0f)
                {
                    EffectWaterTrail water = new EffectWaterTrail(Game);
                    water.Initialize((float)gameTime.TotalGameTime.TotalSeconds + 3.5f, Position + (Heading * 40), false);
                    water.Rotation = Rotation - MathHelper.PiOver2;

                    water = new EffectWaterTrail(Game);
                    water.Initialize((float)gameTime.TotalGameTime.TotalSeconds + 3.5f, Position + (Heading * 40), false);
                    water.Rotation = Rotation + MathHelper.PiOver2;

                    m_tNextWaterTrail = (float)gameTime.TotalGameTime.TotalSeconds + 0.1f;
                }
            }



            base.Update(gameTime);
        }
Exemple #25
0
 public void PlayCue(string name, AudioListener listener, AudioEmitter emitter)
 {
 }
        public void TestApply3D()
        {
            var list       = new AudioListener();
            var emit       = new AudioEmitter();
            var monoInst   = continousMonoSoundEffect.CreateInstance();
            var stereoInst = continousStereoSoundEffect.CreateInstance();

            monoInst.IsLooped   = true;
            stereoInst.IsLooped = true;

            ////////////////////////////////////////////////////////////////////////////////////////
            // 1. Check that Apply3D for an Disposed instance throw the 'ObjectDisposedException'
            var dispInst = monoSoundEffect.CreateInstance();

            dispInst.Dispose();
            Assert.Throws <ObjectDisposedException>(() => dispInst.Apply3D(list, emit), "SoundEffectInstance.Apply3D did not throw the 'ObjectDisposedException' when called from a disposed object.");

            ////////////////////////////////////////////////////////////////////////////////////////
            // 2. Check that Apply3D with null arguments throw the 'ArgumentNullException'
            Assert.Throws <ArgumentNullException>(() => monoInstance.Apply3D(null, emit), "SoundEffectInstance.Apply3D did not throw the 'ArgumentNullException' with a null listener.");
            Assert.Throws <ArgumentNullException>(() => monoInstance.Apply3D(list, null), "SoundEffectInstance.Apply3D did not throw the 'ArgumentNullException' with a null emitter.");

            /////////////////////////////////////////////////////////////////////////////////////////////
            // 3. Check that the sound is not modified when applying 3D at same position with mono sound
            monoInst.Play();
            Utilities.Sleep(1000);
            monoInst.Apply3D(list, emit);
            Utilities.Sleep(1000);
            monoInst.Stop();
            Utilities.Sleep(1000);

            ///////////////////////////////////////////////////////////////////////////////////
            // 4. Check that Apply3D throws InvalidOperationException when used on stereo sound
            Assert.Throws <InvalidOperationException>(() => stereoInst.Apply3D(list, emit), "InvalidOperationException has not been thrown when used on stereo-sound.");

            /////////////////////////////////////////////////////
            // 5. Check that mono signal attenuate with distance
            monoInst.Play();
            var currentDist = 0f;

            while (currentDist < 5)
            {
                emit.Position = new Vector3(0, 0, currentDist);
                monoInst.Apply3D(list, emit);

                currentDist += 0.01f;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);

            ////////////////////////////////////////////////////////////////////////////////
            // 6. Check that signal do not attenuate when we move both emitter and listener
            monoInst.Play();
            currentDist = 0f;
            while (currentDist < 5)
            {
                emit.Position = new Vector3(0, 0, currentDist);
                list.Position = new Vector3(0, 0, currentDist);
                monoInst.Apply3D(list, emit);

                currentDist += 0.01f;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);

            //////////////////////////////////////////////////////////////////////////////////////
            // 7. Check that attenuation increase/decrease when modifying DistaceScale parameter
            monoInst.Play();
            var currentScale = 2f;

            list.Position = Vector3.Zero;
            emit.Position = Vector3.One;
            while (currentScale > 0.01f)
            {
                emit.DistanceScale = currentScale;
                monoInst.Apply3D(list, emit);

                currentScale -= 0.005f;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);

            ////////////////////////////////////////////////////////////////////////////////////////////////
            // 8. Check that mono the localization works properly by turning the emiter around the listener
            // Should start from the front, go to the right, go to the back, go to the left, and finnaly go back to the front.
            monoInst.Play();
            var angle = 0f;

            emit.DistanceScale = 1;
            while (angle > -2 * (float)Math.PI)
            {
                const float Offset = (float)Math.PI / 2;
                emit.Position = new Vector3((float)Math.Cos(angle + Offset), 0, (float)Math.Sin(angle + Offset));

                monoInst.Apply3D(list, emit);

                angle -= 0.005f;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 9. Check that the sound frequency is modified properly when object move away and goes back to the listener (doppler effect)
            monoInst.Play();
            var         speed      = 0f;
            const float SpeedLimit = 500f;
            var         sign       = 1f;

            emit.Position = new Vector3(0, 0, 1);
            while (speed > -SpeedLimit)
            {
                emit.Velocity = new Vector3(0, 0, speed);

                monoInst.Apply3D(list, emit);

                speed += sign * 0.005f * SpeedLimit;

                if (speed > SpeedLimit)
                {
                    sign  = -1f;
                    speed = 0;
                }

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 10. Check that the sound frequency is not modified when both objects move away at same speed (doppler effect)
            monoInst.Play();
            speed = 0f;
            while (speed < SpeedLimit)
            {
                emit.Velocity = new Vector3(0, 0, speed);
                list.Velocity = new Vector3(0, 0, speed);

                monoInst.Apply3D(list, emit);

                speed += 0.005f * SpeedLimit;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(600);

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 11. Check the doppler effect influence is modified properly when DopplerScale changes (should increase)
            monoInst.Play();
            var dopplerScale = 0.1f;

            emit.Position = new Vector3(0, 0, 1);
            emit.Velocity = new Vector3(0, 0, 10);
            list.Velocity = Vector3.Zero;
            while (dopplerScale < 50f)
            {
                emit.DopplerScale = dopplerScale;

                monoInst.Apply3D(list, emit);

                dopplerScale *= 1.01f;

                Utilities.Sleep(10);
            }
            monoInst.Stop();
            Utilities.Sleep(1000);
            emit.DopplerScale = 1;

            /////////////////////////////////////////////////////////
            // 12. Check that Apply3D does not perturb Volume value.
            var contInst = continousMonoSoundEffect.CreateInstance();

            contInst.IsLooped = true;
            contInst.Play();
            var volume = 1f;

            sign = -1f;
            while (volume <= 1f)
            {
                contInst.Volume = volume;
                contInst.Apply3D(new AudioListener(), new AudioEmitter());
                Assert.AreEqual(MathUtil.Clamp(volume, 0f, 1f), contInst.Volume, "Volume of continous sound is not what it should be.");

                volume += sign * 0.01f;

                if (volume < 0)
                {
                    sign = 1f;
                }

                Utilities.Sleep(10);
            }
            contInst.Stop();
            Utilities.Sleep(1000);

            ////////////////////////////////////////////////
            // 13. Check that Apply3D reset the Pan value.
            contInst.Play();
            contInst.Pan = 1;
            Utilities.Sleep(1000);
            contInst.Apply3D(new AudioListener(), new AudioEmitter {
                Position = new Vector3(-1, 0, 0)
            });
            Assert.AreEqual(0, contInst.Pan, "The Pan value has not been reset.");
            Utilities.Sleep(1000);
            contInst.Stop();

            contInst.Dispose();
            stereoInst.Dispose();
        }
        public void TestPan()
        {
            var pan = 0f;
            /////////////////////////////////////////////////////////////////////////////////////////////
            // 1. Check that get and set Pan for an Disposed instance throw the 'ObjectDisposedException'
            var dispInst = monoSoundEffect.CreateInstance();
            dispInst.Dispose();
            Assert.Throws<ObjectDisposedException>(() => pan = dispInst.Pan, "SoundEffectInstance.Pan { get } did not throw the 'ObjectDisposedException' when called from a disposed object.");
            Assert.Throws<ObjectDisposedException>(() => dispInst.Pan = 0f, "SoundEffectInstance.Pan { set } did not throw the 'ObjectDisposedException' when called from a disposed object.");

            /////////////////////////////////////////////////////////////
            // 2. Check that Pan set/get do not crash on valid sound
            var newInst = monoSoundEffect.CreateInstance();
            Assert.DoesNotThrow(() => pan = newInst.Pan, "SoundEffectInstance.Pan { get } crashed.");
            Assert.DoesNotThrow(() => newInst.Pan = 0f, "SoundEffectInstance.Pan { set } crashed.");
            newInst.Dispose();

            /////////////////////////////////////////
            // 3. Check that Pan default value is 0f
            Assert.AreEqual(0f, monoInstance.Pan, "Default Pan value is not 0f.");

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 4. Check that mono sound is Panning correctly (should listen => sound comming from left -> going to right -> going back to left)
            var monoContInst = continousMonoSoundEffect.CreateInstance();
            monoContInst.IsLooped = true;
            monoContInst.Play();
            const float BornValue = 1.5f;
            var currentPan = -BornValue;
            var sign = 1f;
            while (currentPan >= -BornValue)
            {
                Assert.DoesNotThrow(() => monoContInst.Pan = currentPan, "SoundEffectInstance.Pan { set } crashed with varying values.");
                Assert.AreEqual(MathUtil.Clamp(currentPan, -1, 1), monoContInst.Pan, "SoundEffectInstance.Pan { get } is not what it is supposed to be.");

                currentPan += sign * 0.01f;

                if (currentPan > BornValue)
                    sign = -1f;

                Utilities.Sleep(20);
            }
            monoContInst.Stop();

            ////////////////////////////////////////////////////////////
            // Check that Modifying the pan reset the 3D localization
            var list = new AudioListener();
            var emit = new AudioEmitter { Position = new Vector3(7, 0, 0) };
            monoContInst.Apply3D(list, emit);
            monoContInst.Play();
            Utilities.Sleep(1000);
            monoContInst.Pan = 0;
            Utilities.Sleep(1000);
            monoContInst.Stop();
            monoContInst.Dispose();

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 5. Check that stereo sound is Panning correctly (should listen => sound comming from left -> going to right -> going back to left)
            Utilities.Sleep(1000);
            var stereoContInst = continousStereoSoundEffect.CreateInstance();
            stereoContInst.IsLooped = true;
            stereoContInst.Play();
            currentPan = -BornValue;
            sign = 1f;
            while (currentPan >= -BornValue)
            {
                Assert.DoesNotThrow(() => stereoContInst.Pan = currentPan, "SoundEffectInstance.Pan { set } crashed with varying values.");
                Assert.AreEqual(MathUtil.Clamp(currentPan, -1, 1), stereoContInst.Pan, "SoundEffectInstance.Pan { get } is not what it is supposed to be.");

                currentPan += sign * 0.01f;

                if (currentPan > BornValue)
                    sign = -1f;

                Utilities.Sleep(20);
            }
            stereoContInst.Stop();
            stereoContInst.Dispose();
            Utilities.Sleep(1000);
        }
    public void LoadContent()
    {
        //Finding and declaring the grid
        Level parentLevel = parent as Level;
        TileGrid tileGrid = parentLevel.Find("TileGrid") as TileGrid;
        this.grid = tileGrid.Objects;
        gridWidth = grid.GetLength(0);
        gridHeight = grid.GetLength(1);
        stepgrid = new int[gridWidth, gridHeight];

        //Counting the amount of path-tiles in the room
        for (int x = 0; x < gridWidth; x++)
        {
            for (int y = 0; y < gridHeight; y++)
            {
                if (grid[x, y] is Tile && !(grid[x, y] is WallTile))
                {
                    tiles++;
                }
            }
        }

        //Monster's position
        foreach(GameObject tile in tileGrid.Objects)
            if (tile != null)
                if (tile.ID == "EntryTile")
                    monsterPosition = tile.Position + new Vector3(0, 200, 0);

        //Monster's velocity
        velocity = 150;

        //Setting the emitter and listener for 3D sound
        playerListener = new AudioListener();
        monsterEmitter = new AudioEmitter();
    }
 public void SoundApply3D(AudioListener listener, AudioEmitter emitter)
 {
     iSound.Apply3D(listener, emitter);
 }
Exemple #30
0
 public SoundInstance(SoundEffectInstance inst, AudioEmitter emit = null)
 {
     Instance = inst;
     Emitter  = emit;
 }
Exemple #31
0
        public override void HandleData(NetIncomingMessage msg)
        {
            NetEntityType Type;
            ushort        ID;
            Vector3       Position;
            Vector3       Velocity;
            Quaternion    Orientation;
            NetMsgType    datatype = (NetMsgType)msg.ReadByte();

            switch (datatype)
            {
            case NetMsgType.Chat:
                Console.WriteLine(msg.ReadString());
                break;

            case NetMsgType.CreateOnClient:
                #region CreateOnClient
                Type        = (NetEntityType)msg.ReadByte();
                ID          = msg.ReadUInt16();
                Position    = new Vector3(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                Orientation = new Quaternion(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                ushort Resource;
                long   OwnerID;

                //DEBUG
                if (Type == NetEntityType.Ship)
                {
                    int[] shipWeapons  = null;
                    var   shipNose     = msg.ReadInt32();
                    var   shipCore     = msg.ReadInt32();
                    var   shipTail     = msg.ReadInt32();
                    int   weaponLength = msg.ReadInt32();
                    if (weaponLength > 0)
                    {
                        shipWeapons = new int[weaponLength];
                        for (int i = 0; i < weaponLength; i++)
                        {
                            shipWeapons[i] = msg.ReadInt32();
                        }
                    }
                    Resource = 0;
                    OwnerID  = msg.ReadInt64();
                    var shipData = new ShipData(shipNose, shipCore, shipTail);
                    WeaponsFromData(shipData, shipWeapons);
                    var ship = new ShipObj(MobileFortressClient.Game, Position, Orientation, shipData);
                    ship.ID = ID;
                    if (OwnerID == Network.Client.UniqueIdentifier)
                    {
                        Network.JoinedGame = true;
                        Camera.Setup(MobileFortressClient.Game, ship, new Vector3(0, 2f, 6f));
                        var HUD = new ShipHUD();
                        if (shipWeapons != null)
                        {
                            for (int i = 0; i < shipWeapons.Length; i++)
                            {
                                HUD.MakeAmmoIndicator(shipWeapons[i]);
                            }
                        }
                        MenuManager.Menu = HUD;
                    }
                }
                else
                {
                    Resource = msg.ReadUInt16();
                    if (Type == NetEntityType.Building)
                    {
                        new Building(Position, Resource);
                    }
                    else if (Type == NetEntityType.Missile)
                    {
                        var obj = new Rocket(MobileFortressClient.Game, Resource, Position, Orientation);
                        obj.ID = ID;
                    }
                    else
                    {
                        var obj = new PhysicsObj(MobileFortressClient.Game, Position, Orientation, Resource);
                        obj.ID = ID;
                    }
                }
                #endregion
                break;

            case NetMsgType.MapLoading:
                #region MapLoading
                if (msg.ReadByte() == 0)
                {
                    var Seed      = msg.ReadInt32();
                    var Power     = msg.ReadInt32();
                    var Roughness = msg.ReadFloat();
                    Sector.Redria.Terrain.Terrain = new Heightmap(Seed, Power, Roughness);
                }
                else
                {
                    var terrain     = Sector.Redria.Terrain.Terrain;
                    int alterations = msg.ReadInt32();
                    Console.WriteLine(alterations + " Recieved Alterations.");
                    for (int i = 0; i < alterations; i++)
                    {
                        Rectangle flattenedArea = new Rectangle(msg.ReadInt32(),
                                                                msg.ReadInt32(), msg.ReadInt32(), msg.ReadInt32());
                        terrain.FlattenArea(flattenedArea);
                    }
                    terrain.Graphics.ResetVertexBuffer();
                }
                #endregion
                break;

            case NetMsgType.EntityUpdate:
                #region EntityUpdate
                Type        = (NetEntityType)msg.ReadByte();
                ID          = msg.ReadUInt16();
                Position    = new Vector3(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                Velocity    = new Vector3(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                Orientation = new Quaternion(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                if (Type == NetEntityType.Ship)
                {
                    var ship = Sector.Redria.Ships.Retrieve(ID);
                    if (ship == null)
                    {
                        Console.WriteLine("No such ship ID: " + ID);
                        break;
                    }
                    ship.UpdateFromNet(Position, Orientation, Velocity);
                }
                else if (Type == NetEntityType.Missile)
                {
                    var missile = Sector.Redria.Objects.Retrieve(ID);
                    if (missile == null)
                    {
                        break;
                    }
                    missile.UpdateFromNet(Position, Orientation, Velocity);
                }
                #endregion
                break;

            case NetMsgType.Bullet:
                #region Bullet
                ID          = msg.ReadUInt16();
                Position    = new Vector3(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                Velocity    = new Vector3(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                Orientation = new Quaternion(msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat(), msg.ReadFloat());
                var Projectile = ProjectileData.ProjectileTable[ID];
                var ping       = Network.Client.ServerConnection.AverageRoundtripTime;
                Projectile.Create(Position + Velocity * (ping / 2), Orientation, Velocity);
                var Audio = new AudioEmitter();
                Audio.Position = Position / Resources.AudioPositionQuotient;
                Audio.Forward  = Vector3.Transform(Vector3.Forward, Orientation);
                Audio.Up       = Vector3.Up;
                Audio.Velocity = Velocity;

                var sound = Resources.Sounds.WeaponSounds[ID].CreateInstance();
                sound.Apply3D(Camera.Audio, Audio);
                sound.Play();
                #endregion
                break;

            case NetMsgType.ShipExplode:
                #region ShipExplode
                ID = msg.ReadUInt16();
                var deadship = Sector.Redria.Ships.Retrieve(ID);
                deadship.Explode();
                #endregion
                break;

            case NetMsgType.Explosion:
                #region Explosion
                ID = msg.ReadUInt16();
                var Radius    = msg.ReadFloat();
                var exploding = Sector.Redria.Objects.Retrieve(ID);
                if (exploding != null)
                {
                    new Explosion(exploding.Position, Radius);
                    exploding.Destroy();
                }
                #endregion
                break;

            case NetMsgType.Lockon:
                #region Lockon
                if (!(MenuManager.Menu is ShipHUD))
                {
                    break;
                }
                ID = msg.ReadUInt16();
                var     LockonStatus = (LockonStatus)msg.ReadByte();
                ShipHUD Menu         = (ShipHUD)MenuManager.Menu;
                if (LockonStatus > LockonStatus.Locked)
                {
                    if (LockonStatus == LockonStatus.EnemyLock)
                    {
                        Menu.enemyLock = true;
                    }
                    else if (LockonStatus == LockonStatus.EnemyMissile)
                    {
                        Menu.enemyLock    = false;
                        Menu.enemyMissile = true;
                    }
                    else
                    {
                        Menu.enemyMissile = false;
                        Menu.enemyLock    = false;
                    }
                }
                else
                {
                    if (ID == ushort.MaxValue)
                    {
                        Menu.Target     = null;
                        Menu.LockStatus = LockonStatus.NotLocked;
                    }
                    else
                    {
                        Menu.Target     = Sector.Redria.Ships.Retrieve(ID);
                        Menu.LockStatus = LockonStatus;
                        if (Menu.LockStatus == LockonStatus.Locking)
                        {
                            Resources.Sounds.LockingOn.Play();
                        }
                        else if (Menu.LockStatus == LockonStatus.Locked)
                        {
                            Resources.Sounds.LockedOn.Play();
                        }
                    }
                }
                #endregion
                break;

            case NetMsgType.ShipUpdate:
                #region ShipUpdate
                var Health    = msg.ReadFloat();
                var Throttle  = msg.ReadFloat();
                var AmmoCount = msg.ReadByte();
                var Ammo      = new ushort[AmmoCount];
                for (byte i = 0; i < AmmoCount; i++)
                {
                    Ammo[i] = msg.ReadUInt16();
                }
                if (MenuManager.Menu is ShipHUD)
                {
                    var HUD = (ShipHUD)MenuManager.Menu;
                    HUD.SetHealth((int)Health);

                    for (int i = 0; i < Ammo.Length; i++)
                    {
                        HUD.SetAmmo(i, Ammo[i]);
                    }
                    ping = msg.SenderConnection.AverageRoundtripTime * 1000;
                    HUD.SetPing(ping);

                    var ship = (ShipObj)Camera.Target;
                    ship.SetThrottle(Throttle);
                }

                #endregion
                break;

            default:
                Console.WriteLine("Unhandled NetMsgType: " + datatype);
                break;
            }
        }
Exemple #32
0
    /// <summary>
    /// Attempts to play the sound with 3D effects.
    /// Returns a Handle to the AudioCue that gets played.
    /// </summary>
    /// <param name="soundName">The name of the sound to play.</param>
    public AudioHandle PlaySound3D(String soundName, AudioEmitter emitter)
    {
        AudioHandle handle = m_cuePool.Allocate();
        AudioCue cue = m_cuePool.GetItem(handle);
        if (null != cue)
        {
            System.Diagnostics.Debug.Assert(cue.m_state == AudioCue.State.AVAILABLE);
            System.Diagnostics.Debug.Assert(cue.m_cue == null);
            cue.SetUp(m_soundBank, soundName);
            cue.m_cue.Apply3D(m_listener, emitter);
            cue.Play();
#if AUDIO_DEBUG
            ++m_numPlaying;
            ++m_numPlayed;
        }
        else
        {
            ++m_numFailed;
#endif
        }
        return handle;
    }
        public void TestReset3D()
        {
            var list = new AudioListener();
            var emit = new AudioEmitter();
            var monoInst = continousMonoSoundEffect.CreateInstance();
            monoInst.IsLooped = true;

            /////////////////////////////
            // Check that Pitch is reset
            emit.Position = new Vector3(0,0,1);
            emit.Velocity = new Vector3(500,0,0);
            monoInst.Apply3D(list, emit);
            monoInst.Play();
            Utilities.Sleep(1000);
            monoInst.Reset3D();
            Utilities.Sleep(1000);
            monoInst.Stop();
            Utilities.Sleep(500);

            ///////////////////////////
            // Check that Pan is reset
            emit.Position = new Vector3(1, 0, 0);
            emit.Velocity = new Vector3(0, 0, 0);
            monoInst.Apply3D(list, emit);
            monoInst.Play();
            Utilities.Sleep(1000);
            monoInst.Reset3D();
            Utilities.Sleep(1000);
            monoInst.Stop();
            Utilities.Sleep(500);

            ////////////////////////////////////////////
            // Check that effect on the Volume is reset
            emit.Position = new Vector3(0, 0, 10);
            monoInst.Apply3D(list, emit);
            monoInst.Play();
            Utilities.Sleep(1000);
            monoInst.Reset3D();
            Utilities.Sleep(1000);
            monoInst.Stop();
            Utilities.Sleep(500);

            /////////////////////////////////
            // Check that Volume is not reset
            monoInst.Volume = 0.5f;
            monoInst.Reset3D();
            monoInst.Play();
            Utilities.Sleep(1000);
            Assert.AreEqual(0.5f, monoInst.Volume, "Reset3D has modified the music Volume");
            monoInst.Volume = 1f;
            Utilities.Sleep(1000);
            monoInst.Stop();
            Utilities.Sleep(500);

            monoInst.Dispose();
        }
Exemple #34
0
 /// <summary>
 /// Creates a new Cue3D.
 /// </summary>
 /// <param name="cues">A list of cues. One for each AuidoListener.</param>
 /// <param name="emitter">The emitter of the sound.</param>
 public Cue3D(List <Cue> cues, AudioEmitter emitter)
 {
     Cues    = cues;
     Emitter = emitter;
 }
 public void Play3DSound(AudioListener listener, AudioEmitter emitter)
 {
     iSound.Apply3D(listener, emitter);
     playingState = "playing";
     iSound.Play();
 }
 public void OnEnable()
 {
     _previewer = EditorUtility.CreateGameObjectWithHideFlags("Audio preview", HideFlags.HideAndDontSave, typeof(AudioEmitter)).GetComponent <AudioEmitter>();
 }
        public void TestPan()
        {
            var pan = 0f;
            /////////////////////////////////////////////////////////////////////////////////////////////
            // 1. Check that get and set Pan for an Disposed instance throw the 'ObjectDisposedException'
            var dispInst = monoSoundEffect.CreateInstance();

            dispInst.Dispose();
            Assert.Throws <ObjectDisposedException>(() => pan          = dispInst.Pan, "SoundEffectInstance.Pan { get } did not throw the 'ObjectDisposedException' when called from a disposed object.");
            Assert.Throws <ObjectDisposedException>(() => dispInst.Pan = 0f, "SoundEffectInstance.Pan { set } did not throw the 'ObjectDisposedException' when called from a disposed object.");

            /////////////////////////////////////////////////////////////
            // 2. Check that Pan set/get do not crash on valid sound
            var newInst = monoSoundEffect.CreateInstance();

            Assert.DoesNotThrow(() => pan         = newInst.Pan, "SoundEffectInstance.Pan { get } crashed.");
            Assert.DoesNotThrow(() => newInst.Pan = 0f, "SoundEffectInstance.Pan { set } crashed.");
            newInst.Dispose();

            /////////////////////////////////////////
            // 3. Check that Pan default value is 0f
            Assert.AreEqual(0f, monoInstance.Pan, "Default Pan value is not 0f.");

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 4. Check that mono sound is Panning correctly (should listen => sound comming from left -> going to right -> going back to left)
            var monoContInst = continousMonoSoundEffect.CreateInstance();

            monoContInst.IsLooped = true;
            monoContInst.Play();
            const float BornValue  = 1.5f;
            var         currentPan = -BornValue;
            var         sign       = 1f;

            while (currentPan >= -BornValue)
            {
                Assert.DoesNotThrow(() => monoContInst.Pan = currentPan, "SoundEffectInstance.Pan { set } crashed with varying values.");
                Assert.AreEqual(MathUtil.Clamp(currentPan, -1, 1), monoContInst.Pan, "SoundEffectInstance.Pan { get } is not what it is supposed to be.");

                currentPan += sign * 0.01f;

                if (currentPan > BornValue)
                {
                    sign = -1f;
                }

                Utilities.Sleep(20);
            }
            monoContInst.Stop();

            ////////////////////////////////////////////////////////////
            // Check that Modifying the pan reset the 3D localization
            var list = new AudioListener();
            var emit = new AudioEmitter {
                Position = new Vector3(7, 0, 0)
            };

            monoContInst.Apply3D(list, emit);
            monoContInst.Play();
            Utilities.Sleep(1000);
            monoContInst.Pan = 0;
            Utilities.Sleep(1000);
            monoContInst.Stop();
            monoContInst.Dispose();

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 5. Check that stereo sound is Panning correctly (should listen => sound comming from left -> going to right -> going back to left)
            Utilities.Sleep(1000);
            var stereoContInst = continousStereoSoundEffect.CreateInstance();

            stereoContInst.IsLooped = true;
            stereoContInst.Play();
            currentPan = -BornValue;
            sign       = 1f;
            while (currentPan >= -BornValue)
            {
                Assert.DoesNotThrow(() => stereoContInst.Pan = currentPan, "SoundEffectInstance.Pan { set } crashed with varying values.");
                Assert.AreEqual(MathUtil.Clamp(currentPan, -1, 1), stereoContInst.Pan, "SoundEffectInstance.Pan { get } is not what it is supposed to be.");

                currentPan += sign * 0.01f;

                if (currentPan > BornValue)
                {
                    sign = -1f;
                }

                Utilities.Sleep(20);
            }
            stereoContInst.Stop();
            stereoContInst.Dispose();
            Utilities.Sleep(1000);
        }
Exemple #38
0
        public virtual bool FireRight(GameTime gameTime)
        {
            if (m_cannonsReady > 4)
            {
                if (!m_bFiring)
                {
                    m_bFiring   = true;
                    m_bFireLeft = false;

                    Cue c = null;

                    if (m_cannonsReady > 6)
                    {
                        m_tTimeBetweenShots = 1.3f / m_cannonsReady;
                        // c = Game1.Audio.PlaySound("sfx_cannon_shoot_many");
                        c = Game1.Audio.GetCue("sfx_cannon_shoot_many");
                    }
                    else
                    {
                        m_tTimeBetweenShots = 0.5f / m_cannonsReady;
                        // c = Game1.Audio.PlaySound("sfx_cannon_shoot");
                        c = Game1.Audio.GetCue("sfx_cannon_shoot");
                    }

                    AudioListener al = new AudioListener();
                    al.Position = new Vector3(m_screen.Player.Position, 0);
                    al.Up       = Vector3.Backward;
                    al.Forward  = Vector3.Up;

                    AudioEmitter ae = new AudioEmitter();
                    ae.Position = new Vector3(Position, 0);
                    ae.Up       = Vector3.Backward;
                    ae.Forward  = Vector3.Up;

                    c.Apply3D(al, ae);
                    Game1.Audio.PlayCue(c);

                    c.SetVariable("Distance", (Screen.Player.Position - Position).Length());

                    m_nextShot = (float)gameTime.TotalGameTime.TotalSeconds;
                }

                /*
                 * Vector2 back = Position - (Heading * 50);
                 * Vector2 length = Heading * 100;
                 *
                 * Vector2 pos = back + (length * (float)Game1.Rand.NextDouble());
                 *
                 * Texture2D tex = GameplayScreen.m_debugSprites;
                 * Proj_CannonBall p = new Proj_CannonBall(Game, this, ref tex, m_screen);
                 * p.Initialize(Rotation + MathHelper.PiOver2, pos, null, false, false, gameTime);
                 *
                 * m_cannonsReady--;
                 *
                 * return true;
                 *
                 */
            }

            return(false);
        }
Exemple #39
0
 public void Apply3D(AudioListener listener, AudioEmitter emitter)
 {
     Apply3D(new AudioListener[] { listener }, emitter);
 }
Exemple #40
0
 /// <summary>
 /// Updates a 3D sound with its latest emitter data
 /// </summary>
 /// <param name="handle">A handle to the sound being played</param>
 /// <param name="emitter">The emitter that contains the position and velocity data</param>
 public void UpdateSound3D(AudioHandle handle, AudioEmitter emitter)
 {
     AudioCue cue = m_cuePool.GetItem(handle);
     if (null != cue)
     {
         cue.m_cue.Apply3D(m_listener, emitter);
     }    
 }