Example #1
0
int main(int argc, char*argv[]) {
    // ████████ INITS 1 ████████
#ifndef COMMON_INITS1
    cfg.init("bedlab.cfg");
    ui2::init_ui();
    Vec2i windowsize;
    Vec2i screen_resolution = { int(VideoMode::getDesktopMode().width), int(VideoMode::getDesktopMode().height) };
    if (cfg.getvar<int>("auto_winsize")) {
        auto window_scale = cfg.getvar<Vec2>("window_scale");
        windowsize = Vec2i(scal(Vec2(screen_resolution), window_scale));
    }
    else {
        windowsize = cfg.getvar<Vec2i>("windowsize");
    }
    winsize = Vec2(windowsize);
    //UI.init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE
    ui2::init_console(); // ALWAYS AFTER SO IT CAN GET WINDOW SIZE

    wincenter = 0.5f*Vec2(windowsize);
    Vec2i windowpos;
    VideoMode::getDesktopMode().height;
    if (cfg.getvar<int>("stick_left")) {
        windowpos = Vec2i(
            screen_resolution.x - windowsize.x - 10,
            screen_resolution.y - windowsize.y - 40
        );
    }
    else
        windowpos = (Vec2i(5, 25));

    sf::RenderWindow window(sf::VideoMode(windowsize.x, windowsize.y),
        "bedlab!", 7
        //,sf::ContextSettings(0, 0, 1)
    );
    window.setFramerateLimit(cfg.getvar<int>("fps_max"));
    frame_duration = 1.0f / cfg.getvar<int>("fps_max");

    window.setPosition(windowpos);

    vector<string> keys;
    auto choice = cfg.getstr("app");
    // show_keys(cfg.getstr("app"), keys);
#endif
// ████████ INITS2 ████████
#ifndef COMMON_INITS2

// we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway.
// Texture cursor_tx;
// if (!cursor_tx.loadFromFile(cfg.getstr("cursor")))
//     cout << "did not load cursor" << endl;
// Sprite cursor;
// cursor.setTexture(cursor_tx);
// cursor.setOrigin(3, 3);

    CircleShape cursor = mkcircle({ 0,0 }, Color::Transparent, 3, 1);
    Color background = cfg.getvar<Color>("background");
    window.setMouseCursorVisible(false);
    Vec2 mpos;
    bool leftclicked = false, rightclicked = false;

    // view and zoom
    View view, ui_view;
    ui_view = view = window.getDefaultView();
    float zoomlevel = 1;
    Vec2 mpos_abs;
    float frame_duration = 1.0f / cfg.getvar<int>("fps_max");
#endif // COMMON_INITS2
    // ████████ APP ACTUAL ████████

    float smaller_size = min(windowsize.y, windowsize.x);
    string descriptor;

    Transform transf;
    transf.translate(10, 10);
    transf.scale(Vec2(smaller_size, smaller_size));

    transf_glob = transf;

    auto addvt_col = [&](Vec2 v, Color col) {
        glob_vert_single.append(Vertex(transf.transformPoint(v), col));
    };

    auto va_to_va_col = [&](mesh2d&idxd_v, Color col) {
        for (unsigned int i = 0; i < idxd_v.size(); ++i)
        {
            // if (i<)
            addvt_col(idxd_v[i].first, col);
            addvt_col(idxd_v[i].second, col);

            //addpt(idxd_v[i].first, Orange, 5);
            //addpt(idxd_v[i].second, Cyan, 5);
        }

        for (auto&a : idxd_v.verts) {
            addpt_col(a, col, 2);
        }
    };
    auto stripify = [&](vector<Vec2> strip, Color col) {
        glob_vert_single = VertexArray(LineStrip);

        for (auto&a : strip) {
            glob_vert_single.append(Vertex(transf.transformPoint(a), col));
            addpt_col(a, col, 2);
        }

    };

    size_t edit_mode = 1;
    // ████████████████████████████████████████
    sf::Sound sound;

    auto make_segment = [](int size, int amplitude) {
        vector<Int16> sample;

        for (int i = 0; i < size; ++i)
        {
            sample.push_back(amplitude*sin(float(i)*PI*2.0f));
        }
        return sample;
    };

    /*
    <Jonny> duration will be sample count * sample rate
    <Jonny> so at 44khz you'll have 44k samples per second
    <Jonny> if you have 88k samples that will last 2 second
    */

    plot_bare pl;
    
    float sample_rate = 22050;

    auto make_tone = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i){
            sample.push_back(amplitude*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;
    };
    // http://sol.gfxile.net/interpolation/

    auto make_tone_progressive_2 = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i) {
            float soft = float(i) / sample_quantity;
            //soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft);
            soft = 1 - (1 - 2 * soft)*(1 - 2 * soft);
            soft *= amplitude;

            sample.push_back(soft*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;

    };
    auto make_tone_progressive_4 = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i) {
            float soft = float(i) / sample_quantity;
            soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft);
            soft *= amplitude;

            sample.push_back(soft*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;

    };
    auto make_tone_progressive_6 = [&](float duration, float frequency, int amplitude_exp) {
        float sample_quantity = sample_rate * duration;
        vector<Int16> sample;
        int amplitude = 1 << amplitude_exp;
        float increment = frequency / sample_rate;
        float x = 0;
        for (int i = 0; i < sample_quantity; ++i) {
            float soft = float(i) / sample_quantity;
            soft = 1 - (1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft)*(1 - 2 * soft);
            soft *= amplitude;

            sample.push_back(soft*sin(float(x)*PI*2.0f));
            x += increment;
        }
        return sample;

    };


    auto sample_string2 = cfg.getstr("sound1");
    auto spl1 = splitdelim(sample_string2, ',');
    auto params2 = splitdelim(spl1[0]);
    //float freq = parse<float>(params[1]);
    //float duration = parse<float>(params[2]);
    //float amplitude_exp = parse<float>(params[3]);

    float freq,  duration, amplitude_exp, pause;
    int times, smoothstep_exp;
    dip_bars dbars(FONT, FONTSIZE, {400,20});
    //dbars.add("sampling", &sampling,5, 10000);
    dbars.add("sample_rate", &sample_rate, 1000, 45000);
    dbars.add("freq", &freq,50,5000);
    dbars.add("duration", &duration, 0.5, 5);
    dbars.add("amplitude_exp", &amplitude_exp, 1, 14);
    SoundBuffer buffer; // always lived!
    auto load_sample2 = [&](){
        auto delaystr = splitdelim(spl1[1]);
        vector<float> segment_sizes;
        float total = 0;
        for (auto&a : delaystr) {
            total += parse<float>(a);
            segment_sizes.push_back(parse<float>(a));
        }
        int i = 0;
        vector<Int16> sample;
        vector<vector<Int16>> samples;

        for (auto&a : segment_sizes) a /= total;
        //for (auto&a : segment_sizes) msg(a*total);
        for (auto&a : segment_sizes){
            auto scaled_back = duration * freq * a;

            int amplitude = i % 2 ? 0 : 1 << int(amplitude_exp);
            msg(scaled_back);
            samples.push_back(make_segment(scaled_back, amplitude));
            ++i;
        }
        for (auto&a : samples){
            concatenate(sample, a);
        }
        SoundBuffer buffer;
        // \param sampleRate   Sample rate (number of samples to play per second)

        buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size()/duration);
        {
            // plut josting just plotting
            vector<Vec2> plot_this;
            int i = 0;

            for (auto&a : sample) {
                //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) });
                plot_this.push_back({ float(i), float(a) });
                i++;
            }
            pl.clear();
            pl.from_data_normalized(plot_this);
        }

        return buffer;
    };
    auto load_sample = [&]() {
        auto delaystr = splitdelim(spl1[1]);
        vector<float> segment_sizes;
        float total = 0;
        for (auto&a : delaystr) {
            total += parse<float>(a);
            segment_sizes.push_back(parse<float>(a));
        }
        int i = 0;
        vector<Int16> sample;
        vector<vector<Int16>> samples;

        for (auto&a : segment_sizes) a /= total;
        //for (auto&a : segment_sizes) msg(a*total);
        if (smoothstep_exp == 2) {
            for (auto&a : segment_sizes) {
                samples.push_back(make_tone_progressive_2(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
       
        }
        else if (smoothstep_exp == 4){
            for (auto&a : segment_sizes) {
                samples.push_back(make_tone_progressive_4(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }


        for (auto&a : samples) {
            concatenate(sample, a);
        }
        SoundBuffer buffer;
        // \param sampleRate   Sample rate (number of samples to play per second)
        //sample = make_tone(2, 400, 8);
        //buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration);
        buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration);
        if (true) {
            // plut josting just plotting
            vector<Vec2> plot_this;
            int i = 0;

            for (auto&a : sample) {
                //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) });
                plot_this.push_back({ float(i), float(a) });
                i++;
            }
            pl.clear();
            pl.from_data_normalized(plot_this);
        }

        return buffer;
    };
    
    auto load_from_cfg = [
        &freq,
        &duration,
        &amplitude_exp,
        &pause,
        &times,
        &descriptor,
        &smoothstep_exp]() {
        auto temp_cfg = configfile();
        temp_cfg.init("bedlab.cfg");
        auto sample_string = temp_cfg.getstr("sound2");

        auto things = split2(sample_string, ",");
        auto params = split2(things[0], " ");
        auto segments = split2(things[1], " ");

        string segments_dashed = things[1];

        if (segments_dashed[0] == ' ') segments_dashed = segments_dashed.substr(1);
        if (things[1][0] == ' ') things[1] = things[1].substr(1);
        if (things[2][0] == ' ') things[2] = things[2].substr(1);
        if (things[3][0] == ' ') things[3] = things[3].substr(1);
        if (things[4][0] == ' ') things[4] = things[4].substr(1);
        
        for (auto&c : segments_dashed) {
            if (c == ' ') c = '-';
        }
        
        freq = parse<float>(params[0]);
        duration = parse<float>(params[1]);
        amplitude_exp = parse<float>(params[2]);
        pause = parse<float>(things[2]);
        times = parse<int>(things[3]);
        smoothstep_exp = parse<int>(things[4]);
        msgs(smoothstep_exp);
        descriptor =
            params[0]         // freq
            + "_" + params[1] // duration
            + "_" + params[2] // amplitude_exp
            + "_" + segments_dashed
            + "_" + things[2] // pause
            + "_" + things[3] // times
            + "_" + things[4] // smoothstep_exp
            ;
        msgs(descriptor);
        return segments;
    };
    auto segments = load_from_cfg();

    auto flexible_expanse = [&]() {
        vector<float> segment_sizes, segment_concat;
        for (auto&a : segments) {
            segment_sizes.push_back(parse<float>(a));
        }
        segment_sizes.push_back(pause);

        for (int i = 0; i < times; ++i) {
            concatenate(segment_concat, segment_sizes);
        }
        float total = 0;
        for (auto&a : segment_concat) total+=a;
        for (auto&a : segment_concat) a /= total;

        vector<vector<Int16>> samples;
        int i = 0;
        if (smoothstep_exp == 2) {
            for (auto&a : segment_concat) {
                samples.push_back(make_tone_progressive_2(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }
        else if (smoothstep_exp == 4) {
            for (auto&a : segment_concat) {
                samples.push_back(make_tone_progressive_4(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }
        else if (smoothstep_exp == 6) {
            for (auto&a : segment_concat) {
                samples.push_back(make_tone_progressive_6(duration*a, freq, i % 2 ? 0 : int(amplitude_exp)));
                ++i;
            }
        }
        vector<Int16> sample;

        for (auto&a : samples) { concatenate(sample, a); }
        SoundBuffer buffer;

        //buffer.loadFromSamples(&sample[0], sample.size(), 1, sample.size() / duration);
        buffer.loadFromSamples(&sample[0], sample.size(), 1, sample_rate);
        if (true) {
            // plut josting just plotting
            vector<Vec2> plot_this;
            int i = 0;

            for (auto&a : sample) {
                //plot_this.push_back({ float(i), 200 * float(a) / (1 << 12) });
                plot_this.push_back({ float(i), float(a) });
                i++;
            }
            pl.clear();
            pl.from_data_normalized(plot_this);
        }
        return buffer;
    };

    //buffer = load_sample(sample_string);
    auto make_sound = [&]() {
        //buffer = load_sample();
        segments = load_from_cfg();
        buffer = flexible_expanse();

        sound.setBuffer(buffer);
        string filename = "rngtn_" + descriptor+".wav";
        //buffer.saveToFile("file.wav");
        buffer.saveToFile(filename);
        sound.play();
    };

    make_sound();
    dbars.read_from_pointers();


    // ████████ callbacks ████████

#ifndef LOOP_LAMBDAS
    draw = [&]() {
        window.setView(view);
        //////////////// OBJECTS THAT CAN ZOOMED ////////////////
        window.draw(glob_vert_single);
        for (auto&a : glob_pts)window.draw(a);
        for (auto&a : glob_rects)window.draw(a);
        for (auto&a : glob_vert)window.draw(a);
        for (auto&a : glob_texts)window.draw(a);
        // UI draw, AFTER ui view and BEFORE other draw
        window.setView(ui_view);
        //////////////// OBJECTS THAT CANNOT ZOOMED, MEANING UI ////////////////
        pl.draw(window);
        dbars.draw(window);

        //br.drawwithtext(window);
        UI.draw(window);
        window.draw(cursor);
    };
    update = [&]() {
    };
    treatkeyevent = [&](Keyboard::Key k) {
        switch (k)
        {
        case Keyboard::E:
            break;
        case Keyboard::I:

            break;
        case Keyboard::Q:
            break;
        case Keyboard::BackSpace:
            glob_pts.clear();
            glob_texts.clear();
            glob_rects.clear();
            glob_vert.clear();
            break;

        case Keyboard::Space:
            make_sound();
            sound.play();
            sound.setLoop(false);
            break;

        case Keyboard::S:
            screenshot(window);
            break;
        case Keyboard::Num1:
        case Keyboard::Num2:
        case Keyboard::Num3:
        case Keyboard::Num4:
        case Keyboard::Num5:
            break;
        }
    };
    mousemoved = [&](Vec2 pos) {
        cursor.setPosition(pos);
        if (leftclicked);

        dbars.mouse_moved(pos);
    };
    mouseclick = [&](sf::Mouse::Button button) {
        if (button == Mouse::Button::Left) leftclicked = true;
        if (button == Mouse::Button::Right) rightclicked = true;
    
        if (button == Mouse::Button::Left) dbars.mouse_click(mpos);

    
    };
    mouserelease = [&](sf::Mouse::Button button) {
        if (button == Mouse::Button::Left) leftclicked = false;
        if (button == Mouse::Button::Right) rightclicked = false;

        if (button == Mouse::Button::Left) { 
            dbars.mouse_release(); 
            make_sound();

        }

    };
    loop = [&]() {
        while (window.isOpen())
        {
            sf::Event event;
            while (window.pollEvent(event))
            {
                switch (event.type)
                {
                case sf::Event::KeyPressed:
                    if (event.key.code == sf::Keyboard::Escape)
                        window.close();
                    treatkeyevent(event.key.code);
                    break;
                case sf::Event::Closed:
                    window.close();
                    break;
                case sf::Event::MouseButtonPressed:
                    mouseclick(event.mouseButton.button);
                    break;
                case sf::Event::MouseButtonReleased:
                    mouserelease(event.mouseButton.button);
                    break;
                case sf::Event::MouseMoved:
                    mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
                    mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);
                    mousemoved(mpos);
                    break;
                default:
                    treatotherevent(event);
                    break;
                }
            }

            window.clear(background);
            update();
            draw();
            window.display();
        }
    };
    treatotherevent = [&](Event&e) {
        if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta)
        {
            mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);

            //view = window.getView();
            if (e.mouseWheel.delta < 0)
            {
                zoomlevel *= 2.f;
                view.setSize(view.getSize()*2.f);
                view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
                //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
            }
            if (e.mouseWheel.delta > 0)
            {
                zoomlevel *= 0.5;
                view.setSize(view.getSize()*.5f);
                view.setCenter(.5f*(view.getCenter() + mpos_abs));
                //view.setCenter(.5f*(view.getCenter() + mpos_abs));
            }
            window.setView(view);
        }
    };
#endif // LOOP_LAMBDAS

    loop();
}
Example #2
0
int main() {
 
	const unsigned SAMPLES = 992;			// Samples = time period * sample rate = 22.5*44100 = 992 samples
	const unsigned SAMPLE_RATE = 44100;		// Standard for audio 
	double AMPLITUDE = 30000;					// Amplitude need to be sorted out accoring to DX8 standard 
	double microsec = 44; 
	double sync = 0;	
	vector<Int16> frame;					// raw stream of samples 
											// fill one time period in the raw sample array
	vector<Int16>::iterator it; 
	it = frame.begin(); 

	map<int, double > PPMChannels; 
	PPMChannels[1] = 00.00	; 
	PPMChannels[2] = 50.00	;
	PPMChannels[3] = 50.00	;
	PPMChannels[4] = 50.00	;
	PPMChannels[5] = 50.00	;
	PPMChannels[6] = 50.00	;
	PPMChannels[7] = 50.00	;
	PPMChannels[8] = 50.00	;
	



	for(int i = 1; i <= 8; i++)
	{
		sync += PPMChannels[i];
	}
	sync = (int)(13.3-((sync)*0.008)) * 44;
	cout << sync; 
	

	frame.insert(it, (int)(sync), AMPLITUDE);
	it = frame.end(); 
	frame.insert(it, (int)(0.4*microsec), -1*AMPLITUDE); 
	it = frame.end(); 

	for (int i = 1; i <= 8; i++){
	
		frame.insert(it, (int)(.7*microsec), AMPLITUDE); 
		it = frame.end(); 
		frame.insert(it, (int)(PPMChannels[i] * 0.8*microsec / 100), AMPLITUDE); 
		it = frame.end(); 
		frame.insert(it, (int)(0.4*microsec), -1*AMPLITUDE); 
		it = frame.end(); 
	}

	cout << frame.size();
	//size_t SAMPLES = frame.size(); 
	/*for (unsigned i = SAMPLES / 2; i < SAMPLES; i++){
		frame[i] = 0; 
	}*/
	
	Int16* p = &frame[0]; 

	SoundBuffer Buffer;						// define a sound buffer and load raw samples to buffer 
	if (!Buffer.loadFromSamples(p, frame.size(), 1, SAMPLE_RATE)) {
		std::cerr << "Loading failed!" << std::endl;
		return 1;
	}

	Sound Sound;						// create sound object 
	Sound.setBuffer(Buffer);			// pass the buffer we created 
	Sound.setLoop(true);				// play sound in loop 
	Sound.play();					
	while (1) {							// If the program ends, the audio will end too so we make it wait infinitely 	
		sleep(milliseconds(10));
	}
	return 0;
}