SPB Git

Repository Public License

make-icon.swift 19.7 KB 418 lines swift

1#!/usr/bin/env swift2// ORIX Navigator — app icon generator.3//4// Draws the original app icon (an orbital ring around a core with a navigation needle, on an obsidian field with a5// subtle lunar glow) with CoreGraphics and writes:6//7//   DesignSystem/AppIcon/AppIcon-1024.png                      master (macOS shape, transparent margin)8//   DesignSystem/AppIcon/AppIcon-iOS-1024{,-dark,-tinted}.png  full-bleed, opaque (no alpha channel)9//   DesignSystem/AppIcon/macOS/AppIcon.appiconset/             16…512 pt at 1x and 2x + Contents.json10//   DesignSystem/AppIcon/iOS/AppIcon.appiconset/               single 1024 universal + dark + tinted + Contents.json11//12// Usage (from the repository root):   swift scripts/make-icon.swift [output-directory]13//14// The mark geometry mirrors `LunarMarkGeometry` in Sources/LunarDesign/Icons/LunarMark.swift (100-unit grid);15// keep the two in sync. Every size is drawn from vectors, not downscaled, and thin strokes are thickened at small16// sizes so the ring survives at 16 px. There is no text in the icon.1718import CoreGraphics19import Foundation20import ImageIO21import UniformTypeIdentifiers2223// MARK: - Palette (Lunar Glass core colours)2425func rgb(_ hex: UInt32, _ alpha: CGFloat = 1) -> CGColor {26    CGColor(srgbRed: CGFloat((hex >> 16) & 0xFF) / 255, green: CGFloat((hex >> 8) & 0xFF) / 255,27            blue: CGFloat(hex & 0xFF) / 255, alpha: alpha)28}2930let srgb = CGColorSpace(name: CGColorSpace.sRGB)!3132func gradient(_ stops: [(CGFloat, CGColor)]) -> CGGradient {33    CGGradient(colorsSpace: srgb, colors: stops.map(\.1) as CFArray, locations: stops.map(\.0))!34}3536enum Variant {37    /// macOS: rounded-rectangle tile on a transparent canvas, per the macOS icon grid.38    case mac39    /// iOS default: full-bleed opaque square (the system applies the mask).40    case iOS41    /// iOS dark appearance: deeper field, same mark.42    case iOSDark43    /// iOS tinted appearance: greyscale mark on black; the system applies the tint.44    case iOSTinted45}4647struct Colors {48    var fieldTop, fieldMid, fieldBottom: CGColor49    var glow, glowSecondary: CGColor50    var ringStart, ringMid, ringEnd: CGColor51    var coreLight, coreMid, coreDark, rim: CGColor52    var needle, needleTail, satellite, star: CGColor5354    static func make(_ variant: Variant) -> Colors {55        switch variant {56        case .mac, .iOS:57            return Colors(58                fieldTop: rgb(0x141B30), fieldMid: rgb(0x0B0F1C), fieldBottom: rgb(0x05070E),59                glow: rgb(0x9BAEFF, 0.34), glowSecondary: rgb(0x927ADB, 0.20),60                ringStart: rgb(0x927ADB), ringMid: rgb(0x9BAEFF), ringEnd: rgb(0x75DFC9),61                coreLight: rgb(0x4A5BA8), coreMid: rgb(0x222C57), coreDark: rgb(0x0B0F20), rim: rgb(0xE6EAFA),62                needle: rgb(0xF4F6FF), needleTail: rgb(0x9BAEFF, 0.55), satellite: rgb(0x75DFC9),63                star: rgb(0xE6EAFA))64        case .iOSDark:65            return Colors(66                fieldTop: rgb(0x0C101D), fieldMid: rgb(0x05070E), fieldBottom: rgb(0x000000),67                glow: rgb(0x9BAEFF, 0.24), glowSecondary: rgb(0x927ADB, 0.14),68                ringStart: rgb(0x927ADB), ringMid: rgb(0x9BAEFF), ringEnd: rgb(0x75DFC9),69                coreLight: rgb(0x3A4990), coreMid: rgb(0x182046), coreDark: rgb(0x070A17), rim: rgb(0xE6EAFA),70                needle: rgb(0xF4F6FF), needleTail: rgb(0x9BAEFF, 0.55), satellite: rgb(0x75DFC9),71                star: rgb(0xE6EAFA))72        case .iOSTinted:73            return Colors(74                fieldTop: rgb(0x1C1C1C), fieldMid: rgb(0x0A0A0A), fieldBottom: rgb(0x000000),75                glow: rgb(0xFFFFFF, 0.16), glowSecondary: rgb(0xFFFFFF, 0.06),76                ringStart: rgb(0x8C8C8C), ringMid: rgb(0xE0E0E0), ringEnd: rgb(0xFFFFFF),77                coreLight: rgb(0x6A6A6A), coreMid: rgb(0x343434), coreDark: rgb(0x121212), rim: rgb(0xFFFFFF),78                needle: rgb(0xFFFFFF), needleTail: rgb(0xFFFFFF, 0.45), satellite: rgb(0xFFFFFF),79                star: rgb(0xFFFFFF))80        }81    }82}8384// MARK: - Mark geometry (mirror of LunarMarkGeometry)8586enum Mark {87    static let center = CGPoint(x: 50, y: 50)88    static let coreRadius: CGFloat = 1989    static let ringSemiMajor: CGFloat = 4590    static let ringSemiMinor: CGFloat = 15.591    static let ringTilt: CGFloat = 24 * .pi / 18092    static let needleAngle: CGFloat = -52 * .pi / 18093    static let needleLength: CGFloat = 15.594    static let needleHalfWidth: CGFloat = 4.895    static let satelliteParameter: CGFloat = -0.6296    static let satelliteRadius: CGFloat = 3.49798    static func ringPoint(_ t: CGFloat) -> CGPoint {99        let x = ringSemiMajor * cos(t), y = ringSemiMinor * sin(t)100        return CGPoint(x: center.x + x * cos(ringTilt) - y * sin(ringTilt),101                       y: center.y + x * sin(ringTilt) + y * cos(ringTilt))102    }103104    static func ringArc(from start: CGFloat, to end: CGFloat) -> CGPath {105        let path = CGMutablePath()106        let steps = 120107        for step in 0...steps {108            let point = ringPoint(start + (end - start) * CGFloat(step) / CGFloat(steps))109            if step == 0 { path.move(to: point) } else { path.addLine(to: point) }110        }111        return path112    }113114    static func needleHalf(forward: Bool) -> CGPath {115        let direction = CGPoint(x: cos(needleAngle), y: sin(needleAngle))116        let normal = CGPoint(x: -direction.y, y: direction.x)117        let sign: CGFloat = forward ? 1 : -1118        let path = CGMutablePath()119        path.move(to: CGPoint(x: center.x + direction.x * needleLength * sign,120                              y: center.y + direction.y * needleLength * sign))121        path.addLine(to: CGPoint(x: center.x + normal.x * needleHalfWidth, y: center.y + normal.y * needleHalfWidth))122        path.addLine(to: CGPoint(x: center.x - normal.x * needleHalfWidth, y: center.y - normal.y * needleHalfWidth))123        path.closeSubpath()124        return path125    }126}127128/// SplitMix64, so the handful of stars is identical on every run.129struct Generator {130    var state: UInt64131    mutating func next() -> CGFloat {132        state &+= 0x9E37_79B9_7F4A_7C15133        var z = state134        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9135        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB136        z ^= z >> 31137        return CGFloat(z >> 11) / CGFloat(1 << 53)138    }139}140141// MARK: - Drawing142143func drawIcon(pixels: Int, variant: Variant) -> CGImage {144    let size = CGFloat(pixels)145    let opaque = variant != .mac146    let context = CGContext(147        data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: 0, space: srgb,148        bitmapInfo: (opaque ? CGImageAlphaInfo.noneSkipLast : CGImageAlphaInfo.premultipliedLast).rawValue)!149    context.interpolationQuality = .high150    context.setAllowsAntialiasing(true)151    // Top-left origin, y down: the same orientation as the SwiftUI mark.152    context.translateBy(x: 0, y: size)153    context.scaleBy(x: 1, y: -1)154155    let colors = Colors.make(variant)156157    // The tile: macOS icons sit on an 824-pt rounded rectangle inside the 1024 canvas; iOS is full-bleed.158    let tile: CGRect159    let tilePath: CGPath160    if variant == .mac {161        let inset = size * 100 / 1024162        tile = CGRect(x: inset, y: inset, width: size - inset * 2, height: size - inset * 2)163        tilePath = CGPath(roundedRect: tile, cornerWidth: tile.width * 0.225, cornerHeight: tile.width * 0.225,164                          transform: nil)165        // A soft contact shadow under the tile.166        context.saveGState()167        context.setShadow(offset: CGSize(width: 0, height: size * 0.012), blur: size * 0.022,168                          color: rgb(0x000000, 0.42))169        context.addPath(tilePath)170        context.setFillColor(colors.fieldMid)171        context.fillPath()172        context.restoreGState()173    } else {174        tile = CGRect(x: 0, y: 0, width: size, height: size)175        tilePath = CGPath(rect: tile, transform: nil)176    }177178    context.saveGState()179    context.addPath(tilePath)180    context.clip()181182    // Obsidian field.183    context.drawLinearGradient(184        gradient([(0, colors.fieldTop), (0.45, colors.fieldMid), (1, colors.fieldBottom)]),185        start: CGPoint(x: tile.midX, y: tile.minY), end: CGPoint(x: tile.midX, y: tile.maxY), options: [])186187    // Lunar glow: a wide halo behind the mark and a fainter violet one low on the trailing side.188    let w = tile.width189    let glowCenter = CGPoint(x: tile.midX - w * 0.03, y: tile.midY - w * 0.05)190    context.drawRadialGradient(191        gradient([(0, colors.glow), (0.55, colors.glow.copy(alpha: colors.glow.alpha * 0.28)!),192                  (1, colors.glow.copy(alpha: 0)!)]),193        startCenter: glowCenter, startRadius: 0, endCenter: glowCenter, endRadius: w * 0.58, options: [])194    let secondCenter = CGPoint(x: tile.midX + w * 0.26, y: tile.midY + w * 0.30)195    context.drawRadialGradient(196        gradient([(0, colors.glowSecondary), (1, colors.glowSecondary.copy(alpha: 0)!)]),197        startCenter: secondCenter, startRadius: 0, endCenter: secondCenter, endRadius: w * 0.5, options: [])198199    // Mark space: the 100-unit grid, scaled to 82 % of the tile and centred.200    // Small sizes use more of the tile: there is no room for air at 16 px.201    let markSide = w * (pixels >= 128 ? 0.82 : (pixels >= 64 ? 0.9 : 0.98))202    let unit = markSide / 100203    context.translateBy(x: tile.midX - markSide / 2, y: tile.midY - markSide / 2)204    context.scaleBy(x: unit, y: unit)205    // Strokes never get thinner than about 1.2 px, whatever the size.206    func stroke(_ units: CGFloat) -> CGFloat { max(units, 1.2 / unit) }207    let detailed = pixels >= 128208209    if detailed {210        // A few stars and two faint concentric orbits, only where there are pixels to carry them.211        var generator = Generator(state: 0x4F52_4958)212        for _ in 0..<46 {213            let x = generator.next() * 124 - 12, y = generator.next() * 124 - 12214            let magnitude = generator.next()215            let distance = hypot(x - 50, y - 50)216            guard distance > 30 else { continue }217            let radius = 0.16 + magnitude * magnitude * 0.42218            context.setFillColor(colors.star.copy(alpha: 0.16 + 0.5 * magnitude)!)219            context.fillEllipse(in: CGRect(x: x - radius, y: y - radius, width: radius * 2, height: radius * 2))220        }221        for (radius, alpha) in [(CGFloat(33), CGFloat(0.13)), (CGFloat(54), CGFloat(0.08))] {222            context.setStrokeColor(colors.rim.copy(alpha: alpha)!)223            context.setLineWidth(stroke(0.32))224            context.strokeEllipse(in: CGRect(x: 50 - radius, y: 50 - radius, width: radius * 2, height: radius * 2))225        }226    }227228    let ringWidth = stroke(pixels >= 256 ? 2.5 : 3.4)229    let ringGradient = gradient([(0, colors.ringStart), (0.5, colors.ringMid), (1, colors.ringEnd)])230    func strokeRing(_ arc: CGPath, alpha: CGFloat, glow: Bool) {231        context.saveGState()232        context.setAlpha(alpha)233        if glow && detailed {234            // Luminous bloom under the ring.235            context.saveGState()236            context.setShadow(offset: .zero, blur: unit * 3.2, color: colors.ringMid.copy(alpha: 0.85)!)237            context.addPath(arc)238            context.setLineWidth(ringWidth)239            context.setLineCap(.butt)240            context.setStrokeColor(colors.ringMid.copy(alpha: 0.55)!)241            context.strokePath()242            context.restoreGState()243        }244        context.addPath(arc)245        context.setLineWidth(ringWidth)246        context.setLineCap(.butt)247        context.replacePathWithStrokedPath()248        context.clip()249        context.drawLinearGradient(ringGradient, start: Mark.ringPoint(.pi), end: Mark.ringPoint(0),250                                   options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])251        context.restoreGState()252    }253254    // Far half of the ring, dimmer, behind the core.255    // It recedes smoothly: full strength where it meets the near half, about half strength at the back.256    context.beginTransparencyLayer(auxiliaryInfo: nil)257    strokeRing(Mark.ringArc(from: .pi - 0.02, to: 2 * .pi + 0.02), alpha: 1, glow: false)258    context.setBlendMode(.destinationOut)259    let back = Mark.ringPoint(1.5 * .pi)260    context.drawRadialGradient(261        gradient([(0, rgb(0x000000, 0.52)), (0.6, rgb(0x000000, 0.36)), (1, rgb(0x000000, 0))]),262        startCenter: back, startRadius: 0, endCenter: back, endRadius: Mark.ringSemiMajor * 0.98, options: [])263    context.setBlendMode(.normal)264    context.endTransparencyLayer()265266    // Core: a dark glass sphere lit from the upper left, with a halo and a bright rim.267    let coreRect = CGRect(x: 50 - Mark.coreRadius, y: 50 - Mark.coreRadius, width: Mark.coreRadius * 2,268                          height: Mark.coreRadius * 2)269    context.saveGState()270    context.setShadow(offset: .zero, blur: unit * 9, color: colors.glow.copy(alpha: min(1, colors.glow.alpha * 2.4))!)271    context.setFillColor(colors.coreMid)272    context.fillEllipse(in: coreRect)273    context.restoreGState()274    context.saveGState()275    context.addEllipse(in: coreRect)276    context.clip()277    let light = CGPoint(x: 50 - Mark.coreRadius * 0.42, y: 50 - Mark.coreRadius * 0.5)278    context.drawRadialGradient(279        gradient([(0, colors.coreLight), (0.5, colors.coreMid), (1, colors.coreDark)]),280        startCenter: light, startRadius: 0, endCenter: CGPoint(x: 50, y: 50), endRadius: Mark.coreRadius * 1.25,281        options: [.drawsAfterEndLocation])282    // A soft crescent of reflected light along the lower right edge.283    let crescent = CGPoint(x: 50 + Mark.coreRadius * 0.55, y: 50 + Mark.coreRadius * 0.62)284    context.drawRadialGradient(285        gradient([(0, colors.ringMid.copy(alpha: 0.30)!), (1, colors.ringMid.copy(alpha: 0)!)]),286        startCenter: crescent, startRadius: 0, endCenter: crescent, endRadius: Mark.coreRadius * 0.9, options: [])287    context.restoreGState()288    context.saveGState()289    context.addEllipse(in: coreRect.insetBy(dx: stroke(0.5) / 2, dy: stroke(0.5) / 2))290    context.setLineWidth(stroke(0.55))291    context.replacePathWithStrokedPath()292    context.clip()293    context.drawLinearGradient(294        gradient([(0, colors.rim.copy(alpha: 0.95)!), (0.55, colors.rim.copy(alpha: 0.25)!),295                  (1, colors.ringMid.copy(alpha: 0.6)!)]),296        start: CGPoint(x: coreRect.minX, y: coreRect.minY), end: CGPoint(x: coreRect.maxX, y: coreRect.maxY),297        options: [])298    context.restoreGState()299300    // Navigation needle: a bright pointing half and a translucent tail.301    context.saveGState()302    if detailed {303        context.setShadow(offset: .zero, blur: unit * 2.2, color: colors.needle.copy(alpha: 0.55)!)304    }305    context.addPath(Mark.needleHalf(forward: true))306    context.setFillColor(colors.needle)307    context.fillPath()308    context.restoreGState()309    context.addPath(Mark.needleHalf(forward: false))310    context.setFillColor(colors.needleTail)311    context.fillPath()312    if detailed {313        // The pivot.314        context.setFillColor(colors.coreDark)315        context.fillEllipse(in: CGRect(x: 50 - 1.15, y: 50 - 1.15, width: 2.3, height: 2.3))316    }317318    // Near half of the ring, over the core.319    strokeRing(Mark.ringArc(from: 0, to: .pi), alpha: 1, glow: true)320321    // Satellite.322    let satellite = Mark.ringPoint(Mark.satelliteParameter)323    let satelliteRadius = max(Mark.satelliteRadius, 1.15 / unit)324    context.saveGState()325    if detailed {326        context.setShadow(offset: .zero, blur: unit * 4, color: colors.satellite.copy(alpha: 0.9)!)327    }328    context.setFillColor(colors.satellite)329    context.fillEllipse(in: CGRect(x: satellite.x - satelliteRadius, y: satellite.y - satelliteRadius,330                                   width: satelliteRadius * 2, height: satelliteRadius * 2))331    context.restoreGState()332    context.restoreGState()333334    if variant == .mac {335        // A luminous hairline on the tile edge: bright at the top, vanishing downwards.336        context.saveGState()337        let line = max(1, size / 512)338        context.addPath(CGPath(roundedRect: tile.insetBy(dx: line / 2, dy: line / 2),339                               cornerWidth: tile.width * 0.225 - line / 2, cornerHeight: tile.width * 0.225 - line / 2,340                               transform: nil))341        context.setLineWidth(line)342        context.replacePathWithStrokedPath()343        context.clip()344        context.drawLinearGradient(345            gradient([(0, rgb(0xFFFFFF, 0.34)), (0.4, rgb(0xFFFFFF, 0.07)), (1, rgb(0xFFFFFF, 0.03))]),346            start: CGPoint(x: tile.midX, y: tile.minY), end: CGPoint(x: tile.midX, y: tile.maxY), options: [])347        context.restoreGState()348    }349350    return context.makeImage()!351}352353// MARK: - Output354355func write(_ image: CGImage, to url: URL) throws {356    try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)357    guard let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil)358    else { throw CocoaError(.fileWriteUnknown) }359    CGImageDestinationAddImage(destination, image, nil)360    guard CGImageDestinationFinalize(destination) else { throw CocoaError(.fileWriteUnknown) }361}362363func writeJSON(_ object: Any, to url: URL) throws {364    var data = try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys])365    data.append(0x0A)366    try data.write(to: url, options: .atomic)367}368369let scriptURL = URL(fileURLWithPath: CommandLine.arguments[0]).standardizedFileURL370let defaultOutput = scriptURL.deletingLastPathComponent().deletingLastPathComponent()371    .appendingPathComponent("DesignSystem/AppIcon", isDirectory: true)372let output = CommandLine.arguments.count > 1373    ? URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true) : defaultOutput374375do {376    // Masters.377    try write(drawIcon(pixels: 1024, variant: .mac), to: output.appendingPathComponent("AppIcon-1024.png"))378    try write(drawIcon(pixels: 1024, variant: .iOS), to: output.appendingPathComponent("AppIcon-iOS-1024.png"))379    try write(drawIcon(pixels: 1024, variant: .iOSDark),380              to: output.appendingPathComponent("AppIcon-iOS-1024-dark.png"))381    try write(drawIcon(pixels: 1024, variant: .iOSTinted),382              to: output.appendingPathComponent("AppIcon-iOS-1024-tinted.png"))383384    // macOS asset catalog: 16, 32, 128, 256, 512 pt at 1x and 2x.385    let macSet = output.appendingPathComponent("macOS/AppIcon.appiconset", isDirectory: true)386    var macImages: [[String: String]] = []387    for points in [16, 32, 128, 256, 512] {388        for scale in [1, 2] {389            let name = "icon_\(points)x\(points)\(scale == 2 ? "@2x" : "").png"390            try write(drawIcon(pixels: points * scale, variant: .mac), to: macSet.appendingPathComponent(name))391            macImages.append(["filename": name, "idiom": "mac", "scale": "\(scale)x", "size": "\(points)x\(points)"])392        }393    }394    try writeJSON(["images": macImages, "info": ["author": "xcode", "version": 1]],395                  to: macSet.appendingPathComponent("Contents.json"))396397    // iOS asset catalog: one universal 1024 image per appearance.398    let iosSet = output.appendingPathComponent("iOS/AppIcon.appiconset", isDirectory: true)399    let appearances: [(String, Variant, String?)] = [400        ("AppIcon-1024.png", .iOS, nil), ("AppIcon-1024-dark.png", .iOSDark, "dark"),401        ("AppIcon-1024-tinted.png", .iOSTinted, "tinted"),402    ]403    var iosImages: [[String: Any]] = []404    for (name, variant, appearance) in appearances {405        try write(drawIcon(pixels: 1024, variant: variant), to: iosSet.appendingPathComponent(name))406        var entry: [String: Any] = ["filename": name, "idiom": "universal", "platform": "ios", "size": "1024x1024"]407        if let appearance { entry["appearances"] = [["appearance": "luminosity", "value": appearance]] }408        iosImages.append(entry)409    }410    try writeJSON(["images": iosImages, "info": ["author": "xcode", "version": 1]],411                  to: iosSet.appendingPathComponent("Contents.json"))412413    print("App icon written to \(output.path)")414} catch {415    FileHandle.standardError.write(Data("make-icon: \(error)\n".utf8))416    exit(1)417}418
Files main
Menu

Theme