예제 #1
0
        public static float[] FromBitmap(Bitmap bitmap)
        {
            float[] result = new float[bitmap.Width * bitmap.Height];

            int k = 0;

            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    var pixel = bitmap.GetPixel(i, j);

                    float value = (float)(pixel.R + pixel.G + pixel.B) / 3f;

                    float valueNormalized = value / 255;

                    result[k] = valueNormalized;
                    k++;
                }
            }

            if (result.All(x => x == 0))
            {
            }

            return(result);
        }
예제 #2
0
 public bool Check(Vector3[] vertices)
 {
     float[] sidesSquared = new float[3];
     for (int i = 0; i < 3; i++)
     {
         int j = (i + 1) % 3;
         sidesSquared[i] = (vertices[i] - vertices[j]).LengthSquared();
     }
     return(sidesSquared.All(sqr => sqr < maxLengthSquared));
 }
예제 #3
0
        private void SetCustomCameraPosition(string content, bool forceUpdateInFreeCameraMode)
        {
            //note: ここはv0.9.0以降ではシリアライズしたJson、それより前ではfloatのカンマ区切り配列。
            //Jsonシリアライズを導入したのは、OSのロケールによっては(EU圏とかで)floatの小数点が","になる問題をラクして避けるため。
            float[] values = new float[0];
            try
            {
                //シリアライズ: 普通はこれで通る
                values = JsonUtility.FromJson <SerializedCameraPosition>(content)
                         .values
                         .ToArray();
            }
            catch (Exception ex)
            {
                LogOutput.Instance.Write(ex);
            }

            if (values.Length != 6)
            {
                try
                {
                    //旧バージョンから設定をインポートしたときはこれでうまくいく
                    values = content.Split(',')
                             .Select(float.Parse)
                             .ToArray();
                }
                catch (Exception ex)
                {
                    LogOutput.Instance.Write(ex);
                }
            }

            if (values.Length != 6)
            {
                return;
            }

            //ぜんぶ0な場合、無効値として無視
            if (values.All(v => Mathf.Abs(v) < Mathf.Epsilon))
            {
                return;
            }

            _customCameraPosition = new Vector3(
                values[0], values[1], values[2]
                );

            _customCameraRotationEuler = new Vector3(
                values[3], values[4], values[5]
                );

            UpdateCameraTransform(forceUpdateInFreeCameraMode);
        }
예제 #4
0
        public void SubCTest_float()
        {
            foreach (int length in new[] { 24, 128 })
            {
                float[] a = new float[length];
                float[] y = new float[length];

                Vectors.Set(length, 0, a, 0);
                Mathematics.SubC(length, a, 0, 1, y, 0);
                Assert.IsTrue(y.All(x => x == -1));

                Vectors.Set(length, float.NegativeInfinity, a, 0);
                Mathematics.SubC(length, a, 0, 1, y, 0);
                Assert.IsTrue(y.All(x => float.IsNegativeInfinity(x)));

                Vectors.Set(length, float.PositiveInfinity, a, 0);
                Mathematics.SubC(length, a, 0, 1, y, 0);
                Assert.IsTrue(y.All(x => float.IsPositiveInfinity(x)));

                Vectors.Set(length, float.MinValue, a, 0);
                Mathematics.SubC(length, a, 0, 1, y, 0);
                Assert.IsTrue(y.All(x => x == float.MinValue));

                Vectors.Set(length, float.MaxValue, a, 0);
                Mathematics.SubC(length, a, 0, 1, y, 0);
                Assert.IsTrue(y.All(x => x == float.MaxValue));

                Vectors.Set(length, float.NaN, a, 0);
                Mathematics.SubC(length, a, 0, 1, y, 0);
                Assert.IsTrue(y.All(x => float.IsNaN(x)));
            }
        }
예제 #5
0
        public void No_Arg_All_Values_Are_Between_Zero_And_MaxValue()
        {
            var floats = new float[Assertion.Amount];

            for (var i = 0; i < Assertion.Amount; i++)
            {
                floats[i] = FloatProvider.Float();
            }

            floats.AssertNotAllValuesAreTheSame();
            Assert.True(
                floats.All(x => x >= 0 && x < float.MaxValue),
                "Floats.All(x => x >= 0 && x < Float.MaxValue)"
                );
        }
    internal static IEnumerable <int> Read10Digits(this IReadWrite io, string prompt, Stream retryText)
    {
        while (true)
        {
            var numbers = new float[10];
            io.ReadNumbers(prompt, numbers);

            if (numbers.All(n => n == 0 || n == 1 || n == 2))
            {
                return(numbers.Select(n => (int)n));
            }

            io.Write(retryText);
        }
    }
예제 #7
0
        public void Inclusive_Min_Arg()
        {
            var floats = new float[Assertion.Amount];

            const float arg = 100;

            for (var i = 0; i < Assertion.Amount; i++)
            {
                floats[i] = FloatProvider.Float(arg, arg);
            }

            Assert.True(
                floats.All(x => x == arg),
                "Floats.All(x => x == arg)"
                );
        }
예제 #8
0
        public void All_Values_Are_Between_Zero_And_Max()
        {
            var floats = new float[Assertion.Amount];

            const float max = 200;

            for (var i = 0; i < Assertion.Amount; i++)
            {
                floats[i] = FloatProvider.Float(max);
            }

            floats.AssertNotAllValuesAreTheSame();
            Assert.True(
                floats.All(x => x >= 0 && x < max),
                "Floats.All(x => x >= 0 && x < max)"
                );
        }
예제 #9
0
        public void Exclusive_Max_Arg()
        {
            var         floats = new float[Assertion.Amount];
            const float max    = 100;
            const float min    = max - MaxSupportedPrecision;

            for (var i = 0; i < Assertion.Amount; i++)
            {
                floats[i] = FloatProvider.Float(min, max);
            }


            floats.AssertNotAllValuesAreTheSame();
            Assert.True(
                floats.All(x => x < max),
                "Floats.All(x => x < max)"
                );
        }
예제 #10
0
        private static void Go(string filename, ICollection <string> filenames, int width, int height, int fps,
                               string background,
                               string logo, string vgmFile, int previewFrameskip, float highPassFrequency, float scale,
                               Type triggerAlgorithm, int viewSamples, int numColumns, string ffMpegPath, string ffMpegExtraArgs,
                               string masterAudioFilename, float autoScale, Color gridColor, float gridWidth, bool gridOuter,
                               Color zeroLineColor, float zeroLineWidth, float lineWidth)
        {
            filename = Path.GetFullPath(filename);
            var waitForm = new WaitForm();

            waitForm.Show();

            int sampleRate;

            using (var reader = new WaveFileReader(filenames.First()))
            {
                sampleRate = reader.WaveFormat.SampleRate;
            }

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            int stepsPerFile  = 1 + (highPassFrequency > 0 ? 1 : 0) + 2;
            int totalProgress = filenames.Count * stepsPerFile;
            int progress      = 0;

            var loadTask = Task.Run(() =>
            {
                // Do a parallel read of all files
                var channels = filenames.AsParallel().Select((wavFilename, channelIndex) =>
                {
                    var reader = new WaveFileReader(wavFilename);
                    var buffer = new float[reader.SampleCount];

                    // We read the file and convert to mono
                    reader.ToSampleProvider().ToMono().Read(buffer, 0, (int)reader.SampleCount);
                    Interlocked.Increment(ref progress);

                    // We don't care about ones where the samples are all equal
                    // ReSharper disable once CompareOfFloatsByEqualityOperator
                    if (buffer.Length == 0 || buffer.All(s => s == buffer[0]))
                    {
                        // So we skip steps here
                        reader.Dispose();
                        Interlocked.Add(ref progress, stepsPerFile - 1);
                        return(null);
                    }

                    if (highPassFrequency > 0)
                    {
                        // Apply the high pass filter
                        var filter = BiQuadFilter.HighPassFilter(reader.WaveFormat.SampleRate, highPassFrequency, 1);
                        for (int i = 0; i < buffer.Length; ++i)
                        {
                            buffer[i] = filter.Transform(buffer[i]);
                        }

                        Interlocked.Increment(ref progress);
                    }

                    float max = float.MinValue;
                    foreach (var sample in buffer)
                    {
                        max = Math.Max(max, Math.Abs(sample));
                    }

                    return(new { Data = buffer, WavReader = reader, Max = max });
                }).Where(ch => ch != null).ToList();

                if (autoScale > 0 || scale > 1)
                {
                    // Calculate the multiplier
                    float multiplier = 1.0f;
                    if (autoScale > 0)
                    {
                        multiplier = autoScale / channels.Max(channel => channel.Max);
                    }

                    if (scale > 1)
                    {
                        multiplier *= scale;
                    }

                    // ...and we apply it
                    channels.AsParallel().Select(channel => channel.Data).ForAll(samples =>
                    {
                        for (int i = 0; i < samples.Length; ++i)
                        {
                            samples[i] *= multiplier;
                        }

                        Interlocked.Increment(ref progress);
                    });
                }

                return(channels.ToList());
            });

            while (!loadTask.IsCompleted)
            {
                Application.DoEvents();
                Thread.Sleep(1);
                waitForm.Progress("Reading data...", (double)progress / totalProgress);
            }

            var voiceData = loadTask.Result.Select(channel => channel.Data).ToList();

            waitForm.Close();

            // Emit normalised data to a WAV file for later mixing
            if (masterAudioFilename == null)
            {
                // Generate a temp filename
                masterAudioFilename = filename + ".wav";
                // Mix the audio. We should probably not be re-reading it here... should do this in one pass.
                foreach (var reader in loadTask.Result.Select(channel => channel.WavReader))
                {
                    reader.Position = 0;
                }
                var mixer     = new MixingSampleProvider(loadTask.Result.Select(channel => channel.WavReader.ToSampleProvider()));
                var length    = (int)loadTask.Result.Max(channel => channel.WavReader.SampleCount);
                var mixedData = new float[length * mixer.WaveFormat.Channels];
                mixer.Read(mixedData, 0, mixedData.Length);
                // Then we want to deinterleave it
                var leftChannel  = new float[length];
                var rightChannel = new float[length];
                for (int i = 0; i < length; ++i)
                {
                    leftChannel[i]  = mixedData[i * 2];
                    rightChannel[i] = mixedData[i * 2 + 1];
                }
                // Then Replay Gain it
                // The +3 is to make it at "YouTube loudness", which is a lot louder than ReplayGain defaults to.
                var replayGain = new TrackGain(sampleRate);
                replayGain.AnalyzeSamples(leftChannel, rightChannel);
                float multiplier = (float)Math.Pow(10, (replayGain.GetGain() + 3) / 20);
                Debug.WriteLine($"ReplayGain multiplier is {multiplier}");
                // And apply it
                for (int i = 0; i < mixedData.Length; ++i)
                {
                    mixedData[i] *= multiplier;
                }
                WaveFileWriter.CreateWaveFile(
                    masterAudioFilename,
                    new FloatArraySampleProvider(mixedData, sampleRate).ToWaveProvider());
            }

            var backgroundImage = new BackgroundRenderer(width, height, Color.Black);

            if (background != null)
            {
                using (var bm = Image.FromFile(background))
                {
                    backgroundImage.Add(new ImageInfo(bm, ContentAlignment.MiddleCenter, true, DockStyle.None, 0.5f));
                }
            }

            if (logo != null)
            {
                using (var bm = Image.FromFile(logo))
                {
                    backgroundImage.Add(new ImageInfo(bm, ContentAlignment.BottomRight, false, DockStyle.None, 1));
                }
            }

            if (vgmFile != null)
            {
                var gd3     = Gd3Tag.LoadFromVgm(vgmFile);
                var gd3Text = gd3.ToString();
                if (gd3Text.Length > 0)
                {
                    backgroundImage.Add(new TextInfo(gd3Text, "Tahoma", 16, ContentAlignment.BottomLeft, FontStyle.Regular,
                                                     DockStyle.Bottom, Color.White));
                }
            }

            var renderer = new WaveformRenderer
            {
                BackgroundImage            = backgroundImage.Image,
                Columns                    = numColumns,
                FramesPerSecond            = fps,
                Width                      = width,
                Height                     = height,
                SamplingRate               = sampleRate,
                RenderedLineWidthInSamples = viewSamples,
                RenderingBounds            = backgroundImage.WaveArea
            };

            if (gridColor != Color.Empty && gridWidth > 0)
            {
                renderer.Grid = new WaveformRenderer.GridConfig
                {
                    Color      = gridColor,
                    Width      = gridWidth,
                    DrawBorder = gridOuter
                };
            }

            if (zeroLineColor != Color.Empty && zeroLineWidth > 0)
            {
                renderer.ZeroLine = new WaveformRenderer.ZeroLineConfig
                {
                    Color = zeroLineColor,
                    Width = zeroLineWidth
                };
            }

            foreach (var channel in voiceData)
            {
                renderer.AddChannel(new Channel(channel, Color.White, lineWidth, "Hello world", Activator.CreateInstance(triggerAlgorithm) as ITriggerAlgorithm, 0));
            }

            var outputs = new List <IGraphicsOutput>();

            if (ffMpegPath != null)
            {
                outputs.Add(new FfmpegOutput(ffMpegPath, filename, width, height, fps, ffMpegExtraArgs, masterAudioFilename));
            }

            if (previewFrameskip > 0)
            {
                outputs.Add(new PreviewOutput(previewFrameskip));
            }

            try
            {
                renderer.Render(outputs);
            }
            catch (Exception)
            {
                // Should mean it was cancelled
            }
            finally
            {
                foreach (var graphicsOutput in outputs)
                {
                    graphicsOutput.Dispose();
                }
            }
        }
예제 #11
0
 public void Fill()
 {
     float[] v = new float[127];
     v.AsSpan().Fill(() => 1.8f);
     Assert.IsTrue(v.All(f => f.EqualsWithDelta(1.8f)));
 }
예제 #12
0
        public void LoadAudio(IList <string> filenames)
        {
            // TODO file load feedback for GUI?
            Console.WriteLine("Loading audio files...");
            using (var reader = new WaveFileReader(filenames.First()))
            {
                SampleRate = reader.WaveFormat.SampleRate;
            }

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            // int stepsPerFile = 3 + (settings.HighPassFilterFrequency > 0 ? 1 : 0);
            // int totalProgress = settings.InputFiles.Count * stepsPerFile;
            // int progress = 0;

            // We have to copy the reference to make it "safe" for threads
            var loadTask = Task.Run(() =>
            {
                // Do a parallel read of all files
                var channels = filenames.AsParallel().Select((wavFilename, channelIndex) =>
                {
                    var filename = Path.GetFileName(wavFilename);
                    Console.WriteLine($"- Reading {filename}");
                    var reader = new WaveFileReader(wavFilename);
                    var buffer = new float[reader.SampleCount];

                    // We read the file and convert to mono
                    reader.ToSampleProvider().ToMono().Read(buffer, 0, (int)reader.SampleCount);
                    // Interlocked.Increment(ref progress);

                    // We don't care about ones where the samples are all equal
                    // ReSharper disable once CompareOfFloatsByEqualityOperator
                    if (buffer.Length == 0 || buffer.All(s => s == buffer[0]))
                    {
                        Console.WriteLine($"- Skipping {filename} because it is silent");
                        // So we skip steps here
                        reader.Dispose();
                        // Interlocked.Add(ref progress, stepsPerFile - 1);
                        return(null);
                    }

                    if (HighPassFilterFrequency > 0)
                    {
                        Console.WriteLine($"- High-pass filtering {filename}");
                        // Apply the high pass filter
                        var filter = BiQuadFilter.HighPassFilter(reader.WaveFormat.SampleRate, HighPassFilterFrequency, 1);
                        for (int i = 0; i < buffer.Length; ++i)
                        {
                            buffer[i] = filter.Transform(buffer[i]);
                        }

                        // Interlocked.Increment(ref progress);
                    }

                    float max = float.MinValue;
                    foreach (var sample in buffer)
                    {
                        max = Math.Max(max, Math.Abs(sample));
                    }

                    return(new ChannelData {
                        Data = buffer, WavReader = reader, Max = max, Filename = filename
                    });
                }).Where(ch => ch != null).ToList();

                if (AutoScalePercentage > 0 || VerticalScaleMultiplier > 1)
                {
                    // Calculate the multiplier
                    float multiplier = 1.0f;
                    if (AutoScalePercentage > 0)
                    {
                        multiplier = AutoScalePercentage / 100 / channels.Max(channel => channel.Max);
                    }

                    if (VerticalScaleMultiplier > 1)
                    {
                        multiplier *= VerticalScaleMultiplier;
                    }

                    // ...and we apply it
                    Console.WriteLine($"- Applying scaling (x{multiplier:N})...");
                    channels.AsParallel().Select(channel => channel.Data).ForAll(samples =>
                    {
                        for (int i = 0; i < samples.Length; ++i)
                        {
                            samples[i] *= multiplier;
                        }

                        // Interlocked.Increment(ref progress);
                    });
                }

                return(channels.ToList());
            });

            loadTask.Wait();

            _data  = loadTask.Result;
            Length = TimeSpan.FromSeconds((double)_data.Max(x => x.Data.Length) / SampleRate);
        }