#pragma once #import #include static NSString *shader = @R"metal( #include 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 image [[texture(0)]]) { constexpr sampler sampleNearest(coord::normalized,filter::nearest,address::clamp_to_edge); return image.sample(sampleNearest,v.uv); } )metal"; inline id buildPipeline(id device){ NSError *error = nil; id 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 cmd, MTLRenderPassDescriptor* pass, id texture,id 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; }