canvas.h, render.py, example.cpp
说明
写 Cryscent 原型时为了方便地用 cpp 绘制图形做的一样东西。无需链接库之类,因为实际上 cpp 只是做了一件事,即对文件进行读写,实际上的绘图由 python 进行。
注意这个东西只是用来进行简单的绘图,目标也只是方便地看到 cpp 程序里面的数据,而不是创造什么特别精美的东西。
代码
// canvas.h
// Author: colGem , License: MIT
#pragma once
#include <fstream>
#include <string>
#include <vector>
struct Coord { int x; int y; };
struct Color { int r; int g; int b; };
namespace Canvas {
bool checkLock() {
std::ifstream lock("canvas_lock.txt");
return lock.get() != '0';
}
void writeInstruction(const std::string& cmd) {
if (checkLock()) return;
std::ofstream out("canvas_instruction.txt", std::ios::app);
if (out) {
out << cmd << "\n";
out.close();
}
}
void refreshCanvas() {
if (checkLock()) return;
writeInstruction("REFRESH");
std::ofstream lock("canvas_lock.txt");
if (lock) {
lock << '1';
lock.close();
}
}
void drawRect(Coord p1, Coord p2, Color c) {
writeInstruction("RECT " +
std::to_string(p1.x) + "," + std::to_string(p1.y) + " " +
std::to_string(p2.x) + "," + std::to_string(p2.y) + " " +
std::to_string(c.r) + "," + std::to_string(c.g) + "," + std::to_string(c.b));
}
void drawLine(Coord p1, Coord p2, Color c) {
writeInstruction("LINE " +
std::to_string(p1.x) + "," + std::to_string(p1.y) + " " +
std::to_string(p2.x) + "," + std::to_string(p2.y) + " " +
std::to_string(c.r) + "," + std::to_string(c.g) + "," + std::to_string(c.b));
}
void drawPixel(Coord p, Color c) {
writeInstruction("PIXEL " +
std::to_string(p.x) + "," + std::to_string(p.y) + " " +
std::to_string(c.r) + "," + std::to_string(c.g) + "," + std::to_string(c.b));
}
void drawText(Coord p, Color c, const std::string& text) {
writeInstruction("TEXT " +
std::to_string(p.x) + "," + std::to_string(p.y) + " " +
std::to_string(c.r) + "," + std::to_string(c.g) + "," + std::to_string(c.b) + " " +
text);
}
void drawPolyline(const std::vector<Coord>& points, Color c) {
std::string cmd = "POLYLINE";
for (const auto& p : points) {
cmd += " " + std::to_string(p.x) + "," + std::to_string(p.y);
}
cmd += " " + std::to_string(c.r) + "," + std::to_string(c.g) + "," + std::to_string(c.b);
writeInstruction(cmd);
}
}
# render.py
# Author: colGem , License: MIT
import pygame
import os
import traceback
from pygame.locals import *
WINDOW_SIZE = (800, 600)
DEBUG_GRID = True # 绘制网格
def parse_color(s):
return tuple(map(int, s.split(',')))
def draw_debug_grid(surface):
w, h = surface.get_size()
color = (50, 50, 50)
for x in range(0, w, 50):
pygame.draw.line(surface, color, (x, 0), (x, h))
for y in range(0, h, 50):
pygame.draw.line(surface, color, (0, y), (w, y))
pygame.draw.circle(surface, (255, 0, 0), (0, 0), 5)
font = pygame.font.Font(None, 24)
text = font.render("(0,0)", True, (255,255,255))
surface.blit(text, (10,5))
def main():
pygame.init()
screen = pygame.display.set_mode(WINDOW_SIZE, RESIZABLE)
pygame.display.set_caption("colgem Renderer")
clock = pygame.time.Clock()
current_commands = []
font = pygame.font.Font(None, 24)
lock_file = "canvas_lock.txt"
cmd_file = "canvas_instruction.txt"
for f in [lock_file, cmd_file]:
if not os.path.exists(f):
with open(f, "w") as _f: pass
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
return
# canvas_lock
try:
with open(lock_file, "r") as f:
if f.read().strip() == '1':
with open(lock_file, "w") as f_lock:
f_lock.write('2') # processing
new_commands = []
with open(cmd_file, "r") as cf:
for line in cf:
line = line.strip()
if line == "REFRESH":
break
new_commands.append(line)
current_commands = new_commands
open(cmd_file, "w").close()
with open(lock_file, "w") as f_lock:
f_lock.write('0') # 解锁
except Exception as e:
continue
# surface
offscreen = pygame.Surface(screen.get_size())
offscreen.fill((0, 0, 0))
if DEBUG_GRID:
draw_debug_grid(offscreen)
for cmd in current_commands:
parts = cmd.split()
if not parts:
continue
try:
cmd_type = parts[0]
if cmd_type == "RECT":
p1 = tuple(map(int, parts[1].split(',')))
p2 = tuple(map(int, parts[2].split(',')))
color = parse_color(parts[3])
x = min(p1[0], p2[0])
y = min(p1[1], p2[1])
w = abs(p1[0] - p2[0])
h = abs(p1[1] - p2[1])
pygame.draw.rect(offscreen, color, (x, y, w, h), 2)
elif cmd_type == "LINE":
p1 = tuple(map(int, parts[1].split(',')))
p2 = tuple(map(int, parts[2].split(',')))
color = parse_color(parts[3])
pygame.draw.line(offscreen, color, p1, p2, 2)
elif cmd_type == "PIXEL":
p = tuple(map(int, parts[1].split(',')))
color = parse_color(parts[2])
offscreen.set_at(p, color)
elif cmd_type == "TEXT":
p = tuple(map(int, parts[1].split(',')))
color = parse_color(parts[2])
text = ' '.join(parts[3:])
img = font.render(text, True, color)
offscreen.blit(img, p)
elif cmd_type == "POLYLINE":
points = [tuple(map(int, p.split(','))) for p in parts[1:-1]]
color = parse_color(parts[-1])
if len(points) >= 2:
pygame.draw.lines(offscreen, color, False, points, 2)
except:
pass
screen.blit(offscreen, (0, 0))
pygame.display.flip()
clock.tick(60) # 此处是设置 fps = 60
if __name__ == "__main__":
main()
编写时使用的是 Python 3.11 (64-bit) 和 Dev-cpp (c++11 标准)。要安装必要的库,可以使用 python -m pip install pygame -i https://pypi.mirrors.ustc.edu.cn/simple/ ,这个是中科大镜像。
使用
// example.cpp
#include "canvas.h"
#include <thread>
#include <Windows.h>
int main()
{
using namespace Canvas;
std::ofstream("canvas_lock.txt") << '0';
std::ofstream("canvas_instruction.txt").close();
while(1)
{
std::ofstream clear("canvas_instruction.txt", std::ios::trunc);
clear.close();
drawRect({100,100}, {200,200}, {255,0,0});
drawLine({300,300}, {400,400}, {0,255,0});
drawPixel({500,500}, {0,0,255});
drawText({150,150}, {255,255,0}, "Hello World");
drawPolyline({{50,50}, {100,150}, {200,80}}, {255,255,255});
refreshCanvas();
Sleep(100); // Windows.h
}
return 0;
}
文件结构:
.
├─canvas.h
├─example.cpp
├─example.exe
└─render.py
如果文件放的正确,用 Dev-cpp 就能直接编译运行 example.cpp 。
对于这个 example.cpp 编译的 example.exe ,当你同时运行 example.exe 和 render.py ,render.py 就能绘制出画面。总而言之,一般情况下二者同时运行就能产生正确效果,但是如果你同一个目录下有两个程序在同时尝试绘图,这个 render.py 就会同时接到两个程序的信息,会导致问题,所以如果有问题但是又找不到什么作祟的命令行窗口可以去任务管理器细看一下有没有什么可疑的进程。
逻辑上,当你完成一系列 draw 的调用,它会把要绘制的信息作为指令存储在文件里而不绘制。你可以在调用绘制函数后进行一次 canvasRefresh(); ,此时 render.py 会清空窗口上的画面并绘制缓存的指令,然后清空缓存。所以说如果想要一帧中有多次绘制,那么就需要最后再 canvasRefresh(); 。
具体逻辑可以细看 canvas.h ,因为 cpp 侧写的也不复杂。里面的函数怎么调用也可以去看。
如果你发现就是无法正常运行,那一定要写上
std::ofstream("canvas_lock.txt") << '0';
std::ofstream("canvas_instruction.txt").close();
std::ofstream clear("canvas_instruction.txt", std::ios::trunc);
clear.close();
或者在你的目录下执行一遍
echo 0 > canvas_lock.txt
type nul > canvas_instruction.txt
或者自己把这两个文件归位到正常状态。
下面的内容默认这两个文件是正常的。如果不能正常运行就尝试让这两个文件回归正常状态。所以为了保险,启动程序的顺序应该是 example.exe -> render.py ,关闭的顺序应该是 example.exe -> render.py 。
使用场景
比如计算几何的题,你可以把点画进去看看样例长什么样。
总而言之这个东西对我来说的用途就是让抽象的数字能被直观看到,特别是看它的连续变化是如何进行的。
使用例
接下来只保留 main() ,在 main() 上面的部分写成这样:
#include <bits/stdc++.h>
#include <Windows.h>
#include "canvas.h"
using namespace Canvas;
using namespace std;
输入 n 个点的坐标按顺序连线
int main()
{
int n;
vector<Coord> pointlist;
scanf("%d", &n);
for(int i=1;i<=n;i++)
{
int x, y;
scanf("%d%d", &x, &y);
pointlist.push_back({x, y});
drawRect({x-5, y-5}, {x+5, y+5}, {255, 0, 255}); // 画点
drawText({x, y-15}, {0, 255, 255}, to_string(i)); // 画点序号
}
int r, g, b;
scanf("%d%d%d", &r, &g, &b);
drawPolyline(pointlist, {r, g, b});
refreshCanvas();
return 0;
}
绘制圆(动画)
这里会绘制一个紫色的小圆在蓝色的大圆左边按
const double pi = 3.14159265358979323846;
void drawCircle(Coord center, double radius, Color color, int n = 24)
{
n = std::max(3, std::min(8192, n));
std::vector<Coord> points;
for (int i=0;i<=n;++i)
{
double angle = 2.0 * pi * i / n;
int x = center.x + static_cast<int>(radius * cos(angle));
int y = center.y + static_cast<int>(radius * sin(angle));
points.push_back({x, y});
}
drawPolyline(points, color);
}
int main()
{
auto p_start = std::chrono::high_resolution_clock::now();
double fps = 60.0; // 可能需要略高一点. 若闪烁严重可降低
while(1)
{
auto now = std::chrono::high_resolution_clock::now();
double elapsed = std::chrono::duration<double>(now - p_start).count();
double y = 300 + (int)(150.0 * sin(elapsed*0.4));
printf("\rtime: %.2f\ty: %.2f", elapsed, y);
drawCircle({200, (int)y}, 88.8, {255, 0, 255}); // 24边形
drawCircle({400, 300}, 256, {0, 255, 255}, 48);
refreshCanvas();
Sleep((int)(1000.0 / fps));
}
return 0;
}
最后
如果有需要我可能会追加点内容。不过我打算现就放在这里。对于 绘制圆(动画) 部分,实测中目测可以达到