Exemplo n.º 1
0
    private void addFrequencyEvent(WaveData waveData)
    {
        //no shower, use collision timing safeguards, potentially different directions
        for (int i=0; i<waveData.frequency.count; i++) {
            BlobData blobData = worldManager.getBlobDataFromPrefab (waveData.blobPrefab);

            applyWaveData (blobData, waveData, i);

            float deltaTime = waveData.getDeltaTimeFromIndex (i);
            float spawnTime = waveData.getStartTime () + deltaTime;
            addSpawnEvent (blobData, spawnTime, true);
        }
    }
Exemplo n.º 2
0
        public void Construction()
        {
            int n = 10;
            WaveData wd = new WaveData(n);

            Assert.AreEqual(n, wd.Length);

            n = 24;
            double[] arr = new double[n];
            wd = new WaveData(arr);
            Assert.AreEqual(n, wd.Length);

            n = 20;
            ComplexArray ca = new ComplexArray(n, false);
            wd = new WaveData(ca);

            Assert.AreEqual(n + 1, wd.SpLength);
            Assert.AreEqual(n * 2, wd.Length);
        }
Exemplo n.º 3
0
    private void addShowerEvent(WaveData waveData)
    {
        //shower, ignore collision timing safeguards, same direction

        //gen direction and size to use on all shower blobs
        BlobData showerBlobData = worldManager.getBlobDataFromPrefab (waveData.blobPrefab);
        applyWaveData (showerBlobData, waveData, 0);

        int[,,] mainMapData = worldManager.getMainBlob ().getMapData ();
        IntVector3 direction=showerBlobData.getMoveDirectionUnitVector();
        IntVector2 areaSize = MDCollision.getCollisionArraySize (mainMapData, direction);
        IntVector2 cellSize = MDCollision.getCollisionArraySize (showerBlobData.getSizeVector(), direction);

        //Debug.Log ("cellsize: "+ZTools.toString(cellSize));

        int count=waveData.frequency.count;
        int spacing=waveData.frequency.showerSpacing;
        ArrayList points = ZTools.getGridSquares (areaSize, cellSize, count,spacing);
        ZTools.shuffleArraylist(points);

        int iterIndex = -1;
        foreach (IntVector2 point in points) {
            iterIndex++;

            BlobData blobData = worldManager.getBlobDataFromPrefab (waveData.blobPrefab);

            blobData.setMoveDirection (showerBlobData.getMoveDirection ());
            blobData.size = showerBlobData.size;
            blobData.setOffset (point);
            blobData.offset.guarenteeHit=false;

            float deltaTime = waveData.getDeltaTimeFromIndex (iterIndex);
            float spawnTime = waveData.getStartTime () + deltaTime;
            addSpawnEvent (blobData, spawnTime, false);
        }
    }
    void Update()
    {
        if (ShipsIncomingLabel != null && ShipsIncomingLabel.gameObject.activeSelf)
        {
            if (TimeUtils.TimestampMilliseconds > _showingIncomingShipStartTime + 1000)
            {
                ShipsIncomingLabel.gameObject.SetActive(false);
            }
        }

        switch (_battleState)
        {
        case EBattleState.E_WAVE_START:
        {
            if (TimeUtils.TimestampMilliseconds > _stateStartTime + _stateTime)
            {
                ChangeState(EBattleState.E_PLAYING);
            }

            break;
        }

        case EBattleState.E_PLAYING:
        {
            if (_currentWaveData == null)
            {
                if (_currentWaveDataIdx < _currentWaveDatasInStage.Count)
                {
                    _currentWaveEnemy = 0;
                    _currentWaveData  = _currentWaveDatasInStage[_currentWaveDataIdx];
                    _currentWaveDataIdx++;

                    _waveTimer.Wait(_currentWaveData.Rhythm);
                }
                else
                {
                    if (GSB_GameManager.Instance.CurrentGameState == GSB_GameManager.GameState.E_PLAYING_2_VERSUS)
                    {
                        ChangeState(EBattleState.E_WAVE_END);
                    }
                    else
                    {
                        if (_enemies.Count == 0)
                        {
                            ChangeState(EBattleState.E_WAVE_END);
                        }
                    }
                }
            }
            else
            {
                if (_waveTimer.IsFinished)
                {
                    if (_currentWaveEnemy == _currentWaveData.NumEnemies)
                    {
                        _currentWaveData = null;
                    }
                    else
                    {
                        GenerateEnemy();
                        _currentWaveEnemy++;

                        if (_currentWaveEnemy == _currentWaveData.NumEnemies)
                        {
                            _waveTimer.Wait(_currentWaveData.RhythmInterWave);
                        }
                        else
                        {
                            _waveTimer.Wait(_currentWaveData.Rhythm);
                        }
                    }
                }
            }

            if (GSB_GameManager.Instance.CurrentGameState == GSB_GameManager.GameState.E_PLAYING_2_VERSUS)
            {
                if (_currentVSWaveData == null)
                {
                    if (_currentVSWaveDatas.Count > 0)
                    {
                        _currentVSWaveEnemy = 0;
                        _currentVSWaveData  = _currentVSWaveDatas[0];
                        _currentVSWaveDatas.RemoveAt(0);

                        _waveVSTimer.Wait(_currentVSWaveData.Rhythm);
                    }
                }
                else
                {
                    if (_waveVSTimer.IsFinished)
                    {
                        if (_currentVSWaveEnemy == _currentVSWaveData.NumEnemies)
                        {
                            _currentVSWaveData = null;
                        }
                        else
                        {
                            GenerateEnemy(true);
                            _currentVSWaveEnemy++;

                            if (_currentVSWaveEnemy == _currentVSWaveData.NumEnemies)
                            {
                                _waveVSTimer.Wait(_currentVSWaveData.RhythmInterWave);
                            }
                            else
                            {
                                _waveVSTimer.Wait(_currentVSWaveData.Rhythm);
                            }
                        }
                    }
                }
            }

            break;
        }

        case EBattleState.E_WAVE_END:
        {
            if (TimeUtils.TimestampMilliseconds > _stateStartTime + _stateTime)
            {
                ChangeState(EBattleState.E_WAVE_START);
            }

            break;
        }

        case EBattleState.E_GAMEOVER:
        {
            if (TimeUtils.TimestampMilliseconds > _stateStartTime + _stateTime)
            {
                if (GSB_GameManager.Instance.CurrentGameState == GSB_GameManager.GameState.E_PLAYING_1_PLAYER)
                {
                    GSB_GameManager.Instance.SetGameState(GSB_GameManager.GameState.E_TITLE);
                }
            }

            break;
        }
        }

        switch (_battleSubState)
        {
        case EBattleState.E_WIN:
        case EBattleState.E_LOSE:
        {
            if (TimeUtils.TimestampMilliseconds > _stateStartTime + _stateTime)
            {
                GSB_GameManager.Instance.SetGameState(GSB_GameManager.GameState.E_TITLE);
            }

            break;
        }
        }
    }
Exemplo n.º 5
0
    IEnumerator SpawnMonsterImpl(int index, WaveData waveData)
    {
        var        data   = DataManager.GetInstance().dicMonsterData[waveData.monster_id];
        GameObject prefab = (GameObject)(from obj in App.instance.resource
                                         where obj.name == data.prefab_name
                                         select obj).FirstOrDefault();

        EasyObjectPool.instance.MakePoolInfo(data.name, prefab);

        var monsterPosition = new Vector3(waveData.x, waveData.y, waveData.z);

        for (int i = 0; i < waveData.count; i++)
        {
            GameObject go = EasyObjectPool.instance.GetObjectFromPool(data.name, monsterPosition, Quaternion.identity);

            TestMonster monster = go.GetComponent <TestMonster>();
            if (monster == null)
            {
                monster = go.AddComponent <TestMonster>();
            }

            var destination_x = UnityEngine.Random.Range(waveData.destination_x - 1, waveData.destination_x + 1);
            var destination   = new Vector3(destination_x, waveData.destination_y, waveData.destination_z);

            monster.Init(destination, DataManager.GetInstance().dicMonsterData[waveData.monster_id], fence, whiteMaterial);

            monster.monsterAttackEvent.monsterAttackAction = () =>
            {
                fence.Hit(monster.data.damage);
            };

            monster.ChangeBehavior(TestMonster.eMonsterState.MOVE);

            listMonsters.Add(monster);

            monster.OnCompleteMove = () =>
            {
                monster.previousState = monster.currentState;
                monster.ChangeBehavior(TestMonster.eMonsterState.FOLLOW);
            };
            monster.OnCompleteKnockBack = () =>
            {
                if (monster.previousState == TestMonster.eMonsterState.MOVE)
                {
                    monster.previousState = TestMonster.eMonsterState.FOLLOW;
                }
                monster.ChangeBehavior(monster.previousState);
                monster.previousState = monster.currentState;
            };
            monster.OnCompleteStun = () =>
            {
                monster.ChangeBehavior(monster.previousState);
                monster.previousState = monster.currentState;
            };
            monster.OnMonsterDie = () =>
            {
                //Debug.Log($"OnMonsterDie{monster.name}");
                monster.previousState = monster.currentState;
                monster.ChangeBehavior(TestMonster.eMonsterState.DIE);
                bool isSuccess = listMonsters.Remove(monster);
                //Debug.Log($"isSuccess: {isSuccess}");
                OnMonsterRemovedFromList();
            };
            monster.OnMonsterDead = () =>
            {
                monster.previousState = monster.currentState;
                monster.ChangeBehavior(TestMonster.eMonsterState.IDLE);
                EasyObjectPool.instance.ReturnObjectToPool(monster.gameObject);
            };
            monster.OnDisplayHudText = (damage) =>
            {
                DisplayHudText(uiRoot, monster.transform.position, damage);
            };
            yield return(new WaitForSeconds(waveData.term));
        }

        OnStopSpawnMonster(index);
    }
 public void theSetValueMethod(WaveData listPassagewayWave, string fileName, byte[] address)
 {
     this.fileName           = fileName;
     this.address            = address;
     this.listPassagewayWave = listPassagewayWave;
 }
Exemplo n.º 7
0
        public void SpawnWave()
        {
            //Game Over?
            if (GameManager.Instance.PlayerBase.Equals(null))
            {
                return;
            }
            //Through all waves? Make it harder!
            if (_currentWaveIndex >= waves.Length)
            {
                Sun.Instance.SpeedUpDayTime();
                _currentWaveIndex = 0;
            }

            waveDisplay.ShowCurrentWave(_currentWaveIndex);
            WaveData wave = waves[_currentWaveIndex];

            //Using the data from SpawnData, spawns the enemies of this wave
            foreach (SpawnData spawnData in wave.spawnData)
            {
                StartCoroutine(SpawnEnemies(spawnData));
            }
            _currentWaveIndex++;

            //Spawns enemies defined in the SpawnData
            IEnumerator SpawnEnemies(SpawnData spawnData)
            {
                for (int i = 0; i < spawnData.numberOfSpawns; i++)
                {
                    //Left
                    Transform spawnPosition;
                    switch (spawnData.spawnLocation)
                    {
                    case SpawnData.SpawnLocation.Left:
                        spawnPosition = enemySpawnPoints[0];
                        break;

                    case SpawnData.SpawnLocation.Right:
                        spawnPosition = enemySpawnPoints[1];
                        break;

                    case SpawnData.SpawnLocation.Both:
                        spawnPosition = enemySpawnPoints[i % enemySpawnPoints.Length];
                        break;

                    default:
                        spawnPosition = enemySpawnPoints[0];
                        break;
                    }

                    if (GameManager.Instance.PlayerBase.Equals(null))
                    {
                        yield break;
                    }
                    Enemy newEnemy = Instantiate(spawnData.enemy);
                    newEnemy.transform.position = spawnPosition.position;

                    newEnemy.SetPlayerBase(GameManager.Instance.PlayerBase.transform);
                    yield return(new WaitForSeconds(spawnData.spawnDelayPerUnit));
                }
            }
        }
Exemplo n.º 8
0
            public static WaveData readWAV(string filename)
            {
                BinaryReader inputFile = new BinaryReader(new FileStream(filename, FileMode.Open));

                // File Magic
                string id = readRIFFHeader(inputFile);

                if (!id.Equals("RIFF"))
                {
                    throw new Exception(String.Format("File {0} is no WAV File", filename));
                }

                UInt32 fs = inputFile.ReadUInt32();

                if (fs + 8 != inputFile.BaseStream.Length)
                {
                    throw new Exception(String.Format("File {0} seems truncated", filename));
                }

                // File type
                string typ = readRIFFHeader(inputFile);

                if (!typ.Equals("WAVE"))
                {
                    throw new Exception(String.Format("File {0} contains no WAV-Data", filename));
                }

                // Format header
                string fmt = readRIFFHeader(inputFile);

                if (!fmt.Equals("fmt "))
                {
                    throw new Exception(String.Format("File {0} has no format chunk", filename));
                }

                UInt32 fmtlen = inputFile.ReadUInt32();

                if (fmtlen < 16)
                {
                    throw new Exception(String.Format("File {0} has a truncated format chunk", filename));
                }

                UInt16 formatTag = inputFile.ReadUInt16();

                if (formatTag != 1)
                {
                    throw new Exception(String.Format("File {0} is not a PCM File", filename));
                }

                UInt16 chs = inputFile.ReadUInt16();

                if ((chs < 1) || (chs > 8))
                {
                    throw new Exception(String.Format("File {0} has an unsupported number of channels (only 1 to 8 allowed)", filename));
                }

                UInt32 srs        = inputFile.ReadUInt32();
                UInt32 datarate   = inputFile.ReadUInt32();
                UInt16 blockalign = inputFile.ReadUInt16();
                UInt16 bits       = inputFile.ReadUInt16();

                if (bits != 16)
                {
                    throw new Exception(String.Format("File {0} has an unsupported number of bits/sample (only 16 allowed)", filename));
                }

                if (fmtlen > 16)
                {
                    // Skip over any additional bytes
                    for (int i = 0; i < fmtlen - 16; i++)
                    {
                        inputFile.ReadByte();
                    }
                }

                string datahdr = readRIFFHeader(inputFile);

                if (!datahdr.Equals("data"))
                {
                    throw new Exception(String.Format("File {0} has no data chunk", filename));
                }
                UInt32 dlen = inputFile.ReadUInt32();

                if (dlen + fmtlen + 8 + 8 + 8 + 4 > inputFile.BaseStream.Length)
                {
                    throw new Exception(String.Format("File {0} seems to be corrupt", filename));
                }

                // Try to allocate a structure
                UInt64   samples = (UInt64)(dlen / (2 * chs));
                WaveData wvd     = null;

                try
                {
                    wvd = new WaveData((Byte)chs, samples, srs);
                }
                catch (Exception e)
                {
                    throw new Exception("File {0} cannot be read --> Out of Memory");
                }
                for (UInt64 i = 0; i < samples; i++)
                {
                    for (byte j = 0; j < chs; j++)
                    {
                        wvd.wave[j][i] = (float)inputFile.ReadInt16() / (float)32768.0;
                    }
                }
                inputFile.Close();
                wvd.filename = filename;
                return(wvd);
            }
Exemplo n.º 9
0
    public void Initialize(WaveData waveData)
    {
        data = waveData;

        timeElapsed = data.Interval;
    }
Exemplo n.º 10
0
    /// <summary> 初始化用户修改纸片的关卡 </summary>
    public void InitializeModifyLevel()
    {
        DataController dc = DataController.Instance;

        Debug.Log("datacontroler instance is " + dc);
        // 关卡数据
        LevelData levelData = dc.GetCurrentLevelData();

        // 纸片们数据
        PaperData[] papersData = levelData.papersData;
        // 用户可操作纸片的数据们
        WaveData[] waveDatas = new WaveData[2];
        // 所有纸片的 WaveController们
        WaveController[] waveControllers =
            new WaveController[levelData.papersData.Length];

        // 设置纸片组 Holder 的位置(纸片组的左上角)
        papersParentTransform.position = levelData.HolderPosition;

        // 生成纸片们,尚未给予 WaveData
        {
            int i = 0;
            foreach (PaperData paperData in papersData)
            {
                waveControllers[i++] = GetPaper(paperData);
            }
        }

        // 配置两张基础纸片的 WaveData
        for (int i = 0; i < 2; ++i)
        {
            waveControllers[i].WaveData = waveDatas[i] =
                new WaveData(papersData[i].waveAttributes);
        }

        // 配置 和视图纸片 的 WaveData
        // 注: 和视图纸片 不能被用户直接修改
        //     但会自动立即反应其下 加数纸片 的修改
        //     即创建自己的 waveDataMasks,记录别人的 WaveDataMask们
        WaveData sum = waveControllers[2].WaveData = new WaveData(waveDatas);

        // 配置目标纸片的 WaveData
        // 注:目标纸片 初始化的结果为最原始的 和视图纸片 叠加一个 目标修改
        //             且初始化后不能被修改
        //     即:如果关卡只修改 用户可操作纸片们的WaveModification
        //            则至少对和纸片的拷贝级别应该达到 拷贝每个WaveModification
        WaveData goal = new WaveData(sum);

        // 对目标纸片的每个蒙版(每个用户可操作纸片)做目标修改
        for (int i = 0; i < 2; ++i)
        {
            goal.ModifyByMask(i, levelData.modifications[i]);
        }
        waveControllers[3].WaveData = goal;

        // 关卡初始化完成,将数据引用传送给 WaveInputController
        WaveInputController waveInputController = GetComponent <WaveInputController>();

        waveInputController.SetDatas(
            papersData,
            waveDatas,
            waveControllers
            );
        // 激活 WaveInputController
        waveInputController.enabled = true;
    }
        private static void SearchTest()
        {
            var fileName = "CollectedData.csv";

            InputCount = (MaxPathingPoints * CountPerPathing) +
                         (MaxWaterPoints * CountPerWater) +
                         (MaxTowers * CountPerTower) +
                         (MaxEnemies * CountPerEnemy);

            var slrList  = new List <double>();
            var smList   = new List <double>();
            var uslrList = new List <double>();
            var usmList  = new List <double>();
            var usdList  = new List <double>();

            CSV = new StringBuilder();
            File.WriteAllText(fileName, CSV.ToString());

            for (var slr = 0.0; slr <= 1; slr += 0.1)
            {
                slrList.Add(slr);
            }
            for (var sm = 0.0; sm <= 1; sm += 0.1)
            {
                smList.Add(sm);
            }
            for (var uslr = 0.0; uslr <= 1; uslr += 0.1)
            {
                uslrList.Add(uslr);
            }
            for (var usm = 0.0; usm <= 1; usm += 0.1)
            {
                usmList.Add(usm);
            }
            for (var usd = 0.01; usd <= 0.3; usd += 0.025)
            {
                usdList.Add(usd);
            }

            var triedCombos = new List <string>();
            var outputList  = new List <double>();
            var inputList   = new List <double[]>();

            _waveData = new WaveData
            {
                WaveInputs = inputList,
                WaveScores = outputList,
            };

            using (var reader = new StreamReader(@"wavedata.csv"))
            {
                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split('\t');

                    var output = double.Parse(values[0]);
                    outputList.Add(output);

                    var inputCount = values.Length - 1;

                    var inputArray = new double[inputCount];

                    for (var i = 1; i < inputCount; i++)
                    {
                        inputArray[i - 1] = double.Parse(values[i]);
                    }
                    inputList.Add(inputArray);
                }
            }

            DeepBeliefNetworkModel baseModel = new DeepBeliefNetworkModel();

            baseModel.Initialize(InputCount, (int)(InputCount * 0.8), 0, 0, 0, 0, 0);
            baseModel.Save("BaseModel.model");
            DeepBeliefNetworkModel newModel = baseModel;

            while (true)
            {
                var slr  = FlatRedBallServices.Random.In(slrList);
                var sm   = FlatRedBallServices.Random.In(smList);
                var uslr = FlatRedBallServices.Random.In(uslrList);
                var usm  = FlatRedBallServices.Random.In(usmList);
                var usd  = FlatRedBallServices.Random.In(usdList);

                var combo = $"{slr}{sm}{uslr}{usm}{usd}";

                if (triedCombos.Contains(combo))
                {
                    continue;
                }

                triedCombos.Add(combo);

                CSV.Clear();

                newModel.Initialize(InputCount, (int)(InputCount * 0.8), uslr, usm, usd, slr, sm);
                newModel.Load("BaseModel.model");

                CSV.Append($"{slr},{sm},{uslr},{usm},{usd},");

                newModel.LearnAll(_waveData);

                CSV.Append(newModel.LastMSE);
                CSV.Append(Environment.NewLine);
                File.AppendAllText(fileName, CSV.ToString());
                CSV.Clear();

                if (newModel.LastMSE < 0.03)
                {
                    newModel.Save("BESTMODEL" + newModel.LastMSE + "SAVE.model");
                }
            }
        }
Exemplo n.º 12
0
    /// <summary>
    /// 读取数据
    /// </summary>
    public void ReadXml()
    {
        XmlDocument document = new XmlDocument();
        document.LoadXml(data.text);

        //获取xml的根节点
        XmlElement root = document.DocumentElement;

        //获取xml的属性
        foreach (XmlAttribute attribute in root.Attributes)
        {

        }

        //获取xml的子节点
        XmlNodeList nodes = document.GetElementsByTagName("Monster");

        foreach (XmlNode node in nodes)
        {
            WaveData waveData = new WaveData();
            foreach (XmlAttribute attribute in node.Attributes)
            {
                if (attribute.Name.Equals("Monster"))
                {
                    string[] arr = attribute.Value.Split(':');
                    int[] ids = new int[arr.Length];

                    for (int i = 0; i < arr.Length; i++)
                    {
                        ids[i] = int.Parse(arr[i]);
                    }
                    waveData.randomId = ids;
                }
                else if (attribute.Name.Equals("Nums"))
                {
                    waveData.nums = int.Parse(attribute.Value);
                }
                else if (attribute.Name.Equals("CD"))
                {
                    waveData.cd = int.Parse(attribute.Value);
                }
                else if (attribute.Name.Equals("Time"))
                {
                    waveData.delay = int.Parse(attribute.Value);
                }
            }
            WaveList.Add(waveData);
        }

        XmlNodeList grids = document.GetElementsByTagName("Grid");
        foreach (XmlNode node in grids)
        {
            WaveData waveData = new WaveData();
            foreach (XmlAttribute attribute in node.Attributes)
            {
                if (attribute.Name.Equals("id"))
                {
                   disableList.Add(int.Parse(attribute.Value));
                }
               
            }
            
        }
    }
        public void SplitChannelsTest()
        {
            var splitChannelsTests = new SplitChannelsTest[]
            {
                new SplitChannelsTest()
                {
                    BitsPerSample    = 8,
                    NumberOfChannels = 2,
                    Input            = new byte[]
                    {
                        0x15,
                        0x51
                    },
                    Output = new short[][]
                    {
                        new short[]
                        {
                            0x15
                        },
                        new short[]
                        {
                            0x51
                        }
                    }
                },
                new SplitChannelsTest()
                {
                    BitsPerSample    = 4,
                    NumberOfChannels = 1,
                    Input            = new byte[]
                    {
                        0x15,
                        0x51
                    },
                    Output = new short[][]
                    {
                        new short[]
                        {
                            0x01,
                            0x05,
                            0x05,
                            0x01
                        }
                    }
                },
                new SplitChannelsTest()
                {
                    BitsPerSample    = 16,
                    NumberOfChannels = 1,
                    Input            = new byte[]
                    {
                        0x15,
                        0x51
                    },
                    Output = new short[][]
                    {
                        new short[]
                        {
                            0x5115
                        }
                    }
                }
            };

            foreach (var splitChannelsTest in splitChannelsTests)
            {
                using (var stream = new MemoryStream(splitChannelsTest.Input))
                    using (var binaryReader = new BinaryReader(stream))
                    {
                        var actual = WaveData.SplitChannels(binaryReader, splitChannelsTest.NumberOfChannels, splitChannelsTest.BitsPerSample, splitChannelsTest.GetNumberOfFrames());
                        Assert.AreEqual(splitChannelsTest.Output.Length, actual.Length);
                        for (var channel = 0; channel < splitChannelsTest.NumberOfChannels; channel++)
                        {
                            Assert.IsTrue(splitChannelsTest.Output[channel].SequenceEqual(actual[channel]));
                        }
                    }
            }
        }
Exemplo n.º 14
0
    /// <summary>
    /// 读取数据
    /// </summary>
    public void ReadXml()
    {
        XmlDocument document = new XmlDocument();

        document.LoadXml(data.text);

        //获取xml的根节点
        XmlElement root = document.DocumentElement;

        //获取xml的属性
        foreach (XmlAttribute attribute in root.Attributes)
        {
        }

        //获取xml的子节点
        XmlNodeList nodes = document.GetElementsByTagName("Monster");

        foreach (XmlNode node in nodes)
        {
            WaveData waveData = new WaveData();
            foreach (XmlAttribute attribute in node.Attributes)
            {
                if (attribute.Name.Equals("Monster"))
                {
                    string[] arr = attribute.Value.Split(':');
                    int[]    ids = new int[arr.Length];

                    for (int i = 0; i < arr.Length; i++)
                    {
                        ids[i] = int.Parse(arr[i]);
                    }
                    waveData.randomId = ids;
                }
                else if (attribute.Name.Equals("Nums"))
                {
                    waveData.nums = int.Parse(attribute.Value);
                }
                else if (attribute.Name.Equals("CD"))
                {
                    waveData.cd = int.Parse(attribute.Value);
                }
                else if (attribute.Name.Equals("Time"))
                {
                    waveData.delay = int.Parse(attribute.Value);
                }
            }
            WaveList.Add(waveData);
        }

        XmlNodeList grids = document.GetElementsByTagName("Grid");

        foreach (XmlNode node in grids)
        {
            WaveData waveData = new WaveData();
            foreach (XmlAttribute attribute in node.Attributes)
            {
                if (attribute.Name.Equals("id"))
                {
                    disableList.Add(int.Parse(attribute.Value));
                }
            }
        }
    }
        private static void LoadTestData()
        {
            CSV = new StringBuilder();
            CSV.Append("SampleSize, AVMMSE, MSE");
            CSV.Append(Environment.NewLine);

            var slr  = 0.8;
            var sm   = 0.8;
            var uslr = 0.9;
            var usm  = 0.2;
            var usd  = 0.21;

            InputCount = (MaxPathingPoints * CountPerPathing) +
                         (MaxWaterPoints * CountPerWater) +
                         (MaxTowers * CountPerTower) +
                         (MaxEnemies * CountPerEnemy);

            _machineLearningModel = new DeepBeliefNetworkModel();
            _machineLearningModel.Initialize(InputCount, (int)(InputCount * 0.8), uslr, usm, usd, slr, sm);

            var outputList = new List <double>();
            var inputList  = new List <double[]>();

            _waveData = new WaveData
            {
                WaveInputs = inputList,
                WaveScores = outputList,
            };

            var priorMSE = 0.0;

            using (var reader = new StreamReader(@"wavedata.csv"))
            {
                var sampleSize = 0;
                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split('\t');

                    var output = double.Parse(values[0]);
                    outputList.Add(output);

                    var inputCount = values.Length - 1;

                    var inputArray = new double[inputCount];

                    for (var i = 1; i < inputCount; i++)
                    {
                        inputArray[i - 1] = double.Parse(values[i]);
                    }
                    inputList.Add(inputArray);

                    _machineLearningModel.LearnAll(_waveData);

                    CSV.Append($"{++sampleSize}, {_machineLearningModel.AVMMSE}, {_machineLearningModel.LastMSE}");
                    CSV.Append(Environment.NewLine);
                    if ((sampleSize / 50 >= 1 && sampleSize % 50 == 0) || (sampleSize > 20 && Math.Abs(priorMSE - _machineLearningModel.LastMSE) > 0.05))
                    {
                        var wait = _machineLearningModel.LastMSE;
                    }

                    priorMSE = _machineLearningModel.LastMSE;
                }
            }

            var fileName = "ModelData.csv";

            File.WriteAllText(fileName, CSV.ToString());
        }
        private static void IncrementalTest()
        {
            var slr  = 0.8;
            var sm   = 0.8;
            var uslr = 0.9;
            var usm  = 0.2;
            var usd  = 0.21;

            InputCount = (MaxPathingPoints * CountPerPathing) +
                         (MaxWaterPoints * CountPerWater) +
                         (MaxTowers * CountPerTower) +
                         (MaxEnemies * CountPerEnemy);

            var outputList = new List <double>();
            var inputList  = new List <double[]>();

            using (var reader = new StreamReader(@"wavedata.csv"))
            {
                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split('\t');

                    var output = double.Parse(values[0]);
                    outputList.Add(output);

                    var inputCount = values.Length - 1;

                    var inputArray = new double[inputCount];

                    for (var i = 1; i < inputCount; i++)
                    {
                        inputArray[i - 1] = double.Parse(values[i]);
                    }
                    inputList.Add(inputArray);
                }
            }

            for (var modelTest = 5; modelTest <= 9; modelTest++)
            {
                _machineLearningModel = new DeepBeliefNetworkModel();
                _machineLearningModel.Initialize(InputCount, (int)(InputCount * 0.8), uslr, usm, usd, slr, sm);

                CSV = new StringBuilder();
                CSV.Append("SampleSize, AVMMSE, MSE, LearnTime");
                CSV.Append(Environment.NewLine);

                var partialOutput = new List <double>();
                var partialInput  = new List <double[]>();

                _waveData = new WaveData
                {
                    WaveInputs = partialInput,
                    WaveScores = partialOutput,
                };

                var sampleSize = FlatRedBallServices.Random.Next(150, 630);

                for (var i = 0; i <= sampleSize; i++)
                {
                    var randomIndex = FlatRedBallServices.Random.Next(0, outputList.Count - 1);
                    partialInput.Add(inputList[randomIndex]);
                    partialOutput.Add(outputList[randomIndex]);

                    _machineLearningModel.LearnAll(_waveData);
                    CSV.Append($"{i + 1}, {_machineLearningModel.AVMMSE}, {_machineLearningModel.LastMSE}, {_machineLearningModel.LastLearnTime}");
                    CSV.Append(Environment.NewLine);
                }

                var fileName = $"Player{modelTest}Data.csv";
                File.WriteAllText(fileName, CSV.ToString());
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// 设置波数
 /// </summary>
 /// <param name="data"></param>
 /// <param name="turn"></param>
 public void SetWave(WaveData data, int turn, int wave = 1)
 {
     waveData = data;
     currentWave = wave;
     currentTurn = turn;
     Reset();
 }
Exemplo n.º 18
0
        /// <summary>Converts the specified wave data to mono.</summary>
        /// <param name="data">The original wave data.</param>
        /// <returns>The wave data converted to mono.</returns>
        /// <remarks>This function will try to mix the channels, but will revert to a single channel if silence, constructive or destructive interference is detected, or if the number of bits per channel exceeds 48.</remarks>
        private static WaveData ConvertToMono(WaveData data)
        {
            if (data.Format.Channels == 1)
            {
                // is already mono
                return(data);
            }
            else
            {
                // convert to mono
                int bytesPerSample = (data.Format.BitsPerSample + 7) / 8;
                int samples        = data.Bytes.Length / (data.Format.Channels * bytesPerSample);

                /*
                 * In order to detect for silence, constructive interference and
                 * destructive interference, compute the sums of the absolute values
                 * of the signed samples in each channel, considering the high byte only.
                 *  */
                long[] channelSum = new long[data.Format.Channels];
                int    position   = 0;
                for (int i = 0; i < samples; i++)
                {
                    for (int j = 0; j < data.Format.Channels; j++)
                    {
                        int value;
                        if (data.Format.BitsPerSample <= 8)
                        {
                            value = (int)data.Bytes[position + bytesPerSample - 1] - 128;
                        }
                        else
                        {
                            unchecked {
                                value = (int)(sbyte)data.Bytes[position + bytesPerSample - 1];
                            }
                        }
                        channelSum[j] += Math.Abs(value);
                        position      += bytesPerSample;
                    }
                }

                /*
                 * Determine the highest of all channel sums.
                 * */
                long maximum = 0;
                for (int i = 0; i < data.Format.Channels; i++)
                {
                    if (channelSum[i] > maximum)
                    {
                        maximum = channelSum[i];
                    }
                }

                /*
                 * Isolate channels which are not silent. A channel is considered not silent
                 * if its sum is more than 0.39% of the highest sum found in all channels.
                 * */
                long  silenceThreshold       = maximum >> 8;
                int[] nonSilentChannels      = new int[data.Format.Channels];
                int   nonSilentChannelsCount = 0;
                for (int i = 0; i < data.Format.Channels; i++)
                {
                    if (channelSum[i] >= silenceThreshold)
                    {
                        nonSilentChannels[nonSilentChannelsCount] = i;
                        nonSilentChannelsCount++;
                    }
                }

                /*
                 * If there is only one non-silent channel, use that channel.
                 * Otherwise, try to mix the non-silent channels.
                 * */
                if (nonSilentChannelsCount == 1 | bytesPerSample > 3)
                {
                    /* Use the only non-silent channel. */
                    byte[] bytes   = new byte[samples * bytesPerSample];
                    int    channel = nonSilentChannels[0];
                    int    to      = 0;
                    int    from    = channel * bytesPerSample;
                    for (int i = 0; i < samples; i++)
                    {
                        for (int j = 0; j < bytesPerSample; j++)
                        {
                            bytes[to] = data.Bytes[from + j];
                            to++;
                        }
                        from += data.Format.Channels * bytesPerSample;
                    }
                    WaveFormat format = new WaveFormat(data.Format.SampleRate, data.Format.BitsPerSample, 1);
                    return(ConvertToMono8Or16(new WaveData(format, bytes)));
                }
                else
                {
                    /*
                     * Try mixing the non-silent channels. In order to detect for constructive
                     * or destructive interference, compute the sum of the absolute values
                     * of the signed samples in the mixed channel, considering the high
                     * byte only.
                     * */
                    long   mixedSum        = 0;
                    byte[] bytes           = new byte[samples * bytesPerSample];
                    int    from            = 0;
                    int    to              = 0;
                    long   bytesFullRange  = 1 << (8 * bytesPerSample);
                    long   bytesHalfRange  = bytesFullRange >> 1;
                    long   bytesMinimum    = -bytesHalfRange;
                    long   bytesMaximum    = bytesHalfRange - 1;
                    int    mixedRightShift = 8 * (bytesPerSample - 1);
                    for (int i = 0; i < samples; i++)
                    {
                        long mixed = 0;
                        for (int j = 0; j < nonSilentChannelsCount; j++)
                        {
                            if (j == 0)
                            {
                                from += bytesPerSample * nonSilentChannels[0];
                            }
                            else
                            {
                                from += bytesPerSample * (nonSilentChannels[j] - nonSilentChannels[j - 1]);
                            }
                            if (bytesPerSample == 1)
                            {
                                long sample = (long)data.Bytes[from] - 0x80;
                                mixed += sample;
                            }
                            else
                            {
                                ulong sampleUnsigned = 0;
                                for (int k = 0; k < bytesPerSample; k++)
                                {
                                    sampleUnsigned |= (ulong)data.Bytes[from + k] << (k << 3);
                                }
                                unchecked {
                                    long sampleSigned = (long)sampleUnsigned;
                                    if (sampleSigned >= bytesHalfRange)
                                    {
                                        sampleSigned -= bytesFullRange;
                                    }
                                    mixed += sampleSigned;
                                }
                            }
                        }
                        if (bytesPerSample == 1)
                        {
                            mixedSum += Math.Abs(mixed);
                            unchecked {
                                bytes[to] = (byte)(mixed + 0x80);
                            }
                        }
                        else
                        {
                            mixedSum += Math.Abs(mixed >> mixedRightShift);
                            if (mixed < bytesMinimum)
                            {
                                mixed = bytesMinimum;
                            }
                            else if (mixed > bytesMaximum)
                            {
                                mixed = bytesMaximum;
                            }
                            ulong mixedUnsigned;
                            unchecked {
                                if (mixed < 0)
                                {
                                    mixed += bytesFullRange;
                                }
                                mixedUnsigned = (ulong)mixed;
                                for (int k = 0; k < bytesPerSample; k++)
                                {
                                    bytes[to + k]   = (byte)mixedUnsigned;
                                    mixedUnsigned >>= 8;
                                }
                            }
                        }
                        from += bytesPerSample * (data.Format.Channels - nonSilentChannels[nonSilentChannelsCount - 1]);
                        to   += bytesPerSample;
                    }

                    /*
                     * Determine the lowest of all non-silent channel sums.
                     * */
                    long minimum = long.MaxValue;
                    for (int i = 0; i < nonSilentChannelsCount; i++)
                    {
                        if (channelSum[nonSilentChannels[i]] < minimum)
                        {
                            minimum = channelSum[nonSilentChannels[i]];
                        }
                    }

                    /*
                     * Detect constructive and destructive interference. If an interference is
                     * detected, use the first non-silent channel, otherwise the mixed channel.
                     * */
                    if (
                        (double)mixedSum < 0.4 * (double)minimum ||
                        (double)mixedSum > 1.1 * (double)maximum
                        )
                    {
                        /* Interference detected. Use the first non-silent channel. */
                        int channel = nonSilentChannels[0];
                        from = channel * bytesPerSample;
                        to   = 0;
                        for (int i = 0; i < samples; i++)
                        {
                            for (int j = 0; j < bytesPerSample; j++)
                            {
                                bytes[to] = data.Bytes[from + j];
                                to++;
                            }
                            from += data.Format.Channels * bytesPerSample;
                        }
                        WaveFormat format = new WaveFormat(data.Format.SampleRate, data.Format.BitsPerSample, 1);
                        return(ConvertToMono8Or16(new WaveData(format, bytes)));
                    }
                    else
                    {
                        /* No interference detected. Use the mixed channel. */
                        WaveFormat format = new WaveFormat(data.Format.SampleRate, data.Format.BitsPerSample, 1);
                        return(ConvertToMono8Or16(new WaveData(format, bytes)));
                    }
                }
            }
        }
Exemplo n.º 19
0
 private void FindWave()
 {
     currentLine = 0;
     currentWave = data.wavesList[Random.Range(0, data.wavesList.Count)];
 }
Exemplo n.º 20
0
        public void update()
        {
            lock (this)
            {
                if (now_updating) return;  // To avoid stack overflow
                now_updating = true;
            }

            setup_raw_wave();
            apply_filter();

            if (current_over_sample != over_sample || over.wave_id < ans.wave_id)
            {
                if (over.Length != ans.Length * over_sample)
                {
                    lock (fftw)
                    {
                        over = new WaveData(ans.Length * over_sample);
                    }
                }

                if (over_sample == 1)
                {
                    // noneed to upsampling;
                    over.Wave = ans.Wave;
                }
                else
                {
                    over.clear_sp(); // need clear
                    over.Spectrum = ans.Spectrum.Select(x=>x*over_sample);
                }
                over_sampled = over.Wave.Take(num_disp * over_sample).ToArray();
                current_over_sample = over_sample; //calc
                NotifyPropertyChanged("over_sampled");
            }
            initialized = true;
            lock (this)
            {
                now_updating = false;
            }
        }
Exemplo n.º 21
0
 public Wave(WaveData data, Action <WaveSpawnData> spawnEnemyCallbackFunction, Action prepareNextWaveCallback)
 {
     waveData           = data;
     SpawnEnemyCallback = spawnEnemyCallbackFunction;
     NextWaveCallback   = prepareNextWaveCallback;
 }
Exemplo n.º 22
0
        /// <summary>
        /// NFFT: Number of data for FFT (= 2^n > 4tap + num_disp, >1024)
        /// </summary>
        private void update_nfft()
        {
            int val = 1024;
            while (val < num_disp + filter.tap * 4)
                val *= 2;

            if (nfft != val)
            {
                // update
                nfft = val;

                lock (fftw)
                {
                    over = new WaveData(nfft * over_sample_);
                    ans = new WaveData(nfft);
                    factors = new WaveData(nfft);
                    wave = new WaveData(nfft);
                    raw_wave = new WaveData(nfft);
                }
                extracted_raw_wave = new double[nfft];

                // update Omega
                double fs = 1.0 / dt;
                double df = fs / nfft;
                lock (fftw)
                {
                    omega = new ComplexArray(nfft / 2 + 1);
                    omega2 = new ComplexArray(nfft / 2 + 1);
                }

                double df0 = -1.0 / (df*2*Math.PI);
                double v;
                for (int i = 1; i < nfft/2; i++)
                {
                    v = df0 / i;
                    omega[i].Imag = v;
                    omega2[i].Real = - v * v;
                }

                // update freqs
                freqs = Enumerable.Range(0, nfft / 2 + 1).Select(i => df * i).ToArray();
            }
        }
Exemplo n.º 23
0
 // Start is called before the first frame update
 void Start()
 {
     spawners     = new List <ProjectileSpawner>();
     previousData = waveData.Copy();
     Init();
 }
Exemplo n.º 24
0
 void ReloadWaveData()
 {
     wave = DataReader.instance.LoadWaveData();
     ReadWaveData();
 }
Exemplo n.º 25
0
 //constructor initializes the wave
 public EffectSpawnEnemyOnDeath()
 {
     spawnWave      = new WaveData();
     spawnWave.time = 2.0f;
 }
Exemplo n.º 26
0
 /// <summary>
 /// Generates a WAV file with the given <paramref name="Data"/> and params.
 /// </summary>
 /// <param name="Data">The raw sample Data.</param>
 /// <param name="SampleRate">The SampleRate in Hz.</param>
 /// <param name="BitsPerSample">The number of Bits per Sample.</param>
 /// <param name="NrChannel">The number of Channels.</param>
 public WAV(byte[] Data, UInt32 SampleRate, UInt16 BitsPerSample, UInt16 NrChannel)
 {
     Header = new RIFFHeader((uint)(4 + 8 + 16 + 8 + Data.Length + 8));
     Wave   = new WaveData(Data, SampleRate, BitsPerSample, NrChannel);
 }
Exemplo n.º 27
0
 public void fromJson(string jsonData)
 {
     this.data = JsonUtility.FromJson <WaveData>(jsonData);
 }
Exemplo n.º 28
0
 public XAudio2SoundClip(WaveData data)
 {
     _data = data;
 }
    public void ChangeState(EBattleState battleState)
    {
        _stateStartTime = TimeUtils.TimestampMilliseconds;

        switch (battleState)
        {
        case EBattleState.E_WAVE_START:
        {
            _currentWave++;
            _currentWaveData    = null;
            _currentWaveDataIdx = 0;

            GenerateRandomCurrentWave();

            if (GSB_GameManager.Instance.CurrentGameState == GSB_GameManager.GameState.E_PLAYING_1_PLAYER)
            {
                if (HealthVSBoxText != null)
                {
                    HealthVSBoxText.enabled = false;
                }

                if (WaveLabel != null)
                {
                    WaveLabel.text = "WAVE ";
                    if (_currentWave < 10)
                    {
                        WaveLabel.text += "0";
                    }

                    WaveLabel.text += _currentWave;

                    WaveLabel.gameObject.SetActive(true);
                }

                if (Player != null)
                {
                    Player.MakeDamage(-HealthRecoveryAfterWave);
                }

                GameAudioManager.SharedInstance.PlaySound("Audio/Sounds/GSB_wavestart");

                _stateTime = 3000;
            }
            else
            {
                _stateTime = 0;
            }

            break;
        }

        case EBattleState.E_PLAYING:
        {
            if (WaveLabel != null)
            {
                WaveLabel.gameObject.SetActive(false);
            }

            break;
        }

        case EBattleState.E_WAVE_END:
        {
            _stateTime = 2000;

            break;
        }

        case EBattleState.E_GAMEOVER:
        {
            if (GSB_GameManager.Instance.CurrentGameState == GSB_GameManager.GameState.E_PLAYING_1_PLAYER)
            {
                GameAudioManager.SharedInstance.StopSound(0);
                GameAudioManager.SharedInstance.PlaySound("Audio/Sounds/GSB_gameover");

                if (GameOverLabel != null)
                {
                    GameOverLabel.gameObject.SetActive(true);
                }

                _stateTime = 4000;
            }
            else if (GSB_GameManager.Instance.CurrentGameState == GSB_GameManager.GameState.E_PLAYING_2_VERSUS)
            {
                if (GSB_GameManager.Instance.NetworkController.PlayerOnlineController != null)
                {
                    GSB_GameManager.Instance.NetworkController.PlayerOnlineController.CmdPlayerHasDiedClient(GSB_GameManager.Instance.NetworkController.PlayerControllerId);
                }

                _stateTime = 0;
            }

            break;
        }
        }

        _battleState = battleState;
    }
Exemplo n.º 30
0
    void playWavePerFrame()
    {
        var topVerAry  = topMesh.vertices;
        var sideVerAry = sideMesh.vertices;
        //var texData = WaveTexture.GetRawTextureData ();
        //Debug.Log ("texData size : " + texData.Length);
        //float rateX = WaveTexture.width / ((float)planeX * MaxWidthClip);
        //float rateY = WaveTexture.height/ ((float)planeY * MaxHeightClip);
        //float rateX = ClipWidth / (float)planeX ;
        //float rateY = ClipHeight / (float)planeY ;
        float rateX = ClipWidth / TitleWidth.x;
        float rateY = ClipHeight / TitleWidth.y;

        //reset plane height
        for (int y = 0; y < planeY; y++)
        {
            for (int x = 0; x < planeX; x++)
            {
                topVerAry[x + y * planeX].y = 0;

                if (y == 0)
                {
                    sideVerAry[x].z = 0;
                }
            }
        }
        //sideVerAry[planeX].z = 0;

        for (int i = 0; i < playWaveCenter.Count; i++)
        {
            WaveData wave = playWaveCenter[i];
            if (wave.DoPlay == false)
            {
                continue;
            }

            int     clip   = wave.NowClip;
            Vector2 center = wave.Center;

            Vector2 sPos;
            sPos.x = (clip % MaxWidthClip) * ClipWidth;
            sPos.y = (clip / MaxWidthClip) * ClipHeight;

            var texData = WaveTexture.GetPixels((int)sPos.x, (int)sPos.y, ClipWidth, ClipHeight);

            Vector2 pivot = new Vector2(center.x - (TitleWidth.x / 2), center.y - (TitleWidth.y / 2));
            for (int y = 0; y < TitleWidth.y; y++)
            {
                for (int x = 0; x < TitleWidth.x; x++)
                {
                    int nowX = (int)pivot.x + x;
                    if (nowX < 0 || nowX > planeX)
                    {
                        continue;
                    }

                    int nowY = (int)pivot.y + y;
                    if (nowY < 0 || nowY > planeY)
                    {
                        continue;
                    }


                    //Vector2 sPos;
                    //sPos.x = (clip % TotalClip) * ClipWidth;
                    //sPos.y = (clip / TotalClip) * ClipHeight;

                    //var basePos = (int)(sPos.x + x * rateX) + (int)(sPos.y + y * rateY) * WaveTexture.width;
                    var basePos = (int)(x * rateX) + (int)(y * rateY) * ClipWidth;


                    //var value = WaveTexture.getp;
                    //verAry [x + y * planeX].y = value;
                    var value = (texData[basePos].r) - OffsetColorValue;
                    topVerAry[nowX + nowY * planeX].y += value * Amplitude;

                    //Debug.Log (value);

                    // side plane
                    if (nowY == 0)
                    {
                        sideVerAry[planeX - nowX].z += value * Amplitude * -1;
                    }
                }
            }


            wave.NowClip++;
            if (wave.NowClip == TotalClip)
            {
                wave.DoPlay = false;
            }
        }

        topMesh.vertices = topVerAry;
        topMesh.RecalculateNormals();

        sideMesh.vertices = sideVerAry;
        sideMesh.RecalculateNormals();
    }
Exemplo n.º 31
0
        private void MakeMovie_Main()
        {
            this.DiscJacket         = new Canvas2(this.DiscJacketFile);
            this.BluredDiscJacket   = PictureUtils.Blur(this.DiscJacket, 5);           // 要調整
            this.MarginedDiscJacket = PictureUtils.PutMargin(this.DiscJacket);

            {
                string wavFile       = this.WD.GetPath("audio.wav");
                string masterWavFile = this.WD.GetPath("audio2.wav");

                FFmpegConv.MakeWavFile(this.SourceMediaFile, wavFile);

                if (this.MasterFlag && MasterUtils.Mastering(wavFile, masterWavFile))
                {
                    this.Wave = new WaveData(masterWavFile);
                    this.FFmpeg.Audio.PutAudioFile(masterWavFile);
                }
                else
                {
                    this.Wave = new WaveData(wavFile);
                    this.FFmpeg.Audio.PutAudioFile(this.SourceMediaFile);
                }
            }

            ShadowSpectraData ss = new ShadowSpectraData();
            FadeInOutData     f1 = new FadeInOutData()
            {
                MaxValue = 20
            };
            FadeInOutData f2 = new FadeInOutData();

            f1.Rate = 1.0;

            int frameNum = DoubleTools.ToInt((this.Wave.Length * 1.0 / this.Wave.WavHz) * AudioPicMP4Props.FPS);

            for (int frame = 0; frame < frameNum; frame++)
            {
                if (frame == 2 * AudioPicMP4Props.FPS)
                {
                    f1.TargetRate = 0.0;
                }

                if (frame == frameNum - 10 - f2.MaxValue)
                {
                    f2.TargetRate = 1.0;
                }

                f1.Approach();
                f2.Approach();

                double rate    = frame * 1.0 / (frameNum - 1);
                double invRate = 1.0 - rate;

                double r1 = 1.0 + 0.2 * rate;
                double r2 = 1.0 + 0.1 * invRate;

                D4Rect wallRect;
                D4Rect frntRect;

                {
                    D2Size size = Utils.TangentSize(
                        new D2Size(AudioPicMP4Props.VIDEO_W, AudioPicMP4Props.VIDEO_H),
                        new D2Size(this.DiscJacket.GetWidth(), this.DiscJacket.GetHeight()),
                        false
                        );

                    size.W *= r1;
                    size.H *= r1;

                    wallRect = Utils.Centering(new D2Size(AudioPicMP4Props.VIDEO_W, AudioPicMP4Props.VIDEO_H), size);
                }

                {
                    D2Size size = Utils.TangentSize(
                        new D2Size(AudioPicMP4Props.VIDEO_W, AudioPicMP4Props.VIDEO_H),
                        new D2Size(this.DiscJacket.GetWidth(), this.DiscJacket.GetHeight()),
                        true
                        );

                    size.W *= r2;
                    size.H *= r2;

                    // マージン分
                    size.W *= this.MarginedDiscJacket.GetWidth() * 1.0 / this.DiscJacket.GetWidth();
                    size.H *= this.MarginedDiscJacket.GetHeight() * 1.0 / this.DiscJacket.GetHeight();

                    frntRect = Utils.Centering(new D2Size(AudioPicMP4Props.VIDEO_W, AudioPicMP4Props.VIDEO_H), size);
                }

                Canvas2 frameImg = new Canvas2(AudioPicMP4Props.VIDEO_W, AudioPicMP4Props.VIDEO_H);

                PictureUtils.Paste(frameImg, this.BluredDiscJacket, wallRect);
                PictureUtils.Filter(frameImg, Color.Black, 0.5);                 // 要調整
                PictureUtils.Paste(frameImg, this.MarginedDiscJacket, frntRect);
                PictureUtils.Filter(frameImg, Color.Black, 0.1);                 // 要調整

                PictureUtils.Filter(frameImg, Color.Black, f1.Rate);             // 背景カーテン

                this.Wave.SetWavPart(DoubleTools.ToInt((frame * 1.0 / AudioPicMP4Props.FPS + AudioPicMP4Props.AUDIO_DELAY_SEC) * this.Wave.WavHz));
                SpectrumGraph0001 sg = new SpectrumGraph0001(hz => this.Wave.GetSpectrum(hz));
                ss.Projection(sg.Spectra);
                this.DrawSpectra(frameImg, sg, ss);

                PictureUtils.Filter(frameImg, Color.Black, f2.Rate);                 // 前景カーテン

                frameImg.Save(this.FFmpeg.GetImageFile(frame), ImageFormat.Jpeg, AudioPicMP4Props.JPEG_QUALITY);

                GC.Collect();
            }

            this.FFmpeg.MakeMovie();

            File.Copy(this.FFmpeg.GetMovieFile(), this.DestMP4File);
        }
Exemplo n.º 32
0
        static WaveData convertWaveData(WaveData inputData, ushort outputSampleRate, bool outputStereo)
        {
            // Step 1: Mix channels
            float[][] mixed;
            if ((inputData.channelSamples.Length > 1 && !outputStereo) || (inputData.channelSamples.Length > 2 && outputStereo))
            {
                long sampleCount = inputData.channelSamples[0].LongLength;
                mixed = new float[outputStereo ? 2 : 1][];
                for (int j = 0; j < mixed.Length; ++j)
                {
                    mixed[j] = new float[sampleCount];
                }
                for (long i = 0; i < sampleCount; ++i)
                {
                    for (int j = 0; j < inputData.channelSamples.Length; ++j)
                    {
                        mixed[j % mixed.Length][i] += inputData.channelSamples[j][i];
                    }
                    if (mixed.Length > 1)
                    {
                        mixed[0][i] /= ((inputData.channelSamples.Length + 1) / 2);
                        mixed[1][i] /= inputData.channelSamples.Length / 2;
                    }
                    else
                    {
                        mixed[0][i] /= inputData.channelSamples.Length;
                    }
                }
            }
            else
            {
                mixed = inputData.channelSamples;
            }

            // Step 2: Adjust sample rate
            WaveData result;

            if (outputSampleRate != inputData.sampleRate)
            {
                string tempFile1 = "resample1.wav";
                using (WaveFileWriter writer = new WaveFileWriter(tempFile1, WaveFormat.CreateIeeeFloatWaveFormat(inputData.sampleRate, mixed.Length))) {
                    for (long i = 0; i < mixed[0].LongLength; ++i)
                    {
                        for (int j = 0; j < mixed.Length; ++j)
                        {
                            writer.WriteSample(mixed[j][i]);
                        }
                    }
                }

                string tempFile2 = "resample2.wav";
                using (WaveFileReader reader = new WaveFileReader(tempFile1)) {
                    WaveFormat outFormat = new WaveFormat(outputSampleRate, reader.WaveFormat.Channels);
                    using (MediaFoundationResampler resampler = new MediaFoundationResampler(reader, outFormat)) {
                        WaveFileWriter.CreateWaveFile(tempFile2, resampler);
                    }
                }

                result = readWaveData(tempFile2);
                File.Delete(tempFile1);
                File.Delete(tempFile2);
            }
            else
            {
                result                = new WaveData();
                result.sampleRate     = inputData.sampleRate;
                result.channelSamples = mixed;
            }

            return(result);
        }
Exemplo n.º 33
0
        public AnalyzedAudio Analyze(WaveData wave, double framePeriod, Action <double> notifyProgress)
        {
            var frameSize  = wave.SampleRate * framePeriod * 0.001 * FrameSizeRate;
            var frameCount = (int)Math.Ceiling(wave.Wave.Length / frameSize);
            var frames     = wave.Wave.SplitByIndexes(
                Enumerable.Range(0, frameCount).Select((i) => (int)Math.Ceiling(i * frameSize)),
                (frame, start, i) => new Frame(start, i, frame)
                );
            var silentFrames = frames.Where((x) => x.Silent).ToArray();

            var elements = new List <AnalyzedElement>();

            if (silentFrames.Any())
            {
                if (silentFrames.First().Index != 0)
                {
                    silentFrames = new Frame(0, 0, (int)Math.Ceiling(frameSize), false).PushTo(silentFrames).ToArray();
                }
                if (!frames.Last().Silent)
                {
                    silentFrames = silentFrames.Append(frames.Last()).ToArray();
                }

                var capFrames = silentFrames.Zip3(
                    new Frame(silentFrames[0], silentFrames[0].Index - 1).PushTo(silentFrames),
                    silentFrames.Skip(1).Append(new Frame(silentFrames.Last(), silentFrames.Last().Index + 1)),
                    (f, s, t) => new { Target = f, Prev = s, Next = t }
                    )
                                .Where((x) => (x.Prev.Index + 1 == x.Target.Index && x.Target.Index + 1 != x.Next.Index) || (x.Prev.Index + 1 != x.Target.Index && x.Target.Index + 1 == x.Next.Index))
                                .Select((x) => x.Target)
                                .ToArray()
                                .AsEnumerable();


                foreach (var cap in capFrames.Grouped(2))
                {
                    var first = cap.First();
                    if (cap.Count() < 2)
                    {
                        elements.Add(
                            new AnalyzedElement(
                                wave.Wave.Skip(first.Position).ToArray(),
                                first.Position,
                                first.Index * FrameSizeRate,
                                wave.SampleRate,
                                framePeriod,
                                first.Silent
                                )
                            );
                    }
                    else
                    {
                        elements.Add(
                            new AnalyzedElement(
                                wave.Wave.Skip(first.Position).Take(cap.Last().Position - first.Position + cap.Last().FrameSize).ToArray(),
                                first.Position,
                                first.Index * FrameSizeRate,
                                wave.SampleRate,
                                framePeriod,
                                first.Silent
                                )
                            );
                    }
                }
            }
            else
            {
                elements.Add(new AnalyzedElement(wave.Wave, 0, 0, wave.SampleRate, framePeriod, false));
            }

            notifyProgress(1 / (double)(elements.Count + 1) * 100.0);

            var progress       = 1;
            var skipElement    = new List <AnalyzedElement>();
            var combineElement = new List <CombineElement>();

            Parallel.For(0, elements.Count, (i) =>
            {
                var target = elements[i];
                try
                {
                    target.Analyze();

                    lock (LockObject)
                    {
                        progress++;
                        notifyProgress(progress / (double)(elements.Count + 1) * 100.0);
                    }
                }
                catch (IndexOutOfRangeException)
                {
                    var side = new List <AnalyzedElement>();
                    if (i > 0 && (elements[i - 1].SamplePosition + elements[i - 1].Wave.Length - target.SamplePosition) / frameSize <= CombinableFrameGap)
                    {
                        side.Add(elements[i - 1]);
                    }
                    if (i < elements.Count - 1 && (elements[i + 1].SamplePosition - target.SamplePosition - target.Wave.Length) / frameSize <= CombinableFrameGap)
                    {
                        side.Add(elements[i + 1]);
                    }
                    if (side.Count > 0)
                    {
                        combineElement.Add(new CombineElement(new List <AnalyzedElement>()
                        {
                            target
                        }, side));
                    }
                    else
                    {
                        skipElement.Add(target);
                    }
                }
            });

            while (true)
            {
                var concat = combineElement.Zip(combineElement.Skip(1), (t, n) => Optional <CombineElement> .Iif(() => t.Concat(n), t.CanConcat(n)));

                if (concat.All((c) => c.IsEmpty))
                {
                    break;
                }
                else
                {
                    var newCombineElement = concat.SelectMany((c) => c).ToList();
                    skipElement.AddRange(combineElement.SelectMany(c => c.Targets).Except(newCombineElement.SelectMany(c => c.Targets)));
                    combineElement = newCombineElement;
                }
            }
            elements.RemoveAll(skipElement.Contains);

            double totalCount = elements.Count + combineElement.Count + 1.0;

            progress = elements.Count + 1;
            notifyProgress(progress / totalCount * 100.0);
            Parallel.For(0, combineElement.Count, (i) =>
            {
                try
                {
                    var element = combineElement[i].Combine(wave.Wave);
                    element.Analyze();

                    lock (LockObject)
                    {
                        elements.RemoveAll(combineElement[i].Targets.Contains);
                        elements.RemoveAll(combineElement[i].SideElements.Contains);
                        elements.Add(element);
                        progress++;
                        notifyProgress(progress / totalCount * 100.0);
                    }
                }
                catch (IndexOutOfRangeException)
                {
                    lock (LockObject)
                    {
                        elements.RemoveAll(combineElement[i].Targets.Contains);
                        progress++;
                        notifyProgress(progress / totalCount * 100.0);
                    }
                }
            });

            elements.Sort();

            var f0 = new double[(int)Math.Ceiling((wave.Wave.Length / frameSize) * FrameSizeRate)];

            foreach (var element in elements)
            {
                element.F0.BlockCopy(f0, element.FramePosition);
            }

            return(new WorldAnalyzedAudio(f0, framePeriod, wave.SampleRate, wave.Wave.Length, 0, elements.ToArray()));
        }
Exemplo n.º 34
0
		/// <summary>Converts the specified wave data to 8-bit or 16-bit mono.</summary>
		/// <param name="data">The original wave data.</param>
		/// <returns>The wave data converted to 8-bit or 16-bit mono.</returns>
		/// <remarks>If the bits per sample per channel are less than or equal to 8, the result will be 8-bit mono, otherwise 16-bit mono.</remarks>
		internal static WaveData ConvertToMono8Or16(WaveData data) {
			if ((data.Format.BitsPerSample == 8 | data.Format.BitsPerSample == 16) & data.Format.Channels == 1) {
				// already in target format
				return data;
			} else if (data.Format.Channels != 1) {
				// convert to mono first
				return ConvertToMono(data);
			} else if (data.Format.BitsPerSample < 8) {
				// less than 8 bits per sample
				WaveFormat format = new WaveFormat(data.Format.SampleRate, 8, 1);
				return new WaveData(format, data.Bytes);
			} else if (data.Format.BitsPerSample < 16) {
				// between 9 and 15 bits per sample
				WaveFormat format = new WaveFormat(data.Format.SampleRate, 16, 1);
				return new WaveData(format, data.Bytes);
			} else {
				// more than 16 bits per sample
				int bytesPerSample = data.Format.BitsPerSample + 7 >> 3;
				int samples = data.Bytes.Length / bytesPerSample;
				byte[] bytes = new byte[samples << 1];
				for (int i = 0; i < samples; i++) {
					int j = (i + 1) * bytesPerSample;
					bytes[2 * i] = data.Bytes[j - 2];
					bytes[2 * i + 1] = data.Bytes[j - 1];
				}
				WaveFormat format = new WaveFormat(data.Format.SampleRate, 16, 1);
				return new WaveData(format, bytes);
			}
		}
Exemplo n.º 35
0
    private void applyWaveData(BlobData blobData, WaveData waveData, int frequencyIndex)
    {
        Directions.Cardinal direction = waveData.genDirection ();
        if (direction != Directions.Cardinal.unknown)
            blobData.moveDirection = direction;

        float sizeMultiplier = waveData.genSizeMultiplier (frequencyIndex);
        IntVector3 blobSize = blobData.getSize ();
        blobData.setSize (blobSize * sizeMultiplier);

        Vector2 offsetMultiplier = waveData.genOffset ();
        IntVector3 mainSize = worldManager.getMainSizeVector ();
        IntVector2 collisionSize= MDCollision.getCollisionArraySize(blobData.getSizeVector(),blobData.getMoveDirectionUnitVector());
        blobData.offset.x = (int)(collisionSize.x * offsetMultiplier.x);
        blobData.offset.y = (int)(collisionSize.y * offsetMultiplier.y);
    }
Exemplo n.º 36
0
        public override void OnInspectorGUI()
        {
            _height    = 50;
            _maxHeight = 0;
            _width     = 3;

            bool   typeChanged = false;
            string clickedName = "";

            GUI.Label(MakeRect(150, 17), "File to load");
            file = (TextAsset)EditorGUI.ObjectField(MakeRect(250, 17, true), file, typeof(TextAsset), false);
            if (GUI.Button(MakeRect(350, 17, true), "Load file"))
            {
                _data.LoadFile(file);
            }

            for (int waveIdx = 0; waveIdx < _data.wavesList.Count; ++waveIdx)
            {
                MakeRect(20, 17);
                bool foldout = EditorGUI.Foldout(MakeRect(200, 17, true), waveIdx == _foldoutId, "Wave " + waveIdx);

                if (!foldout)
                {
                    if (_foldoutId == waveIdx)
                    {
                        _foldoutId = -1;
                    }
                    continue;
                }

                _foldoutId = waveIdx;
                WaveData wave = _data.wavesList[waveIdx];
                wave.SetWidth(_dataWidth);
                for (int lineIdx = wave.lines.Count - 1; lineIdx >= 0; --lineIdx)
                {
                    string[] tileStringsTab = wave.lines[lineIdx].Split('-');

                    List <string> tileStrings = new List <string>();

                    for (int tileId = 0; tileId < wave.GetWidth(); ++tileId)
                    {
                        string name = "TileDefault";
                        if (tileStringsTab.Length > tileId)
                        {
                            name = tileStringsTab[tileId];
                        }

                        tileStrings.Add(name);

                        Rect currentRect = MakeRect(150, 20);
                        GUI.Label(currentRect, name.Replace("Tile", ""));
                    }

                    string newString = string.Join("-", tileStrings.ToArray());
                    // ReSharper disable once RedundantCheckBeforeAssignment
                    if (_data.wavesList[waveIdx].lines[lineIdx] != newString)
                    {
                        _data.wavesList[waveIdx].lines[lineIdx] = newString;
                    }

                    NewLine();
                }
            }

            /*
             * NewLine();
             * if (GUI.Button(MakeRect(150, 17, true), "Refresh"))
             * {
             *      SetDescriptions();
             * }
             * float previewSize = 75;
             * int count = 0;
             * List<Texture2D> images = new List<Texture2D>();
             * foreach (GameObject tile in tiles)
             * {
             ++count;
             *      Rect currentRect =  MakeRect(previewSize, 17);
             *      GUI.Label(currentRect, tile.name.Replace("Tile", ""));
             *      images.Add(AssetPreview.GetAssetPreview(tile));
             *
             *      currentRect.height += previewSize;
             *
             *      if (DetectClick(currentRect))
             *      {
             *              typeChanged = true;
             *              clickedName = tile.name;
             *      }
             *
             *      if (count > 10)
             *      {
             *              NewLine();
             *              foreach (Texture2D im in images)
             *              {
             *                      GUI.Label(MakeRect(previewSize, previewSize), im);
             *              }
             *              images.Clear();
             *              NewLine();
             *              count = 0;
             *      }
             * }
             * NewLine();
             * foreach (Texture2D im in images)
             * {
             *      GUI.Label(MakeRect(previewSize, previewSize), im);
             * }
             *
             * NewLine();
             * GUI.Label(MakeRect(100, 17), "Width");
             * _dataWidth = Mathf.Clamp(EditorGUI.IntField(MakeRect(200, 17, true), _dataWidth), 2, 10);
             *
             * NewLine();
             *
             * if (GUI.Button(MakeRect(200, 17), "Add wave"))
             * {
             *      _data.wavesList.Add(new WaveData());
             * }
             * if (GUI.Button(MakeRect(200, 17, true), "Save"))
             * {
             *      EditorUtility.SetDirty(_data);
             *      AssetDatabase.SaveAssets();
             * }
             *
             * NewLine();
             *
             * for (int waveIdx = 0; waveIdx < _data.wavesList.Count; ++waveIdx)
             * {
             *      MakeRect(20, 17);
             *      bool foldout = EditorGUI.Foldout(MakeRect(200, 17), waveIdx == _foldoutId, "Wave " + waveIdx);
             *      if (GUI.Button(MakeRect(20, 20, true), "X"))
             *      {
             *              _data.wavesList.RemoveAt(waveIdx);
             *              return;
             *      }
             *
             *      if (!foldout)
             *      {
             *              if (_foldoutId == waveIdx)
             *              {
             *                      _foldoutId = -1;
             *              }
             *              continue;
             *      }
             *
             *      _foldoutId = waveIdx;
             *      WaveData wave = _data.wavesList[waveIdx];
             *      wave.SetWidth(_dataWidth);
             *      for (int lineIdx = wave.lines.Count - 1; lineIdx >= 0; --lineIdx)
             *      {
             *              if (GUI.Button(MakeRect(20, 17), "X"))
             *              {
             *                      wave.lines.RemoveAt(lineIdx);
             *                      continue;
             *              }
             *              string[] tileStringsTab = wave.lines[lineIdx].Split('-');
             *
             *              List<string> tileStrings = new List<string>();
             *
             *              for (int tileId = 0; tileId < wave.GetWidth(); ++tileId)
             *              {
             *                      string name = "TileDefault";
             *                      if (tileStringsTab.Length > tileId)
             *                      {
             *                              name = tileStringsTab[tileId];
             *                      }
             *
             *                      tileStrings.Add(name);
             *                      Rect selectionRect;
             *                      if (lineIdx == _selectedCoordinates.x && tileId == _selectedCoordinates.y)
             *                      {
             *                              if (typeChanged)
             *                              {
             *                                      name = clickedName;
             *                                      tileStrings[tileId] = name;
             *                              }
             *
             *                              selectionRect = new Rect(_width - 1, _height - 1, 77, 77);
             *                              EditorGUI.DrawPreviewTexture(selectionRect, _selectedTexture);
             *                      }
             *
             *                      Rect currentRect = MakeRect(75, 75);
             *                      if (_tileImages.ContainsKey(name) == false)
             *                      {
             *                              name = "TileDefault";
             *                      }
             *                      GUI.Label(currentRect, _tileImages[name]);
             *                      GUI.Label(currentRect, name.Replace("Tile", ""));
             *                      if (!DetectClick(currentRect))
             *                      {
             *                              continue;
             *                      }
             *                      _selectedCoordinates = new Vector2Int(lineIdx, tileId);
             *                      tileStrings[tileId] = name;
             *              }
             *
             *              string newString = string.Join("-", tileStrings.ToArray());
             *              // ReSharper disable once RedundantCheckBeforeAssignment
             *              if (_data.wavesList[waveIdx].lines[lineIdx] != newString)
             *              {
             *                      _data.wavesList[waveIdx].lines[lineIdx] = newString;
             *              }
             *
             *              NewLine();
             *      }
             *
             *      MakeRect(20, 17);
             *      if (GUI.Button(MakeRect(200, 17, true), "Add Line"))
             *      {
             *              wave.lines.Insert(0, "");
             *      }
             * }*/
        }
Exemplo n.º 37
0
 public WaveBehaviour(WaveData waveData, int enemyListSize, int levelEventId)
 {
     enemyList         = new List <Enemy>(enemyListSize);
     this.waveData     = waveData;
     this.levelEventId = levelEventId;
 }
Exemplo n.º 38
0
 public WaveDataEx(WaveData WaveData)
 {
     m_WaveData = WaveData;
 }
Exemplo n.º 39
0
		/// <summary>Converts the specified wave data to mono.</summary>
		/// <param name="data">The original wave data.</param>
		/// <returns>The wave data converted to mono.</returns>
		/// <remarks>This function will try to mix the channels, but will revert to a single channel if silence, constructive or destructive interference is detected, or if the number of bits per channel exceeds 48.</remarks>
		private static WaveData ConvertToMono(WaveData data) {
			if (data.Format.Channels == 1) {
				// is already mono
				return data;
			} else {
				// convert to mono
				int bytesPerSample = (data.Format.BitsPerSample + 7) / 8;
				int samples = data.Bytes.Length / (data.Format.Channels * bytesPerSample);
				/* 
				 * In order to detect for silence, constructive interference and
				 * destructive interference, compute the sums of the absolute values
				 * of the signed samples in each channel, considering the high byte only.
				 *  */
				long[] channelSum = new long[data.Format.Channels];
				int position = 0;
				for (int i = 0; i < samples; i++) {
					for (int j = 0; j < data.Format.Channels; j++) {
						int value;
						if (data.Format.BitsPerSample <= 8) {
							value = (int)data.Bytes[position + bytesPerSample - 1] - 128;
						} else {
							unchecked {
								value = (int)(sbyte)data.Bytes[position + bytesPerSample - 1];
							}
						}
						channelSum[j] += Math.Abs(value);
						position += bytesPerSample;
					}
				}
				/*
				 * Determine the highest of all channel sums.
				 * */
				long maximum = 0;
				for (int i = 0; i < data.Format.Channels; i++) {
					if (channelSum[i] > maximum) {
						maximum = channelSum[i];
					}
				}
				/*
				 * Isolate channels which are not silent. A channel is considered not silent
				 * if its sum is more than 0.39% of the highest sum found in all channels.
				 * */
				long silenceThreshold = maximum >> 8;
				int[] nonSilentChannels = new int[data.Format.Channels];
				int nonSilentChannelsCount = 0;
				for (int i = 0; i < data.Format.Channels; i++) {
					if (channelSum[i] >= silenceThreshold) {
						nonSilentChannels[nonSilentChannelsCount] = i;
						nonSilentChannelsCount++;
					}
				}
				/*
				 * If there is only one non-silent channel, use that channel.
				 * Otherwise, try to mix the non-silent channels.
				 * */
				if (nonSilentChannelsCount == 1 | bytesPerSample > 3) {
					/* Use the only non-silent channel. */
					byte[] bytes = new byte[samples * bytesPerSample];
					int channel = nonSilentChannels[0];
					int to = 0;
					int from = channel * bytesPerSample;
					for (int i = 0; i < samples; i++) {
						for (int j = 0; j < bytesPerSample; j++) {
							bytes[to] = data.Bytes[from + j];
							to++;
						}
						from += data.Format.Channels * bytesPerSample;
					}
					WaveFormat format = new WaveFormat(data.Format.SampleRate, data.Format.BitsPerSample, 1);
					return ConvertToMono8Or16(new WaveData(format, bytes));
				} else {
					/*
					 * Try mixing the non-silent channels. In order to detect for constructive
					 * or destructive interference, compute the sum of the absolute values
					 * of the signed samples in the mixed channel, considering the high
					 * byte only.
					 * */
					long mixedSum = 0;
					byte[] bytes = new byte[samples * bytesPerSample];
					int from = 0;
					int to = 0;
					long bytesFullRange = 1 << (8 * bytesPerSample);
					long bytesHalfRange = bytesFullRange >> 1;
					long bytesMinimum = -bytesHalfRange;
					long bytesMaximum = bytesHalfRange - 1;
					int mixedRightShift = 8 * (bytesPerSample - 1);
					for (int i = 0; i < samples; i++) {
						long mixed = 0;
						for (int j = 0; j < nonSilentChannelsCount; j++) {
							if (j == 0) {
								from += bytesPerSample * nonSilentChannels[0];
							} else {
								from += bytesPerSample * (nonSilentChannels[j] - nonSilentChannels[j - 1]);
							}
							if (bytesPerSample == 1) {
								long sample = (long)data.Bytes[from] - 0x80;
								mixed += sample;
							} else {
								ulong sampleUnsigned = 0;
								for (int k = 0; k < bytesPerSample; k++) {
									sampleUnsigned |= (ulong)data.Bytes[from + k] << (k << 3);
								}
								unchecked {
									long sampleSigned = (long)sampleUnsigned;
									if (sampleSigned >= bytesHalfRange) {
										sampleSigned -= bytesFullRange;
									}
									mixed += sampleSigned;
								}
							}
						}
						if (bytesPerSample == 1) {
							mixedSum += Math.Abs(mixed);
							unchecked {
								bytes[to] = (byte)(mixed + 0x80);
							}
						} else {
							mixedSum += Math.Abs(mixed >> mixedRightShift);
							if (mixed < bytesMinimum) {
								mixed = bytesMinimum;
							} else if (mixed > bytesMaximum) {
								mixed = bytesMaximum;
							}
							ulong mixedUnsigned;
							unchecked {
								if (mixed < 0) {
									mixed += bytesFullRange;
								}
								mixedUnsigned = (ulong)mixed;
								for (int k = 0; k < bytesPerSample; k++) {
									bytes[to + k] = (byte)mixedUnsigned;
									mixedUnsigned >>= 8;
								}
							}
						}
						from += bytesPerSample * (data.Format.Channels - nonSilentChannels[nonSilentChannelsCount - 1]);
						to += bytesPerSample;
					}
					/*
					 * Determine the lowest of all non-silent channel sums.
					 * */
					long minimum = long.MaxValue;
					for (int i = 0; i < nonSilentChannelsCount; i++) {
						if (channelSum[nonSilentChannels[i]] < minimum) {
							minimum = channelSum[nonSilentChannels[i]];
						}
					}
					/*
					 * Detect constructive and destructive interference. If an interference is
					 * detected, use the first non-silent channel, otherwise the mixed channel.
					 * */
					if (
						(double)mixedSum < 0.4 * (double)minimum ||
						(double)mixedSum > 1.1 * (double)maximum
					) {
						/* Interference detected. Use the first non-silent channel. */
						int channel = nonSilentChannels[0];
						from = channel * bytesPerSample;
						to = 0;
						for (int i = 0; i < samples; i++) {
							for (int j = 0; j < bytesPerSample; j++) {
								bytes[to] = data.Bytes[from + j];
								to++;
							}
							from += data.Format.Channels * bytesPerSample;
						}
						WaveFormat format = new WaveFormat(data.Format.SampleRate, data.Format.BitsPerSample, 1);
						return ConvertToMono8Or16(new WaveData(format, bytes));
					} else {
						/* No interference detected. Use the mixed channel. */
						WaveFormat format = new WaveFormat(data.Format.SampleRate, data.Format.BitsPerSample, 1);
						return ConvertToMono8Or16(new WaveData(format, bytes));
					}
				}
			}
		}
Exemplo n.º 40
0
 public static void SpawnWave(int eventId, WaveData waveData)
 {
     OnSpawnWave?.Invoke(eventId, waveData);
 }