Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Distance Squared node?

Discussion in 'Shader Graph' started by dgoyette, Jul 16, 2020.

  1. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,117
    When I was writing shaders by hand, there were plenty of cases where I would use Distance Squared, instead of Distance, due to the perceived performance benefits. If possible, I would square the value I was comparing the distance to, and use Distance Squared, to avoid needing to take the square root of the distance. But I notice there's no existing node for doing Distance Squared in Shader Graph. (I could square the Distance node's output, but there's no performance benefit to that.)

    So, I know I can easily make a subgraph to compute Distance Squared. But given how simple it is, and how it's not just part of Shader Graph already, it made me wonder if there was some good reason why using Distance Squared isn't all I imagine it to be.

    Also, I wonder if my own hand-made subgraph for this will be as performant as the built-in Distance node. I just don't know if the built-in nodes have any kind of optimization that makes them faster than what I can produce using a subgraph?

    So,in short: Why is there no Distance Squared node? Is it not needed, from a performance perspective? Is this implementation going to be faster than just using the built-in Distance node?

    upload_2020-7-16_12-10-41.png
     
  2. FissicsPeep

    FissicsPeep

    Joined:
    Jan 14, 2014
    Posts:
    65
    Still no squared magnitude nodes in Shader Graph it seems. Anybody know if there's any plans to add them. Would be very useful, and optimal.
     
  3. fleity

    fleity

    Joined:
    Oct 13, 2015
    Posts:
    289
    as dgoyette said a simple subgraph can do this. Is the performance better? probably a tiny bit because we omit the square root. One could check the amount of saved instructions in the decompiled shader but all in all .. it's probably hard to notice even on mobile.
    Screenshot 2022-01-21 140507.jpg
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,236
    There already is a "Length Squared" node. It's called the Dot Product node. A Distance Squared sub graph should look like this:
    upload_2022-1-22_22-21-35.png
    And this will be faster than the other versions.