First commit
This commit is contained in:
Executable
+2301
File diff suppressed because it is too large
Load Diff
Executable
+1
@@ -0,0 +1 @@
|
||||
uid://ievsqm6w1ks4
|
||||
Executable
+670
@@ -0,0 +1,670 @@
|
||||
@tool
|
||||
class_name PdGeo
|
||||
## Static geometry helpers for Polydoodle.
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- edges ---
|
||||
static func loop_edges(loop: PackedInt32Array) -> Array:
|
||||
var out: Array = []
|
||||
var n := loop.size()
|
||||
if n < 2:
|
||||
return out
|
||||
for i in n:
|
||||
var a := loop[i]
|
||||
var b := loop[(i + 1) % n]
|
||||
if a == b:
|
||||
continue
|
||||
out.append(Vector2i(mini(a, b), maxi(a, b)))
|
||||
return out
|
||||
|
||||
|
||||
static func unique_edges(faces: Array) -> Array:
|
||||
var seen := {}
|
||||
var out: Array = []
|
||||
for f in faces:
|
||||
for e in loop_edges(f):
|
||||
if not seen.has(e):
|
||||
seen[e] = true
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
# -------------------------------------------------------------- normals ---
|
||||
static func face_normal(pts: PackedVector3Array) -> Vector3:
|
||||
# Newell's method; robust for concave loops.
|
||||
var n := Vector3.ZERO
|
||||
var c := pts.size()
|
||||
if c < 3:
|
||||
return Vector3.ZERO
|
||||
for i in c:
|
||||
var a := pts[i]
|
||||
var b := pts[(i + 1) % c]
|
||||
n.x += (a.y - b.y) * (a.z + b.z)
|
||||
n.y += (a.z - b.z) * (a.x + b.x)
|
||||
n.z += (a.x - b.x) * (a.y + b.y)
|
||||
if n.length() < 1e-9:
|
||||
return Vector3.ZERO
|
||||
return n.normalized()
|
||||
|
||||
|
||||
static func face_center(pts: PackedVector3Array) -> Vector3:
|
||||
var c := Vector3.ZERO
|
||||
for p in pts:
|
||||
c += p
|
||||
return c / float(maxi(1, pts.size()))
|
||||
|
||||
|
||||
# ------------------------------------------------------- triangulation ---
|
||||
## True when a triangle is safe to hand to CanvasItem.draw_polygon /
|
||||
## draw_colored_polygon. Godot triangulates those polygons internally and
|
||||
## prints "ERROR: Invalid polygon data, triangulation failed." for every
|
||||
## zero-area or NaN input - degenerate face triangles (a vertex dragged
|
||||
## through the mesh, bowtie quads) must be filtered out BEFORE drawing,
|
||||
## or the editor spams that error on every redraw.
|
||||
static func tri_drawable(a: Vector2, b: Vector2, c: Vector2) -> bool:
|
||||
if is_nan(a.x) or is_nan(a.y) or is_nan(b.x) or is_nan(b.y) \
|
||||
or is_nan(c.x) or is_nan(c.y):
|
||||
return false
|
||||
if a.distance_squared_to(b) < 1e-14 \
|
||||
or b.distance_squared_to(c) < 1e-14 \
|
||||
or a.distance_squared_to(c) < 1e-14:
|
||||
return false
|
||||
return absf((b - a).cross(c - a)) > 1e-4
|
||||
|
||||
|
||||
static func _signed_area2(p2: PackedVector2Array) -> float:
|
||||
var a := 0.0
|
||||
var n := p2.size()
|
||||
for i in n:
|
||||
var p := p2[i]
|
||||
var q := p2[(i + 1) % n]
|
||||
a += p.x * q.y - q.x * p.y
|
||||
return a * 0.5
|
||||
|
||||
|
||||
static func _point_in_tri(a: Vector2, b: Vector2, c: Vector2, p: Vector2) -> bool:
|
||||
var d1 := (b - a).cross(p - a)
|
||||
var d2 := (c - b).cross(p - b)
|
||||
var d3 := (a - c).cross(p - c)
|
||||
var has_neg := d1 < -1e-9 or d2 < -1e-9 or d3 < -1e-9
|
||||
var has_pos := d1 > 1e-9 or d2 > 1e-9 or d3 > 1e-9
|
||||
return not (has_neg and has_pos)
|
||||
|
||||
|
||||
static func triangulate(pts3: PackedVector3Array) -> PackedInt32Array:
|
||||
# Ear clipping projected onto the face plane; output winding follows
|
||||
# the polygon's own winding. Falls back to a fan for degenerate loops.
|
||||
var out := PackedInt32Array()
|
||||
var n := pts3.size()
|
||||
if n < 3:
|
||||
return out
|
||||
if n == 3:
|
||||
return PackedInt32Array([0, 1, 2])
|
||||
var nrm := face_normal(pts3)
|
||||
if nrm == Vector3.ZERO:
|
||||
for i in range(1, n - 1):
|
||||
out.append_array(PackedInt32Array([0, i, i + 1]))
|
||||
return out
|
||||
var u := Vector3.RIGHT
|
||||
for i in range(1, n):
|
||||
var t := pts3[i] - pts3[0]
|
||||
if t.length() > 1e-7:
|
||||
u = t.normalized()
|
||||
break
|
||||
var v := nrm.cross(u).normalized()
|
||||
var p2 := PackedVector2Array()
|
||||
p2.resize(n)
|
||||
for i in n:
|
||||
var d := pts3[i] - pts3[0]
|
||||
p2[i] = Vector2(d.dot(u), d.dot(v))
|
||||
# normalize winding to CCW and remember the remap
|
||||
var remap := PackedInt32Array()
|
||||
remap.resize(n)
|
||||
for i in n:
|
||||
remap[i] = i
|
||||
if _signed_area2(p2) < 0.0:
|
||||
p2.reverse()
|
||||
for i in n:
|
||||
remap[i] = n - 1 - i
|
||||
var tris: PackedInt32Array = _ear_clip(p2)["tris"]
|
||||
for t in tris:
|
||||
out.append(remap[t])
|
||||
return out
|
||||
|
||||
|
||||
static func _ear_clip(p2: PackedVector2Array) -> Dictionary:
|
||||
# Returns {"tris": PackedInt32Array, "complete": bool}. `complete` is
|
||||
# false when the clipper had to fall back to a fan (or finish a
|
||||
# leftover loop with one) - the caller uses that to decide whether to
|
||||
# attempt a self-intersection split.
|
||||
var n := p2.size()
|
||||
var idx := PackedInt32Array()
|
||||
idx.resize(n)
|
||||
for i in n:
|
||||
idx[i] = i
|
||||
var out := PackedInt32Array()
|
||||
var complete := true
|
||||
var guard := 0
|
||||
while idx.size() > 3 and guard < 4096:
|
||||
guard += 1
|
||||
var clipped := false
|
||||
var m := idx.size()
|
||||
for k in m:
|
||||
var i0 := idx[(k + m - 1) % m]
|
||||
var i1 := idx[k]
|
||||
var i2 := idx[(k + 1) % m]
|
||||
var a := p2[i0]
|
||||
var b := p2[i1]
|
||||
var c := p2[i2]
|
||||
if (b - a).cross(c - a) <= 1e-9:
|
||||
continue
|
||||
var ear := true
|
||||
for j in idx:
|
||||
var p := p2[j]
|
||||
if p == a or p == b or p == c:
|
||||
continue
|
||||
if _point_in_tri(a, b, c, p):
|
||||
ear = false
|
||||
break
|
||||
if ear:
|
||||
out.append_array(PackedInt32Array([i0, i1, i2]))
|
||||
idx.remove_at(k)
|
||||
clipped = true
|
||||
break
|
||||
if not clipped:
|
||||
complete = false
|
||||
break
|
||||
if idx.size() == 3:
|
||||
out.append_array(PackedInt32Array([idx[0], idx[1], idx[2]]))
|
||||
elif idx.size() > 3:
|
||||
# could not finish clipping (self-intersection or numerical
|
||||
# trouble): fan whatever loop is left so no vertex is lost
|
||||
complete = false
|
||||
var m := idx.size()
|
||||
for i in range(1, m - 1):
|
||||
out.append_array(PackedInt32Array([idx[0], idx[i], idx[i + 1]]))
|
||||
elif out.is_empty():
|
||||
# Degenerate loop: fan fallback.
|
||||
complete = false
|
||||
var m := p2.size()
|
||||
for i in range(1, m - 1):
|
||||
out.append_array(PackedInt32Array([0, i, i + 1]))
|
||||
return {"tris": out, "complete": complete}
|
||||
|
||||
|
||||
# ---------------------------------------------------- robust triangulation ---
|
||||
## Segment-segment intersection. Returns {"t","u"} with the crossing at
|
||||
## a + (b-a)*t == c + (d-c)*u, or {} when the segments do not cross.
|
||||
static func _seg_hit(a: Vector2, b: Vector2, c: Vector2, d: Vector2) -> Dictionary:
|
||||
var r := b - a
|
||||
var s := d - c
|
||||
var denom := r.cross(s)
|
||||
if absf(denom) < 1e-12:
|
||||
return {}
|
||||
var ac := c - a
|
||||
var t := ac.cross(s) / denom
|
||||
var u := ac.cross(r) / denom
|
||||
if t < -1e-9 or t > 1.0 + 1e-9 or u < -1e-9 or u > 1.0 + 1e-9:
|
||||
return {}
|
||||
return {"t": t, "u": u}
|
||||
|
||||
|
||||
## First self-crossing between two non-adjacent edges of a closed 2D loop.
|
||||
## Returns {"i","j","t"} (crossing on edge i at parameter t) or {}.
|
||||
static func _first_crossing(p2: PackedVector2Array) -> Dictionary:
|
||||
var n := p2.size()
|
||||
if n < 4 or n > 900:
|
||||
return {}
|
||||
for i in n:
|
||||
var a := p2[i]
|
||||
var b := p2[(i + 1) % n]
|
||||
for j in range(i + 2, n):
|
||||
if i == 0 and j == n - 1:
|
||||
continue # adjacent through the wraparound
|
||||
var c := p2[j]
|
||||
var d := p2[(j + 1) % n]
|
||||
var hit := _seg_hit(a, b, c, d)
|
||||
if not hit.is_empty():
|
||||
hit["i"] = i
|
||||
hit["j"] = j
|
||||
return hit
|
||||
return {}
|
||||
|
||||
|
||||
## Projection basis (u, v) for a vertex index loop - the loop's own plane.
|
||||
static func _loop_basis(verts: PackedVector3Array, ids: Array) -> Array:
|
||||
var pts := PackedVector3Array()
|
||||
pts.resize(ids.size())
|
||||
for k in ids.size():
|
||||
pts[k] = verts[ids[k]]
|
||||
var nrm := face_normal(pts)
|
||||
if nrm == Vector3.ZERO:
|
||||
nrm = Vector3.UP
|
||||
var u := Vector3.RIGHT
|
||||
for k in ids.size():
|
||||
var t: Vector3 = verts[ids[k]] - verts[ids[0]]
|
||||
if t.length() > 1e-7:
|
||||
u = t.normalized()
|
||||
break
|
||||
var v := nrm.cross(u).normalized()
|
||||
return [u, v]
|
||||
|
||||
|
||||
static func _dedupe_loop(verts: PackedVector3Array, idxs: Array) -> Array:
|
||||
# Drop consecutive duplicates (freehand strokes often re-touch their
|
||||
# start point) - zero-area ears would stall the clipper.
|
||||
var ids: Array = []
|
||||
for k in idxs.size():
|
||||
var vi: int = idxs[k]
|
||||
if vi < 0 or vi >= verts.size():
|
||||
continue
|
||||
if not ids.is_empty() and verts[ids[ids.size() - 1]] \
|
||||
.distance_squared_to(verts[vi]) < 1e-12:
|
||||
continue
|
||||
if k == idxs.size() - 1 and not ids.is_empty() \
|
||||
and verts[ids[0]].distance_squared_to(verts[vi]) < 1e-12:
|
||||
continue
|
||||
ids.append(vi)
|
||||
return ids
|
||||
|
||||
|
||||
static func _concat_i(a: PackedInt32Array, b: PackedInt32Array) -> PackedInt32Array:
|
||||
a.append_array(b)
|
||||
return a
|
||||
|
||||
|
||||
## Robust triangulation of a POSSIBLY SELF-INTERSECTING polygon loop
|
||||
## (freehand doodles cross themselves all the time). The loop is split at
|
||||
## crossing points into simple sub-loops and each is ear-clipped, so the
|
||||
## fill covers the union of the drawn loops - a figure-eight fills both
|
||||
## lobes, a scribble fills every enclosed pocket. No engine triangulator
|
||||
## is ever invoked, so "Invalid polygon data" errors cannot happen.
|
||||
##
|
||||
## Returns {"verts": PackedVector3Array, "tris": PackedInt32Array}.
|
||||
## verts may be LONGER than the input (crossing points are appended);
|
||||
## tris index into verts. Winding follows the polygon's own normal side.
|
||||
static func triangulate_robust(pts3: PackedVector3Array) -> Dictionary:
|
||||
if pts3.size() < 3:
|
||||
return {"verts": PackedVector3Array(pts3), "tris": PackedInt32Array()}
|
||||
return _tri_recurse(pts3, _seq(pts3.size()), 0, [])
|
||||
|
||||
|
||||
static func _seq(n: int) -> Array:
|
||||
var a: Array = []
|
||||
a.resize(n)
|
||||
for i in n:
|
||||
a[i] = i
|
||||
return a
|
||||
|
||||
|
||||
static func _tri_recurse(verts: PackedVector3Array, idxs: Array,
|
||||
depth: int, basis: Array) -> Dictionary:
|
||||
var ids := _dedupe_loop(verts, idxs)
|
||||
if ids.size() < 3:
|
||||
return {"verts": verts, "tris": PackedInt32Array()}
|
||||
if basis.is_empty():
|
||||
basis = _loop_basis(verts, ids)
|
||||
var u: Vector3 = basis[0]
|
||||
var v: Vector3 = basis[1]
|
||||
var p0: Vector3 = verts[ids[0]]
|
||||
var p2 := PackedVector2Array()
|
||||
p2.resize(ids.size())
|
||||
for k in ids.size():
|
||||
var d: Vector3 = verts[ids[k]] - p0
|
||||
p2[k] = Vector2(d.dot(u), d.dot(v))
|
||||
if _signed_area2(p2) < 0.0:
|
||||
ids.reverse()
|
||||
for k in ids.size():
|
||||
var d: Vector3 = verts[ids[k]] - p0
|
||||
p2[k] = Vector2(d.dot(u), d.dot(v))
|
||||
var clipped: Dictionary = _ear_clip(p2)
|
||||
var tris: PackedInt32Array = clipped["tris"]
|
||||
if not clipped["complete"] and depth < 24:
|
||||
var cross := _first_crossing(p2)
|
||||
if not cross.is_empty():
|
||||
var i: int = cross["i"]
|
||||
var j: int = cross["j"]
|
||||
var t: float = cross["t"]
|
||||
# 3D crossing point: both edges lie in the loop plane,
|
||||
# so interpolating along edge i lands exactly on it.
|
||||
var p3: Vector3 = verts[ids[i]] \
|
||||
.lerp(verts[ids[(i + 1) % ids.size()]], t)
|
||||
var verts2 := PackedVector3Array(verts)
|
||||
var new_i := verts2.size()
|
||||
verts2.append(p3)
|
||||
var loop_a: Array = []
|
||||
for k in range(0, i + 1):
|
||||
loop_a.append(ids[k])
|
||||
loop_a.append(new_i)
|
||||
for k in range(j + 1, ids.size()):
|
||||
loop_a.append(ids[k])
|
||||
var loop_b: Array = [new_i]
|
||||
for k in range(i + 1, j + 1):
|
||||
loop_b.append(ids[k])
|
||||
var ra := _tri_recurse(verts2, loop_a, depth + 1, basis)
|
||||
var rb := _tri_recurse(ra["verts"], loop_b, depth + 1, basis)
|
||||
return {"verts": rb["verts"],
|
||||
"tris": _concat_i(ra["tris"], rb["tris"])}
|
||||
var out := PackedInt32Array()
|
||||
for t in tris:
|
||||
out.append(ids[t])
|
||||
return {"verts": verts, "tris": out}
|
||||
|
||||
|
||||
# ------------------------------------------------------------ polygon ---
|
||||
static func point_in_poly2(poly: PackedVector2Array, p: Vector2) -> bool:
|
||||
var inside := false
|
||||
var n := poly.size()
|
||||
if n < 3:
|
||||
return false
|
||||
var j := n - 1
|
||||
for i in n:
|
||||
var a := poly[i]
|
||||
var b := poly[j]
|
||||
if (a.y > p.y) != (b.y > p.y):
|
||||
var t := (p.y - a.y) / (b.y - a.y)
|
||||
if p.x < a.x + t * (b.x - a.x):
|
||||
inside = not inside
|
||||
j = i
|
||||
return inside
|
||||
|
||||
|
||||
static func dist_to_seg(p: Vector2, a: Vector2, b: Vector2) -> float:
|
||||
var ab := b - a
|
||||
var l2 := ab.length_squared()
|
||||
if l2 < 1e-9:
|
||||
return p.distance_to(a)
|
||||
var t := clampf((p - a).dot(ab) / l2, 0.0, 1.0)
|
||||
return p.distance_to(a + ab * t)
|
||||
|
||||
|
||||
# ---------------------------------------------------- barycentric UV ---
|
||||
## Barycentric coordinates of `p` inside triangle (a, b, c), computed in
|
||||
## 2D. Barycentric coords are affine-invariant, so they can be computed in
|
||||
## ANY projection of the triangle (e.g. the dominant-axis projection of a
|
||||
## 3D face) and applied to a differently-warped image of the same triangle
|
||||
## - which is exactly how the texture mapping stays consistent with the
|
||||
## GPU's per-vertex interpolation. Returns (-1,-1,-1) for degenerate tris.
|
||||
static func bary2(a: Vector2, b: Vector2, c: Vector2, p: Vector2) -> Vector3:
|
||||
var d := (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y)
|
||||
if absf(d) < 1e-12:
|
||||
return Vector3(-1, -1, -1)
|
||||
var l1 := ((b.y - c.y) * (p.x - c.x) + (c.x - b.x) * (p.y - c.y)) / d
|
||||
var l2 := ((c.y - a.y) * (p.x - c.x) + (a.x - c.x) * (p.y - c.y)) / d
|
||||
return Vector3(l1, l2, 1.0 - l1 - l2)
|
||||
|
||||
|
||||
## True when `lam` (from bary2) places the point inside (or on the edge
|
||||
## of) the triangle, with a small negative tolerance for edge texels.
|
||||
static func bary_inside(lam: Vector3, eps := 1.0 / 4096.0) -> bool:
|
||||
return lam.x >= -eps and lam.y >= -eps and lam.z >= -eps
|
||||
|
||||
|
||||
static func rdp(points: PackedVector2Array, eps: float) -> PackedVector2Array:
|
||||
# Ramer-Douglas-Peucker simplification (iterative).
|
||||
var n := points.size()
|
||||
if n < 3:
|
||||
return PackedVector2Array(points)
|
||||
var keep := PackedByteArray()
|
||||
keep.resize(n)
|
||||
for i in n:
|
||||
keep[i] = 0
|
||||
keep[0] = 1
|
||||
keep[n - 1] = 1
|
||||
var stack: Array = [[0, n - 1]]
|
||||
while not stack.is_empty():
|
||||
var job: Array = stack.pop_back()
|
||||
var s := int(job[0])
|
||||
var e := int(job[1])
|
||||
if e <= s + 1:
|
||||
continue
|
||||
var best := -1.0
|
||||
var best_i := -1
|
||||
for i in range(s + 1, e):
|
||||
var d := dist_to_seg(points[i], points[s], points[e])
|
||||
if d > best:
|
||||
best = d
|
||||
best_i = i
|
||||
if best > eps and best_i > 0:
|
||||
keep[best_i] = 1
|
||||
stack.append([s, best_i])
|
||||
stack.append([best_i, e])
|
||||
var out := PackedVector2Array()
|
||||
for i in n:
|
||||
if keep[i] == 1:
|
||||
out.append(points[i])
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ray ---
|
||||
static func ray_tri(o: Vector3, d: Vector3, a: Vector3, b: Vector3, c: Vector3) -> float:
|
||||
# Moller-Trumbore; returns distance along d, or -1.0.
|
||||
var e1 := b - a
|
||||
var e2 := c - a
|
||||
var p := d.cross(e2)
|
||||
var det := e1.dot(p)
|
||||
if absf(det) < 1e-9:
|
||||
return -1.0
|
||||
var inv := 1.0 / det
|
||||
var t := o - a
|
||||
var u := t.dot(p) * inv
|
||||
if u < -1e-6 or u > 1.0 + 1e-6:
|
||||
return -1.0
|
||||
var q := t.cross(e1)
|
||||
var vv := d.dot(q) * inv
|
||||
if vv < -1e-6 or u + vv > 1.0 + 1e-6:
|
||||
return -1.0
|
||||
var dist := e2.dot(q) * inv
|
||||
if dist < 1e-6:
|
||||
return -1.0
|
||||
return dist
|
||||
|
||||
|
||||
static func closest_ray_line(o: Vector3, d: Vector3, p0: Vector3, dir: Vector3) -> Dictionary:
|
||||
# Closest points between a ray (o,d) and an infinite line (p0,dir).
|
||||
var dir2 := dir.normalized()
|
||||
var w0 := o - p0
|
||||
var a := d.dot(d)
|
||||
var b := d.dot(dir2)
|
||||
var cc := dir2.dot(dir2)
|
||||
var dd := d.dot(w0)
|
||||
var e := dir2.dot(w0)
|
||||
var denom := a * cc - b * b
|
||||
var t_ray := 0.0
|
||||
var t_line := 0.0
|
||||
if absf(denom) < 1e-9:
|
||||
t_ray = 0.0
|
||||
t_line = e / maxf(cc, 1e-9)
|
||||
else:
|
||||
t_ray = (b * e - cc * dd) / denom
|
||||
t_line = (a * e - b * dd) / denom
|
||||
t_ray = maxf(t_ray, 0.0)
|
||||
return {
|
||||
"ray": o + d * t_ray,
|
||||
"line": p0 + dir2 * t_line,
|
||||
"t_line": t_line,
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------- shape makers ---
|
||||
|
||||
static func _orient_out(verts: PackedVector3Array, faces: Array, want := Vector3.ZERO) -> void:
|
||||
# Flip any face loop whose Newell normal disagrees with the outward
|
||||
# direction (radial from `want` origin).
|
||||
for fi in faces.size():
|
||||
var loop: PackedInt32Array = faces[fi]
|
||||
var pts := PackedVector3Array()
|
||||
for vi in loop:
|
||||
pts.append(verts[vi])
|
||||
var n := face_normal(pts)
|
||||
if n == Vector3.ZERO:
|
||||
continue
|
||||
var c := face_center(pts)
|
||||
var dir := c - want
|
||||
if dir.length() < 1e-9:
|
||||
dir = want
|
||||
if n.dot(dir.normalized()) < 0.0:
|
||||
loop.reverse()
|
||||
faces[fi] = loop
|
||||
|
||||
|
||||
|
||||
static func make_cube(s: float = 1.0) -> Dictionary:
|
||||
var h := s * 0.5
|
||||
var v := PackedVector3Array([
|
||||
Vector3(-h, -h, -h), Vector3(h, -h, -h), Vector3(h, h, -h), Vector3(-h, h, -h),
|
||||
Vector3(-h, -h, h), Vector3(h, -h, h), Vector3(h, h, h), Vector3(-h, h, h),
|
||||
])
|
||||
var faces: Array = [
|
||||
PackedInt32Array([3, 2, 6, 7]), # +Y
|
||||
PackedInt32Array([0, 1, 5, 4]), # -Y
|
||||
PackedInt32Array([1, 2, 6, 5]), # +X
|
||||
PackedInt32Array([0, 4, 7, 3]), # -X
|
||||
PackedInt32Array([4, 5, 6, 7]), # +Z
|
||||
PackedInt32Array([1, 0, 3, 2]), # -Z
|
||||
]
|
||||
_orient_out(v, faces, Vector3.ZERO)
|
||||
return {"verts": v, "faces": faces}
|
||||
|
||||
|
||||
static func make_plane(w: float = 1.0, d: float = 1.0, seg: int = 1) -> Dictionary:
|
||||
seg = maxi(1, seg)
|
||||
var v := PackedVector3Array()
|
||||
var faces: Array = []
|
||||
var n := seg + 1
|
||||
for j in n:
|
||||
for i in n:
|
||||
v.append(Vector3(
|
||||
(i / float(seg) - 0.5) * w, 0.0,
|
||||
(j / float(seg) - 0.5) * d))
|
||||
for j in seg:
|
||||
for i in seg:
|
||||
var a := j * n + i
|
||||
faces.append(PackedInt32Array([a, a + 1, a + n + 1, a + n]))
|
||||
_orient_out(v, faces, Vector3.UP)
|
||||
return {"verts": v, "faces": faces}
|
||||
|
||||
|
||||
static func make_prism(s: float = 1.0) -> Dictionary:
|
||||
var h := s * 0.5
|
||||
var v := PackedVector3Array([
|
||||
Vector3(-h, -h, -h * 0.866), Vector3(h, -h, -h * 0.866), Vector3(0, -h, h * 0.866),
|
||||
Vector3(-h, h, -h * 0.866), Vector3(h, h, -h * 0.866), Vector3(0, h, h * 0.866),
|
||||
])
|
||||
var faces: Array = [
|
||||
PackedInt32Array([3, 4, 5]), # +Y
|
||||
PackedInt32Array([0, 2, 1]), # -Y
|
||||
PackedInt32Array([0, 1, 4, 3]), # -Z
|
||||
PackedInt32Array([1, 2, 5, 4]), # +X-ish
|
||||
PackedInt32Array([2, 0, 3, 5]), # -X-ish
|
||||
]
|
||||
_orient_out(v, faces, Vector3.ZERO)
|
||||
return {"verts": v, "faces": faces}
|
||||
|
||||
|
||||
static func make_cylinder(r: float = 0.5, h: float = 1.0, seg: int = 12) -> Dictionary:
|
||||
seg = clampi(seg, 3, 64)
|
||||
var v := PackedVector3Array()
|
||||
var faces: Array = []
|
||||
for i in seg:
|
||||
var a := TAU * i / seg
|
||||
v.append(Vector3(cos(a) * r, -h * 0.5, sin(a) * r))
|
||||
for i in seg:
|
||||
var a := TAU * i / seg
|
||||
v.append(Vector3(cos(a) * r, h * 0.5, sin(a) * r))
|
||||
for i in seg:
|
||||
var j := (i + 1) % seg
|
||||
faces.append(PackedInt32Array([i, j, seg + j, seg + i]))
|
||||
var cap_bottom := PackedInt32Array()
|
||||
for i in seg:
|
||||
cap_bottom.append(seg - 1 - i)
|
||||
faces.append(cap_bottom)
|
||||
var cap_top := PackedInt32Array()
|
||||
for i in seg:
|
||||
cap_top.append(seg + i)
|
||||
faces.append(cap_top)
|
||||
_orient_out(v, faces, Vector3.ZERO)
|
||||
return {"verts": v, "faces": faces}
|
||||
|
||||
|
||||
static func make_sphere(r: float = 0.5, seg: int = 10) -> Dictionary:
|
||||
seg = clampi(seg, 4, 32)
|
||||
var rings := maxi(3, seg / 2)
|
||||
var v := PackedVector3Array()
|
||||
var faces: Array = []
|
||||
v.append(Vector3(0, -r, 0)) # south pole, index 0
|
||||
for j in range(1, rings):
|
||||
var phi := -PI * 0.5 + PI * j / rings
|
||||
for i in seg:
|
||||
var a := TAU * i / seg
|
||||
v.append(Vector3(cos(a) * cos(phi) * r, sin(phi) * r, sin(a) * cos(phi) * r))
|
||||
v.append(Vector3(0, r, 0)) # north pole
|
||||
var top := v.size() - 1
|
||||
var ring_start := func(j: int) -> int: return 1 + (j - 1) * seg
|
||||
# Bottom cap (ring 1 = indices 1..seg).
|
||||
var r1 := ring_start.call(1)
|
||||
for i in seg:
|
||||
faces.append(PackedInt32Array([0, r1 + (i + 1) % seg, r1 + i]))
|
||||
# Middle quads between consecutive rings.
|
||||
for j in range(1, rings - 1):
|
||||
var ra := ring_start.call(j)
|
||||
var rb := ring_start.call(j + 1)
|
||||
for i in seg:
|
||||
var i2 := (i + 1) % seg
|
||||
faces.append(PackedInt32Array([ra + i, ra + i2, rb + i2, rb + i]))
|
||||
# Top cap.
|
||||
var rl := ring_start.call(rings - 1)
|
||||
for i in seg:
|
||||
faces.append(PackedInt32Array([top, rl + i, rl + (i + 1) % seg]))
|
||||
_orient_out(v, faces, Vector3.ZERO)
|
||||
return {"verts": v, "faces": faces}
|
||||
|
||||
|
||||
static func make_torus(R: float = 0.5, r: float = 0.18,
|
||||
seg_main: int = 16, seg_minor: int = 8) -> Dictionary:
|
||||
# Torus lying in the XZ plane, tube around the Y axis, centered at origin.
|
||||
seg_main = clampi(seg_main, 3, 48)
|
||||
seg_minor = clampi(seg_minor, 3, 24)
|
||||
var v := PackedVector3Array()
|
||||
var faces: Array = []
|
||||
for i in seg_main:
|
||||
var a := TAU * i / seg_main
|
||||
var ca := cos(a)
|
||||
var sa := sin(a)
|
||||
for j in seg_minor:
|
||||
var b := TAU * j / seg_minor
|
||||
var rr := R + r * cos(b)
|
||||
v.append(Vector3(ca * rr, r * sin(b), sa * rr))
|
||||
for i in seg_main:
|
||||
var i2 := (i + 1) % seg_main
|
||||
for j in seg_minor:
|
||||
var j2 := (j + 1) % seg_minor
|
||||
faces.append(PackedInt32Array([
|
||||
i * seg_minor + j, i2 * seg_minor + j,
|
||||
i2 * seg_minor + j2, i * seg_minor + j2]))
|
||||
_orient_out(v, faces, Vector3.ZERO)
|
||||
return {"verts": v, "faces": faces}
|
||||
|
||||
|
||||
# ------------------------------------------------- doodle generators ---
|
||||
## Regular n-gon inscribed in the rect (0,0)-(w,h), point up.
|
||||
static func ngon_pts(n: int, w: float, h: float) -> PackedVector2Array:
|
||||
var out := PackedVector2Array()
|
||||
var cx := w * 0.5
|
||||
var cy := h * 0.5
|
||||
for i in maxi(3, n):
|
||||
var a := -PI * 0.5 + TAU * i / maxi(3, n)
|
||||
out.append(Vector2(cx + cos(a) * w * 0.5, cy + sin(a) * h * 0.5))
|
||||
return out
|
||||
|
||||
|
||||
## 5-point star inscribed in the rect, point up.
|
||||
static func star_pts(w: float, h: float) -> PackedVector2Array:
|
||||
var out := PackedVector2Array()
|
||||
var cx := w * 0.5
|
||||
var cy := h * 0.5
|
||||
for i in 10:
|
||||
var a := -PI * 0.5 + PI * i / 5.0
|
||||
var k := 1.0 if i % 2 == 0 else 0.42
|
||||
out.append(Vector2(cx + cos(a) * w * 0.5 * k, cy + sin(a) * h * 0.5 * k))
|
||||
return out
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
uid://cs0j06a8nqdx5
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
@tool
|
||||
class_name PdIcons
|
||||
## Icon loader. The icons are REAL PNG image files stored in
|
||||
## res://addons/polydoodle/icons/ - generated once, shipped with the
|
||||
## plugin, editable by anyone with an image editor. They are read as raw
|
||||
## bytes through FileAccess (NOT the resource loader), so the plugin has
|
||||
## zero dependency on Godot's import system: no first-boot import errors,
|
||||
## works straight from a fresh unzip.
|
||||
|
||||
const DIR := "res://addons/polydoodle/icons/"
|
||||
|
||||
const NAMES := [
|
||||
"icon", "ws_3d", "ws_uv",
|
||||
"mode_object", "mode_vertex", "mode_edge", "mode_face",
|
||||
"mode_draw", "mode_paint", "draw_tools", "paint_tools",
|
||||
"tool_freehand", "tool_rect", "tool_circle", "tool_triangle",
|
||||
"tool_pentagon", "tool_hexagon", "tool_star", "tool_torus",
|
||||
"tool_brush", "tool_fill", "tool_fillobject", "tool_pixel",
|
||||
"tool_eraser", "tool_picker", "tool_replace",
|
||||
"tool_uv", "uv_reset",
|
||||
"gizmo", "gizmo_move", "gizmo_scale", "gizmo_rotate",
|
||||
"snap", "grid", "doubleside",
|
||||
"add", "duplicate", "delete",
|
||||
"undo", "redo", "save", "open", "export",
|
||||
"arrow_down", "flip", "expand",
|
||||
"eye", "eye_off", "lock", "unlock",
|
||||
"gear", "docs", "rotate", "detach", "image", "import_model",
|
||||
]
|
||||
|
||||
static var _cache := {}
|
||||
|
||||
|
||||
static func get_icon(icon_name: String) -> Texture2D:
|
||||
return _load_sized(icon_name, 0)
|
||||
|
||||
|
||||
## Same icon, resized to an exact `size` x `size` square BEFORE the
|
||||
## texture is built. Needed anywhere Godot's own control has no icon-size
|
||||
## theme knob to scale a source texture down - e.g. Tree.add_button()
|
||||
## always draws its icon at the PNG's native pixel size, so the hierarchy
|
||||
## panel's eye/lock buttons looked huge next to the 16px toolbar icons
|
||||
## (which get scaled down via the "icon_max_width" theme constant that
|
||||
## Button supports but Tree's per-cell buttons do not). Pre-resizing the
|
||||
## source image keeps every icon in the UI at the SAME visual size
|
||||
## regardless of which control ends up drawing it.
|
||||
static func get_icon_sized(icon_name: String, size: int) -> Texture2D:
|
||||
return _load_sized(icon_name, size)
|
||||
|
||||
|
||||
static func _load_sized(icon_name: String, size: int) -> Texture2D:
|
||||
var key := icon_name.trim_suffix(".svg").trim_suffix(".png")
|
||||
var cache_key := key if size <= 0 else "%s@%d" % [key, size]
|
||||
if _cache.has(cache_key):
|
||||
return _cache[cache_key]
|
||||
var path := DIR + key + ".png"
|
||||
var tex: Texture2D = null
|
||||
if FileAccess.file_exists(path):
|
||||
var f := FileAccess.open(path, FileAccess.READ)
|
||||
if f != null:
|
||||
var bytes := f.get_buffer(f.get_length())
|
||||
f.close()
|
||||
var img := Image.new()
|
||||
if img.load_png_from_buffer(bytes) == OK:
|
||||
if size > 0 and (img.get_width() != size
|
||||
or img.get_height() != size):
|
||||
img.resize(size, size, Image.INTERPOLATE_LANCZOS)
|
||||
tex = ImageTexture.create_from_image(img)
|
||||
if tex == null:
|
||||
push_warning("Polydoodle: missing icon '%s'" % key)
|
||||
_cache[cache_key] = tex
|
||||
return tex
|
||||
|
||||
|
||||
## True when every icon file exists - used by the test suite.
|
||||
static func all_present() -> bool:
|
||||
for n in NAMES:
|
||||
if not FileAccess.file_exists(DIR + n + ".png"):
|
||||
return false
|
||||
return true
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
uid://vttbbohp04p0
|
||||
Executable
+1146
File diff suppressed because it is too large
Load Diff
Executable
+1
@@ -0,0 +1 @@
|
||||
uid://5ntgg2uadv1c
|
||||
Executable
+555
@@ -0,0 +1,555 @@
|
||||
@tool
|
||||
class_name PdIo
|
||||
## Export & project I/O for Polydoodle: ArrayMesh, .tres, .obj (+ .mtl and
|
||||
## texture PNG), .tscn, add-to-scene, and native .pdoodle project files.
|
||||
|
||||
|
||||
static func build_mesh(o: PdPolyObj, fallback := PdPolyObj.BASE,
|
||||
both_sides := true, use_texture := true,
|
||||
pixel_filter := false, alpha_tex := false) -> ArrayMesh:
|
||||
var st := SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
var vc := 0
|
||||
var tex_w := 0.0
|
||||
if use_texture:
|
||||
o.ensure_uv()
|
||||
# the atlas ALWAYS has a visual: the empty texture slot
|
||||
# renders through the generated checkerboard placeholder
|
||||
# (a transparent blank when the checker is hidden)
|
||||
tex_w = float(o.atlas_size())
|
||||
# Per-object SHADE SMOOTH: average the face normals at every mesh
|
||||
# vertex so shared corners shade continuously. Flat (default) keeps
|
||||
# the hard per-face normal everywhere.
|
||||
var smooth_on: bool = o.shade_smooth
|
||||
var vnorm := {}
|
||||
if smooth_on:
|
||||
for fi2 in o.nfaces():
|
||||
var n2 := o.face_normal_w(fi2)
|
||||
if n2 == Vector3.ZERO:
|
||||
continue
|
||||
for vi in o.face_loop(fi2):
|
||||
vnorm[vi] = (vnorm.get(vi, Vector3.ZERO) as Vector3) + n2
|
||||
for fi in o.nfaces():
|
||||
# robust triangulation: self-intersecting doodle faces come
|
||||
# out filled (union of their loops) instead of erroring
|
||||
var tr := o.face_triangulation(fi)
|
||||
var pts: PackedVector3Array = tr["verts"]
|
||||
var tris: PackedInt32Array = tr["tris"]
|
||||
if pts.size() < 3 or tris.size() < 3:
|
||||
continue
|
||||
var n := o.face_normal_w(fi)
|
||||
if n == Vector3.ZERO:
|
||||
continue
|
||||
var loop := o.face_loop(fi)
|
||||
for t in range(0, tris.size() - 2, 3):
|
||||
# Godot uses CLOCKWISE winding for front faces; the
|
||||
# triangulator emits CCW (viewed from the normal side),
|
||||
# so reverse each triangle or CULL_BACK shows the
|
||||
# inside of the model.
|
||||
for k in [2, 1, 0]:
|
||||
var nrm: Vector3 = n
|
||||
if smooth_on:
|
||||
var ti: int = tris[t + k]
|
||||
if ti < loop.size():
|
||||
var acc: Vector3 = vnorm.get(
|
||||
loop[ti], n)
|
||||
if acc.length() > 0.0001:
|
||||
nrm = acc.normalized()
|
||||
st.set_normal(nrm)
|
||||
if tex_w > 0.0:
|
||||
st.set_uv(o.uv_of_world(fi, pts[tris[t + k]]))
|
||||
else:
|
||||
var c := o.face_color(fi)
|
||||
st.set_color(fallback if c.a < 0.01 else c)
|
||||
st.add_vertex(pts[tris[t + k]])
|
||||
vc += 1
|
||||
if vc == 0:
|
||||
return null
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.roughness = 0.85
|
||||
mat.metallic = 0.0
|
||||
if tex_w > 0.0:
|
||||
# alpha_tex = the checker placeholder is NOT served: the
|
||||
# raw page (transparent where unpainted) is used, so the
|
||||
# material must alpha-test the holes. Otherwise the
|
||||
# checker+page composite renders opaque as always.
|
||||
mat.albedo_texture = o.get_texture(not alpha_tex)
|
||||
if alpha_tex:
|
||||
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA_SCISSOR
|
||||
mat.alpha_scissor_threshold = 0.5
|
||||
# Pixel mode samples the texture NEAREST (crisp texels on
|
||||
# the model), Smooth mode keeps the filtered default.
|
||||
mat.texture_filter = BaseMaterial3D.TEXTURE_FILTER_NEAREST \
|
||||
if pixel_filter \
|
||||
else BaseMaterial3D.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS
|
||||
else:
|
||||
mat.vertex_color_use_as_albedo = true
|
||||
# "Render both sides": no backface culling, ON by default
|
||||
mat.cull_mode = BaseMaterial3D.CULL_DISABLED if both_sides \
|
||||
else BaseMaterial3D.CULL_BACK
|
||||
st.set_material(mat)
|
||||
st.index()
|
||||
return st.commit()
|
||||
|
||||
|
||||
static func build_document_mesh(doc: PdDocument,
|
||||
alpha_tex := false) -> ArrayMesh:
|
||||
var merged := ArrayMesh.new()
|
||||
var any := false
|
||||
for o in doc.objects:
|
||||
if not o.is_visible:
|
||||
continue
|
||||
var m := build_mesh(o, PdPolyObj.BASE, doc.both_sides,
|
||||
true, doc.tex_filter == 1, alpha_tex)
|
||||
if m == null:
|
||||
continue
|
||||
any = true
|
||||
for si in m.get_surface_count():
|
||||
merged.add_surface_from_arrays(
|
||||
Mesh.PRIMITIVE_TRIANGLES, m.surface_get_arrays(si))
|
||||
merged.surface_set_material(merged.get_surface_count() - 1,
|
||||
m.surface_get_material(si))
|
||||
return merged if any else null
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- obj ---
|
||||
## Wavefront OBJ export with TEXTURE support:
|
||||
## - "s off" per object so importers (which default to SMOOTH shading when
|
||||
## no s-lines exist) render the flat, per-face look Polydoodle shows.
|
||||
## - Per-corner "vt" coordinates taken from each face's CURRENT sampling
|
||||
## texels (moved UVs export correctly), V flipped to OBJ's bottom-left
|
||||
## convention (Godot images are top-left).
|
||||
## - A companion .mtl with map_Kd plus the atlas saved as a PNG next to
|
||||
## the .obj (one PNG per textured object).
|
||||
## Returns OK, or the FileAccess error.
|
||||
static func write_obj(doc: PdDocument, path: String) -> Error:
|
||||
var f := FileAccess.open(path, FileAccess.WRITE)
|
||||
if f == null:
|
||||
return FileAccess.get_open_error()
|
||||
var mtl_name := path.get_file().get_basename() + ".mtl"
|
||||
f.store_line("# Exported by Polydoodle")
|
||||
f.store_line("# %d object(s)" % doc.objects.size())
|
||||
f.store_line("mtllib %s" % mtl_name)
|
||||
var base := 1
|
||||
var vt_base := 1
|
||||
var mats := "" # accumulated .mtl content
|
||||
var pngs := [] # [path, Image] pairs to save
|
||||
var mid := 0
|
||||
for o in doc.objects:
|
||||
if not o.is_visible:
|
||||
continue
|
||||
f.store_line("o %s" % o.obj_name.validate_node_name()
|
||||
if not o.obj_name.is_empty() else "o Shape")
|
||||
# s on = smooth shading (importers average normals),
|
||||
# s off = the flat per-face look Polydoodle shows by default
|
||||
f.store_line("s on" if o.shade_smooth else "s off")
|
||||
for i in o.nverts():
|
||||
var w: Vector3 = o.wvert(i)
|
||||
f.store_line("v %.5f %.5f %.5f" % [w.x, w.y, w.z])
|
||||
# vt: one per face loop corner, sampling position, V flipped
|
||||
var has_tex: bool = o.tex != null
|
||||
var mat_id := ""
|
||||
if has_tex:
|
||||
mid += 1
|
||||
mat_id = "polydoodle_mat%d" % mid
|
||||
f.store_line("usemtl %s" % mat_id)
|
||||
var tex: Image = o.tex
|
||||
var tw := float(tex.get_width())
|
||||
var th := float(tex.get_height())
|
||||
for fi in o.nfaces():
|
||||
var loop: PackedInt32Array = o.face_loop(fi)
|
||||
for k in loop.size():
|
||||
var t: Vector2 = o.corner_texel(fi, k)
|
||||
var u: float = (t.x + 0.5) / tw
|
||||
var vv: float = 1.0 - (t.y + 0.5) / th
|
||||
f.store_line("vt %.5f %.5f" % [u, vv])
|
||||
# texture PNG next to the obj (absolute path for
|
||||
# IO). Same bake rule as the mesh exports: the
|
||||
# checker rides along when it is shown in the
|
||||
# editor or "Bake Into Export" is on; otherwise the
|
||||
# raw page (alpha 0 where unpainted) exports.
|
||||
var png_name := "%s_%d.png" % [
|
||||
path.get_file().get_basename(), mid]
|
||||
mats += "newmtl %s\n" % mat_id
|
||||
mats += "Ka 1.000 1.000 1.000\n"
|
||||
mats += "Kd 1.000 1.000 1.000\n"
|
||||
mats += "d 1.000\n"
|
||||
mats += "illum 1\n"
|
||||
mats += "map_Kd %s\n\n" % png_name
|
||||
pngs.append([path.get_base_dir().path_join(png_name),
|
||||
o.export_image(doc.show_checker
|
||||
or doc.export_checker)])
|
||||
for face in o.faces:
|
||||
var parts := PackedStringArray(["f"])
|
||||
for vi in face:
|
||||
if has_tex:
|
||||
parts.append("%d/%d" % [base + vi, vt_base])
|
||||
vt_base += 1
|
||||
else:
|
||||
parts.append(str(base + vi))
|
||||
f.store_line(" ".join(parts))
|
||||
base += o.nverts()
|
||||
f.close()
|
||||
if mats != "":
|
||||
var mf := FileAccess.open(
|
||||
path.get_base_dir().path_join(mtl_name), FileAccess.WRITE)
|
||||
if mf != null:
|
||||
mf.store_string(mats)
|
||||
mf.close()
|
||||
for p in pngs:
|
||||
var gp := ProjectSettings.globalize_path(p[0])
|
||||
(p[1] as Image).save_png(gp)
|
||||
return OK
|
||||
|
||||
|
||||
## The export-texture rule shared by every path: the checkerboard bakes
|
||||
## into the exported texture when it is shown in the editor OR the
|
||||
## "Export Checkerboard" option is on; otherwise unpainted texels export
|
||||
## transparent (alpha 0) and the material alpha-tests the holes.
|
||||
static func export_alpha_tex(doc: PdDocument) -> bool:
|
||||
return not (doc.show_checker or doc.export_checker)
|
||||
|
||||
|
||||
# --------------------------------------------------------------- tres ---
|
||||
static func save_mesh_tres(doc: PdDocument, path: String) -> Error:
|
||||
var mesh := build_document_mesh(doc, export_alpha_tex(doc))
|
||||
if mesh == null:
|
||||
return ERR_CANT_CREATE
|
||||
return ResourceSaver.save(mesh, path)
|
||||
|
||||
|
||||
# --------------------------------------------------------------- tscn ---
|
||||
static func save_scene_tscn(doc: PdDocument, path: String) -> Error:
|
||||
var mesh_path := path.get_basename() + ".tres"
|
||||
var err := save_mesh_tres(doc, mesh_path)
|
||||
if err != OK:
|
||||
return err
|
||||
var uid := ResourceUID.create_id()
|
||||
var f := FileAccess.open(path, FileAccess.WRITE)
|
||||
if f == null:
|
||||
return FileAccess.get_open_error()
|
||||
f.store_line('[gd_scene load_steps=2 format=3 uid="%s"]' % ResourceUID.id_to_text(uid))
|
||||
f.store_line("")
|
||||
f.store_line('[ext_resource type="ArrayMesh" path="%s" id="1_mesh"]' % mesh_path)
|
||||
f.store_line("")
|
||||
f.store_line('[node name="PolydoodleModel" type="MeshInstance3D"]')
|
||||
f.store_line('mesh = ExtResource("1_mesh")')
|
||||
f.close()
|
||||
return OK
|
||||
|
||||
|
||||
# ------------------------------------------------------------ project ---
|
||||
## Native .pdoodle project files: plain var_to_str text of the full state
|
||||
## (avoids ResourceSaver's extension registry entirely).
|
||||
|
||||
static func save_project(doc: PdDocument, path: String) -> Error:
|
||||
var f := FileAccess.open(path, FileAccess.WRITE)
|
||||
if f == null:
|
||||
return FileAccess.get_open_error()
|
||||
var data := {
|
||||
"version": 1,
|
||||
"app": "polydoodle",
|
||||
"objects": doc.snapshot(),
|
||||
"bg_color": doc.bg_color,
|
||||
"grid_size": doc.grid_size,
|
||||
"grid_visible": doc.grid_visible,
|
||||
"snap_enabled": doc.snap_enabled,
|
||||
"gizmo_on": doc.gizmo_on,
|
||||
"draw_free": doc.draw_free,
|
||||
"draw_kind": doc.draw_kind,
|
||||
"paint_color": doc.paint_color,
|
||||
"paint_tool": doc.paint_tool,
|
||||
"brush_size": doc.brush_size,
|
||||
"pixel_size": doc.pixel_size,
|
||||
"recent_colors": doc.recent_colors,
|
||||
"both_sides": doc.both_sides,
|
||||
"view_shading": doc.view_shading,
|
||||
"uv_snap": doc.uv_snap,
|
||||
"tex_filter": doc.tex_filter,
|
||||
"pixel_px": doc.pixel_px,
|
||||
"gizmo_kind": doc.gizmo_kind,
|
||||
"brush_opacity": doc.brush_opacity,
|
||||
"brush_smooth": doc.brush_smooth,
|
||||
"face_lock": doc.face_lock,
|
||||
"inset_dist": doc.inset_dist,
|
||||
"hints_enabled": doc.hints_enabled,
|
||||
"show_checker": doc.show_checker,
|
||||
"export_checker": doc.export_checker,
|
||||
}
|
||||
f.store_string(var_to_str(data))
|
||||
f.close()
|
||||
return OK
|
||||
|
||||
|
||||
## Project files only ever hold plain data. An Object(...) literal outside
|
||||
## a quoted string would make str_to_var instantiate engine objects.
|
||||
static func _has_object_literal(text: String) -> bool:
|
||||
if not text.contains("Object("):
|
||||
return false
|
||||
var rx := RegEx.new()
|
||||
rx.compile("\"(?:[^\"\\\\]|\\\\.)*\"")
|
||||
return rx.sub(text, "", true).contains("Object(")
|
||||
|
||||
|
||||
static func load_project(path: String) -> PdDocument:
|
||||
var f := FileAccess.open(path, FileAccess.READ)
|
||||
if f == null:
|
||||
return null
|
||||
var text := f.get_as_text()
|
||||
f.close()
|
||||
if _has_object_literal(text):
|
||||
return null
|
||||
var parsed = str_to_var(text)
|
||||
if typeof(parsed) != TYPE_DICTIONARY:
|
||||
return null
|
||||
if typeof(parsed.get("objects", [])) != TYPE_ARRAY:
|
||||
return null
|
||||
for od in parsed.get("objects", []):
|
||||
if typeof(od) != TYPE_DICTIONARY:
|
||||
return null
|
||||
var doc := PdDocument.new()
|
||||
doc.restore_snapshot(parsed.get("objects", []))
|
||||
doc.bg_color = parsed.get("bg_color", doc.bg_color)
|
||||
doc.grid_size = parsed.get("grid_size", doc.grid_size)
|
||||
doc.grid_visible = parsed.get("grid_visible", doc.grid_visible)
|
||||
doc.snap_enabled = parsed.get("snap_enabled", doc.snap_enabled)
|
||||
doc.gizmo_on = parsed.get("gizmo_on", doc.gizmo_on)
|
||||
doc.draw_free = parsed.get("draw_free", doc.draw_free)
|
||||
doc.draw_kind = parsed.get("draw_kind",
|
||||
"Freehand" if doc.draw_free else "Rectangle")
|
||||
doc.paint_color = parsed.get("paint_color", doc.paint_color)
|
||||
doc.paint_tool = parsed.get("paint_tool", doc.paint_tool)
|
||||
doc.brush_size = parsed.get("brush_size", doc.brush_size)
|
||||
doc.pixel_size = parsed.get("pixel_size", doc.pixel_size)
|
||||
doc.recent_colors = parsed.get("recent_colors", doc.recent_colors)
|
||||
doc.both_sides = parsed.get("both_sides", doc.both_sides)
|
||||
doc.view_shading = int(parsed.get("view_shading", doc.view_shading))
|
||||
doc.uv_snap = bool(parsed.get("uv_snap", doc.uv_snap))
|
||||
doc.tex_filter = int(parsed.get("tex_filter", doc.tex_filter))
|
||||
doc.pixel_px = int(parsed.get("pixel_px", doc.pixel_px))
|
||||
doc.gizmo_kind = int(parsed.get("gizmo_kind", doc.gizmo_kind))
|
||||
doc.brush_opacity = parsed.get("brush_opacity", doc.brush_opacity)
|
||||
doc.brush_smooth = parsed.get("brush_smooth", doc.brush_smooth)
|
||||
doc.face_lock = bool(parsed.get("face_lock", doc.face_lock))
|
||||
doc.inset_dist = float(parsed.get("inset_dist", doc.inset_dist))
|
||||
doc.hints_enabled = bool(parsed.get("hints_enabled", doc.hints_enabled))
|
||||
doc.show_checker = bool(parsed.get("show_checker", doc.show_checker))
|
||||
doc.export_checker = bool(parsed.get("export_checker", doc.export_checker))
|
||||
return doc
|
||||
|
||||
|
||||
# ------------------------------------------------------------ session ---
|
||||
## AUTOMATIC SESSION SAVE: the same state a .pdoodle project
|
||||
## carries, written to user:// so the editor restores the user's models
|
||||
## exactly as they were left when Polydoodle reopens. Binary store_var
|
||||
## keeps the atlas bytes compact (the text .pdoodle format would inflate
|
||||
## them ~4x, which is fine for an explicit save but not for autosaving).
|
||||
|
||||
const SESSION_PATH := "user://polydoodle_session.pdoodle"
|
||||
|
||||
|
||||
static func session_data(doc: PdDocument) -> Dictionary:
|
||||
return {
|
||||
"version": 1,
|
||||
"app": "polydoodle_session",
|
||||
"objects": doc.snapshot(),
|
||||
"bg_color": doc.bg_color,
|
||||
"grid_size": doc.grid_size,
|
||||
"grid_visible": doc.grid_visible,
|
||||
"snap_enabled": doc.snap_enabled,
|
||||
"gizmo_on": doc.gizmo_on,
|
||||
"draw_free": doc.draw_free,
|
||||
"draw_kind": doc.draw_kind,
|
||||
"paint_color": doc.paint_color,
|
||||
"paint_tool": doc.paint_tool,
|
||||
"brush_size": doc.brush_size,
|
||||
"pixel_size": doc.pixel_size,
|
||||
"recent_colors": doc.recent_colors,
|
||||
"both_sides": doc.both_sides,
|
||||
"view_shading": doc.view_shading,
|
||||
"uv_snap": doc.uv_snap,
|
||||
"tex_filter": doc.tex_filter,
|
||||
"pixel_px": doc.pixel_px,
|
||||
"gizmo_kind": doc.gizmo_kind,
|
||||
"brush_opacity": doc.brush_opacity,
|
||||
"brush_smooth": doc.brush_smooth,
|
||||
"face_lock": doc.face_lock,
|
||||
"inset_dist": doc.inset_dist,
|
||||
"hints_enabled": doc.hints_enabled,
|
||||
"show_checker": doc.show_checker,
|
||||
"export_checker": doc.export_checker,
|
||||
"mode": doc.mode,
|
||||
"tex_edit": doc.tex_edit,
|
||||
}
|
||||
|
||||
|
||||
## The atlas bytes dominate the session file (a 1024 atlas is 4 MB raw),
|
||||
## and the autosave rewrites it often - store the texels zlib-compressed
|
||||
## (the checkerboard and flat paints shrink dramatically). Raw arrays
|
||||
## stay compatible with older sessions.
|
||||
static func _pack_textures(d: Dictionary) -> void:
|
||||
var objects: Array = d.get("objects", [])
|
||||
for o in objects:
|
||||
var od: Dictionary = o
|
||||
if od.has("tex"):
|
||||
od["tex_z"] = (od["tex"] as PackedByteArray).compress()
|
||||
od.erase("tex")
|
||||
|
||||
|
||||
static func _unpack_textures(d: Dictionary) -> void:
|
||||
var objects: Array = d.get("objects", [])
|
||||
for o in objects:
|
||||
var od: Dictionary = o
|
||||
if od.has("tex_z"):
|
||||
var raw := od["tex_z"] as PackedByteArray
|
||||
var w := int(od.get("texw", 0))
|
||||
if w > 0 and raw.size() > 0:
|
||||
od["tex"] = raw.decompress(w * w * 4)
|
||||
od.erase("tex_z")
|
||||
|
||||
|
||||
static func save_session(doc: PdDocument, path := SESSION_PATH) -> Error:
|
||||
var tmp := path + ".tmp"
|
||||
var f := FileAccess.open(tmp, FileAccess.WRITE)
|
||||
if f == null:
|
||||
return FileAccess.get_open_error()
|
||||
var d := session_data(doc)
|
||||
_pack_textures(d)
|
||||
f.store_var(d)
|
||||
var werr := f.get_error()
|
||||
f.close()
|
||||
if werr != OK:
|
||||
DirAccess.remove_absolute(ProjectSettings.globalize_path(tmp))
|
||||
return werr
|
||||
return DirAccess.rename_absolute(
|
||||
ProjectSettings.globalize_path(tmp),
|
||||
ProjectSettings.globalize_path(path))
|
||||
|
||||
|
||||
## Returns the raw session dictionary, or null when absent / corrupt.
|
||||
static func load_session(path := SESSION_PATH) -> Dictionary:
|
||||
if not FileAccess.file_exists(path):
|
||||
return {}
|
||||
var f := FileAccess.open(path, FileAccess.READ)
|
||||
if f == null:
|
||||
return {}
|
||||
var parsed: Variant = f.get_var()
|
||||
f.close()
|
||||
if typeof(parsed) != TYPE_DICTIONARY:
|
||||
return {}
|
||||
var d: Dictionary = parsed
|
||||
if d.get("app", "") != "polydoodle_session":
|
||||
return {}
|
||||
_unpack_textures(d)
|
||||
return d
|
||||
|
||||
|
||||
## Apply a session dictionary (from load_session) onto `doc`. Returns the
|
||||
## number of restored objects, or -1 when the session is invalid.
|
||||
static func apply_session(doc: PdDocument, d: Dictionary) -> int:
|
||||
if d.is_empty() or d.get("app", "") != "polydoodle_session":
|
||||
return -1
|
||||
doc.restore_snapshot(d.get("objects", []))
|
||||
doc.bg_color = d.get("bg_color", doc.bg_color)
|
||||
doc.grid_size = d.get("grid_size", doc.grid_size)
|
||||
doc.grid_visible = bool(d.get("grid_visible", doc.grid_visible))
|
||||
doc.snap_enabled = bool(d.get("snap_enabled", doc.snap_enabled))
|
||||
doc.gizmo_on = bool(d.get("gizmo_on", doc.gizmo_on))
|
||||
doc.draw_free = bool(d.get("draw_free", doc.draw_free))
|
||||
doc.draw_kind = d.get("draw_kind",
|
||||
"Freehand" if doc.draw_free else "Rectangle")
|
||||
doc.paint_color = d.get("paint_color", doc.paint_color)
|
||||
doc.paint_tool = d.get("paint_tool", doc.paint_tool)
|
||||
doc.brush_size = d.get("brush_size", doc.brush_size)
|
||||
doc.pixel_size = d.get("pixel_size", doc.pixel_size)
|
||||
doc.recent_colors = d.get("recent_colors", doc.recent_colors)
|
||||
doc.both_sides = bool(d.get("both_sides", doc.both_sides))
|
||||
doc.view_shading = int(d.get("view_shading", doc.view_shading))
|
||||
doc.uv_snap = bool(d.get("uv_snap", doc.uv_snap))
|
||||
doc.tex_filter = int(d.get("tex_filter", doc.tex_filter))
|
||||
doc.pixel_px = int(d.get("pixel_px", doc.pixel_px))
|
||||
doc.gizmo_kind = int(d.get("gizmo_kind", doc.gizmo_kind))
|
||||
doc.brush_opacity = d.get("brush_opacity", doc.brush_opacity)
|
||||
doc.brush_smooth = d.get("brush_smooth", doc.brush_smooth)
|
||||
doc.face_lock = bool(d.get("face_lock", doc.face_lock))
|
||||
doc.inset_dist = float(d.get("inset_dist", doc.inset_dist))
|
||||
doc.hints_enabled = bool(d.get("hints_enabled", doc.hints_enabled))
|
||||
doc.show_checker = bool(d.get("show_checker", doc.show_checker))
|
||||
doc.export_checker = bool(d.get("export_checker", doc.export_checker))
|
||||
return doc.objects.size()
|
||||
|
||||
|
||||
# --------------------------------------------------------- add to scene ---
|
||||
## A node that carries a Polydoodle model: tagged by meta from this version
|
||||
## on, or simply NAMED PolydoodleModel... by older plugin versions.
|
||||
static func _is_polydoodle_node(n: Node) -> bool:
|
||||
return n is MeshInstance3D \
|
||||
and (n.has_meta("polydoodle")
|
||||
or String(n.name).begins_with("PolydoodleModel"))
|
||||
|
||||
|
||||
## Collect every Polydoodle model node under `root` (inclusive).
|
||||
static func _collect_polydoodle_nodes(root: Node, out: Array) -> void:
|
||||
if _is_polydoodle_node(root):
|
||||
out.append(root)
|
||||
for c in root.get_children():
|
||||
_collect_polydoodle_nodes(c, out)
|
||||
|
||||
|
||||
## Export the document into the current scene. The FIRST time this adds a
|
||||
## new "PolydoodleModel" node; every LATER export UPDATES that node in
|
||||
## place - the mesh resource (geometry, UVs, material, texture) is swapped,
|
||||
## while the node keeps its name, its transform (position / rotation /
|
||||
## scale set in the Godot editor) and its children. With several Polydoodle
|
||||
## models in one scene the SELECTED one is updated; if the selection is
|
||||
## ambiguous a new numbered node is added instead.
|
||||
static func add_to_scene(doc: PdDocument) -> String:
|
||||
var scene_root := EditorInterface.get_edited_scene_root()
|
||||
if scene_root == null:
|
||||
return "Open or create a scene first (Scene > New Scene), then try again."
|
||||
var mesh := build_document_mesh(doc, export_alpha_tex(doc))
|
||||
if mesh == null:
|
||||
return "Nothing to add - the document is empty."
|
||||
var existing := []
|
||||
_collect_polydoodle_nodes(scene_root, existing)
|
||||
var target: MeshInstance3D = null
|
||||
if existing.size() == 1:
|
||||
target = existing[0]
|
||||
elif existing.size() > 1:
|
||||
# several candidates: prefer the single selected one
|
||||
var sel := EditorInterface.get_selection()
|
||||
var picked := []
|
||||
for n in sel.get_selected_nodes():
|
||||
if _is_polydoodle_node(n):
|
||||
picked.append(n)
|
||||
if picked.size() == 1:
|
||||
target = picked[0]
|
||||
if target != null:
|
||||
var old_name := String(target.name)
|
||||
target.mesh = mesh
|
||||
target.owner = scene_root # keep the node saved
|
||||
var sel := EditorInterface.get_selection()
|
||||
sel.clear()
|
||||
sel.add_node(target)
|
||||
EditorInterface.mark_scene_as_unsaved()
|
||||
return "Updated %s in the current scene (position and scale kept)." % old_name
|
||||
var mi := MeshInstance3D.new()
|
||||
var name := "PolydoodleModel"
|
||||
var i := 2
|
||||
while scene_root.has_node(name):
|
||||
name = "PolydoodleModel%d" % i
|
||||
i += 1
|
||||
mi.name = name
|
||||
mi.mesh = mesh
|
||||
mi.set_meta("polydoodle", true)
|
||||
scene_root.add_child(mi)
|
||||
mi.owner = scene_root
|
||||
var sel2 := EditorInterface.get_selection()
|
||||
sel2.clear()
|
||||
sel2.add_node(mi)
|
||||
EditorInterface.mark_scene_as_unsaved()
|
||||
if existing.size() > 1:
|
||||
return ("Added %s to the current scene. Several Polydoodle models "
|
||||
+ "already exist - select the stale one and export again "
|
||||
+ "to update it in place.") % name
|
||||
return "Added %s to the current scene." % name
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
uid://bjj1odyy86tq
|
||||
Executable
+3298
File diff suppressed because it is too large
Load Diff
Executable
+1
@@ -0,0 +1 @@
|
||||
uid://d1vuvpva42t25
|
||||
Reference in New Issue
Block a user