node-editor.cpp 45.5 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
10
#include <future>
#include <mutex>
Gauthier Quesnel's avatar
Gauthier Quesnel committed
11
#include <string>
12
13
#include <thread>

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

namespace irt {

20
21
window_logger log_w;

22
enum class simulation_status
23
{
24
25
26
27
    success,
    running,
    uninitialized,
    internal_error,
28
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
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;
}

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

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

106
107
    sim.clean();

108
109
    st = simulation_status::success;
}
110
111
112

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
119
120
121
122
123
124
125
126
127
    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;

128
129
    vector<observation_output> observation_outputs;

130
131
    void clear()
    {
132
        observation_outputs.clear();
133
134
135
136

        sim.clear();
    }

137
138
139
140
141
142
143
144
145
146
    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));
    }

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

151
        return sim.models.get_id(mdl);
152
153
    }

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

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

163
        return sim.input_ports.get_id(port);
164
165
    }

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

        return static_cast<int>(index);
173
174
    }

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

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

        return sim.output_ports.get_id(port);
183
184
    }

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

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

195
196
        initialized = true;

Gauthier Quesnel's avatar
Gauthier Quesnel committed
197
        return status::success;
198
199
    }

200
    status initialize_lotka_volterra() noexcept
201
202
203
204
    {
        if (!sim.adder_2_models.can_alloc(2) ||
            !sim.mult_2_models.can_alloc(2) ||
            !sim.integrator_models.can_alloc(2) ||
205
            !sim.quantifier_models.can_alloc(2) || !sim.models.can_alloc(10))
206
207
208
209
210
211
212
213
214
215
            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
216
        integrator_a.default_current_value = 18.0;
217

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
224
        integrator_b.default_current_value = 7.0;
225

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
232
233
234
235
236
237
        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;
238

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

254
255
        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]));
256

257
258
        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]));
259

260
261
        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]));
262

263
264
        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]));
265

266
267
268
269
        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]));
270

271
272
        return status::success;
    }
273
274
275

    status initialize_izhikevitch()
    {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
276
277
278
279
280
281
282
283
284
        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;

285
286
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
        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;

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

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

360
        irt_return_if_bad(
361
362
          sim.alloc(product, sim.mult_2_models.get_id(product), "prod"));
        irt_return_if_bad(sim.alloc(
363
          integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"));
364
        irt_return_if_bad(sim.alloc(
365
          integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"));
366
        irt_return_if_bad(sim.alloc(
367
          quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"));
368
        irt_return_if_bad(sim.alloc(
369
370
          quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"));
        irt_return_if_bad(
371
          sim.alloc(cross, sim.cross_models.get_id(cross), "cross"));
372
        irt_return_if_bad(
373
374
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
          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]));
407
408
409

        return status::success;
    }
410

Gauthier Quesnel's avatar
Gauthier Quesnel committed
411
412
413
414
415
416
417
418
419
420
421
    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));
                }
422
423
424
            }
        }
    }
425

Gauthier Quesnel's avatar
Gauthier Quesnel committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
    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);
            }
445
        }
446

Gauthier Quesnel's avatar
Gauthier Quesnel committed
447
448
449
450
451
        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);
        }
452
453
        ImGui::PopItemWidth();

Gauthier Quesnel's avatar
Gauthier Quesnel committed
454
455
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
697
698
699
700
701
702
703
704
705
        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);
            // 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;
        }
706
707
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
708
709
710
    bool show_editor()
    {
        imnodes::EditorContextSet(context);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
711
712
        static bool show_load_file_dialog = false;
        static bool show_save_file_dialog = false;
713

Gauthier Quesnel's avatar
Gauthier Quesnel committed
714
715
        ImGuiWindowFlags windows_flags = 0;
        windows_flags |= ImGuiWindowFlags_MenuBar;
716

Gauthier Quesnel's avatar
Gauthier Quesnel committed
717
718
719
720
        if (!ImGui::Begin(name.c_str(), &show, windows_flags)) {
            ImGui::End();
            return true;
        }
721

Gauthier Quesnel's avatar
Gauthier Quesnel committed
722
723
        if (ImGui::BeginMenuBar()) {
            if (ImGui::BeginMenu("File")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
                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());
                    writer w(std::fopen(path.string().c_str(), "w"));
                    auto ret = w(sim);
                    if (is_success(ret))
                        log_w.log(5, "success\n");
                    else
                        log_w.log(4, "error writing\n");
                }

                if (ImGui::MenuItem("Save as..."))
                    show_save_file_dialog = true;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
739
740
741
742
743
744
745

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
747
748
749
750
751
                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("Edition")) {
                if (ImGui::MenuItem("Clear"))
                    clear();
752

Gauthier Quesnel's avatar
Gauthier Quesnel committed
753
                ImGui::EndMenu();
754
755
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
756
757
758
            if (ImGui::BeginMenu("Examples")) {
                if (ImGui::MenuItem("Insert Lotka Volterra model")) {
                    if (is_bad(initialize_lotka_volterra()))
Gauthier Quesnel's avatar
Gauthier Quesnel committed
759
                        log_w.log(3, "Fail to initialize a Lotka Volterra\n");
Gauthier Quesnel's avatar
Gauthier Quesnel committed
760
761
762
763
                }

                if (ImGui::MenuItem("Insert Izhikevitch model")) {
                    if (is_bad(initialize_izhikevitch()))
Gauthier Quesnel's avatar
Gauthier Quesnel committed
764
                        log_w.log(3, "Fail to initialize an Izhikevitch model\n");
Gauthier Quesnel's avatar
Gauthier Quesnel committed
765
766
767
                }

                ImGui::EndMenu();
768
            }
769

Gauthier Quesnel's avatar
Gauthier Quesnel committed
770
            ImGui::EndMenuBar();
771
        }
772

Gauthier Quesnel's avatar
Gauthier Quesnel committed
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
        if (show_load_file_dialog) {
            static std::string out;
            static const char* filters[] = { "irt", nullptr };

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

            if (load_file_dialog("Select a file path to load", filters, path)) {
                show_load_file_dialog = false;
                log_w.log(5, "Load file from %s\n", path.string().c_str());
                reader r(std::fopen(path.string().c_str(), "r"));
                auto ret = r(sim);
                if (is_success(ret))
                    log_w.log(5, "success\n");
                else
                    log_w.log(4, "error writing\n");
            }
        }

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

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

            if (save_file_dialog("Select a file path to save", nullptr, path)) {
                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());
                writer w(std::fopen(path.string().c_str(), "w"));
                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
810
811
        ImGui::Text("X -- delete selected nodes and/or connections /"
                    " D -- duplicate selected nodes");
812

Gauthier Quesnel's avatar
Gauthier Quesnel committed
813
        imnodes::BeginNodeEditor();
814

Gauthier Quesnel's avatar
Gauthier Quesnel committed
815
816
817
818
        {
            model* mdl = nullptr;
            while (sim.models.next(mdl)) {
                imnodes::BeginNode(get_model(*mdl));
819

Gauthier Quesnel's avatar
Gauthier Quesnel committed
820
821
822
                imnodes::BeginNodeTitleBar();
                ImGui::TextUnformatted(mdl->name.c_str());
                imnodes::EndNodeTitleBar();
823

Gauthier Quesnel's avatar
Gauthier Quesnel committed
824
                show_model_dynamics(*mdl);
825

Gauthier Quesnel's avatar
Gauthier Quesnel committed
826
827
                imnodes::EndNode();
            }
828
        }
829

Gauthier Quesnel's avatar
Gauthier Quesnel committed
830
831
        show_connections();
        imnodes::EndNodeEditor();
832

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
835
836
        if (!ImGui::IsAnyItemHovered() && ImGui::IsMouseClicked(1))
            ImGui::OpenPopup("Context menu");
837

Gauthier Quesnel's avatar
Gauthier Quesnel committed
838
839
        if (ImGui::BeginPopup("Context menu")) {
            // ImVec2 click_pos = ImGui::GetMousePosOnOpeningCurrentPopup();
840

Gauthier Quesnel's avatar
Gauthier Quesnel committed
841
842
843
844
845
            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");
                }
846
847
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
848
849
850
851
852
853
854
            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");
                }
855
856
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
            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");
                }
872
873
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
874
875
876
877
878
879
            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");
                }
880
881
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
882
883
884
885
886
887
            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");
                }
888
889
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
890
891
892
893
894
895
            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");
                }
896
897
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
898
899
900
901
902
903
            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");
                }
904
905
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
906
907
908
909
910
911
            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");
                }
912
913
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
914
915
916
917
918
919
            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");
                }
920
921
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
922
923
924
925
926
927
928
            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");
                }
929
930
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
931
932
933
934
935
936
            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");
                }
937
938
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
939
940
941
942
943
944
            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");
                }
945
946
            }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
947
948
949
950
951
952
953
            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");
                }
954
            }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
955
956
957

            ImGui::EndPopup();
            // imnodes::SetNodeScreenSpacePos(new_node, click_pos);
958
959
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
960
961
962
963
964
965
966
967
968
969
970
971
972
        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);
973
974
975
            }
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
976
977
        {
            static array<int> selected_links;
978

Gauthier Quesnel's avatar
Gauthier Quesnel committed
979
980
981
            const int num_selected = imnodes::NumSelectedLinks();
            if (num_selected > 0 && ImGui::IsKeyReleased('X')) {
                selected_links.init(static_cast<size_t>(num_selected));
982

Gauthier Quesnel's avatar
Gauthier Quesnel committed
983
984
985
986
987
                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>());
988

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
992
993
994
                size_t i = 0;
                int link_id_to_delete = selected_links[0];
                int current_link_id = 0;
995

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
                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;
                        }
1018
1019
                    }
                }
1020

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1021
1022
                selected_links.clear();
            }
1023
1024
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1025
1026
        {
            static array<int> selected_nodes;
1027

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1028
1029
1030
1031
1032
            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
1033

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1036
1037
1038
1039
1040
1041
                    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
1042
                    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1043
1044
1045
                } else if (ImGui::IsKeyReleased('D')) {
                    selected_nodes.init(num_selected);
                    imnodes::GetSelectedNodes(selected_nodes.data());
1046

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1047
1048
1049
1050
                    array<model_id> sources;
                    array<model_id> destinations;
                    if (is_success(sources.init(num_selected)) &&
                        is_success(destinations.init(num_selected))) {
1051

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1052
1053
1054
                        for (size_t i = 0; i != selected_nodes.size(); ++i)
                            sources[i] = get_model(selected_nodes[i]);
                    }
1055

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1056
1057
1058
1059
                    sim.copy(std::begin(sources),
                             std::end(sources),
                             std::begin(destinations));
                }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1060
            }
1061
        }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084

        /*
        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
1085
        log_w.log(2, "Too many open editor\n");
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1086
        return nullptr;
1087
1088
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1089
1090
1091
1092
1093
1094
    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;
1095
1096
    }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1097
    log_w.log(5, "Open editor %s\n", ed.name.c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1098
1099
    return &ed;
}
1100

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1101
1102
1103
void
editors_free(editor& ed)
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1104
    log_w.log(5, "Close editor %s\n", ed.name.c_str());
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
    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)) {
1114
        ImGui::End();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1115
1116
        return;
    }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1117

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1118
1119
1120
1121
1122
1123
1124
    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();
        }
1125
    } else {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
        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
1146

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1147
1148
1149
1150
        if (ed->st != simulation_status::running) {
            if (ed->simulation_thread.joinable()) {
                ed->simulation_thread.join();
                ed->st = simulation_status::success;
1151
1152
1153
            }

            if (ImGui::Button("Start")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1154
                ed->observation_outputs.clear();
1155
                observer* obs = nullptr;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1156
1157
                while (ed->sim.observers.next(obs)) {
                    ed->observation_outputs.emplace_back(obs->name.c_str());
1158

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1159
                    const auto diff = ed->simulation_end - ed->simulation_begin;
1160
1161
1162
                    const auto freq = diff / obs->time_step;
                    const size_t lenght = static_cast<size_t>(freq);

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1163
                    ed->observation_outputs.back().data.init(lenght);
1164
1165
1166
                    obs->initialize = &observation_output_initialize;
                    obs->observe = &observation_output_observe;
                    obs->user_data =
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1167
                      static_cast<void*>(&ed->observation_outputs.back());
1168
                }
1169

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1170
1171
                ed->st = simulation_status::running;
                ed->stop = false;
1172

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1173
                ed->simulation_thread =
1174
                  std::thread(&run_simulation,
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1175
1176
1177
1178
1179
1180
                              std::ref(ed->sim),
                              ed->simulation_begin,
                              ed->simulation_end,
                              std::ref(ed->simulation_current),
                              std::ref(ed->st),
                              std::cref(ed->stop));
1181
1182
1183
            }
        }

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1184
1185
1186
        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
1187

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

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1191
1192
1193
            const double duration = ed->simulation_end - ed->simulation_begin;
            const double elapsed =
              ed->simulation_current - ed->simulation_begin;
1194
1195
            const double fraction = elapsed / duration;
            ImGui::ProgressBar(static_cast<float>(fraction));
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1196

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1197
            for (const auto& obs : ed->observation_outputs)
1198
1199
1200
1201
1202
1203
1204
1205
                ImGui::PlotLines(obs.name,
                                 obs.data.data(),
                                 static_cast<int>(obs.data.size()),
                                 0,
                                 nullptr,
                                 obs.min,
                                 obs.max,
                                 ImVec2(0.f, 50.f));
1206
1207
        }
    }
1208

Gauthier Quesnel's avatar
Gauthier Quesnel committed
1209
1210
    ImGui::End();
}
1211
1212
1213
1214

void
node_editor_initialize()
{
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1215
    if (auto ret = editors.init(50u); is_bad(ret)) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1216
        log_w.log(
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1217
1218
1219
1220
          2, "Fail to initialize irritator: %d\n", static_cast<int>(ret));
    } else {
        if (auto* ed = editors_new(); ed)
            ed->context = imnodes::EditorContextCreate();
1221
    }
1222
1223
1224
1225
1226
}

void
node_editor_show()
{
1227
    static bool show_log = true;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
    static bool show_simulation = true;

    if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("File")) {
            if (ImGui::MenuItem("New")) {
                if