diff --git a/autocal_dense355_windows.go b/autocal_dense355_windows.go index 64f6ef2..5b475b4 100644 --- a/autocal_dense355_windows.go +++ b/autocal_dense355_windows.go @@ -19,12 +19,13 @@ func (a *app) checkDenseCalibration355(owner *calibrationOwner, surfs []Surface) return } } + if err=flatScanSession363(&ref);err!=nil{logf("Dense calibration check: UNVERIFIED: %v. No verification dots projected.",err);return} defer func() { a.presMu.Lock(); pat.clear(); a.presTok = PatternToken{}; a.presMu.Unlock() }() logf("Dense calibration check: measuring 12 fresh markers against saved pixel correspondence. This checks correspondence, not every renderer/compositor path.") - n, mean, worst, report, complete := verifyScanComplete355(winScanIO{}, res, surfs) + n, mean, worst, report, complete := verifyScanComplete355(flatScanIO363Windows{ref:&ref}, res, surfs) if !calibrationCheckGood355(n, complete, mean, worst) && complete && n < 12 { logf("Dense calibration check: retrying once with 50%% larger fiducials for missing markers; dense addresses and quality thresholds unchanged.") - n, mean, worst, report, complete = verifyScanComplete355(largerFiducials355{}, res, surfs) + n, mean, worst, report, complete = verifyScanComplete355(flatLargerIO363Windows{flatScanIO363Windows{ref:&ref}}, res, surfs) } for _, line := range report { @@ -34,6 +35,7 @@ func (a *app) checkDenseCalibration355(owner *calibrationOwner, surfs []Surface) logf("Dense calibration check: UNVERIFIED (complete=%v, %d/12 markers, average %.1f px, worst %.1f). Map unchanged.", complete, n, mean, worst) return } + if err=flatScanSession363(&ref);err!=nil{logf("Dense calibration check: session expired or changed; result discarded: %v",err);return} if !verifyScanBinding(&ref, binding) { logf("Dense calibration check: scan files changed; result discarded.") return diff --git a/common.go b/common.go index 31fe5b4..e5d8965 100644 --- a/common.go +++ b/common.go @@ -11,7 +11,7 @@ import ( "time" ) -const version = "0.98.362-experimental1" +const version = "0.98.363-experimental1" const appDisplayName = "Projection Mapper - Built by Instinct" diff --git a/flat_dots363.go b/flat_dots363.go new file mode 100644 index 0000000..1f72c6e --- /dev/null +++ b/flat_dots363.go @@ -0,0 +1,235 @@ +package main + +import ( + "fmt" + "math" + "strings" +) + +// A measured correspondence screen, not a claim that brightness proves a +// physical plane. Missing/ambiguous scan addresses never become guessed sites. +// The footprint includes the larger retry dot (.009) plus a .006 guard. +const flatDotFootprint363 = .015 + +type flatDotSite363 struct{ Projector, Camera [2]float64 } + +func flatScanShape363(res *scanResult, inv *scanInverse, frame gray32) bool { + if res == nil || inv == nil || res.W < 16 || res.H < 16 || res.ProjW < 64 || res.ProjH < 64 || res.W > 8192 || res.H > 8192 || res.ProjW > 8192 || res.ProjH > 8192 { + return false + } + n := res.W * res.H + m := res.ProjW * res.ProjH + return len(res.Valid) == n && len(res.PX) == n && len(res.PY) == n && len(res.Conf) == n && inv.CamW == res.W && inv.CamH == res.H && inv.ProjW == res.ProjW && inv.ProjH == res.ProjH && len(inv.Valid) == m && len(inv.Disputed) == m && len(inv.X) == m && len(inv.Y) == m && frame.W == res.W && frame.H == res.H && len(frame.G) == n +} +func flatObjectVeto363(q [2]float64, surfs []Surface) bool { + for _, s := range surfs { + // Hidden receiving outlines can still represent real physical obstacles. + if strings.EqualFold(strings.TrimSpace(s.Cls), "wall") && !s.Occluder { + continue + } + poly := s.Poly + if len(poly) < 3 { + poly = s.Quad + } + if len(poly) >= 3 && pointInPolyXY(q[0], q[1], poly) { + return true + } + } + return false +} + +// Fit using the retained measured address, not the rounded inverse-bin center. +// Inverse bins can select the nearest decoded camera pixel, but must not turn +// its quantization error into apparent physical curvature. +func flatMeasuredPair363(res *scanResult, q, a [2]float64) ([2]float64, bool) { + cx, cy := int(q[0]*float64(res.W)), int(q[1]*float64(res.H)) + i := cy*res.W + cx + if cx < 0 || cy < 0 || cx >= res.W || cy >= res.H || !res.Valid[i] || res.Conf[i] < 70 { + return [2]float64{}, false + } + x, y := float64(res.PX[i]), float64(res.PY[i]) + if len(res.PXF) == res.W*res.H && len(res.PYF) == res.W*res.H { + x, y = float64(res.PXF[i]), float64(res.PYF[i]) + } + if math.IsNaN(x+y) || math.IsInf(x+y, 0) || x < 0 || y < 0 || x >= float64(res.ProjW) || y >= float64(res.ProjH) || math.Hypot(x-a[0]*float64(res.ProjW), y-a[1]*float64(res.ProjH)) > 2.5 { + return [2]float64{}, false + } + return [2]float64{x / float64(res.ProjW), y / float64(res.ProjH)}, true +} +func flatDotAt363(res *scanResult, inv *scanInverse, frame gray32, surfs []Surface, p [2]float64) (flatDotSite363, bool) { + var out flatDotSite363 + if !flatScanShape363(res, inv, frame) || math.IsNaN(p[0]+p[1]) || math.IsInf(p[0]+p[1], 0) || p[0] < .03 || p[0] > .97 || p[1] < .03 || p[1] > .97 { + return out, false + } + // Stencil throughout an inflated square, including the full circular dot. + src, dst := make([][2]float64, 0, 25), make([][2]float64, 0, 25) + var lo, hi float64 = 256, -1 + var footprintP, footprintC [][2]float64 + for y := -2; y <= 2; y++ { + for x := -2; x <= 2; x++ { + a := [2]float64{p[0] + float64(x)*flatDotFootprint363/2, p[1] + float64(y)*flatDotFootprint363*float64(res.ProjW)/float64(res.ProjH)/2} + q, ok := scanPredict(inv, a, 2) + if !ok || math.IsNaN(q[0]+q[1]) || math.IsInf(q[0]+q[1], 0) || q[0] < .02 || q[0] > .98 || q[1] < .02 || q[1] > .98 || flatObjectVeto363(q, surfs) { + return out, false + } + cx, cy := int(q[0]*float64(res.W)), int(q[1]*float64(res.H)) + i := cy*res.W + cx + if !res.Valid[i] || res.Conf[i] < 70 { + return out, false + } + back, ok := scanToProj(res, q, 1) + if !ok || math.Hypot((back[0]-a[0])*float64(res.ProjW), (back[1]-a[1])*float64(res.ProjH)) > 2.5 { + return out, false + } + v := float64(frame.G[i]) + if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 245 { + return out, false + } + lo = math.Min(lo, v) + hi = math.Max(hi, v) + measured, ok := flatMeasuredPair363(res, q, a) + if !ok { + return out, false + } + src = append(src, measured) + dst = append(dst, q) + } + } + // Inspect every projector pixel in the inflated footprint as well as the + // fit stencil. A thin foreground edge must not slip between stencil points. + rx, ry := int(math.Ceil(flatDotFootprint363*float64(res.ProjW))), int(math.Ceil(flatDotFootprint363*float64(res.ProjW))) + px, py := int(p[0]*float64(res.ProjW)), int(p[1]*float64(res.ProjH)) + for y := py - ry; y <= py+ry; y++ { + for x := px - rx; x <= px+rx; x++ { + a := [2]float64{float64(x) / float64(res.ProjW), float64(y) / float64(res.ProjH)} + q, ok := scanPredict(inv, a, 2) + if !ok || math.IsNaN(q[0]+q[1]) || math.IsInf(q[0]+q[1], 0) || q[0] < 0 || q[0] >= 1 || q[1] < 0 || q[1] >= 1 || flatObjectVeto363(q, surfs) { + return out, false + } + cx, cy := int(q[0]*float64(res.W)), int(q[1]*float64(res.H)) + i := int(cy)*res.W + int(cx) + if i < 0 || i >= len(res.Valid) || !res.Valid[i] || res.Conf[i] < 70 { + return out, false + } + v := float64(frame.G[i]) + if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 245 { + return out, false + } + lo = math.Min(lo, v) + hi = math.Max(hi, v) + measured, ok := flatMeasuredPair363(res, q, a) + if !ok { + return out, false + } + footprintP = append(footprintP, measured) + footprintC = append(footprintC, q) + } + } + // Conservative continuous obstacle overlap: pixel centers alone can miss + // a thin outlined edge. Bounding boxes may over-reject, never admit it. + box := [4]float64{1, 1, 0, 0} + for _, q := range append(dst, footprintC...) { + box[0] = math.Min(box[0], q[0]) + box[1] = math.Min(box[1], q[1]) + box[2] = math.Max(box[2], q[0]) + box[3] = math.Max(box[3], q[1]) + } + for _, sf := range surfs { + if strings.EqualFold(strings.TrimSpace(sf.Cls), "wall") && !sf.Occluder { + continue + } + poly := sf.Poly + if len(poly) < 3 { + poly = sf.Quad + } + if len(poly) < 3 { + continue + } + b := [4]float64{1, 1, 0, 0} + for _, q := range poly { + b[0] = math.Min(b[0], q[0]) + b[1] = math.Min(b[1], q[1]) + b[2] = math.Max(b[2], q[0]) + b[3] = math.Max(b[3], q[1]) + } + if b[0] <= box[2] && b[2] >= box[0] && b[1] <= box[3] && b[3] >= box[1] { + return out, false + } + } + if hi-lo > 24 { + return out, false + } // veto clutter/clipping, never establish flatness + allP := append(src, footprintP...) + allC := append(dst, footprintC...) + h, ok := fitH(allP, allC, nil) + if !ok { + return out, false + } + // Projective consistency screens depth steps/curvature in measured scan. + // Fit all measured pixels to avoid bias from a small quantized stencil. + // Residual is camera pixels, separate from verification's unchanged limits. + for i, a := range allP { + x, y, ok := h.applyOK(a[0], a[1]) + if !ok || math.Hypot((x-allC[i][0])*float64(res.W), (y-allC[i][1])*float64(res.H)) > 1.25 { + return out, false + } + } + out = flatDotSite363{p, dst[12]} + return out, true +} +func flatDotPlan363(res *scanResult, inv *scanInverse, frame gray32, surfs []Surface) ([]flatDotSite363, error) { + if !flatScanShape363(res, inv, frame) { + return nil, fmt.Errorf("flat-site screen requires a same-size fresh camera frame and valid dense correspondence") + } + // One site in each of twelve disjoint projector regions. Never cluster all + // markers into one easy corner or silently reduce the required twelve. + out := make([]flatDotSite363, 0, 12) + for row := 0; row < 3; row++ { + for col := 0; col < 4; col++ { + found := false + center := [2]float64{.125 + float64(col)*.25, 1.0/6 + float64(row)/3} + for ring := 0; ring <= 4 && !found; ring++ { + for dy := -ring; dy <= ring && !found; dy++ { + for dx := -ring; dx <= ring; dx++ { + if ring > 0 && absInt363(dx) != ring && absInt363(dy) != ring { + continue + } + p := [2]float64{center[0] + float64(dx)*.019, center[1] + float64(dy)*.027} + if site, ok := flatDotAt363(res, inv, frame, surfs, p); ok { + out = append(out, site) + found = true + break + } + } + } + } + if !found { + return nil, fmt.Errorf("no guarded low-distortion site in projector region %d/12; no verification dots projected", row*4+col+1) + } + } + } + return out, nil +} +func absInt363(x int) int { + if x < 0 { + return -x + } + return x +} + +// Mark unavailable pixels without changing either original capture. A steady +// bright lamp with no projector modulation is not a usable calibration site. +func flatIllumination363(base, lit gray32) gray32 { + if base.W != lit.W || base.H != lit.H || base.W < 1 || len(base.G) != base.W*base.H || len(lit.G) != len(base.G) { + return gray32{} + } + out := gray32{W: lit.W, H: lit.H, G: make([]float32, len(lit.G))} + for i, v := range lit.G { + if math.IsNaN(float64(v)) || math.IsNaN(float64(base.G[i])) || math.IsInf(float64(v+base.G[i]), 0) || v-base.G[i] < 12 || v > 245 { + out.G[i] = float32(math.NaN()) + } else { + out.G[i] = v + } + } + return out +} diff --git a/flat_dots363_test.go b/flat_dots363_test.go new file mode 100644 index 0000000..0f44491 --- /dev/null +++ b/flat_dots363_test.go @@ -0,0 +1,389 @@ +package main + +import ( + "encoding/json" + "fmt" + "image" + "image/color" + "image/png" + "math" + "os" + "testing" + "time" +) + +func flatFixture363() (*scanResult, *scanInverse, gray32) { + w, h := 320, 240 + n := w * h + r := &scanResult{W: w, H: h, ProjW: w, ProjH: h, BitsX: 9, BitsY: 8, PX: make([]uint16, n), PY: make([]uint16, n), PXF: make([]float32, n), PYF: make([]float32, n), Conf: make([]uint8, n), Valid: make([]bool, n)} + f := gray32{W: w, H: h, G: make([]float32, n)} + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + i := y*w + x + r.PX[i] = uint16(x) + r.PY[i] = uint16(y) + r.PXF[i] = float32(x) + r.PYF[i] = float32(y) + r.Conf[i] = 220 + r.Valid[i] = true + f.G[i] = 32 + } + } + return r, buildScanInverse(r), f +} +func Test363PlanTwelveDistributedMeasuredSites(t *testing.T) { + r, inv, f := flatFixture363() + p, e := flatDotPlan363(r, inv, f, nil) + if e != nil || len(p) != 12 { + t.Fatal(e, len(p)) + } + for i, s := range p { + if int(s.Projector[0]*4) != i%4 || int(s.Projector[1]*3) != i/4 { + t.Fatal("clustered", i, s) + } + if math.Hypot(s.Camera[0]-s.Projector[0], s.Camera[1]-s.Projector[1]) > .01 { + t.Fatal("unmeasured guess", s) + } + } +} +func Test363VetoObjectsAndUnavailableRegion(t *testing.T) { + r, inv, f := flatFixture363() + s := []Surface{{Cls: "piano", Poly: [][2]float64{{0, 0}, {.25, 0}, {.25, .333}, {0, .333}}}} + if p, e := flatDotPlan363(r, inv, f, s); e == nil || len(p) != 0 { + t.Fatal("projecting into object", e) + } + s[0].Visible = boolPtr363(false) + if _, e := flatDotPlan363(r, inv, f, s); e == nil { + t.Fatal("hidden obstacle ignored") + } +} +func boolPtr363(v bool) *bool { return &v } +func Test363MissingStaleShapeAndClippedFramesRejected(t *testing.T) { + r, inv, f := flatFixture363() + for _, mut := range []func(){func() { f.W-- }, func() { f.W = r.W; f.G = nil }, func() { + f.G = make([]float32, r.W*r.H) + for i := range f.G { + f.G[i] = 255 + } + }, func() { + for i := range r.Valid { + r.Valid[i] = false + } + }} { + mut() + if _, e := flatDotPlan363(r, inv, f, nil); e == nil { + t.Fatal("unsafe frame admitted") + } + } +} +func Test363DisputedAndCurvedCorrespondenceRejected(t *testing.T) { + r, inv, f := flatFixture363() + p := [2]float64{.5, .5} + for i := range inv.Disputed { + inv.Disputed[i] = true + } + if _, ok := flatDotAt363(r, inv, f, nil, p); ok { + t.Fatal("disputed") + } + r, inv, f = flatFixture363() + for y := 0; y < r.H; y++ { + for x := 0; x < r.W; x++ { + i := y*r.W + x + d := float64(x - r.W/2) + r.PXF[i] += float32(.7 * d * d) + } + } + inv = buildScanInverse(r) + if _, ok := flatDotAt363(r, inv, f, nil, p); ok { + t.Fatal("curved") + } +} + +type flatScanIO363 struct { + res *scanResult + frame gray32 + dotCalls int + pts [][2]float64 + white bool +} + +func (f *flatScanIO363) Black() { f.white = false } +func (f *flatScanIO363) White() { f.white = true } +func (f *flatScanIO363) Plane(gray32) {} +func (f *flatScanIO363) Dots(p [][2]float64, r float64) { f.dotCalls++; f.pts = append(f.pts, p...) } +func (f *flatScanIO363) Gray(n int) gray32 { + if f.white { + return f.frame + } + return gray32{W: f.frame.W, H: f.frame.H, G: make([]float32, len(f.frame.G))} +} + +func (f *flatScanIO363) Sleep(int) {} +func (f *flatScanIO363) Log(string, ...any) {} +func Test363ActualVerifyNoDotsWithoutCompleteSafePlan(t *testing.T) { + r, _, f := flatFixture363() + io := &flatScanIO363{res: r, frame: f} + s := []Surface{{Cls: "piano", Poly: [][2]float64{{0, 0}, {.25, 0}, {.25, .333}, {0, .333}}}} + n, _, _, report, complete := verifyScanComplete355(io, r, s) + if n != 0 || complete || io.dotCalls != 0 || len(report) == 0 { + t.Fatal("unsafe partial projection", n, complete, io.dotCalls, report) + } +} +func Test363FootprintIncludesTallDotAndThinObstacle(t *testing.T) { + r, inv, f := flatFixture363() + p := [2]float64{.5, .5} + q := [][2]float64{{.499, .514}, {.501, .514}, {.501, .518}, {.499, .518}} + if _, ok := flatDotAt363(r, inv, f, []Surface{{Cls: "thin obstacle", Poly: q}}, p); ok { + t.Fatal("width-scaled y footprint lost thin obstacle") + } +} +func Test363NonfiniteInverseFailsWithoutPanic(t *testing.T) { + r, inv, f := flatFixture363() + for i := range inv.X { + inv.X[i] = float32(math.NaN()) + } + if _, ok := flatDotAt363(r, inv, f, nil, [2]float64{.5, .5}); ok { + t.Fatal("NaN inverse admitted") + } +} +func Test363ActualVerificationSelectsTwelveAndKeepsErrorLimits(t *testing.T) { + r, _, _ := flatFixture363() + io := newLoopbackRoom(320, 240, 320, 240, ident, 15, 0) + io.albedoRect(0, 0, 1, 1, .7) + seen, mean, worst, report, complete := verifyScanComplete355(io, r, nil) + if !complete || seen != 12 || mean > 2 || worst > 8 { + t.Fatal(seen, mean, worst, complete, report) + } + if !calibrationCheckGood355(seen, complete, mean, worst) { + t.Fatal("existing check no longer accepts measured result") + } +} + +func Test363NoIlluminationNoDots(t *testing.T) { + r, _, f := flatFixture363() + io := &flatScanIO363{res: r, frame: f} + for i := range f.G { + f.G[i] = 0 + } + _, _, _, _, ok := verifyScanComplete355(io, r, nil) + if ok || io.dotCalls != 0 { + t.Fatal("unlit capture projected dots") + } +} +func Test363RelocatesBlockedNominalSiteWithinSameRegion(t *testing.T) { + r, inv, f := flatFixture363() + s := []Surface{{Cls: "small object", Poly: [][2]float64{{.117, .158}, {.133, .158}, {.133, .175}, {.117, .175}}}} + sites, e := flatDotPlan363(r, inv, f, s) + if e != nil || len(sites) != 12 { + t.Fatal(e) + } + if sites[0].Projector == ([2]float64{.125, 1.0 / 6}) { + t.Fatal("did not relocate") + } + for _, site := range sites { + if _, ok := flatDotAt363(r, inv, f, s, site.Projector); !ok { + t.Fatal("unsafe final site") + } + } +} +func Test363FullFootprintRejectsUnmappedPixels(t *testing.T) { + r, inv, f := flatFixture363() + for y := 115; y <= 125; y++ { + for x := 155; x <= 165; x++ { + j := y*r.ProjW + x + inv.Valid[j] = false + } + } + if _, ok := flatDotAt363(r, inv, f, nil, [2]float64{.5, .5}); ok { + t.Fatal("gap admitted") + } +} +func Test363DifferentCameraProjectorDensity(t *testing.T) { + r, _, f := flatFixture363() + r.ProjW = 640 + r.ProjH = 480 + r.BitsX = 10 + r.BitsY = 9 + for i := range r.PX { + r.PX[i] *= 2 + r.PY[i] *= 2 + r.PXF[i] *= 2 + r.PYF[i] *= 2 + } + sites, e := flatDotPlan363(r, buildScanInverse(r), f, nil) + if e != nil || len(sites) != 12 { + t.Fatal("ordinary2x camera/projector density unsupported", e) + } +} + +type guardedFlatIO363 struct { + *flatScanIO363 + calls, failAt int + changeFrame bool +} + +func (io *guardedFlatIO363) FlatGuard363() error { + io.calls++ + if io.calls >= io.failAt { + return fmt.Errorf("session changed") + } + return nil +} +func (io *guardedFlatIO363) Gray(n int) gray32 { + if io.changeFrame && io.dotCalls > 0 { + return gray32{} + } + return io.flatScanIO363.Gray(n) +} +func Test363SessionGuardStopsBeforeAnyDot(t *testing.T) { + r, _, f := flatFixture363() + for _, stop := range []int{1, 2} { + io := &guardedFlatIO363{flatScanIO363: &flatScanIO363{res: r, frame: f}, failAt: stop} + _, _, _, _, ok := verifyScanComplete355(io, r, nil) + if ok || io.dotCalls != 0 { + t.Fatal("guard bypass", stop, io.dotCalls) + } + } +} +func Test363ChangingFrameStopsVerification(t *testing.T) { + r, _, f := flatFixture363() + io := &guardedFlatIO363{flatScanIO363: &flatScanIO363{res: r, frame: f}, failAt: 100, changeFrame: true} + _, _, _, _, ok := verifyScanComplete355(io, r, nil) + if ok || io.dotCalls != 1 { + t.Fatal("frame change not stopped", ok, io.dotCalls) + } +} +func Test363PlannerPixelsAndCost(t *testing.T) { + if os.Getenv("PM363_ARTIFACTS") == "" { + t.Skip("explicit artifact and cost run") + } + dir := os.Getenv("PM363_ARTIFACTS") + os.MkdirAll(dir, 0700) + r, inv, f := flatFixture363() + surfs := []Surface{{Cls: "piano", Poly: [][2]float64{{.115, .15}, {.18, .15}, {.18, .245}, {.115, .245}}}, {Cls: "chair", Poly: [][2]float64{{.35, .4}, {.41, .4}, {.41, .57}, {.35, .57}}}} + sites, e := flatDotPlan363(r, inv, f, surfs) + if e != nil { + t.Fatal(e) + } + img := image.NewRGBA(image.Rect(0, 0, 960, 720)) + for y := 0; y < 720; y++ { + for x := 0; x < 960; x++ { + c := color.RGBA{25, 32, 40, 255} + if x%240 < 2 || y%240 < 2 { + c = color.RGBA{70, 80, 90, 255} + } + if flatObjectVeto363([2]float64{float64(x) / 960, float64(y) / 720}, surfs) { + c = color.RGBA{145, 65, 55, 255} + } + img.SetRGBA(x, y, c) + } + } + for _, s := range sites { + cx, cy := int(s.Projector[0]*960), int(s.Projector[1]*720) + for y := cy - 15; y <= cy+15; y++ { + for x := cx - 15; x <= cx+15; x++ { + c := color.RGBA{45, 155, 95, 255} + if (x-cx)*(x-cx)+(y-cy)*(y-cy) < 36 { + c = color.RGBA{245, 245, 230, 255} + } + img.SetRGBA(x, y, c) + } + } + } + out, _ := os.Create(dir + "/planner-synthetic.png") + png.Encode(out, img) + out.Close() + data, _ := json.MarshalIndent(sites, "", " ") + os.WriteFile(dir+"/sites-synthetic.json", data, 0600) + for _, wh := range [][2]int{{1920, 1080}, {3840, 2160}} { + w, h := wh[0], wh[1] + n := w * h + rr := &scanResult{W: w, H: h, ProjW: w, ProjH: h, BitsX: 12, BitsY: 12, PX: make([]uint16, n), PY: make([]uint16, n), Conf: make([]uint8, n), Valid: make([]bool, n)} + ff := gray32{W: w, H: h, G: make([]float32, n)} + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + i := y*w + x + rr.PX[i] = uint16(x) + rr.PY[i] = uint16(y) + rr.Valid[i] = true + rr.Conf[i] = 220 + ff.G[i] = 180 + } + } + start := time.Now() + ii := buildScanInverse(rr) + build := time.Since(start) + start = time.Now() + p, e := flatDotPlan363(rr, ii, ff, nil) + t.Logf("%dx%d inverse=%s plan=%s count=%d err=%v", w, h, build, time.Since(start), len(p), e) + if e != nil { + t.Fatal(e) + } + for i := range ff.G { + if i%2 == 0 { + ff.G[i] = 30 + } + } + start = time.Now() + _, e = flatDotPlan363(rr, ii, ff, nil) + t.Logf("%dx%d all-candidates-texture-veto=%s err=%v", w, h, time.Since(start), e) + if e == nil { + t.Fatal("texture veto bypassed") + } + } +} + +func Test363MalformedSiteCoordinatesRejected(t *testing.T) { + r, i, f := flatFixture363() + for _, p := range [][2]float64{{math.NaN(), .5}, {.5, math.Inf(1)}, {-.1, .5}, {1, .5}} { + if _, ok := flatDotAt363(r, i, f, nil, p); ok { + t.Fatal(p) + } + } +} + +func Test363AffineSkewPlaneAndOffStencilBump(t *testing.T) { + r, _, f := flatFixture363() + for y := 0; y < r.H; y++ { + for x := 0; x < r.W; x++ { + i := y*r.W + x + px := float64(x) + float64(y)*.25 + py := float64(y) + r.PX[i] = uint16(px) + r.PY[i] = uint16(py) + r.PXF[i] = float32(px) + r.PYF[i] = float32(py) + } + } + inv := buildScanInverse(r) + if _, ok := flatDotAt363(r, inv, f, nil, [2]float64{.5, .5}); !ok { + t.Fatal("affine-skew plane rejected") + } + // Distort one non-stencil decoded pixel inside the footprint. + r, inv, f = flatFixture363() + j := 121*r.W + 161 + inv.X[j] += 5 + if _, ok := flatDotAt363(r, inv, f, nil, [2]float64{.5, .5}); ok { + t.Fatal("off-stencil depth discontinuity admitted") + } +} + +func Test363PerspectivePlaneUsesMeasuredNotRoundedAddresses(t *testing.T) { + r, _, f := flatFixture363() + for y := 0; y < r.H; y++ { + for x := 0; x < r.W; x++ { + i := y*r.W + x + d := 1 + .12*float64(y)/float64(r.H) + px := (float64(x) + 8) / d + py := (float64(y) + 5) / d + r.PX[i] = uint16(px) + r.PY[i] = uint16(py) + r.PXF[i] = float32(px) + r.PYF[i] = float32(py) + } + } + inv := buildScanInverse(r) + if _, ok := flatDotAt363(r, inv, f, nil, [2]float64{.5, .5}); !ok { + t.Fatal("perspective plane rejected") + } +} diff --git a/flat_dots363_windows.go b/flat_dots363_windows.go new file mode 100644 index 0000000..1bcd12a --- /dev/null +++ b/flat_dots363_windows.go @@ -0,0 +1,49 @@ +//go:build windows + +package main + +import ( + "fmt" + "time" +) + +// A same-sized image is not evidence that the camera stayed in place. Only a +// recent scan from the still-live original capture session enters this screen. +// Undetected physical movement is still possible and remains a stated limit. +func flatScanSession363(ref *ScanRef) error { + if fakeCam { + return fmt.Errorf("physical flat-site screening is unavailable for a virtual camera") + } + if ref == nil || ref.CaptureEvidence == nil { + return fmt.Errorf("scan has no capture-session provenance; run a new dense scan") + } + if e := scanCaptureEvidenceValid(ref.CaptureEvidence, ref, time.Now()); e != nil { + return fmt.Errorf("flat-site screen needs a fresh scan: %w", e) + } + camCurMu.Lock() + s := camCur + ok := s != nil && camSessionAlive(s.done) && s.captureID == ref.CaptureEvidence.SessionID && s.identity == ref.CaptureEvidence.Source.CameraID + camCurMu.Unlock() + if !ok { + return fmt.Errorf("scan camera session changed; run a new dense scan") + } + camMu.Lock() + ok = camW == ref.CamW && camH == ref.CamH + camMu.Unlock() + if !ok { + return fmt.Errorf("scan camera dimensions changed") + } + return nil +} + +// Revalidate live session before each projected marker and before committing. +type flatScanIO363Windows struct { + winScanIO + ref *ScanRef +} + +func (io flatScanIO363Windows) FlatGuard363() error { return flatScanSession363(io.ref) } + +type flatLargerIO363Windows struct{ flatScanIO363Windows } + +func (io flatLargerIO363Windows) Dots(p [][2]float64, r float64) { io.winScanIO.Dots(p, r*1.5) } diff --git a/flat_dots363_windows_test.go b/flat_dots363_windows_test.go new file mode 100644 index 0000000..4ca0f53 --- /dev/null +++ b/flat_dots363_windows_test.go @@ -0,0 +1,73 @@ +//go:build windows + +package main + +import ( + "strings" + "testing" + "time" +) + +func Test363NativeSessionGuardBindings(t *testing.T) { + camCurMu.Lock() + saved := camCur + camCurMu.Unlock() + camMu.Lock() + w, h := camW, camH + camMu.Unlock() + wasFake := fakeCam + defer func() { + camCurMu.Lock() + camCur = saved + camCurMu.Unlock() + camMu.Lock() + camW, camH = w, h + camMu.Unlock() + fakeCam = wasFake + }() + now := time.Now() + src := PumpkinCapture{ID: "session:1", CameraID: "camera", RigID: "rig", CalibrationID: "cal", SceneID: "scene", At: now.Add(-time.Minute), Width: 320, Height: 240} + end := src + end.ID = "session:2" + end.At = now.Add(-time.Second) + ref := &ScanRef{CamW: 320, CamH: 240, CaptureEvidence: &ScanCaptureEvidence{Source: src, End: end, SessionID: "session", SourcePhoto: "fixture-source.jpg", SourceSHA256: strings.Repeat("a", 64)}} + session := &camSession{captureID: "session", identity: "camera", done: make(chan struct{})} + camCurMu.Lock() + camCur = session + camCurMu.Unlock() + camMu.Lock() + camW, camH = 320, 240 + camMu.Unlock() + fakeCam = false + if e := flatScanSession363(ref); e != nil { + t.Fatal(e) + } + for _, kind := range []string{"missing", "stale", "identity", "session", "dimensions", "closed", "virtual"} { + original := *ref.CaptureEvidence + session.identity = "camera" + session.captureID = "session" + session.done = make(chan struct{}) + camW = 320 + fakeCam = false + switch kind { + case "missing": + ref.CaptureEvidence = nil + case "stale": + ref.CaptureEvidence.Source.At = now.Add(-6 * time.Minute) + case "identity": + session.identity = "other" + case "session": + session.captureID = "replacement" + case "dimensions": + camW = 640 + case "closed": + close(session.done) + case "virtual": + fakeCam = true + } + if e := flatScanSession363(ref); e == nil { + t.Fatal("binding admitted", kind) + } + ref.CaptureEvidence = &original + } +} diff --git a/graycore.go b/graycore.go index d775cd6..81d7393 100644 --- a/graycore.go +++ b/graycore.go @@ -1405,7 +1405,8 @@ func verifyScan(io scanIO, res *scanResult, surfs []Surface) (int, float64, floa n,m,w,r,_ := verifyScanComplete355(io,res,surfs); return n,m,w,r } func verifyScanComplete355(io scanIO, res *scanResult, surfs []Surface) (seen int, mean, worst float64, report []string, complete bool) { - grid := calibGridN(4, 3) + if guard,ok:=io.(interface{FlatGuard363()error});ok{if e:=guard.FlatGuard363();e!=nil{return 0,0,0,[]string{"UNVERIFIED: "+e.Error()},false}} + var grid [][2]float64 surfErr := map[string][]float64{} var surfOrder []string surfName := map[string]string{} @@ -1418,25 +1419,27 @@ func verifyScanComplete355(io scanIO, res *scanResult, surfs []Surface) (seen in } base := io.Gray(3) - vinv := buildScanInverse(res) + vinv:=buildScanInverse(res) + if !showPatternAcked(io,PatternToken{Kind:"white",Axis:-1,Bit:-1},io.White,vrun,&vseq,400,2,nil,vfail){return 0,0,0,[]string{"flat-site screen: white reference was not presented"},false} + lit:=io.Gray(3) + if !showPatternAcked(io,PatternToken{Kind:"black",Axis:-1,Bit:-1},io.Black,vrun,&vseq,200,2,nil,vfail){return 0,0,0,[]string{"flat-site screen: black return was not presented"},false} + screened:=flatIllumination363(base,lit) + sites,planErr:=flatDotPlan363(res,vinv,screened,surfs) + if planErr!=nil{return 0,0,0,[]string{"UNVERIFIED: "+planErr.Error()},false} + for _,site:=range sites{grid=append(grid,site.Projector)} + report=append(report,"12 distributed sites screened for local correspondence consistency, full dot footprint, clipping and mapped obstacles; not proof of physical flatness or camera immobility") for _, p := range grid { + if guard,ok:=io.(interface{FlatGuard363()error});ok{if e:=guard.FlatGuard363();e!=nil{if seen>0{mean/=float64(seen)};return seen,mean,worst,append(report,"UNVERIFIED: "+e.Error()),false}} + exp,predOK:=scanPredict(vinv,p,2) + if !predOK{if seen>0{mean/=float64(seen)};return seen,mean,worst,append(report,"scan address became unavailable"),false} if !showPatternAcked(io, PatternToken{Kind: "dots", Axis: -1, Bit: -1}, func() { io.Dots([][2]float64{p}, 0.006) }, vrun, &vseq, 400, 2, nil, vfail) { report = append(report, "the projector stopped painting fiducials - verify stopped early") if seen > 0 { mean /= float64(seen) }; return seen, mean, worst, report, false } g := io.Gray(3) + if g.W!=res.W||g.H!=res.H||len(g.G)!=res.W*res.H{io.Black();if seen>0{mean/=float64(seen)};return seen,mean,worst,append(report,"UNVERIFIED: camera frame changed during verification"),false} d := diffImg(base, g) - exp := [2]float64{p[0], p[1]} - if vinv != nil { - jx, jy := int(p[0]*float64(res.ProjW)), int(p[1]*float64(res.ProjH)) - if jx >= 0 && jy >= 0 && jx < res.ProjW && jy < res.ProjH { - j := jy*res.ProjW + jx - if vinv.Valid[j] { - exp = [2]float64{float64(vinv.X[j]) / float64(res.W), float64(vinv.Y[j]) / float64(res.H)} - } - } - } b := findBlob(d, &exp, 1.0/6.0, 30) if !showPatternAcked(io, PatternToken{Kind: "black", Axis: -1, Bit: -1}, io.Black, vrun, &vseq, 200, 2, nil, vfail) { report = append(report, "the projector stopped painting between fiducials - verify stopped early") diff --git a/scanrun.go b/scanrun.go index ec728e9..44bba63 100644 --- a/scanrun.go +++ b/scanrun.go @@ -788,73 +788,13 @@ func (a *app) scanWithOwner(ctx context.Context, continuation func(*camSession, } } -func (a *app) scanVerify() { - if !camJobStart("scan verify") { - return - } - defer camJobEnd() - defer calGuard("Scan verify")() - if !a.projOpen && !fakeCam { - logf("Verify needs the projector window. Click Open projector first.") - return - } - a.pl.mu.Lock() - ref := a.pl.P.Scan - a.pl.mu.Unlock() - if ref == nil { - logf("No scan yet - run Start the scan first.") - return - } - res, err := loadScan(ref) - if err != nil { - logf("ERROR could not read the saved scan: %v. Run the scan again.", err) - return - } - if !fakeCam { - if _, err := startCamera(); err != nil { - logf("ERROR camera: %v", err) - return - } - } - logf("Verify: projecting 12 markers, camera measures each...") - a.pl.mu.Lock() - surfs := append([]Surface(nil), a.pl.P.Surfaces...) - a.pl.mu.Unlock() - seen, mean, worst, report, complete := verifyScanComplete355(winScanIO{}, res, surfs) - - A.presMu.Lock() - pat.clear() - A.presTok = PatternToken{} - A.presMu.Unlock() - for _, line := range report { - logf("Verify: %s", line) - } - if seen == 0 { - logf("Verify FAILED: the camera saw NONE of the 12 markers. Check the camera actually points at the lit wall, the projector window is on the projector (not a monitor), the room is dark, and the lens cap is off. Your saved scan is untouched.") - return - } - if seen < 12 { - logf("Verify: only %d of 12 markers were seen - treat the numbers below with suspicion.", seen) - } - - - if !calibrationCheckGood355(seen,complete,mean,worst) { - scanMapUnverified.Store(true) - logf("Verify: UNVERIFIED (complete=%v, %d/12 markers, %.1f px average, %.1f worst). No verified receipt saved.",complete,seen,mean,worst) - return - } - calibStateMu.Lock() - a.pl.mu.Lock() - if a.pl.P.Scan != nil && a.pl.P.Scan.XFile == ref.XFile && a.pl.P.Scan.At == ref.At { - a.pl.P.Scan.VerifN, a.pl.P.Scan.VerifMean, a.pl.P.Scan.VerifWorst, a.pl.P.Scan.VerifAt = seen, mean, worst, time.Now().Unix() - a.pl.P.Scan.VerifCam, a.pl.P.Scan.VerifCamRes, a.pl.P.Scan.VerifProjRes = camName(a.st.Camera), [2]int{camW, camH}, a.pl.P.Map.ProjRes - if serr := a.pl.P.save(a.cur.Path); serr != nil { - logf("NOTE: could not save the verify result (%v) - the numbers above stand for this session only.", serr) - } - } - a.pl.mu.Unlock() - calibStateMu.Unlock() - logf("Verify: average error %.1f projector px, worst %.1f over %d markers. Under ~2 px average is excellent for a full show; edges worse than center usually means the camera moved since the scan - re-scan.", mean, worst, seen) +//363: use the same owned, bound, guarded dense check as Auto calibrate. +func(a *app)scanVerify(){ + if a.pl==nil{return} + a.pl.mu.Lock();hasScan:=a.pl.P!=nil&&a.pl.P.Scan!=nil;active:=hasScan&&scanActiveFor(a.pl.P,a.pl.P.Map.ProjRes);a.pl.mu.Unlock() + if !hasScan{logf("No scan yet. Run Start the scan first.");return} + if !active{logf("Scan does not match current projector output. Run a new scan; no verification dots projected.");return} + a.checkCalibration() } func safeFrac(res *scanResult) float64 {