-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathofApp.cpp
More file actions
784 lines (675 loc) · 30.1 KB
/
ofApp.cpp
File metadata and controls
784 lines (675 loc) · 30.1 KB
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
#include "ofApp.h"
#include <deque>
#include <random>
#include <chrono>
//--------------------------------------------------------------
void ofApp::setup() {
// Load and setup shaders with explicit version
if (!glowShader.load("shaders/glow")) {
ofLogError("ofApp") << "Failed to load shaders";
}
shaderTime = 0;
// Setup GL state
cellSize = 20; // Initial cell size
ofSetFrameRate(60);
showSolution = false;
showGui = true;
// Set initial background and drawing colors
ofBackground(33); // Dark background for both modes
ofSetColor(255); // White for drawing
// ofSetCurrentRenderer(std::shared_ptr<ofBaseRenderer> renderer);
// Setup GUI
gui.setup("Maze Controls");
showGui.set("Show GUI", true);
mazeInfo.set("Maze Info", "");
// Maze Settings group
sizeControls.setName("Maze Settings");
animationEnabled.set("Enable Animation", true);
view3D.set("3D View", false);
cellSizeGui.set("Cell Size", cellSize, 10, 50);
sizeControls.add(animationEnabled);
sizeControls.add(view3D);
sizeControls.add(cellSizeGui);
// Initialize 3D properties
wallHeight = cellSize * 2; // Reduced wall height
cam.setDistance(500);
cam.setNearClip(0.01); // Allow even closer zoom
cam.setFarClip(10000); // Maintain far viewing distance
// Set camera target to maze center
cam.setTarget(ofVec3f(
(2 * mazeWidth + 1) * cellSize / 2,
(2 * mazeHeight + 1) * cellSize / 2,
wallHeight / 2
));
// Setup lights for OF 0.12
pointLight.setup();
pointLight.enable();
pointLight.setDiffuseColor(ofColor(200, 200, 200)); // Softer diffuse light
pointLight.setSpecularColor(ofColor(255, 255, 255));
pointLight.setAttenuation(1.0, 0.002, 0.0); // Adjusted attenuation for better falloff
directionalLight.setup();
directionalLight.enable();
directionalLight.setDirectional();
directionalLight.setDiffuseColor(ofColor(100, 100, 100)); // Dimmer ambient light
directionalLight.setSpecularColor(ofColor(150, 150, 150)); // Reduced specular
generateButton.setup("Generate New Maze");
solveButton.setup("Show Solution"); // Changed text to be more clear
gui.add(&generateButton);
gui.add(&solveButton);
// Algorithm selection group
algorithmGroup.setName("Generation Algorithm");
algorithmRecursive.set("Recursive Backtracker", true);
algorithmPrims.set("Prim's Algorithm", false);
algorithmKruskals.set("Kruskal's Algorithm", false);
algorithmGroup.add(algorithmRecursive);
algorithmGroup.add(algorithmPrims);
algorithmGroup.add(algorithmKruskals);
// Add groups to GUI
gui.add(sizeControls);
gui.add(algorithmGroup);
generateButton.addListener(this, &ofApp::onGeneratePressed);
solveButton.addListener(this, &ofApp::onSolvePressed);
currentGenerationAlgorithm = GenerationAlgorithm::RECURSIVE_BACKTRACKER;
// Set initial window size
ofSetWindowShape(1024, 768);
// Initialize maze dimensions
mazeWidth = 10; // Start with fixed size for testing
mazeHeight = 10;
// Initialize maze vector with proper dimensions
maze.resize(2 * mazeHeight + 1);
for (auto& row : maze) {
row.resize(2 * mazeWidth + 1, 1);
}
// Initialize animation properties
animatingGeneration = false;
animatingSolution = false;
generationDelay = 50; // milliseconds
solutionDelay = 100; // milliseconds
lastUpdateTime = 0;
// Initialize directions for maze generation
directions = {{0, 2}, {2, 0}, {0, -2}, {-2, 0}};
// Generate first maze
resetMaze();
generateMaze();
}
void ofApp::onGeneratePressed() {
if (!animatingGeneration) {
resetMaze();
if (animationEnabled) {
// Start animated generation
animatingGeneration = true;
animatingSolution = false;
showSolution = false;
current_x = 2 * (static_cast<int>(ofRandom(mazeWidth))) + 1;
current_y = 2 * (static_cast<int>(ofRandom(mazeHeight))) + 1;
unvisited = mazeWidth * mazeHeight - 1;
maze[current_y][current_x] = 0;
} else {
// Instant generation
animatingGeneration = false;
generateMaze();
solveMaze();
}
} else if (animatingGeneration) {
// Stop animation if it's running
animatingGeneration = false;
generateMaze();
solveMaze();
}
}
void ofApp::onSolvePressed() {
if (!animatingGeneration) {
// Always toggle solution visibility
showSolution = !showSolution;
if (showSolution) {
// If showing solution and animation is enabled, start animation
if (animationEnabled) {
animatingSolution = true;
solution.clear();
solveMaze();
currentSolutionIndex = 0;
} else {
// Just show the full solution without animation
solution.clear();
solveMaze();
animatingSolution = false;
}
} else {
// When hiding solution, stop any ongoing animation
animatingSolution = false;
}
}
}
//--------------------------------------------------------------
void ofApp::update() {
float currentTime = ofGetElapsedTimeMillis();
// Handle algorithm selection
if (algorithmRecursive && currentGenerationAlgorithm != GenerationAlgorithm::RECURSIVE_BACKTRACKER) {
algorithmPrims = false;
algorithmKruskals = false;
currentGenerationAlgorithm = GenerationAlgorithm::RECURSIVE_BACKTRACKER;
} else if (algorithmPrims && currentGenerationAlgorithm != GenerationAlgorithm::PRIMS) {
algorithmRecursive = false;
algorithmKruskals = false;
currentGenerationAlgorithm = GenerationAlgorithm::PRIMS;
} else if (algorithmKruskals && currentGenerationAlgorithm != GenerationAlgorithm::KRUSKALS) {
algorithmRecursive = false;
algorithmPrims = false;
currentGenerationAlgorithm = GenerationAlgorithm::KRUSKALS;
}
// Sync cell size with GUI
if (cellSize != cellSizeGui) {
cellSize = cellSizeGui;
updateMazeDimensions();
resetMaze();
generateMaze();
solveMaze();
}
if ((animatingGeneration || animatingSolution) &&
(currentTime - lastUpdateTime > (animatingGeneration ? generationDelay : solutionDelay))) {
updateAnimation();
lastUpdateTime = currentTime;
} else if (animatingSolution && !solution.empty()) {
// Animate solution path
if (currentSolutionIndex < static_cast<int>(solution.size())) {
currentSolutionIndex++;
} else {
animatingSolution = false;
}
}
}
//--------------------------------------------------------------
void ofApp::draw() {
ofBackground(33); // Keep consistent dark background
// Update maze info
string info = "Maze Size: " + ofToString(mazeWidth) + "x" + ofToString(mazeHeight) + "\n";
info += "Cell Size: " + ofToString(cellSize) + "px\n";
info += "Generation Algorithm: ";
info += (algorithmRecursive ? "Recursive Backtracker" :
algorithmPrims ? "Prim's Algorithm" :
"Kruskal's Algorithm");
info += "\n";
info += animatingGeneration ? "Generating..." :
(animatingSolution ? "Solving..." : "Ready");
mazeInfo.set(info);
if (view3D) {
// Basic 3D setup
ofEnableDepthTest();
ofEnableLighting();
// Set up camera for better 3D viewing
cam.disableOrtho(); // Use perspective for better 3D view
cam.begin();
// Adjust lighting for better visibility
ofEnableSeparateSpecularLight();
// Main point light above maze
pointLight.setDiffuseColor(ofColor(255, 255, 255));
pointLight.setSpecularColor(ofColor(255, 255, 255));
pointLight.setPosition((2 * mazeWidth + 1) * cellSize / 2,
(2 * mazeHeight + 1) * cellSize / 2,
wallHeight * 4);
// Add ambient light for better shadows
directionalLight.setDiffuseColor(ofColor(100, 100, 100));
directionalLight.setPosition(-wallHeight * 2, -wallHeight * 2, wallHeight * 2);
directionalLight.lookAt(ofVec3f((2 * mazeWidth + 1) * cellSize / 2,
(2 * mazeHeight + 1) * cellSize / 2,
0));
// Scale for retina displays
float scale = ofGetScreenWidth() / ofGetWidth();
ofScale(scale, scale, scale);
// Update directional light for ambient illumination
directionalLight.setPosition(0, 0, wallHeight * 4);
directionalLight.setOrientation(ofVec3f(0, 0, -90));
directionalLight.setDiffuseColor(ofColor(150, 150, 150)); // Brighter ambient light
// Center the maze
ofTranslate(
-(2 * mazeWidth + 1) * cellSize / 2,
-(2 * mazeHeight + 1) * cellSize / 2,
0
);
// Draw maze
// Draw floor
ofSetColor(50); // Darker floor for better contrast
ofDrawRectangle(0, 0, (2 * mazeWidth + 1) * cellSize, (2 * mazeHeight + 1) * cellSize);
// Draw walls as a single solid structure
ofSetColor(100, 100, 120); // Light gray-blue color for better contrast
ofMesh wallMesh;
wallMesh.setMode(OF_PRIMITIVE_TRIANGLES);
// Helper lambda to add a wall face (two triangles)
auto addWallFace = [&](const ofVec3f& bl, const ofVec3f& br,
const ofVec3f& tr, const ofVec3f& tl) {
int idx = wallMesh.getNumVertices();
wallMesh.addVertex(bl);
wallMesh.addVertex(br);
wallMesh.addVertex(tr);
wallMesh.addVertex(tl);
// First triangle
wallMesh.addIndex(idx);
wallMesh.addIndex(idx + 1);
wallMesh.addIndex(idx + 2);
// Second triangle
wallMesh.addIndex(idx);
wallMesh.addIndex(idx + 2);
wallMesh.addIndex(idx + 3);
// Add normals for better lighting
ofVec3f normal = ((br - bl).getCrossed(tr - bl)).normalized();
for (int i = 0; i < 4; i++) {
wallMesh.addNormal(normal);
}
};
for (int y = 0; y < 2 * mazeHeight + 1; y++) {
for (int x = 0; x < 2 * mazeWidth + 1; x++) {
if (maze[y][x] == 1) {
float wx = x * cellSize;
float wy = y * cellSize;
float wz = 0;
// Create vertices with a small offset to prevent z-fighting
const float eps = 0.01f; // Increased offset to prevent z-fighting
// Only create faces that are visible (not adjacent to another wall)
bool hasWallNorth = (y > 0) && maze[y-1][x] == 1;
bool hasWallSouth = (y < 2 * mazeHeight) && maze[y+1][x] == 1;
bool hasWallEast = (x < 2 * mazeWidth) && maze[y][x+1] == 1;
bool hasWallWest = (x > 0) && maze[y][x-1] == 1;
// Create vertices for the wall cube with slight offsets
ofVec3f frontBL(wx + eps, wy + eps, wz);
ofVec3f frontBR(wx + cellSize - eps, wy + eps, wz);
ofVec3f frontTR(wx + cellSize - eps, wy + eps, wz + wallHeight);
ofVec3f frontTL(wx + eps, wy + eps, wz + wallHeight);
ofVec3f backBL(wx + eps, wy + cellSize - eps, wz);
ofVec3f backBR(wx + cellSize - eps, wy + cellSize - eps, wz);
ofVec3f backTR(wx + cellSize - eps, wy + cellSize - eps, wz + wallHeight);
ofVec3f backTL(wx + eps, wy + cellSize - eps, wz + wallHeight);
// Only add faces that are visible, with proper depth testing
if (!hasWallNorth) addWallFace(frontBL, frontBR, frontTR, frontTL); // Front
if (!hasWallSouth) addWallFace(backBR, backBL, backTL, backTR); // Back
if (!hasWallEast) addWallFace(frontBR, backBR, backTR, frontTR); // Right
if (!hasWallWest) addWallFace(backBL, frontBL, frontTL, backTL); // Left
// Top face with slight inset to prevent z-fighting
ofVec3f topFrontLeft = frontTL + ofVec3f(eps, eps, 0);
ofVec3f topFrontRight = frontTR + ofVec3f(-eps, eps, 0);
ofVec3f topBackRight = backTR + ofVec3f(-eps, -eps, 0);
ofVec3f topBackLeft = backTL + ofVec3f(eps, -eps, 0);
addWallFace(topFrontLeft, topFrontRight, topBackRight, topBackLeft); // Top always visible
}
}
}
// Draw the entire maze as a single mesh
wallMesh.draw();
} else {
// 2D view with consistent dark theme
for (int y = 0; y < 2 * mazeHeight + 1; y++) {
for (int x = 0; x < 2 * mazeWidth + 1; x++) {
if (maze[y][x] == 1) {
ofSetColor(100, 100, 120); // Same color as 3D walls
drawCell(x, y, ofColor(100, 100, 120));
}
}
}
}
// Draw current position during generation
if (animatingGeneration) {
drawCell(current_x, current_y, ofColor(255, 0, 0, 128)); // Semi-transparent red
}
// Draw solution if enabled and exists
if (showSolution && !solution.empty()) {
if (view3D) {
// Draw solution path as a continuous tube
// Draw solution path as a continuous tube
int endIndex = animatingSolution ? currentSolutionIndex : solution.size();
ofMesh tubeMesh; // Moved outside the if block
if (endIndex > 1) {
tubeMesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
const int segments = 8; // Number of segments around the tube
const float radius = cellSize/4; // Much thicker tube
for (size_t i = 0; i < endIndex - 1; i++) {
const auto& current = solution[i];
const auto& next = solution[i + 1];
float x1 = (current.first + 0.5) * cellSize;
float y1 = (current.second + 0.5) * cellSize;
float x2 = (next.first + 0.5) * cellSize;
float y2 = (next.second + 0.5) * cellSize;
// Calculate direction vector
ofVec3f dir(x2 - x1, y2 - y1, 0);
ofVec3f up(0, 0, 1);
ofVec3f right = dir.getCrossed(up).normalized();
// Create circle points around the tube
for (int s = 0; s <= segments; s++) {
float angle = TWO_PI * s / segments;
float cosA = cos(angle);
float sinA = sin(angle);
// Calculate points for both ends of this segment
ofVec3f offset = right * (radius * cosA) + up * (radius * sinA);
// Add vertices for both ends with proper height (lifted by half cell size)
ofVec3f v1(x1, y1, cellSize); // Lifted to cellSize instead of cellSize/2
ofVec3f v2(x2, y2, cellSize); // Lifted to cellSize instead of cellSize/2
// Calculate normal vector for proper 3D appearance
ofVec3f normal = offset.normalized();
// Add height offset based on normal
v1 += normal * radius;
v2 += normal * radius;
tubeMesh.addVertex(v1);
tubeMesh.addVertex(v2);
// Add color for both vertices
ofFloatColor color(1.0, 0.55, 0.0); // Golden orange
tubeMesh.addColor(color);
tubeMesh.addColor(color);
}
}
tubeMesh.draw();
}
// Apply glow effect and lights to the solution path
if (showSolution) {
// Update tube lights - limit to max 8 lights
tubeLights.clear();
size_t numLights = std::min(size_t(8), solution.size());
size_t step = solution.size() / numLights;
for (size_t i = 0; i < numLights; i++) {
size_t index = i * step;
if (index >= endIndex) break;
const auto& pos = solution[index];
ofLight tubeLight;
tubeLight.setup();
tubeLight.enable();
tubeLight.setPointLight();
// Position light slightly above the tube
tubeLight.setPosition(
(pos.first + 0.5) * cellSize,
(pos.second + 0.5) * cellSize,
cellSize * 1.5 // Raised position
);
// Point light downward at the tube
tubeLight.lookAt(ofVec3f(
(pos.first + 0.5) * cellSize,
(pos.second + 0.5) * cellSize,
cellSize
));
tubeLight.setDiffuseColor(ofColor(255, 140, 0, 200)); // Semi-transparent golden orange
tubeLight.setSpecularColor(ofColor(255, 200, 0, 200));
tubeLight.setAttenuation(0.5, 0.001, 0.0); // Reduced attenuation for wider light spread
tubeLight.setSpotlight(); // Use spotlight for more focused illumination
tubeLight.setSpotlightCutOff(60); // Wide angle for better coverage
tubeLight.setSpotConcentration(2); // Soft edge falloff
tubeLights.push_back(tubeLight);
}
// Set up blending for glow effect
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
// Begin glow shader with enhanced parameters
glowShader.begin();
glowShader.setUniform3f("glowColor", 1.0, 0.65, 0.0); // Brighter golden orange
glowShader.setUniform1f("glowIntensity", 2.5); // Increased intensity
glowShader.setUniform1f("time", shaderTime);
// Update shader time only when solution is visible
shaderTime += ofGetLastFrameTime() * 0.5; // Slower pulsing
tubeMesh.draw();
glowShader.end();
// Reset OpenGL state
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_BLEND);
// Disable tube lights
for (auto& light : tubeLights) {
light.disable();
}
tubeLights.clear();
} else {
// Draw without glow effect when solution is not visible
tubeMesh.draw();
}
} else {
// Draw solution path background
ofSetColor(255, 240, 240); // Light red background
int endIndex = animatingSolution ? currentSolutionIndex : solution.size();
for (int i = 0; i < endIndex && i < solution.size(); i++) {
const auto& pos = solution[i];
drawCell(pos.first, pos.second, ofColor(255, 240, 240));
}
ofSetColor(255, 0, 0); // Red path
ofSetLineWidth(cellSize/3);
// Draw lines connecting solution points
int lineEndIndex = animatingSolution ? currentSolutionIndex : solution.size();
for (size_t i = 0; i < lineEndIndex - 1 && i < solution.size() - 1; i++) {
const auto& current = solution[i];
const auto& next = solution[i + 1];
float x1 = (current.first + 0.5) * cellSize;
float y1 = (current.second + 0.5) * cellSize;
float x2 = (next.first + 0.5) * cellSize;
float y2 = (next.second + 0.5) * cellSize;
ofDrawLine(x1, y1, x2, y2);
}
}
}
if (view3D) {
cam.end();
ofDisableLighting();
ofDisableDepthTest();
}
// Draw GUI if enabled (now on top of everything)
if (showGui) {
ofSetColor(255); // Ensure GUI is drawn in white
gui.draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
bool needsUpdate = false;
if (key == ' ') { // Spacebar generates new maze instantly
animatingGeneration = false; // Stop any ongoing animation
animatingSolution = false;
resetMaze();
generateMaze();
solveMaze();
animationEnabled = false; // Disable animation when using spacebar
} else if (key == 'g') { // 'g' toggles animated generation
animationEnabled = !animationEnabled; // Toggle animation state
if (animatingGeneration) {
// Stop current animation if running
animatingGeneration = false;
generateMaze();
solveMaze();
}
} else if (key == 'f') { // 'f' toggles animated solution
if (!animatingGeneration) {
if (!animatingSolution) {
animatingSolution = true;
showSolution = true;
solution.clear();
solveMaze();
currentSolutionIndex = 0;
} else {
animatingSolution = false;
}
}
} else if (key == 's') { // 's' toggles solution visibility
showSolution = !showSolution;
animatingSolution = false; // Stop any ongoing solution animation
} else if (key == '+' || key == '=') { // Increase cell size
cellSizeGui = min(50, cellSize + 2);
cellSize = cellSizeGui;
needsUpdate = true;
} else if (key == '-' || key == '_') { // Decrease cell size
cellSizeGui = max(10, cellSize - 2);
cellSize = cellSizeGui;
needsUpdate = true;
} else if (key == 'h') { // Toggle GUI
showGui = !showGui;
}
if (needsUpdate) {
updateMazeDimensions();
resetMaze();
generateMaze();
solveMaze();
}
}
//--------------------------------------------------------------
void ofApp::generateMaze() {
// Start with all walls
for (int y = 0; y < 2 * mazeHeight + 1; y++) {
for (int x = 0; x < 2 * mazeWidth + 1; x++) {
maze[y][x] = 1;
}
}
// Start at a random cell
int current_x = 2 * (static_cast<int>(ofRandom(mazeWidth))) + 1;
int current_y = 2 * (static_cast<int>(ofRandom(mazeHeight))) + 1;
maze[current_y][current_x] = 0;
int unvisited = mazeWidth * mazeHeight - 1;
vector<pair<int, int>> directions = {{0, 2}, {2, 0}, {0, -2}, {-2, 0}};
while (unvisited > 0) {
// Pick a random direction
int dir_idx = static_cast<int>(ofRandom(4));
int dx = directions[dir_idx].first;
int dy = directions[dir_idx].second;
int next_x = current_x + dx;
int next_y = current_y + dy;
// Check if the next cell is valid and unvisited
if (next_x > 0 && next_x < 2 * mazeWidth &&
next_y > 0 && next_y < 2 * mazeHeight &&
maze[next_y][next_x] == 1) {
// Carve a passage
maze[(current_y + next_y) / 2][(current_x + next_x) / 2] = 0; // Remove wall
maze[next_y][next_x] = 0; // Mark cell as visited
unvisited--;
current_x = next_x;
current_y = next_y;
} else {
// If we hit a wall or visited cell, randomly jump to a visited cell
do {
current_x = 2 * (static_cast<int>(ofRandom(mazeWidth))) + 1;
current_y = 2 * (static_cast<int>(ofRandom(mazeHeight))) + 1;
} while (maze[current_y][current_x] == 1);
}
}
// Create entrance and exit
maze[0][1] = 0; // Entrance at top
maze[2 * mazeHeight][2 * mazeWidth - 1] = 0; // Exit at bottom
// Ensure the cells next to entrance/exit are open
maze[1][1] = 0; // Cell after entrance
maze[2 * mazeHeight - 1][2 * mazeWidth - 1] = 0; // Cell before exit
}
//--------------------------------------------------------------
bool ofApp::isValid(int x, int y) {
// Check bounds for the entire maze including walls
return x >= 0 && x < (2 * mazeWidth + 1) &&
y >= 0 && y < (2 * mazeHeight + 1);
}
//--------------------------------------------------------------
void ofApp::solveMaze() {
solution.clear();
// Start from entrance, end at exit
pair<int, int> start = {1, 0};
pair<int, int> end = {2 * mazeWidth - 1, 2 * mazeHeight};
// BFS queue and visited set
deque<pair<pair<int, int>, vector<pair<int, int>>>> queue;
set<pair<int, int>> visited;
// Initialize with start position
queue.push_back({start, {start}});
visited.insert(start);
// Possible moves: down, right, up, left
vector<pair<int, int>> moves = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!queue.empty()) {
auto current = queue.front().first;
auto path = queue.front().second;
queue.pop_front();
// Check if we reached the exit
if (current == end) {
solution = path;
return;
}
// Try all possible moves
for (const auto& move : moves) {
int next_x = current.first + move.first;
int next_y = current.second + move.second;
// Check if the move is valid
if (isValid(next_x, next_y) &&
maze[next_y][next_x] == 0 &&
visited.find({next_x, next_y}) == visited.end()) {
// Create new path with this move
auto new_path = path;
new_path.push_back({next_x, next_y});
// Add to queue and mark as visited
queue.push_back({{next_x, next_y}, new_path});
visited.insert({next_x, next_y});
}
}
}
}
//--------------------------------------------------------------
void ofApp::drawCell(int x, int y, const ofColor& color) {
ofSetColor(color);
ofFill();
ofDrawRectangle(x * cellSize, y * cellSize, cellSize, cellSize);
}
//--------------------------------------------------------------
void ofApp::resetMaze() {
// Ensure maze vector has correct size before accessing
if (maze.size() != 2 * mazeHeight + 1) {
maze.resize(2 * mazeHeight + 1);
}
for (int y = 0; y < 2 * mazeHeight + 1; y++) {
if (maze[y].size() != 2 * mazeWidth + 1) {
maze[y].resize(2 * mazeWidth + 1);
}
for (int x = 0; x < 2 * mazeWidth + 1; x++) {
maze[y][x] = 1;
}
}
solution.clear();
}
void ofApp::windowResized(int w, int h) {
updateMazeDimensions();
resetMaze();
generateMaze();
solveMaze();
}
void ofApp::updateMazeDimensions() {
// Calculate new dimensions with bounds checking
int newWidth = std::clamp((ofGetWidth() / cellSize - 1) / 2, 5, 100);
int newHeight = std::clamp((ofGetHeight() / cellSize - 1) / 2, 5, 100);
// Only update if dimensions have changed
if (newWidth != mazeWidth || newHeight != mazeHeight) {
mazeWidth = newWidth;
mazeHeight = newHeight;
// Properly resize both dimensions of the vector
maze.resize(2 * mazeHeight + 1);
for (auto& row : maze) {
row.resize(2 * mazeWidth + 1, 1);
}
// Clear solution when dimensions change
solution.clear();
}
}
void ofApp::updateAnimation() {
if (animatingGeneration) {
if (unvisited > 0) {
// Pick a random direction
int dir_idx = static_cast<int>(ofRandom(4));
int dx = directions[dir_idx].first;
int dy = directions[dir_idx].second;
int next_x = current_x + dx;
int next_y = current_y + dy;
// Check if the next cell is valid and unvisited
if (next_x > 0 && next_x < 2 * mazeWidth &&
next_y > 0 && next_y < 2 * mazeHeight &&
maze[next_y][next_x] == 1) {
// Carve a passage
maze[(current_y + next_y) / 2][(current_x + next_x) / 2] = 0;
maze[next_y][next_x] = 0;
unvisited--;
current_x = next_x;
current_y = next_y;
} else {
// If we hit a wall or visited cell, randomly jump to a visited cell
do {
current_x = 2 * (static_cast<int>(ofRandom(mazeWidth))) + 1;
current_y = 2 * (static_cast<int>(ofRandom(mazeHeight))) + 1;
} while (maze[current_y][current_x] == 1);
}
} else {
// Finish generation
maze[0][1] = 0; // Create entrance
maze[2 * mazeHeight][2 * mazeWidth - 1] = 0; // Create exit
maze[1][1] = 0; // Ensure entrance path
maze[2 * mazeHeight - 1][2 * mazeWidth - 1] = 0; // Ensure exit path
animatingGeneration = false;
}
}
}