Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func toImage() -> NSImage? {
- let texture = self
- let width = texture.width
- let height = texture.height
- let bytesPerRow = width * 4
- let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
- defer {
- data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
- }
- let region = MTLRegionMake2D(0, 0, width, height)
- texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
- var buffer = vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: bytesPerRow)
- let map: [UInt8] = [2, 1, 0, 3]
- vImagePermuteChannels_ARGB8888(&buffer, &buffer, map, 0)
- guard let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear) else { return nil }
- guard let context = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow,
- space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }
- guard let cgImage = context.makeImage() else { return nil }
- return NSImage(cgImage: cgImage, size: NSSize(width: width, height: height))
- }
- extension MTLTexture {
- func toImage() -> CGImage? {
- let context = CIContext()
- let texture = self
- let cImg = CIImage(mtlTexture: texture, options: nil)!
- let cgImg = context.createCGImage(cImg, from: cImg.extent)!
- return cgImg
- }
- }
- func anythingHere(_ texture: MTLTexture) -> Bool {
- let width = texture.width
- let height = texture.height
- let bytesPerRow = width * 4
- let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
- defer {
- data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
- }
- let region = MTLRegionMake2D(0, 0, width, height)
- texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
- var bind = data.assumingMemoryBound(to: UInt8.self)
- var sum:UInt8 = 0;
- for i in 0..<width*height {
- sum += bind.pointee
- bind = bind.advanced(by: 1)
- }
- return sum != 0
- }
Add Comment
Please, Sign In to add comment