<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[The Arcane Programmer - Medium]]></title>
        <description><![CDATA[Coding and it’s discussions focused in unusual stuff that I see. - Medium]]></description>
        <link>https://medium.com/thearcaneprogrammer?source=rss----8fdf9e726385---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Arcane Programmer - Medium</title>
            <link>https://medium.com/thearcaneprogrammer?source=rss----8fdf9e726385---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:44:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/thearcaneprogrammer" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom Navigation Transitions with Metal]]></title>
            <link>https://medium.com/thearcaneprogrammer/custom-navigation-transitions-with-metal-d0962d8f912c?source=rss----8fdf9e726385---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0962d8f912c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ricardo Rachaus]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 21:24:36 GMT</pubDate>
            <atom:updated>2022-12-12T21:24:36.048Z</atom:updated>
            <content:encoded><![CDATA[<p>As someone who likes graphics programming and has been studying Metal, I see that a lot of times people don’t find a reason to learn or where to apply the Metal API in their apps. Usually this comes from a lack of knowledge of what the tool can provide, but also with the lack of information available online to learn (usually only Apple docs). So here, we will learn how to use Metal in an app by creating custom Navigation Transitions.</p><p>Just to refresh what Metal is:</p><blockquote><em>Metal is a low-level API for GPGPU (General Purpose Graphics Processing Unit) programming.</em></blockquote><p>But what does this mean? In a simplified manner, it means that we can create programs to use the GPU of our device, usually for graphical applications, but also for computations in general (AI for instance).</p><p>The main advantage of the GPU is the parallel processing. Different from the CPU, the GPU is made for processing data in a very fast manner, or how do you think that your screen can refresh at 60 (or more) frames per second with so many pixels? But if so, why don’t we use only the GPU? The reason is that the GPU is great for parallel computations, which means that all the math being done is independent and can be worked at the same time, different from a database usage for instance, where we want to follow some order and have control over the process of the data and for that, the CPU is better fitted.</p><p>But anyway, let’s start to talk about the project that we will do and start to see some code.</p><p>So, the idea of this post is to teach how to create custom UINavigationController transitions. We will create a custom animation when we do a push to show a new UIViewController, which is something that anyone that has used an iOS device is very familiar with. Even so you probably now, let’s refresh how the push animation looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*76Ng31NoE-brlWnaAppLiA.gif" /></figure><p>Nothing new, right?</p><p>For most applications and in most use cases, this animation is perfectly fine and there is no need for creating something new or different. But sometimes we want to create something more striking to tell the user what is happening. Perhaps your app is highly customized and doesn’t necessarily follow too much the Apple standard for UI. Or the designer can have some custom transition for a specific part of the app and you can’t do it with what UIKit provides.</p><p>From now on, we will do this transition, but in an app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*YEB0ujhXu6DJMeei7QN-4g.gif" /><figcaption><a href="https://doom.fandom.com/wiki/Screen_melt">https://doom.fandom.com/wiki/Screen_melt</a></figcaption></figure><p>That ‘s cool! Very unexpected and stylish. For those who never played Doom, this is known as the Doom’s <strong>Screen Melt</strong>. We will do this transition just because it looks exciting and different, but Metal has almost no limit for what you can do (yeah, you could do a 3D transition if you wanted it).</p><h4>UINavigationControllerDelegate</h4><p>First, we will implement the <a href="https://developer.apple.com/documentation/uikit/uinavigationcontrollerdelegate"><strong>UINavigationControllerDelegate</strong></a>:</p><pre>extension FirstViewController: UINavigationControllerDelegate {<br><br>    func navigationController(<br>        _ navigationController: UINavigationController,<br>        animationControllerFor operation: UINavigationController.Operation,<br>        from fromVC: UIViewController,<br>        to toVC: UIViewController<br>    ) -&gt; UIViewControllerAnimatedTransitioning? {<br>        return DoomTransition()<br>    }<br><br>}</pre><p>This is nothing different than the usual delegates from UIKit. Here is where we will return the object that will implement the transition, which needs to be a <a href="https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning"><strong>UIViewControllerAnimatedTransitioning</strong></a>. Now, let’s take a deeper look in the <strong>DoomTransition</strong> class.</p><h3>DoomTransition</h3><p>The <strong>DoomTransition</strong> class is where we will configure and create the code to execute the transition.</p><pre>class DoomTransition: NSObject, UIViewControllerAnimatedTransitioning {<br><br>    let duration: TimeInterval = 2<br>    let view = MetalView(device: device)<br>    let queue = DispatchQueue.main<br><br>    func transitionDuration(<br>        using transitionContext: UIViewControllerContextTransitioning?<br>    ) -&gt; TimeInterval {<br>        duration<br>    }<br><br>    func animateTransition(<br>        using transitionContext: UIViewControllerContextTransitioning<br>    ) {<br>        guard<br>            let from = transitionContext.viewController(forKey: .from),<br>            let to = transitionContext.viewController(forKey: .to)<br>        else { return }<br><br>        let container = transitionContext.containerView<br>        let frame = container.frame<br><br>        view.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)<br><br>        container.addSubview(to.view)<br>        container.addSubview(view)<br><br>        view.fromTexture = from.view.snapshot()<br>        view.toTexture = to.view.snapshot()<br><br>        queue.asyncAfter(deadline: .now() + duration) {<br>            self.view.removeFromSuperview()<br>            transitionContext.completeTransition(<br>                !transitionContext.transitionWasCancelled<br>            )<br>        }<br>    }<br><br>}</pre><p>It inherits from <strong>NSObject</strong> to be able to conform to the protocol <strong>UIViewControllerAnimatedTransitioning</strong>. We have two properties: the duration of the transition and a custom view that will run the animation. This custom view receives a <strong>device</strong> parameter, which is a <strong>MTLDevice</strong> and it is a reference to the GPU. We should have only one in the application and can be created through the function <a href="https://developer.apple.com/documentation/metal/1433401-mtlcreatesystemdefaultdevice"><strong>MTLCreateSystemDefaultDevice</strong></a>.</p><p>The first method, <strong>transitionDuration</strong>, as the name says, returns how much time it will take the transition. The <strong>animateTransition</strong> method is where we will use our custom view to execute the animation.</p><p>We get a reference for both the UIViewController that we are coming <strong>from</strong> and as the one we are going <strong>to</strong>. We set the frame of the custom view that will execute the animation (yes, the frame, we can’t use constraints here), and we add both the next view as the animation view. The order here matters, since we want the custom view to be on top to execute the animation.</p><h4>Snapshot</h4><p>After setting the views (so far nothing too complex), we get a snapshot for the <strong>from </strong>and one from the <strong>to </strong>view. Why is that? Because Metal can’t change the UIViews themselves, but we can animate two images. If you think that this is not optimal, it is very common to use images (textures) in 3D applications and Metal is made for dealing with them. Also, the animation needs two frames (or textures in this case) to know which pixel will show (from the current view or from the next view).</p><pre>extension UIView {<br><br>    func snapshot() -&gt; MTLTexture? {<br>        let width = Int(bounds.width)<br>        let height = Int(bounds.height)<br><br>        let context = CGContext(<br>            data: nil,<br>            width: width,<br>            height: height,<br>            bitsPerComponent: 8,<br>            bytesPerRow: 0,<br>            space: CGColorSpaceCreateDeviceRGB(),<br>            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue<br>        )<br><br>        if let context, let data = context.data {<br>            layer.render(in: context)<br><br>            let descriptor = MTLTextureDescriptor.texture2DDescriptor(<br>                pixelFormat: .rgba8Unorm,<br>                width: width,<br>                height: height,<br>                mipmapped: false<br>            )<br>            descriptor.usage = [.shaderRead, .shaderWrite]<br><br>            if let texture = device.makeTexture(descriptor: descriptor) {<br>                texture.replace(<br>                    region: MTLRegionMake2D(0, 0, width, height),<br>                    mipmapLevel: 0,<br>                    withBytes: data,<br>                    bytesPerRow: context.bytesPerRow<br>                )<br>                return texture<br>            }<br>        }<br><br>        return nil<br>    }<br><br>}</pre><p>The snapshot code is very simple even though it seems like a lot. We “create an empty image” of the size of our view (the whole screen) and the <strong>Core Animation</strong> layer updates the “empty image” with the contents of the screen (or a snapshot). After that, we create a <strong>MTLTextureDescriptor</strong> so that Metal can create an empty texture and we replace its contents with the ones from the snapshot that we created.</p><p>And now, to finish our <strong>animateTransition </strong>method, we schedule a block to be executed after the duration of the animation. This block removes the custom view and tells that the transition has completed. Here, we use <strong>asyncAfter</strong> because we don’t have a standard way to schedule like <strong>UIView.animate</strong> provides.</p><h3>MetalView</h3><p>So far, the code has been very straightforward and has nothing special. But we didn’t talk about the <strong>MetalView</strong>, a custom View that does all the heavy lifting necessary to render this animation. Let’s take a look at it:</p><pre>final class MetalView: MTKView {<br><br>    let positions = [<br>        SIMD3&lt;Float&gt;(-1,  1, 0), // Top Left<br>        SIMD3&lt;Float&gt;(-1, -1, 0), // Bottom Left<br>        SIMD3&lt;Float&gt;( 1, -1, 0), // Bottom Right<br><br>        SIMD3&lt;Float&gt;( 1,  1, 0), // Top Right<br>        SIMD3&lt;Float&gt;(-1,  1, 0), // Top Left<br>        SIMD3&lt;Float&gt;( 1, -1, 0), // Bottom Right<br>    ]<br><br>    let textureCoordinates = [<br>        SIMD2&lt;Float&gt;(0, 0), // Top Left<br>        SIMD2&lt;Float&gt;(0, 1), // Bottom Left<br>        SIMD2&lt;Float&gt;(1, 1), // Bottom Right<br><br>        SIMD2&lt;Float&gt;(1, 0), // Top Right<br>        SIMD2&lt;Float&gt;(0, 0), // Top Left<br>        SIMD2&lt;Float&gt;(1, 1), // Bottom Right<br>    ]<br><br>    var renderPipelineState: MTLRenderPipelineState!<br>    var commandQueue: MTLCommandQueue!<br>    var sampler: MTLSamplerState!<br><br>    var fromTexture: MTLTexture?<br>    var toTexture: MTLTexture?<br>    var timePassed: Float = 0<br><br>    override init(frame: CGRect = .zero, device: MTLDevice?) {<br>        super.init(frame: frame, device: device)<br>        setup()<br>    }<br>}</pre><p>This is a very big class, but we can break it down in smaller parts and most of it is configuration and setup rather than actually rendering code.</p><h4>Coordinates</h4><p>First let’s take a look at some two properties that we have: <strong>positions</strong> and <strong>textureCoordinates</strong>. Metal uses a normalized coordinate system, where positioning follows the same logic of the following image independent of screen size or device orientation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*82KDDt0e5Sv8FZc5xFfFkQ.png" /><figcaption>Screen Coordinates</figcaption></figure><p>And the <strong>texture coordinates</strong> are coordinates to identity positions in a texture. It follows a similar logic like UIKit, but also normalized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*z1NXW1p3SonFND67ayntqg.png" /><figcaption>Texture Coordinates</figcaption></figure><p>With that, we can understand the values for these properties.</p><p>The <strong>SIMD3</strong> and <strong>SIMD2</strong> are a vector with 3 properties (x, y, z) and another with 2 properties (x, y) that is used in Metal (there is more about it, but it is outside the scope of this article). We have 6 values for each, because the most complex geometric form that Metal renders is a triangle (the simplest geometric figure that we can use to build all others). So we divide the screen in 2 right triangles with a line that cuts from the diagonal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKYxnuisGxB3wsDPfCFIYw.png" /></figure><p>So we have the first three values of both properties to identify the coordinates of the triangle at the bottom and the last three values for the triangle at the top.</p><h4>Metal Objects</h4><p>We will have a <strong>MTLRenderPipelineState</strong> object that is also known as <strong>PSO (Pipeline State Object)</strong> and it is the object that stores the shaders to be used and how to interpret the data that we will send to the GPU. If you don’t know about shaders, soon we will talk more about it.</p><p>Then we have a <strong>MTLCommandQueue</strong>, which the name tells much about. It is a queue that we will use to tell the commands that we want for rendering in the current frame.</p><p>There is also the <strong>MTLSamplerState</strong> that describes how we will sample (interpret) the pixels in a given texture. There are a lot of configurations for it, but in this case we will use the default values.</p><p>These three last properties are very simple: two textures for the current view presented and the view that will be presented; and how much time has passed since the start of the animation (this is needed to calculate the position of pixels).</p><p>For the first setup, we will create the command queue and the sampler.</p><pre>func setup() {<br>    commandQueue = device!.makeCommandQueue()<br>    sampler = device!.makeSamplerState(descriptor: MTLSamplerDescriptor())<br>    createRenderPipelineState()<br>}</pre><p>For the renderPipelineState, let’s use its own method since it requires more information:</p><pre>func createRenderPipelineState() {<br>    let library = device!.makeDefaultLibrary()!<br>    let vertexFunction = library.makeFunction(name: &quot;main_vertex&quot;)!<br>    let fragmentFunction = library.makeFunction(name: &quot;doom_melt&quot;)!<br><br>    let vertexDescriptor = MTLVertexDescriptor()<br>    vertexDescriptor.attributes[0].format = .float3<br>    vertexDescriptor.attributes[0].bufferIndex = 0<br>    vertexDescriptor.attributes[0].offset = 0<br><br>    vertexDescriptor.attributes[1].format = .float2<br>    vertexDescriptor.attributes[1].bufferIndex = 0<br>    vertexDescriptor.attributes[1].offset = MemoryLayout&lt;SIMD3&lt;Float&gt;&gt;.size<br><br>    vertexDescriptor.layouts[0].stride = MemoryLayout&lt;SIMD3&lt;Float&gt;&gt;.stride + MemoryLayout&lt;SIMD2&lt;Float&gt;&gt;.stride<br><br>    let renderPipelineDescriptor = MTLRenderPipelineDescriptor()<br>    renderPipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm<br>    renderPipelineDescriptor.vertexFunction = vertexFunction<br>    renderPipelineDescriptor.fragmentFunction = fragmentFunction<br>    renderPipelineDescriptor.vertexDescriptor = vertexDescriptor<br><br>    renderPipelineState = try! device!.makeRenderPipelineState(descriptor: renderPipelineDescriptor)<br>}</pre><p>Let’s walk through each part of this code.</p><p>First we get a <strong>MTLLibrary</strong> and two <strong>MTLFunction</strong>. The library is where we can get reference to the shaders and we get one for the <strong>vertex</strong> and other for the <strong>fragment</strong> shader. Until now we didn’t create them, but the <strong>vertex shader</strong> is responsible for positioning in the screen and the <strong>fragment shader</strong> for coloring each pixel. We will get more in depth about them soon.</p><p>Then we create a <strong>MTLVertexDescriptor</strong>, which describes the vertex which is the data that we send to the vertex shader. Usually it is the position of the objects on the screen, but can also have texture coordinates, some matrices and other data relevant to positioning. In this case it is the positions and texture coordinates only.</p><p>So the first attribute (in the 0th position) is a <strong>float3</strong> (a vector with x, y and z) in the buffer index 0 with 0 of offset. This offset is the offset of how many bytes we will need to “jump” for the next attribute, in this case, zero. The second attribute is a <strong>float2</strong> (vector with x and y), at the index 0 and offset of a <strong>SIMD3</strong> of <strong>Float</strong> (the same as a float3). The float<strong>X</strong> and SIMD<strong>X</strong> where <strong>X</strong> is the same number represents the same type, we could explain the details, but for this project it doesn’t make much difference.</p><p>After this, we set the memory layout for the object that we send, which is the stride of a <strong>SIMD3</strong> plus the stride of a <strong>SIMD2</strong>. But what is a stride? The stride is the number of bytes for the next element in a contiguous memory. This explanation can be confusing, but imagine that each element is separated from each other with 32 bytes. Let’s assume that we only use 24. In memory, each element will still be using 32 bytes, but 8 of these will not be filled with any data, to conform the memory layout specified (we use exponents of 2 because of the way computers work).</p><p>Then, we will create an <strong>MTLRenderPipelineDescriptor</strong>, which will tell us how to use the data and which shaders. This is very trivial, except for the <strong>colorAttachments[0].pixelFormat = .bgra8Unorm</strong>. This is the default way to interpret pixel bytes and there isn’t much of an official answer, but a lot of Apple examples use it and we will stick to it.</p><p>And finally, we use the device to make a new <strong>MTLRenderPipelineState</strong>. Here we don’t focus on handling errors, but it is a good practice to deal with them accordingly.</p><h4>draw</h4><p>Now we will move forward to the render loop before talking about the shaders:</p><pre>override func draw(_ rect: CGRect) {<br>    guard<br>        let drawable = currentDrawable,<br>        let renderPassDescriptor = currentRenderPassDescriptor<br>    else { return }<br><br>    timePassed += 1 / Float(preferredFramesPerSecond)<br><br>    let commandBuffer = commandQueue.makeCommandBuffer()<br>    let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: renderPassDescriptor)<br><br>    commandEncoder?.setRenderPipelineState(renderPipelineState)<br>    commandEncoder?.setVertexBytes(<br>        positions,<br>        length: MemoryLayout&lt;SIMD3&lt;Float&gt;&gt;.stride * positions.count,<br>        index: 0<br>    )<br><br>    commandEncoder?.setVertexBytes(<br>        textureCoordinates,<br>        length: MemoryLayout&lt;SIMD2&lt;Float&gt;&gt;.stride * textureCoordinates.count,<br>        index: 1<br>    )<br><br>    if let fromTexture, let toTexture {<br>        commandEncoder?.setFragmentTexture(fromTexture, index: 0)<br>        commandEncoder?.setFragmentTexture(toTexture, index: 1)<br>        commandEncoder?.setFragmentSamplerState(sampler, index: 0)<br>        commandEncoder?.setFragmentBytes(<br>            &amp;timePassed,<br>            length: MemoryLayout&lt;Float&gt;.stride,<br>            index: 0<br>        )<br>    }<br><br>    commandEncoder?.drawPrimitives(<br>        type: .triangle,<br>        vertexStart: 0,<br>        vertexCount: positions.count<br>    )<br>    commandEncoder?.endEncoding()<br><br>    commandBuffer?.present(drawable)<br>    commandBuffer?.commit()<br>}</pre><p>The <strong>draw</strong> method is the method to actually render things on the screen and usually is called at the same number of times as the refresh screen (60, 120, etc.). If the work being done is too heavy, it is possible that some frames will take longer and it will break the rendering, so in more complex workloads it is important to be aware of the performance of the code written. For our case, we don’t need to worry about that.</p><p>We start by getting a reference for the object in which we will draw into and the current render pass. We can have multiple render passes in which each will add something to the screen, so we could have one for basic rendering, another one for shadows and so forth. We don’t need multiple, so we only use the current one created.</p><p>Then we calculate how much time has passed between the first frame to the current. The <strong>preferredFramesPerSecond</strong> is how many frames the display should render.</p><p>We create a <strong>MTLCommandBuffer </strong>and a <strong>MTLRenderCommandEncoder</strong>. The first is a buffer of commands that will be sent to the Command Queue and the encoder is where we set all information necessary (the pipeline state, data, etc.). So it is very simple to see that we are only calling a bunch of set methods to tell how to interpret the data and the data that we will be sending.</p><p>Before we finish with the encoder, we tell how it will draw the data, in this case as triangles (there is also point and line), since we use two triangles to create the rectangle that fills the screen. We say that it starts at vertex 0 and goes to the amount of positions that we have.</p><p>We say that we finish with this encoder and in other cases we could use a different one for another task, but we need only this one.</p><p>Finally, we say to the buffer render its contents to the drawable and commit the commands to be executed.</p><p>I know, it has been a lot of code, but we are almost finished.</p><p>Lastly, we will talk about shaders. So far we talked about shaders but didn’t explain and for those who don’t know, it can be somewhat confusing. But shaders are small programs (or functions) that we create to use the GPU.</p><h3>Shaders</h3><p>We have three main shaders: <strong>kernel</strong>, <strong>vertex</strong> and <strong>fragment</strong>. The <strong>kernel</strong> is used for computations and not necessarily for rendering, so we will not talk about it. The<strong> vertex shader</strong> is responsible for positioning the elements we want to render on the screen and the <strong>fragment</strong> is responsible for saying the color of each pixel of the screen. It is important to note that all this is runned in parallel using a lot of cores that the GPU has (<strong>some GPUs have thousands of cores!</strong>), so don’t need to worry if there are too many pixels to be calculated.</p><p>Before diving into the code, it is important to tell you that the shaders are written in a language called <strong>Metal Shader Language</strong>, a variation of <strong>C++14</strong>. Don’t worry if you don’t know C++, this should be very easy even if you don’t know. Also, we can create shaders as strings in our code or use the <strong>Metal File</strong> that Xcode creates to write it. Using the <strong>Metal File</strong> makes the shaders to be compiled alongside the rest of the code instead of on the fly. In this example we use one of these files.</p><h4>VertexShader</h4><p>Let’s start with the vertex shader that is very simple:</p><pre>struct VertexOut {<br>    float4 position [[ position ]];<br>    float2 textureCoordinate;<br>};<br><br>vertex VertexOut main_vertex(constant float3 *positions [[ buffer(0) ]],<br>                             constant float2 *textureCoordinates [[ buffer(1) ]],<br>                             uint vertexID [[ vertex_id ]]) {<br>    VertexOut out {<br>        .position = float4(positions[vertexID], 1),<br>        .textureCoordinate = textureCoordinates[vertexID],<br>    };<br>    return out;<br>}</pre><p>The vertex function starts with the <strong>vertex</strong> keyword, to tell that this is a <strong>vertex function</strong> and not any other function (we can create helper functions, etc.). We have the return value to be our custom struct called <strong>VertexOut</strong>, which has the values that we will return both to the GPU so that it knows how to position the objects (marked with the <strong>position</strong> annotation) but also for feeding it to the <strong>fragment</strong> shader soon.</p><p>It is important to note that the value for position in the vertex shader has to be a <strong>float4 </strong>(x, y, z and w), even though we aren’t using all the coordinates.</p><p>We have three parameters, both the positions and the textureCoordinates, that we use the annotations to tell to retrieve from the buffers at the specified indices and we have an <strong>vertex_id</strong>, which is the index of the current vertex that we are accessing (remember that we are sending 6 values for each array). It is important to note that you should not assume anything about the ordering or the values being accessed, since it is not guaranteed that it will always be the same.</p><p>Then, we just create a new <strong>VertexOut</strong> and set the values for the attributes, and return the object. The <strong>position</strong> annotation in the <strong>position</strong> property will already be recognized by the Metal API as where to place the points and how to connect them (each three points makes a triangle).</p><h4>Fragment Shader</h4><p>Now, we go to the last piece of code that is the fragment shader:</p><pre>constant float START_SPEED = 2.7;<br>constant float MELT_SPEED = 1;<br><br>/// Adaptation of the Doom Effect shader from: https://www.shadertoy.com/view/XtlyDn<br>/// Created by k_kondrak in 2017-09-02<br>fragment float4 doom_melt(texture2d&lt;float&gt; from [[ texture(0) ]],<br>                          texture2d&lt;float&gt; to [[ texture(1) ]],<br>                          sampler sampler [[ sampler(0) ]],<br>                          VertexOut vertexIn [[ stage_in ]],<br>                          constant float &amp;timePassed [[ buffer(0) ]]) {<br>    float2 uv = vertexIn.textureCoordinate;<br>    float velocity = START_SPEED * timePassed;<br>    if (velocity &gt; 1) velocity = 1;<br><br>    uv.y -= velocity * 0.35 * fract(sin(dot(float2(uv.x, 0), float2(12.9898, 78.233))) * 43758.5453);<br><br>    if (velocity == 1) uv.y -= MELT_SPEED * (timePassed - velocity / START_SPEED);<br><br>    if (uv.y &lt; 0) {<br>        return to.sample(sampler, vertexIn.textureCoordinate);<br>    }<br><br>    return from.sample(sampler, uv);<br>}</pre><p>Before we dive into the code, this is an adaptation from the <a href="https://www.shadertoy.com/view/XtlyDn">fragment shader</a> from Shader Toy made by <em>k_kondrak</em>.</p><p>First we have two constants that are the <strong>START_SPEED</strong> for the animation and the <strong>MELT_SPEED</strong>, which are very clear by their name. You can tweak and play with these values.</p><p>Then we have the declaration of the <strong>fragment</strong> shader which returns a <strong>float4</strong> (this could be other values but not relevant for this example) to tell each value of a pixel (<strong>Red</strong>, <strong>Green</strong>, <strong>Blue</strong> and <strong>Alpha</strong>).</p><p>We have a lot of parameters. The first two are the snapshot textures from earlier and we have the sampler to interpret each pixel from it. We have a <strong>VertexOut</strong> object that we received from the <strong>vertex</strong> shader (using the <strong>stage_in</strong> annotation) and the time passed since the beginning of the animation.</p><p>We create a copy of the texture coordinate calling it <strong>uv</strong>, which is a common pattern for x and y axis for textures coordinates. We calculate the current speed and if it is above 1 (remember that we use normalized values?) we set it to 1.</p><p>Then we have this long and fancy line. It can be scary, but it is simply using the speed with some values to randomize the column order. We “randomize” the start point for each column. This order will be maintained for all the animation, so the “randomization” only happens once. Also, I am calling it “randomization” because it is not really random, just pseudo-random. You can play with the values and even replace the math for another one if you want.</p><p>If we are still animating the columns (if there is a velocity) we calculate where the next pixel should be displayed.</p><p>If the <strong>y value is below zero</strong>, we should not display the pixel for the current screen but instead the pixel for the next screen. Else, we display the current pixel at the calculated position.</p><p>Phew! That was a lot! But now, if we run our application, we should see the animation working properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hsSRnJMHoStjC5udozLU3Q.gif" /></figure><p>Some things to note:</p><ol><li>The usage of colored screens is just to create an easy to see contrast between the two screens, it is not a requirement and it can be applied to any app.</li><li>This code should work in all Apple devices with some adaptations (the usage of Cocoa classes for macOS, etc.).</li><li>Even though it is a lot of code, in reality most of it will not change for a lot of animations like this one, mostly changing the fragment shader.</li></ol><p>Here is the <a href="https://github.com/ricardorachaus/metaltransition">repository</a> with the source code of this project.</p><p>Hope that you use Metal in your apps in creative and innovative ways!</p><p>Thanks if you read until this point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0962d8f912c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thearcaneprogrammer/custom-navigation-transitions-with-metal-d0962d8f912c">Custom Navigation Transitions with Metal</a> was originally published in <a href="https://medium.com/thearcaneprogrammer">The Arcane Programmer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing states (or State Machines)]]></title>
            <link>https://medium.com/thearcaneprogrammer/managing-states-or-state-machines-e3fa2725be2f?source=rss----8fdf9e726385---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3fa2725be2f</guid>
            <category><![CDATA[state-machine]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ricardo Rachaus]]></dc:creator>
            <pubDate>Mon, 25 May 2020 22:25:11 GMT</pubDate>
            <atom:updated>2020-05-25T22:30:08.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUQJOYNpvVKEvRyVotBCqw.jpeg" /><figcaption>A Photo by Darren Hester from FreeImages</figcaption></figure><p>For my first topic, I will discuss state machines. It&#39;s a simple concept, but I see a lot of people don&#39;t know or understand. I have already talked about in this <a href="https://youtu.be/gdCfBSCZe8E">Cocoa Heads SP</a> (it&#39;s in portuguese and focused on iOS). For this article I will take a more broad approach. All the code will be written in Swift, but its concepts is applied in any scenario (really, a lot of things can be represented as a state machine).</p><p>So, State Machines are a <strong>finite state automaton</strong>. But what the hell? Although looks like a complicated subject, it&#39;s very simple. Basically, everything has states. A simple example is a <strong>switch</strong>: you have turned <strong>on</strong> or <strong>off</strong>. Two states that can be represented in two values: <strong>0</strong> or <strong>1</strong>, <strong>true</strong> or <strong>false</strong>. This is the simplest form of state control and manage states: a boolean value.</p><p>One of the most common use of states is very clear in circuit boards (and that&#39;s the reason of the cover). If you have ever study digital circuits and how it works, you already have seen state machines. This is the example of the switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*2U_zlkf71Dp4yMg2UDyayA.png" /><figcaption>A example of switch states</figcaption></figure><p>So, not scary at all right? Of course, this is the simplest state machine, and if you are more curious about state machines in circuits and computer theory, <a href="https://www.geeksforgeeks.org/mealy-and-moore-machines-in-toc/">this article</a> can help you understand more.</p><p>But when will we start the real programming examples? So let&#39;s dive in more daily programming examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e60cd863e8a4997ef2b01918741dba1/href">https://medium.com/media/4e60cd863e8a4997ef2b01918741dba1/href</a></iframe><p>The code from above shows a simple example of a switch. I didn&#39;t think in a more complex example because we all do it everyday in programming. It&#39;s usually a <strong>control flag</strong> that we use in <strong>ifs</strong> around the code to <strong>do something if true, otherwise do something else</strong>. Of course that boolean managing can be really a pain and with more booleans, we cause the infamous pyramid of doom (or Hadouken code) when we manage a lot of things with booleans in some code block.</p><p>And now that I have mentioned games, let&#39;s use it more, mainly because games it&#39;s the perfect example of states and state machines (if you doubt, search in Google for any character spritesheet and probably each row is a state of the character).</p><p>I already talked about using a boolean flag to control your states, but imagine something like <strong>Super Mario Bros</strong>. A simple game with simple mechanics: jump, run, and if you catch a flower, attack. With only a naive approach we have at least for flags: isJumping , isRunning , hasCatchFlower , isAttacking . But we have also when he died, when he is small, when catch a star… not much fun ahead right? (I don&#39;t know the original Super Mario Bros code, but probably they handled with a lot of flags since the original code is in <a href="https://wiki.nesdev.com/w/index.php/Programming_guide">Assembly 6502</a>)</p><p>So, how we will handle all of those states? The next step is something not really new: <strong>enumerations</strong>. For those who don&#39;t know, enums (short for enumerations) is a feature in languages since <strong>C</strong> (can be even older, I don&#39;t know, but I think that quoting a language from the 70’s is enough for example). But then, what we do to use enums ?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8a62b9b713cab85b7205fd1722fe7ad/href">https://medium.com/media/b8a62b9b713cab85b7205fd1722fe7ad/href</a></iframe><p>A lot more of code than the previous example right? If this sound more complex, we are looking to a simplified version of a <a href="https://pt.wikipedia.org/wiki/Super_Mario_Bros.">1985 game</a>. Imagine games like <strong>Megaman X</strong> or <strong>The Legend Of Zelda: A Link to the Past</strong> (give me chills just of thinking, but also a nice challenge 😉). For those who don&#39;t know these games, just a quick look at YouTube and you will find various gameplay videos.</p><p>The downside of this approach is that you need to handle with a lot of switch statements and can be really repetitive and painful to maintain. Also, you can mix a lot of responsibilities in just one place (I faked some methods that would contain the real logic, but the real world is not always this beautiful).</p><p>Okay, some may think &quot;I don&#39;t make games, why will I use this?&quot;. If you&#39;re a <strong>frontend</strong> <strong>developer</strong>, probably you can use a these in: <strong>display content</strong>, <strong>loading</strong> and <strong>error</strong>. Or a button that has: <strong>pressed</strong>, <strong>highlight</strong>, <strong>normal</strong>. Don&#39;t sound like daily work? If you&#39;re a <strong>backend developer</strong>, this can be a status of a purchase in an e-commerce. Or even environments: <strong>develop</strong>, <strong>homolog</strong>, <strong>production</strong>. And like I said, everything can be modelled as states: message received, message send; wake, work, sleep; birth, life, death (☠️)… I think that it&#39;s not needed more examples, right?</p><blockquote>After writing I noticed that a lot of my examples is 3 states based, but can be any N number of states, since N is a finite number. So yes, you can have a billion different states, but it doesn&#39;t look like something humans can handle (🤷).</blockquote><p>And now what? It&#39;s just this? Now is everyone a <strong>&quot;state master&quot;</strong>? Actually there is still something to show: <a href="https://gameprogrammingpatterns.com/state.html">State Pattern</a>. However, isn’t everything above a State Pattern? Or better, different States Patterns? Yes, but there is one more that is based in <strong>OOP</strong>, but we will take a different approach and make <strong>POP </strong>(not the music style, but <strong>Protocol Oriented Programming</strong>). POP is something in the roots of Swift, and for those who don&#39;t understand, basically are something like <strong>Java/Kotlin Interfaces</strong> or <strong>C++ Abstract Classes</strong> (actually there is some differences, but it&#39;s out of scope from this article).</p><p>If you&#39;re an iOS developer, there is a chance that you&#39;ve heard about <strong>GameplayKit</strong>. In this Apple framework, there is already a full State Pattern implemented and free to use (also, it&#39;s the topic of my talk from the beginning of this text) called <strong>GKStateMachine</strong>. If you are curious, I have <a href="https://github.com/ricardorachaus/StateMachine">my own implementation</a> of the GKStateMachine. If you aren&#39;t an iOS developer, I also recommend seeing the code, it&#39;s not complex and can easily be ported to another language.</p><p>So, what is a State Pattern using POP? Let&#39;s look (here comes a long gist, sorry 😅):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9430df33b3fac4219e9ecff76584e66e/href">https://medium.com/media/9430df33b3fac4219e9ecff76584e66e/href</a></iframe><p>A lot of stuff going on. Also, can be seen as over-engineering or something like that. But remember, this is for complex cases where there is a lot of states or also complex behaviour and you want very clear separation of responsibilities (anyone think of the <strong>S</strong> of <strong>SOLID</strong>?). For instance, in a game like <strong>Super Mario Bros.</strong> that I referred before, it would really help, since in each state you can set the player animation, physics and etc.</p><p>For those who don&#39;t understand everything going on, basically the State Machine is a <a href="https://developer.apple.com/swift/blog/?id=10">Value Type</a> and to alter it&#39;s contents in some method, you need to specify that is mutating . I use metatypes to decide which state I should enter. Metatypes are types that describe types of the language (confusing?). Let&#39;s take the example of a String : we all know what a string is, but imagine that we want to reference the type String and not it&#39;s contents, how would we do that? And that&#39;s when enter metatypes. You can refer to the type itself and not the contents that holds. It&#39;s really useful in situations like the above that the type already know what will do, you just need to retrieve the type you want and it will do what needs to be done.</p><p>Likewise, this State Machine is resilient to mistakes like in the last line (trying to enter a State that is not mapped). But you can modify and handle each case in any way you want (make it crash, display an error…). And you don&#39;t really need a State Machine, as you can see, it&#39;s a little advanced (handling <strong>metatypes </strong>can be hard for beginners). The alternative would be for you to hold each state on it&#39;s own variable or &quot;<strong>holder</strong>&quot; (I don&#39;t know if anyone would make a type for something like this 🤔, but you can expect anything from people).</p><p>I think that another example is not necessary for when to use a state machine, and besides in a more complex case, everything that I mentioned earlier can be used (like, you could add a loading view in your application when it’s in loading state and remove it when finishing the loading). And if it isn’t clear until know, you can avoid a lot of duplication because each state is self-contained.</p><p>So, after a long way talking about state machine and managing states, you now can use in many places and try to avoid some common pitfalls that people do when handling states. Each case has its needs and don&#39;t jump into something complex when you usually just need few states. It&#39;s easy to want to use something more complex but you just have a case like a switch. Don&#39;t abuse!</p><p>Just reinforcing something that I said in the beginning: yes, state machines are applied everywhere. AI, circuit boards, mathematical models, physics models, computer graphics (OpenGL works like a State Machine and others graphics APIs also use state concepts) and etc. This is just a scratch at teaching it&#39;s use in common programming, but as you dive into more complex problems, state machines can be really handy and useful.</p><p>I hope that after reading this, at least some of you will try to use states and manage better your application. Let me know if something is not clear or any other topics related.</p><blockquote>If you are curious about state pattern in different programming paradigms <a href="https://www.adamtornhill.com/Patterns%20in%20C%202,%20STATE.pdf">here</a> is a example in C and <a href="https://wiki.haskell.org/State_Monad">here</a> in Haskell language. I find important to show in different paradigms to see that even with my code being in Swift it&#39;s not limited to the language or the paradigms that Swift implements.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3fa2725be2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thearcaneprogrammer/managing-states-or-state-machines-e3fa2725be2f">Managing states (or State Machines)</a> was originally published in <a href="https://medium.com/thearcaneprogrammer">The Arcane Programmer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About Me]]></title>
            <link>https://medium.com/thearcaneprogrammer/about-me-6bc18f9e5b7f?source=rss----8fdf9e726385---4</link>
            <guid isPermaLink="false">https://medium.com/p/6bc18f9e5b7f</guid>
            <category><![CDATA[game-developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[about-me]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ricardo Rachaus]]></dc:creator>
            <pubDate>Mon, 18 May 2020 23:25:09 GMT</pubDate>
            <atom:updated>2020-05-18T23:25:08.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*b8ke4-SH8o3rKcmKILxBCw.png" /></figure><h3>About</h3><p>Hi, I am Ricardo Rachaus.</p><p>I&#39;m an iOS Developer and also a Game Developer (that is now on hold but I hope to return soon) who is a enthusiastic of programming, computer and technology.</p><p>The goal with this Medium is to write about stuff that normally I don&#39;t find or had a lot of work to find materials related. Also I intend to write about some topics that I like, made or just find curious enough to write about. Probably most of the content will be programming related (heads up).</p><p>I will try to make posts about a broad range of topics: tests, low-level, games, some bizarre ideas and etc. It&#39;s not guaranteed that always will have a post or something like that, but I will try my best to write something now and then.</p><p>The name The Arcane Programmer came from a day that I was talking with a friend from work and he told that one of his college teachers said that exists something beyond &quot;exoteric programming&quot;, the &quot;arcane programming&quot;. I really love the sound of &quot;arcane programming&quot;, mainly because I really love low-level and old-school programming, so it sound magic and mysterious (also sounded like something lovecraftian).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bc18f9e5b7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thearcaneprogrammer/about-me-6bc18f9e5b7f">About Me</a> was originally published in <a href="https://medium.com/thearcaneprogrammer">The Arcane Programmer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>