File size: 7,538 Bytes
61e89b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import numpy as np
from scipy.spatial import ConvexHull
from scipy.optimize import linprog

# ---------- Small helpers ----------

def orthonormal_basis_from_up(up):
    up = np.asarray(up, dtype=float)
    up = up / (np.linalg.norm(up) + 1e-12)
    # pick any vector not parallel to up
    t = np.array([1.0, 0.0, 0.0]) if abs(up[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
    u0 = t - (t @ up) * up
    u0 /= (np.linalg.norm(u0) + 1e-12)
    v0 = np.cross(up, u0)
    v0 /= (np.linalg.norm(v0) + 1e-12)
    return u0, v0, up

def project_to_plane(points, u0, v0):
    U = np.stack([u0, v0], axis=1)            # 3x2
    return points @ U                          # (N,2), coordinates in (u0,v0)

def hull_halfspaces_2d(P2):
    hull = ConvexHull(P2)
    # equations: for 2D, each row [a,b,c] with a*x + b*y + c == 0 on edge, <= 0 inside
    A = hull.equations[:, :2]
    b = -hull.equations[:, 2]
    return A, b, hull

def solve_rect_lp(A, b, R2, alpha):
    """
    Maximize alpha^T h, subject to A c + |A R2| h <= b, h>=0.
    Vars: [c_x, c_y, h_x, h_y]
    """
    S = np.abs(A @ R2)                  # (m,2)
    A_ub = np.hstack([A, S])            # (m,4)
    b_ub = b.copy()
    bounds = [(-np.inf, np.inf), (-np.inf, np.inf), (0, np.inf), (0, np.inf)]
    c_vec = np.array([0.0, 0.0, -alpha[0], -alpha[1]])
    res = linprog(c=c_vec, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs")
    if not res.success:
        return None
    c2 = res.x[:2]
    h2 = res.x[2:]
    return c2, h2

def rect_vertices_3d(center3, hx, hy, u_dir, v_dir):
    signs = np.array([[-1,-1],[ -1, 1],[ 1, 1],[ 1,-1]], float)
    verts2 = signs * np.array([hx, hy])
    verts3 = center3[None,:] + verts2[:,0:1]*u_dir[None,:] + verts2[:,1:2]*v_dir[None,:]
    return verts3  # 4x3 (rectangle corners in plane, no vertical thickness)

# ---------- Main: max inscribed rectangle footprint + height ----------

def max_inscribed_rectangle_2d_box(
    centers_np,
    up=np.array([0.0, -1.0, 0.0]),
    ground_level=0.0,
    n_angles=181,           # sample 0..90° inclusive (exploits symmetry); doubled internally
    n_weights=16,           # LPs per angle (sweep trade-offs)
    seed=0
):
    """
    Finds the maximum-area rectangle (any in-plane orientation) inside the 2D projection
    of `centers_np` onto the plane orthogonal to `up`. Height is then set from ground_level
    to the highest camera along +up.

    Returns dict with:
      center (3,), half_sizes (hx,hy,hz/2), sizes (3,),
      R (3x3), quat_xyzw (4,), footprint_vertices (4,3), box_vertices (8,3), area, volume
    """
    rng = np.random.default_rng(seed)
    u0, v0, up = orthonormal_basis_from_up(up)

    # 1) 2D projection and hull halfspaces in (u0, v0) coords
    P2 = project_to_plane(centers_np, u0, v0)     # (N,2)
    A2, b2, hull2 = hull_halfspaces_2d(P2)

    # 2) Search over angles theta in [0, pi/2) due to rectangle symmetry
    thetas = np.linspace(0.0, 0.5*np.pi, n_angles)
    best = {"area": -1.0}

    # Simple Dirichlet weights over 2 dims => Beta; add a couple of axis-focused weights
    weights = list(rng.dirichlet(np.ones(2), size=n_weights))
    weights += [np.array([1.0, 0.0]), np.array([0.0, 1.0]), np.array([0.5, 0.5])]

    for theta in thetas:
        # local rectangle axes in (u0,v0) coordinates
        ct, st = np.cos(theta), np.sin(theta)
        R2 = np.array([[ct, -st],
                       [st,  ct]], dtype=float)   # maps local (x,y) to (u0,v0)

        for alpha in weights:
            sol = solve_rect_lp(A2, b2, R2, alpha)
            if sol is None:
                continue
            c2, h2 = sol
            area = float(4.0 * h2[0] * h2[1])
            if area > best["area"]:
                best = {"area": area, "theta": theta, "c2": c2, "h2": h2}

    if best["area"] <= 0:
        raise RuntimeError("Failed to inscribe a rectangle; check point configuration.")

    # 3) Build 3D pose from best solution
    theta = best["theta"]; ct, st = np.cos(theta), np.sin(theta)
    u_dir =  ct * u0 + st * v0          # rectangle local X in world
    v_dir = -st * u0 + ct * v0          # rectangle local Y in world (right-handed with up)
    c2 = best["c2"]; hx, hy = best["h2"]
    center_plane = c2[0]*u0 + c2[1]*v0

    # Height: ground -> highest camera
    cam_h = centers_np @ up
    H = float(np.max(cam_h) - ground_level)
    H = max(H, 1e-9)
    center3 = center_plane + (ground_level + 0.5*H) * up

    # Rotation matrix with columns = local axes (X=u_dir, Y=v_dir, Z=up)
    R_box = np.column_stack([u_dir, v_dir, up])
    # Quaternion xyzw (from rotmat)
    # Manual conversion (no SciPy quaternion dependency):
    def rotmat_to_quat_xyzw(M):
        t = np.trace(M)
        if t > 0:
            s = np.sqrt(t+1.0)*2
            w = 0.25*s
            x = (M[2,1]-M[1,2])/s
            y = (M[0,2]-M[2,0])/s
            z = (M[1,0]-M[0,1])/s
        else:
            i = np.argmax([M[0,0], M[1,1], M[2,2]])
            if i == 0:
                s = np.sqrt(1.0 + M[0,0] - M[1,1] - M[2,2]) * 2
                w = (M[2,1] - M[1,2]) / s
                x = 0.25 * s
                y = (M[0,1] + M[1,0]) / s
                z = (M[0,2] + M[2,0]) / s
            elif i == 1:
                s = np.sqrt(1.0 + M[1,1] - M[0,0] - M[2,2]) * 2
                w = (M[0,2] - M[2,0]) / s
                x = (M[0,1] + M[1,0]) / s
                y = 0.25 * s
                z = (M[1,2] + M[2,1]) / s
            else:
                s = np.sqrt(1.0 + M[2,2] - M[0,0] - M[1,1]) * 2
                w = (M[1,0] - M[0,1]) / s
                x = (M[0,2] + M[2,0]) / s
                y = (M[1,2] + M[2,1]) / s
                z = 0.25 * s
        return np.array([x, y, z, w], dtype=float)

    quat_xyzw = rotmat_to_quat_xyzw(R_box)

    # Vertices (footprint & full 3D box)
    footprint4 = rect_vertices_3d(center_plane, hx, hy, u_dir, v_dir)  # 4x3 at ground plane height=0 (in plane coords)
    # 8 box corners:
    rect4_top = footprint4 + H * up
    verts8 = np.vstack([footprint4, rect4_top])

    sizes3 = np.array([2*hx, 2*hy, H], dtype=float)
    return {
        "center": center3,
        "half_sizes": np.array([hx, hy, 0.5*H], dtype=float),
        "sizes": sizes3,
        "R": R_box,
        "quat_xyzw": quat_xyzw,
        "footprint_vertices": footprint4,  # 4x3 (bottom rectangle)
        "box_vertices": verts8,            # 8x3
        "area": float(4*hx*hy),
        "volume": float((2*hx)*(2*hy)*H),
        "up": up,
        "u_dir": u_dir,
        "v_dir": v_dir,
    }

# -------- Example usage --------
# result = max_inscribed_rectangle_2d_box(
#     centers_np,
#     up=np.array([0, 1, 0]),  # your "up"
#     ground_level=0.0,        # if your ground plane is y=0 (for example)
#     n_angles=181,
#     n_weights=24,
#     seed=42
# )
# c = result["center"]; sizes = result["sizes"]; R = result["R"]; q = result["quat_xyzw"]
# print("center:", c, "sizes (W,D,H):", sizes)

def point_in_convex_hull_2d(points_xy, query_xy, tol=1e-12):
    """
    points_xy: (N,2) cloud
    query_xy:  (...,2) points to test
    Returns: boolean array with shape query_xy.shape[:-1]
    """
    hull = ConvexHull(points_xy)
    # hull.equations: rows [a, b, c] with a*x + b*y + c == 0 on edge, <= 0 inside
    A = hull.equations[:, :2]
    c = hull.equations[:, 2]
    q = np.atleast_2d(query_xy)            # (M,2)
    vals = (A @ q.T) + c[:, None]          # (num_edges, M)
    inside = np.all(vals <= tol, axis=0)   # inside if all halfspaces satisfied
    return inside.reshape(query_xy.shape[:-1])