import Foundation import SwiftUI import ImageIO #if GROUNDROOM_SELF_TEST && os(macOS) import AppKit #endif import UniformTypeIdentifiers enum GardenError: LocalizedError { case bad(String); var errorDescription: String? { if case .bad(let s)=self{return s};return nil } } struct Point: Codable, Equatable { var x:Double; var y:Double; var z:Double func valid(_ bound:Double=1e12)->Bool {[x,y,z].allSatisfy{$0.isFinite && abs($0)Self { guard version==1,house.count%3==0,house.count<=Mesh.maxTriangles*3,house.allSatisfy({$0.valid(1001)}),plants.count<=500,plants.allSatisfy({[$0.x,$0.z].allSatisfy{$0.isFinite && abs($0)<=1000}}) else {throw GardenError.bad("Invalid project geometry or plant count.")} return self } } enum Mesh { static let maxBytes=8*1024*1024,maxTriangles=60_000 static func checked(_ v:[Point])throws->[Point] { guard !v.isEmpty,v.count%3==0,v.count<=maxTriangles*3,v.allSatisfy({$0.valid()}) else {throw GardenError.bad("Invalid STL mesh. Check coordinate and triangle limits.")} return v } static func parse(_ data:Data)throws->[Point] { guard data.count>=15,data.count<=maxBytes else {throw GardenError.bad("Use an STL below 8 MB.")} func word(_ k:Int)->UInt32 { data.withUnsafeBytes{UInt32(littleEndian:$0.loadUnaligned(fromByteOffset:k,as:UInt32.self))} } if data.count>=84 { let n=Int(word(80)) if n>0,84+n*50==data.count { guard n<=maxTriangles else {throw GardenError.bad("Up to 60,000 triangles are supported.")} var v:[Point]=[];v.reserveCapacity(n*3) for i in 0..2,(l.count-2)%7==0 else {throw GardenError.bad("Invalid ASCII STL structure.")} guard (l.count-2)/7<=maxTriangles else {throw GardenError.bad("Up to 60,000 triangles are supported.")} var v:[Point]=[] for i in stride(from:1,to:l.count-1,by:7) { guard l[i].count==5,l[i][0...1].map({$0.lowercased()})==["facet","normal"],l[i].dropFirst(2).allSatisfy({Double($0)?.isFinite==true}),l[i+1].map({$0.lowercased()})==["outer","loop"],l[i+5].map({$0.lowercased()})==["endloop"],l[i+6].map({$0.lowercased()})==["endfacet"] else {throw GardenError.bad("Invalid ASCII STL face.")} for j in 2...4 { let p=l[i+j];guard p.count==4,p[0].lowercased()=="vertex",let x=Double(p[1]),let y=Double(p[2]),let z=Double(p[3]) else {throw GardenError.bad("Invalid ASCII STL vertex.")};v.append(.init(x:x,y:y,z:z)) } } return try checked(v) } static func orient(_ v:[Point],units:Units,up:Up)throws->[Point] { let scale=units.scale let a=try checked(v).map{up == .Y ? Point(x:$0.x*scale,y:$0.y*scale,z:$0.z*scale) : Point(x:$0.x*scale,y:$0.z*scale,z:(-$0.y)*scale)} let x=a.map(\.x),y=a.map(\.y),z=a.map(\.z) let mx=x.min()!,my=y.min()!,mz=z.min()! let dx=x.max()!-mx,dy=y.max()!-my,dz=z.max()!-mz guard max(dx,dy,dz)<=1000 else {throw GardenError.bad("House exceeds 1,000 metres. Check the export units.")} return a.map{Point(x:$0.x-(mx+dx/2),y:$0.y-my,z:$0.z-(mz+dz/2))} } static func house(width:Double=6,depth:Double=4,wall:Double=2,rise:Double=1)->[Point] { let p:[Point]=[.init(x:-3,y:0,z:-2),.init(x:3,y:0,z:-2),.init(x:3,y:0,z:2),.init(x:-3,y:0,z:2),.init(x:-3,y:2,z:-2),.init(x:3,y:2,z:-2),.init(x:3,y:2,z:2),.init(x:-3,y:2,z:2),.init(x:0,y:3,z:-2),.init(x:0,y:3,z:2)] let scaled=p.map { Point(x:$0.x * width/6,y:$0.y<=2 ? $0.y*wall/2 : wall+rise,z:$0.z*depth/4) } return [[0,1,5],[0,5,4],[1,2,6],[1,6,5],[2,3,7],[2,7,6],[3,0,4],[3,4,7],[4,5,8],[7,6,9],[4,8,9],[4,9,7],[8,5,6],[8,6,9]].flatMap{$0.map{scaled[$0]}} } } struct GardenDocument:FileDocument { static var readableContentTypes:[UTType]{[.json]} var value:Garden init(value:Garden){self.value=value} init(configuration:ReadConfiguration)throws {guard let data=configuration.file.regularFileContents,data.count<=16*1024*1024 else{throw GardenError.bad("Project exceeds 16 MB.")};value=try JSONDecoder().decode(Garden.self,from:data).checked()} func fileWrapper(configuration:WriteConfiguration)throws->FileWrapper {.init(regularFileWithContents:try JSONEncoder().encode(value.checked()))} } struct Projection { let size:CGSize;let angle:Double;let scale:Double func point(_ p:Point)->(CGPoint,Double) {let u=p.x*cos(angle)-p.z*sin(angle),v=p.x*sin(angle)+p.z*cos(angle);return (CGPoint(x:size.width/2+u*scale,y:size.height*0.61+(v*0.46-p.y)*scale),v+p.y*0.23)} func ground(_ p:CGPoint)->(Double,Double) { let u=(p.x-size.width/2)/scale,v=(p.y-size.height*0.61)/(0.46*scale) return (u*cos(angle)+v*sin(angle),(-u)*sin(angle)+v*cos(angle)) } } struct GardenView: View { @State private var garden:Garden let snapshot:Bool init(initial:Garden=Garden(),snapshot:Bool=false){_garden=State(initialValue:initial);self.snapshot=snapshot} @State private var pending:[Point]=[] @State private var units:Units?=nil @State private var up:Up?=nil @State private var species:Species = .Tree @State private var coordsX="2" @State private var coordsZ="2" @State private var status="Build a house template or choose a reference photo." @State private var angle=Double.pi/4 enum ImportKind {case stl,plan,photo} @State private var importKind:ImportKind = .stl @State private var importing=false @State private var exporting=false @State private var photo:CGImage? @State private var width="6" @State private var depth="4" @State private var wall="2" @State private var rise="1" var body:some View { GeometryReader { metrics in if metrics.size.width >= 740 { HStack(spacing:0){ controls.frame(width:260); Divider(); workspace } } else { VStack(spacing:0){ workspace.frame(height:min(350,max(200,metrics.size.height*0.48))) Divider() controls } } } .fileImporter(isPresented:$importing,allowedContentTypes:allowedType){r in switch importKind { case .stl: pending=[];units=nil;up=nil file(r,max:Mesh.maxBytes){d in pending=try Mesh.parse(d);status="Loaded \(pending.count/3) triangles. Choose units and up axis."} case .plan: file(r,max:16*1024*1024){d in garden=try JSONDecoder().decode(Garden.self,from:d).checked();photo=nil;if let q=garden.spec{width=String(q.width);depth=String(q.depth);wall=String(q.wall);rise=String(q.rise)};status="Saved garden loaded."} case .photo: file(r,max:12*1024*1024){d in let options = [kCGImageSourceCreateThumbnailFromImageAlways:true, kCGImageSourceCreateThumbnailWithTransform:true, kCGImageSourceThumbnailMaxPixelSize:1024] as CFDictionary guard let imageSource=CGImageSourceCreateWithData(d as CFData,nil),let thumbnail=CGImageSourceCreateThumbnailAtIndex(imageSource,0,options) else {throw GardenError.bad("Couldn’t read that photo.")} photo=thumbnail if garden.house.isEmpty {makeTemplate()} status="Reference photo added. Adjust the editable starter house to match." } } } .fileExporter(isPresented:$exporting,document:GardenDocument(value:garden),contentType:.json,defaultFilename:"Groundroom Plan"){result in switch result{case .success:status="Garden plan saved.";case .failure(let e):status=e.localizedDescription} } } @ViewBuilder private var controls:some View { if snapshot {controlFields} else { ScrollView {controlFields} } } private var controlFields:some View { VStack(alignment:.leading,spacing:13){ Text("Groundroom").font(.title2.bold()) Text("Local prototype").font(.subheadline).foregroundStyle(.secondary) Divider() Text("House model").font(.headline) LabeledContent("Width (m)"){TextField("",text:$width).textFieldStyle(.roundedBorder).frame(width:68)} LabeledContent("Depth (m)"){TextField("",text:$depth).textFieldStyle(.roundedBorder).frame(width:68)} LabeledContent("Wall height (m)"){TextField("",text:$wall).textFieldStyle(.roundedBorder).frame(width:68)} LabeledContent("Roof rise (m)"){TextField("",text:$rise).textFieldStyle(.roundedBorder).frame(width:68)} Button("Apply house dimensions"){makeTemplate()} Button("Choose reference photo…"){importKind = .photo;importing=true} if let photo {Image(decorative:photo,scale:1).resizable().scaledToFit().frame(maxHeight:105).accessibilityLabel("Local reference photo") Text("Adjust the starter house dimensions to match. The photo isn’t automatically reconstructed.").font(.caption).foregroundStyle(.secondary) } Button("Import STL (optional)…"){importKind = .stl;importing=true} Picker("Export units",selection:$units){Text("Choose").tag(Units?.none);ForEach(Units.allCases,id:\.self){Text($0.rawValue).tag(Optional($0))}} Picker("Up axis",selection:$up){Text("Choose").tag(Up?.none);ForEach(Up.allCases,id:\.self){Text($0.rawValue).tag(Optional($0))}} Button("Apply scale and orientation"){if let units,let up {do{garden.house=try Mesh.orient(pending,units:units,up:up);garden.spec=nil;status="House centred on the ground."}catch{status=error.localizedDescription}}} .disabled(pending.isEmpty || units==nil || up==nil) Text("STL does not include units. Match your CAD export.").font(.caption).foregroundStyle(.secondary) Divider() Text("Place plants").font(.headline) Picker("Plant form", selection:$species){ForEach(Species.allCases,id:\.self){Text($0.rawValue).tag($0)}} TextField("East / west (m)",text:$coordsX) TextField("North / south (m)",text:$coordsZ) Button("Place at coordinates"){if let x=Double(coordsX),let z=Double(coordsZ){plant(x,z)}else{status="Enter numeric metre coordinates."}} Button("Undo last plant"){_ = garden.plants.popLast();status="Last plant removed."}.disabled(garden.plants.isEmpty) Divider() Button("Save project…"){exporting=true} Button("Open project…"){importKind = .plan;importing=true} }.padding(22).frame(maxWidth:.infinity,alignment:.leading) } private var workspace:some View { VStack(alignment:.leading,spacing:12){ HStack{Text("Garden workspace").font(.headline);Spacer();Button("Rotate view"){angle += .pi/4}} GeometryReader{ geo in let p=projection(geo.size) Canvas{ context,_ in render(context,p) } .background(Color(red:0.87,green:0.90,blue:0.83)) .clipShape(.rect(cornerRadius:12)) .contentShape(Rectangle()) .gesture(SpatialTapGesture().onEnded{v in let (x,z)=p.ground(v.location);plant(x,z)}) .accessibilityLabel("Isometric garden preview") .accessibilityHint("Use the coordinate fields to place a plant without a pointer.") } Text(status).accessibilityAddTraits(.updatesFrequently) Text("\(garden.plants.count) plants · No upload · Placeholder plant forms").font(.caption).foregroundStyle(.secondary) }.padding(20) } private var allowedType:[UTType]{switch importKind{case .stl:[UTType(filenameExtension:"stl") ?? .data];case .plan:[.json];case .photo:[.jpeg,.png,.heic]}} private func makeTemplate(){ guard let a=Double(width),let b=Double(depth),let c=Double(wall),let d=Double(rise),[a,b,c].allSatisfy({$0.isFinite && $0>0 && $0<=100}),d.isFinite,d>=0,d<=30 else {status="Use dimensions above 0 and up to 100 metres, and a roof rise from 0 to 30.";return} garden.spec=HouseSpec(width:a,depth:b,wall:c,rise:d);garden.house=Mesh.house(width:a,depth:b,wall:c,rise:d);status="Editable house template added." } private func file(_ r:Result,max:Int,action:(Data)throws->Void){ do{let url=try r.get(),scope=url.startAccessingSecurityScopedResource();defer{if scope{url.stopAccessingSecurityScopedResource()}} let h=try FileHandle(forReadingFrom:url);defer{try? h.close()} let data=try h.read(upToCount:max+1) ?? Data();guard data.count<=max else{throw GardenError.bad("File exceeds the prototype size limit.")};try action(data) }catch{status=error.localizedDescription} } private func plant(_ x:Double,_ z:Double){ guard x.isFinite,z.isFinite,abs(x)<=1000,abs(z)<=1000,garden.plants.count<500 else{status="Try coordinates within ±1,000 metres, or remove a plant (500 max).";return} garden.plants.append(.init(type:species,x:x,z:z));status="\(species.rawValue) placed." } private func projection(_ s:CGSize)->Projection { let span=max(12,garden.house.map{hypot($0.x,$0.z)*2}.max() ?? 0) let height=garden.house.map(\.y).max() ?? 0 return .init(size:s,angle:angle,scale:max(1,min(s.width*0.78/span,s.height*0.48/(span*0.36+height)))) } private struct DrawItem{let depth:Double;let path:Path;let fill:Color?;let stroke:Color?} private func render(_ context:GraphicsContext,_ p:Projection){ let extent=min(1000,max(18,Int(p.size.width/max(1,p.scale)))) let step=max(1,extent/25) let grid=Color(red:0.73,green:0.77,blue:0.68) func ground(_ x:Int,_ z:Int)->CGPoint{p.point(.init(x:Double(x),y:0,z:Double(z))).0} for i in stride(from:-extent,to:extent+1,by:step){context.stroke(Path{v in v.move(to:ground(i,-extent));v.addLine(to:ground(i,extent));v.move(to:ground(-extent,i));v.addLine(to:ground(extent,i))},with:.color(grid),lineWidth:0.6)} var items:[DrawItem]=[] for n in stride(from:0,to:garden.house.count,by:3) { let (a,da)=p.point(garden.house[n]),(b,db)=p.point(garden.house[n+1]),(c,dc)=p.point(garden.house[n+2]) let face=Path{v in v.move(to:a);v.addLine(to:b);v.addLine(to:c);v.closeSubpath()} items.append(.init(depth:(da+db+dc)/3,path:face,fill:Color(red:0.81,green:0.75,blue:0.66),stroke:.brown)) } for plant in garden.plants{ let (base,depth)=p.point(.init(x:plant.x,y:0,z:plant.z)),(top,_)=p.point(.init(x:plant.x,y:plant.type.height,z:plant.z)),radius=max(2,p.scale*plant.type.spread) items.append(.init(depth:depth,path:Path{v in v.move(to:base);v.addLine(to:top)},fill:nil,stroke:.brown)) items.append(.init(depth:depth+0.01,path:Path(ellipseIn:.init(x:top.x-radius,y:top.y-radius*0.69,width:radius*2,height:radius*1.38)),fill:plant.type.color,stroke:nil)) } for i in items.sorted(by:{$0.depth<$1.depth}){if let fill=i.fill{context.fill(i.path,with:.color(fill))};if let stroke=i.stroke{context.stroke(i.path,with:.color(stroke),lineWidth:0.8)}} } } @main struct GroundroomApp:App { #if GROUNDROOM_SELF_TEST @MainActor static func main() { if let i=CommandLine.arguments.firstIndex(of:"--snapshot"),CommandLine.arguments.count>i+1 { do {try capture(to:CommandLine.arguments[i+1]);return} catch {print(error.localizedDescription);exit(2)} } do {try tests();print("Groundroom tests passed: ASCII/binary STL, malformed/oversize input, units and orientation, editable house dimensions, projection round trip, project save/load.")} catch {print(error.localizedDescription);exit(1)} } #endif #if os(visionOS) @StateObject private var walkthrough = WalkthroughState() #endif var body:some Scene { WindowGroup("Groundroom"){ #if os(visionOS) TabView { GardenView().tabItem { Label("Design", systemImage: "square.grid.2x2") } WalkthroughWindow(state: walkthrough).tabItem { Label("Sample walkthrough", systemImage: "visionpro") } } #else GardenView() #endif } #if os(visionOS) ImmersiveSpace(id:"groundroom-walkthrough"){WalkthroughRoom(state:walkthrough)} .immersionStyle(selection:.constant(.mixed),in:.mixed) #endif } } #if GROUNDROOM_SELF_TEST @MainActor func capture(to path:String)throws { let sample=Garden(spec:.init(width:6,depth:4,wall:2,rise:1),house:Mesh.house(),plants:[.init(type:.Tree,x:2,z:3),.init(type:.Shrub,x:-3,z:3),.init(type:.Grass,x:4,z:2)]) let renderer=ImageRenderer(content:GardenView(initial:sample,snapshot:true).frame(width:1200,height:840).background(Color.white).environment(\.colorScheme,.light)) renderer.scale=1 guard let image=renderer.nsImage,let tiff=image.tiffRepresentation,let rep=NSBitmapImageRep(data:tiff),let png=rep.representation(using:.png,properties:[:]) else{throw GardenError.bad("Could not render native preview.")} try png.write(to:URL(fileURLWithPath:path)) print("Rendered native Groundroom SwiftUI editor (synthetic model).") } func tests()throws{ let ascii=Data("solid demo\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1000 0 0\nvertex 0 1500 2000\nendloop\nendfacet\nendsolid demo".utf8) let mesh=try Mesh.parse(ascii);precondition(mesh.count==3) var binary=Data(repeating:0,count:134) func put(_ name:UInt32,_ location:Int){var word=name.littleEndian;withUnsafeBytes(of:&word){binary.replaceSubrange(location..