Uploaded image for project: 'Commons Geometry'
  1. Commons Geometry
  2. GEOMETRY-119

Vector normalizeOrDefault() method

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Done
    • None
    • None
    • None
    • None

    Description

      A frequent use case when working with vectors, especially vectors coming from external data, is attempting to normalize the vector, and if this is not possible, to use an alternative value. For example, the QuaternionRotation code here does exactly this; it attempts to normalize a vector and failing that (ie, if the vector is exactly zero), it returns a substitute value. The QuaternionRotation class is able to take advantage of our internal Vectors.tryNormalize() but callers outside of the library are not able to do so and so are left with 2 choices:
      1. wrap the normalize() call in a try-catch and handle the exception thrown on illegal norm values, or
      2. compute and test the norm prior to calling normalize() to ensure that the call won't fail, resulting in 2 computations of the norm.

      Neither of these options are very good.

      I propose adding a new method to the Euclidean Vector classes to handle this situation: normalizeOrDefault(). The method would accept a default value (possibly null) to return if the vector cannot be normalized. The normal would then only need to be computed once and an exception would not need to be thrown in case of failure. The behavior of the current normalize method would be the same.

      Examples:

      // get some kind of normal, preferably vec but +z will also do
      Vector3D.Unit norm = vec.normalizeOrDefault(Vector3D.Unit.PLUS_Z);
      
      // throw a very use-case specific error message
      Vector3D norm = vec.normalizeOrDefault(null);
      if (norm == null) {
          throw new Exception("Invalid triangle at index " + i + ": cannot compute normal.");
      } 
      

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              mattjuntunen Matt Juntunen
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: