node-editor.cpp 46.2 KB
Newer Older
1
2
3
4
// Copyright (c) 2020 INRA Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

Gauthier Quesnel's avatar
Gauthier Quesnel committed
5
6
7
8
#include "gui.hpp"
#include "imnodes.hpp"

#include <filesystem>
9
#include <fstream>
10
11
#include <future>
#include <mutex>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
12
#include <string>
13
14
#include <thread>

15
#include <fmt/format.h>
16
#include <irritator/core.hpp>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
17
#include <irritator/io.hpp>
18
19
20

namespace irt {

21
22
window_logger log_w;

23
enum class simulation_status
24
{
25
26
27
28
    success,
    running,
    uninitialized,
    internal_error,
29
30
};

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
struct observation_output
{
    observation_output() = default;

    observation_output(const char* name_)
      : name(name_)
    {}

    const char* name = nullptr;
    array<float> data;
    double tl = 0.0;
    float min = -1.f;
    float max = +1.f;
    int id = 0;
};

static void
observation_output_initialize(const irt::observer& obs,
                              const irt::time t) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);
    std::fill_n(output->data.data(), output->data.size(), 0.0f);
    output->tl = t;
    output->min = -1.f;
    output->max = +1.f;
    output->id = 0;
}

static void
observation_output_observe(const irt::observer& obs,
                           const irt::time t,
                           const irt::message& msg) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);

    auto value = static_cast<float>(msg.to_real_64(0));
    output->min = std::min(output->min, value);
    output->max = std::max(output->max, value);

    for (double to_fill = output->tl; to_fill < t; to_fill += obs.time_step)
        if (static_cast<size_t>(output->id) < output->data.size())
            output->data[output->id++] = value;

    output->tl = t;
}

83
84
85
86
87
88
static void
run_simulation(simulation& sim,
               double begin,
               double end,
               double& current,
               simulation_status& st,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
89
               const bool& stop) noexcept
90
{
91
    current = begin;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
92
93
    if (auto ret = sim.initialize(current); irt::is_bad(ret)) {
        log_w.log(
Gauthier Quesnel's avatar
Gauthier Quesnel committed
94
          3, "Simulation initialization failure (%d)\n", static_cast<int>(ret));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
95
96
97
        st = simulation_status::internal_error;
        return;
    }
98
99

    do {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
100
        if (auto ret = sim.run(current); irt::is_bad(ret)) {
101
102
            log_w.log(
              3, "Simulation run failure (%d)\n", static_cast<int>(ret));
103
104
105
            st = simulation_status::internal_error;
            return;
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
106
    } while (current < end && !stop);
107

108
109
    sim.clean();

110
111
    st = simulation_status::success;
}
112
113
114

struct editor
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
115
    small_string<16> name;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
116
    std::filesystem::path path;
117
    imnodes::EditorContext* context = nullptr;
118
    bool initialized = false;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
119
    bool show = true;
120

Gauthier Quesnel's avatar
Gauthier Quesnel committed
121
122
123
124
125
126
127
128
129
    simulation sim;
    double simulation_begin = 0.0;
    double simulation_end = 10.0;
    double simulation_current = 10.0;
    std::future<std::tuple<std::string, status>> future_content;
    std::thread simulation_thread;
    simulation_status st = simulation_status::uninitialized;
    bool stop = false;

130
131
    vector<observation_output> observation_outputs;

132
133
    void clear()
    {
134
        observation_outputs.clear();
135
136
137
138

        sim.clear();
    }

139
140
141
142
143
144
145
146
147
148
    int get_model(model& mdl) const noexcept
    {
        return static_cast<int>(get_index(sim.models.get_id(mdl)));
    }

    int get_model(model_id id) const noexcept
    {
        return static_cast<int>(get_index(id));
    }

149
    model_id get_model(int index) const noexcept
150
    {
151
        auto* mdl = sim.models.try_to_get(static_cast<u32>(index));
152

153
        return sim.models.get_id(mdl);
154
155
    }

156
    int get_in(input_port_id id) const noexcept
157
    {
158
        return static_cast<int>(get_index(id));
159
160
    }

161
    input_port_id get_in(int index) const noexcept
162
    {
163
        auto* port = sim.input_ports.try_to_get(static_cast<u32>(index));
164

165
        return sim.input_ports.get_id(port);
166
167
    }

168
    int get_out(output_port_id id) const noexcept
169
    {
170
171
172
173
174
        constexpr u32 is_output = 1 << 31;
        u32 index = get_index(id);
        index |= is_output;

        return static_cast<int>(index);
175
176
    }

177
    output_port_id get_out(int index) const noexcept
178
    {
179
180
        constexpr u32 mask = ~(1 << 31); /* remove the first bit */
        index &= mask;
181

182
183
184
        auto* port = sim.output_ports.try_to_get(static_cast<u32>(index));

        return sim.output_ports.get_id(port);
185
186
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
187
    status initialize(u32 id) noexcept
188
    {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
189
190
191
        if (is_bad(sim.init(1024u, 32768u)) ||
            is_bad(observation_outputs.init(sim.models.capacity())))
            return status::gui_not_enough_memory;
192

Gauthier Quesnel's avatar
Gauthier Quesnel committed
193
194
195
196
        auto sz =
          fmt::format_to_n(name.begin(), name.capacity(), "Editor {}", id);
        name.size(sz.size);

197
198
        initialized = true;

Gauthier Quesnel's avatar
Gauthier Quesnel committed
199
        return status::success;
200
201
    }

202
    status initialize_lotka_volterra() noexcept
203
204
205
206
    {
        if (!sim.adder_2_models.can_alloc(2) ||
            !sim.mult_2_models.can_alloc(2) ||
            !sim.integrator_models.can_alloc(2) ||
207
            !sim.quantifier_models.can_alloc(2) || !sim.models.can_alloc(10))
208
209
210
211
212
213
214
215
216
217
            return status::simulation_not_enough_model;

        auto& sum_a = sim.adder_2_models.alloc();
        auto& sum_b = sim.adder_2_models.alloc();
        auto& product = sim.mult_2_models.alloc();
        auto& integrator_a = sim.integrator_models.alloc();
        auto& integrator_b = sim.integrator_models.alloc();
        auto& quantifier_a = sim.quantifier_models.alloc();
        auto& quantifier_b = sim.quantifier_models.alloc();

Gauthier Quesnel's avatar
Gauthier Quesnel committed
218
        integrator_a.default_current_value = 18.0;
219

220
221
        quantifier_a.default_adapt_state =
          irt::quantifier::adapt_state::possible;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
222
223
224
        quantifier_a.default_zero_init_offset = true;
        quantifier_a.default_step_size = 0.01;
        quantifier_a.default_past_length = 3;
225

Gauthier Quesnel's avatar
Gauthier Quesnel committed
226
        integrator_b.default_current_value = 7.0;
227

228
229
        quantifier_b.default_adapt_state =
          irt::quantifier::adapt_state::possible;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
230
231
232
        quantifier_b.default_zero_init_offset = true;
        quantifier_b.default_step_size = 0.01;
        quantifier_b.default_past_length = 3;
233

Gauthier Quesnel's avatar
Gauthier Quesnel committed
234
235
236
237
238
239
        product.default_input_coeffs[0] = 1.0;
        product.default_input_coeffs[1] = 1.0;
        sum_a.default_input_coeffs[0] = 2.0;
        sum_a.default_input_coeffs[1] = -0.4;
        sum_b.default_input_coeffs[0] = -1.0;
        sum_b.default_input_coeffs[1] = 0.1;
240

241
        irt_return_if_bad(
242
          sim.alloc(sum_a, sim.adder_2_models.get_id(sum_a), "sum_a"));
243
        irt_return_if_bad(
244
          sim.alloc(sum_b, sim.adder_2_models.get_id(sum_b), "sum_b"));
245
        irt_return_if_bad(
246
247
          sim.alloc(product, sim.mult_2_models.get_id(product), "prod"));
        irt_return_if_bad(sim.alloc(
248
          integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"));
249
        irt_return_if_bad(sim.alloc(
250
          integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"));
251
        irt_return_if_bad(sim.alloc(
252
          quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"));
253
        irt_return_if_bad(sim.alloc(
254
          quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"));
255

256
257
        irt_return_if_bad(sim.connect(sum_a.y[0], integrator_a.x[1]));
        irt_return_if_bad(sim.connect(sum_b.y[0], integrator_b.x[1]));
258

259
260
        irt_return_if_bad(sim.connect(integrator_a.y[0], sum_a.x[0]));
        irt_return_if_bad(sim.connect(integrator_b.y[0], sum_b.x[0]));
261

262
263
        irt_return_if_bad(sim.connect(integrator_a.y[0], product.x[0]));
        irt_return_if_bad(sim.connect(integrator_b.y[0], product.x[1]));
264

265
266
        irt_return_if_bad(sim.connect(product.y[0], sum_a.x[1]));
        irt_return_if_bad(sim.connect(product.y[0], sum_b.x[1]));
267

268
269
270
271
        irt_return_if_bad(sim.connect(quantifier_a.y[0], integrator_a.x[0]));
        irt_return_if_bad(sim.connect(quantifier_b.y[0], integrator_b.x[0]));
        irt_return_if_bad(sim.connect(integrator_a.y[0], quantifier_a.x[0]));
        irt_return_if_bad(sim.connect(integrator_b.y[0], quantifier_b.x[0]));
272

273
274
        return status::success;
    }
275
276
277

    status initialize_izhikevitch()
    {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
278
279
280
281
282
283
284
285
286
        if (!sim.constant_models.can_alloc(3) ||
            !sim.adder_2_models.can_alloc(3) ||
            !sim.adder_4_models.can_alloc(1) ||
            !sim.mult_2_models.can_alloc(1) ||
            !sim.integrator_models.can_alloc(2) ||
            !sim.quantifier_models.can_alloc(2) ||
            !sim.cross_models.can_alloc(2) || !sim.models.can_alloc(14))
            return status::simulation_not_enough_model;

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        auto& constant = sim.constant_models.alloc();
        auto& constant2 = sim.constant_models.alloc();
        auto& constant3 = sim.constant_models.alloc();
        auto& sum_a = sim.adder_2_models.alloc();
        auto& sum_b = sim.adder_2_models.alloc();
        auto& sum_c = sim.adder_4_models.alloc();
        auto& sum_d = sim.adder_2_models.alloc();
        auto& product = sim.mult_2_models.alloc();
        auto& integrator_a = sim.integrator_models.alloc();
        auto& integrator_b = sim.integrator_models.alloc();
        auto& quantifier_a = sim.quantifier_models.alloc();
        auto& quantifier_b = sim.quantifier_models.alloc();
        auto& cross = sim.cross_models.alloc();
        auto& cross2 = sim.cross_models.alloc();

        double a = 0.2;
        double b = 2.0;
        double c = -56.0;
        double d = -16.0;
        double I = -99.0;
        double vt = 30.0;

        constant.default_value = 1.0;
        constant2.default_value = c;
        constant3.default_value = I;

        cross.default_threshold = vt;
        cross2.default_threshold = vt;

        integrator_a.default_current_value = 0.0;

        quantifier_a.default_adapt_state =
          irt::quantifier::adapt_state::possible;
        quantifier_a.default_zero_init_offset = true;
        quantifier_a.default_step_size = 0.01;
        quantifier_a.default_past_length = 3;

        integrator_b.default_current_value = 0.0;

        quantifier_b.default_adapt_state =
          irt::quantifier::adapt_state::possible;
        quantifier_b.default_zero_init_offset = true;
        quantifier_b.default_step_size = 0.01;
        quantifier_b.default_past_length = 3;

        product.default_input_coeffs[0] = 1.0;
        product.default_input_coeffs[1] = 1.0;

        sum_a.default_input_coeffs[0] = 1.0;
        sum_a.default_input_coeffs[1] = -1.0;
        sum_b.default_input_coeffs[0] = -a;
        sum_b.default_input_coeffs[1] = a * b;
        sum_c.default_input_coeffs[0] = 0.04;
        sum_c.default_input_coeffs[1] = 5.0;
        sum_c.default_input_coeffs[2] = 140.0;
        sum_c.default_input_coeffs[3] = 1.0;
        sum_d.default_input_coeffs[0] = 1.0;
        sum_d.default_input_coeffs[1] = d;

346
        irt_return_if_bad(
347
          sim.alloc(constant3, sim.constant_models.get_id(constant3), "tfun"));
348
        irt_return_if_bad(
349
          sim.alloc(constant, sim.constant_models.get_id(constant), "1.0"));
350
        irt_return_if_bad(
351
          sim.alloc(constant2, sim.constant_models.get_id(constant2), "-56.0"));
352

353
        irt_return_if_bad(
354
          sim.alloc(sum_a, sim.adder_2_models.get_id(sum_a), "sum_a"));
355
        irt_return_if_bad(
356
          sim.alloc(sum_b, sim.adder_2_models.get_id(sum_b), "sum_b"));
357
        irt_return_if_bad(
358
          sim.alloc(sum_c, sim.adder_4_models.get_id(sum_c), "sum_c"));
359
        irt_return_if_bad(
360
          sim.alloc(sum_d, sim.adder_2_models.get_id(sum_d), "sum_d"));
361

362
        irt_return_if_bad(
363
364
          sim.alloc(product, sim.mult_2_models.get_id(product), "prod"));
        irt_return_if_bad(sim.alloc(
365
          integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"));
366
        irt_return_if_bad(sim.alloc(
367
          integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"));
368
        irt_return_if_bad(sim.alloc(
369
          quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"));
370
        irt_return_if_bad(sim.alloc(
371
372
          quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"));
        irt_return_if_bad(
373
          sim.alloc(cross, sim.cross_models.get_id(cross), "cross"));
374
        irt_return_if_bad(
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
          sim.alloc(cross2, sim.cross_models.get_id(cross2), "cross2"));

        irt_return_if_bad(sim.connect(integrator_a.y[0], cross.x[0]));
        irt_return_if_bad(sim.connect(constant2.y[0], cross.x[1]));
        irt_return_if_bad(sim.connect(integrator_a.y[0], cross.x[2]));

        irt_return_if_bad(sim.connect(cross.y[0], quantifier_a.x[0]));
        irt_return_if_bad(sim.connect(cross.y[0], product.x[0]));
        irt_return_if_bad(sim.connect(cross.y[0], product.x[1]));
        irt_return_if_bad(sim.connect(product.y[0], sum_c.x[0]));
        irt_return_if_bad(sim.connect(cross.y[0], sum_c.x[1]));
        irt_return_if_bad(sim.connect(cross.y[0], sum_b.x[1]));

        irt_return_if_bad(sim.connect(constant.y[0], sum_c.x[2]));
        irt_return_if_bad(sim.connect(constant3.y[0], sum_c.x[3]));

        irt_return_if_bad(sim.connect(sum_c.y[0], sum_a.x[0]));
        irt_return_if_bad(sim.connect(integrator_b.y[0], sum_a.x[1]));
        irt_return_if_bad(sim.connect(cross2.y[0], sum_a.x[1]));
        irt_return_if_bad(sim.connect(sum_a.y[0], integrator_a.x[1]));
        irt_return_if_bad(sim.connect(cross.y[0], integrator_a.x[2]));
        irt_return_if_bad(sim.connect(quantifier_a.y[0], integrator_a.x[0]));

        irt_return_if_bad(sim.connect(cross2.y[0], quantifier_b.x[0]));
        irt_return_if_bad(sim.connect(cross2.y[0], sum_b.x[0]));
        irt_return_if_bad(sim.connect(quantifier_b.y[0], integrator_b.x[0]));
        irt_return_if_bad(sim.connect(sum_b.y[0], integrator_b.x[1]));

        irt_return_if_bad(sim.connect(cross2.y[0], integrator_b.x[2]));
        irt_return_if_bad(sim.connect(integrator_a.y[0], cross2.x[0]));
        irt_return_if_bad(sim.connect(integrator_b.y[0], cross2.x[2]));
        irt_return_if_bad(sim.connect(sum_d.y[0], cross2.x[1]));
        irt_return_if_bad(sim.connect(integrator_b.y[0], sum_d.x[0]));
        irt_return_if_bad(sim.connect(constant.y[0], sum_d.x[1]));
409
410
411

        return status::success;
    }
412

Gauthier Quesnel's avatar
Gauthier Quesnel committed
413
414
415
416
417
418
419
420
421
422
423
    void show_connections() noexcept
    {
        int id = 0;
        output_port* o_port = nullptr;
        while (sim.output_ports.next(o_port)) {
            for (const auto dst : o_port->connections) {
                if (auto* i_port = sim.input_ports.try_to_get(dst); i_port) {
                    imnodes::Link(id++,
                                  get_out(sim.output_ports.get_id(o_port)),
                                  get_in(dst));
                }
424
425
426
            }
        }
    }
427

Gauthier Quesnel's avatar
Gauthier Quesnel committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
    void show_model_dynamics(model& mdl)
    {
        auto* obs = sim.observers.try_to_get(mdl.obs_id);
        bool open = obs != nullptr;

        ImGui::PushItemWidth(100.0f);
        if (ImGui::Checkbox("observation", &open)) {
            if (open) {
                if (auto* old = sim.observers.try_to_get(mdl.obs_id); old)
                    sim.observers.free(*old);

                auto& o = sim.observers.alloc(0.01, mdl.name.c_str(), nullptr);
                mdl.obs_id = sim.observers.get_id(o);
            } else {
                if (auto* old = sim.observers.try_to_get(mdl.obs_id); old)
                    sim.observers.free(*old);

                mdl.obs_id = static_cast<observer_id>(0);
            }
447
        }
448

Gauthier Quesnel's avatar
Gauthier Quesnel committed
449
450
451
452
453
        if (auto* o = sim.observers.try_to_get(mdl.obs_id); o) {
            float v = static_cast<float>(o->time_step);
            if (ImGui::InputFloat("freq.", &v, 0.001f, 0.1f, "%.3f", 0))
                o->time_step = static_cast<double>(v);
        }
454
455
        ImGui::PopItemWidth();

Gauthier Quesnel's avatar
Gauthier Quesnel committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
        switch (mdl.type) {
        case dynamics_type::none: /* none does not have input port. */
            break;
        case dynamics_type::integrator: {
            auto& dyn = sim.integrator_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("quanta");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x_dot");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[2]));
            ImGui::TextUnformatted("reset");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("value", &dyn.default_current_value);
            ImGui::InputDouble("reset", &dyn.default_reset_value);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("x").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("quanta").x - text_width);
            ImGui::TextUnformatted("x");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::quantifier: {
            auto& dyn = sim.quantifier_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x_dot");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("quantum", &dyn.default_step_size);
            ImGui::SliderInt(
              "archive length", &dyn.default_past_length, 3, 100);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            ImGui::TextUnformatted("quanta");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::adder_2: {
            auto& dyn = sim.adder_2_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x0");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x1");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("coeff-0", &dyn.default_input_coeffs[0]);
            ImGui::InputDouble("coeff-1", &dyn.default_input_coeffs[1]);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("sum").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("coeff-0").x -
                          text_width);
            ImGui::TextUnformatted("sum");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::adder_3: {
            auto& dyn = sim.adder_3_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x0");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x1");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[2]));
            ImGui::TextUnformatted("x2");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("coeff-0", &dyn.default_input_coeffs[0]);
            ImGui::InputDouble("coeff-1", &dyn.default_input_coeffs[1]);
            ImGui::InputDouble("coeff-2", &dyn.default_input_coeffs[2]);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("sum").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("coeff-0").x -
                          text_width);
            ImGui::TextUnformatted("sum");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::adder_4: {
            auto& dyn = sim.adder_4_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x0");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x1");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[2]));
            ImGui::TextUnformatted("x2");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[3]));
            ImGui::TextUnformatted("x3");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("coeff-0", &dyn.default_input_coeffs[0]);
            ImGui::InputDouble("coeff-1", &dyn.default_input_coeffs[1]);
            ImGui::InputDouble("coeff-2", &dyn.default_input_coeffs[2]);
            ImGui::InputDouble("coeff-2", &dyn.default_input_coeffs[3]);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("sum").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("coeff-0").x -
                          text_width);
            ImGui::TextUnformatted("sum");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::mult_2: {
            auto& dyn = sim.mult_2_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x0");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x1");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("coeff-0", &dyn.default_input_coeffs[0]);
            ImGui::InputDouble("coeff-1", &dyn.default_input_coeffs[1]);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("prod").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("coeff-0").x -
                          text_width);
            ImGui::TextUnformatted("prod");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::mult_3: {
            auto& dyn = sim.mult_3_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x0");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x1");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[2]));
            ImGui::TextUnformatted("x2");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("coeff-0", &dyn.default_input_coeffs[0]);
            ImGui::InputDouble("coeff-1", &dyn.default_input_coeffs[1]);
            ImGui::InputDouble("coeff-2", &dyn.default_input_coeffs[2]);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("prod").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("coeff-0").x -
                          text_width);
            ImGui::TextUnformatted("prod");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::mult_4: {
            auto& dyn = sim.mult_4_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("x0");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("x1");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[2]));
            ImGui::TextUnformatted("x2");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[3]));
            ImGui::TextUnformatted("x3");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("coeff-0", &dyn.default_input_coeffs[0]);
            ImGui::InputDouble("coeff-1", &dyn.default_input_coeffs[1]);
            ImGui::InputDouble("coeff-2", &dyn.default_input_coeffs[2]);
            ImGui::InputDouble("coeff-3", &dyn.default_input_coeffs[3]);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("prod").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("coeff-0").x -
                          text_width);
            ImGui::TextUnformatted("prod");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::counter: {
            auto& dyn = sim.counter_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("in");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::generator: {
            auto& dyn = sim.generator_models.get(mdl.id);
            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            ImGui::TextUnformatted("prod");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::constant: {
            auto& dyn = sim.constant_models.get(mdl.id);

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("value", &dyn.default_value);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("out").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("value").x - text_width);
            ImGui::TextUnformatted("out");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::cross: {
            auto& dyn = sim.cross_models.get(mdl.id);
            imnodes::BeginInputAttribute(get_in(dyn.x[0]));
            ImGui::TextUnformatted("value");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[1]));
            ImGui::TextUnformatted("if_value");
            imnodes::EndAttribute();
            imnodes::BeginInputAttribute(get_in(dyn.x[2]));
            ImGui::TextUnformatted("else");
            imnodes::EndAttribute();

            ImGui::PushItemWidth(120.0f);
            ImGui::InputDouble("threshold", &dyn.default_threshold);
            ImGui::PopItemWidth();

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("out").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("value").x - text_width);
            ImGui::TextUnformatted("out");
            imnodes::EndAttribute();
        } break;
        case dynamics_type::time_func: {
            auto& dyn = sim.time_func_models.get(mdl.id);
697
698
699
700
701
702
703
704
705
            const char* items[] = { "time", "square" };
            ImGui::PushItemWidth(120.0f);
            int item_current = dyn.default_f == &time_function ? 0 : 1;
            if (ImGui::Combo(
                  "function", &item_current, items, IM_ARRAYSIZE(items))) {
                dyn.default_f =
                  item_current == 0 ? &time_function : square_time_function;
            }
            ImGui::PopItemWidth();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
706
707
708
709
710
711
712
713

            imnodes::BeginOutputAttribute(get_out(dyn.y[0]));
            const float text_width = ImGui::CalcTextSize("out").x;
            ImGui::Indent(120.f + ImGui::CalcTextSize("value").x - text_width);
            ImGui::TextUnformatted("out");
            imnodes::EndAttribute();
        } break;
        }
714
715
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
716
717
718
    bool show_editor()
    {
        imnodes::EditorContextSet(context);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
719
720
        static bool show_load_file_dialog = false;
        static bool show_save_file_dialog = false;
721

Gauthier Quesnel's avatar
Gauthier Quesnel committed
722
723
        ImGuiWindowFlags windows_flags = 0;
        windows_flags |= ImGuiWindowFlags_MenuBar;
724

Gauthier Quesnel's avatar
Gauthier Quesnel committed
725
726
727
728
        if (!ImGui::Begin(name.c_str(), &show, windows_flags)) {
            ImGui::End();
            return true;
        }
729

Gauthier Quesnel's avatar
Gauthier Quesnel committed
730
731
        if (ImGui::BeginMenuBar()) {
            if (ImGui::BeginMenu("File")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
732
733
734
735
736
                if (ImGui::MenuItem("Open"))
                    show_load_file_dialog = true;

                if (!path.empty() && ImGui::MenuItem("Save")) {
                    log_w.log(3, "Write into file %s\n", path.string().c_str());
737
738
739
740
741
742
743
744
                    if (auto os = std::ofstream(path); os.is_open()) {
                        writer w(os);
                        auto ret = w(sim);
                        if (is_success(ret))
                            log_w.log(5, "success\n");
                        else
                            log_w.log(4, "error writing\n");
                    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
745
746
747
748
                }

                if (ImGui::MenuItem("Save as..."))
                    show_save_file_dialog = true;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
749
750
751
752
753
754
755

                if (ImGui::MenuItem("Close")) {
                    ImGui::EndMenu();
                    ImGui::EndMenuBar();
                    ImGui::End();
                    return false;
                }
756

Gauthier Quesnel's avatar
Gauthier Quesnel committed
757
758
759
760
761
                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("Edition")) {
                if (ImGui::MenuItem("Clear"))
                    clear();
762

Gauthier Quesnel's avatar
Gauthier Quesnel committed
763
                ImGui::EndMenu();
764
765
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
766
767
768
            if (ImGui::BeginMenu("Examples")) {
                if (ImGui::MenuItem("Insert Lotka Volterra model")) {
                    if (is_bad(initialize_lotka_volterra()))
Gauthier Quesnel's avatar
Gauthier Quesnel committed
769
                        log_w.log(3, "Fail to initialize a Lotka Volterra\n");
Gauthier Quesnel's avatar
Gauthier Quesnel committed
770
771
772
773
                }

                if (ImGui::MenuItem("Insert Izhikevitch model")) {
                    if (is_bad(initialize_izhikevitch()))
774
775
                        log_w.log(3,
                                  "Fail to initialize an Izhikevitch model\n");
Gauthier Quesnel's avatar
Gauthier Quesnel committed
776
777
778
                }

                ImGui::EndMenu();
779
            }
780

Gauthier Quesnel's avatar
Gauthier Quesnel committed
781
            ImGui::EndMenuBar();
782
        }
783

Gauthier Quesnel's avatar
Gauthier Quesnel committed
784
785
786
        if (show_load_file_dialog) {
            static std::string out;

787
788
            auto size = ImGui::GetContentRegionMax();
            ImGui::SetNextWindowSize(ImVec2(size.x * 0.7f, size.y * 0.7f));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
789
790
            ImGui::OpenPopup("Select file path to load");

Gauthier Quesnel's avatar
Gauthier Quesnel committed
791
            if (load_file_dialog(path)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
792
793
                show_load_file_dialog = false;
                log_w.log(5, "Load file from %s\n", path.string().c_str());
794
795
796
797
798
799
800
801
                if (auto is = std::ifstream(path); is.is_open()) {
                    reader r(is);
                    auto ret = r(sim);
                    if (is_success(ret))
                        log_w.log(5, "success\n");
                    else
                        log_w.log(4, "error writing\n");
                }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
802
803
804
805
806
807
808
809
            }
        }

        if (show_save_file_dialog) {
            static std::string out;

            ImGui::OpenPopup("Select file path to save");

810
811
            auto size = ImGui::GetContentRegionMax();
            ImGui::SetNextWindowSize(ImVec2(size.x * 0.7f, size.y * 0.7f));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
812
            if (save_file_dialog(path)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
813
814
815
816
                show_save_file_dialog = false;
                log_w.log(5, "Save file to %s\n", path.string().c_str());

                log_w.log(3, "Write into file %s\n", path.string().c_str());
817
818
819
820
821
822
823
824
                if (auto os = std::ofstream(path); os.is_open()) {
                    writer w(os);
                    auto ret = w(sim);
                    if (is_success(ret))
                        log_w.log(5, "success\n");
                    else
                        log_w.log(4, "error writing\n");
                }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
825
826
827
            }
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
828
829
        ImGui::Text("X -- delete selected nodes and/or connections /"
                    " D -- duplicate selected nodes");
830

Gauthier Quesnel's avatar
Gauthier Quesnel committed
831
        imnodes::BeginNodeEditor();
832

Gauthier Quesnel's avatar
Gauthier Quesnel committed
833
834
835
836
        {
            model* mdl = nullptr;
            while (sim.models.next(mdl)) {
                imnodes::BeginNode(get_model(*mdl));
837

Gauthier Quesnel's avatar
Gauthier Quesnel committed
838
839
840
                imnodes::BeginNodeTitleBar();
                ImGui::TextUnformatted(mdl->name.c_str());
                imnodes::EndNodeTitleBar();
841

Gauthier Quesnel's avatar
Gauthier Quesnel committed
842
                show_model_dynamics(*mdl);
843

Gauthier Quesnel's avatar
Gauthier Quesnel committed
844
845
                imnodes::EndNode();
            }
846
        }
847

Gauthier Quesnel's avatar
Gauthier Quesnel committed
848
849
        show_connections();
        imnodes::EndNodeEditor();
850

Gauthier Quesnel's avatar
Gauthier Quesnel committed
851
        ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.f, 8.f));
852

Gauthier Quesnel's avatar
Gauthier Quesnel committed
853
854
        if (!ImGui::IsAnyItemHovered() && ImGui::IsMouseClicked(1))
            ImGui::OpenPopup("Context menu");
855

Gauthier Quesnel's avatar
Gauthier Quesnel committed
856
857
        if (ImGui::BeginPopup("Context menu")) {
            // ImVec2 click_pos = ImGui::GetMousePosOnOpeningCurrentPopup();
858

Gauthier Quesnel's avatar
Gauthier Quesnel committed
859
860
861
862
863
            if (ImGui::MenuItem("none")) {
                if (sim.none_models.can_alloc(1u) && sim.models.can_alloc(1u)) {
                    auto& mdl = sim.none_models.alloc();
                    sim.alloc(mdl, sim.none_models.get_id(mdl), "none");
                }
864
865
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
866
867
868
869
870
871
872
            if (ImGui::MenuItem("integrator")) {
                if (sim.integrator_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.integrator_models.alloc();
                    sim.alloc(
                      mdl, sim.integrator_models.get_id(mdl), "integrator");
                }
873
874
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
            if (ImGui::MenuItem("quantifier")) {
                if (sim.quantifier_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.quantifier_models.alloc();
                    sim.alloc(
                      mdl, sim.quantifier_models.get_id(mdl), "quantifier");
                }
            }

            if (ImGui::MenuItem("adder_2")) {
                if (sim.adder_2_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.adder_2_models.alloc();
                    sim.alloc(mdl, sim.adder_2_models.get_id(mdl), "adder");
                }
890
891
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
892
893
894
895
896
897
            if (ImGui::MenuItem("adder_3")) {
                if (sim.adder_3_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.adder_3_models.alloc();
                    sim.alloc(mdl, sim.adder_3_models.get_id(mdl), "adder");
                }
898
899
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
900
901
902
903
904
905
            if (ImGui::MenuItem("adder_4")) {
                if (sim.adder_4_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.adder_4_models.alloc();
                    sim.alloc(mdl, sim.adder_4_models.get_id(mdl), "adder");
                }
906
907
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
908
909
910
911
912
913
            if (ImGui::MenuItem("mult_2")) {
                if (sim.mult_2_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.mult_2_models.alloc();
                    sim.alloc(mdl, sim.mult_2_models.get_id(mdl), "mult");
                }
914
915
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
916
917
918
919
920
921
            if (ImGui::MenuItem("mult_3")) {
                if (sim.mult_3_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.mult_3_models.alloc();
                    sim.alloc(mdl, sim.mult_3_models.get_id(mdl), "mult");
                }
922
923
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
924
925
926
927
928
929
            if (ImGui::MenuItem("mult_4")) {
                if (sim.mult_4_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.mult_4_models.alloc();
                    sim.alloc(mdl, sim.mult_4_models.get_id(mdl), "mult");
                }
930
931
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
932
933
934
935
936
937
            if (ImGui::MenuItem("counter")) {
                if (sim.counter_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.counter_models.alloc();
                    sim.alloc(mdl, sim.counter_models.get_id(mdl), "counter");
                }
938
939
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
940
941
942
943
944
945
946
            if (ImGui::MenuItem("generator")) {
                if (sim.generator_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.generator_models.alloc();
                    sim.alloc(
                      mdl, sim.generator_models.get_id(mdl), "generator");
                }
947
948
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
949
950
951
952
953
954
            if (ImGui::MenuItem("constant")) {
                if (sim.constant_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.constant_models.alloc();
                    sim.alloc(mdl, sim.constant_models.get_id(mdl), "constant");
                }
955
956
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
957
958
959
960
961
962
            if (ImGui::MenuItem("cross")) {
                if (sim.cross_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.cross_models.alloc();
                    sim.alloc(mdl, sim.cross_models.get_id(mdl), "cross");
                }
963
964
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
965
966
967
968
969
970
971
            if (ImGui::MenuItem("time_func")) {
                if (sim.time_func_models.can_alloc(1u) &&
                    sim.models.can_alloc(1u)) {
                    auto& mdl = sim.time_func_models.alloc();
                    sim.alloc(
                      mdl, sim.time_func_models.get_id(mdl), "time-func");
                }
972
            }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
973
974
975

            ImGui::EndPopup();
            // imnodes::SetNodeScreenSpacePos(new_node, click_pos);
976
977
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
978
979
980
981
982
983
984
985
986
987
988
989
990
        ImGui::PopStyleVar();

        {
            int start = 0, end = 0;
            if (imnodes::IsLinkCreated(&start, &end)) {
                output_port_id out = get_out(start);
                input_port_id in = get_in(end);

                auto* o_port = sim.output_ports.try_to_get(out);
                auto* i_port = sim.input_ports.try_to_get(in);

                if (i_port && o_port)
                    sim.connect(out, in);
991
992
993
            }
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
994
995
        {
            static array<int> selected_links;
996

Gauthier Quesnel's avatar
Gauthier Quesnel committed
997
998
999
            const int num_selected = imnodes::NumSelectedLinks();
            if (num_selected > 0 && ImGui::IsKeyReleased('X')) {
                selected_links.init(static_cast<size_t>(num_selected));
1000

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1001
1002
1003
1004
1005
                std::fill_n(selected_links.data(), selected_links.size(), -1);
                imnodes::GetSelectedLinks(selected_links.data());
                std::sort(selected_links.begin(),
                          selected_links.end(),
                          std::less<int>());
1006

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1007
1008
                for (size_t i = 0; i != selected_links.size(); ++i)
                    assert(selected_links[i] != -1);
1009

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1010
1011
1012
                size_t i = 0;
                int link_id_to_delete = selected_links[0];
                int current_link_id = 0;
1013

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1014
                log_w.log(7, "%d connections to delete\n", num_selected);
1015

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
                output_port* o_port = nullptr;
                while (sim.output_ports.next(o_port) &&
                       link_id_to_delete != -1) {
                    for (const auto dst : o_port->connections) {
                        if (auto* i_port = sim.input_ports.try_to_get(dst);
                            i_port) {
                            if (current_link_id == link_id_to_delete) {
                                sim.disconnect(sim.output_ports.get_id(o_port),
                                               dst);

                                ++i;

                                if (i != selected_links.size())
                                    link_id_to_delete = selected_links[i];
                                else
                                    link_id_to_delete = -1;
                            }

                            ++current_link_id;
                        }
1036
1037
                    }
                }
1038

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1039
1040
                selected_links.clear();
            }
1041
1042
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1043
1044
        {
            static array<int> selected_nodes;
1045

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1046
1047
1048
1049
1050
            const int num_selected = imnodes::NumSelectedNodes();
            if (num_selected > 0) {
                if (ImGui::IsKeyReleased('X')) {
                    selected_nodes.init(num_selected);
                    imnodes::GetSelectedNodes(selected_nodes.data());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1051

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1052
                    log_w.log(7, "%d connections to delete\n", num_selected);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1053

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1054
1055
1056
1057
1058
1059
                    for (const int node_id : selected_nodes) {
                        auto id = get_model(node_id);
                        if (auto* mdl = sim.models.try_to_get(id); mdl) {
                            log_w.log(7, "delete %s\n", mdl->name.c_str());
                            sim.deallocate(sim.models.get_id(mdl));
                        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1060
                    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1061
1062
1063
                } else if (ImGui::IsKeyReleased('D')) {
                    selected_nodes.init(num_selected);
                    imnodes::GetSelectedNodes(selected_nodes.data());
1064

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1065
1066
1067
1068
                    array<model_id> sources;
                    array<model_id> destinations;
                    if (is_success(sources.init(num_selected)) &&
                        is_success(destinations.init(num_selected))) {
1069

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1070
1071
1072
                        for (size_t i = 0; i != selected_nodes.size(); ++i)
                            sources[i] = get_model(selected_nodes[i]);
                    }
1073

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1074
1075
1076
1077
                    sim.copy(std::begin(sources),
                             std::end(sources),
                             std::begin(destinations));
                }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1078
            }
1079
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102

        /*
        if (ImGui::IsKeyReleased(SDL_SCANCODE_A) &&
            ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)) {
            const int node_id = ++editor.current_id;
            imnodes::SetNodeScreenSpacePos(node_id, ImGui::GetMousePos());
            editor.nodes.push_back(Node{ node_id, 0.f });
        }
        */

        ImGui::End();

        return true;
    }
};

enum class editor_id : std::uint64_t;
static data_array<editor, editor_id> editors;

editor*
editors_new()
{
    if (!editors.can_alloc(1u)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1103
        log_w.log(2, "Too many open editor\n");
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1104
        return nullptr;
1105
1106
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1107
1108
1109
1110
1111
1112
    auto& ed = editors.alloc();
    if (auto ret = ed.initialize(get_index(editors.get_id(ed))); is_bad(ret)) {
        log_w.log(
          2, "Fail to initialize irritator: %d\n", static_cast<int>(ret));
        editors.free(ed);
        return nullptr;
1113
1114
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1115
    log_w.log(5, "Open editor %s\n", ed.name.c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1116
1117
    return &ed;
}
1118

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1119
1120
1121
void
editors_free(editor& ed)
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1122
    log_w.log(5, "Close editor %s\n", ed.name.c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1123
1124
1125
1126
1127
1128
1129
1130
1131
    editors.free(ed);
}

void
show_simulation_box(bool* show_simulation)
{
    static editor_id current_editor_id = static_cast<editor_id>(0);

    if (!ImGui::Begin("Simulation", show_simulation)) {
1132
        ImGui::End();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1133
1134
        return;
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1135

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1136
1137
1138
1139
1140
1141
1142
    const char* combo_name = "";
    if (auto* ed = editors.try_to_get(current_editor_id); !ed) {
        ed = nullptr;
        if (editors.next(ed)) {
            current_editor_id = editors.get_id(ed);
            combo_name = ed->name.c_str();
        }
1143
    } else {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
        combo_name = ed->name.c_str();
    }

    if (ImGui::BeginCombo("Name", combo_name)) {
        editor* ed = nullptr;
        while (editors.next(ed)) {
            bool is_selected = current_editor_id == editors.get_id(ed);
            if (ImGui::Selectable(ed->name.c_str(), is_selected))
                current_editor_id = editors.get_id(ed);

            if (is_selected)
                ImGui::SetItemDefaultFocus();
        }

        ImGui::EndCombo();
    }

    if (auto* ed = editors.try_to_get(current_editor_id); ed) {
        ImGui::InputDouble("Begin", &ed->simulation_begin);
        ImGui::InputDouble("End", &ed->simulation_end);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1164

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1165
1166
1167
1168
        if (ed->st != simulation_status::running) {
            if (ed->simulation_thread.joinable()) {
                ed->simulation_thread.join();
                ed->st = simulation_status::success;
1169
1170
1171
            }

            if (ImGui::Button("Start")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1172
                ed->observation_outputs.clear();
1173
                observer* obs = nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1174
1175
                while (ed->sim.observers.next(obs)) {
                    ed->observation_outputs.emplace_back(obs->name.c_str());
1176

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1177
                    const auto diff = ed->simulation_end - ed->simulation_begin;
1178
1179
1180
                    const auto freq = diff / obs->time_step;
                    const size_t lenght = static_cast<size_t>(freq);

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1181
                    ed->observation_outputs.back().data.init(lenght);
1182
1183
1184
                    obs->initialize = &observation_output_initialize;
                    obs->observe = &observation_output_observe;
                    obs->user_data =
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1185
                      static_cast<void*>(&ed->observation_outputs.back());
1186
                }
1187

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1188
1189
                ed->st = simulation_status::running;
                ed->stop = false;
1190

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1191
                ed->simulation_thread =
1192
                  std::thread(&run_simulation,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1193
1194
1195
1196
1197
1198
                              std::ref(ed->sim),
                              ed->simulation_begin,
                              ed->simulation_end,
                              std::ref(ed->simulation_current),
                              std::ref(ed->st),
                              std::cref(ed->stop));
1199
1200
1201
            }
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1202
1203
1204
        if (ed->st == simulation_status::success ||
            ed->st == simulation_status::running) {
            ImGui::Text("Current: %g", ed->simulation_current);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1205

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1206
1207
            if (ed->st == simulation_status::running && ImGui::Button("Stop"))
                ed->stop = true;
1208

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1209
1210
1211
            const double duration = ed->simulation_end - ed->simulation_begin;
            const double elapsed =
              ed->simulation_current - ed->simulation_begin;
1212
1213
            const double fraction = elapsed / duration;
            ImGui::ProgressBar(static_cast<float>(fraction));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1214

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1215
            for (const auto& obs : ed->observation_outputs)
1216
1217
1218
1219
1220
1221
1222
1223
                ImGui::PlotLines(obs.name,
                                 obs.data.data(),
                                 static_cast<int>(obs.data.size()),