Debian Codegraph @

src/uk/me/parabola/imgfmt/app/trergn/LinePreparer.java

raw symbols SCIP
1 /**
2 * Copyright (C) 2006 Steve Ratcliffe
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 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * Author: steve
14 * Date: 24-Dec-2006
15 */
16 package uk.me.parabola.imgfmt.app.trergn;
17
18 import java.util.List;
19
20 import uk.me.parabola.imgfmt.app.BitWriter;
21 import uk.me.parabola.imgfmt.app.Coord;
22 import uk.me.parabola.log.Logger;
23
24 /**
25 * This class holds all of the calculations needed to encode a line into
26 * the garmin format.
27 */
28 public class LinePreparer {
29 private static final Logger log = Logger.getLogger(LinePreparer.class);
30
31 // These are our inputs.
32 private final Polyline polyline;
33
34 /** if true, we must write the extraBits which allow to find out which points are nodes */
35 private final boolean extraBit;
36 private final boolean extTypeLine;
37 private boolean xSameSign;
38 private boolean xSignNegative; // Set if all negative
39
40 private boolean ySameSign;
41 private boolean ySignNegative; // Set if all negative
42
43 // The base number of bits
44 private int xBase;
45 private int yBase;
46
47 // The delta changes between the points.
48 private int[] deltas;
49 private boolean[] nodes;
50
51 private final boolean ignoreNumberOnlyNodes;
52
53 LinePreparer(Polyline line) {
54 extraBit = line.isRoad() && line.getSubdiv().getZoom().getLevel() == 0
55 && (line.hasInternalNodes() || !line.isLastSegment());
56 ignoreNumberOnlyNodes = !line.hasHouseNumbers();
57 extTypeLine = line.hasExtendedType();
58
59 polyline = line;
60 calcLatLong();
61 calcDeltas();
62 }
63
64 /**
65 * Write the bit stream to a BitWriter and return it.
66 * Try different values for xBase and yBase to find the one
67 * that results in the shortest bit stream.
68 *
69 * @return A class containing the written byte stream.
70 */
71 public BitWriter makeShortestBitStream(int minPointsRequired) {
72 BitWriter bsSimple = makeBitStream(minPointsRequired, xBase, yBase);
73 if (bsSimple == null)
74 return bsSimple;
75 BitWriter bsBest = bsSimple;
76 int xBestBase = xBase;
77 int yBestBase = yBase;
78 if ((xBase > 0 || yBase > 0) && log.isDebugEnabled()) {
79 log.debug("start opt:", xBase, yBase, xSameSign, xSignNegative, ySameSign, ySignNegative);
80 }
81 if (xBase > 0){
82 int notBetter = 0;
83 int xTestBase = xBase-1;
84 boolean xSameSignBak = xSameSign;
85 if (xSameSign) {
86 xSameSign = false;
87 --xTestBase; // changing to signed will add a bit to each node so xBase-1 can't give saving
88 }
89 for ( ; xTestBase >= 0; xTestBase--){
90 BitWriter bstest = makeBitStream(minPointsRequired, xTestBase, yBase);
91 if (bstest.getBitPosition() >= bsBest.getBitPosition()){
92 if (++notBetter >= 2)
93 break; // give up
94 } else {
95 xBestBase = xTestBase;
96 bsBest = bstest;
97 xSameSignBak = false;
98 }
99 }
100 xSameSign = xSameSignBak;
101 }
102 if (yBase > 0){
103 int notBetter = 0;
104 int yTestBase = yBase-1;
105 boolean ySameSignBak = ySameSign;
106 if (ySameSign) {
107 ySameSign = false;
108 --yTestBase; // changing to signed will add a bit to each node so yBase-1 can't give saving
109 }
110 for ( ; yTestBase >= 0; yTestBase--){
111 BitWriter bstest = makeBitStream(minPointsRequired, xBestBase, yTestBase);
112 if (bstest.getBitPosition() >= bsBest.getBitPosition()){
113 if (++notBetter >= 2)
114 break; // give up
115 } else {
116 yBestBase = yTestBase;
117 bsBest = bstest;
118 ySameSignBak = false;
119 }
120 }
121 ySameSign = ySameSignBak;
122 }
123 if ((xBase != xBestBase || yBestBase != yBase) && log.isInfoEnabled()) {
124 if (bsSimple.getLength() > bsBest.getLength())
125 log.info("optimizer reduced bit stream byte length from",bsSimple.getLength(),"->",bsBest.getLength(),"(" + (bsSimple.getLength()-bsBest.getLength()), "byte(s)) for",polyline.getClass().getSimpleName(),"with",polyline.getPoints().size(),"points");
126 else
127 log.info("optimizer only reduced bit stream bit length from",bsSimple.getBitPosition(),"->",bsBest.getBitPosition(),"bits for",polyline.getClass().getSimpleName(),"with",polyline.getPoints().size(),"points, using original bit stream");
128 }
129 if (bsSimple.getLength() == bsBest.getLength()){
130 // if the (byte) length was not improved,
131 // prefer the bit stream that doesn't need the special "trick"
132 // to encode large values, it is assumed that this can safe a
133 // few CPU cycles when reading the map
134 return bsSimple;
135 }
136 return bsBest;
137 }
138 /**
139 * Write the bit stream to a BitWriter and return it.
140 *
141 * @return A class containing the written byte stream.
142 */
143 public BitWriter makeBitStream(int minPointsRequired, int xb, int yb) {
144 assert xb >= 0 && yb >= 0;
145
146 int xbits = base2Bits(xb);
147 if (!xSameSign)
148 xbits++;
149 int ybits = base2Bits(yb);
150 if (!ySameSign)
151 ybits++;
152
153
154 // Note no sign included.
155 if (log.isDebugEnabled())
156 log.debug("xbits", xbits, ", y=", ybits);
157
158 // Write the bitstream
159 BitWriter bw = new BitWriter();
160
161 // Pre bit stream info
162 bw.putn(xb, 4);
163 bw.putn(yb, 4);
164
165 bw.put1(xSameSign);
166 if (xSameSign)
167 bw.put1(xSignNegative);
168
169 bw.put1(ySameSign);
170 if (ySameSign)
171 bw.put1(ySignNegative);
172
173 if (log.isDebugEnabled()) {
174 log.debug("x same is", xSameSign, "sign is", xSignNegative);
175 log.debug("y same is", ySameSign, "sign is", ySignNegative);
176 }
177
178 if(extTypeLine) {
179 bw.put1(false); // no extra bits required
180 }
181
182 // first extra bit always appears to be false
183 // refers to the start point?
184 if (extraBit)
185 bw.put1(false);
186
187 int numPointsEncoded = 1;
188 for (int i = 0; i < deltas.length; i+=2) {
189 int dx = deltas[i];
190 int dy = deltas[i + 1];
191 if (dx == 0 && dy == 0) {
192 if (extraBit && !nodes[i/2+1] && i+2 != deltas.length) // don't skip CoordNode
193 continue;
194 }
195 ++numPointsEncoded;
196
197 if (log.isDebugEnabled())
198 log.debug("x delta", dx, "~", xbits);
199 if (xSameSign) {
200 bw.putn(Math.abs(dx), xbits);
201 } else {
202 bw.sputn(dx, xbits);
203 }
204
205 if (log.isDebugEnabled())
206 log.debug("y delta", dy, ybits);
207 if (ySameSign) {
208 bw.putn(Math.abs(dy), ybits);
209 } else {
210 bw.sputn(dy, ybits);
211 }
212 if (extraBit)
213 bw.put1(nodes[i/2+1]);
214 }
215
216 if (log.isDebugEnabled())
217 log.debug(bw);
218
219 if(numPointsEncoded < minPointsRequired)
220 return null;
221
222 return bw;
223 }
224
225 /**
226 * Calculate the correct lat and long points. They must be shifted if
227 * required by the zoom level. The point that is taken to be the
228 * location is just the first point in the line.
229 */
230 private void calcLatLong() {
231 Coord co = polyline.getPoints().get(0);
232
233 polyline.setLatitude(co.getLatitude());
234 polyline.setLongitude(co.getLongitude());
235 }
236
237 /**
238 * Calculate the deltas of one point to the other. While we are doing
239 * this we must save more information about the maximum sizes, if they
240 * are all the same sign etc. This must be done separately for both
241 * the lat and long values.
242 */
243 private void calcDeltas() {
244 Subdivision subdiv = polyline.getSubdiv();
245 if(log.isDebugEnabled())
246 log.debug("label offset", polyline.getLabel().getOffset());
247 List<Coord> points = polyline.getPoints();
248
249 // Space to hold the deltas
250 int numPointsToUse = points.size();
251 if (polyline instanceof Polygon && points.get(0).equals(points.get(points.size()-1))) {
252 --numPointsToUse; // no need to write the closing point
253 }
254 deltas = new int[2 * (numPointsToUse - 1)];
255
256 if (extraBit)
257 nodes = new boolean[numPointsToUse];
258 boolean first = true;
259
260 // OK go through the points
261 int lastLat = 0;
262 int lastLong = 0;
263 int minDx = 0, maxDx = 0;
264 int minDy = 0, maxDy = 0;
265 // index of first point in a series of identical coords (after shift)
266 int firstsame = 0;
267 for (int i = 0; i < numPointsToUse; i++) {
268 Coord co = points.get(i);
269
270 int lat = subdiv.roundLatToLocalShifted(co.getLatitude());
271 int lon = subdiv.roundLonToLocalShifted(co.getLongitude());
272 if (log.isDebugEnabled())
273 log.debug("shifted pos", lat, lon);
274
275 int dx = lon - lastLong;
276 int dy = lat - lastLat;
277 lastLong = lon;
278 lastLat = lat;
279 if (first) {
280 first = false;
281 continue;
282 }
283
284 /*
285 * Current thought is that the node indicator is set when
286 * the point is a routing node or a house number node.
287 * There's a separate first extra bit
288 * that always appears to be false. The last points' extra bit
289 * is set if the point is a node and this is not the last
290 * polyline making up the road.
291 */
292 if (extraBit) {
293 boolean isSpecialNode = co.getId() > 0 || (!ignoreNumberOnlyNodes && co.isNumberNode());
294 if (dx != 0 || dy != 0 || isSpecialNode)
295 firstsame = i;
296 boolean extra = false;
297 if (isSpecialNode) {
298 if (i < nodes.length - 1)
299 // inner node of polyline
300 extra = true;
301 else
302 // end node of polyline: set if inner
303 // node of road
304 extra = !polyline.isLastSegment();
305 }
306
307 /*
308 * Only the first among a range of equal points
309 * is written, so set the bit if any of the points
310 * is a node.
311 * Since we only write extra bits at level 0 now,
312 * this can only happen when points in the input
313 * data round to the same point in map units, so
314 * it may be better to handle this in the
315 * reader.
316 */
317 nodes[firstsame] = nodes[firstsame] || extra;
318 }
319
320 // find largest delta values
321 if (dx < minDx)
322 minDx = dx;
323 if (dx > maxDx)
324 maxDx = dx;
325 if (dy < minDy)
326 minDy = dy;
327 if (dy > maxDy)
328 maxDy = dy;
329
330 // Save the deltas
331 deltas[2*(i-1)] = dx;
332 deltas[2*(i-1) + 1] = dy;
333 }
334 // Find the maximum number of bits required to hold the delta values.
335 int xBits = Math.max(bitsNeeded(minDx), bitsNeeded(maxDx));
336 int yBits = Math.max(bitsNeeded(minDy), bitsNeeded(maxDy));
337
338 // Now we need to know the 'base' number of bits used to represent
339 // the value. In decoding you start with that number and add various
340 // adjustments to get the final value. We need to try and work
341 // backwards from this.
342 //
343 // Note that the sign bit is already not included so there is
344 // no adjustment needed for it.
345
346 if (log.isDebugEnabled())
347 log.debug("initial xBits, yBits", xBits, yBits);
348
349 this.xBase = bits2Base(xBits);
350 this.yBase = bits2Base(yBits);
351
352 if (log.isDebugEnabled())
353 log.debug("initial xBase, yBase", xBase, yBase);
354
355 // Set flags for same sign etc.
356 this.xSameSign = !(minDx < 0 && maxDx > 0);
357 this.ySameSign = !(minDy < 0 && maxDy > 0);
358 if (this.xSameSign)
359 this.xSignNegative = minDx < 0;
360 if (this.ySameSign)
361 this.ySignNegative = minDy < 0;
362 }
363
364 /**
365 * The bits needed to hold a number without truncating it.
366 *
367 * @param val The number for bit counting.
368 * @return The number of bits required.
369 */
370 public static int bitsNeeded(int val) {
371 int n = Math.abs(val);
372
373 int count = 0;
374 while (n != 0) {
375 n >>>= 1;
376 count++;
377 }
378 return count;
379 // count should be equal to Integer.SIZE - Integer.numberOfLeadingZeros(Math.abs(val));
380
381 }
382
383 public boolean isExtraBit() {
384 return extraBit;
385 }
386
387 private static int base2Bits(int base){
388 int bits = 2;
389 if (base < 10)
390 return bits + base;
391 else
392 return bits + (2 * base) - 9;
393 }
394
395 private static int bits2Base(int bits){
396 int base = Math.max(0, bits - 2);
397 if (base > 10) {
398 if ((base & 0x1) == 0)
399 base++;
400 base = 9 + (base - 9) / 2;
401 }
402 return base;
403 }
404 }