Guest User

Untitled

a guest
Mar 20th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. func toImage() -> NSImage? {
  2. let texture = self
  3. let width = texture.width
  4. let height = texture.height
  5. let bytesPerRow = width * 4
  6.  
  7. let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
  8. defer {
  9. data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
  10. }
  11.  
  12. let region = MTLRegionMake2D(0, 0, width, height)
  13. texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
  14. var buffer = vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: bytesPerRow)
  15.  
  16. let map: [UInt8] = [2, 1, 0, 3]
  17. vImagePermuteChannels_ARGB8888(&buffer, &buffer, map, 0)
  18.  
  19. guard let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear) else { return nil }
  20. guard let context = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow,
  21. space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }
  22. guard let cgImage = context.makeImage() else { return nil }
  23.  
  24.  
  25. return NSImage(cgImage: cgImage, size: NSSize(width: width, height: height))
  26. }
  27.  
  28. extension MTLTexture {
  29. func toImage() -> CGImage? {
  30. let context = CIContext()
  31. let texture = self
  32. let cImg = CIImage(mtlTexture: texture, options: nil)!
  33. let cgImg = context.createCGImage(cImg, from: cImg.extent)!
  34. return cgImg
  35. }
  36. }
  37.  
  38. func anythingHere(_ texture: MTLTexture) -> Bool {
  39. let width = texture.width
  40. let height = texture.height
  41. let bytesPerRow = width * 4
  42.  
  43. let data = UnsafeMutableRawPointer.allocate(bytes: bytesPerRow * height, alignedTo: 4)
  44. defer {
  45. data.deallocate(bytes: bytesPerRow * height, alignedTo: 4)
  46. }
  47.  
  48. let region = MTLRegionMake2D(0, 0, width, height)
  49. texture.getBytes(data, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
  50. var bind = data.assumingMemoryBound(to: UInt8.self)
  51.  
  52. var sum:UInt8 = 0;
  53. for i in 0..<width*height {
  54. sum += bind.pointee
  55. bind = bind.advanced(by: 1)
  56. }
  57. return sum != 0
  58. }
Add Comment
Please, Sign In to add comment