summaryrefslogtreecommitdiff
path: root/tools/seq_compiler.cc
blob: 548f467d1a289a19154fc3b2f129a8c902799d1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// This file is part of the 64k demo project.
// It implements the sequence compiler tool.
// Converts a text-based timeline description into C++ code.

#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

struct EffectEntry {
  std::string class_name;
  std::string start;
  std::string end;
  std::string priority;
  std::string extra_args;
};

struct SequenceEntry {
  std::string start_time;
  std::string priority;
  std::string end_time;  // Optional: -1.0f means "no explicit end"
  std::vector<EffectEntry> effects;
};

std::string trim(const std::string& str) {
  size_t first = str.find_first_not_of(" \t");
  if (std::string::npos == first)
    return "";  // String is all whitespace, return empty string
  size_t last = str.find_last_not_of(" \t");
  return str.substr(first, (last - first + 1));
}

// Generate ASCII Gantt chart for timeline visualization
void generate_gantt_chart(const std::string& output_file,
                          const std::vector<SequenceEntry>& sequences,
                          float bpm, const std::string& demo_end_time) {
  std::ofstream out(output_file);
  if (!out.is_open()) {
    std::cerr << "Warning: Could not open Gantt chart output file: " << output_file << "\n";
    return;
  }

  // Find max time for the chart
  float max_time = demo_end_time.empty() ? 0.0f : std::stof(demo_end_time);
  for (const auto& seq : sequences) {
    float seq_start = std::stof(seq.start_time);
    for (const auto& eff : seq.effects) {
      float eff_end = seq_start + std::stof(eff.end);
      max_time = std::max(max_time, eff_end);
    }
    if (seq.end_time != "-1.0") {
      max_time = std::max(max_time, seq_start + std::stof(seq.end_time));
    }
  }

  // Chart configuration
  const int chart_width = 100;
  const float time_scale = chart_width / max_time;

  out << "Demo Timeline Gantt Chart\n";
  out << "==============================================================================\n";
  out << "BPM: " << bpm << ", Duration: " << max_time << "s";
  if (!demo_end_time.empty()) {
    out << " (explicit end)";
  }
  out << "\n\n";

  // Time axis header
  out << "Time (s): ";
  for (int i = 0; i <= (int)max_time; i += 5) {
    out << i;
    int spacing = (i < 10) ? 4 : (i < 100) ? 3 : 2;
    if (i + 5 <= max_time) {
      for (int j = 0; j < spacing; ++j) out << " ";
    }
  }
  out << "\n";
  out << "          ";
  for (int i = 0; i < chart_width; ++i) {
    if (i % 5 == 0) out << "|";
    else out << "-";
  }
  out << "\n\n";

  // Draw sequences and effects
  for (const auto& seq : sequences) {
    float seq_start = std::stof(seq.start_time);
    float seq_end = max_time;  // Default: runs until end

    // Check if sequence has explicit end time
    if (seq.end_time != "-1.0") {
      seq_end = seq_start + std::stof(seq.end_time);
    } else {
      // Calculate implicit end from latest effect
      for (const auto& eff : seq.effects) {
        seq_end = std::max(seq_end, seq_start + std::stof(eff.end));
      }
    }

    // Draw sequence bar
    out << "SEQ@" << seq_start << "s [pri=" << seq.priority << "]";
    if (seq.end_time != "-1.0") {
      out << " [END=" << seq_end << "s]";
    }
    out << "\n";

    int start_col = (int)(seq_start * time_scale);
    int end_col = (int)(seq_end * time_scale);
    out << "          ";
    for (int i = 0; i < chart_width; ++i) {
      if (i >= start_col && i < end_col) out << "█";
      else out << " ";
    }
    out << "  (" << seq_start << "-" << seq_end << "s)\n";

    // Draw effects within sequence
    for (const auto& eff : seq.effects) {
      float eff_start = seq_start + std::stof(eff.start);
      float eff_end = seq_start + std::stof(eff.end);

      // Truncate if sequence has explicit end time
      if (seq.end_time != "-1.0") {
        eff_end = std::min(eff_end, seq_end);
      }

      out << "  " << eff.class_name << " [pri=" << eff.priority << "]";
      if (eff_end < eff_start) {
        out << " *** INVALID TIME RANGE ***";
      }
      out << "\n";
      out << "          ";

      int eff_start_col = (int)(eff_start * time_scale);
      int eff_end_col = (int)(eff_end * time_scale);

      for (int i = 0; i < chart_width; ++i) {
        if (i >= eff_start_col && i < eff_end_col) {
          out << "▓";
        } else if (i >= start_col && i < end_col) {
          out << "·";  // Show sequence background
        } else {
          out << " ";
        }
      }
      out << "  (" << eff_start << "-" << eff_end << "s)\n";
    }
    out << "\n";
  }

  out << "==============================================================================\n";
  out << "Legend: █ Sequence  ▓ Effect  · Sequence background\n";
  out << "Priority: Higher numbers render later (on top)\n";

  out.close();
  std::cout << "Gantt chart written to: " << output_file << "\n";
}

// Convert beat notation to time in seconds
// Supports: "64b" or "64" (beats), "32.0s" or "32.0" with decimal point (seconds)
std::string convert_to_time(const std::string& value, float bpm) {
  std::string val = value;
  bool is_beat = false;

  // Check for explicit 'b' suffix (beat)
  if (!val.empty() && val.back() == 'b') {
    is_beat = true;
    val.pop_back();
  }
  // Check for explicit 's' suffix (seconds)
  else if (!val.empty() && val.back() == 's') {
    val.pop_back();
    return val;  // Already in seconds
  }
  // If no suffix and no decimal point, assume beats
  else if (val.find('.') == std::string::npos) {
    is_beat = true;
  }

  if (is_beat) {
    float beat = std::stof(val);
    float time = beat * 60.0f / bpm;
    return std::to_string(time);
  }

  return val;  // Return as-is (seconds)
}

int main(int argc, char* argv[]) {
  if (argc < 3 || argc > 4) {
    std::cerr << "Usage: " << argv[0] << " <input.seq> <output.cc> [--gantt <gantt.txt>]\n";
    std::cerr << "Example: " << argv[0]
              << " assets/demo.seq src/generated/timeline.cc\n";
    std::cerr << "         " << argv[0]
              << " assets/demo.seq src/generated/timeline.cc --gantt timeline.txt\n";
    return 1;
  }

  std::string gantt_output = "";
  if (argc == 4 && std::string(argv[3]).rfind("--gantt=", 0) == 0) {
    gantt_output = std::string(argv[3]).substr(8);  // Extract filename after --gantt=
  }

  std::ifstream in_file(argv[1]);
  if (!in_file.is_open()) {
    std::cerr << "Error: Could not open input file " << argv[1] << "\n";
    return 1;
  }

  std::vector<SequenceEntry> sequences;
  SequenceEntry* current_seq = nullptr;
  float bpm = 120.0f;  // Default BPM
  std::string demo_end_time = "";  // Demo end time (optional)

  std::string line;
  int line_num = 0;
  while (std::getline(in_file, line)) {
    ++line_num;
    std::string trimmed = trim(line);
    if (trimmed.empty())
      continue;

    // Parse BPM from comment
    if (trimmed[0] == '#') {
      std::stringstream ss(trimmed);
      std::string hash, keyword;
      ss >> hash >> keyword;
      if (keyword == "BPM") {
        ss >> bpm;
        std::cout << "Using BPM: " << bpm << "\n";
      }
      continue;
    }

    std::stringstream ss(trimmed);
    std::string command;
    ss >> command;

    if (command == "END_DEMO") {
      std::string end_time;
      if (!(ss >> end_time)) {
        std::cerr << "Error line " << line_num
                  << ": END_DEMO requires <time>\n";
        return 1;
      }
      // Convert beat notation to time
      demo_end_time = convert_to_time(end_time, bpm);
      std::cout << "Demo end time: " << demo_end_time << "s\n";
    } else if (command == "SEQUENCE") {
      std::string start, priority;
      if (!(ss >> start >> priority)) {
        std::cerr << "Error line " << line_num
                  << ": SEQUENCE requires <start> <priority>\n";
        return 1;
      }
      // Convert beat notation to time
      std::string start_time = convert_to_time(start, bpm);

      // Check for optional [end_time]
      std::string end_time_str = "-1.0";  // Default: no explicit end
      std::string optional_param;
      if (ss >> optional_param) {
        // Check if it's wrapped in brackets [time]
        if (optional_param.size() >= 3 &&
            optional_param.front() == '[' &&
            optional_param.back() == ']') {
          // Extract time from [time]
          std::string time_value = optional_param.substr(1, optional_param.size() - 2);
          end_time_str = convert_to_time(time_value, bpm);
        } else {
          std::cerr << "Error line " << line_num
                    << ": Optional sequence end time must be in brackets [time]\n";
          return 1;
        }
      }

      sequences.push_back({start_time, priority, end_time_str, {}});
      current_seq = &sequences.back();
    } else if (command == "EFFECT") {
      if (!current_seq) {
        std::cerr << "Error line " << line_num
                  << ": EFFECT found outside of SEQUENCE\n";
        return 1;
      }
      std::string class_name, start, end, priority;
      if (!(ss >> class_name >> start >> end >> priority)) {
        std::cerr << "Error line " << line_num
                  << ": EFFECT requires <Class> <start> <end> <priority>\n";
        return 1;
      }

      // Convert beat notation to time
      std::string start_time = convert_to_time(start, bpm);
      std::string end_time = convert_to_time(end, bpm);

      // Capture remaining args (but strip inline comments)
      std::string rest_of_line;
      std::getline(ss, rest_of_line); // Read rest of line
      // Strip inline comments (everything from '#' onwards)
      size_t comment_pos = rest_of_line.find('#');
      if (comment_pos != std::string::npos) {
        rest_of_line = rest_of_line.substr(0, comment_pos);
      }
      // Remove leading/trailing whitespace
      rest_of_line = trim(rest_of_line);

      std::string extra_args = "";
      if (!rest_of_line.empty()) {
        extra_args = ", " + rest_of_line;
      }

      current_seq->effects.push_back(
          {class_name, start_time, end_time, priority, extra_args});
    } else {
      std::cerr << "Error line " << line_num << ": Unknown command '" << command
                << "'\n";
      return 1;
    }
  }

  // Sort sequences by priority
  std::sort(sequences.begin(), sequences.end(),
            [](const SequenceEntry& a, const SequenceEntry& b) {
              return std::stoi(a.priority) < std::stoi(b.priority);
            });

  // Sort effects within each sequence by priority
  for (auto& seq : sequences) {
    std::sort(seq.effects.begin(), seq.effects.end(),
              [](const EffectEntry& a, const EffectEntry& b) {
                return std::stoi(a.priority) < std::stoi(b.priority);
              });
  }

  std::ofstream out_file(argv[2]);
  if (!out_file.is_open()) {
    std::cerr << "Error: Could not open output file " << argv[2] << "\n";
    return 1;
  }

  out_file << "// Auto-generated by seq_compiler. Do not edit.\n";
  out_file << "#include \"gpu/demo_effects.h\"\n";
  out_file << "#include \"gpu/effect.h\"\n\n";

  // Generate demo duration function
  if (!demo_end_time.empty()) {
    out_file << "float GetDemoDuration() {\n";
    out_file << "  return " << demo_end_time << "f;\n";
    out_file << "}\n\n";
  } else {
    out_file << "float GetDemoDuration() {\n";
    out_file << "  return -1.0f;  // No end time specified\n";
    out_file << "}\n\n";
  }

  out_file << "void LoadTimeline(MainSequence& main_seq, WGPUDevice device, "
              "WGPUQueue queue, WGPUTextureFormat format) {\n";

  for (const SequenceEntry& seq : sequences) {
    out_file << "  {\n";
    out_file << "    auto seq = std::make_shared<Sequence>();\n";
    // Set sequence end time if specified
    if (seq.end_time != "-1.0") {
      out_file << "    seq->set_end_time(" << seq.end_time << "f);\n";
    }
    for (const EffectEntry& eff : seq.effects) {
      out_file << "    seq->add_effect(std::make_shared<" << eff.class_name
               << ">(device, queue, format" << eff.extra_args << "), "
               << eff.start << "f, " << eff.end << "f, " << eff.priority
               << ");\n";
    }
    out_file << "    main_seq.add_sequence(seq, " << seq.start_time << "f, "
             << seq.priority << ");\n";
    out_file << "  }\n";
  }

  out_file << "}\n";

  std::cout << "Successfully generated timeline with " << sequences.size()
            << " sequences.\n";

  // Generate Gantt chart if requested
  if (!gantt_output.empty()) {
    generate_gantt_chart(gantt_output, sequences, bpm, demo_end_time);
  }

  return 0;
}