如果只看一张截图,你可能会以为这是某个轻量级 3D 引擎做出来的小游戏:镜头在弯曲的隧道里高速前进,远处的方块迎面扑来,玩家需要不断旋转跑道,在越来越密集的障碍之间寻找缺口。
但这个 Demo 没有使用现成的 3D 游戏引擎,也没有依赖模型、贴图或其他外部素材。透视投影、三角形光栅化、深度缓冲、雾效、方块光照、碰撞检测和游戏状态,全部写在一个 C++ 源文件里,最终画面直接交给 EGE 显示。
先通过下面这段约 8 秒的实机片段感受速度、转向、障碍逼近和碰撞反馈:
这是一份适合“边玩边学”的 EGE 范例:你可以先挑战自己的最高分,再沿着源码逐层拆开一个小型 3D 游戏究竟由哪些部分组成。
从早期 iPhone 经典,到浏览器里的 3D 隧道
Cube Runner 这个名字,会唤起不少早期智能手机玩家的记忆。
2008 年,开发者 Andy Qua 在 App Store 初期推出了面向 iPhone 和 iPod touch 的《Cube Runner》。玩法非常直接:利用手机的重力感应控制飞行器,在布满方块的场地中高速穿行。它是免费游戏,画面简洁,控制灵敏,还支持下载和分享自制关卡。多年后,App Store 上的玩家评论依然经常提到它带来的怀旧感,而开发者也持续为它加入复古模式、第一人称视角、手柄支持等功能。
不过,本篇介绍的 EGE Demo 并不是对 iOS 版本的官方移植。
它直接参考的是 Game5 制作的浏览器实验 Cuberunner。这个项目于 2015 年进入 Chrome Experiments,使用 WebGL 构建了一条可以不断旋转的 3D 隧道:玩家控制小方块绕着隧道移动,躲避迎面而来的彩色障碍。
EGE 版本延续了这种“隧道旋转 + 方块躲避”的核心体验,同时重新实现了几何、软件光栅器、HUD 和游戏逻辑,没有复用原项目的模型、贴图或音频资源。换句话说,它更像一次从玩法出发的 C++ / EGE 重写,而不是把浏览器代码简单搬进桌面程序。
可以把这三段历史这样理解:
- 2008 年的 iPhone《Cube Runner》,代表了早期移动游戏中“规则简单、依靠反应、不断挑战高分”的经典体验;
- 2015 年 Game5 的
Cuberunner,把相似的躲避乐趣放进旋转的 WebGL 隧道; - 现在的 EGE Demo,则进一步用 C++ 和 CPU 软件渲染重新完成这套视觉与玩法。
目前没有可靠证据表明 Game5 版本与 Andy Qua 的手机游戏存在官方授权或移植关系,因此本文只把前者作为 EGE 源码的直接参考,把后者作为同名经典游戏的时代背景。
游戏怎么玩?
玩家控制的是画面下方的黄色小方块。它的位置基本固定,真正旋转的是整条隧道。这样既保留了高速前进的视觉效果,也让操作始终保持直观:把安全的轨道转到玩家脚下即可。
操作方式
| 操作 | 功能 |
|---|---|
A / D 或方向键 |
向左、向右旋转隧道 |
| 按住鼠标左键并拖动 | 连续转向 |
P |
暂停或继续 |
R |
从头重新开始 |
Esc |
退出游戏 |
键盘转向不是生硬地跳到下一条轨道,而是先计算目标角速度,再让当前角速度平滑靠近目标。松开按键后,转速也会快速衰减,因此操作既灵敏,又不会显得突然。
三次机会,八种关卡
游戏开始时有三点生命。撞上障碍物会扣除一点生命,并获得短暂的无敌时间;无敌期间,玩家方块会闪烁,避免连续碰撞瞬间耗尽生命。生命归零后进入游戏结束状态,按 R 就能马上再来一局。
关卡每 30 秒切换一次,共有八种障碍模式:
- 基础彩色方块;
- 速度更快的红色方块;
- 更高、更厚的石块;
- 向隧道中心伸出的长方体;
- 组合出现的彩色障碍;
- 连续占据多条轨道的方块墙;
- 带有连续追击节奏的障碍组合;
- 宽阔屏障与高速方块的混合挑战。
完成八个阶段后,游戏进入下一轮,基础前进速度继续提高。得分则随存活时间不断增加。规则并不复杂,但当速度越来越快、障碍组合越来越紧密时,“再多撑十秒”就会变得很有吸引力。
不使用 3D 引擎,画面是怎么出现的?
这个 Demo 最值得学习的部分,是它没有调用现成的 3D 场景系统,而是自己完成了一个精简的软件渲染管线。
1. 先在三维空间中描述点
程序使用一个很小的 Vec3 结构表示三维坐标,并实现向量加减、缩放、点积、叉积和单位化。这些基础运算足以计算方块顶点、表面法线和光照方向。
|
1 2 3 4 5 |
struct Vec3 { float x; float y; float z; }; |
一只方块由 8 个顶点、6 个面组成。每个四边形面再拆成两个三角形,于是无论玩家、普通障碍还是大型屏障,最终都能交给同一套三角形绘制函数处理。
2. 把三维坐标投影到屏幕
透视投影的直观规律是“近大远小”。程序根据视场角计算焦距,再用深度 z 的倒数缩放横纵坐标:
|
1 2 |
screenX = width * 0.5f + x * focalLength / z; screenY = height * 0.5f - (y - cameraY) * focalLength / z; |
这里的垂直视场角为 75 度。距离摄像机过近的点会被近平面剔除,远处的物体则逐渐融入深色背景,形成速度游戏常见的纵深和雾感。
3. 用重心坐标填充三角形
三角形投影到屏幕后,程序计算它的包围盒,并逐像素判断采样点是否位于三角形内部。三个边函数得到的权重既可以完成覆盖测试,也可以插值深度。
每个像素还对应一个深度缓冲值。只有更靠近摄像机的新像素才能覆盖旧像素,因此隧道、方块和网格线才能保持正确的前后遮挡关系。
这就是一个小而完整的软件光栅器:
|
1 2 3 4 5 6 |
三维顶点 → 透视投影 → 三角形包围盒 → 重心坐标覆盖测试 → 深度测试 → 雾效与颜色写入 |
4. 直接写入 EGE 图像缓冲区
EGE 的 newimage() 创建离屏图像,getbuffer() 取得像素缓冲区。软件渲染器直接把 ARGB 像素写进这块内存,完成一帧后再通过 putimage() 显示到窗口。
这样避免了“先渲染到自己的数组、再整帧复制到 EGE 图像”的额外开销。HUD 则在画面提交后用 EGE 原生字体接口绘制,所以 Windows/MSVC 版本可以直接显示“生命、关卡、帧率”等中文信息。
一条会转弯的十二边形隧道
隧道横截面由 12 条轨道组成,纵深方向保留 24 排网格。程序根据角度计算圆周上的点,再把相邻轨道和相邻深度之间的四个点连成网格面。
如果隧道永远笔直,速度感很快就会变得单调。这里还为远处的隧道中心加入了一条二次曲线:距离超过一定范围后,隧道逐渐向下弯曲。玩家看不到终点,只能看到网格和障碍不断从弯道深处出现。
为了制造前进效果,程序不需要让摄像机真的无限移动。它只累计已经前进的距离,再用“距离对单格长度取余”的方式移动最近一排网格。当一排从身后消失时,远处会自然补上新的一排,形成连续不断的隧道。
八种障碍,不只是随机扔方块
如果障碍完全随机,游戏很容易出现无解局面,也很难产生节奏。Cube Runner 把障碍生成拆成八个阶段,每个阶段有自己的颜色、尺寸、速度、组合方式和间距。
例如:
- 快速方块会使用更高的移动倍率,让玩家必须提前反应;
- 高障碍向隧道中心延伸,视觉压迫感更强;
- 连续方块占据相邻轨道,要求玩家迅速判断缺口;
- 大型屏障会横跨多条轨道,同时配合另一个高速障碍制造选择压力。
障碍并不是凭空“闪现”在眼前,而是从远端生成,沿 z 轴向玩家移动。碰撞检测只需要同时判断两个条件:障碍是否进入玩家所在的深度范围,以及它旋转后的角度范围是否覆盖玩家。
这套设计很适合新手学习,因为它把关卡难度拆成了几个容易控制的参数:
- 障碍间距;
- 障碍尺寸;
- 占据的轨道数量;
- 相对移动速度;
- 同时生成的障碍组合;
- 每轮游戏的整体速度。
只改这些参数,就可以做出完全不同的节奏。
多线程软件渲染
1280×720 分辨率下,一帧接近 92 万个像素。为了让 CPU 软件渲染保持流畅,程序会根据硬件线程数选择 1、2 或 4 个渲染线程,并把屏幕按水平方向切成多个区域。
每个线程只写自己的像素带,因此不会同时修改同一个像素,也不需要给每次绘制加锁。主线程完成自己的区域后,等待其他渲染线程结束,再统一显示这一帧。
这不是大型引擎采用的完整并行渲染架构,但代码集中、概念清楚,很适合通过一个 Demo 理解任务分发、条件变量和无冲突分区这些基础思想。
为什么这个 Demo 适合新手?
乍看之下,三维投影、光栅化和多线程好像都很难。但 Cube Runner 的优势是:你不需要一次学完所有内容,也能先获得一个可以玩的结果。
推荐按照下面的顺序阅读源码:
- 先看
main(),了解 EGE 窗口、输入和每帧循环; - 再看
Game::update(),理解得分、速度、转向和障碍移动; - 阅读
spawnPattern(),尝试修改关卡组合; - 阅读
drawTube()和drawBox(),理解场景怎样由三角形组成; - 最后再进入
project()和rasterTriangle(),研究软件 3D 渲染。
第一次修改可以从这些小目标开始:
- 给玩家和障碍换一套颜色;
- 修改生命数量或每关持续时间;
- 设计第九种障碍模式;
- 增加最高分保存;
- 加入碰撞音效和背景音乐;
- 让隧道向左右弯曲,而不只是向下;
- 加入第一人称或无尽练习模式。
每完成一个小目标,你都会更熟悉游戏状态、实时输入、二维像素和三维数学之间的关系。
编译和运行
Cube Runner 已经包含在 EGE 仓库的 demo/game_cube_runner.cpp 中。在 Windows 开发环境中获取最新源码并完成 EGE 项目配置后,可以构建 game_cube_runner 目标。
仓库的 VS Code 任务已经提供 Debug 和 Release 两种运行入口;对应的 Release 命令为:
|
1 |
tasks.sh --release --target game_cube_runner --build --run game_cube_runner.exe |
程序默认使用 1280×720 分辨率,也可以通过参数指定其他尺寸:
|
1 |
game_cube_runner.exe --resolution 1920x1080 |
建议优先使用 Release 模式运行。软件光栅化需要处理大量像素,Debug 构建的帧率通常会明显低于 Release。
现在,挑战一下自己的最高分
Cube Runner 的规则几秒钟就能理解,但想在高速障碍之间稳定穿行并不容易。它保留了早期休闲游戏最迷人的特点:没有复杂的养成和菜单,只需要专注于眼前的轨道、下一组障碍,以及不断增长的分数。
更重要的是,这不仅是一个“能玩”的 Demo。它还把向量、投影、光栅化、深度缓冲、游戏循环、碰撞检测和并发渲染放进了一份可以逐行阅读的 C++ 源码里。
如果你刚开始学习 EGE,不妨先运行游戏、挑战一次最高分,然后改一种颜色、设计一种障碍。很多图形编程知识,正是在“我想让它再好玩一点”的过程中真正学会的。
源码与背景资料
- EGE Cube Runner 完整源码:https://github.com/x-ege/xege/blob/master/demo/game_cube_runner.cpp
- Cube Runner 合入记录与技术说明:https://github.com/x-ege/xege/pull/375
- Game5 WebGL
Cuberunner:https://www.game5.com.de/cuberunner/index.html - Chrome Experiments 项目页:https://experiments.withgoogle.com/cuberunner
- Andy Qua 的 iPhone / iPad《Cube Runner》:https://apps.apple.com/us/app/cube-runner/id284596345
- 2008 年 TouchArcade 介绍:https://toucharcade.com/2008/07/11/cube-runner-a-free-download-from-andy-qua/
完整源代码
下面是当前 EGE 仓库中的完整 demo/game_cube_runner.cpp。将它放在已配置好的 EGE Demo 工程中,即可构建并运行;如果仓库后续继续更新,请以文首链接指向的最新版为准。
|
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 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 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 |
// Cube Runner - a compact software-rendered 3D game for XEGE. // // Inspired by https://www.game5.com.de/cuberunner/index.html. The geometry, // rasterizer, HUD, and game logic below are original and use no external assets. #include <graphics.h> #include <algorithm> #include <array> #include <cmath> #include <condition_variable> #include <cstdint> #include <cstdlib> #include <functional> #include <iostream> #include <limits> #include <mutex> #include <string> #include <thread> #include <vector> // Total render threads, including the main thread. Set to 1 to disable parallel rendering. #ifndef CUBE_RUNNER_MAX_RENDER_THREADS #define CUBE_RUNNER_MAX_RENDER_THREADS 4 #endif // 文本本地化宏定义 // 与其它 demo 一致: MSVC 编译器使用中文文案, 其它编译器使用英文文案. #ifdef _MSC_VER // MSVC 编译器使用中文文案 #define TEXT_WINDOW_TITLE "XEGE - 立方体跑酷" #define TEXT_HUD_TITLE "立方体跑酷" #define TEXT_SCORE "得分 " #define TEXT_LIVES "生命 " #define TEXT_STAGE "关卡 " #define TEXT_FPS "帧率 " #define TEXT_CONTROLS "[A/D] 或拖动转向 [P] 暂停 [R] 重新开始" #define TEXT_GAME_OVER "游戏结束" #define TEXT_PAUSED "已暂停" #define TEXT_ACTION_RESTART "[R] 重新开始" #define TEXT_ACTION_RESUME "[P] 继续" #define TEXT_FONT_NAME "宋体" #else // 非MSVC编译器使用英文文案 #define TEXT_WINDOW_TITLE "XEGE - Cube Runner" #define TEXT_HUD_TITLE "CUBE RUNNER" #define TEXT_SCORE "SCORE " #define TEXT_LIVES "LIVES " #define TEXT_STAGE "STAGE " #define TEXT_FPS "FPS " #define TEXT_CONTROLS "[A/D] OR DRAG TO STEER [P] PAUSE [R] RESTART" #define TEXT_GAME_OVER "GAME OVER" #define TEXT_PAUSED "PAUSED" #define TEXT_ACTION_RESTART "[R] RESTART" #define TEXT_ACTION_RESUME "[P] RESUME" #define TEXT_FONT_NAME "Arial" #endif namespace cube_runner { constexpr int kDefaultWidth = 1280; constexpr int kDefaultHeight = 720; constexpr int kTracks = 12; constexpr int kTubeRows = 24; constexpr int kStageCount = 8; constexpr float kPi = 3.14159265358979323846f; constexpr float kTrackAngle = 2.0f * kPi / kTracks; const float kTileSize = 2.0f * std::sin(kPi / kTracks); constexpr float kTubeRadius = 1.0f; constexpr float kNearPlane = 0.18f; const float kFarPlane = kTileSize * kTubeRows; const float kFogNear = kFarPlane * 0.25f; constexpr float kCameraY = -0.5f; constexpr float kPlayerAngle = -kPi * 0.5f; constexpr float kVerticalFieldOfView = 75.0f; // The browser game advances 0.14 world units per 60 Hz frame and adds // 0.02 units per frame after each complete eight-stage level. constexpr float kReferenceFps = 60.0f; constexpr float kBaseSpeed = 0.14f * kReferenceFps; constexpr float kLevelSpeedStep = 0.02f * kReferenceFps; constexpr float kStageDuration = 30.0f; constexpr float kTubeStart = 0.42f; constexpr float kKeyboardTurnSpeed = kTrackAngle * 8.0f; constexpr float kMouseDragSensitivity = kTrackAngle / 56.0f; static_assert(CUBE_RUNNER_MAX_RENDER_THREADS >= 1, "CUBE_RUNNER_MAX_RENDER_THREADS must be at least one"); thread_local int gRenderBandTop = 0; thread_local int gRenderBandBottom = std::numeric_limits<int>::max(); class RenderBandScope { public: RenderBandScope(int top, int bottom) : previousTop(gRenderBandTop), previousBottom(gRenderBandBottom) { gRenderBandTop = top; gRenderBandBottom = bottom; } ~RenderBandScope() { gRenderBandTop = previousTop; gRenderBandBottom = previousBottom; } private: int previousTop; int previousBottom; }; int chooseRenderThreadCount() { const unsigned int hardwareThreads = std::thread::hardware_concurrency(); const int automaticCount = hardwareThreads == 0 ? 2 : (hardwareThreads >= 8 ? 4 : (hardwareThreads > 2 ? 2 : 1)); return std::max(1, std::min({automaticCount, CUBE_RUNNER_MAX_RENDER_THREADS, 4})); } class KeyPressLatch { public: bool update(bool down, int pressCount) { const bool pressed = pressCount > 0 || (down && !wasDown); wasDown = down; return pressed; } private: bool wasDown {false}; }; class RenderExecutor { public: RenderExecutor() : totalThreads(chooseRenderThreadCount()) { for (int workerIndex = 1; workerIndex < totalThreads; ++workerIndex) { workers.emplace_back(&RenderExecutor::workerLoop, this, workerIndex); } } ~RenderExecutor() { { std::lock_guard<std::mutex> lock(mutex); stopping = true; ++generation; } workReady.notify_all(); for (std::thread& worker : workers) { worker.join(); } } int threadCount() const { return totalThreads; } void execute(const std::function<void(int)>& task) { if (totalThreads == 1) { task(0); return; } { std::lock_guard<std::mutex> lock(mutex); frameTask = task; remainingWorkers = totalThreads - 1; ++generation; } workReady.notify_all(); task(0); std::unique_lock<std::mutex> lock(mutex); frameFinished.wait(lock, [&] { return remainingWorkers == 0; }); frameTask = nullptr; } private: void workerLoop(int workerIndex) { std::size_t completedGeneration = 0; for (;;) { std::function<void(int)> task; { std::unique_lock<std::mutex> lock(mutex); workReady.wait(lock, [&] { return stopping || generation != completedGeneration; }); if (stopping) { return; } completedGeneration = generation; task = frameTask; } task(workerIndex); { std::lock_guard<std::mutex> lock(mutex); --remainingWorkers; if (remainingWorkers == 0) { frameFinished.notify_one(); } } } } const int totalThreads; std::vector<std::thread> workers; std::mutex mutex; std::condition_variable workReady; std::condition_variable frameFinished; std::function<void(int)> frameTask; std::size_t generation {0}; int remainingWorkers {0}; bool stopping {false}; }; RenderExecutor& renderExecutor() { static RenderExecutor executor; return executor; } int renderThreadCount() { return renderExecutor().threadCount(); } struct Vec3 { float x; float y; float z; Vec3 operator+(const Vec3& other) const { return {x + other.x, y + other.y, z + other.z}; } Vec3 operator-(const Vec3& other) const { return {x - other.x, y - other.y, z - other.z}; } Vec3 operator*(float value) const { return {x * value, y * value, z * value}; } }; Vec3 cross(const Vec3& a, const Vec3& b) { return { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x, }; } float dot(const Vec3& a, const Vec3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } Vec3 normalize(const Vec3& value) { const float length = std::sqrt(std::max(dot(value, value), 0.000001f)); return value * (1.0f / length); } struct Color { int r; int g; int b; }; Color scaleColor(Color color, float scale) { return { std::clamp(static_cast<int>(color.r * scale), 0, 255), std::clamp(static_cast<int>(color.g * scale), 0, 255), std::clamp(static_cast<int>(color.b * scale), 0, 255), }; } Color mixColor(Color a, Color b, float amount) { amount = std::clamp(amount, 0.0f, 1.0f); return { static_cast<int>(a.r + (b.r - a.r) * amount), static_cast<int>(a.g + (b.g - a.g) * amount), static_cast<int>(a.b + (b.b - a.b) * amount), }; } std::uint32_t packColor(Color color) { return 0xff000000u | (static_cast<std::uint32_t>(std::clamp(color.r, 0, 255)) << 16) | (static_cast<std::uint32_t>(std::clamp(color.g, 0, 255)) << 8) | static_cast<std::uint32_t>(std::clamp(color.b, 0, 255)); } class Surface { public: // Borrows an externally-owned color buffer (typically the EGE PIMAGE buffer // returned by getbuffer(); color_t is uint32_t and packColor already emits // 0xAARRGGBB, so no conversion is needed). The z-buffer remains owned. Surface(int width, int height, std::uint32_t* pixels) : width(width), height(height), pixels(pixels), depth(static_cast<std::size_t>(width) * height) { } void clear(Color color) { const int top = std::clamp(gRenderBandTop, 0, height); const int bottom = std::clamp(gRenderBandBottom, top, height); const std::size_t first = static_cast<std::size_t>(top) * width; const std::size_t last = static_cast<std::size_t>(bottom) * width; std::fill(pixels + first, pixels + last, packColor(color)); std::fill(depth.begin() + first, depth.begin() + last, std::numeric_limits<float>::infinity()); } void blendPixel(int x, int y, Color color, float alpha) { if (x < 0 || x >= width || y < 0 || y >= height || y < gRenderBandTop || y >= gRenderBandBottom) { return; } const std::size_t index = static_cast<std::size_t>(y) * width + x; const std::uint32_t old = pixels[index]; const Color background { static_cast<int>((old >> 16) & 0xff), static_cast<int>((old >> 8) & 0xff), static_cast<int>(old & 0xff), }; pixels[index] = packColor(mixColor(background, color, alpha)); } void fillRect(int x, int y, int rectWidth, int rectHeight, Color color, float alpha = 1.0f) { const int left = std::max(0, x); const int top = std::max({0, y, gRenderBandTop}); const int right = std::min(width, x + rectWidth); const int bottom = std::min({height, y + rectHeight, gRenderBandBottom}); for (int py = top; py < bottom; ++py) { for (int px = left; px < right; ++px) { blendPixel(px, py, color, alpha); } } } int width; int height; std::uint32_t* pixels; std::vector<float> depth; }; struct Projected { float x; float y; float inverseDepth; bool valid; }; Projected project(const Surface& surface, const Vec3& point) { if (point.z <= kNearPlane) { return {0.0f, 0.0f, 0.0f, false}; } const float inverseDepth = 1.0f / point.z; const float focalLength = (surface.height * 0.5f) / std::tan(kVerticalFieldOfView * kPi / 360.0f); return { surface.width * 0.5f + point.x * focalLength * inverseDepth, surface.height * 0.5f - (point.y - kCameraY) * focalLength * inverseDepth, inverseDepth, true, }; } float edge(float ax, float ay, float bx, float by, float px, float py) { return (px - ax) * (by - ay) - (py - ay) * (bx - ax); } Color applyFog(Color color, float z) { const float visibility = std::clamp((kFarPlane - z) / (kFarPlane - kFogNear), 0.0f, 1.0f); return scaleColor(color, visibility); } void rasterTriangle(Surface& surface, const Vec3& a, const Vec3& b, const Vec3& c, Color color, bool fog = true, float alpha = 1.0f) { const Projected p0 = project(surface, a); const Projected p1 = project(surface, b); const Projected p2 = project(surface, c); if (!p0.valid || !p1.valid || !p2.valid) { return; } const float area = edge(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y); if (std::abs(area) < 0.001f) { return; } const int minX = std::max(0, static_cast<int>(std::floor(std::min({p0.x, p1.x, p2.x})))); const int maxX = std::min(surface.width - 1, static_cast<int>(std::ceil(std::max({p0.x, p1.x, p2.x})))); const int minY = std::max({0, gRenderBandTop, static_cast<int>(std::floor(std::min({p0.y, p1.y, p2.y})))}); const int maxY = std::min({surface.height - 1, gRenderBandBottom - 1, static_cast<int>(std::ceil(std::max({p0.y, p1.y, p2.y})))}); const float inverseArea = 1.0f / area; for (int y = minY; y <= maxY; ++y) { for (int x = minX; x <= maxX; ++x) { const float px = x + 0.5f; const float py = y + 0.5f; const float w0 = edge(p1.x, p1.y, p2.x, p2.y, px, py) * inverseArea; const float w1 = edge(p2.x, p2.y, p0.x, p0.y, px, py) * inverseArea; const float w2 = 1.0f - w0 - w1; if (w0 < 0.0f || w1 < 0.0f || w2 < 0.0f) { continue; } const float inverseDepth = w0 * p0.inverseDepth + w1 * p1.inverseDepth + w2 * p2.inverseDepth; if (inverseDepth <= 0.0f) { continue; } const float z = 1.0f / inverseDepth; const std::size_t index = static_cast<std::size_t>(y) * surface.width + x; if (z >= surface.depth[index]) { continue; } const Color shaded = fog ? applyFog(color, z) : color; if (alpha >= 0.999f) { surface.pixels[index] = packColor(shaded); } else { surface.blendPixel(x, y, shaded, alpha); } surface.depth[index] = z; } } } void rasterLine(Surface& surface, const Vec3& a, const Vec3& b, Color color) { const Projected p0 = project(surface, a); const Projected p1 = project(surface, b); if (!p0.valid || !p1.valid) { return; } const float dx = p1.x - p0.x; const float dy = p1.y - p0.y; const bool xMajor = std::abs(dx) >= std::abs(dy); const float lineWidth = std::clamp(surface.height / 480.0f, 1.35f, 2.0f); const float halfWidth = lineWidth * 0.5f; auto drawSample = [&](int majorPixel, float minor, float t) { const float inverseDepth = p0.inverseDepth + (p1.inverseDepth - p0.inverseDepth) * t; const float z = 0.997f / std::max(inverseDepth, 0.00001f); const Color shaded = applyFog(color, z); const int centerMinorPixel = static_cast<int>(std::floor(minor)); for (int offset = -1; offset <= 1; ++offset) { const int minorPixel = centerMinorPixel + offset; const float pixelCenter = minorPixel + 0.5f; const float coverage = std::clamp( halfWidth + 0.5f - std::abs(pixelCenter - minor), 0.0f, 1.0f); if (coverage <= 0.0f) { continue; } const int x = xMajor ? majorPixel : minorPixel; const int y = xMajor ? minorPixel : majorPixel; if (x < 0 || x >= surface.width || y < 0 || y >= surface.height || y < gRenderBandTop || y >= gRenderBandBottom) { continue; } const std::size_t index = static_cast<std::size_t>(y) * surface.width + x; if (z < surface.depth[index]) { if (coverage >= 0.999f) { surface.pixels[index] = packColor(shaded); } else { surface.blendPixel(x, y, shaded, coverage); } surface.depth[index] = z; } } }; if (xMajor) { const int first = std::max(0, static_cast<int>(std::floor(std::min(p0.x, p1.x)))); const int last = std::min(surface.width - 1, static_cast<int>(std::floor(std::max(p0.x, p1.x)))); for (int x = first; x <= last; ++x) { const float sampleX = x + 0.5f; const float t = std::clamp( std::abs(dx) > 0.00001f ? (sampleX - p0.x) / dx : 0.0f, 0.0f, 1.0f); drawSample(x, p0.y + dy * t, t); } } else { const int first = std::max({0, gRenderBandTop, static_cast<int>(std::floor(std::min(p0.y, p1.y)))}); const int last = std::min({surface.height - 1, gRenderBandBottom - 1, static_cast<int>(std::floor(std::max(p0.y, p1.y)))}); for (int y = first; y <= last; ++y) { const float sampleY = y + 0.5f; const float t = std::clamp( std::abs(dy) > 0.00001f ? (sampleY - p0.y) / dy : 0.0f, 0.0f, 1.0f); drawSample(y, p0.x + dx * t, t); } } } Vec3 curveCenter(float z) { const float distance = std::max(0.0f, z - 6.0f); return {0.0f, -(distance * distance) / 20.0f, z}; } // HUD text helpers wrapping EGE's native font API, so the HUD can render CJK // (宋体 under MSVC) as well as ASCII. The font height tracks the old 5x7 bitmap // font's row count to preserve the original HUD layout. int textFontHeight(int scale) { return std::max(7, 7 * scale); } void drawTextLine(int x, int y, const std::string& text, int scale, Color color, bool shadow = true) { setfont(textFontHeight(scale), 0, TEXT_FONT_NAME); setbkmode(TRANSPARENT); if (shadow) { setcolor(EGERGB(0, 0, 0)); outtextxy(x + scale, y + scale, text.c_str()); } setcolor(EGERGB(color.r, color.g, color.b)); outtextxy(x, y, text.c_str()); } int textLineWidth(const std::string& text, int scale) { setfont(textFontHeight(scale), 0, TEXT_FONT_NAME); return textwidth(text.c_str()); } class Random { public: explicit Random(std::uint32_t seed) : state(seed) { } std::uint32_t next() { state ^= state << 13; state ^= state >> 17; state ^= state << 5; return state; } int range(int limit) { return static_cast<int>(next() % static_cast<std::uint32_t>(limit)); } private: std::uint32_t state; }; struct Obstacle { float z; int track; Color color; float tangentSize; float radialSize; float depthSize; float speedScale; }; constexpr std::array<Color, 13> kObstacleColors {{ {255, 153, 204}, {153, 255, 204}, {153, 204, 255}, {191, 191, 191}, {128, 128, 128}, {64, 64, 64}, {255, 40, 40}, {40, 255, 80}, {255, 128, 20}, {255, 45, 45}, {40, 255, 90}, {255, 150, 20}, {30, 235, 255}, }}; float wrapAngle(float angle) { while (angle > kPi) angle -= 2.0f * kPi; while (angle < -kPi) angle += 2.0f * kPi; return angle; } class Game { public: explicit Game(bool collisionsEnabled = true) : random(0x58454745u), collisionsEnabled(collisionsEnabled) { reset(); } void reset() { obstacles.clear(); elapsed = 0.0f; score = 0.0f; forwardDistance = 0.0; rotation = 0.0f; angularVelocity = 0.0f; currentSpeed = kBaseSpeed; spawnDistance = 6.0 * kTileSize; invincible = 0.0f; lives = 3; stage = 0; level = 0; paused = false; gameOver = false; } void togglePause() { if (!gameOver) paused = !paused; } void update(float deltaTime, bool turnLeft, bool turnRight, float dragRotation = 0.0f) { if (paused || gameOver) { return; } elapsed += deltaTime; const int stageProgress = static_cast<int>(elapsed / kStageDuration); stage = stageProgress % kStageCount; level = stageProgress / kStageCount; currentSpeed = kBaseSpeed + kLevelSpeedStep * level; const float frameDistance = currentSpeed * deltaTime; forwardDistance += frameDistance; score += kReferenceFps * deltaTime; invincible = std::max(0.0f, invincible - deltaTime); const float steering = (turnRight ? 1.0f : 0.0f) - (turnLeft ? 1.0f : 0.0f); const float targetVelocity = steering * kKeyboardTurnSpeed; angularVelocity += (targetVelocity - angularVelocity) * std::min(1.0f, deltaTime * 18.0f); if (!turnLeft && !turnRight) { angularVelocity *= std::pow(0.12f, deltaTime); } rotation = wrapAngle(rotation + angularVelocity * deltaTime + dragRotation); for (Obstacle& obstacle : obstacles) { obstacle.z -= frameDistance * obstacle.speedScale; } checkCollisions(); obstacles.erase(std::remove_if(obstacles.begin(), obstacles.end(), [](const Obstacle& obstacle) { return obstacle.z < 0.22f; }), obstacles.end()); spawnDistance -= frameDistance; while (spawnDistance <= 0.0) { spawnPattern(); } } float speed() const { return currentSpeed; } double distance() const { return forwardDistance; } float rotationAngle() const { return rotation; } int currentStage() const { return stage; } int currentLevel() const { return level; } int livesRemaining() const { return lives; } bool isGameOver() const { return gameOver; } std::size_t obstacleCount() const { return obstacles.size(); } void render(Surface& surface) const { RenderExecutor& executor = renderExecutor(); const int threadCount = executor.threadCount(); executor.execute([&](int threadIndex) { const int top = surface.height * threadIndex / threadCount; const int bottom = surface.height * (threadIndex + 1) / threadCount; RenderBandScope band(top, bottom); renderBand(surface); }); } // Draws the HUD and overlay text with EGE's native fonts (so the HUD can // show CJK under MSVC). Called by the windowed main after the frame is // blitted; the text lands on the device backbuffer on top of the image. void drawHud(const Surface& surface, float framesPerSecond) const; void drawOverlay(const Surface& surface) const; private: void renderBand(Surface& surface) const { surface.clear({2, 4, 10}); drawTube(surface); for (const Obstacle& obstacle : obstacles) { drawObstacle(surface, obstacle); } if (invincible <= 0.0f || (static_cast<int>(invincible * 12.0f) & 1) == 0) { drawPlayer(surface); } drawHudBackground(surface); if (invincible > 0.8f) { surface.fillRect(0, 0, surface.width, surface.height, {255, 215, 30}, 0.16f); } if (paused || gameOver) { surface.fillRect(0, 0, surface.width, surface.height, {0, 0, 0}, 0.62f); } } static int hudScale(const Surface& surface) { const float resolutionScale = std::min( surface.width / 640.0f, surface.height / 480.0f); return std::clamp(static_cast<int>(resolutionScale + 0.5f), 1, 3); } void spawnOne(int track, int colorIndex, float tangentScale = 0.78f, float radialScale = 0.72f, float depthScale = 0.86f, float speedScale = 1.0f, float zOffset = 0.0f) { obstacles.push_back({ kFarPlane - 0.3f + zOffset, track % kTracks, kObstacleColors[colorIndex], kTileSize * tangentScale, kTileSize * radialScale, kTileSize * depthScale, speedScale, }); } void spawnPattern() { const int track = random.range(kTracks); switch (stage) { case 0: spawnOne(track, random.range(3)); break; case 1: spawnOne(track, 6, 0.76f, 0.72f, 0.82f, 1.28f); break; case 2: spawnOne(track, 3 + random.range(3), 0.82f, 1.18f, 0.92f); break; case 3: spawnOne(track, 8, 0.82f, 1.75f, 0.88f); break; case 4: spawnOne(track, random.range(3)); if (random.range(4) == 0) { spawnOne((track + 3 + random.range(4)) % kTracks, 11, 0.78f, 1.55f, 0.86f); } break; case 5: { const int count = 4 + 2 * random.range(3); for (int i = 0; i < count; ++i) { spawnOne((track + i) % kTracks, 12); } break; } case 6: spawnOne(track, random.range(3)); if (random.range(3) == 0) { spawnOne((track + 1) % kTracks, 12, 0.75f, 0.75f, 0.82f, 1.0f, 0.32f); spawnOne((track + 2) % kTracks, 12, 0.75f, 0.75f, 0.82f, 1.0f, 0.64f); } break; default: spawnOne(track, 9, 2.65f, 1.7f, 0.9f); spawnOne((track + 5 + random.range(3)) % kTracks, 7, 0.76f, 0.76f, 0.82f, 1.2f, 0.5f); break; } float spacingInTiles = 6.0f; switch (stage) { case 2: spacingInTiles = 8.0f + 2.0f * level; break; case 3: case 7: spacingInTiles = 10.0f; break; case 4: spacingInTiles = 6.0f + 2.0f * level; break; case 6: spacingInTiles = 6.0f + 3.0f * level; break; default: break; } spawnDistance += spacingInTiles * kTileSize; } void checkCollisions() { if (!collisionsEnabled || invincible > 0.0f) { return; } for (Obstacle& obstacle : obstacles) { if (obstacle.z < 0.72f || obstacle.z > 1.36f) { continue; } // The player sits at a fixed kPlayerAngle, so only the obstacle's // track offset and the current rotation determine the relative angle. // (kPlayerAngle previously added and subtracted here cancelled out.) const float relativeAngle = obstacle.track * kTrackAngle + rotation; const float angularExtent = (obstacle.tangentSize / (2.0f * 0.72f)) + 0.12f; if (std::abs(wrapAngle(relativeAngle)) < angularExtent) { obstacle.z = 0.15f; invincible = 1.25f; --lives; if (lives <= 0) { gameOver = true; } break; } } } Vec3 tubePoint(int trackEdge, float z) const { const float angle = kPlayerAngle - kTrackAngle * 0.5f + trackEdge * kTrackAngle + rotation; const Vec3 center = curveCenter(z); return { center.x + std::cos(angle) * kTubeRadius, center.y + std::sin(angle) * kTubeRadius, z, }; } void drawTube(Surface& surface) const { const bool brightStage = (stage % 2) == 0; const float brightness = brightStage ? 1.0f : 0.34f; const double tilePosition = forwardDistance / kTileSize; const long long passedTiles = static_cast<long long>(std::floor(tilePosition)); const float tubeOffset = static_cast<float>( forwardDistance - static_cast<double>(passedTiles) * kTileSize); const float firstRowZ = kTubeStart - tubeOffset; const float clippedNear = kNearPlane + 0.001f; // Start one row behind the near plane. That extra row replaces the one // that just passed the player and keeps the tunnel continuous when the // offset wraps at a tile boundary. for (int row = -1; row < kTubeRows; ++row) { const float rawZ0 = firstRowZ + row * kTileSize; const float rawZ1 = rawZ0 + kTileSize; if (rawZ1 <= clippedNear) { continue; } const float z0 = std::max(rawZ0, clippedNear); const float z1 = rawZ1; for (int track = 0; track < kTracks; ++track) { const Vec3 p00 = tubePoint(track, z0); const Vec3 p10 = tubePoint(track + 1, z0); const Vec3 p11 = tubePoint(track + 1, z1); const Vec3 p01 = tubePoint(track, z1); const bool alternate = ((track + row + passedTiles) & 1LL) != 0; const float checker = alternate ? 0.93f : 1.0f; const Color tile = scaleColor({224, 234, 244}, brightness * checker); rasterTriangle(surface, p00, p10, p11, tile); rasterTriangle(surface, p00, p11, p01, tile); } } const Color grid = brightStage ? Color {25, 42, 58} : Color {4, 8, 13}; for (int row = -1; row <= kTubeRows; ++row) { const float z = firstRowZ + row * kTileSize; if (z <= clippedNear) { continue; } for (int track = 0; track < kTracks; ++track) { rasterLine(surface, tubePoint(track, z), tubePoint(track + 1, z), grid); } } for (int row = -1; row < kTubeRows; ++row) { const float rawZ0 = firstRowZ + row * kTileSize; const float rawZ1 = rawZ0 + kTileSize; if (rawZ1 <= clippedNear) { continue; } const float z0 = std::max(rawZ0, clippedNear); const float z1 = rawZ1; for (int track = 0; track < kTracks; ++track) { rasterLine(surface, tubePoint(track, z0), tubePoint(track, z1), grid); } } } void drawBox(Surface& surface, Vec3 center, const Vec3& tangent, const Vec3& radial, float tangentSize, float radialSize, float depthSize, Color color, float alpha = 1.0f) const { const Vec3 t = tangent * (tangentSize * 0.5f); const Vec3 r = radial * (radialSize * 0.5f); const Vec3 d {0.0f, 0.0f, depthSize * 0.5f}; const std::array<Vec3, 8> vertices {{ center - t - r - d, center + t - r - d, center + t + r - d, center - t + r - d, center - t - r + d, center + t - r + d, center + t + r + d, center - t + r + d, }}; constexpr std::array<std::array<int, 4>, 6> faces {{ {{0, 1, 2, 3}}, {{5, 4, 7, 6}}, {{4, 0, 3, 7}}, {{1, 5, 6, 2}}, {{3, 2, 6, 7}}, {{4, 5, 1, 0}}, }}; const Vec3 light = normalize({-0.35f, 0.65f, -0.65f}); for (const auto& face : faces) { const Vec3 normal = normalize(cross( vertices[face[1]] - vertices[face[0]], vertices[face[2]] - vertices[face[0]])); const float lightAmount = 0.42f + 0.58f * std::abs(dot(normal, light)); const Color faceColor = scaleColor(color, lightAmount); rasterTriangle(surface, vertices[face[0]], vertices[face[1]], vertices[face[2]], faceColor, true, alpha); rasterTriangle(surface, vertices[face[0]], vertices[face[2]], vertices[face[3]], faceColor, true, alpha); } const Color edgeColor = scaleColor(color, 0.24f); constexpr std::array<std::array<int, 2>, 12> edges {{ {{0, 1}}, {{1, 2}}, {{2, 3}}, {{3, 0}}, {{4, 5}}, {{5, 6}}, {{6, 7}}, {{7, 4}}, {{0, 4}}, {{1, 5}}, {{2, 6}}, {{3, 7}}, }}; for (const auto& edge : edges) { rasterLine(surface, vertices[edge[0]], vertices[edge[1]], edgeColor); } } void drawObstacle(Surface& surface, const Obstacle& obstacle) const { const float angle = kPlayerAngle + obstacle.track * kTrackAngle + rotation; const Vec3 radial {std::cos(angle), std::sin(angle), 0.0f}; const Vec3 tangent {-std::sin(angle), std::cos(angle), 0.0f}; Vec3 center = curveCenter(obstacle.z); center = center + radial * 0.72f; drawBox(surface, center, tangent, radial, obstacle.tangentSize, obstacle.radialSize, obstacle.depthSize, obstacle.color); } void drawPlayer(Surface& surface) const { const Vec3 radial {0.0f, -1.0f, 0.0f}; const Vec3 tangent {1.0f, 0.0f, 0.0f}; const Vec3 center {0.0f, -0.80f, 0.72f}; drawBox(surface, center, tangent, radial, 0.20f, 0.20f, 0.20f, {255, 226, 35}, 0.94f); } void drawHudBackground(Surface& surface) const { const int uiScale = hudScale(surface); surface.fillRect(14 * uiScale, 14 * uiScale, 214 * uiScale, 62 * uiScale, {3, 8, 16}, 0.72f); surface.fillRect(14 * uiScale, 14 * uiScale, 214 * uiScale, 2 * uiScale, {70, 225, 255}, 0.88f); surface.fillRect(0, surface.height - 31 * uiScale, surface.width, 31 * uiScale, {2, 5, 11}, 0.72f); } Random random; std::vector<Obstacle> obstacles; double elapsed {0.0}; float score {0.0f}; double forwardDistance {0.0}; float rotation {0.0f}; float angularVelocity {0.0f}; float currentSpeed {kBaseSpeed}; double spawnDistance {0.0}; float invincible {0.0f}; int lives {3}; int stage {0}; int level {0}; bool paused {false}; bool gameOver {false}; bool collisionsEnabled {true}; }; void Game::drawHud(const Surface& surface, float framesPerSecond) const { const int uiScale = hudScale(surface); const int textScale = 2 * uiScale; drawTextLine(26 * uiScale, 24 * uiScale, TEXT_HUD_TITLE, textScale, {115, 235, 255}); drawTextLine(26 * uiScale, 48 * uiScale, std::string(TEXT_SCORE) + std::to_string(static_cast<int>(score)), textScale, {245, 248, 255}); const std::string status = std::string(TEXT_LIVES) + std::to_string(lives) + " " + TEXT_STAGE + std::to_string(stage + 1); const int statusWidth = textLineWidth(status, textScale); drawTextLine(surface.width - statusWidth - 18 * uiScale, 24 * uiScale, status, textScale, {255, 225, 70}); const std::string fps = std::string(TEXT_FPS) + std::to_string(std::max(0, static_cast<int>(framesPerSecond + 0.5f))); const int fpsWidth = textLineWidth(fps, textScale); drawTextLine(surface.width - fpsWidth - 18 * uiScale, 48 * uiScale, fps, textScale, {115, 235, 255}); const int controlsScale = uiScale; const int controlsWidth = textLineWidth(TEXT_CONTROLS, controlsScale); drawTextLine((surface.width - controlsWidth) / 2, surface.height - 22 * uiScale, TEXT_CONTROLS, controlsScale, {190, 220, 240}, false); } void Game::drawOverlay(const Surface& surface) const { if (!paused && !gameOver) { return; } const std::string message = gameOver ? TEXT_GAME_OVER : TEXT_PAUSED; const int uiScale = hudScale(surface); const int scale = 5 * uiScale; const int messageWidth = textLineWidth(message, scale); const int messageY = static_cast<int>(surface.height * 0.40f); drawTextLine((surface.width - messageWidth) / 2, messageY, message, scale, gameOver ? Color {255, 80, 70} : Color {255, 220, 70}); const std::string action = gameOver ? TEXT_ACTION_RESTART : TEXT_ACTION_RESUME; const int actionScale = 2 * uiScale; const int actionWidth = textLineWidth(action, actionScale); drawTextLine((surface.width - actionWidth) / 2, messageY + 52 * uiScale, action, actionScale, {220, 235, 255}); } bool parseResolution(const std::string& text, int& width, int& height) { const std::size_t separator = text.find_first_of("xX"); if (separator == std::string::npos) { return false; } const std::string widthText = text.substr(0, separator); const std::string heightText = text.substr(separator + 1); char* widthEnd = nullptr; char* heightEnd = nullptr; const long parsedWidth = std::strtol(widthText.c_str(), &widthEnd, 10); const long parsedHeight = std::strtol(heightText.c_str(), &heightEnd, 10); if (widthEnd == widthText.c_str() || *widthEnd != '\0' || heightEnd == heightText.c_str() || *heightEnd != '\0' || parsedWidth < 640 || parsedWidth > 3840 || parsedHeight < 480 || parsedHeight > 2160) { return false; } width = static_cast<int>(parsedWidth); height = static_cast<int>(parsedHeight); return true; } } // namespace cube_runner int main(int argc, char** argv) { using namespace ege; using namespace cube_runner; int width = kDefaultWidth; int height = kDefaultHeight; int exitAfterFrames = 0; for (int index = 1; index < argc; ++index) { const std::string argument = argv[index]; if (argument == "--resolution" && index + 1 < argc) { if (!parseResolution(argv[++index], width, height)) { std::cerr << "Invalid resolution. Expected WIDTHxHEIGHT between 640x480 and 3840x2160.\n"; return EXIT_FAILURE; } } else if (argument == "--exit-after" && index + 1 < argc) { exitAfterFrames = std::max(1, std::atoi(argv[++index])); } else if (argument == "--help") { std::cout << "Usage: game_cube_runner [--resolution WIDTHxHEIGHT]" " [--exit-after frames]\n"; return EXIT_SUCCESS; } else { std::cerr << "Unknown argument: " << argument << '\n'; return EXIT_FAILURE; } } initgraph(width, height, INIT_ANIMATION); setcaption(TEXT_WINDOW_TITLE); setrendermode(RENDER_MANUAL); auto closeWindow = [] { const HWND window = getHWnd(); SetCloseHandler(nullptr); if (::IsWindow(window)) { ::SendMessageW(window, WM_CLOSE, 0, 0); } }; PIMAGE frameImage = newimage(width, height); if (frameImage == nullptr) { std::cerr << "Failed to create the " << width << 'x' << height << " frame buffer.\n"; closeWindow(); return EXIT_FAILURE; } Surface surface(width, height, getbuffer(frameImage)); Game game; bool dragging = false; int lastMouseX = 0; int renderedFrames = 0; KeyPressLatch escapeKey; KeyPressLatch pauseKey; KeyPressLatch restartKey; const float dragSensitivity = kMouseDragSensitivity * 640.0f / width; while (is_run()) { if (escapeKey.update(keystate(key_esc), keypress(key_esc))) { break; } if (pauseKey.update(keystate(key_P), keypress(key_P))) { game.togglePause(); } if (restartKey.update(keystate(key_R), keypress(key_R))) { game.reset(); } float dragRotation = 0.0f; while (mousemsg()) { const mouse_msg message = getmouse(); if (message.is_down() && message.is_left()) { dragging = true; lastMouseX = message.x; } else if (message.is_up() && message.is_left()) { dragging = false; } else if (message.is_move() && dragging) { dragRotation += (message.x - lastMouseX) * dragSensitivity; lastMouseX = message.x; } } if (dragging && !keystate(key_mouse_l)) { dragging = false; } const bool turnLeft = keystate(key_left) || keystate(key_A); const bool turnRight = keystate(key_right) || keystate(key_D); const float framesPerSecond = getfps(); game.update(1.0f / 60.0f, turnLeft, turnRight, dragRotation); // render() writes directly into frameImage's buffer (Surface borrows it), // so there is no per-frame copy before the blit. game.render(surface); putimage(0, 0, frameImage); game.drawHud(surface, framesPerSecond); game.drawOverlay(surface); ++renderedFrames; if (exitAfterFrames > 0 && renderedFrames >= exitAfterFrames) { break; } delay_fps(60); } delimage(frameImage); closeWindow(); return 0; } |
近期评论