Initial RPS CUDA implementation

This commit is contained in:
Skeleton bootstrap 2026-11-26 09:07:21 +03:00
commit 8d583036d0
33 changed files with 2968 additions and 0 deletions

228
macos/client.mm Normal file
View file

@ -0,0 +1,228 @@
#include "socks.hpp"
#import <AppKit/AppKit.h>
#import <MetalKit/MetalKit.h>
#include <chrono>
#include <csignal>
#include <iostream>
#include <map>
#include "renderer.hpp"
@interface Screen : NSObject <MTKViewDelegate, NSWindowDelegate>
@property NSWindow *window;
@property MTKView *view;
@property id<MTLCommandQueue> queue;
@property id<MTLRenderPipelineState> pipeline;
@property id<MTLTexture> texture;
@property id<MTLCommandBuffer> lastDraw;
- (BOOL)setup;
- (id<MTLCommandBuffer>)present;
@end
@implementation Screen
- (BOOL)setup {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
if (!device)
return NO;
self.queue = [device newCommandQueue];
self.pipeline = buildPipeline(device);
if (!self.pipeline)
return NO;
NSRect rect = NSMakeRect(0, 0, 800, 600);
self.window = [[NSWindow alloc]
initWithContentRect:rect
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskResizable |
NSWindowStyleMaskMiniaturizable
backing:NSBackingStoreBuffered
defer:NO];
self.view = [[MTKView alloc] initWithFrame:rect device:device];
self.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
self.view.clearColor = MTLClearColorMake(0, 0, 0, 1);
self.view.paused = YES;
self.view.enableSetNeedsDisplay = YES;
self.view.delegate = self;
self.window.delegate = self;
self.window.contentView = self.view;
self.window.title = @"RPS · Подключение";
[self.window center];
[self.window makeKeyAndOrderFront:nil];
return YES;
}
- (void)windowWillClose:(NSNotification *)note {
[NSApp terminate:nil];
}
- (void)mtkView:(MTKView *)view drawableSizeWillChange:(CGSize)size {
[view setNeedsDisplay:YES];
}
- (void)drawInMTKView:(MTKView *)view {
self.lastDraw = [self present];
}
- (id<MTLCommandBuffer>)present {
if (!self.texture)
return nil;
auto pass = self.view.currentRenderPassDescriptor;
auto drawable = self.view.currentDrawable;
if (!pass || !drawable)
return nil;
auto cmd = [self.queue commandBuffer];
if (!encodeImage(cmd, pass, self.texture, self.pipeline))
return nil;
[cmd presentDrawable:drawable];
[cmd commit];
return cmd;
}
@end
static void status(Screen *screen, NSString *title) {
dispatch_async(dispatch_get_main_queue(), ^{
screen.window.title = title;
});
}
static void observe(Screen *screen, std::string raw, Config c, std::string ca,
int proxy, int port, const std::string &remoteHost,
const std::string &tlsName) {
auto ctx = context(true);
SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
sslok(SSL_CTX_load_verify_locations(ctx.get(), ca.c_str(), nullptr),
"CA certificate");
FD sock(socket(AF_INET, SOCK_STREAM, 0));
socks(sock.fd, proxy, port, remoteHost);
auto tls = session(ctx.get(), sock.fd);
sslok(SSL_set_tlsext_host_name(tls.get(), tlsName.c_str()), "TLS SNI");
sslok(SSL_set1_host(tls.get(), tlsName.c_str()), "TLS name");
sslok(SSL_connect(tls.get()), "TLS handshake");
Bytes config(raw.begin(), raw.end());
sendMsg(tls.get(), CONFIG, config);
require(receive(tls.get(), {ACCEPTED, ERROR_MSG}).second == config,
"config echo mismatch");
u64 frameId = 0, prev = 0;
__block u64 uploadNs = 0;
auto start = std::chrono::steady_clock::now();
do {
@autoreleasepool {
auto data = receive(tls.get(), {FRAME, ERROR_MSG}).second;
auto b = data.data();
u64 gen = get(b + 8, 8);
require(data.size() == 32 + c.bytes() && get(b, 8) == frameId + 1 &&
(frameId ? gen > prev : gen == 0) && gen <= c.g &&
get(b + 16, 4) == c.aw() && get(b + 20, 4) == c.ah() &&
get(b + 24, 4) == c.k && get(b + 28, 4) == 1,
"invalid FRAME");
__block id<MTLCommandBuffer> cmd = nil;
dispatch_sync(dispatch_get_main_queue(), ^{
auto texDesc = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:c.aw()
height:c.ah()
mipmapped:NO];
texDesc.storageMode = MTLStorageModeShared;
auto tex = [screen.view.device newTextureWithDescriptor:texDesc];
const auto uploadStart = std::chrono::steady_clock::now();
[tex replaceRegion:MTLRegionMake2D(0, 0, c.aw(), c.ah())
mipmapLevel:0
withBytes:b + 32
bytesPerRow:4 * c.aw()];
uploadNs += std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - uploadStart)
.count();
screen.texture = tex;
screen.lastDraw = nil;
[screen.view draw];
cmd = screen.lastDraw;
});
require(cmd != nil, "Metal drawable or texture unavailable");
[cmd waitUntilCompleted];
if (cmd.status != MTLCommandBufferStatusCompleted)
throw std::runtime_error(cmd.error.localizedDescription.UTF8String
?: "Metal presentation failed");
Bytes ack;
put(ack, ++frameId, 8);
sendMsg(tls.get(), ACK, ack);
prev = gen;
status(screen, [NSString stringWithFormat:@"RPS · Поколение %llu / %u",
(unsigned long long)gen, c.g]);
}
} while (prev < c.g);
auto done = receive(tls.get(), {FINISHED, ERROR_MSG}).second;
require(get(done.data(), 8) == c.g && get(done.data() + 8, 4) == 0,
"invalid FINISHED");
auto durationNs = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - start)
.count();
std::cerr << "metal_upload_ns=" << uploadNs << " milli_fps="
<< uint64_t(__uint128_t(frameId) * 1000000000000ULL / durationNs)
<< " finished frames=" << frameId << " generation=" << prev
<< " elapsed_ms="
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start)
.count()
<< "\n";
status(screen,
[NSString stringWithFormat:@"RPS · Завершено · Поколение %u", c.g]);
SSL_shutdown(tls.get());
}
int main(int argc, char **argv) {
@autoreleasepool {
try {
signal(SIGPIPE, SIG_IGN);
std::map<std::string, std::string> opts;
require(argc % 2 == 1, "expected option value");
for (int i = 1; i < argc; i += 2)
opts[argv[i]] = argv[i + 1];
auto port = [&](const char *key, int fallback) {
int n = opts.count(key) ? std::stoi(opts.at(key)) : fallback;
require(n > 0 && n <= 65535, "port range");
return n;
};
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp activateIgnoringOtherApps:YES];
if (!opts.count("--config")) {
auto panel = [NSOpenPanel openPanel];
panel.message = @"Выберите JSON конфигурации симуляции";
if ([panel runModal] != NSModalResponseOK)
return 0;
opts["--config"] = panel.URL.fileSystemRepresentation;
}
const bool sharedProxy = opts.count("--host") != 0;
if (!opts.count("--ca")) {
NSString *path = sharedProxy ? @"~/.config/skeleton/pki/root-ca.crt"
: @"~/Library/Application Support/rps-cuda/server.crt";
path = [path stringByExpandingTildeInPath];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
auto panel = [NSOpenPanel openPanel];
panel.message = @"Выберите доверенный сертификат CA";
if ([panel runModal] != NSModalResponseOK)
return 0;
path = panel.URL.path;
}
opts["--ca"] = path.fileSystemRepresentation;
}
auto raw = readConfig(opts.at("--config"));
auto c = parse(raw);
auto ca = opts.at("--ca");
int proxy = port("--socks-port", sharedProxy ? 11082 : 11080), remote = port("--port", 7443);
const std::string remoteHost = sharedProxy ? opts.at("--host") : "127.0.0.1";
const std::string tlsName = sharedProxy ? remoteHost : "infra-gpu";
Screen *screen = [Screen new];
require([screen setup], "cannot initialize Metal");
[NSApp activateIgnoringOtherApps:YES];
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
@autoreleasepool {
try {
observe(screen, raw, c, ca, proxy, remote, remoteHost, tlsName);
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
status(screen,
[NSString stringWithFormat:@"RPS · Ошибка · %s", e.what()]);
}
}
});
[NSApp run];
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
return 1;
}
}
}

56
macos/renderer.hpp Normal file
View file

@ -0,0 +1,56 @@
#pragma once
#import <Metal/Metal.h>
#include <algorithm>
static NSString *shader = @R"metal(
#include <metal_stdlib>
using namespace metal;
struct Out { float4 position [[position]]; float2 uv; };
vertex Out vertexMain(uint i [[vertex_id]]) {
const float2 uv[]={{0,0},{0,1},{1,0},{1,1}};
return {float4(uv[i].x*2-1,1-uv[i].y*2,0,1),uv[i]};
}
fragment float4 pixelMain(Out v [[stage_in]],texture2d<float> image [[texture(0)]]) {
constexpr sampler sampleNearest(coord::normalized,filter::nearest,address::clamp_to_edge);
return image.sample(sampleNearest,v.uv);
}
)metal";
inline id<MTLRenderPipelineState> buildPipeline(id<MTLDevice> device){
NSError *error = nil;
id<MTLLibrary> lib = [device newLibraryWithSource:shader
options:nil
error:&error];
if (!lib) {
NSLog(@"%@", error);
return nil;
}
auto desc = [MTLRenderPipelineDescriptor new];
desc.vertexFunction = [lib newFunctionWithName:@"vertexMain"];
desc.fragmentFunction = [lib newFunctionWithName:@"pixelMain"];
desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
auto pipeline = [device newRenderPipelineStateWithDescriptor:desc
error:&error];
if (!pipeline) {
NSLog(@"%@", error);
return nil;
}
return pipeline;
}
inline bool encodeImage(id<MTLCommandBuffer> cmd, MTLRenderPassDescriptor* pass, id<MTLTexture> texture,id<MTLRenderPipelineState> pipeline){
auto target=pass.colorAttachments[0].texture;
auto enc = [cmd renderCommandEncoderWithDescriptor:pass];
if (!enc)
return false;
double w = target.width, h = target.height;
double scale = std::min(w / texture.width, h / texture.height);
double sw = texture.width * scale, sh = texture.height * scale;
[enc setViewport:MTLViewport{(w - sw) / 2, (h - sh) / 2, sw, sh, 0, 1}];
[enc setRenderPipelineState:pipeline];
[enc setFragmentTexture:texture atIndex:0];
[enc drawPrimitives:MTLPrimitiveTypeTriangleStrip
vertexStart:0
vertexCount:4];
[enc endEncoding];
return true;
}