Debian Codegraph @

src/uk/me/parabola/imgfmt/app/mdr/Mdr7.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2009.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 package uk.me.parabola.imgfmt.app.mdr;
14
15 import java.text.Collator;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22
23 import uk.me.parabola.imgfmt.MapFailedException;
24 import uk.me.parabola.imgfmt.app.ImgFileWriter;
25 import uk.me.parabola.imgfmt.app.srt.Sort;
26 import uk.me.parabola.imgfmt.app.srt.SortKey;
27
28 /**
29 * The MDR 7 section is a list of all streets. Only street names are saved
30 * and so I believe that the NET section is required to make this work.
31 *
32 * @author Steve Ratcliffe
33 */
34 public class Mdr7 extends MdrMapSection {
35 public static final int MDR7_HAS_STRING = 0x01;
36 public static final int MDR7_HAS_NAME_OFFSET = 0x20;
37 public static final int MDR7_PARTIAL_SHIFT = 6;
38 public static final int MDR7_U1 = 0x2;
39 public static final int MDR7_HAS_MDR17 = 0x4;
40
41 private static final int MAX_NAME_OFFSET = 127;
42
43 private final int codepage;
44 private final boolean isMulti;
45 private final boolean splitName;
46
47 private Set<Mdr7Record> roadsPerMap= new HashSet<>();
48 private ArrayList<Mdr7Record> allStreets = new ArrayList<>();
49 private ArrayList<Mdr7Record> streets = new ArrayList<>();
50 private int lastMaxIndex = -1;
51
52 private int partialInfoSize;
53 private Set<String> exclNames;
54 private final Sort sort;
55 private int maxPrefixCount;
56 private int maxSuffixCount;
57 private boolean magicIsValid;
58 private int magic;
59
60 public Mdr7(MdrConfig config) {
61 setConfig(config);
62 sort = config.getSort();
63 splitName = config.isSplitName();
64 exclNames = config.getMdr7Excl();
65 codepage = sort.getCodepage();
66 isMulti = sort.isMulti();
67 }
68
69 public void addStreet(int mapId, String name, int lblOffset, int strOff, Mdr5Record mdrCity) {
70 if (name.isEmpty())
71 return;
72
73 // Find a name prefix, which is either a shield or a word ending 0x1e or 0x1c. We are treating
74 // a shield as a prefix of length one.
75 int prefix = 0;
76 if (name.charAt(0) < 7)
77 prefix = 1;
78 int sep = name.indexOf(0x1e);
79 if (sep < 0)
80 sep = name.indexOf(0x1b);
81 if (sep > 0) {
82 prefix = sep + 1;
83 }
84
85 // Find a name suffix which begins with 0x1 or 0x1c
86 sep = name.indexOf(0x1f);
87 if (sep < 0)
88 sep = name.indexOf(0x1c);
89 int suffix = 0;
90 if (sep > 0) {
91 suffix = sep;
92 }
93
94 // Large values can't actually work.
95 if (prefix >= MAX_NAME_OFFSET || suffix >= MAX_NAME_OFFSET)
96 return;
97
98 Mdr7Record st = new Mdr7Record();
99 st.setMapIndex(mapId);
100 st.setLabelOffset(lblOffset);
101 st.setStringOffset(strOff);
102 st.setName(name);
103 st.setCity(mdrCity);
104 st.setPrefixOffset((byte) prefix);
105 st.setSuffixOffset((byte) suffix);
106 storeMdr7(st);
107
108 if (!splitName)
109 return;
110
111 boolean start = false;
112 boolean inWord = false;
113
114 int c;
115 int outOffset = 0;
116
117 int end = Math.min(((suffix > 0) ? suffix : name.length()) - prefix - 1, MAX_NAME_OFFSET);
118 for (int nameOffset = 0; nameOffset < end; nameOffset += Character.charCount(c)) {
119 c = name.codePointAt(prefix + nameOffset);
120
121 // Don't use any word after a bracket
122 if (c == '(')
123 break;
124
125 if (!Character.isLetterOrDigit(c)) {
126 start = true;
127 inWord = false;
128 } else if (start && Character.isLetterOrDigit(c)) {
129 inWord = true;
130 }
131
132 if (start && inWord && outOffset > 0) {
133 st = new Mdr7Record();
134 st.setMapIndex(mapId);
135 st.setLabelOffset(lblOffset);
136 st.setStringOffset(strOff);
137 st.setName(name);
138 st.setCity(mdrCity);
139 st.setNameOffset((byte) nameOffset);
140 st.setOutNameOffset((byte) outOffset);
141 st.setPrefixOffset((byte) prefix);
142 st.setSuffixOffset((byte) suffix);
143 if (!exclNames.contains(st.getPartialName()))
144 storeMdr7(st);
145
146 start = false;
147 }
148
149 outOffset += outSize(c);
150 if (outOffset > MAX_NAME_OFFSET)
151 break;
152 }
153 }
154
155 /**
156 * Store in array if not already done
157 * @param st the mdr7 record
158 */
159 private void storeMdr7(Mdr7Record st) {
160 if (lastMaxIndex != st.getMapIndex()) {
161 // we process all roads of one map tile sequentially, so we can clear the set with each new map tile
162 lastMaxIndex = st.getMapIndex();
163 roadsPerMap.clear();
164 }
165
166 if (roadsPerMap.add(st)) {
167 allStreets.add(st);
168 }
169 }
170
171 /**
172 * Return the number of bytes that the given character will consume in the output encoded
173 * format.
174 */
175 private int outSize(int c) {
176 if (codepage == 65001) {
177 // For unicode a simple lookup gives the number of bytes.
178 if (c < 0x80) {
179 return 1;
180 } else if (c <= 0x7FF) {
181 return 2;
182 } else if (c <= 0xFFFF) {
183 return 3;
184 } else if (c <= 0x10FFFF) {
185 return 4;
186 } else {
187 throw new MapFailedException(String.format("Invalid code point: 0x%x", c));
188 }
189 } else if (!isMulti) {
190 // The traditional single byte code-pages, always one byte.
191 return 1;
192 } else {
193 // Other multi-byte code-pages (eg ms932); can't currently create index for these anyway.
194 return 0;
195 }
196 }
197
198 /**
199 * Since we change the number of records by removing some after sorting,
200 * we sort and de-duplicate here.
201 * This is a performance critical part of the index creation process
202 * as it requires a lot of heap to store the sort keys.
203 */
204 @Override
205 protected void preWriteImpl() {
206
207 LargeListSorter<Mdr7Record> partialSorter = new LargeListSorter<Mdr7Record>(sort) {
208 @Override
209 protected SortKey<Mdr7Record> makeKey(Mdr7Record r, Sort sort, Map<String, byte[]> cache) {
210 return sort.createSortKey(r, r.getPartialName(), 0, cache); // first sort by partial name only
211 }
212 };
213
214 ArrayList<Mdr7Record> sorted = new ArrayList<>(allStreets);
215 allStreets.clear();
216 partialSorter.sort(sorted);
217 // list is now sorted by partial name only, we have to group by name and map index now
218 String lastPartial = null;
219 List<Mdr7Record> samePartial = new ArrayList<>();
220 Collator collator = sort.getCollator();
221 collator.setStrength(Collator.SECONDARY);
222 for (int i = 0; i < sorted.size(); i++) {
223 Mdr7Record r = sorted.get(i);
224 String partial = r.getPartialName();
225 if (lastPartial == null || collator.compare(partial, lastPartial) != 0) {
226 groupByNameAndMap(samePartial);
227 samePartial.clear();
228 }
229 samePartial.add(r);
230 lastPartial = partial;
231 }
232 groupByNameAndMap(samePartial);
233
234 allStreets.trimToSize();
235 streets.trimToSize();
236 }
237
238 /**
239 * Group a list of roads with the same partial name.
240 * @param samePartial
241 */
242 private void groupByNameAndMap(List<Mdr7Record> samePartial) {
243 if (samePartial.isEmpty())
244 return;
245
246 // Basecamp needs the records grouped by partial name, full name, and map index.
247 // This sometimes presents search results in the wrong order. The partial sort fields allow to
248 // tell the right order.
249
250 LargeListSorter<Mdr7Record> fullNameSorter = new LargeListSorter<Mdr7Record>(sort) {
251 @Override
252 protected SortKey<Mdr7Record> makeKey(Mdr7Record r, Sort sort, Map<String, byte[]> cache) {
253 return sort.createSortKey(r, r.getName(), r.getMapIndex(), cache);
254 }
255 };
256
257
258 fullNameSorter.sort(samePartial);
259 Mdr7Record last = null;
260 int recordNumber = streets.size();
261
262 // list is now sorted by partial name, name, and map index
263 // De-duplicate the street names so that there is only one entry
264 // per map for the same name.
265 for (int i = 0; i < samePartial.size(); i++) {
266 Mdr7Record r = samePartial.get(i);
267 if (last != null && r.getMapIndex() == last.getMapIndex() && r.getName().equals(last.getName())) {
268 // This has the same name (and map number) as the previous one.
269 // Save the pointer to that one
270 // which is going into the file.
271 r.setIndex(recordNumber);
272 } else {
273 recordNumber++;
274 r.setIndex(recordNumber);
275 streets.add(r);
276 }
277 if (r.getCity() != null)
278 allStreets.add(r);
279 last = r;
280 }
281 }
282
283 public void writeSectData(ImgFileWriter writer) {
284 boolean hasStrings = hasFlag(MDR7_HAS_STRING);
285 boolean hasNameOffset = hasFlag(MDR7_HAS_NAME_OFFSET);
286 Collator collator = sort.getCollator();
287 collator.setStrength(Collator.SECONDARY);
288 Mdr7Record last = null;
289 for (Mdr7Record s : streets) {
290 addIndexPointer(s.getMapIndex(), s.getIndex());
291
292 putMapIndex(writer, s.getMapIndex());
293 int lab = s.getLabelOffset();
294
295 int rr = s.checkRepeat(last, collator);
296 if (rr != 3)
297 lab |= 0x800000;
298
299 writer.put3u(lab);
300 if (hasStrings)
301 putStringOffset(writer, s.getStringOffset());
302
303 if (hasNameOffset)
304 writer.put1u(s.getOutNameOffset());
305 if (partialInfoSize > 0) {
306 int trailingFlags = ((rr & 1) == 0) ? 1 : 0;
307 writer.putNu(partialInfoSize, trailingFlags);
308 }
309 last = s;
310 }
311 }
312
313 /**
314 * For the map number, label, string (opt), and trailing flags (opt).
315 * The trailing flags are variable size. We are just using 1 now.
316 */
317 public int getItemSize() {
318 PointerSizes sizes = getSizes();
319 int size = sizes.getMapSize() + 3 + partialInfoSize;
320 if (!isForDevice())
321 size += sizes.getStrOffSize();
322 if ((getExtraValue() & MDR7_HAS_NAME_OFFSET) != 0)
323 size += 1;
324 return size;
325 }
326
327 protected int numberOfItems() {
328 return streets.size();
329 }
330
331 /**
332 * Value of 3 possibly the existence of the lbl field.
333 */
334 public int getExtraValue() {
335 if (!magicIsValid) {
336 int bitsPrefix = (maxPrefixCount == 0) ? 0 : Integer.numberOfTrailingZeros(Integer.highestOneBit(maxPrefixCount)) + 1;
337 int bitsSuffix = (maxSuffixCount == 0) ? 0 : Integer.numberOfTrailingZeros(Integer.highestOneBit(maxSuffixCount)) + 1;
338 int bits = bitsPrefix + bitsSuffix + 1;
339 partialInfoSize = 1 + bits / 8;
340 assert bitsSuffix <= 15;
341 magic = MDR7_U1 | MDR7_HAS_NAME_OFFSET | (partialInfoSize << MDR7_PARTIAL_SHIFT) | (bitsPrefix << 9);
342
343 if (isForDevice()) {
344 if (!getConfig().getSort().isMulti())
345 magic |= MDR7_HAS_MDR17; // mdr17 sub section present (not with unicode)
346 } else {
347 magic |= MDR7_HAS_STRING;
348 }
349 int unk2size = (magic >> 6) & 0x7;
350 int unk2split = ((magic >> 9) & 0xf);
351 assert unk2size == partialInfoSize;
352 assert unk2split == bitsPrefix;
353 magicIsValid = true;
354 }
355 return magic;
356 }
357
358 @Override
359 protected void releaseMemory() {
360 allStreets = null;
361 streets = null;
362 }
363
364
365 public List<Mdr7Record> getStreets() {
366 return Collections.unmodifiableList(allStreets);
367 }
368
369 public List<Mdr7Record> getSortedStreets() {
370 return Collections.unmodifiableList(streets);
371 }
372
373
374 /**
375 * Free as much memory as possible.
376 */
377 public void trim() {
378 allStreets.trimToSize();
379 roadsPerMap = new HashSet<>();
380 }
381 }