subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

PlannerView.swift (18204B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import DivePlanner
      3 import SwiftUI
      4 
      5 /// Planning tools: a quick no-stop calculation, the decompression planner, and gas calculations.
      6 struct PlannerView: View {
      7     enum Mode: String, CaseIterable { case simple, technical, gas }
      8     @AppStorage("plannerMode") private var mode = LaunchOptions.value("-planner").flatMap(Mode.init(rawValue:)) ?? Mode.simple
      9 
     10     var body: some View {
     11         NavigationStack {
     12             Group {
     13                 switch mode {
     14                 case .simple: SimplePlanView()
     15                 case .technical: TechPlanView()
     16                 case .gas: GasToolsView()
     17                 }
     18             }
     19             .navigationTitle("Planning")
     20             .navigationBarTitleDisplayMode(.inline)
     21             .safeAreaInset(edge: .top, spacing: 0) {
     22                 Picker("Tool", selection: $mode) {
     23                     Text("No-stop").tag(Mode.simple)
     24                     Text("Decompression").tag(Mode.technical)
     25                     Text("Gas").tag(Mode.gas)
     26                 }
     27                 .pickerStyle(.segmented)
     28                 .padding(.horizontal)
     29                 .padding(.vertical, 8)
     30                 .background(.bar)
     31             }
     32         }
     33         .onAppear {
     34             if let forced = LaunchOptions.value("-planner").flatMap(Mode.init(rawValue:)) { mode = forced }
     35         }
     36     }
     37 }
     38 
     39 /// A figure with a fixed number of decimals, written the way the user's region writes numbers.
     40 func fixed(_ value: Double, _ digits: Int) -> String {
     41     value.formatted(.number.precision(.fractionLength(digits)))
     42 }
     43 
     44 /// What every planning screen ends with.
     45 struct PlanningDisclaimer: View {
     46     var body: some View {
     47         Text("A planning aid, not a dive computer: models differ, and so do divers. Check a decompression plan against another tool, dive within your training, and follow your dive computer in the water.")
     48     }
     49 }
     50 
     51 /// A number with its unit on one row of a form.
     52 struct NumberRow: View {
     53     let title: LocalizedStringKey
     54     @Binding var value: Double
     55     let unit: String
     56     var digits = 0
     57     var range: ClosedRange<Double>?
     58     var step: Double?
     59 
     60     var body: some View {
     61         HStack {
     62             Text(title)
     63             Spacer(minLength: 8)
     64             TextField("0", value: clamped, format: .number.precision(.fractionLength(0...digits)))
     65                 .keyboardType(.decimalPad)
     66                 .multilineTextAlignment(.trailing)
     67                 .frame(width: 72)
     68             Text(unit).foregroundStyle(.secondary).frame(minWidth: 34, alignment: .leading)
     69             if let step {
     70                 Stepper(title, value: clamped, step: step).labelsHidden()
     71             }
     72         }
     73     }
     74 
     75     private var clamped: Binding<Double> {
     76         Binding {
     77             value
     78         } set: { new in
     79             value = range.map { min(max(new, $0.lowerBound), $0.upperBound) } ?? new
     80         }
     81     }
     82 }
     83 
     84 extension Units {
     85     /// A depth kept in metres, edited in the units on screen (whole feet, or tenths of a metre).
     86     func depthBinding(_ meters: Binding<Double>) -> Binding<Double> {
     87         Binding {
     88             let shown = depthValue(meters.wrappedValue)
     89             return imperial ? shown.rounded() : (shown * 10).rounded() / 10
     90         } set: {
     91             meters.wrappedValue = max(0, metersFromDisplay($0))
     92         }
     93     }
     94 
     95     func pressureBinding(_ bar: Binding<Double>) -> Binding<Double> {
     96         Binding {
     97             pressureValue(bar.wrappedValue).rounded()
     98         } set: {
     99             bar.wrappedValue = max(0, barFromDisplay($0))
    100         }
    101     }
    102 
    103     /// Step of a depth stepper, in the units on screen.
    104     var depthStep: Double { imperial ? 5 : 1 }
    105 }
    106 
    107 /// Gradient factors by name, the way dive computers offer them.
    108 enum Conservatism: String, CaseIterable, Identifiable {
    109     case low, medium, high
    110     var id: String { rawValue }
    111     var gradientFactors: (low: Double, high: Double) {
    112         switch self {
    113         case .low: return (0.45, 0.95)
    114         case .medium: return (0.40, 0.85)
    115         case .high: return (0.35, 0.75)
    116         }
    117     }
    118     var label: String {
    119         switch self {
    120         case .low: return String(localized: "Low (GF 45/95)")
    121         case .medium: return String(localized: "Medium (GF 40/85)")
    122         case .high: return String(localized: "High (GF 35/75)")
    123         }
    124     }
    125 }
    126 
    127 struct CylinderPreset: Identifiable {
    128     let name: String
    129     let liters: Double
    130     let bar: Double
    131     var id: String { name }
    132     static let all = [
    133         CylinderPreset(name: "AL80", liters: 11.1, bar: 207), CylinderPreset(name: "AL63", liters: 9.0, bar: 207),
    134         CylinderPreset(name: "AL40", liters: 5.7, bar: 207), CylinderPreset(name: "HP100", liters: 12.9, bar: 237),
    135         CylinderPreset(name: "HP130", liters: 16.8, bar: 237), CylinderPreset(name: "10 L", liters: 10, bar: 232),
    136         CylinderPreset(name: "12 L", liters: 12, bar: 232), CylinderPreset(name: "15 L", liters: 15, bar: 232),
    137         CylinderPreset(name: "2 × 12 L", liters: 24, bar: 232),
    138     ]
    139 }
    140 
    141 // MARK: No-stop diving
    142 
    143 /// The quick answer for a recreational dive: how long at this depth, on this gas, with this cylinder.
    144 struct SimplePlanView: View {
    145     @Environment(AppModel.self) private var model
    146     @AppStorage("simplePlanDepth") private var depth = 18.0
    147     @AppStorage("simplePlanO2") private var o2 = 21.0
    148     @AppStorage("simplePlanVolume") private var volume = 11.1
    149     @AppStorage("simplePlanPressure") private var pressure = 200.0
    150     @AppStorage("simplePlanReserve") private var reserve = 50.0
    151     @AppStorage("simplePlanSAC") private var sac = 18.0
    152     @AppStorage("simplePlanConservatism") private var conservatism = Conservatism.medium
    153     @AppStorage("simplePlanFreshWater") private var freshWater = false
    154     @State private var table: [(depth: Double, minutes: Int?)] = []
    155 
    156     private var gas: BreathingGas { BreathingGas(o2: o2 / 100) }
    157 
    158     private var settings: PlanSettings {
    159         var settings = PlanSettings()
    160         settings.gfLow = conservatism.gradientFactors.low
    161         settings.gfHigh = conservatism.gradientFactors.high
    162         settings.sacBottom = sac
    163         settings.sacDeco = sac
    164         settings.environment = freshWater ? .freshWater : .sea
    165         return settings
    166     }
    167 
    168     var body: some View {
    169         let units = model.units
    170         let settings = settings
    171         let noStop = DivePlanner.noStopLimit(depth: depth, gas: gas, settings: settings)
    172         let gasTime = DivePlanner.gasLimit(depth: depth, volumeLiters: volume, startBar: pressure, reserveBar: reserve, settings: settings)
    173         let ppO2 = gas.ppO2(atDepth: depth, in: settings.environment)
    174         let mod = gas.maximumOperatingDepth(ppO2: 1.4, in: settings.environment)
    175         Form {
    176             Section {
    177                 NumberRow(title: "Depth", value: units.depthBinding($depth), unit: units.depthUnit, digits: units.imperial ? 0 : 1,
    178                           range: 0...units.depthValue(60), step: units.depthStep)
    179                 Picker("Gas", selection: $o2) {
    180                     Text("Air").tag(21.0)
    181                     Text(verbatim: "EAN32").tag(32.0)
    182                     Text(verbatim: "EAN36").tag(36.0)
    183                     if ![21, 32, 36].contains(o2) { Text(verbatim: gas.name).tag(o2) }
    184                 }
    185                 NumberRow(title: "Oxygen", value: $o2, unit: "%", range: 21...40, step: 1)
    186             }
    187 
    188             Section {
    189                 answer(noStop: noStop, gasTime: gasTime)
    190                 Grid(horizontalSpacing: 8, verticalSpacing: 8) {
    191                     GridRow {
    192                         Figure(title: "No-stop time", value: noStop.map { String(localized: "\($0) min") } ?? String(localized: "No limit"), icon: "timer")
    193                         Figure(title: "Gas lasts", value: String(localized: "\(gasTime) min"), icon: "gauge.with.dots.needle.33percent")
    194                     }
    195                     GridRow {
    196                         Figure(title: "Oxygen pressure", value: fixed(ppO2, 2) + " bar", icon: "o.circle")
    197                         Figure(title: "Deepest for this gas", value: units.depth(mod), icon: "arrow.down.to.line")
    198                     }
    199                 }
    200                 .listRowInsets(EdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12))
    201                 if ppO2 > 1.4 {
    202                     Label("Too deep for this gas: \(gas.name) should not be breathed below \(units.depth(mod)).", systemImage: "exclamationmark.triangle.fill")
    203                         .foregroundStyle(.red)
    204                         .font(.callout)
    205                 }
    206             } header: {
    207                 Text("Answer")
    208             } footer: {
    209                 Text("Times count from leaving the surface, the descent included. The gas time keeps the reserve and what the ascent and a safety stop of 3 minutes at \(units.depth(5)) take.")
    210             }
    211 
    212             Section("Cylinder") {
    213                 Menu {
    214                     ForEach(CylinderPreset.all) { preset in
    215                         Button(preset.name) { volume = preset.liters }
    216                     }
    217                 } label: {
    218                     Label("Common cylinders", systemImage: "list.bullet")
    219                 }
    220                 NumberRow(title: "Volume", value: $volume, unit: "L", digits: 1, range: 1...50)
    221                 NumberRow(title: "Pressure", value: units.pressureBinding($pressure), unit: units.pressureUnit, range: 0...units.pressureValue(350))
    222                 NumberRow(title: "Reserve", value: units.pressureBinding($reserve), unit: units.pressureUnit, range: 0...units.pressureValue(150))
    223                 NumberRow(title: "Consumption at the surface", value: $sac, unit: "L/min", digits: 1, range: 5...60, step: 1)
    224             }
    225 
    226             Section {
    227                 Picker("Conservatism", selection: $conservatism) {
    228                     ForEach(Conservatism.allCases) { Text($0.label).tag($0) }
    229                 }
    230                 Toggle("Fresh water", isOn: $freshWater)
    231             }
    232 
    233             Section {
    234                 ForEach(table, id: \.depth) { row in
    235                     HStack {
    236                         Text(units.depth(row.depth))
    237                         Spacer()
    238                         Text(row.minutes.map { String(localized: "\($0) min") } ?? String(localized: "No limit"))
    239                             .monospacedDigit()
    240                             .foregroundStyle(abs(row.depth - depth) < 1.5 ? Color.accentColor : Color.primary)
    241                     }
    242                 }
    243             } header: {
    244                 Text("No-stop times on \(gas.name)")
    245             } footer: {
    246                 PlanningDisclaimer()
    247             }
    248         }
    249         .task(id: "\(o2)-\(conservatism.rawValue)-\(freshWater)") {
    250             let gas = gas
    251             table = await Task.detached {
    252                 stride(from: 12.0, through: 42.0, by: 3.0).map { ($0, DivePlanner.noStopLimit(depth: $0, gas: gas, settings: settings)) }
    253             }.value
    254         }
    255     }
    256 
    257     /// One sentence: how long, and what sets the limit.
    258     @ViewBuilder private func answer(noStop: Int?, gasTime: Int) -> some View {
    259         let limit = min(noStop ?? .max, gasTime)
    260         VStack(alignment: .leading, spacing: 4) {
    261             Text(limit > 0 ? String(localized: "Up to \(limit) minutes") : String(localized: "Not enough gas"))
    262                 .font(.title2.weight(.semibold))
    263             Text((noStop ?? .max) <= gasTime
    264                  ? String(localized: "The no-stop time sets the limit.")
    265                  : String(localized: "The gas sets the limit."))
    266                 .font(.callout)
    267                 .foregroundStyle(.secondary)
    268         }
    269         .padding(.vertical, 2)
    270     }
    271 }
    272 
    273 // MARK: Gas
    274 
    275 /// Figures about a mix: how deep, how narcotic, how dense; and the best mix for a depth.
    276 struct GasToolsView: View {
    277     @Environment(AppModel.self) private var model
    278     @AppStorage("gasToolO2") private var o2 = 32.0
    279     @AppStorage("gasToolHe") private var he = 0.0
    280     @AppStorage("gasToolDepth") private var depth = 30.0
    281     @AppStorage("gasToolBestDepth") private var bestDepth = 45.0
    282     @AppStorage("gasToolBestPO2") private var bestPO2 = 1.4
    283     @AppStorage("gasToolLimitEND") private var limitEND = true
    284     @AppStorage("gasToolMaxEND") private var maxEND = 30.0
    285     @AppStorage("gasToolOxygenNarcotic") private var oxygenNarcotic = true
    286     @AppStorage("gasToolSAC") private var sac = 18.0
    287     @AppStorage("gasToolMinutes") private var minutes = 30.0
    288     @AppStorage("gasToolVolume") private var volume = 11.1
    289 
    290     var body: some View {
    291         let units = model.units
    292         let gas = BreathingGas(o2: o2 / 100, he: he / 100)
    293         let ppO2 = gas.ppO2(atDepth: depth)
    294         let density = gas.density(atDepth: depth)
    295         let best = BreathingGas.bestMix(forDepth: bestDepth, ppO2: bestPO2, maximumEND: limitEND ? maxEND : nil, oxygenNarcotic: oxygenNarcotic)
    296         let end = gas.equivalentNarcoticDepth(atDepth: depth, oxygenNarcotic: oxygenNarcotic)
    297         let liters = sac * DiveEnvironment.sea.pressure(atDepth: depth) * minutes
    298         Form {
    299             Section {
    300                 NumberRow(title: "Oxygen", value: $o2, unit: "%", range: 5...100, step: 1)
    301                 NumberRow(title: "Helium", value: $he, unit: "%", range: 0...(100 - o2), step: 1)
    302                 NumberRow(title: "Depth", value: units.depthBinding($depth), unit: units.depthUnit, digits: units.imperial ? 0 : 1,
    303                           range: 0...units.depthValue(150), step: units.depthStep)
    304             } header: {
    305                 Text(verbatim: gas.name)
    306             }
    307 
    308             Section("At this depth") {
    309                 row("Oxygen pressure", fixed(ppO2, 2) + " bar", alert: ppO2 > 1.6 ? .red : (ppO2 > 1.4 ? .orange : (ppO2 < 0.16 ? .red : nil)))
    310                 row("Equivalent narcotic depth", units.depth(end), alert: end > maxEND + 0.5 ? .orange : nil)
    311                 if he == 0, o2 > 21 { row("Equivalent air depth", units.depth(gas.equivalentAirDepth(atDepth: depth))) }
    312                 row("Gas density", fixed(density, 1) + " g/L", alert: density > 6.2 ? .red : (density > 5.2 ? .orange : nil))
    313             }
    314 
    315             Section {
    316                 row("Bottom gas (1.4 bar)", units.depth(gas.maximumOperatingDepth(ppO2: 1.4)))
    317                 row("Decompression (1.6 bar)", units.depth(gas.maximumOperatingDepth(ppO2: 1.6)))
    318                 if gas.minimumDepth() > 0 { row("Not breathable above", units.depth(gas.minimumDepth()), alert: .orange) }
    319             } header: {
    320                 Text("Maximum depth")
    321             }
    322 
    323             Section {
    324                 Grid(alignment: .trailing, horizontalSpacing: 12, verticalSpacing: 6) {
    325                     GridRow {
    326                         Text("Oxygen").gridColumnAlignment(.leading)
    327                         Text("Maximum depth")
    328                         Text("Narcotic depth there")
    329                     }
    330                     .font(.caption)
    331                     .foregroundStyle(.secondary)
    332                     ForEach([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6], id: \.self) { limit in
    333                         let mod = gas.maximumOperatingDepth(ppO2: limit)
    334                         GridRow {
    335                             Text(fixed(limit, 1) + " bar")
    336                             Text(units.depth(mod))
    337                             Text(units.depth(gas.equivalentNarcoticDepth(atDepth: mod, oxygenNarcotic: oxygenNarcotic)))
    338                         }
    339                         .monospacedDigit()
    340                         .fontWeight(limit == 1.4 || limit == 1.6 ? .semibold : .regular)
    341                     }
    342                 }
    343                 .frame(maxWidth: .infinity)
    344             } header: {
    345                 Text("By oxygen pressure")
    346             }
    347 
    348             Section {
    349                 Toggle("Oxygen counts as narcotic", isOn: $oxygenNarcotic)
    350                 NumberRow(title: "Narcotic depth not to pass", value: units.depthBinding($maxEND), unit: units.depthUnit,
    351                           range: units.depthValue(10)...units.depthValue(60), step: units.depthStep)
    352             } footer: {
    353                 Text("Density: 5.2 g/L is the recommended limit, 6.2 the one not to pass.")
    354             }
    355 
    356             Section {
    357                 NumberRow(title: "Depth", value: units.depthBinding($bestDepth), unit: units.depthUnit, digits: units.imperial ? 0 : 1,
    358                           range: 0...units.depthValue(150), step: units.depthStep)
    359                 Picker("Oxygen pressure", selection: $bestPO2) {
    360                     ForEach([1.2, 1.3, 1.4, 1.5, 1.6], id: \.self) { Text(fixed($0, 1) + " bar").tag($0) }
    361                 }
    362                 Toggle("Keep the narcotic depth at \(units.depth(maxEND))", isOn: $limitEND)
    363                 HStack {
    364                     Text("Best mix")
    365                     Spacer()
    366                     Text(verbatim: best.name).font(.headline)
    367                     Button("Use") {
    368                         o2 = Double(best.o2Percent)
    369                         he = Double(best.hePercent)
    370                         depth = bestDepth
    371                     }
    372                     .buttonStyle(.bordered)
    373                     .controlSize(.small)
    374                 }
    375             } header: {
    376                 Text("Best mix for a depth")
    377             }
    378 
    379             Section {
    380                 NumberRow(title: "Consumption at the surface", value: $sac, unit: "L/min", digits: 1, range: 5...60, step: 1)
    381                 NumberRow(title: "Time", value: $minutes, unit: "min", range: 0...600, step: 5)
    382                 NumberRow(title: "Cylinder", value: $volume, unit: "L", digits: 1, range: 1...50)
    383                 row("Gas needed", fixed(liters, 0) + " L")
    384                 row("In this cylinder", units.pressure(liters / max(volume, 0.1)))
    385             } header: {
    386                 Text("Consumption at \(units.depth(depth))")
    387             } footer: {
    388                 PlanningDisclaimer()
    389             }
    390         }
    391     }
    392 
    393     private func row(_ title: LocalizedStringKey, _ value: String, alert: Color? = nil) -> some View {
    394         HStack {
    395             Text(title)
    396             Spacer()
    397             if alert != nil { Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(alert ?? .orange) }
    398             Text(value).monospacedDigit().foregroundStyle(alert ?? Color.secondary)
    399         }
    400     }
    401 }