nicklockwood / Euclid

A Swift library for creating and manipulating 3D geometry

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Improve semantics for Vector

jkalias opened this issue · comments

The struct Vector is used to define multiple entities (vertex, vector and direction), all of which have 3 coordinates (x, y and z). Admittedly there are commonalities among these entities, however the API does not follow the semantics of rigorous mathematical definition.

In detail, the following mathematically illegal operations are allowed, since all of them are based on the Vector API:

  1. Adding a position vector (vertex) to another position vector (vertex)
  2. Adding a direction vector to a position vector
  3. Adding two direction vectors

I propose the introduction of three separate structs (Direction, CartesianPosition, CartesianVector), in order to enforce the proper mathematical operations on the compiler level. This would ensure that only the following operations are allowed:

  1. CartesianPosition + CartesianVector -> CartesianPosition
  2. CartesianVector + Distance * Direction -> CartesianVector
  3. CartesianPosition + Distance * Direction -> CartesianPosition
  4. CartesianPosition - CartesianPosition -> CartesianVector

I'd be more than happy to send a PR

@jkalias I did consider this (there's precedent in Apple's own APIs, e.g. with CGSize vs CGPoint). My main concern was that this would lead to a significant amount of code duplication between the different vector types and operations.

I'm also not sure about the naming - while I'm sure it's appropriate mathematically it's a bit verbose for types that are used so frequently. Maybe Position, Distance and Direction would work?

I do like the idea of being able to enforce things like vector normalization though, and also to potentially use different precision for direction vs position.

If you're keen to try this out I'd be happy to look at a PR.

@nicklockwood Thanks for the prompt reply. Once I finish the remaining work for the Angle PR, I'll start with this.

Regarding the naming, my thought was to make it explicit what the type is all about. I guess we can discuss about it once it's finished.

Hi @nicklockwood,

I know the vector semantics PR is still open, but I have a working prototype for the generalized 3D geometry operations of line and plane based on this work (Line_, Plane_ and LineSegment_ in my branch line-plane).

I'm not sure this belongs here or if it is at all relevant (new issue or PR?). Perhaps you don't want such an invasive change, I fully understand. I thought before I invest more time in changing so much API it's worth having your feedback.

Take care

Partial implementation is already covered in merged PR #38 (refactoring covering only directions and normals). The rest will follow in separate PRs.

This issue has fully been resolved