nswtopo 2.0.0.pre.beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (97) hide show
  1. checksums.yaml +7 -0
  2. data/COPYING +674 -0
  3. data/bin/nswtopo +430 -0
  4. data/docs/README.md +78 -0
  5. data/docs/add.md +49 -0
  6. data/docs/config.md +24 -0
  7. data/docs/contours.md +37 -0
  8. data/docs/controls.md +9 -0
  9. data/docs/declination.md +15 -0
  10. data/docs/delete.md +15 -0
  11. data/docs/grid.md +5 -0
  12. data/docs/info.md +5 -0
  13. data/docs/init.md +38 -0
  14. data/docs/layers.md +11 -0
  15. data/docs/overlay.md +37 -0
  16. data/docs/relief.md +22 -0
  17. data/docs/render.md +43 -0
  18. data/docs/spot-heights.md +23 -0
  19. data/lib/nswtopo/archive.rb +93 -0
  20. data/lib/nswtopo/avl_tree.rb +128 -0
  21. data/lib/nswtopo/config.rb +73 -0
  22. data/lib/nswtopo/dither.rb +31 -0
  23. data/lib/nswtopo/font/chrome.rb +59 -0
  24. data/lib/nswtopo/font/generic.rb +25 -0
  25. data/lib/nswtopo/font.rb +43 -0
  26. data/lib/nswtopo/formats/kmz.rb +149 -0
  27. data/lib/nswtopo/formats/mbtiles.rb +64 -0
  28. data/lib/nswtopo/formats/pdf.rb +31 -0
  29. data/lib/nswtopo/formats/svg.rb +69 -0
  30. data/lib/nswtopo/formats/svgz.rb +13 -0
  31. data/lib/nswtopo/formats/zip.rb +40 -0
  32. data/lib/nswtopo/formats.rb +76 -0
  33. data/lib/nswtopo/geometry/overlap.rb +78 -0
  34. data/lib/nswtopo/geometry/r_tree.rb +47 -0
  35. data/lib/nswtopo/geometry/segment.rb +27 -0
  36. data/lib/nswtopo/geometry/straight_skeleton/collapse.rb +21 -0
  37. data/lib/nswtopo/geometry/straight_skeleton/interior_node.rb +17 -0
  38. data/lib/nswtopo/geometry/straight_skeleton/node.rb +50 -0
  39. data/lib/nswtopo/geometry/straight_skeleton/nodes.rb +295 -0
  40. data/lib/nswtopo/geometry/straight_skeleton/split.rb +33 -0
  41. data/lib/nswtopo/geometry/straight_skeleton/vertex.rb +9 -0
  42. data/lib/nswtopo/geometry/straight_skeleton.rb +6 -0
  43. data/lib/nswtopo/geometry/vector.rb +91 -0
  44. data/lib/nswtopo/geometry/vector_sequence.rb +179 -0
  45. data/lib/nswtopo/geometry.rb +8 -0
  46. data/lib/nswtopo/gis/arcgis_server/connection.rb +52 -0
  47. data/lib/nswtopo/gis/arcgis_server.rb +155 -0
  48. data/lib/nswtopo/gis/dem.rb +70 -0
  49. data/lib/nswtopo/gis/esri_hdr.rb +77 -0
  50. data/lib/nswtopo/gis/gdal_glob.rb +41 -0
  51. data/lib/nswtopo/gis/geojson/collection.rb +94 -0
  52. data/lib/nswtopo/gis/geojson/line_string.rb +11 -0
  53. data/lib/nswtopo/gis/geojson/multi_line_string.rb +63 -0
  54. data/lib/nswtopo/gis/geojson/multi_point.rb +12 -0
  55. data/lib/nswtopo/gis/geojson/multi_polygon.rb +167 -0
  56. data/lib/nswtopo/gis/geojson/point.rb +9 -0
  57. data/lib/nswtopo/gis/geojson/polygon.rb +11 -0
  58. data/lib/nswtopo/gis/geojson.rb +89 -0
  59. data/lib/nswtopo/gis/gps/gpx.rb +22 -0
  60. data/lib/nswtopo/gis/gps/kml.rb +66 -0
  61. data/lib/nswtopo/gis/gps.rb +20 -0
  62. data/lib/nswtopo/gis/projection.rb +56 -0
  63. data/lib/nswtopo/gis/shapefile.rb +24 -0
  64. data/lib/nswtopo/gis/world_file.rb +19 -0
  65. data/lib/nswtopo/gis.rb +9 -0
  66. data/lib/nswtopo/help_formatter.rb +59 -0
  67. data/lib/nswtopo/helpers/array.rb +30 -0
  68. data/lib/nswtopo/helpers/colour.rb +176 -0
  69. data/lib/nswtopo/helpers/concurrently.rb +27 -0
  70. data/lib/nswtopo/helpers/dir.rb +7 -0
  71. data/lib/nswtopo/helpers/hash.rb +15 -0
  72. data/lib/nswtopo/helpers/tar_writer.rb +11 -0
  73. data/lib/nswtopo/helpers.rb +6 -0
  74. data/lib/nswtopo/layer/arcgis_raster.rb +73 -0
  75. data/lib/nswtopo/layer/contour.rb +233 -0
  76. data/lib/nswtopo/layer/control.rb +94 -0
  77. data/lib/nswtopo/layer/declination.rb +53 -0
  78. data/lib/nswtopo/layer/feature.rb +87 -0
  79. data/lib/nswtopo/layer/grid.rb +120 -0
  80. data/lib/nswtopo/layer/import.rb +25 -0
  81. data/lib/nswtopo/layer/labels/fence.rb +20 -0
  82. data/lib/nswtopo/layer/labels.rb +630 -0
  83. data/lib/nswtopo/layer/overlay.rb +53 -0
  84. data/lib/nswtopo/layer/raster.rb +63 -0
  85. data/lib/nswtopo/layer/relief.rb +143 -0
  86. data/lib/nswtopo/layer/spot.rb +171 -0
  87. data/lib/nswtopo/layer/vector.rb +263 -0
  88. data/lib/nswtopo/layer/vegetation.rb +73 -0
  89. data/lib/nswtopo/layer.rb +78 -0
  90. data/lib/nswtopo/log.rb +28 -0
  91. data/lib/nswtopo/map.rb +296 -0
  92. data/lib/nswtopo/os.rb +75 -0
  93. data/lib/nswtopo/safely.rb +13 -0
  94. data/lib/nswtopo/version.rb +4 -0
  95. data/lib/nswtopo/zip.rb +15 -0
  96. data/lib/nswtopo.rb +249 -0
  97. metadata +142 -0
@@ -0,0 +1,149 @@
1
+ module NSWTopo
2
+ module Formats
3
+ module Kmz
4
+ TILE_SIZE = 512
5
+ EARTH_RADIUS = 6378137.0
6
+ TILT = 40 * Math::PI / 180.0
7
+ FOV = 25 * Math::PI / 180.0
8
+ extend self
9
+
10
+ def style
11
+ lambda do |style|
12
+ style.add_element("ListStyle", "id" => "hideChildren").tap do |list_style|
13
+ list_style.add_element("listItemType").text = "checkHideChildren"
14
+ end
15
+ end
16
+ end
17
+
18
+ def lat_lon_box(bounds)
19
+ lambda do |box|
20
+ [%w[west east south north], bounds.flatten].transpose.each do |limit, value|
21
+ box.add_element(limit).text = value
22
+ end
23
+ end
24
+ end
25
+
26
+ def region(bounds, topmost = false)
27
+ lambda do |region|
28
+ region.add_element("Lod").tap do |lod|
29
+ lod.add_element("minLodPixels").text = topmost ? 0 : TILE_SIZE / 2
30
+ lod.add_element("maxLodPixels").text = -1
31
+ end
32
+ region.add_element("LatLonAltBox").tap(&lat_lon_box(bounds))
33
+ end
34
+ end
35
+
36
+ def network_link(bounds, path)
37
+ lambda do |network|
38
+ network.add_element("Region").tap(&region(bounds))
39
+ network.add_element("Link").tap do |link|
40
+ link.add_element("href").text = path
41
+ link.add_element("viewRefreshMode").text = "onRegion"
42
+ link.add_element("viewFormat")
43
+ end
44
+ end
45
+ end
46
+ end
47
+
48
+ def render_kmz(kmz_path, name:, ppi: PPI, **options)
49
+ metre_resolution = 0.0254 * @scale / ppi
50
+ degree_resolution = 180.0 * metre_resolution / Math::PI / Kmz::EARTH_RADIUS
51
+
52
+ wgs84_bounds = bounds(projection: Projection.wgs84)
53
+ wgs84_dimensions = wgs84_bounds.transpose.difference / degree_resolution
54
+ max_zoom = Math::log2(wgs84_dimensions.max).ceil - Math::log2(Kmz::TILE_SIZE).to_i
55
+ topleft = [wgs84_bounds[0][0], wgs84_bounds[1][1]]
56
+ png_path = yield(ppi: ppi)
57
+
58
+ Dir.mktmppath do |temp_dir|
59
+ pyramid = (0..max_zoom).map do |zoom|
60
+ resolution = degree_resolution * 2**(max_zoom - zoom)
61
+ degrees_per_tile = resolution * Kmz::TILE_SIZE
62
+ counts = (wgs84_bounds.transpose.difference / degrees_per_tile).map(&:ceil)
63
+ dimensions = counts.times Kmz::TILE_SIZE
64
+
65
+ tfw_path = temp_dir / "#{name}.kmz.zoom.#{zoom}.tfw"
66
+ tif_path = temp_dir / "#{name}.kmz.zoom.#{zoom}.tif"
67
+ WorldFile.write topleft, resolution, 0, tfw_path
68
+ OS.convert "-size", dimensions.join(?x), "canvas:none", "-type", "TrueColorMatte", "-depth", 8, tif_path
69
+ OS.gdalwarp "-s_srs", @projection, "-t_srs", Projection.wgs84, "-r", "bilinear", "-dstalpha", png_path, tif_path
70
+
71
+ indices_bounds = [topleft, counts, %i[+ -]].transpose.map do |coord, count, increment|
72
+ boundaries = (0..count).map { |index| coord.send increment, index * degrees_per_tile }
73
+ [boundaries[0..-2], boundaries[1..-1]].transpose.map(&:sort)
74
+ end.map do |tile_bounds|
75
+ tile_bounds.each.with_index.to_a
76
+ end.inject(:product).map(&:transpose).map do |tile_bounds, indices|
77
+ { indices => tile_bounds }
78
+ end.inject({}, &:merge)
79
+
80
+ log_update "kmz: resizing image pyramid: %i%%" % (100 * (2**(zoom + 1) - 1) / (2**(max_zoom + 1) - 1))
81
+ { zoom => [indices_bounds, tif_path] }
82
+ end.inject({}, &:merge)
83
+
84
+ kmz_dir = temp_dir.join("#{name}.kmz").tap(&:mkpath)
85
+ pyramid.map do |zoom, (indices_bounds, tif_path)|
86
+ zoom_dir = kmz_dir.join(zoom.to_s).tap(&:mkpath)
87
+ indices_bounds.map do |indices, tile_bounds|
88
+ index_dir = zoom_dir.join(indices.first.to_s).tap(&:mkpath)
89
+ tile_kml_path = index_dir / "#{indices.last}.kml"
90
+ tile_png_path = index_dir / "#{indices.last}.png"
91
+
92
+ xml = REXML::Document.new
93
+ xml << REXML::XMLDecl.new(1.0, "UTF-8")
94
+ xml.add_element("kml", "xmlns" => "http://earth.google.com/kml/2.1").tap do |kml|
95
+ kml.add_element("Document").tap do |document|
96
+ document.add_element("Style").tap(&Kmz.style)
97
+ document.add_element("Region").tap(&Kmz.region(tile_bounds, true))
98
+ document.add_element("GroundOverlay").tap do |overlay|
99
+ overlay.add_element("drawOrder").text = zoom
100
+ overlay.add_element("Icon").add_element("href").text = tile_png_path.basename
101
+ overlay.add_element("LatLonBox").tap(&Kmz.lat_lon_box(tile_bounds))
102
+ end
103
+ if zoom < max_zoom
104
+ indices.map do |index|
105
+ [2 * index, 2 * index + 1]
106
+ end.inject(:product).select do |subindices|
107
+ pyramid[zoom + 1][0][subindices]
108
+ end.each do |subindices|
109
+ path = "../../%i/%i/%i.kml" % [zoom + 1, *subindices]
110
+ document.add_element("NetworkLink").tap(&Kmz.network_link(pyramid[zoom + 1][0][subindices], path))
111
+ end
112
+ end
113
+ end
114
+ end
115
+ tile_kml_path.write xml
116
+
117
+ crop = "%ix%i+%i+%s" % [Kmz::TILE_SIZE, Kmz::TILE_SIZE, indices[0] * Kmz::TILE_SIZE, indices[1] * Kmz::TILE_SIZE]
118
+ [tif_path, "-quiet", "+repage", "-crop", crop, "+repage", "+dither", "-type", "PaletteBilevelMatte", "PNG8:#{tile_png_path}"]
119
+ end
120
+ end.flatten(1).tap do |tiles|
121
+ log_update "kmz: creating %i tiles" % tiles.length
122
+ end.each.concurrently do |args|
123
+ OS.convert *args
124
+ end
125
+
126
+ xml = REXML::Document.new
127
+ xml << REXML::XMLDecl.new(1.0, "UTF-8")
128
+ xml.add_element("kml", "xmlns" => "http://earth.google.com/kml/2.1").tap do |kml|
129
+ kml.add_element("Document").tap do |document|
130
+ document.add_element("LookAt").tap do |look_at|
131
+ range_x = @extents.first / 2.0 / Math::tan(Kmz::FOV) / Math::cos(Kmz::TILT)
132
+ range_y = @extents.last / Math::cos(Kmz::FOV - Kmz::TILT) / 2 / (Math::tan(Kmz::FOV - Kmz::TILT) + Math::sin(Kmz::TILT))
133
+ names_values = [%w[longitude latitude], wgs84_centre].transpose
134
+ names_values << ["tilt", Kmz::TILT * 180.0 / Math::PI] << ["range", 1.2 * [range_x, range_y].max] << ["heading", @rotation]
135
+ names_values.each { |name, value| look_at.add_element(name).text = value }
136
+ end
137
+ document.add_element("Name").text = name
138
+ document.add_element("Style").tap(&Kmz.style)
139
+ document.add_element("NetworkLink").tap(&Kmz.network_link(pyramid[0][0][[0,0]], "0/0/0.kml"))
140
+ end
141
+ end
142
+ kml_path = kmz_dir / "doc.kml"
143
+ kml_path.write xml
144
+
145
+ zip kmz_dir, kmz_path
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,64 @@
1
+ module NSWTopo
2
+ module Formats
3
+ module Mbtiles
4
+ RESOLUTION, ORIGIN, TILE_SIZE, ZOOM = 2 * 78271.516, -20037508.34, 256, 16
5
+ end
6
+
7
+ def render_mbtiles(mbtiles_path, name:, zoom: Mbtiles::ZOOM, **options)
8
+ raise "invalid zoom outside 10-19 range: #{zoom}" unless (10..19) === zoom
9
+
10
+ web_mercator_bounds = bounds(projection: Projection.new("EPSG:3857"))
11
+ wgs84_bounds = bounds(projection: Projection.wgs84)
12
+ sql = <<~SQL
13
+ CREATE TABLE metadata (name TEXT, value TEXT);
14
+ INSERT INTO metadata VALUES ("name", "#{name}");
15
+ INSERT INTO metadata VALUES ("type", "baselayer");
16
+ INSERT INTO metadata VALUES ("version", "1.1");
17
+ INSERT INTO metadata VALUES ("description", "#{name}");
18
+ INSERT INTO metadata VALUES ("format", "png");
19
+ INSERT INTO metadata VALUES ("bounds", "#{wgs84_bounds.transpose.flatten.join ?,}");
20
+ CREATE TABLE tiles (zoom_level INTEGER, tile_column INTEGER, tile_row INTEGER, tile_data BLOB);
21
+ SQL
22
+
23
+ Dir.mktmppath do |temp_dir|
24
+ png_path = nil
25
+ zoom.downto(0).inject([]) do |levels, zoom|
26
+ resolution = Mbtiles::RESOLUTION / 2**zoom
27
+ indices, dimensions, topleft = web_mercator_bounds.map do |lower, upper|
28
+ ((lower - Mbtiles::ORIGIN) / resolution / Mbtiles::TILE_SIZE).floor ... ((upper - Mbtiles::ORIGIN) / resolution / Mbtiles::TILE_SIZE).ceil
29
+ end.map.with_index do |indices, axis|
30
+ [indices, (indices.last - indices.first) * Mbtiles::TILE_SIZE, Mbtiles::ORIGIN + (axis.zero? ? indices.first : indices.last) * Mbtiles::TILE_SIZE * resolution]
31
+ end.transpose
32
+ tile_path = temp_dir.join("#{name}.mbtiles.#{zoom}.%09d.png").to_s
33
+ levels << [resolution, indices, dimensions, topleft, tile_path, zoom]
34
+ break levels if indices.map(&:size).all? { |size| size < 3 }
35
+ levels
36
+ end.tap do |(resolution, *, zoom), *|
37
+ png_path = yield(resolution: resolution)
38
+ end.tap do |levels|
39
+ log_update "mbtiles: tiling for zoom levels %s" % levels.map(&:last).minmax.uniq.join(?-)
40
+ end.each.concurrently do |resolution, indices, dimensions, topleft, tile_path, zoom|
41
+ tif_path, tfw_path = %w[tif tfw].map { |ext| temp_dir / "#{name}.mbtiles.#{zoom}.#{ext}" }
42
+ WorldFile.write topleft, resolution, 0, tfw_path
43
+ OS.convert "-size", dimensions.join(?x), "canvas:none", "-type", "TrueColorAlpha", "-depth", 8, tif_path
44
+ OS.gdalwarp "-s_srs", @projection, "-t_srs", "EPSG:3857", "-r", "lanczos", "-dstalpha", png_path, tif_path
45
+ OS.convert tif_path, "-quiet", "+repage", "-crop", "#{Mbtiles::TILE_SIZE}x#{Mbtiles::TILE_SIZE}", tile_path
46
+ end.map do |resolution, indices, dimensions, topleft, tile_path, zoom|
47
+ indices[1].to_a.reverse.product(indices[0].to_a).map.with_index do |(row, col), index|
48
+ [tile_path % index, zoom, col, row]
49
+ end
50
+ end.flatten(1).each do |tile_path, zoom, col, row|
51
+ sql << %Q[INSERT INTO tiles VALUES (#{zoom}, #{col}, #{row}, readfile("#{tile_path}"));\n]
52
+ end.tap do |tiles|
53
+ log_update "mbtiles: optimising %i tiles" % tiles.length
54
+ end.map(&:first).each.concurrent_groups do |png_paths|
55
+ dither *png_paths
56
+ end
57
+ OS.sqlite3 mbtiles_path do |stdin|
58
+ stdin.puts sql
59
+ stdin.puts ".exit"
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,31 @@
1
+ module NSWTopo
2
+ module Formats
3
+ def render_pdf(pdf_path, ppi: nil, external: nil, **options)
4
+ if ppi
5
+ OS.gdal_translate "-a_srs", @projection, "-of", "PDF", "-co", "DPI=#{ppi}", "-co", "MARGIN=0", "-co", "CREATOR=nswtopo", "-co", "GEO_ENCODING=ISO32000", yield(ppi: ppi), pdf_path
6
+ else
7
+ Dir.mktmppath do |temp_dir|
8
+ svg_path = temp_dir / "pdf-map.svg"
9
+ render_svg svg_path, external: external
10
+ xml = REXML::Document.new svg_path.read
11
+ style = "@media print { @page { margin: 0 0 -1mm 0; size: %s %s; } }"
12
+ svg = xml.elements["svg"]
13
+ svg.add_element("style").text = style % svg.attributes.values_at("width", "height")
14
+ svg_path.write xml
15
+
16
+ FileUtils.rm pdf_path if pdf_path.exist?
17
+ NSWTopo.with_browser do |browser_name, browser_path|
18
+ args = case browser_name
19
+ when "chrome"
20
+ ["--headless", "--disable-gpu", "--print-to-pdf=#{pdf_path}"]
21
+ when "firefox"
22
+ raise "can't create vector PDF with firefox; use chrome or specify ppi for a raster PDF"
23
+ end
24
+ stdout, stderr, status = Open3.capture3 browser_path.to_s, *args, "file://#{svg_path}"
25
+ raise "couldn't create PDF using %s" % browser_name unless status.success? && pdf_path.file?
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,69 @@
1
+ module NSWTopo
2
+ module Formats
3
+ def render_svg(svg_path, external: nil, **options)
4
+ case
5
+ when external
6
+ raise "not a file: %s" % external unless external.file?
7
+ begin
8
+ svg = REXML::Document.new(external.read).elements["svg"]
9
+ raise "not an SVG file: %s" % external unless svg
10
+ desc = svg.elements["metadata/rdf:RDF/rdf:Description[@dc:creator='nswtopo']"]
11
+ raise "not an nswtopo SVG file: %s" % external unless desc
12
+ rescue REXML::ParseException
13
+ raise "not an SVG file: %s" % external
14
+ end
15
+ FileUtils.cp external, svg_path
16
+
17
+ when @archive.uptodate?("map.svg", "map.yml")
18
+ svg_path.write @archive.read("map.svg")
19
+
20
+ else
21
+ width, height = extents.times(1000.0 / scale)
22
+ xml = REXML::Document.new
23
+ xml << REXML::XMLDecl.new(1.0, "utf-8")
24
+ svg = xml.add_element "svg",
25
+ "version" => 1.1,
26
+ "baseProfile" => "full",
27
+ "width" => "#{width}mm",
28
+ "height" => "#{height}mm",
29
+ "viewBox" => "0 0 #{width} #{height}",
30
+ "xmlns" => "http://www.w3.org/2000/svg",
31
+ "xmlns:xlink" => "http://www.w3.org/1999/xlink",
32
+ "xmlns:sodipodi" => "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd",
33
+ "xmlns:inkscape" => "http://www.inkscape.org/namespaces/inkscape"
34
+
35
+ meta = svg.add_element "metadata"
36
+ rdf = meta.add_element "rdf:RDF",
37
+ "xmlns:rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
38
+ "xmlns:dc" => "http://purl.org/dc/elements/1.1/"
39
+ rdf.add_element "rdf:Description",
40
+ "dc:date" => Date.today.iso8601,
41
+ "dc:format" => "image/svg+xml",
42
+ "dc:creator" => "nswtopo"
43
+
44
+ defs = svg.add_element "defs"
45
+ svg.add_element "sodipodi:namedview", "borderlayer" => true
46
+ svg.add_element "rect", "x" => 0, "y" => 0, "width" => width, "height" => height, "fill" => "white"
47
+
48
+ labels = Layer.new "labels", self, Config.fetch("labels", {}).merge("type" => "Labels")
49
+ layers.reject(&:empty?).each do |layer|
50
+ next if Config["labelling"] == false
51
+ labels.add layer if Vector === layer
52
+ end.push(labels).each do |layer|
53
+ log_update "compositing: #{layer.name}"
54
+ group = svg.add_element "g", "id" => layer.name, "inkscape:groupmode" => "layer"
55
+ layer.render group, defs, &labels.method(:add_fence)
56
+ end
57
+
58
+ until xml.elements.each("svg//g[not(*)]", &:remove).empty? do
59
+ end
60
+
61
+ string, formatter = String.new, REXML::Formatters::Pretty.new
62
+ formatter.compact = true
63
+ formatter.write xml, string
64
+ write "map.svg", string
65
+ svg_path.write string
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,13 @@
1
+ module NSWTopo
2
+ module Formats
3
+ def render_svgz(svgz_path, external: nil, **options)
4
+ Dir.mktmppath do |temp_dir|
5
+ svg_path = temp_dir / "svgz-map.svg"
6
+ render_svg svg_path, external: external
7
+ Zlib::GzipWriter.open svgz_path do |gz|
8
+ gz.write svg_path.binread
9
+ end
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,40 @@
1
+ module NSWTopo
2
+ module Formats
3
+ def render_zip(zip_path, name:, ppi: PPI, **options)
4
+ Dir.mktmppath do |temp_dir|
5
+ zip_dir = temp_dir.join("#{name}.avenza").tap(&:mkpath)
6
+ tiles_dir = zip_dir.join("tiles").tap(&:mkpath)
7
+ png_path = yield(ppi: ppi)
8
+ top_left = bounding_box.coordinates[0][3]
9
+
10
+ 2.downto(0).map.with_index do |level, index|
11
+ [level, index, ppi.to_f / 2**index]
12
+ end.each.concurrently do |level, index, ppi|
13
+ dimensions, ppi, resolution = raster_dimensions_at ppi: ppi
14
+ img_path = index.zero? ? png_path : temp_dir / "#{name}.avenza.#{level}.png"
15
+ tile_path = temp_dir.join("#{name}.avenza.tile.#{level}.%09d.png").to_s
16
+
17
+ OS.convert png_path, "-filter", "Lanczos", "-resize", "%ix%i!" % dimensions, img_path unless img_path.exist?
18
+ OS.convert img_path, "+repage", "-crop", "256x256", tile_path
19
+
20
+ dimensions.reverse.map do |dimension|
21
+ 0.upto((dimension - 1) / 256).to_a
22
+ end.inject(&:product).each.with_index do |(y, x), n|
23
+ FileUtils.cp tile_path % n, tiles_dir / "#{level}x#{y}x#{x}.png"
24
+ end
25
+ zip_dir.join("#{name}.ref").open("w") do |file|
26
+ file.puts @projection.wkt_simple
27
+ file.puts WorldFile.geotransform(top_left, resolution, -@rotation).flatten.join(?,)
28
+ file << dimensions.join(?,)
29
+ end if index == 1
30
+ end
31
+ Pathname.glob(tiles_dir / "*.png").each.concurrent_groups do |tile_paths|
32
+ dither *tile_paths
33
+ end
34
+
35
+ OS.convert png_path, "-thumbnail", "64x64", "-gravity", "center", "-background", "white", "-extent", "64x64", "-alpha", "Remove", "-type", "TrueColor", zip_dir / "thumb.png"
36
+ zip zip_dir, zip_path
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,76 @@
1
+ require_relative 'formats/svg'
2
+ require_relative 'formats/kmz'
3
+ require_relative 'formats/mbtiles'
4
+ require_relative 'formats/zip'
5
+ require_relative 'formats/pdf'
6
+ require_relative 'formats/svgz'
7
+
8
+ module NSWTopo
9
+ module Formats
10
+ include Log
11
+ PPI = 300
12
+
13
+ def self.extensions
14
+ instance_methods.grep(/^render_([a-z]+)/) { $1 }
15
+ end
16
+
17
+ def self.===(ext)
18
+ extensions.any? ext
19
+ end
20
+
21
+ def render_png(png_path, ppi: PPI, dither: false, **options)
22
+ FileUtils.cp yield(ppi: ppi, dither: dither), png_path
23
+ end
24
+
25
+ def render_tif(tif_path, ppi: PPI, dither: false, **options)
26
+ OS.gdal_translate "-of", "GTiff", "-co", "COMPRESS=DEFLATE", "-co", "ZLEVEL=9", "-a_srs", @projection, yield(ppi: ppi, dither: dither), tif_path
27
+ end
28
+
29
+ def render_jpg(jpg_path, ppi: PPI, **options)
30
+ OS.gdal_translate "-of", "JPEG", "-co", "QUALITY=90", "-mo", "EXIF_XResolution=#{ppi}", "-mo", "EXIF_YResolution=#{ppi}", "-mo", "EXIF_ResolutionUnit=2", yield(ppi: ppi), jpg_path
31
+ end
32
+
33
+ def rasterise(png_path, external:, **options)
34
+ Dir.mktmppath do |temp_dir|
35
+ dimensions, ppi, resolution = raster_dimensions_at **options
36
+ svg_path = temp_dir / "map.svg"
37
+ src_path = temp_dir / "browser.svg"
38
+ render_svg svg_path, external: external
39
+
40
+ NSWTopo.with_browser do |browser_name, browser_path|
41
+ megapixels = dimensions.inject(&:*) / 1024.0 / 1024.0
42
+ log_update "%s: creating %i×%i (%.1fMpx) map raster at %i ppi" % [browser_name, *dimensions, megapixels, options[:ppi] ] if options[:ppi]
43
+ log_update "%s: creating %i×%i (%.1fMpx) map raster at %.1f m/px" % [browser_name, *dimensions, megapixels, options[:resolution]] if options[:resolution]
44
+
45
+ render = lambda do |width, height|
46
+ args = case browser_name
47
+ when "firefox"
48
+ ["--window-size=#{width},#{height}", "-headless", "-screenshot", png_path.to_s]
49
+ when "chrome"
50
+ ["--window-size=#{width},#{height}", "--headless", "--screenshot=#{png_path}", "--disable-lcd-text", "--disable-extensions", "--hide-scrollbars", "--disable-gpu"]
51
+ end
52
+ FileUtils.rm png_path if png_path.exist?
53
+ stdout, stderr, status = Open3.capture3 browser_path.to_s, *args, "file://#{src_path}"
54
+ case browser_name
55
+ when "firefox" then raise "couldn't rasterise map using firefox (ensure browser is closed)"
56
+ when "chrome" then raise "couldn't rasterise map using chrome"
57
+ end unless status.success? && png_path.file?
58
+ end
59
+
60
+ src_path.write %Q[<?xml version='1.0' encoding='UTF-8'?><svg version='1.1' baseProfile='full' xmlns='http://www.w3.org/2000/svg'></svg>]
61
+ render.call 1000, 1000
62
+ json = NSWTopo::OS.gdalinfo "-json", png_path
63
+ scaling = JSON.parse(json)["size"][0] / 1000.0
64
+
65
+ svg = %w[width height].inject(svg_path.read) do |svg, attribute|
66
+ svg.sub(/#{attribute}='(.*?)mm'/) { %Q[#{attribute}='#{$1.to_f * ppi / 96.0 / scaling}mm'] }
67
+ end
68
+ src_path.write svg
69
+ render.call *(dimensions / scaling).map(&:ceil)
70
+ end
71
+
72
+ OS.mogrify "+repage", "-crop", "#{dimensions.join ?x}+0+0", "-background", "white", "-flatten", "-alpha", "Off", "-units", "PixelsPerInch", "-density", ppi, "-define", "PNG:exclude-chunk=bkgd,itxt,ztxt,text,chrm", png_path
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,78 @@
1
+ module Overlap
2
+ def separated_by?(buffer)
3
+ simplex = [map(&:first).inject(&:minus)]
4
+ perp = simplex[0].perp
5
+ loop do
6
+ return false unless case
7
+ when simplex.one? then simplex[0].norm
8
+ when simplex.inject(&:minus).dot(simplex[1]) > 0 then simplex[1].norm
9
+ when simplex.inject(&:minus).dot(simplex[0]) < 0 then simplex[0].norm
10
+ else simplex.inject(&:cross).abs / simplex.inject(&:minus).norm
11
+ end > buffer
12
+ max = self[0].max_by { |point| perp.cross point }
13
+ min = self[1].min_by { |point| perp.cross point }
14
+ support = max.minus min
15
+ return true unless simplex[0].minus(support).cross(perp) > 0
16
+ rays = simplex.map { |point| point.minus support }
17
+ case simplex.length
18
+ when 1
19
+ case
20
+ when rays[0].dot(support) > 0
21
+ simplex, perp = [support], support.perp
22
+ when rays[0].cross(support) < 0
23
+ simplex, perp = [support, *simplex], rays[0]
24
+ else
25
+ simplex, perp = [*simplex, support], rays[0].negate
26
+ end
27
+ when 2
28
+ case
29
+ when rays[0].cross(support) > 0 && rays[0].dot(support) < 0
30
+ simplex, perp = [simplex[0], support], rays[0].negate
31
+ when rays[1].cross(support) < 0 && rays[1].dot(support) < 0
32
+ simplex, perp = [support, simplex[1]], rays[1]
33
+ when rays[0].cross(support) <= 0 && rays[1].cross(support) >= 0
34
+ return false
35
+ else
36
+ simplex, perp = [support], support.perp
37
+ end
38
+ end
39
+ end
40
+ end
41
+
42
+ def overlap?(buffer = 0)
43
+ !separated_by?(buffer)
44
+ end
45
+
46
+ def overlaps(buffer = 0)
47
+ return [] if empty?
48
+ axis = flatten(1).transpose.map { |values| values.max - values.min }.map.with_index.max.last
49
+ events, tops, bots, results = AVLTree.new, [], [], []
50
+ margin = [buffer, 0]
51
+ each.with_index do |hull, index|
52
+ min, max = hull.map { |point| point.rotate axis }.minmax
53
+ events << [min.minus(margin), index, :start]
54
+ events << [max.plus( margin), index, :stop ]
55
+ end
56
+ events.each do |point, index, event|
57
+ top, bot = at(index).transpose[1-axis].minmax
58
+ case event
59
+ when :start
60
+ not_above = bots.select { |bot, other| bot >= top - buffer }.map(&:last)
61
+ not_below = tops.select { |top, other| top <= bot + buffer }.map(&:last)
62
+ (not_below & not_above).reject do |other|
63
+ values_at(index, other).separated_by? buffer
64
+ end.each do |other|
65
+ results << [index, other]
66
+ end
67
+ tops << [top, index]
68
+ bots << [bot, index]
69
+ when :stop
70
+ tops.delete [top, index]
71
+ bots.delete [bot, index]
72
+ end
73
+ end
74
+ results
75
+ end
76
+ end
77
+
78
+ Array.send :include, Overlap
@@ -0,0 +1,47 @@
1
+ class RTree
2
+ def initialize(nodes, bounds, object = nil)
3
+ @nodes, @bounds, @object = nodes, bounds, object
4
+ end
5
+
6
+ def overlaps?(bounds)
7
+ return false if @bounds.empty?
8
+ return true unless bounds
9
+ bounds.zip(@bounds).all? do |bound1, bound2|
10
+ bound1.zip(bound2.rotate).each.with_index.all? do |limits, index|
11
+ limits.rotate(index).inject(&:<=)
12
+ end
13
+ end
14
+ end
15
+
16
+ def self.load(bounds_objects, &block)
17
+ case
18
+ when block_given? then load bounds_objects.map(&block).zip(bounds_objects)
19
+ when bounds_objects.one? then RTree.new [], *bounds_objects.first
20
+ else
21
+ nodes = bounds_objects.sort_by do |bounds, object|
22
+ bounds[0].inject(&:+)
23
+ end.in_two.map do |bounds_objects|
24
+ bounds_objects.sort_by do |bounds, object|
25
+ bounds[1].inject(&:+)
26
+ end.in_two.map do |bounds_objects|
27
+ load bounds_objects
28
+ end
29
+ end.flatten
30
+ RTree.new nodes, bounds_objects.map(&:first).transpose.map(&:flatten).map(&:minmax)
31
+ end
32
+ end
33
+
34
+ def search(bounds, searched = Set.new)
35
+ Enumerator.new do |yielder|
36
+ unless searched.include? self
37
+ if overlaps? bounds
38
+ @nodes.each do |node|
39
+ node.search(bounds, searched).each { |object| yielder << object }
40
+ end
41
+ yielder << @object if @nodes.empty?
42
+ end
43
+ searched << self
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,27 @@
1
+ module Segment
2
+ def segments
3
+ self[0..-2].zip self[1..-1]
4
+ end
5
+
6
+ def ring
7
+ zip rotate
8
+ end
9
+
10
+ def difference
11
+ last.minus first
12
+ end
13
+
14
+ def distance
15
+ difference.norm
16
+ end
17
+
18
+ def along(fraction)
19
+ self[1].times(fraction).plus self[0].times(1.0 - fraction)
20
+ end
21
+
22
+ def midpoint
23
+ transpose.map(&:mean)
24
+ end
25
+ end
26
+
27
+ Array.send :include, Segment
@@ -0,0 +1,21 @@
1
+ module StraightSkeleton
2
+ class Collapse
3
+ include InteriorNode
4
+
5
+ def initialize(nodes, point, travel, sources)
6
+ @original, @nodes, @point, @travel, @sources = self, nodes, point, travel, sources
7
+ end
8
+
9
+ def viable?
10
+ @sources.all?(&:active?)
11
+ end
12
+
13
+ def replace!(&block)
14
+ @neighbours = [@sources[0].prev, @sources[1].next]
15
+ @neighbours.inject(&:==) ? block.call(prev) : insert! if @neighbours.any?
16
+ @sources.each(&block)
17
+ end
18
+
19
+ alias splits? terminal?
20
+ end
21
+ end
@@ -0,0 +1,17 @@
1
+ module StraightSkeleton
2
+ module InteriorNode
3
+ include Node
4
+
5
+ def <=>(other)
6
+ (@travel <=> other.travel) * @nodes.direction
7
+ end
8
+
9
+ def insert!
10
+ @normals = @neighbours.map.with_index do |neighbour, index|
11
+ neighbour.neighbours[1-index] = self if neighbour
12
+ neighbour.normals[1-index] if neighbour
13
+ end
14
+ @nodes.insert self
15
+ end
16
+ end
17
+ end