Metal入门资料009-用playground开发
写在前面:
对Metal技术感兴趣的同学,可以关注我的专题:Metal专辑
也可以关注我个人的简书账号:张芳涛
所有的代码存储的Github地址是:Metal
正文
接下来,我们会用playground进行项目开发(其实,不同平台下面的代码我一样会提供的)。
我们首先为OS X创立一个新的Xcode playground。一旦创立完成,点击Show the Assistant editor按钮,并按下Command + 1以显示项目导航器。 你的playground应该是这样的:

我们要做的第一件事就是在项目导航器中的Resources(资源)文件夹下创立Shaders.metal,并用与本系列前一集相同的源代码。 接下来,我们在Sources文件夹下创立MathUtils.swift和MetalView.swift。 我们在MathUtils.swift中做的唯一改变是我们为Vertex结构创立了一个方便的初始化程序:
struct Vertex {var position: vector_float4var color: vector_float4init(pos: vector_float4, col: vector_float4) { position = pos color = col }}在MetalView.swift中,我们需要做出更多更改。 首先,我们需要公开课程,由于我们将从Sources文件夹以外调使用它。 因而,初始化器和drawRect(:)方法也需要公开。 此外,我们将创立第二个初始化程序,以便我们可以创立具备给定frame(帧)的MetalView:
public class MetalView: MTKView {... required public init(coder: NSCoder) { super.init(coder: coder)}override public init(frame frameRect: CGRect, device: MTLDevice?) { super.init(frame: frameRect, device: device) createBuffers() registerShaders() }... }接下来,我们需要做一个相当奇怪的改变,由于正如你注意到的那样,创立一个库:
let library = device.newDefaultLibrary()!失败的时候显示以下错误消息:
MTLLibrary.mm:1016: failed assertion `filepath must not be nil.'因为playground没有我们可以用的默认filepath(文件路径),我们需要创立自己的文件路径:
func registerShaders() {let path = NSBundle.mainBundle().pathForResource("Shaders", ofType: "metal")let input: String?let library: MTLLibrarylet vert_func: MTLFunctionlet frag_func: MTLFunctiondo { input = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) library = try device!.newLibraryWithSource(input!, options: nil) vert_func = library.newFunctionWithName("vertex_func")! frag_func = library.newFunctionWithName("fragment_func")! let rpld = MTLRenderPipelineDescriptor() rpld.vertexFunction = vert_func rpld.fragmentFunction = frag_func rpld.colorAttachments[0].pixelFormat = .BGRA8Unorm rps = try device!.newRenderPipelineStateWithDescriptor(rpld)} catch let e { Swift.print("\(e)") }}注意,我们告诉playground找到一个名为Shader.metal的资源存在的路径。 接下来,我们将该文件转换为一个大的String,而后我们从这个源创立库。
最后,我们去playground的主页面,并创立一个新的MetalView与给定的框架。 而后我们告诉playground向我们展现实时视图:
import Cocoaimport XCPlaygroundlet device = MTLCreateSystemDefaultDevice()!let frame = NSRect(x: 0, y: 0, width: 300, height: 300)let view = MetalView(frame: frame, device: device)XCPlaygroundPage.currentPage.liveView = view假如您在Assistant editor中显示Timeline,则应该有类似的视图:

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Metal入门资料009-用playground开发