Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v-3): QGIS essentials #369

Merged
merged 4 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 214 additions & 9 deletions src/specklepy/objects/geometry.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
from dataclasses import dataclass, field
from typing import List
from typing import List, Tuple

from specklepy.objects.base import Base
from specklepy.objects.interfaces import ICurve, IHasUnits
from specklepy.objects.models.units import Units
from specklepy.objects.interfaces import ICurve, IHasArea, IHasUnits, IHasVolume
from specklepy.objects.models.units import (
Units,
get_encoding_from_units,
get_scale_factor,
get_units_from_string,
)
from specklepy.objects.primitive import Interval


Expand Down Expand Up @@ -33,11 +38,28 @@ def from_coords(cls, x: float, y: float, z: float, units: str | Units) -> "Point

def distance_to(self, other: "Point") -> float:
"""
calculates the distance between this point and another given point
calculates the distance between this point and another given point.
"""
dx = other.x - self.x
dy = other.y - self.y
dz = other.z - self.z
if not isinstance(other, Point):
raise TypeError(f"Expected Point object, got {type(other)}")

# if units are the same perform direct calculation
if self.units == other.units:
dx = other.x - self.x
dy = other.y - self.y
dz = other.z - self.z
return (dx * dx + dy * dy + dz * dz) ** 0.5

# convert other point's coordinates to this point's units
scale_factor = get_scale_factor(
get_units_from_string(
other.units), get_units_from_string(self.units)
)

dx = (other.x * scale_factor) - self.x
dy = (other.y * scale_factor) - self.y
dz = (other.z * scale_factor) - self.z

return (dx * dx + dy * dy + dz * dz) ** 0.5


Expand Down Expand Up @@ -70,9 +92,10 @@ def to_list(self) -> List[float]:
return result

@classmethod
def from_list(cls, coords: List[float], units: str) -> "Line":
def from_list(cls, coords: List[float], units: str | Units) -> "Line":
if len(coords) < 6:
raise ValueError("Line from coordinate array requires 6 coordinates.")
raise ValueError(
"Line from coordinate array requires 6 coordinates.")

start = Point(x=coords[0], y=coords[1], z=coords[2], units=units)
end = Point(x=coords[3], y=coords[4], z=coords[5], units=units)
Expand All @@ -93,3 +116,185 @@ def from_coords(
start = Point(x=start_x, y=start_y, z=start_z, units=units)
end = Point(x=end_x, y=end_y, z=end_z, units=units)
return cls(start=start, end=end, units=units)


@dataclass(kw_only=True)
class Polyline(Base, IHasUnits, ICurve, speckle_type="Objects.Geometry.Polyline"):
"""
a polyline curve, defined by a set of vertices.
"""

value: List[float]
closed: bool = False
domain: Interval = field(default_factory=Interval.unit_interval)

@property
def length(self) -> float:
points = self.get_points()
total_length = 0.0
for i in range(len(points) - 1):
total_length += points[i].distance_to(points[i + 1])
if self.closed and points:
total_length += points[-1].distance_to(points[0])
return total_length

@property
def _domain(self) -> Interval:
"""
internal domain property for ICurve interface
"""
return self.domain

def get_points(self) -> List[Point]:
"""
converts the raw coordinate list into Point objects
"""
if len(self.value) % 3 != 0:
raise ValueError(
"Polyline value list is malformed: expected length to be multiple of 3"
)

points = []
for i in range(0, len(self.value), 3):
points.append(
Point(
x=self.value[i],
y=self.value[i + 1],
z=self.value[i + 2],
units=self.units,
)
)
return points

def to_list(self) -> List[float]:
"""
returns the values of this Polyline as a list of numbers
"""
result = []
result.append(len(self.value) + 6) # total list length
# type indicator for polyline ?? not sure about this
result.append("Objects.Geometry.Polyline")
result.append(1 if self.closed else 0)
result.append(self.domain.start)
result.append(self.domain.end)
result.append(len(self.value))
result.extend(self.value)
result.append(get_encoding_from_units(self.units))
return result

@classmethod
def from_list(cls, coords: List[float], units: str | Units) -> "Polyline":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we follow C# methods, should we assume units are passed as the last element in the list (without keyword)? Same for Line

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the keywords are required for the class definition but not in the classmethods. So, for classmethods, yes.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I decided to keep units as a seperate argument to be able to compatible with all the classes.

"""
creates a new Polyline based on a list of coordinates
"""
point_count = int(coords[5])
return cls(
closed=(int(coords[2]) == 1),
domain=Interval(start=coords[3], end=coords[4]),
value=coords[6: 6 + point_count],
units=units,
)


@dataclass(kw_only=True)
class Mesh(
Base,
IHasArea,
IHasVolume,
IHasUnits,
speckle_type="Objects.Geometry.Mesh",
detachable={"vertices", "faces", "colors", "textureCoordinates"},
chunkable={
"vertices": 31250,
"faces": 62500,
"colors": 62500,
"textureCoordinates": 31250,
},
):

vertices: List[float]
faces: List[int]
colors: List[int] = field(default_factory=list)
textureCoordinates: List[float] = field(default_factory=list)

@property
def vertices_count(self) -> int:
return len(self.vertices) // 3

@property
def texture_coordinates_count(self) -> int:
return len(self.textureCoordinates) // 2

def get_point(self, index: int) -> Point:

index *= 3
return Point(
x=self.vertices[index],
y=self.vertices[index + 1],
z=self.vertices[index + 2],
units=self.units,
)

def get_points(self) -> List[Point]:

if len(self.vertices) % 3 != 0:
raise ValueError(
"Mesh vertices list is malformed: expected length to be multiple of 3"
)

points = []
for i in range(0, len(self.vertices), 3):
points.append(
Point(
x=self.vertices[i],
y=self.vertices[i + 1],
z=self.vertices[i + 2],
units=self.units,
)
)
return points

def get_texture_coordinate(self, index: int) -> Tuple[float, float]:

index *= 2
return (self.textureCoordinates[index], self.textureCoordinates[index + 1])

def align_vertices_with_texcoords_by_index(self) -> None:

if not self.textureCoordinates:
return

if self.texture_coordinates_count == self.vertices_count:
return

faces_unique = []
vertices_unique = []
has_colors = len(self.colors) > 0
colors_unique = [] if has_colors else None

n_index = 0
while n_index < len(self.faces):
n = self.faces[n_index]
if n < 3:
n += 3

if n_index + n >= len(self.faces):
break

faces_unique.append(n)
for i in range(1, n + 1):
vert_index = self.faces[n_index + i]
new_vert_index = len(vertices_unique) // 3

point = self.get_point(vert_index)
vertices_unique.extend([point.x, point.y, point.z])

if colors_unique is not None:
colors_unique.append(self.colors[vert_index])
faces_unique.append(new_vert_index)

n_index += n + 1

self.vertices = vertices_unique
self.colors = colors_unique if colors_unique is not None else self.colors
self.faces = faces_unique
44 changes: 36 additions & 8 deletions src/specklepy/objects/interfaces.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, field
from typing import Generic, TypeVar
from typing import Generic, List, TypeVar

from specklepy.logging.exceptions import SpeckleInvalidUnitException
from specklepy.objects.base import Base
Expand Down Expand Up @@ -37,22 +37,16 @@ def display_value(self) -> T:

@dataclass(kw_only=True)
class IHasUnits(metaclass=ABCMeta):
"""Interface for objects that have units."""

units: str | Units
_units: str = field(repr=False, init=False)

@property
def units(self) -> str:
"""Get the units of the object"""
return self._units

@units.setter
def units(self, value: str | Units):
"""
While this property accepts any string value, geometry expects units
to be specific strings (see Units enum)
"""
if isinstance(value, str):
self._units = value
elif isinstance(value, Units):
Expand All @@ -63,6 +57,40 @@ def units(self, value: str | Units):
)


@dataclass(kw_only=True)
class IHasArea(metaclass=ABCMeta):

area: float
_area: float = field(init=False, repr=False)

@property
def area(self) -> float:
return self._area

@area.setter
def area(self, value: float):
if not isinstance(value, (int, float)):
raise ValueError(f"Area must be a number, got {type(value)}")
self._area = float(value)


@dataclass(kw_only=True)
class IHasVolume(metaclass=ABCMeta):

volume: float
_volume: float = field(init=False, repr=False)

@property
def volume(self) -> float:
return self._volume

@volume.setter
def volume(self, value: float):
if not isinstance(value, (int, float)):
raise ValueError(f"Volume must be a number, got {type(value)}")
self._volume = float(value)


# data object interfaces
class IProperties(metaclass=ABCMeta):
@property
Expand All @@ -71,7 +99,7 @@ def properties(self) -> dict[str, object]:
pass


class IDataObject(IProperties, IDisplayValue[list[Base]], metaclass=ABCMeta):
class IDataObject(IProperties, IDisplayValue[List[Base]], metaclass=ABCMeta):
@property
@abstractmethod
def name(self) -> str:
Expand Down
5 changes: 3 additions & 2 deletions src/specklepy/objects/primitive.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass
from typing import List

from specklepy.objects.base import Base

Expand All @@ -19,9 +20,9 @@ def __str__(self) -> str:
def unit_interval(cls) -> "Interval":
return cls(start=0, end=1)

def to_list(self) -> list[float]:
def to_list(self) -> List[float]:
return [self.start, self.end]

@classmethod
def from_list(cls, args: list[float]) -> "Interval":
def from_list(cls, args: List[float]) -> "Interval":
return cls(start=args[0], end=args[1])
Loading