diff --git a/android-stuff.sh b/android-stuff.sh deleted file mode 100755 index 7073a287..00000000 --- a/android-stuff.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools -echo yes | android update sdk --filter platform-tools --no-ui -echo yes | android update sdk --filter android-21 --no-ui -echo yes | android update sdk --filter extra-android-support --no-ui -echo yes | android update sdk --filter extra-android-m2repository --no-ui diff --git a/vtm-pmd.xml b/config/vtm-pmd.xml similarity index 100% rename from vtm-pmd.xml rename to config/vtm-pmd.xml diff --git a/eclipse-formatter.xml b/eclipse/eclipse-formatter.xml similarity index 100% rename from eclipse-formatter.xml rename to eclipse/eclipse-formatter.xml diff --git a/eclipse/org.eclipse.jdt.core.prefs b/eclipse/org.eclipse.jdt.core.prefs index 28b67532..af48fa71 100644 --- a/eclipse/org.eclipse.jdt.core.prefs +++ b/eclipse/org.eclipse.jdt.core.prefs @@ -1,14 +1,14 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 +org.eclipse.jdt.core.compiler.source=1.7 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=82 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 @@ -282,7 +282,7 @@ org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false -org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.char=space org.eclipse.jdt.core.formatter.tabulation.size=4 org.eclipse.jdt.core.formatter.use_on_off_tags=false org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true diff --git a/jdee.gradle b/jdee.gradle deleted file mode 100644 index f53208d9..00000000 --- a/jdee.gradle +++ /dev/null @@ -1,72 +0,0 @@ -def prj = { project -> - - "(jde-project-file-version" (["1.0"]) - "(jde-set-variables" { - "'(jde-compile-option-directory" ([project.sourceSets.main.output.classesDir]) - "'(jde-junit-working-directory" ([project.projectDir]) - - "'(jde-compile-option-source" { - "'(" (["default"]) - } - - "'(jde-compile-option-target" { - "'(" (["default"]) - } - - "'(jde-compile-option-command-line-args" { - "'(" (["-${project.sourceCompatibility}"]) - } - - "'(jde-sourcepath" { - "'(" ( - project.sourceSets.main.allSource.srcDirs - + project.sourceSets.test.allSource.srcDirs) - } - - "'(jde-global-classpath" { - "'(" ( - [] + project.sourceSets.main.output.classesDir - + project.sourceSets.test.output.classesDir - + project.sourceSets.main.allSource.srcDirs - + project.sourceSets.test.allSource.srcDirs - + (([] as Set) + project.configurations.compile.getFiles() - + project.configurations.testCompile.getFiles())) - } - } -} - -subprojects { - task("jdee") << { - def output = new File(project.projectDir, "prj.el").newPrintWriter() - try { - prj.delegate = new NodeBuilder() { - def lev = 0 - - def write = { Object file -> - output.print '\n' + ''.padRight(lev, ' ') + "\"${file}\"".tr('\\', '/') - } - - Object createNode(Object name) { - output.print '\n' + ''.padRight(lev++, ' ') + name - return name - } - - Object createNode(Object name, Object value) { - createNode(name) - value.each write - return name - } - - void nodeCompleted(Object parent, Object child) { - output.print ")" - lev-- - } - } - prj(project) - output.close() - } finally { - output.flush() - } - } -} - diff --git a/resources/rendertheme.xsd b/resources/rendertheme.xsd index e1863fd5..728f0d83 100644 --- a/resources/rendertheme.xsd +++ b/resources/rendertheme.xsd @@ -1,274 +1,278 @@ - - - - - - - - - + + + + + + + + + - - - - - - - + + + + + + + - - - - - + + + + + - - - - - - - + + + + + + + - - - - - - - - - - - - - - - - - + + + + + + + - - - - - - - - + + + + + + + + + - - - - - + + + + + + + + - - - - - - + + + + + - - - - - + + + + + + - - - - - - - - + + + + + - - - - - - - - - - - - - + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + - --> - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - + + + - - - + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - + + + + + + + - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - \ No newline at end of file + + + diff --git a/vtm-android-example/proguard-project.txt b/vtm-android-example/proguard-project.txt deleted file mode 100644 index f2fe1559..00000000 --- a/vtm-android-example/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/vtm-android-example/project.properties b/vtm-android-example/project.properties index 6768ec95..916037e3 100644 --- a/vtm-android-example/project.properties +++ b/vtm-android-example/project.properties @@ -11,6 +11,4 @@ #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. -target=android-21 -android.library.reference.1=../vtm-android -android.library.reference.2=../appcompat +target=android-23 diff --git a/vtm-android-example/res/layout/activity_file_picker.xml b/vtm-android-example/res/layout/activity_file_picker.xml index 3ed7ea46..b47fa3b5 100644 --- a/vtm-android-example/res/layout/activity_file_picker.xml +++ b/vtm-android-example/res/layout/activity_file_picker.xml @@ -1,4 +1,9 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/vtm-android-example/res/layout/activity_map.xml b/vtm-android-example/res/layout/activity_map.xml index ea4c4470..884de7dd 100644 --- a/vtm-android-example/res/layout/activity_map.xml +++ b/vtm-android-example/res/layout/activity_map.xml @@ -1,7 +1,6 @@ + android:layout_height="match_parent"> + android:layout_height="match_parent"> - + android:layout_height="fill_parent"> + android:orientation="vertical"> + android:visibility="gone"> + android:orientation="horizontal"> - + android:layout_width="fill_parent" + android:layout_height="fill_parent"> + + \ No newline at end of file diff --git a/vtm-android-example/res/layout/jeo_indoor_map.xml b/vtm-android-example/res/layout/jeo_indoor_map.xml index e761d147..a496530c 100644 --- a/vtm-android-example/res/layout/jeo_indoor_map.xml +++ b/vtm-android-example/res/layout/jeo_indoor_map.xml @@ -1,13 +1,11 @@ + android:layout_height="match_parent"> - + android:layout_height="fill_parent"> + android:orientation="vertical"> - diff --git a/vtm-android-example/res/menu/theme_menu.xml b/vtm-android-example/res/menu/theme_menu.xml index cd0d2bbf..70987103 100644 --- a/vtm-android-example/res/menu/theme_menu.xml +++ b/vtm-android-example/res/menu/theme_menu.xml @@ -1,37 +1,32 @@ - + + android:checkableBehavior="single"> - + android:title="@string/theme_default"> - + android:title="@string/theme_tubes"> - + android:title="@string/theme_osmarender"> - + android:title="@string/theme_newtron"> - + android:title="@string/menu_gridlayer"> \ No newline at end of file diff --git a/vtm-android-example/src/org/oscim/android/filepicker/FilePicker.java b/vtm-android-example/src/org/oscim/android/filepicker/FilePicker.java index 40553e4f..d7fb536f 100755 --- a/vtm-android-example/src/org/oscim/android/filepicker/FilePicker.java +++ b/vtm-android-example/src/org/oscim/android/filepicker/FilePicker.java @@ -14,13 +14,6 @@ */ package org.oscim.android.filepicker; -import java.io.File; -import java.io.FileFilter; -import java.util.Arrays; -import java.util.Comparator; - -import org.oscim.android.test.R; - import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; @@ -32,6 +25,13 @@ import android.view.View; import android.widget.AdapterView; import android.widget.GridView; +import org.oscim.android.test.R; + +import java.io.File; +import java.io.FileFilter; +import java.util.Arrays; +import java.util.Comparator; + /** * A FilePicker displays the contents of directories. The user can navigate * within the file system and select a single @@ -40,211 +40,208 @@ import android.widget.GridView; * {@link #setFileComparator(Comparator)}. By default subfolders and files are * grouped and each group is ordered * alphabetically. - *

+ *

* A {@link FileFilter} can be activated via * {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files and * folders. By default all files and folders are visible. - *

+ *

* Another FileFilter can be applied via * {@link #setFileSelectFilter(ValidFileFilter)} to check if a selected file is * valid before its path is returned. By default all files are considered as * valid and can be selected. */ public class FilePicker extends Activity implements AdapterView.OnItemClickListener { - /** - * The name of the extra data in the result {@link Intent}. - */ - public static final String SELECTED_FILE = "selectedFile"; + /** + * The name of the extra data in the result {@link Intent}. + */ + public static final String SELECTED_FILE = "selectedFile"; - private static final String PREFERENCES_FILE = "FilePicker"; - private static final String CURRENT_DIRECTORY = "currentDirectory"; - private static final String DEFAULT_DIRECTORY = "/"; - private static final int DIALOG_FILE_INVALID = 0; + private static final String PREFERENCES_FILE = "FilePicker"; + private static final String CURRENT_DIRECTORY = "currentDirectory"; + private static final String DEFAULT_DIRECTORY = "/"; + private static final int DIALOG_FILE_INVALID = 0; - // private static final int DIALOG_FILE_SELECT = 1; - protected Comparator mFileComparator = getDefaultFileComparator(); - protected FileFilter mFileDisplayFilter; - protected ValidFileFilter mFileSelectFilter; + // private static final int DIALOG_FILE_SELECT = 1; + protected Comparator mFileComparator = getDefaultFileComparator(); + protected FileFilter mFileDisplayFilter; + protected ValidFileFilter mFileSelectFilter; - /** - * Sets the file comparator which is used to order the contents of all - * directories before displaying them. If set to - * null, subfolders and files will not be ordered. - * - * @param fileComparator - * the file comparator (may be null). - */ - public void setFileComparator(Comparator fileComparator) { - mFileComparator = fileComparator; - } + /** + * Sets the file comparator which is used to order the contents of all + * directories before displaying them. If set to + * null, subfolders and files will not be ordered. + * + * @param fileComparator the file comparator (may be null). + */ + public void setFileComparator(Comparator fileComparator) { + mFileComparator = fileComparator; + } - /** - * Sets the file display filter. This filter is used to determine which - * files and subfolders of directories will be - * displayed. If set to null, all files and subfolders are shown. - * - * @param fileDisplayFilter - * the file display filter (may be null). - */ - public void setFileDisplayFilter(FileFilter fileDisplayFilter) { - mFileDisplayFilter = fileDisplayFilter; - } + /** + * Sets the file display filter. This filter is used to determine which + * files and subfolders of directories will be + * displayed. If set to null, all files and subfolders are shown. + * + * @param fileDisplayFilter the file display filter (may be null). + */ + public void setFileDisplayFilter(FileFilter fileDisplayFilter) { + mFileDisplayFilter = fileDisplayFilter; + } - /** - * Sets the file select filter. This filter is used when the user selects a - * file to determine if it is valid. If set - * to null, all files are considered as valid. - * - * @param fileSelectFilter - * the file selection filter (may be null). - */ - public void setFileSelectFilter(ValidFileFilter fileSelectFilter) { - mFileSelectFilter = fileSelectFilter; - } + /** + * Sets the file select filter. This filter is used when the user selects a + * file to determine if it is valid. If set + * to null, all files are considered as valid. + * + * @param fileSelectFilter the file selection filter (may be null). + */ + public void setFileSelectFilter(ValidFileFilter fileSelectFilter) { + mFileSelectFilter = fileSelectFilter; + } - /** - * Creates the default file comparator. - * - * @return the default file comparator. - */ - private static Comparator getDefaultFileComparator() { - // order all files by type and alphabetically by name - return new Comparator() { - @Override - public int compare(File file1, File file2) { - if (file1.isDirectory() && !file2.isDirectory()) { - return -1; - } else if (!file1.isDirectory() && file2.isDirectory()) { - return 1; - } else { - return file1.getName().compareToIgnoreCase(file2.getName()); - } - } - }; - } + /** + * Creates the default file comparator. + * + * @return the default file comparator. + */ + private static Comparator getDefaultFileComparator() { + // order all files by type and alphabetically by name + return new Comparator() { + @Override + public int compare(File file1, File file2) { + if (file1.isDirectory() && !file2.isDirectory()) { + return -1; + } else if (!file1.isDirectory() && file2.isDirectory()) { + return 1; + } else { + return file1.getName().compareToIgnoreCase(file2.getName()); + } + } + }; + } - private File mDirectory; - private FilePickerIconAdapter mFilePickerIconAdapter; - private File[] mFiles; - private File[] mFilesWithParentFolder; + private File mDirectory; + private FilePickerIconAdapter mFilePickerIconAdapter; + private File[] mFiles; + private File[] mFilesWithParentFolder; - @SuppressWarnings("deprecation") - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - File selectedFile = mFiles[(int) id]; - if (selectedFile.isDirectory()) { - mDirectory = selectedFile; - browseToCurrentDirectory(); - } else if (mFileSelectFilter == null || mFileSelectFilter.accept(selectedFile)) { - setResult(RESULT_OK, - new Intent().putExtra(SELECTED_FILE, selectedFile.getAbsolutePath())); - finish(); - } else { - showDialog(DIALOG_FILE_INVALID); - } - } + @SuppressWarnings("deprecation") + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + File selectedFile = mFiles[(int) id]; + if (selectedFile.isDirectory()) { + mDirectory = selectedFile; + browseToCurrentDirectory(); + } else if (mFileSelectFilter == null || mFileSelectFilter.accept(selectedFile)) { + setResult(RESULT_OK, + new Intent().putExtra(SELECTED_FILE, selectedFile.getAbsolutePath())); + finish(); + } else { + showDialog(DIALOG_FILE_INVALID); + } + } - /** - * Browses to the current directory. - */ - private void browseToCurrentDirectory() { - setTitle(mDirectory.getAbsolutePath()); + /** + * Browses to the current directory. + */ + private void browseToCurrentDirectory() { + setTitle(mDirectory.getAbsolutePath()); - // read the subfolders and files from the current directory - if (mFileDisplayFilter == null) { - mFiles = mDirectory.listFiles(); - } else { - mFiles = mDirectory.listFiles(mFileDisplayFilter); - } + // read the subfolders and files from the current directory + if (mFileDisplayFilter == null) { + mFiles = mDirectory.listFiles(); + } else { + mFiles = mDirectory.listFiles(mFileDisplayFilter); + } - if (mFiles == null) { - mFiles = new File[0]; - } else { - // order the subfolders and files - Arrays.sort(mFiles, mFileComparator); - } + if (mFiles == null) { + mFiles = new File[0]; + } else { + // order the subfolders and files + Arrays.sort(mFiles, mFileComparator); + } - // if a parent directory exists, add it at the first position - if (mDirectory.getParentFile() != null) { - mFilesWithParentFolder = new File[mFiles.length + 1]; - mFilesWithParentFolder[0] = mDirectory.getParentFile(); - System.arraycopy(mFiles, 0, mFilesWithParentFolder, 1, - mFiles.length); - mFiles = mFilesWithParentFolder; - mFilePickerIconAdapter.setFiles(mFiles, true); - } else { - mFilePickerIconAdapter.setFiles(mFiles, false); - } - mFilePickerIconAdapter.notifyDataSetChanged(); - } + // if a parent directory exists, add it at the first position + if (mDirectory.getParentFile() != null) { + mFilesWithParentFolder = new File[mFiles.length + 1]; + mFilesWithParentFolder[0] = mDirectory.getParentFile(); + System.arraycopy(mFiles, 0, mFilesWithParentFolder, 1, + mFiles.length); + mFiles = mFilesWithParentFolder; + mFilePickerIconAdapter.setFiles(mFiles, true); + } else { + mFilePickerIconAdapter.setFiles(mFiles, false); + } + mFilePickerIconAdapter.notifyDataSetChanged(); + } - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_file_picker); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_file_picker); - mFilePickerIconAdapter = new FilePickerIconAdapter(this); - GridView gridView = (GridView) findViewById(R.id.filePickerView); - gridView.setOnItemClickListener(this); - gridView.setAdapter(mFilePickerIconAdapter); + mFilePickerIconAdapter = new FilePickerIconAdapter(this); + GridView gridView = (GridView) findViewById(R.id.filePickerView); + gridView.setOnItemClickListener(this); + gridView.setAdapter(mFilePickerIconAdapter); - // if (savedInstanceState == null) { - // // first start of this instance - // showDialog(DIALOG_FILE_SELECT); - // } - } + // if (savedInstanceState == null) { + // // first start of this instance + // showDialog(DIALOG_FILE_SELECT); + // } + } - @Override - protected Dialog onCreateDialog(int id) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - switch (id) { - case DIALOG_FILE_INVALID: - builder.setIcon(android.R.drawable.ic_menu_info_details); - builder.setTitle(R.string.error); + @Override + protected Dialog onCreateDialog(int id) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + switch (id) { + case DIALOG_FILE_INVALID: + builder.setIcon(android.R.drawable.ic_menu_info_details); + builder.setTitle(R.string.error); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(getString(R.string.file_invalid)); - stringBuilder.append("\n\n"); - stringBuilder.append(mFileSelectFilter.getFileOpenResult() - .getErrorMessage()); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(getString(R.string.file_invalid)); + stringBuilder.append("\n\n"); + stringBuilder.append(mFileSelectFilter.getFileOpenResult() + .getErrorMessage()); - builder.setMessage(stringBuilder.toString()); - builder.setPositiveButton(R.string.ok, null); - return builder.create(); - // case DIALOG_FILE_SELECT: - // builder.setMessage(R.string.file_select); - // builder.setPositiveButton(R.string.ok, null); - // return builder.create(); - default: - // do dialog will be created - return null; - } - } + builder.setMessage(stringBuilder.toString()); + builder.setPositiveButton(R.string.ok, null); + return builder.create(); + // case DIALOG_FILE_SELECT: + // builder.setMessage(R.string.file_select); + // builder.setPositiveButton(R.string.ok, null); + // return builder.create(); + default: + // do dialog will be created + return null; + } + } - @Override - protected void onPause() { - super.onPause(); - // save the current directory - Editor editor = getSharedPreferences(PREFERENCES_FILE, MODE_PRIVATE).edit(); - editor.clear(); - if (mDirectory != null) { - editor.putString(CURRENT_DIRECTORY, mDirectory.getAbsolutePath()); - } - editor.commit(); - } + @Override + protected void onPause() { + super.onPause(); + // save the current directory + Editor editor = getSharedPreferences(PREFERENCES_FILE, MODE_PRIVATE).edit(); + editor.clear(); + if (mDirectory != null) { + editor.putString(CURRENT_DIRECTORY, mDirectory.getAbsolutePath()); + } + editor.commit(); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); - // restore the current directory - SharedPreferences preferences = getSharedPreferences(PREFERENCES_FILE, - MODE_PRIVATE); - mDirectory = new File(preferences.getString(CURRENT_DIRECTORY, - DEFAULT_DIRECTORY)); - if (!mDirectory.exists() || !mDirectory.canRead()) { - mDirectory = new File(DEFAULT_DIRECTORY); - } - browseToCurrentDirectory(); - } + // restore the current directory + SharedPreferences preferences = getSharedPreferences(PREFERENCES_FILE, + MODE_PRIVATE); + mDirectory = new File(preferences.getString(CURRENT_DIRECTORY, + DEFAULT_DIRECTORY)); + if (!mDirectory.exists() || !mDirectory.canRead()) { + mDirectory = new File(DEFAULT_DIRECTORY); + } + browseToCurrentDirectory(); + } } diff --git a/vtm-android-example/src/org/oscim/android/filepicker/FilePickerIconAdapter.java b/vtm-android-example/src/org/oscim/android/filepicker/FilePickerIconAdapter.java index 8943cfe9..d3871d3d 100755 --- a/vtm-android-example/src/org/oscim/android/filepicker/FilePickerIconAdapter.java +++ b/vtm-android-example/src/org/oscim/android/filepicker/FilePickerIconAdapter.java @@ -14,10 +14,6 @@ */ package org.oscim.android.filepicker; -import java.io.File; - -import org.oscim.android.test.R; - import android.content.Context; import android.view.Gravity; import android.view.View; @@ -25,92 +21,93 @@ import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; +import org.oscim.android.test.R; + +import java.io.File; + /** * An adapter for the FilePicker GridView. */ class FilePickerIconAdapter extends BaseAdapter { - private final Context mContext; - private File mCurrentFile; - private File[] mFiles; - private boolean mHasParentFolder; - private TextView mTextView; + private final Context mContext; + private File mCurrentFile; + private File[] mFiles; + private boolean mHasParentFolder; + private TextView mTextView; - /** - * Creates a new FilePickerIconAdapter with the given context. - * - * @param context - * the context of this adapter, through which new Views are - * created. - */ - FilePickerIconAdapter(Context context) { - super(); - mContext = context; - } + /** + * Creates a new FilePickerIconAdapter with the given context. + * + * @param context the context of this adapter, through which new Views are + * created. + */ + FilePickerIconAdapter(Context context) { + super(); + mContext = context; + } - @Override - public int getCount() { - if (mFiles == null) { - return 0; - } - return mFiles.length; - } + @Override + public int getCount() { + if (mFiles == null) { + return 0; + } + return mFiles.length; + } - @Override - public Object getItem(int index) { - return mFiles[index]; - } + @Override + public Object getItem(int index) { + return mFiles[index]; + } - @Override - public long getItemId(int index) { - return index; - } + @Override + public long getItemId(int index) { + return index; + } - @Override - public View getView(int index, View convertView, ViewGroup parent) { - if (convertView instanceof TextView) { - // recycle the old view - mTextView = (TextView) convertView; - } else { - // create a new view object - mTextView = new TextView(mContext); - mTextView.setLines(2); - mTextView.setGravity(Gravity.CENTER_HORIZONTAL); - mTextView.setPadding(5, 10, 5, 10); - } + @Override + public View getView(int index, View convertView, ViewGroup parent) { + if (convertView instanceof TextView) { + // recycle the old view + mTextView = (TextView) convertView; + } else { + // create a new view object + mTextView = new TextView(mContext); + mTextView.setLines(2); + mTextView.setGravity(Gravity.CENTER_HORIZONTAL); + mTextView.setPadding(5, 10, 5, 10); + } - if (index == 0 && mHasParentFolder) { - // the parent directory of the current folder - mTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.file_picker_back, 0, 0); - mTextView.setText(".."); - } else { - mCurrentFile = mFiles[index]; - if (mCurrentFile.isDirectory()) { - mTextView.setCompoundDrawablesWithIntrinsicBounds(0, - R.drawable.file_picker_folder, - 0, - 0); - } else { - mTextView.setCompoundDrawablesWithIntrinsicBounds(0, - R.drawable.file_picker_file, - 0, - 0); - } - mTextView.setText(mCurrentFile.getName()); - } - return mTextView; - } + if (index == 0 && mHasParentFolder) { + // the parent directory of the current folder + mTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.file_picker_back, 0, 0); + mTextView.setText(".."); + } else { + mCurrentFile = mFiles[index]; + if (mCurrentFile.isDirectory()) { + mTextView.setCompoundDrawablesWithIntrinsicBounds(0, + R.drawable.file_picker_folder, + 0, + 0); + } else { + mTextView.setCompoundDrawablesWithIntrinsicBounds(0, + R.drawable.file_picker_file, + 0, + 0); + } + mTextView.setText(mCurrentFile.getName()); + } + return mTextView; + } - /** - * Sets the data of this adapter. - * - * @param files - * the new files for this adapter. - * @param newHasParentFolder - * true if the file array has a parent folder at index 0, false - * otherwise. - */ - void setFiles(File[] files, boolean newHasParentFolder) { - mFiles = files.clone(); - mHasParentFolder = newHasParentFolder; - } + /** + * Sets the data of this adapter. + * + * @param files the new files for this adapter. + * @param newHasParentFolder true if the file array has a parent folder at index 0, false + * otherwise. + */ + void setFiles(File[] files, boolean newHasParentFolder) { + mFiles = files.clone(); + mHasParentFolder = newHasParentFolder; + } } diff --git a/vtm-android-example/src/org/oscim/android/filepicker/FilterByFileExtension.java b/vtm-android-example/src/org/oscim/android/filepicker/FilterByFileExtension.java index 32e1c9df..b3c97e2c 100644 --- a/vtm-android-example/src/org/oscim/android/filepicker/FilterByFileExtension.java +++ b/vtm-android-example/src/org/oscim/android/filepicker/FilterByFileExtension.java @@ -22,27 +22,26 @@ import java.io.FileFilter; * extension. */ public class FilterByFileExtension implements FileFilter { - private final String mExtension; + private final String mExtension; - /** - * @param extension - * the allowed file name extension. - */ - public FilterByFileExtension(String extension) { - mExtension = extension; - } + /** + * @param extension the allowed file name extension. + */ + public FilterByFileExtension(String extension) { + mExtension = extension; + } - @Override - public boolean accept(File file) { - // accept only readable files - if (file.canRead()) { - if (file.isDirectory()) { - // accept all directories - return true; - } else if (file.isFile() && file.getName().endsWith(mExtension)) { - return true; - } - } - return false; - } + @Override + public boolean accept(File file) { + // accept only readable files + if (file.canRead()) { + if (file.isDirectory()) { + // accept all directories + return true; + } else if (file.isFile() && file.getName().endsWith(mExtension)) { + return true; + } + } + return false; + } } diff --git a/vtm-android-example/src/org/oscim/android/filepicker/ValidFileFilter.java b/vtm-android-example/src/org/oscim/android/filepicker/ValidFileFilter.java index cea19fd0..c7bb7f8f 100644 --- a/vtm-android-example/src/org/oscim/android/filepicker/ValidFileFilter.java +++ b/vtm-android-example/src/org/oscim/android/filepicker/ValidFileFilter.java @@ -14,16 +14,16 @@ */ package org.oscim.android.filepicker; -import java.io.FileFilter; - import org.oscim.tiling.TileSource.OpenResult; +import java.io.FileFilter; + /** * An extension of the {@link FileFilter} interface. */ public interface ValidFileFilter extends FileFilter { - /** - * @return the result of the last {@link #accept} call (might be null). - */ - OpenResult getFileOpenResult(); + /** + * @return the result of the last {@link #accept} call (might be null). + */ + OpenResult getFileOpenResult(); } diff --git a/vtm-android-example/src/org/oscim/android/filepicker/ValidMapFile.java b/vtm-android-example/src/org/oscim/android/filepicker/ValidMapFile.java index b916fa2a..ce078b94 100644 --- a/vtm-android-example/src/org/oscim/android/filepicker/ValidMapFile.java +++ b/vtm-android-example/src/org/oscim/android/filepicker/ValidMapFile.java @@ -14,29 +14,29 @@ */ package org.oscim.android.filepicker; -import java.io.File; - import org.oscim.tiling.TileSource.OpenResult; import org.oscim.tiling.source.mapfile.MapFileTileSource; +import java.io.File; + /** * Accepts all valid map files. */ public final class ValidMapFile implements ValidFileFilter { - private OpenResult mOpenResult; + private OpenResult mOpenResult; - @Override - public boolean accept(File file) { - MapFileTileSource mapFileSource = new MapFileTileSource(); - mapFileSource.setMapFile(file.getAbsolutePath()); + @Override + public boolean accept(File file) { + MapFileTileSource mapFileSource = new MapFileTileSource(); + mapFileSource.setMapFile(file.getAbsolutePath()); - this.mOpenResult = mapFileSource.open(); - mapFileSource.close(); - return mOpenResult.isSuccess(); - } + this.mOpenResult = mapFileSource.open(); + mapFileSource.close(); + return mOpenResult.isSuccess(); + } - @Override - public OpenResult getFileOpenResult() { - return mOpenResult; - } + @Override + public OpenResult getFileOpenResult() { + return mOpenResult; + } } diff --git a/vtm-android-example/src/org/oscim/android/filepicker/ValidRenderTheme.java b/vtm-android-example/src/org/oscim/android/filepicker/ValidRenderTheme.java index 08e5f616..d6421143 100644 --- a/vtm-android-example/src/org/oscim/android/filepicker/ValidRenderTheme.java +++ b/vtm-android-example/src/org/oscim/android/filepicker/ValidRenderTheme.java @@ -14,6 +14,12 @@ */ package org.oscim.android.filepicker; +import org.oscim.theme.XmlThemeBuilder; +import org.oscim.tiling.TileSource.OpenResult; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -22,50 +28,44 @@ import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import org.oscim.theme.XmlThemeBuilder; -import org.oscim.tiling.TileSource.OpenResult; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; - /** * Accepts all valid render theme XML files. */ public final class ValidRenderTheme implements ValidFileFilter { - private OpenResult mOpenResult; + private OpenResult mOpenResult; - @Override - public boolean accept(File file) { - InputStream inputStream = null; + @Override + public boolean accept(File file) { + InputStream inputStream = null; - try { - inputStream = new FileInputStream(file); - XmlThemeBuilder renderThemeHandler = new XmlThemeBuilder(); - XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); - xmlReader.setContentHandler(renderThemeHandler); - xmlReader.parse(new InputSource(inputStream)); - mOpenResult = OpenResult.SUCCESS; - } catch (ParserConfigurationException e) { - mOpenResult = new OpenResult(e.getMessage()); - } catch (SAXException e) { - mOpenResult = new OpenResult(e.getMessage()); - } catch (IOException e) { - mOpenResult = new OpenResult(e.getMessage()); - } finally { - try { - if (inputStream != null) { - inputStream.close(); - } - } catch (IOException e) { - mOpenResult = new OpenResult(e.getMessage()); - } - } + try { + inputStream = new FileInputStream(file); + XmlThemeBuilder renderThemeHandler = new XmlThemeBuilder(); + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + xmlReader.setContentHandler(renderThemeHandler); + xmlReader.parse(new InputSource(inputStream)); + mOpenResult = OpenResult.SUCCESS; + } catch (ParserConfigurationException e) { + mOpenResult = new OpenResult(e.getMessage()); + } catch (SAXException e) { + mOpenResult = new OpenResult(e.getMessage()); + } catch (IOException e) { + mOpenResult = new OpenResult(e.getMessage()); + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + mOpenResult = new OpenResult(e.getMessage()); + } + } - return mOpenResult.isSuccess(); - } + return mOpenResult.isSuccess(); + } - @Override - public OpenResult getFileOpenResult() { - return mOpenResult; - } + @Override + public OpenResult getFileOpenResult() { + return mOpenResult; + } } diff --git a/vtm-android-example/src/org/oscim/android/test/BaseMapActivity.java b/vtm-android-example/src/org/oscim/android/test/BaseMapActivity.java index 9cfac367..c1b8a35f 100644 --- a/vtm-android-example/src/org/oscim/android/test/BaseMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/BaseMapActivity.java @@ -16,6 +16,10 @@ */ package org.oscim.android.test; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; + import org.oscim.android.cache.TileCache; import org.oscim.core.MapPosition; import org.oscim.layers.TileGridLayer; @@ -26,101 +30,97 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; - public class BaseMapActivity extends MapActivity { - static final Logger log = LoggerFactory.getLogger(BaseMapActivity.class); + static final Logger log = LoggerFactory.getLogger(BaseMapActivity.class); - final static boolean USE_CACHE = true; + final static boolean USE_CACHE = true; - VectorTileLayer mBaseLayer; - TileSource mTileSource; - TileGridLayer mGridLayer; + VectorTileLayer mBaseLayer; + TileSource mTileSource; + TileGridLayer mGridLayer; - private TileCache mCache; + private TileCache mCache; - public BaseMapActivity(int contentView) { - super(contentView); - } + public BaseMapActivity(int contentView) { + super(contentView); + } - public BaseMapActivity() { - } + public BaseMapActivity() { + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - mTileSource = new OSciMap4TileSource(); + mTileSource = new OSciMap4TileSource(); - if (USE_CACHE) { - mCache = new TileCache(this, null, "tile.db"); - mCache.setCacheSize(512 * (1 << 10)); - mTileSource.setCache(mCache); - } - mBaseLayer = mMap.setBaseMap(mTileSource); + if (USE_CACHE) { + mCache = new TileCache(this, null, "tile.db"); + mCache.setCacheSize(512 * (1 << 10)); + mTileSource.setCache(mCache); + } + mBaseLayer = mMap.setBaseMap(mTileSource); /* set initial position on first run */ - MapPosition pos = new MapPosition(); - mMap.getMapPosition(pos); - if (pos.x == 0.5 && pos.y == 0.5) - mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16)); - } + MapPosition pos = new MapPosition(); + mMap.getMapPosition(pos); + if (pos.x == 0.5 && pos.y == 0.5) + mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16)); + } - @Override - protected void onDestroy() { - super.onDestroy(); + @Override + protected void onDestroy() { + super.onDestroy(); - if (mCache != null) - mCache.dispose(); - } + if (mCache != null) + mCache.dispose(); + } - @Override - public boolean onOptionsItemSelected(MenuItem item) { + @Override + public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.theme_default: - mMap.setTheme(VtmThemes.DEFAULT); - item.setChecked(true); - return true; + switch (item.getItemId()) { + case R.id.theme_default: + mMap.setTheme(VtmThemes.DEFAULT); + item.setChecked(true); + return true; - case R.id.theme_tubes: - mMap.setTheme(VtmThemes.TRONRENDER); - item.setChecked(true); - return true; + case R.id.theme_tubes: + mMap.setTheme(VtmThemes.TRONRENDER); + item.setChecked(true); + return true; - case R.id.theme_osmarender: - mMap.setTheme(VtmThemes.OSMARENDER); - item.setChecked(true); - return true; + case R.id.theme_osmarender: + mMap.setTheme(VtmThemes.OSMARENDER); + item.setChecked(true); + return true; - case R.id.theme_newtron: - mMap.setTheme(VtmThemes.NEWTRON); - item.setChecked(true); - return true; + case R.id.theme_newtron: + mMap.setTheme(VtmThemes.NEWTRON); + item.setChecked(true); + return true; - case R.id.gridlayer: - if (item.isChecked()) { - item.setChecked(false); - mMap.layers().remove(mGridLayer); - } else { - item.setChecked(true); - if (mGridLayer == null) - mGridLayer = new TileGridLayer(mMap); + case R.id.gridlayer: + if (item.isChecked()) { + item.setChecked(false); + mMap.layers().remove(mGridLayer); + } else { + item.setChecked(true); + if (mGridLayer == null) + mGridLayer = new TileGridLayer(mMap); - mMap.layers().add(mGridLayer); - } - mMap.updateMap(true); - return true; - } + mMap.layers().add(mGridLayer); + } + mMap.updateMap(true); + return true; + } - return false; - } + return false; + } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.theme_menu, menu); - return true; - } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.theme_menu, menu); + return true; + } } diff --git a/vtm-android-example/src/org/oscim/android/test/BitmapTileMapActivity.java b/vtm-android-example/src/org/oscim/android/test/BitmapTileMapActivity.java index c92ee595..a61d061a 100644 --- a/vtm-android-example/src/org/oscim/android/test/BitmapTileMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/BitmapTileMapActivity.java @@ -14,6 +14,8 @@ */ package org.oscim.android.test; +import android.os.Bundle; + import org.oscim.android.cache.TileCache; import org.oscim.backend.canvas.Color; import org.oscim.core.MapPosition; @@ -26,92 +28,90 @@ import org.oscim.tiling.source.bitmap.DefaultSources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.os.Bundle; - public class BitmapTileMapActivity extends MapActivity { - static final Logger log = LoggerFactory.getLogger(BitmapTileMapActivity.class); + static final Logger log = LoggerFactory.getLogger(BitmapTileMapActivity.class); - private final static boolean USE_CACHE = true; + private final static boolean USE_CACHE = true; - private final BitmapTileSource mTileSource; - protected BitmapTileLayer mBitmapLayer; + private final BitmapTileSource mTileSource; + protected BitmapTileLayer mBitmapLayer; - public BitmapTileMapActivity() { - this(DefaultSources.OPENSTREETMAP.build()); - } + public BitmapTileMapActivity() { + this(DefaultSources.OPENSTREETMAP.build()); + } - public BitmapTileMapActivity(BitmapTileSource tileSource) { - super(R.layout.activity_map); - mTileSource = tileSource; - } + public BitmapTileMapActivity(BitmapTileSource tileSource) { + super(R.layout.activity_map); + mTileSource = tileSource; + } - private TileCache mCache; + private TileCache mCache; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - MapRenderer.setBackgroundColor(0xff777777); - mMap.layers().add(new TileGridLayer(mMap, Color.GRAY, 1.8f, 8)); + MapRenderer.setBackgroundColor(0xff777777); + mMap.layers().add(new TileGridLayer(mMap, Color.GRAY, 1.8f, 8)); - if (mTileSource == null) - return; + if (mTileSource == null) + return; - if (USE_CACHE) { - String cacheFile = mTileSource.getUrl() - .toString() - .replaceFirst("https?://", "") - .replaceAll("/", "-"); + if (USE_CACHE) { + String cacheFile = mTileSource.getUrl() + .toString() + .replaceFirst("https?://", "") + .replaceAll("/", "-"); - log.debug("use bitmap cache {}", cacheFile); - mCache = new TileCache(this, null, cacheFile); - mCache.setCacheSize(512 * (1 << 10)); - mTileSource.setCache(mCache); - } + log.debug("use bitmap cache {}", cacheFile); + mCache = new TileCache(this, null, cacheFile); + mCache.setCacheSize(512 * (1 << 10)); + mTileSource.setCache(mCache); + } - mBitmapLayer = new BitmapTileLayer(mMap, mTileSource); - mMap.layers().add(mBitmapLayer); + mBitmapLayer = new BitmapTileLayer(mMap, mTileSource); + mMap.layers().add(mBitmapLayer); - //loooop(1); - } + //loooop(1); + } - @Override - protected void onDestroy() { - super.onDestroy(); - if (mCache != null) - mCache.dispose(); - } + @Override + protected void onDestroy() { + super.onDestroy(); + if (mCache != null) + mCache.dispose(); + } - // Stress testing - void loooop(final int i) { - final long time = (long) (500 + Math.random() * 1000); - mMapView.postDelayed(new Runnable() { - @Override - public void run() { + // Stress testing + void loooop(final int i) { + final long time = (long) (500 + Math.random() * 1000); + mMapView.postDelayed(new Runnable() { + @Override + public void run() { - MapPosition p = new MapPosition(); - if (i == 1) { - mMapView.map().getMapPosition(p); - p.setScale(4); - mMapView.map().animator().animateTo(time, p); - } else { - //mMapView.map().setMapPosition(p); - p.setScale(2 + (1 << (int) (Math.random() * 13))); - // p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale())); - // p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale())); - p.setX(MercatorProjection.longitudeToX(Math.random() * 180)); - p.setY(MercatorProjection.latitudeToY(Math.random() * 60)); + MapPosition p = new MapPosition(); + if (i == 1) { + mMapView.map().getMapPosition(p); + p.setScale(4); + mMapView.map().animator().animateTo(time, p); + } else { + //mMapView.map().setMapPosition(p); + p.setScale(2 + (1 << (int) (Math.random() * 13))); + // p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale())); + // p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale())); + p.setX(MercatorProjection.longitudeToX(Math.random() * 180)); + p.setY(MercatorProjection.latitudeToY(Math.random() * 60)); - p.setTilt((float) (Math.random() * 60)); - p.setBearing((float) (Math.random() * 360)); - //mMapView.map().setMapPosition(p); + p.setTilt((float) (Math.random() * 60)); + p.setBearing((float) (Math.random() * 360)); + //mMapView.map().setMapPosition(p); - mMapView.map().animator().animateTo(time, p); - } - loooop((i + 1) % 2); + mMapView.map().animator().animateTo(time, p); + } + loooop((i + 1) % 2); - } - }, time); - } + } + }, time); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/JeoIndoorMapActivity.java b/vtm-android-example/src/org/oscim/android/test/JeoIndoorMapActivity.java index 1630372c..eea516b1 100644 --- a/vtm-android-example/src/org/oscim/android/test/JeoIndoorMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/JeoIndoorMapActivity.java @@ -16,14 +16,14 @@ */ package org.oscim.android.test; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.Arrays; +import android.content.Context; +import android.os.Bundle; +import android.view.View; +import android.widget.Toast; +import android.widget.ToggleButton; -import org.jeo.vector.VectorDataset; import org.jeo.map.Style; +import org.jeo.vector.VectorDataset; import org.oscim.layers.OSMIndoorLayer; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.labeling.LabelLayer; @@ -33,146 +33,146 @@ import org.oscim.utils.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.content.Context; -import android.os.Bundle; -import android.view.View; -import android.widget.Toast; -import android.widget.ToggleButton; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; public class JeoIndoorMapActivity extends BaseMapActivity { - public static final Logger log = LoggerFactory.getLogger(JeoIndoorMapActivity.class); + public static final Logger log = LoggerFactory.getLogger(JeoIndoorMapActivity.class); - // from http://overpass-turbo.eu/s/2vp - String PATH = "https://gist.github.com/anonymous/8960337/raw/overpass.geojson"; - //String PATH = "https://gist.github.com/hjanetzek/9280925/raw/overpass.geojson"; + // from http://overpass-turbo.eu/s/2vp + String PATH = "https://gist.github.com/anonymous/8960337/raw/overpass.geojson"; + //String PATH = "https://gist.github.com/hjanetzek/9280925/raw/overpass.geojson"; - private OSMIndoorLayer mIndoorLayer; + private OSMIndoorLayer mIndoorLayer; - public JeoIndoorMapActivity() { - super(R.layout.jeo_indoor_map); - } + public JeoIndoorMapActivity() { + super(R.layout.jeo_indoor_map); + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - mMap.addTask(new Runnable() { - @Override - public void run() { - showToast("load data"); - InputStream is = null; - try { - // File file = new File(Environment.getExternalStorageDirectory() - // .getAbsolutePath(), "osmindoor.json"); - // is = new FileInputStream(file); + mMap.addTask(new Runnable() { + @Override + public void run() { + showToast("load data"); + InputStream is = null; + try { + // File file = new File(Environment.getExternalStorageDirectory() + // .getAbsolutePath(), "osmindoor.json"); + // is = new FileInputStream(file); - URL url = new URL(PATH); - URLConnection conn = url.openConnection(); - is = conn.getInputStream(); - loadJson(is); - } catch (IOException e) { - e.printStackTrace(); - } finally { - IOUtils.closeQuietly(is); - } - } - }); + URL url = new URL(PATH); + URLConnection conn = url.openConnection(); + is = conn.getInputStream(); + loadJson(is); + } catch (IOException e) { + e.printStackTrace(); + } finally { + IOUtils.closeQuietly(is); + } + } + }); - mMap.setTheme(VtmThemes.DEFAULT); + mMap.setTheme(VtmThemes.DEFAULT); - mMap.layers().add(new BuildingLayer(mMap, mBaseLayer)); - mMap.layers().add(new LabelLayer(mMap, mBaseLayer)); + mMap.layers().add(new BuildingLayer(mMap, mBaseLayer)); + mMap.layers().add(new LabelLayer(mMap, mBaseLayer)); - // mMap.layers().add(new TileGridLayer(mMap)); - // String file = Environment.getExternalStorageDirectory().getAbsolutePath(); - // VectorDataset data = (VectorDataset) JeoTest.getJsonData(file + "/states.json", true); - // Style style = JeoTest.getStyle(); - // mMap.layers().add(new JeoVectorLayer(mMap, data, style)); - } + // mMap.layers().add(new TileGridLayer(mMap)); + // String file = Environment.getExternalStorageDirectory().getAbsolutePath(); + // VectorDataset data = (VectorDataset) JeoTest.getJsonData(file + "/states.json", true); + // Style style = JeoTest.getStyle(); + // mMap.layers().add(new JeoVectorLayer(mMap, data, style)); + } - void loadJson(InputStream is) { - showToast("got data"); + void loadJson(InputStream is) { + showToast("got data"); - VectorDataset data = JeoTest.readGeoJson(is); - Style style = JeoTest.getStyle(); - mIndoorLayer = new OSMIndoorLayer(mMap, data, style); - mMap.layers().add(mIndoorLayer); + VectorDataset data = JeoTest.readGeoJson(is); + Style style = JeoTest.getStyle(); + mIndoorLayer = new OSMIndoorLayer(mMap, data, style); + mMap.layers().add(mIndoorLayer); - showToast("data ready"); - mMap.updateMap(true); + showToast("data ready"); + mMap.updateMap(true); - mIndoorLayer.activeLevels[0] = true; - shift(); - } + mIndoorLayer.activeLevels[0] = true; + shift(); + } - public void showToast(final String text) { - final Context ctx = this; - runOnUiThread(new Runnable() { - @Override - public void run() { - Toast toast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT); - toast.show(); - } - }); - } + public void showToast(final String text) { + final Context ctx = this; + runOnUiThread(new Runnable() { + @Override + public void run() { + Toast toast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT); + toast.show(); + } + }); + } - boolean mShift = true; + boolean mShift = true; - public void shift() { - if (!mShift) - return; + public void shift() { + if (!mShift) + return; - mMap.postDelayed(new Runnable() { + mMap.postDelayed(new Runnable() { - @Override - public void run() { - for (int i = 0; i < 10; i++) { - if (mIndoorLayer.activeLevels[i]) { - mIndoorLayer.activeLevels[i] = false; - mIndoorLayer.activeLevels[(i + 1) % 9] = true; - mIndoorLayer.update(); - break; - } - } - shift(); - } - }, 200); + @Override + public void run() { + for (int i = 0; i < 10; i++) { + if (mIndoorLayer.activeLevels[i]) { + mIndoorLayer.activeLevels[i] = false; + mIndoorLayer.activeLevels[(i + 1) % 9] = true; + mIndoorLayer.update(); + break; + } + } + shift(); + } + }, 200); - } + } - public void onClick(View v) { - mShift = false; + public void onClick(View v) { + mShift = false; - if (mIndoorLayer == null) - return; + if (mIndoorLayer == null) + return; - int i = 0; + int i = 0; - if (v instanceof ToggleButton) { - ToggleButton b = (ToggleButton) v; - i = (b.getTextOn().charAt(0) - '0') + 1; - } + if (v instanceof ToggleButton) { + ToggleButton b = (ToggleButton) v; + i = (b.getTextOn().charAt(0) - '0') + 1; + } - if (i < 0 || i > 9) - i = 0; + if (i < 0 || i > 9) + i = 0; - mIndoorLayer.activeLevels[i] ^= true; - ((ToggleButton) v).setChecked(mIndoorLayer.activeLevels[i]); - log.debug(Arrays.toString(mIndoorLayer.activeLevels)); - mIndoorLayer.update(); - } + mIndoorLayer.activeLevels[i] ^= true; + ((ToggleButton) v).setChecked(mIndoorLayer.activeLevels[i]); + log.debug(Arrays.toString(mIndoorLayer.activeLevels)); + mIndoorLayer.update(); + } - @Override - protected void onStop() { - super.onStop(); - } + @Override + protected void onStop() { + super.onStop(); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); /* ignore saved position */ - //mMap.setMapPosition(49.417, 8.673, 1 << 17); - mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); - } + //mMap.setMapPosition(49.417, 8.673, 1 << 17); + mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/MapActivity.java b/vtm-android-example/src/org/oscim/android/test/MapActivity.java index 3380d202..0acb6421 100644 --- a/vtm-android-example/src/org/oscim/android/test/MapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/MapActivity.java @@ -16,53 +16,53 @@ */ package org.oscim.android.test; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; + import org.oscim.android.MapPreferences; import org.oscim.android.MapView; import org.oscim.map.Map; -import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; - public abstract class MapActivity extends AppCompatActivity { - MapView mMapView; - Map mMap; - MapPreferences mPrefs; + MapView mMapView; + Map mMap; + MapPreferences mPrefs; - protected final int mContentView; + protected final int mContentView; - public MapActivity(int contentView) { - mContentView = contentView; - } + public MapActivity(int contentView) { + mContentView = contentView; + } - public MapActivity() { - this(R.layout.activity_map); - } + public MapActivity() { + this(R.layout.activity_map); + } - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(mContentView); + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(mContentView); - setTitle(getClass().getSimpleName()); + setTitle(getClass().getSimpleName()); - mMapView = (MapView) findViewById(R.id.mapView); - mMap = mMapView.map(); - mPrefs = new MapPreferences(MapActivity.class.getName(), this); - } + mMapView = (MapView) findViewById(R.id.mapView); + mMap = mMapView.map(); + mPrefs = new MapPreferences(MapActivity.class.getName(), this); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); - mPrefs.load(mMapView.map()); - mMapView.onResume(); - } + mPrefs.load(mMapView.map()); + mMapView.onResume(); + } - @Override - protected void onPause() { - super.onPause(); + @Override + protected void onPause() { + super.onPause(); - mMapView.onPause(); - mPrefs.save(mMapView.map()); - } + mMapView.onPause(); + mPrefs.save(mMapView.map()); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/MapsforgeMapActivity.java b/vtm-android-example/src/org/oscim/android/test/MapsforgeMapActivity.java index 944b10bc..6a3ac9d3 100644 --- a/vtm-android-example/src/org/oscim/android/test/MapsforgeMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/MapsforgeMapActivity.java @@ -17,6 +17,11 @@ */ package org.oscim.android.test; +import android.content.Intent; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; + import org.oscim.android.filepicker.FilePicker; import org.oscim.android.filepicker.FilterByFileExtension; import org.oscim.android.filepicker.ValidMapFile; @@ -30,106 +35,101 @@ import org.oscim.theme.VtmThemes; import org.oscim.tiling.source.mapfile.MapFileTileSource; import org.oscim.tiling.source.mapfile.MapInfo; -import android.content.Intent; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; - public class MapsforgeMapActivity extends MapActivity { - private static final int SELECT_MAP_FILE = 0; + private static final int SELECT_MAP_FILE = 0; - private TileGridLayer mGridLayer; + private TileGridLayer mGridLayer; - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - startActivityForResult(new Intent(this, MapFilePicker.class), - SELECT_MAP_FILE); - } + startActivityForResult(new Intent(this, MapFilePicker.class), + SELECT_MAP_FILE); + } - public static class MapFilePicker extends FilePicker { - public MapFilePicker() { - setFileDisplayFilter(new FilterByFileExtension(".map")); - setFileSelectFilter(new ValidMapFile()); - } - } + public static class MapFilePicker extends FilePicker { + public MapFilePicker() { + setFileDisplayFilter(new FilterByFileExtension(".map")); + setFileSelectFilter(new ValidMapFile()); + } + } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.theme_menu, menu); - return true; - } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.theme_menu, menu); + return true; + } - @Override - public boolean onOptionsItemSelected(MenuItem item) { + @Override + public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.theme_default: - mMap.setTheme(VtmThemes.DEFAULT); - item.setChecked(true); - return true; + switch (item.getItemId()) { + case R.id.theme_default: + mMap.setTheme(VtmThemes.DEFAULT); + item.setChecked(true); + return true; - case R.id.theme_tubes: - mMap.setTheme(VtmThemes.TRONRENDER); - item.setChecked(true); - return true; + case R.id.theme_tubes: + mMap.setTheme(VtmThemes.TRONRENDER); + item.setChecked(true); + return true; - case R.id.theme_osmarender: - mMap.setTheme(VtmThemes.OSMARENDER); - item.setChecked(true); - return true; + case R.id.theme_osmarender: + mMap.setTheme(VtmThemes.OSMARENDER); + item.setChecked(true); + return true; - case R.id.theme_newtron: - mMap.setTheme(VtmThemes.NEWTRON); - item.setChecked(true); - return true; + case R.id.theme_newtron: + mMap.setTheme(VtmThemes.NEWTRON); + item.setChecked(true); + return true; - case R.id.gridlayer: - if (item.isChecked()) { - item.setChecked(false); - mMap.layers().remove(mGridLayer); - } else { - item.setChecked(true); - if (mGridLayer == null) - mGridLayer = new TileGridLayer(mMap); + case R.id.gridlayer: + if (item.isChecked()) { + item.setChecked(false); + mMap.layers().remove(mGridLayer); + } else { + item.setChecked(true); + if (mGridLayer == null) + mGridLayer = new TileGridLayer(mMap); - mMap.layers().add(mGridLayer); - } - mMap.updateMap(true); - return true; - } + mMap.layers().add(mGridLayer); + } + mMap.updateMap(true); + return true; + } - return false; - } + return false; + } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent intent) { + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent intent) { - if (requestCode == SELECT_MAP_FILE) { - if (resultCode != RESULT_OK || intent == null || intent.getStringExtra(FilePicker.SELECTED_FILE) == null) { - finish(); - return; - } + if (requestCode == SELECT_MAP_FILE) { + if (resultCode != RESULT_OK || intent == null || intent.getStringExtra(FilePicker.SELECTED_FILE) == null) { + finish(); + return; + } - MapFileTileSource tileSource = new MapFileTileSource(); - tileSource.setPreferredLanguage("en"); - String file = intent.getStringExtra(FilePicker.SELECTED_FILE); - if (tileSource.setMapFile(file)) { + MapFileTileSource tileSource = new MapFileTileSource(); + tileSource.setPreferredLanguage("en"); + String file = intent.getStringExtra(FilePicker.SELECTED_FILE); + if (tileSource.setMapFile(file)) { - VectorTileLayer l = mMap.setBaseMap(tileSource); - mMap.setTheme(VtmThemes.DEFAULT); + VectorTileLayer l = mMap.setBaseMap(tileSource); + mMap.setTheme(VtmThemes.DEFAULT); - mMap.layers().add(new BuildingLayer(mMap, l)); - mMap.layers().add(new LabelLayer(mMap, l)); + mMap.layers().add(new BuildingLayer(mMap, l)); + mMap.layers().add(new LabelLayer(mMap, l)); - MapInfo info = tileSource.getMapInfo(); - MapPosition pos = new MapPosition(); - pos.setByBoundingBox(info.boundingBox, Tile.SIZE * 4, Tile.SIZE * 4); - mMap.setMapPosition(pos); + MapInfo info = tileSource.getMapInfo(); + MapPosition pos = new MapPosition(); + pos.setByBoundingBox(info.boundingBox, Tile.SIZE * 4, Tile.SIZE * 4); + mMap.setMapPosition(pos); - mPrefs.clear(); - } - } - } + mPrefs.clear(); + } + } + } } diff --git a/vtm-android-example/src/org/oscim/android/test/MarkerOverlayActivity.java b/vtm-android-example/src/org/oscim/android/test/MarkerOverlayActivity.java index db13468f..235cf296 100644 --- a/vtm-android-example/src/org/oscim/android/test/MarkerOverlayActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/MarkerOverlayActivity.java @@ -17,11 +17,9 @@ */ package org.oscim.android.test; -import static org.oscim.android.canvas.AndroidGraphics.drawableToBitmap; -import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; - -import java.util.ArrayList; -import java.util.List; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.widget.Toast; import org.oscim.backend.canvas.Bitmap; import org.oscim.core.GeoPoint; @@ -32,83 +30,85 @@ import org.oscim.layers.marker.MarkerItem; import org.oscim.layers.marker.MarkerItem.HotspotPlace; import org.oscim.layers.marker.MarkerSymbol; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.widget.Toast; +import java.util.ArrayList; +import java.util.List; + +import static org.oscim.android.canvas.AndroidGraphics.drawableToBitmap; +import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; public class MarkerOverlayActivity extends BitmapTileMapActivity implements OnItemGestureListener { - private static final boolean BILLBOARDS = true; - private MarkerSymbol mFocusMarker; + private static final boolean BILLBOARDS = true; + private MarkerSymbol mFocusMarker; - public MarkerOverlayActivity() { - super(STAMEN_TONER.build()); - } + public MarkerOverlayActivity() { + super(STAMEN_TONER.build()); + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); /* directly load bitmap from resources */ - Bitmap bitmap = drawableToBitmap(getResources(), R.drawable.marker_poi); + Bitmap bitmap = drawableToBitmap(getResources(), R.drawable.marker_poi); - MarkerSymbol symbol; - if (BILLBOARDS) - symbol = new MarkerSymbol(bitmap, HotspotPlace.CENTER); - else - symbol = new MarkerSymbol(bitmap, 0.5f, 0.5f, false); + MarkerSymbol symbol; + if (BILLBOARDS) + symbol = new MarkerSymbol(bitmap, HotspotPlace.CENTER); + else + symbol = new MarkerSymbol(bitmap, 0.5f, 0.5f, false); /* another option: use some bitmap drawable */ - Drawable d = getResources().getDrawable(R.drawable.ic_launcher); - if (BILLBOARDS) - mFocusMarker = new MarkerSymbol(drawableToBitmap(d), - HotspotPlace.BOTTOM_CENTER); - else - mFocusMarker = new MarkerSymbol(drawableToBitmap(d), - 0.5f, 0.5f, false); + Drawable d = getResources().getDrawable(R.drawable.ic_launcher); + if (BILLBOARDS) + mFocusMarker = new MarkerSymbol(drawableToBitmap(d), + HotspotPlace.BOTTOM_CENTER); + else + mFocusMarker = new MarkerSymbol(drawableToBitmap(d), + 0.5f, 0.5f, false); - ItemizedLayer markerLayer = - new ItemizedLayer(mMap, new ArrayList(), - symbol, this); + ItemizedLayer markerLayer = + new ItemizedLayer(mMap, new ArrayList(), + symbol, this); - mMap.layers().add(markerLayer); + mMap.layers().add(markerLayer); - List pts = new ArrayList(); + List pts = new ArrayList(); - for (double lat = -90; lat <= 90; lat += 5) { - for (double lon = -180; lon <= 180; lon += 5) - pts.add(new MarkerItem(lat + "/" + lon, "", - new GeoPoint(lat, lon))); - } + for (double lat = -90; lat <= 90; lat += 5) { + for (double lon = -180; lon <= 180; lon += 5) + pts.add(new MarkerItem(lat + "/" + lon, "", + new GeoPoint(lat, lon))); + } - markerLayer.addItems(pts); + markerLayer.addItems(pts); - mMap.layers().add(new TileGridLayer(mMap)); - } + mMap.layers().add(new TileGridLayer(mMap)); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); /* ignore saved position */ - mMap.setMapPosition(0, 0, 1 << 2); - } + mMap.setMapPosition(0, 0, 1 << 2); + } - @Override - public boolean onItemSingleTapUp(int index, MarkerItem item) { - if (item.getMarker() == null) - item.setMarker(mFocusMarker); - else - item.setMarker(null); + @Override + public boolean onItemSingleTapUp(int index, MarkerItem item) { + if (item.getMarker() == null) + item.setMarker(mFocusMarker); + else + item.setMarker(null); - Toast toast = Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT); - toast.show(); - return true; - } + Toast toast = Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT); + toast.show(); + return true; + } - @Override - public boolean onItemLongPress(int index, MarkerItem item) { - return false; - } + @Override + public boolean onItemLongPress(int index, MarkerItem item) { + return false; + } } diff --git a/vtm-android-example/src/org/oscim/android/test/OsmJsonMapActivity.java b/vtm-android-example/src/org/oscim/android/test/OsmJsonMapActivity.java index f5a7f95e..3e2e8621 100644 --- a/vtm-android-example/src/org/oscim/android/test/OsmJsonMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/OsmJsonMapActivity.java @@ -17,6 +17,8 @@ */ package org.oscim.android.test; +import android.os.Bundle; + import org.oscim.layers.TileGridLayer; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.VectorTileLayer; @@ -24,49 +26,47 @@ import org.oscim.layers.tile.vector.labeling.LabelLayer; import org.oscim.theme.IRenderTheme; import org.oscim.theme.ThemeLoader; import org.oscim.theme.VtmThemes; -import org.oscim.tiling.source.geojson.OsmRoadLineJsonTileSource; import org.oscim.tiling.source.geojson.OsmBuildingJsonTileSource; import org.oscim.tiling.source.geojson.OsmLanduseJsonTileSource; -import org.oscim.tiling.source.geojson.OsmWaterJsonTileSource; import org.oscim.tiling.source.geojson.OsmRoadLabelJsonTileSource; - -import android.os.Bundle; +import org.oscim.tiling.source.geojson.OsmRoadLineJsonTileSource; +import org.oscim.tiling.source.geojson.OsmWaterJsonTileSource; public class OsmJsonMapActivity extends MapActivity { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - IRenderTheme theme = ThemeLoader.load(VtmThemes.DEFAULT); + IRenderTheme theme = ThemeLoader.load(VtmThemes.DEFAULT); - mMap.setBaseMap(new VectorTileLayer(mMap, new OsmLanduseJsonTileSource())); - mMap.setTheme(theme); + mMap.setBaseMap(new VectorTileLayer(mMap, new OsmLanduseJsonTileSource())); + mMap.setTheme(theme); - VectorTileLayer l = new VectorTileLayer(mMap, new OsmWaterJsonTileSource()); - l.setRenderTheme(theme); - l.tileRenderer().setOverdrawColor(0); - mMap.layers().add(l); + VectorTileLayer l = new VectorTileLayer(mMap, new OsmWaterJsonTileSource()); + l.setRenderTheme(theme); + l.tileRenderer().setOverdrawColor(0); + mMap.layers().add(l); - l = new VectorTileLayer(mMap, new OsmRoadLineJsonTileSource()); - l.setRenderTheme(theme); - l.tileRenderer().setOverdrawColor(0); - mMap.layers().add(l); + l = new VectorTileLayer(mMap, new OsmRoadLineJsonTileSource()); + l.setRenderTheme(theme); + l.tileRenderer().setOverdrawColor(0); + mMap.layers().add(l); - l = new VectorTileLayer(mMap, new OsmBuildingJsonTileSource()); - l.setRenderTheme(theme); - l.tileRenderer().setOverdrawColor(0); - mMap.layers().add(l); - mMap.layers().add(new BuildingLayer(mMap, l)); + l = new VectorTileLayer(mMap, new OsmBuildingJsonTileSource()); + l.setRenderTheme(theme); + l.tileRenderer().setOverdrawColor(0); + mMap.layers().add(l); + mMap.layers().add(new BuildingLayer(mMap, l)); - l = new VectorTileLayer(mMap, new OsmRoadLabelJsonTileSource()); - l.setRenderTheme(theme); - l.tileRenderer().setOverdrawColor(0); - mMap.layers().add(l); - mMap.layers().add(new LabelLayer(mMap, l)); + l = new VectorTileLayer(mMap, new OsmRoadLabelJsonTileSource()); + l.setRenderTheme(theme); + l.tileRenderer().setOverdrawColor(0); + mMap.layers().add(l); + mMap.layers().add(new LabelLayer(mMap, l)); - mMap.layers().add(new TileGridLayer(mMap)); + mMap.layers().add(new TileGridLayer(mMap)); - mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16)); - } + mMap.setMapPosition(53.08, 8.83, Math.pow(2, 16)); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/PathOverlayActivity.java b/vtm-android-example/src/org/oscim/android/test/PathOverlayActivity.java index b5b54aa5..27b247e6 100644 --- a/vtm-android-example/src/org/oscim/android/test/PathOverlayActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/PathOverlayActivity.java @@ -17,9 +17,7 @@ */ package org.oscim.android.test; -import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; - -import java.util.ArrayList; +import android.os.Bundle; import org.oscim.backend.canvas.Color; import org.oscim.core.MapPosition; @@ -27,7 +25,9 @@ import org.oscim.event.Event; import org.oscim.layers.JtsPathLayer; import org.oscim.map.Map.UpdateListener; -import android.os.Bundle; +import java.util.ArrayList; + +import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; /** * This is a very INEFFICIENT and somewhat less usefull example for how to use @@ -35,75 +35,75 @@ import android.os.Bundle; */ public class PathOverlayActivity extends BitmapTileMapActivity { - public PathOverlayActivity() { - super(STAMEN_TONER.build()); - } + public PathOverlayActivity() { + super(STAMEN_TONER.build()); + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - //mBitmapLayer.tileRenderer().setBitmapAlpha(0.5f); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + //mBitmapLayer.tileRenderer().setBitmapAlpha(0.5f); - mMap.setMapPosition(0, 0, 1 << 2); - for (double lat = -90; lat <= 90; lat += 5) { - int c = Color.fade(Color.rainbow((float) (lat + 90) / 180), 0.5f); - JtsPathLayer pathLayer = new JtsPathLayer(mMap, c, 6); - mMap.layers().add(pathLayer); - mPathLayers.add(pathLayer); - } + mMap.setMapPosition(0, 0, 1 << 2); + for (double lat = -90; lat <= 90; lat += 5) { + int c = Color.fade(Color.rainbow((float) (lat + 90) / 180), 0.5f); + JtsPathLayer pathLayer = new JtsPathLayer(mMap, c, 6); + mMap.layers().add(pathLayer); + mPathLayers.add(pathLayer); + } - mMap.events.bind(new UpdateListener() { - @Override - public void onMapEvent(Event e, MapPosition mapPosition) { - //if (e == Map.UPDATE_EVENT) { - long t = System.currentTimeMillis(); - float pos = t % 20000 / 10000f - 1f; - createLayers(pos); + mMap.events.bind(new UpdateListener() { + @Override + public void onMapEvent(Event e, MapPosition mapPosition) { + //if (e == Map.UPDATE_EVENT) { + long t = System.currentTimeMillis(); + float pos = t % 20000 / 10000f - 1f; + createLayers(pos); - mMap.updateMap(true); - //} - } - }); - } + mMap.updateMap(true); + //} + } + }); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); /* ignore saved position */ - mMap.setMapPosition(0, 0, 1 << 2); - } + mMap.setMapPosition(0, 0, 1 << 2); + } - ArrayList mPathLayers = new ArrayList(); + ArrayList mPathLayers = new ArrayList(); - void createLayers(float pos) { + void createLayers(float pos) { - int i = 0; - for (double lat = -90; lat <= 90; lat += 5) { - double[] packedCoordinates = new double[360 + 2]; - //List pts = new ArrayList(); - int c = 0; - for (double lon = -180; lon <= 180; lon += 2) { - //pts.add(new GeoPoint(lat, lon)); - double longitude = lon; + int i = 0; + for (double lat = -90; lat <= 90; lat += 5) { + double[] packedCoordinates = new double[360 + 2]; + //List pts = new ArrayList(); + int c = 0; + for (double lon = -180; lon <= 180; lon += 2) { + //pts.add(new GeoPoint(lat, lon)); + double longitude = lon; - double latitude = lat + (pos * 90); - if (latitude < -90) - latitude += 180; - if (latitude > 90) - latitude -= 180; + double latitude = lat + (pos * 90); + if (latitude < -90) + latitude += 180; + if (latitude > 90) + latitude -= 180; - latitude += Math.sin((Math.abs(pos) * (lon / Math.PI))); + latitude += Math.sin((Math.abs(pos) * (lon / Math.PI))); - packedCoordinates[c++] = longitude; - packedCoordinates[c++] = latitude; - } + packedCoordinates[c++] = longitude; + packedCoordinates[c++] = latitude; + } - //LineString line = new LineString(factory.create(packedCoordinates, 2), geomFactory); - //mPathLayers.get(i++).setLineString(line); + //LineString line = new LineString(factory.create(packedCoordinates, 2), geomFactory); + //mPathLayers.get(i++).setLineString(line); - mPathLayers.get(i++).setLineString(packedCoordinates); + mPathLayers.get(i++).setLineString(packedCoordinates); - } - } + } + } } diff --git a/vtm-android-example/src/org/oscim/android/test/S3DBMapActivity.java b/vtm-android-example/src/org/oscim/android/test/S3DBMapActivity.java index e25558a6..42398b4b 100644 --- a/vtm-android-example/src/org/oscim/android/test/S3DBMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/S3DBMapActivity.java @@ -16,6 +16,8 @@ */ package org.oscim.android.test; +import android.os.Bundle; + import org.oscim.android.cache.TileCache; import org.oscim.layers.tile.TileLayer; import org.oscim.layers.tile.buildings.S3DBLayer; @@ -24,47 +26,45 @@ import org.oscim.theme.VtmThemes; import org.oscim.tiling.TileSource; import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; -import android.os.Bundle; - public class S3DBMapActivity extends BaseMapActivity { - TileCache mS3dbCache; + TileCache mS3dbCache; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - mMap.setTheme(VtmThemes.DEFAULT); + mMap.setTheme(VtmThemes.DEFAULT); - TileSource ts = OSciMap4TileSource.builder() - .url("http://opensciencemap.org/tiles/s3db") - .zoomMin(16) - .zoomMax(16) - .build(); + TileSource ts = OSciMap4TileSource.builder() + .url("http://opensciencemap.org/tiles/s3db") + .zoomMin(16) + .zoomMax(16) + .build(); - if (USE_CACHE) { - mS3dbCache = new TileCache(this, null, "s3db.db"); - mS3dbCache.setCacheSize(512 * (1 << 10)); - ts.setCache(mS3dbCache); - } - TileLayer tl = new S3DBLayer(mMap, ts, true, false); - mMap.layers().add(tl); - mMap.layers().add(new LabelLayer(mMap, mBaseLayer)); - } + if (USE_CACHE) { + mS3dbCache = new TileCache(this, null, "s3db.db"); + mS3dbCache.setCacheSize(512 * (1 << 10)); + ts.setCache(mS3dbCache); + } + TileLayer tl = new S3DBLayer(mMap, ts, true, false); + mMap.layers().add(tl); + mMap.layers().add(new LabelLayer(mMap, mBaseLayer)); + } - @Override - protected void onDestroy() { - super.onDestroy(); + @Override + protected void onDestroy() { + super.onDestroy(); - if (mS3dbCache != null) - mS3dbCache.dispose(); - } + if (mS3dbCache != null) + mS3dbCache.dispose(); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); /* ignore saved position */ - mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); - } + mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/Samples.java b/vtm-android-example/src/org/oscim/android/test/Samples.java index dbda2424..0f5d20da 100644 --- a/vtm-android-example/src/org/oscim/android/test/Samples.java +++ b/vtm-android-example/src/org/oscim/android/test/Samples.java @@ -17,9 +17,6 @@ */ package org.oscim.android.test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import android.app.Activity; import android.content.Intent; import android.os.Bundle; @@ -28,47 +25,50 @@ import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A simple start screen for the sample activities. */ public class Samples extends Activity { - public static Logger log = LoggerFactory.getLogger(Samples.class); + public static Logger log = LoggerFactory.getLogger(Samples.class); - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - setContentView(R.layout.activity_samples); - LinearLayout linearLayout = (LinearLayout) findViewById(R.id.samples); - linearLayout.addView(createButton(SimpleMapActivity.class)); - linearLayout.addView(createButton(BitmapTileMapActivity.class)); - linearLayout.addView(createButton(MapsforgeMapActivity.class)); - linearLayout.addView(createButton(PathOverlayActivity.class)); - linearLayout.addView(createButton(MarkerOverlayActivity.class)); - linearLayout.addView(createButton(ThemeStylerActivity.class)); - linearLayout.addView(createButton(S3DBMapActivity.class)); - linearLayout.addView(createButton(JeoIndoorMapActivity.class)); - linearLayout.addView(createButton(OsmJsonMapActivity.class)); - linearLayout.addView(createButton(VectorLayerMapActivity.class)); - } + setContentView(R.layout.activity_samples); + LinearLayout linearLayout = (LinearLayout) findViewById(R.id.samples); + linearLayout.addView(createButton(SimpleMapActivity.class)); + linearLayout.addView(createButton(BitmapTileMapActivity.class)); + linearLayout.addView(createButton(MapsforgeMapActivity.class)); + linearLayout.addView(createButton(PathOverlayActivity.class)); + linearLayout.addView(createButton(MarkerOverlayActivity.class)); + linearLayout.addView(createButton(ThemeStylerActivity.class)); + linearLayout.addView(createButton(S3DBMapActivity.class)); + linearLayout.addView(createButton(JeoIndoorMapActivity.class)); + linearLayout.addView(createButton(OsmJsonMapActivity.class)); + linearLayout.addView(createButton(VectorLayerMapActivity.class)); + } - private Button createButton(final Class clazz) { - return this.createButton(clazz, null); - } + private Button createButton(final Class clazz) { + return this.createButton(clazz, null); + } - private Button createButton(final Class clazz, String text) { - Button button = new Button(this); - if (text == null) { - button.setText(clazz.getSimpleName()); - } else { - button.setText(text); - } - button.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - startActivity(new Intent(Samples.this, clazz)); - } - }); - return button; - } + private Button createButton(final Class clazz, String text) { + Button button = new Button(this); + if (text == null) { + button.setText(clazz.getSimpleName()); + } else { + button.setText(text); + } + button.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + startActivity(new Intent(Samples.this, clazz)); + } + }); + return button; + } } diff --git a/vtm-android-example/src/org/oscim/android/test/SimpleMapActivity.java b/vtm-android-example/src/org/oscim/android/test/SimpleMapActivity.java index dfbde7d8..228a35ac 100644 --- a/vtm-android-example/src/org/oscim/android/test/SimpleMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/SimpleMapActivity.java @@ -13,7 +13,10 @@ * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see . - */package org.oscim.android.test; + */ +package org.oscim.android.test; + +import android.os.Bundle; import org.oscim.android.MapScaleBar; import org.oscim.core.MapPosition; @@ -25,63 +28,61 @@ import org.oscim.theme.IRenderTheme; import org.oscim.theme.ThemeLoader; import org.oscim.theme.VtmThemes; -import android.os.Bundle; - public class SimpleMapActivity extends BaseMapActivity { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - Layers layers = mMap.layers(); - layers.add(new BuildingLayer(mMap, mBaseLayer)); - layers.add(new LabelLayer(mMap, mBaseLayer)); - layers.add(new MapScaleBar(mMapView)); + Layers layers = mMap.layers(); + layers.add(new BuildingLayer(mMap, mBaseLayer)); + layers.add(new LabelLayer(mMap, mBaseLayer)); + layers.add(new MapScaleBar(mMapView)); - mMap.setTheme(VtmThemes.DEFAULT); - } + mMap.setTheme(VtmThemes.DEFAULT); + } - void runTheMonkey() { - themes[0] = ThemeLoader.load(VtmThemes.DEFAULT); - themes[1] = ThemeLoader.load(VtmThemes.OSMARENDER); - themes[2] = ThemeLoader.load(VtmThemes.TRONRENDER); - loooop(1); - } + void runTheMonkey() { + themes[0] = ThemeLoader.load(VtmThemes.DEFAULT); + themes[1] = ThemeLoader.load(VtmThemes.OSMARENDER); + themes[2] = ThemeLoader.load(VtmThemes.TRONRENDER); + loooop(1); + } - IRenderTheme[] themes = new IRenderTheme[3]; + IRenderTheme[] themes = new IRenderTheme[3]; - // Stress testing - void loooop(final int i) { - final long time = (long) (500 + Math.random() * 1000); - mMapView.postDelayed(new Runnable() { - @Override - public void run() { + // Stress testing + void loooop(final int i) { + final long time = (long) (500 + Math.random() * 1000); + mMapView.postDelayed(new Runnable() { + @Override + public void run() { - mMapView.map().setTheme(themes[i]); + mMapView.map().setTheme(themes[i]); - MapPosition p = new MapPosition(); - if (i == 1) { - mMapView.map().getMapPosition(p); - p.setScale(4); - mMapView.map().animator().animateTo(time, p); - } else { - //mMapView.map().setMapPosition(p); + MapPosition p = new MapPosition(); + if (i == 1) { + mMapView.map().getMapPosition(p); + p.setScale(4); + mMapView.map().animator().animateTo(time, p); + } else { + //mMapView.map().setMapPosition(p); - p.setScale(2 + (1 << (int) (Math.random() * 13))); - // p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale())); - // p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale())); - p.setX(MercatorProjection.longitudeToX(Math.random() * 180)); - p.setY(MercatorProjection.latitudeToY(Math.random() * 60)); + p.setScale(2 + (1 << (int) (Math.random() * 13))); + // p.setX((p.getX() + (Math.random() * 4 - 2) / p.getScale())); + // p.setY((p.getY() + (Math.random() * 4 - 2) / p.getScale())); + p.setX(MercatorProjection.longitudeToX(Math.random() * 180)); + p.setY(MercatorProjection.latitudeToY(Math.random() * 60)); - p.setTilt((float) (Math.random() * 60)); - p.setBearing((float) (Math.random() * 360)); - //mMapView.map().setMapPosition(p); + p.setTilt((float) (Math.random() * 60)); + p.setBearing((float) (Math.random() * 360)); + //mMapView.map().setMapPosition(p); - mMapView.map().animator().animateTo(time, p); - } - loooop((i + 1) % 2); + mMapView.map().animator().animateTo(time, p); + } + loooop((i + 1) % 2); - } - }, time); - } + } + }, time); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/ThemeStylerActivity.java b/vtm-android-example/src/org/oscim/android/test/ThemeStylerActivity.java index d342ef79..b6650d70 100644 --- a/vtm-android-example/src/org/oscim/android/test/ThemeStylerActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/ThemeStylerActivity.java @@ -1,7 +1,11 @@ package org.oscim.android.test; -import static org.oscim.utils.ColorUtil.modHsv; -import static org.oscim.utils.ColorUtil.shiftHue; +import android.os.Bundle; +import android.view.View; +import android.widget.RadioButton; +import android.widget.SeekBar; +import android.widget.SeekBar.OnSeekBarChangeListener; +import android.widget.ToggleButton; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.VectorTileLayer; @@ -20,169 +24,165 @@ import org.oscim.theme.styles.RenderStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.os.Bundle; -import android.view.View; -import android.widget.RadioButton; -import android.widget.SeekBar; -import android.widget.SeekBar.OnSeekBarChangeListener; -import android.widget.ToggleButton; +import static org.oscim.utils.ColorUtil.modHsv; +import static org.oscim.utils.ColorUtil.shiftHue; public class ThemeStylerActivity extends BaseMapActivity implements OnSeekBarChangeListener { - final Logger log = LoggerFactory.getLogger(ThemeStylerActivity.class); + final Logger log = LoggerFactory.getLogger(ThemeStylerActivity.class); - public ThemeStylerActivity() { - super(R.layout.activity_map_styler); - } + public ThemeStylerActivity() { + super(R.layout.activity_map_styler); + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ((SeekBar) findViewById(R.id.seekBarH)).setOnSeekBarChangeListener(this); - ((SeekBar) findViewById(R.id.seekBarS)).setOnSeekBarChangeListener(this); - ((SeekBar) findViewById(R.id.seekBarV)).setOnSeekBarChangeListener(this); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + ((SeekBar) findViewById(R.id.seekBarH)).setOnSeekBarChangeListener(this); + ((SeekBar) findViewById(R.id.seekBarS)).setOnSeekBarChangeListener(this); + ((SeekBar) findViewById(R.id.seekBarV)).setOnSeekBarChangeListener(this); - Layers layers = mMap.layers(); - layers.add(new BuildingLayer(mMap, mBaseLayer)); - layers.add(new LabelLayer(mMap, mBaseLayer)); + Layers layers = mMap.layers(); + layers.add(new BuildingLayer(mMap, mBaseLayer)); + layers.add(new LabelLayer(mMap, mBaseLayer)); - mMap.setTheme(VtmThemes.DEFAULT); - } + mMap.setTheme(VtmThemes.DEFAULT); + } - class ModStyleVisitor extends RuleVisitor { - private final LineBuilder lineBuilder = LineStyle.builder(); - private final AreaBuilder areaBuilder = AreaStyle.builder(); + class ModStyleVisitor extends RuleVisitor { + private final LineBuilder lineBuilder = LineStyle.builder(); + private final AreaBuilder areaBuilder = AreaStyle.builder(); - @Override - public void apply(Rule r) { - for (RenderStyle style : r.styles) { + @Override + public void apply(Rule r) { + for (RenderStyle style : r.styles) { - if (style instanceof LineStyle) { - LineStyle s = (LineStyle) style; - HSV c = lineColor; - if (lineColor.changed && s.outline) - continue; + if (style instanceof LineStyle) { + LineStyle s = (LineStyle) style; + HSV c = lineColor; + if (lineColor.changed && s.outline) + continue; - if (outlineColor.changed) { - if (!s.outline) - continue; - c = outlineColor; - } + if (outlineColor.changed) { + if (!s.outline) + continue; + c = outlineColor; + } - s.set(lineBuilder.set(s) - .color(modColor(s.color, c)) - .stippleColor(modColor(s.stippleColor, c)) - .build()); - continue; - } + s.set(lineBuilder.set(s) + .color(modColor(s.color, c)) + .stippleColor(modColor(s.stippleColor, c)) + .build()); + continue; + } - if (areaColor.changed && style instanceof AreaStyle) { - AreaStyle s = (AreaStyle) style; + if (areaColor.changed && style instanceof AreaStyle) { + AreaStyle s = (AreaStyle) style; - s.set(areaBuilder.set(s) - .color(modColor(s.color, areaColor)) - .blendColor(modColor(s.blendColor, areaColor)) - .strokeColor(modColor(s.strokeColor, areaColor)) - .build()); - } - } - super.apply(r); - } - } + s.set(areaBuilder.set(s) + .color(modColor(s.color, areaColor)) + .blendColor(modColor(s.blendColor, areaColor)) + .strokeColor(modColor(s.strokeColor, areaColor)) + .build()); + } + } + super.apply(r); + } + } - int modColor(int color, HSV hsv) { - return modHsv(shiftHue(color, hsv.hue), 1, hsv.sat, hsv.val, true); - } + int modColor(int color, HSV hsv) { + return modHsv(shiftHue(color, hsv.hue), 1, hsv.sat, hsv.val, true); + } - public static class HSV { - public double hue = 0; - public double sat = 1; - public double val = 1; - public boolean changed; - } + public static class HSV { + public double hue = 0; + public double sat = 1; + public double val = 1; + public boolean changed; + } - HSV lineColor = new HSV(); - HSV outlineColor = new HSV(); - HSV areaColor = new HSV(); + HSV lineColor = new HSV(); + HSV outlineColor = new HSV(); + HSV areaColor = new HSV(); - ModStyleVisitor mStyleVisitor = new ModStyleVisitor(); + ModStyleVisitor mStyleVisitor = new ModStyleVisitor(); - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!fromUser) - return; - int id = seekBar.getId(); + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + if (!fromUser) + return; + int id = seekBar.getId(); - boolean modLine = ((RadioButton) findViewById(R.id.checkBoxLine)).isChecked(); - boolean modArea = ((RadioButton) findViewById(R.id.checkBoxArea)).isChecked(); + boolean modLine = ((RadioButton) findViewById(R.id.checkBoxLine)).isChecked(); + boolean modArea = ((RadioButton) findViewById(R.id.checkBoxArea)).isChecked(); - HSV c; - if (modArea) - c = areaColor; - else if (modLine) - c = lineColor; - else - c = outlineColor; + HSV c; + if (modArea) + c = areaColor; + else if (modLine) + c = lineColor; + else + c = outlineColor; - if (id == R.id.seekBarS) - c.sat = progress / 50f; - else if (id == R.id.seekBarV) - c.val = progress / 50f; - else if (id == R.id.seekBarH) - c.hue = progress / 100f; + if (id == R.id.seekBarS) + c.sat = progress / 50f; + else if (id == R.id.seekBarV) + c.val = progress / 50f; + else if (id == R.id.seekBarH) + c.hue = progress / 100f; - log.debug((modArea ? "area" : "line") - + " h:" + c.hue - + " s:" + c.sat - + " v:" + c.val); + log.debug((modArea ? "area" : "line") + + " h:" + c.hue + + " s:" + c.sat + + " v:" + c.val); - VectorTileLayer l = (VectorTileLayer) mMap.layers().get(1); - RenderTheme t = (RenderTheme) l.getTheme(); + VectorTileLayer l = (VectorTileLayer) mMap.layers().get(1); + RenderTheme t = (RenderTheme) l.getTheme(); - c.changed = true; - t.traverseRules(mStyleVisitor); - t.updateStyles(); - c.changed = false; + c.changed = true; + t.traverseRules(mStyleVisitor); + t.updateStyles(); + c.changed = false; - if (modArea) - MapRenderer.setBackgroundColor(modColor(t.getMapBackground(), c)); + if (modArea) + MapRenderer.setBackgroundColor(modColor(t.getMapBackground(), c)); - mMap.render(); - } + mMap.render(); + } - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - } + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + } - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - } + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + } - public void onToggleControls(View view) { - findViewById(R.id.controls).setVisibility(((ToggleButton) view).isChecked() ? - View.VISIBLE : View.GONE); - } + public void onToggleControls(View view) { + findViewById(R.id.controls).setVisibility(((ToggleButton) view).isChecked() ? + View.VISIBLE : View.GONE); + } - public void onRadioButtonClicked(View view) { - boolean checked = ((RadioButton) view).isChecked(); - if (!checked) - return; + public void onRadioButtonClicked(View view) { + boolean checked = ((RadioButton) view).isChecked(); + if (!checked) + return; - HSV c = null; - switch (view.getId()) { - case R.id.checkBoxArea: - c = areaColor; - break; - case R.id.checkBoxLine: - c = lineColor; - break; - case R.id.checkBoxOutline: - c = outlineColor; - break; - } - if (c == null) - return; - ((SeekBar) findViewById(R.id.seekBarS)).setProgress((int) (c.sat * 50)); - ((SeekBar) findViewById(R.id.seekBarV)).setProgress((int) (c.val * 50)); - ((SeekBar) findViewById(R.id.seekBarH)).setProgress((int) (c.hue * 100)); - } + HSV c = null; + switch (view.getId()) { + case R.id.checkBoxArea: + c = areaColor; + break; + case R.id.checkBoxLine: + c = lineColor; + break; + case R.id.checkBoxOutline: + c = outlineColor; + break; + } + if (c == null) + return; + ((SeekBar) findViewById(R.id.seekBarS)).setProgress((int) (c.sat * 50)); + ((SeekBar) findViewById(R.id.seekBarV)).setProgress((int) (c.val * 50)); + ((SeekBar) findViewById(R.id.seekBarH)).setProgress((int) (c.hue * 100)); + } } diff --git a/vtm-android-example/src/org/oscim/android/test/VectorLayerMapActivity.java b/vtm-android-example/src/org/oscim/android/test/VectorLayerMapActivity.java index e832d65a..f128d410 100644 --- a/vtm-android-example/src/org/oscim/android/test/VectorLayerMapActivity.java +++ b/vtm-android-example/src/org/oscim/android/test/VectorLayerMapActivity.java @@ -17,6 +17,8 @@ */ package org.oscim.android.test; +import android.os.Bundle; + import org.oscim.backend.canvas.Color; import org.oscim.layers.TileGridLayer; import org.oscim.layers.vector.VectorLayer; @@ -25,73 +27,71 @@ import org.oscim.layers.vector.geometries.Style; import org.oscim.theme.VtmThemes; import org.oscim.utils.ColorUtil; -import android.os.Bundle; - public class VectorLayerMapActivity extends BaseMapActivity { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - mMap.setTheme(VtmThemes.DEFAULT); + mMap.setTheme(VtmThemes.DEFAULT); - VectorLayer vectorLayer = new VectorLayer(mMap); + VectorLayer vectorLayer = new VectorLayer(mMap); - // Geometry g = new GeomBuilder() - // .point(8.8, 53.1) - // .point() - // .buffer(1) - // .get(); - // - // vectorLayer.add(new PolygonDrawable(g, defaultStyle())); - // - // vectorLayer.add(new PointDrawable(53.1, 8.8, Style.builder() - // .setBuffer(0.5) - // .setFillColor(Color.RED) - // .setFillAlpha(0.2) - // .build())); - // - // Style.Builder sb = Style.builder() - // .setBuffer(0.5) - // .setFillColor(Color.RED) - // .setFillAlpha(0.2); - // - // Style style = sb.setFillAlpha(0.2).build(); - // - // int tileSize = 5; - // for (int x = -180; x < 180; x += tileSize) { - // for (int y = -90; y < 90; y += tileSize) { - // // Style style = sb.setFillAlpha(FastMath.clamp(FastMath.length(x, y) / 180, 0.2, 1)) - // // .build(); - // - // vectorLayer.add(new RectangleDrawable(FastMath.clamp(y, -85, 85), x, - // FastMath.clamp(y + tileSize - 0.1, -85, 85), - // x + tileSize - 0.1, style)); - // - // } - // } + // Geometry g = new GeomBuilder() + // .point(8.8, 53.1) + // .point() + // .buffer(1) + // .get(); + // + // vectorLayer.add(new PolygonDrawable(g, defaultStyle())); + // + // vectorLayer.add(new PointDrawable(53.1, 8.8, Style.builder() + // .setBuffer(0.5) + // .setFillColor(Color.RED) + // .setFillAlpha(0.2) + // .build())); + // + // Style.Builder sb = Style.builder() + // .setBuffer(0.5) + // .setFillColor(Color.RED) + // .setFillAlpha(0.2); + // + // Style style = sb.setFillAlpha(0.2).build(); + // + // int tileSize = 5; + // for (int x = -180; x < 180; x += tileSize) { + // for (int y = -90; y < 90; y += tileSize) { + // // Style style = sb.setFillAlpha(FastMath.clamp(FastMath.length(x, y) / 180, 0.2, 1)) + // // .build(); + // + // vectorLayer.add(new RectangleDrawable(FastMath.clamp(y, -85, 85), x, + // FastMath.clamp(y + tileSize - 0.1, -85, 85), + // x + tileSize - 0.1, style)); + // + // } + // } - Style.Builder sb = Style.builder() - .buffer(0.5) - .fillColor(Color.RED) - .fillAlpha(0.2); + Style.Builder sb = Style.builder() + .buffer(0.5) + .fillColor(Color.RED) + .fillAlpha(0.2); - for (int i = 0; i < 2000; i++) { - Style style = sb.buffer(Math.random() + 0.2) - .fillColor(ColorUtil.setHue(Color.RED, - (int) (Math.random() * 50) / 50.0)) - .fillAlpha(0.5) - .build(); + for (int i = 0; i < 2000; i++) { + Style style = sb.buffer(Math.random() + 0.2) + .fillColor(ColorUtil.setHue(Color.RED, + (int) (Math.random() * 50) / 50.0)) + .fillAlpha(0.5) + .build(); - vectorLayer.add(new PointDrawable(Math.random() * 180 - 90, - Math.random() * 360 - 180, - style)); + vectorLayer.add(new PointDrawable(Math.random() * 180 - 90, + Math.random() * 360 - 180, + style)); - } + } - mMap.layers().add(vectorLayer); - mMap.layers().add(new TileGridLayer(mMap, 0xff222222, 1.2f, 1)); + mMap.layers().add(vectorLayer); + mMap.layers().add(new TileGridLayer(mMap, 0xff222222, 1.2f, 1)); - mMap.setMapPosition(0, 0, 1 << 2); - } + mMap.setMapPosition(0, 0, 1 << 2); + } } diff --git a/vtm-android-gdx/AndroidManifest.xml b/vtm-android-gdx/AndroidManifest.xml index 8d978e08..078bc6e6 100644 --- a/vtm-android-gdx/AndroidManifest.xml +++ b/vtm-android-gdx/AndroidManifest.xml @@ -2,7 +2,7 @@ + android:versionName="1.0"> @@ -13,15 +13,15 @@ android:targetSdkVersion="22" /> + android:label="@string/app_name"> + android:screenOrientation="portrait"> @@ -29,4 +29,4 @@ - \ No newline at end of file + diff --git a/vtm-android-gdx/project.properties b/vtm-android-gdx/project.properties index bbe203c8..916037e3 100644 --- a/vtm-android-gdx/project.properties +++ b/vtm-android-gdx/project.properties @@ -3,9 +3,12 @@ # # This file must be checked in Version Control Systems. # -# To customize properties used by the Ant build system use, +# To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. -target=android-21 +target=android-23 diff --git a/vtm-android-gdx/res/layout/main.xml b/vtm-android-gdx/res/layout/main.xml index 777a3e48..a7f88043 100644 --- a/vtm-android-gdx/res/layout/main.xml +++ b/vtm-android-gdx/res/layout/main.xml @@ -2,6 +2,6 @@ + android:orientation="vertical"> \ No newline at end of file diff --git a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidBitmap.java b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidBitmap.java index 35b68e5b..0655deb9 100644 --- a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidBitmap.java +++ b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidBitmap.java @@ -16,88 +16,88 @@ */ package org.oscim.android.canvas; -import static android.graphics.Bitmap.Config.ARGB_8888; - -import java.io.InputStream; - import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLUtils; +import java.io.InputStream; + +import static android.graphics.Bitmap.Config.ARGB_8888; + public class AndroidBitmap implements org.oscim.backend.canvas.Bitmap { - final Bitmap mBitmap; + final Bitmap mBitmap; - public AndroidBitmap(InputStream inputStream) { - Bitmap bitmap = BitmapFactory.decodeStream(inputStream); - try { - GLUtils.getType(bitmap); - } catch (IllegalArgumentException e) { - bitmap = bitmap.copy(ARGB_8888, false); - } - mBitmap = bitmap; - } + public AndroidBitmap(InputStream inputStream) { + Bitmap bitmap = BitmapFactory.decodeStream(inputStream); + try { + GLUtils.getType(bitmap); + } catch (IllegalArgumentException e) { + bitmap = bitmap.copy(ARGB_8888, false); + } + mBitmap = bitmap; + } - @Override - public boolean isValid() { - return mBitmap != null; - } + @Override + public boolean isValid() { + return mBitmap != null; + } - /** - * @param format ignored always ARGB8888 - */ - public AndroidBitmap(int width, int height, int format) { - mBitmap = android.graphics.Bitmap - .createBitmap(width, height, ARGB_8888); - } + /** + * @param format ignored always ARGB8888 + */ + public AndroidBitmap(int width, int height, int format) { + mBitmap = android.graphics.Bitmap + .createBitmap(width, height, ARGB_8888); + } - public AndroidBitmap(android.graphics.Bitmap bitmap) { - mBitmap = bitmap; - } + public AndroidBitmap(android.graphics.Bitmap bitmap) { + mBitmap = bitmap; + } - @Override - public int getWidth() { - return mBitmap.getWidth(); - } + @Override + public int getWidth() { + return mBitmap.getWidth(); + } - @Override - public int getHeight() { - return mBitmap.getHeight(); - } + @Override + public int getHeight() { + return mBitmap.getHeight(); + } - @Override - public int[] getPixels() { - int width = getWidth(); - int height = getHeight(); - int[] colors = new int[width * height]; - mBitmap.getPixels(colors, 0, width, 0, 0, width, height); - return colors; - } + @Override + public int[] getPixels() { + int width = getWidth(); + int height = getHeight(); + int[] colors = new int[width * height]; + mBitmap.getPixels(colors, 0, width, 0, 0, width, height); + return colors; + } - @Override - public void eraseColor(int color) { - //int a = android.graphics.Color.TRANSPARENT; - mBitmap.eraseColor(color); - } + @Override + public void eraseColor(int color) { + //int a = android.graphics.Color.TRANSPARENT; + mBitmap.eraseColor(color); + } - @Override - public void uploadToTexture(boolean replace) { - int format = GLUtils.getInternalFormat(mBitmap); - int type = GLUtils.getType(mBitmap); + @Override + public void uploadToTexture(boolean replace) { + int format = GLUtils.getInternalFormat(mBitmap); + int type = GLUtils.getType(mBitmap); - if (replace) - GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, - mBitmap, format, type); - else - GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format, - mBitmap, type, 0); - } + if (replace) + GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, + mBitmap, format, type); + else + GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format, + mBitmap, type, 0); + } - @Override - public void recycle() { - if (mBitmap == null) - return; + @Override + public void recycle() { + if (mBitmap == null) + return; - mBitmap.recycle(); - } + mBitmap.recycle(); + } } diff --git a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidCanvas.java b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidCanvas.java index 1fc8aef4..2ae0e4c2 100644 --- a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidCanvas.java +++ b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidCanvas.java @@ -21,31 +21,31 @@ import org.oscim.backend.canvas.Canvas; import org.oscim.backend.canvas.Paint; public class AndroidCanvas implements Canvas { - final android.graphics.Canvas canvas; + final android.graphics.Canvas canvas; - public AndroidCanvas() { - canvas = new android.graphics.Canvas(); - } + public AndroidCanvas() { + canvas = new android.graphics.Canvas(); + } - @Override - public void setBitmap(Bitmap bitmap) { - canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap); - } + @Override + public void setBitmap(Bitmap bitmap) { + canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap); + } - @Override - public void drawText(String string, float x, float y, Paint fill, Paint stroke) { - if (string != null) { - if (stroke != null) - canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint); + @Override + public void drawText(String string, float x, float y, Paint fill, Paint stroke) { + if (string != null) { + if (stroke != null) + canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint); - canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint); - } - } + canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint); + } + } - @Override - public void drawBitmap(Bitmap bitmap, float x, float y) { - canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null); + @Override + public void drawBitmap(Bitmap bitmap, float x, float y) { + canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null); - } + } } diff --git a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidGraphics.java b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidGraphics.java index 4941634c..45a15738 100644 --- a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidGraphics.java +++ b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidGraphics.java @@ -17,8 +17,10 @@ */ package org.oscim.android.canvas; -import java.io.IOException; -import java.io.InputStream; +import android.content.res.Resources; +import android.graphics.Bitmap.Config; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Bitmap; @@ -27,99 +29,97 @@ import org.oscim.backend.canvas.Paint; import org.oscim.layers.marker.MarkerItem.HotspotPlace; import org.oscim.layers.marker.MarkerSymbol; -import android.content.res.Resources; -import android.graphics.Bitmap.Config; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; +import java.io.IOException; +import java.io.InputStream; public final class AndroidGraphics extends CanvasAdapter { - public static void init() { - CanvasAdapter.init(new AndroidGraphics()); - } + public static void init() { + CanvasAdapter.init(new AndroidGraphics()); + } - public static android.graphics.Paint getAndroidPaint(Paint paint) { - return ((AndroidPaint) paint).mPaint; - } + public static android.graphics.Paint getAndroidPaint(Paint paint) { + return ((AndroidPaint) paint).mPaint; + } - public static android.graphics.Bitmap getBitmap(Bitmap bitmap) { - return ((AndroidBitmap) bitmap).mBitmap; - } + public static android.graphics.Bitmap getBitmap(Bitmap bitmap) { + return ((AndroidBitmap) bitmap).mBitmap; + } - private AndroidGraphics() { - // do nothing - } + private AndroidGraphics() { + // do nothing + } - @Override - public Bitmap decodeBitmapImpl(InputStream inputStream) { - return new AndroidBitmap(inputStream); - } + @Override + public Bitmap decodeBitmapImpl(InputStream inputStream) { + return new AndroidBitmap(inputStream); + } - @Override - public Bitmap loadBitmapAssetImpl(String fileName) { - try { - return createBitmap(fileName); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + @Override + public Bitmap loadBitmapAssetImpl(String fileName) { + try { + return createBitmap(fileName); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } - @Override - public Paint newPaintImpl() { - return new AndroidPaint(); - } + @Override + public Paint newPaintImpl() { + return new AndroidPaint(); + } - @Override - public Bitmap newBitmapImpl(int width, int height, int format) { - return new AndroidBitmap(width, height, format); - } + @Override + public Bitmap newBitmapImpl(int width, int height, int format) { + return new AndroidBitmap(width, height, format); + } - @Override - public Canvas newCanvasImpl() { - return new AndroidCanvas(); - } + @Override + public Canvas newCanvasImpl() { + return new AndroidCanvas(); + } - //------------------------------------- - public static Bitmap drawableToBitmap(Drawable drawable) { - if (drawable instanceof BitmapDrawable) { - return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap()); - } + //------------------------------------- + public static Bitmap drawableToBitmap(Drawable drawable) { + if (drawable instanceof BitmapDrawable) { + return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap()); + } - android.graphics.Bitmap bitmap = android.graphics.Bitmap - .createBitmap(drawable.getIntrinsicWidth(), - drawable.getIntrinsicHeight(), - Config.ARGB_8888); + android.graphics.Bitmap bitmap = android.graphics.Bitmap + .createBitmap(drawable.getIntrinsicWidth(), + drawable.getIntrinsicHeight(), + Config.ARGB_8888); - android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); + android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); + drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); + drawable.draw(canvas); - return new AndroidBitmap(bitmap); - } + return new AndroidBitmap(bitmap); + } - public static Bitmap drawableToBitmap(Resources res, int resId) { - return new AndroidBitmap(res.openRawResource(resId)); - } + public static Bitmap drawableToBitmap(Resources res, int resId) { + return new AndroidBitmap(res.openRawResource(resId)); + } - /** - * @deprecated - */ - public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) { - if (place == null) - place = HotspotPlace.CENTER; + /** + * @deprecated + */ + public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) { + if (place == null) + place = HotspotPlace.CENTER; - return new MarkerSymbol(drawableToBitmap(drawable), place); - } + return new MarkerSymbol(drawableToBitmap(drawable), place); + } - /** - * @deprecated - */ - public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) { - if (place == null) - place = HotspotPlace.CENTER; + /** + * @deprecated + */ + public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) { + if (place == null) + place = HotspotPlace.CENTER; - InputStream in = res.openRawResource(resId); - return new MarkerSymbol(new AndroidBitmap(in), place); - } + InputStream in = res.openRawResource(resId); + return new MarkerSymbol(new AndroidBitmap(in), place); + } } diff --git a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidPaint.java b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidPaint.java index e63e9aeb..e574328e 100644 --- a/vtm-android-gdx/src/org/oscim/android/canvas/AndroidPaint.java +++ b/vtm-android-gdx/src/org/oscim/android/canvas/AndroidPaint.java @@ -16,110 +16,110 @@ */ package org.oscim.android.canvas; -import org.oscim.backend.canvas.Paint; - import android.graphics.Paint.FontMetrics; import android.graphics.Typeface; +import org.oscim.backend.canvas.Paint; + class AndroidPaint implements Paint { - private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) { - switch (fontStyle) { - case BOLD: - return 1; - case BOLD_ITALIC: - return 3; - case ITALIC: - return 2; - case NORMAL: - return 0; - } + private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) { + switch (fontStyle) { + case BOLD: + return 1; + case BOLD_ITALIC: + return 3; + case ITALIC: + return 2; + case NORMAL: + return 0; + } - throw new IllegalArgumentException("unknown font style: " + fontStyle); - } + throw new IllegalArgumentException("unknown font style: " + fontStyle); + } - private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) { - switch (fontFamily) { - case DEFAULT: - return Typeface.DEFAULT; - case DEFAULT_BOLD: - return Typeface.DEFAULT_BOLD; - case MONOSPACE: - return Typeface.MONOSPACE; - case SANS_SERIF: - return Typeface.SANS_SERIF; - case SERIF: - return Typeface.SERIF; - } + private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) { + switch (fontFamily) { + case DEFAULT: + return Typeface.DEFAULT; + case DEFAULT_BOLD: + return Typeface.DEFAULT_BOLD; + case MONOSPACE: + return Typeface.MONOSPACE; + case SANS_SERIF: + return Typeface.SANS_SERIF; + case SERIF: + return Typeface.SERIF; + } - throw new IllegalArgumentException("unknown font family: " + fontFamily); - } + throw new IllegalArgumentException("unknown font family: " + fontFamily); + } - final android.graphics.Paint mPaint; + final android.graphics.Paint mPaint; - AndroidPaint() { - mPaint = new android.graphics.Paint( - android.graphics.Paint.ANTI_ALIAS_FLAG); - } + AndroidPaint() { + mPaint = new android.graphics.Paint( + android.graphics.Paint.ANTI_ALIAS_FLAG); + } - @Override - public int getColor() { - return mPaint.getColor(); - } + @Override + public int getColor() { + return mPaint.getColor(); + } - @Override - public void setColor(int color) { - mPaint.setColor(color); - } + @Override + public void setColor(int color) { + mPaint.setColor(color); + } - @Override - public void setStrokeCap(Cap cap) { - android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap - .valueOf(cap.name()); - mPaint.setStrokeCap(androidCap); - } + @Override + public void setStrokeCap(Cap cap) { + android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap + .valueOf(cap.name()); + mPaint.setStrokeCap(androidCap); + } - @Override - public void setStrokeWidth(float width) { - mPaint.setStrokeWidth(width); - } + @Override + public void setStrokeWidth(float width) { + mPaint.setStrokeWidth(width); + } - @Override - public void setStyle(Style style) { - mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name())); - } + @Override + public void setStyle(Style style) { + mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name())); + } - @Override - public void setTextAlign(Align align) { - //mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name())); - } + @Override + public void setTextAlign(Align align) { + //mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name())); + } - @Override - public void setTextSize(float textSize) { - mPaint.setTextSize(textSize); - } + @Override + public void setTextSize(float textSize) { + mPaint.setTextSize(textSize); + } - @Override - public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { - Typeface typeface = Typeface.create(getTypeface(fontFamily), - getStyle(fontStyle)); - mPaint.setTypeface(typeface); - } + @Override + public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { + Typeface typeface = Typeface.create(getTypeface(fontFamily), + getStyle(fontStyle)); + mPaint.setTypeface(typeface); + } - @Override - public float measureText(String text) { - return mPaint.measureText(text); - } + @Override + public float measureText(String text) { + return mPaint.measureText(text); + } - @Override - public float getFontHeight() { - FontMetrics fm = mPaint.getFontMetrics(); - return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); - } + @Override + public float getFontHeight() { + FontMetrics fm = mPaint.getFontMetrics(); + return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); + } - @Override - public float getFontDescent() { - FontMetrics fm = mPaint.getFontMetrics(); - // //fontDescent = (float) Math.ceil(Math.abs(fm.descent)); - return Math.abs(fm.bottom); - } + @Override + public float getFontDescent() { + FontMetrics fm = mPaint.getFontMetrics(); + // //fontDescent = (float) Math.ceil(Math.abs(fm.descent)); + return Math.abs(fm.bottom); + } } diff --git a/vtm-android-gdx/src/org/oscim/gdx/AndroidGL.java b/vtm-android-gdx/src/org/oscim/gdx/AndroidGL.java index 695878f7..ff7c0070 100644 --- a/vtm-android-gdx/src/org/oscim/gdx/AndroidGL.java +++ b/vtm-android-gdx/src/org/oscim/gdx/AndroidGL.java @@ -16,835 +16,835 @@ */ package org.oscim.gdx; +import android.annotation.SuppressLint; +import android.opengl.GLES20; + +import org.oscim.backend.GL; + import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; -import org.oscim.backend.GL; - -import android.annotation.SuppressLint; -import android.opengl.GLES20; - @SuppressLint("NewApi") public class AndroidGL implements GL { - @Override - public void attachShader(int program, int shader) { - GLES20.glAttachShader(program, shader); - } - - @Override - public void bindAttribLocation(int program, int index, String name) { - GLES20.glBindAttribLocation(program, index, name); - } - - @Override - public void bindBuffer(int target, int buffer) { - GLES20.glBindBuffer(target, buffer); - } - - @Override - public void bindFramebuffer(int target, int framebuffer) { - GLES20.glBindFramebuffer(target, framebuffer); - } - - @Override - public void bindRenderbuffer(int target, int renderbuffer) { - GLES20.glBindRenderbuffer(target, renderbuffer); - } - - @Override - public void blendColor(float red, float green, float blue, float alpha) { - GLES20.glBlendColor(red, green, blue, alpha); - } - - @Override - public void blendEquation(int mode) { - GLES20.glBlendEquation(mode); - } - - @Override - public void blendEquationSeparate(int modeRGB, int modeAlpha) { - GLES20.glBlendEquationSeparate(modeRGB, modeAlpha); - } - - @Override - public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { - GLES20.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); - } - - @Override - public void bufferData(int target, int size, Buffer data, int usage) { - GLES20.glBufferData(target, size, data, usage); - } - - @Override - public void bufferSubData(int target, int offset, int size, Buffer data) { - GLES20.glBufferSubData(target, offset, size, data); - } - - @Override - public int checkFramebufferStatus(int target) { - return GLES20.glCheckFramebufferStatus(target); - } - - @Override - public void compileShader(int shader) { - GLES20.glCompileShader(shader); - } - - @Override - public int createProgram() { - return GLES20.glCreateProgram(); - } - - @Override - public int createShader(int type) { - return GLES20.glCreateShader(type); - } - - @Override - public void deleteBuffers(int n, IntBuffer buffers) { - GLES20.glDeleteBuffers(n, buffers); - } - - @Override - public void deleteFramebuffers(int n, IntBuffer framebuffers) { - GLES20.glDeleteFramebuffers(n, framebuffers); - } - - @Override - public void deleteProgram(int program) { - GLES20.glDeleteProgram(program); - } - - @Override - public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { - GLES20.glDeleteRenderbuffers(n, renderbuffers); - } - - @Override - public void deleteShader(int shader) { - GLES20.glDeleteShader(shader); - } - - @Override - public void detachShader(int program, int shader) { - GLES20.glDetachShader(program, shader); - } - - @Override - public void disableVertexAttribArray(int index) { - GLES20.glDisableVertexAttribArray(index); - } - - @Override - public void drawElements(int mode, int count, int type, int offset) { - GLES20.glDrawElements(mode, count, type, offset); - } - - @Override - public void enableVertexAttribArray(int index) { - GLES20.glEnableVertexAttribArray(index); - } - - @Override - public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, - int renderbuffer) { - GLES20.glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); - } - - @Override - public void framebufferTexture2D(int target, int attachment, int textarget, int texture, - int level) { - GLES20.glFramebufferTexture2D(target, attachment, textarget, texture, level); - } - - @Override - public void genBuffers(int n, IntBuffer buffers) { - GLES20.glGenBuffers(n, buffers); - } - - @Override - public void generateMipmap(int target) { - GLES20.glGenerateMipmap(target); - } - - @Override - public void genFramebuffers(int n, IntBuffer framebuffers) { - GLES20.glGenFramebuffers(n, framebuffers); - } - - @Override - public void genRenderbuffers(int n, IntBuffer renderbuffers) { - GLES20.glGenRenderbuffers(n, renderbuffers); - } - - @Override - public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { - return GLES20.glGetActiveAttrib(program, index, size, (IntBuffer) type); - } - - @Override - public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { - //return GLES20.glGetActiveUniform(program, index, bufsize, length, size, type, name); - throw new UnsupportedOperationException("missing implementation"); - } - - @Override - public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { - throw new UnsupportedOperationException("missing implementation"); - //GLES20.glGetAttachedShaders(program, maxcount, count, shaders); - } - - @Override - public int getAttribLocation(int program, String name) { - return GLES20.glGetAttribLocation(program, name); - } - - @Override - public void getBooleanv(int pname, Buffer params) { - throw new UnsupportedOperationException("missing implementation"); - //GLES20.glGetBooleanv(pname, params); - } - - @Override - public void getBufferParameteriv(int target, int pname, IntBuffer params) { - GLES20.glGetBufferParameteriv(target, pname, params); - - } - - @Override - public void getFloatv(int pname, FloatBuffer params) { - GLES20.glGetFloatv(pname, params); - - } - - @Override - public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, - IntBuffer params) { - GLES20.glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); - } - - @Override - public void getProgramiv(int program, int pname, IntBuffer params) { - GLES20.glGetProgramiv(program, pname, params); - - } - - @Override - public String getProgramInfoLog(int program) { - return GLES20.glGetProgramInfoLog(program); - } - - @Override - public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { - GLES20.glGetRenderbufferParameteriv(target, pname, params); - - } - - @Override - public void getShaderiv(int shader, int pname, IntBuffer params) { - GLES20.glGetShaderiv(shader, pname, params); - - } - - @Override - public String getShaderInfoLog(int shader) { - return GLES20.glGetShaderInfoLog(shader); - } - - @Override - public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, - IntBuffer precision) { - GLES20.glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); - } + @Override + public void attachShader(int program, int shader) { + GLES20.glAttachShader(program, shader); + } + + @Override + public void bindAttribLocation(int program, int index, String name) { + GLES20.glBindAttribLocation(program, index, name); + } + + @Override + public void bindBuffer(int target, int buffer) { + GLES20.glBindBuffer(target, buffer); + } + + @Override + public void bindFramebuffer(int target, int framebuffer) { + GLES20.glBindFramebuffer(target, framebuffer); + } + + @Override + public void bindRenderbuffer(int target, int renderbuffer) { + GLES20.glBindRenderbuffer(target, renderbuffer); + } + + @Override + public void blendColor(float red, float green, float blue, float alpha) { + GLES20.glBlendColor(red, green, blue, alpha); + } + + @Override + public void blendEquation(int mode) { + GLES20.glBlendEquation(mode); + } + + @Override + public void blendEquationSeparate(int modeRGB, int modeAlpha) { + GLES20.glBlendEquationSeparate(modeRGB, modeAlpha); + } + + @Override + public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + GLES20.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + + @Override + public void bufferData(int target, int size, Buffer data, int usage) { + GLES20.glBufferData(target, size, data, usage); + } + + @Override + public void bufferSubData(int target, int offset, int size, Buffer data) { + GLES20.glBufferSubData(target, offset, size, data); + } + + @Override + public int checkFramebufferStatus(int target) { + return GLES20.glCheckFramebufferStatus(target); + } + + @Override + public void compileShader(int shader) { + GLES20.glCompileShader(shader); + } + + @Override + public int createProgram() { + return GLES20.glCreateProgram(); + } + + @Override + public int createShader(int type) { + return GLES20.glCreateShader(type); + } + + @Override + public void deleteBuffers(int n, IntBuffer buffers) { + GLES20.glDeleteBuffers(n, buffers); + } + + @Override + public void deleteFramebuffers(int n, IntBuffer framebuffers) { + GLES20.glDeleteFramebuffers(n, framebuffers); + } + + @Override + public void deleteProgram(int program) { + GLES20.glDeleteProgram(program); + } + + @Override + public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { + GLES20.glDeleteRenderbuffers(n, renderbuffers); + } + + @Override + public void deleteShader(int shader) { + GLES20.glDeleteShader(shader); + } + + @Override + public void detachShader(int program, int shader) { + GLES20.glDetachShader(program, shader); + } + + @Override + public void disableVertexAttribArray(int index) { + GLES20.glDisableVertexAttribArray(index); + } + + @Override + public void drawElements(int mode, int count, int type, int offset) { + GLES20.glDrawElements(mode, count, type, offset); + } + + @Override + public void enableVertexAttribArray(int index) { + GLES20.glEnableVertexAttribArray(index); + } + + @Override + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, + int renderbuffer) { + GLES20.glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + } + + @Override + public void framebufferTexture2D(int target, int attachment, int textarget, int texture, + int level) { + GLES20.glFramebufferTexture2D(target, attachment, textarget, texture, level); + } + + @Override + public void genBuffers(int n, IntBuffer buffers) { + GLES20.glGenBuffers(n, buffers); + } + + @Override + public void generateMipmap(int target) { + GLES20.glGenerateMipmap(target); + } + + @Override + public void genFramebuffers(int n, IntBuffer framebuffers) { + GLES20.glGenFramebuffers(n, framebuffers); + } + + @Override + public void genRenderbuffers(int n, IntBuffer renderbuffers) { + GLES20.glGenRenderbuffers(n, renderbuffers); + } + + @Override + public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { + return GLES20.glGetActiveAttrib(program, index, size, (IntBuffer) type); + } + + @Override + public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { + //return GLES20.glGetActiveUniform(program, index, bufsize, length, size, type, name); + throw new UnsupportedOperationException("missing implementation"); + } + + @Override + public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { + throw new UnsupportedOperationException("missing implementation"); + //GLES20.glGetAttachedShaders(program, maxcount, count, shaders); + } + + @Override + public int getAttribLocation(int program, String name) { + return GLES20.glGetAttribLocation(program, name); + } + + @Override + public void getBooleanv(int pname, Buffer params) { + throw new UnsupportedOperationException("missing implementation"); + //GLES20.glGetBooleanv(pname, params); + } + + @Override + public void getBufferParameteriv(int target, int pname, IntBuffer params) { + GLES20.glGetBufferParameteriv(target, pname, params); + + } + + @Override + public void getFloatv(int pname, FloatBuffer params) { + GLES20.glGetFloatv(pname, params); + + } + + @Override + public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, + IntBuffer params) { + GLES20.glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); + } + + @Override + public void getProgramiv(int program, int pname, IntBuffer params) { + GLES20.glGetProgramiv(program, pname, params); + + } + + @Override + public String getProgramInfoLog(int program) { + return GLES20.glGetProgramInfoLog(program); + } + + @Override + public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { + GLES20.glGetRenderbufferParameteriv(target, pname, params); + + } + + @Override + public void getShaderiv(int shader, int pname, IntBuffer params) { + GLES20.glGetShaderiv(shader, pname, params); + + } + + @Override + public String getShaderInfoLog(int shader) { + return GLES20.glGetShaderInfoLog(shader); + } + + @Override + public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, + IntBuffer precision) { + GLES20.glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); + } - @Override - public void getShaderSource(int shader, int bufsize, Buffer length, String source) { - throw new UnsupportedOperationException("missing implementation"); - } + @Override + public void getShaderSource(int shader, int bufsize, Buffer length, String source) { + throw new UnsupportedOperationException("missing implementation"); + } - @Override - public void getTexParameterfv(int target, int pname, FloatBuffer params) { - GLES20.glGetTexParameterfv(target, pname, params); + @Override + public void getTexParameterfv(int target, int pname, FloatBuffer params) { + GLES20.glGetTexParameterfv(target, pname, params); - } + } - @Override - public void getTexParameteriv(int target, int pname, IntBuffer params) { - GLES20.glGetTexParameteriv(target, pname, params); + @Override + public void getTexParameteriv(int target, int pname, IntBuffer params) { + GLES20.glGetTexParameteriv(target, pname, params); - } + } - @Override - public void getUniformfv(int program, int location, FloatBuffer params) { - GLES20.glGetUniformfv(program, location, params); + @Override + public void getUniformfv(int program, int location, FloatBuffer params) { + GLES20.glGetUniformfv(program, location, params); - } + } - @Override - public void getUniformiv(int program, int location, IntBuffer params) { - GLES20.glGetUniformiv(program, location, params); + @Override + public void getUniformiv(int program, int location, IntBuffer params) { + GLES20.glGetUniformiv(program, location, params); - } + } - @Override - public int getUniformLocation(int program, String name) { - return GLES20.glGetUniformLocation(program, name); - } + @Override + public int getUniformLocation(int program, String name) { + return GLES20.glGetUniformLocation(program, name); + } - @Override - public void getVertexAttribfv(int index, int pname, FloatBuffer params) { - GLES20.glGetVertexAttribfv(index, pname, params); + @Override + public void getVertexAttribfv(int index, int pname, FloatBuffer params) { + GLES20.glGetVertexAttribfv(index, pname, params); - } + } - @Override - public void getVertexAttribiv(int index, int pname, IntBuffer params) { - GLES20.glGetVertexAttribiv(index, pname, params); + @Override + public void getVertexAttribiv(int index, int pname, IntBuffer params) { + GLES20.glGetVertexAttribiv(index, pname, params); - } + } - @Override - public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { - //GLES20.glGetVertexAttribPointerv(index, pname, pointer); - throw new UnsupportedOperationException("missing implementation"); - } + @Override + public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { + //GLES20.glGetVertexAttribPointerv(index, pname, pointer); + throw new UnsupportedOperationException("missing implementation"); + } - @Override - public boolean isBuffer(int buffer) { - return GLES20.glIsBuffer(buffer); - } + @Override + public boolean isBuffer(int buffer) { + return GLES20.glIsBuffer(buffer); + } - @Override - public boolean isEnabled(int cap) { - return GLES20.glIsEnabled(cap); - } + @Override + public boolean isEnabled(int cap) { + return GLES20.glIsEnabled(cap); + } - @Override - public boolean isFramebuffer(int framebuffer) { - return GLES20.glIsFramebuffer(framebuffer); - } + @Override + public boolean isFramebuffer(int framebuffer) { + return GLES20.glIsFramebuffer(framebuffer); + } - @Override - public boolean isProgram(int program) { - return GLES20.glIsProgram(program); - } + @Override + public boolean isProgram(int program) { + return GLES20.glIsProgram(program); + } - @Override - public boolean isRenderbuffer(int renderbuffer) { - return GLES20.glIsRenderbuffer(renderbuffer); - } + @Override + public boolean isRenderbuffer(int renderbuffer) { + return GLES20.glIsRenderbuffer(renderbuffer); + } - @Override - public boolean isShader(int shader) { - return GLES20.glIsShader(shader); - } + @Override + public boolean isShader(int shader) { + return GLES20.glIsShader(shader); + } - @Override - public boolean isTexture(int texture) { - return GLES20.glIsTexture(texture); - } + @Override + public boolean isTexture(int texture) { + return GLES20.glIsTexture(texture); + } - @Override - public void linkProgram(int program) { - GLES20.glLinkProgram(program); + @Override + public void linkProgram(int program) { + GLES20.glLinkProgram(program); - } + } - @Override - public void releaseShaderCompiler() { - GLES20.glReleaseShaderCompiler(); + @Override + public void releaseShaderCompiler() { + GLES20.glReleaseShaderCompiler(); - } + } - @Override - public void renderbufferStorage(int target, int internalformat, int width, int height) { - GLES20.glRenderbufferStorage(target, internalformat, width, height); + @Override + public void renderbufferStorage(int target, int internalformat, int width, int height) { + GLES20.glRenderbufferStorage(target, internalformat, width, height); - } + } - @Override - public void sampleCoverage(float value, boolean invert) { - GLES20.glSampleCoverage(value, invert); + @Override + public void sampleCoverage(float value, boolean invert) { + GLES20.glSampleCoverage(value, invert); - } + } - @Override - public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { - GLES20.glShaderBinary(n, shaders, binaryformat, binary, length); + @Override + public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { + GLES20.glShaderBinary(n, shaders, binaryformat, binary, length); - } + } - @Override - public void shaderSource(int shader, String string) { - GLES20.glShaderSource(shader, string); + @Override + public void shaderSource(int shader, String string) { + GLES20.glShaderSource(shader, string); - } + } - @Override - public void stencilFuncSeparate(int face, int func, int ref, int mask) { - GLES20.glStencilFuncSeparate(face, func, ref, mask); + @Override + public void stencilFuncSeparate(int face, int func, int ref, int mask) { + GLES20.glStencilFuncSeparate(face, func, ref, mask); - } + } - @Override - public void stencilMaskSeparate(int face, int mask) { - GLES20.glStencilMaskSeparate(face, mask); + @Override + public void stencilMaskSeparate(int face, int mask) { + GLES20.glStencilMaskSeparate(face, mask); - } + } - @Override - public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { - GLES20.glStencilOpSeparate(face, fail, zfail, zpass); + @Override + public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { + GLES20.glStencilOpSeparate(face, fail, zfail, zpass); - } + } - @Override - public void texParameterfv(int target, int pname, FloatBuffer params) { - GLES20.glTexParameterfv(target, pname, params); + @Override + public void texParameterfv(int target, int pname, FloatBuffer params) { + GLES20.glTexParameterfv(target, pname, params); - } + } - @Override - public void texParameteri(int target, int pname, int param) { - GLES20.glTexParameteri(target, pname, param); + @Override + public void texParameteri(int target, int pname, int param) { + GLES20.glTexParameteri(target, pname, param); - } + } - @Override - public void texParameteriv(int target, int pname, IntBuffer params) { - GLES20.glTexParameteriv(target, pname, params); + @Override + public void texParameteriv(int target, int pname, IntBuffer params) { + GLES20.glTexParameteriv(target, pname, params); - } + } - @Override - public void uniform1f(int location, float x) { - GLES20.glUniform1f(location, x); + @Override + public void uniform1f(int location, float x) { + GLES20.glUniform1f(location, x); - } + } - @Override - public void uniform1fv(int location, int count, FloatBuffer v) { - GLES20.glUniform1fv(location, count, v); + @Override + public void uniform1fv(int location, int count, FloatBuffer v) { + GLES20.glUniform1fv(location, count, v); - } + } - @Override - public void uniform1i(int location, int x) { - GLES20.glUniform1i(location, x); + @Override + public void uniform1i(int location, int x) { + GLES20.glUniform1i(location, x); - } + } - @Override - public void uniform1iv(int location, int count, IntBuffer v) { - GLES20.glUniform1iv(location, count, v); + @Override + public void uniform1iv(int location, int count, IntBuffer v) { + GLES20.glUniform1iv(location, count, v); - } + } - @Override - public void uniform2f(int location, float x, float y) { - GLES20.glUniform2f(location, x, y); + @Override + public void uniform2f(int location, float x, float y) { + GLES20.glUniform2f(location, x, y); - } + } - @Override - public void uniform2fv(int location, int count, FloatBuffer v) { - GLES20.glUniform2fv(location, count, v); + @Override + public void uniform2fv(int location, int count, FloatBuffer v) { + GLES20.glUniform2fv(location, count, v); - } + } - @Override - public void uniform2i(int location, int x, int y) { - GLES20.glUniform2i(location, x, y); + @Override + public void uniform2i(int location, int x, int y) { + GLES20.glUniform2i(location, x, y); - } + } - @Override - public void uniform2iv(int location, int count, IntBuffer v) { - GLES20.glUniform2iv(location, count, v); + @Override + public void uniform2iv(int location, int count, IntBuffer v) { + GLES20.glUniform2iv(location, count, v); - } + } - @Override - public void uniform3f(int location, float x, float y, float z) { - GLES20.glUniform3f(location, x, y, z); + @Override + public void uniform3f(int location, float x, float y, float z) { + GLES20.glUniform3f(location, x, y, z); - } + } - @Override - public void uniform3fv(int location, int count, FloatBuffer v) { - GLES20.glUniform3fv(location, count, v); + @Override + public void uniform3fv(int location, int count, FloatBuffer v) { + GLES20.glUniform3fv(location, count, v); - } + } - @Override - public void uniform3i(int location, int x, int y, int z) { - GLES20.glUniform3i(location, x, y, z); + @Override + public void uniform3i(int location, int x, int y, int z) { + GLES20.glUniform3i(location, x, y, z); - } + } - @Override - public void uniform3iv(int location, int count, IntBuffer v) { - GLES20.glUniform3iv(location, count, v); + @Override + public void uniform3iv(int location, int count, IntBuffer v) { + GLES20.glUniform3iv(location, count, v); - } + } - @Override - public void uniform4f(int location, float x, float y, float z, float w) { - GLES20.glUniform4f(location, x, y, z, w); - } + @Override + public void uniform4f(int location, float x, float y, float z, float w) { + GLES20.glUniform4f(location, x, y, z, w); + } - @Override - public void uniform4fv(int location, int count, FloatBuffer v) { - GLES20.glUniform4fv(location, count, v); - } + @Override + public void uniform4fv(int location, int count, FloatBuffer v) { + GLES20.glUniform4fv(location, count, v); + } - @Override - public void uniform4i(int location, int x, int y, int z, int w) { - GLES20.glUniform4i(location, x, y, z, w); + @Override + public void uniform4i(int location, int x, int y, int z, int w) { + GLES20.glUniform4i(location, x, y, z, w); - } + } - @Override - public void uniform4iv(int location, int count, IntBuffer v) { - GLES20.glUniform4iv(location, count, v); + @Override + public void uniform4iv(int location, int count, IntBuffer v) { + GLES20.glUniform4iv(location, count, v); - } + } - @Override - public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { - GLES20.glUniformMatrix2fv(location, count, transpose, value); + @Override + public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { + GLES20.glUniformMatrix2fv(location, count, transpose, value); - } + } - @Override - public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { - GLES20.glUniformMatrix3fv(location, count, transpose, value); + @Override + public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { + GLES20.glUniformMatrix3fv(location, count, transpose, value); - } + } - @Override - public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { - GLES20.glUniformMatrix4fv(location, count, transpose, value); + @Override + public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { + GLES20.glUniformMatrix4fv(location, count, transpose, value); - } + } - @Override - public void useProgram(int program) { - GLES20.glUseProgram(program); + @Override + public void useProgram(int program) { + GLES20.glUseProgram(program); - } + } - @Override - public void validateProgram(int program) { - GLES20.glValidateProgram(program); + @Override + public void validateProgram(int program) { + GLES20.glValidateProgram(program); - } + } - @Override - public void vertexAttrib1f(int indx, float x) { - GLES20.glVertexAttrib1f(indx, x); + @Override + public void vertexAttrib1f(int indx, float x) { + GLES20.glVertexAttrib1f(indx, x); - } + } - @Override - public void vertexAttrib1fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib1fv(indx, values); + @Override + public void vertexAttrib1fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib1fv(indx, values); - } + } - @Override - public void vertexAttrib2f(int indx, float x, float y) { - GLES20.glVertexAttrib2f(indx, x, y); + @Override + public void vertexAttrib2f(int indx, float x, float y) { + GLES20.glVertexAttrib2f(indx, x, y); - } + } - @Override - public void vertexAttrib2fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib2fv(indx, values); + @Override + public void vertexAttrib2fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib2fv(indx, values); - } + } - @Override - public void vertexAttrib3f(int indx, float x, float y, float z) { - GLES20.glVertexAttrib3f(indx, x, y, z); + @Override + public void vertexAttrib3f(int indx, float x, float y, float z) { + GLES20.glVertexAttrib3f(indx, x, y, z); - } + } - @Override - public void vertexAttrib3fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib3fv(indx, values); + @Override + public void vertexAttrib3fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib3fv(indx, values); - } + } - @Override - public void vertexAttrib4f(int indx, float x, float y, float z, float w) { - GLES20.glVertexAttrib4f(indx, x, y, z, w); + @Override + public void vertexAttrib4f(int indx, float x, float y, float z, float w) { + GLES20.glVertexAttrib4f(indx, x, y, z, w); - } + } - @Override - public void vertexAttrib4fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib4fv(indx, values); + @Override + public void vertexAttrib4fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib4fv(indx, values); - } + } - @Override - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - Buffer ptr) { - GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); - } + @Override + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + Buffer ptr) { + GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); + } - @Override - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - int offset) { - // FIXME check implementation! - GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, offset); - //throw new UnsupportedOperationException("missing implementation"); - } + @Override + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + int offset) { + // FIXME check implementation! + GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, offset); + //throw new UnsupportedOperationException("missing implementation"); + } - @Override - public void activeTexture(int texture) { - GLES20.glActiveTexture(texture); + @Override + public void activeTexture(int texture) { + GLES20.glActiveTexture(texture); - } + } - @Override - public void bindTexture(int target, int texture) { - GLES20.glBindTexture(target, texture); + @Override + public void bindTexture(int target, int texture) { + GLES20.glBindTexture(target, texture); - } + } - @Override - public void blendFunc(int sfactor, int dfactor) { - GLES20.glBlendFunc(sfactor, dfactor); + @Override + public void blendFunc(int sfactor, int dfactor) { + GLES20.glBlendFunc(sfactor, dfactor); - } + } - @Override - public void clear(int mask) { - GLES20.glClear(mask); + @Override + public void clear(int mask) { + GLES20.glClear(mask); - } + } - @Override - public void clearColor(float red, float green, float blue, float alpha) { - GLES20.glClearColor(red, green, blue, alpha); + @Override + public void clearColor(float red, float green, float blue, float alpha) { + GLES20.glClearColor(red, green, blue, alpha); - } + } - @Override - public void clearDepthf(float depth) { - GLES20.glClearDepthf(depth); + @Override + public void clearDepthf(float depth) { + GLES20.glClearDepthf(depth); - } + } - @Override - public void clearStencil(int s) { - GLES20.glClearStencil(s); + @Override + public void clearStencil(int s) { + GLES20.glClearStencil(s); - } + } - @Override - public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - GLES20.glColorMask(red, green, blue, alpha); + @Override + public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + GLES20.glColorMask(red, green, blue, alpha); - } + } - @Override - public void compressedTexImage2D(int target, int level, int internalformat, int width, - int height, int border, int imageSize, Buffer data) { - throw new UnsupportedOperationException("missing implementation"); + @Override + public void compressedTexImage2D(int target, int level, int internalformat, int width, + int height, int border, int imageSize, Buffer data) { + throw new UnsupportedOperationException("missing implementation"); - } + } - @Override - public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, - int width, int height, int format, int imageSize, Buffer data) { - throw new UnsupportedOperationException("missing implementation"); + @Override + public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, + int width, int height, int format, int imageSize, Buffer data) { + throw new UnsupportedOperationException("missing implementation"); - } + } - @Override - public void copyTexImage2D(int target, int level, int internalformat, int x, int y, - int width, int height, int border) { - GLES20.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); - } + @Override + public void copyTexImage2D(int target, int level, int internalformat, int x, int y, + int width, int height, int border) { + GLES20.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + } - @Override - public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, - int width, int height) { - GLES20.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); - } + @Override + public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, + int width, int height) { + GLES20.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + } - @Override - public void cullFace(int mode) { - GLES20.glCullFace(mode); + @Override + public void cullFace(int mode) { + GLES20.glCullFace(mode); - } + } - @Override - public void deleteTextures(int n, IntBuffer textures) { - GLES20.glDeleteTextures(n, textures); + @Override + public void deleteTextures(int n, IntBuffer textures) { + GLES20.glDeleteTextures(n, textures); - } + } - @Override - public void depthFunc(int func) { - GLES20.glDepthFunc(func); + @Override + public void depthFunc(int func) { + GLES20.glDepthFunc(func); - } + } - @Override - public void depthMask(boolean flag) { - GLES20.glDepthMask(flag); + @Override + public void depthMask(boolean flag) { + GLES20.glDepthMask(flag); - } + } - @Override - public void depthRangef(float zNear, float zFar) { - GLES20.glDepthRangef(zNear, zFar); + @Override + public void depthRangef(float zNear, float zFar) { + GLES20.glDepthRangef(zNear, zFar); - } + } - @Override - public void disable(int cap) { - GLES20.glDisable(cap); + @Override + public void disable(int cap) { + GLES20.glDisable(cap); - } + } - @Override - public void drawArrays(int mode, int first, int count) { - GLES20.glDrawArrays(mode, first, count); + @Override + public void drawArrays(int mode, int first, int count) { + GLES20.glDrawArrays(mode, first, count); - } + } - @Override - public void drawElements(int mode, int count, int type, Buffer indices) { - GLES20.glDrawElements(mode, count, type, indices); + @Override + public void drawElements(int mode, int count, int type, Buffer indices) { + GLES20.glDrawElements(mode, count, type, indices); - } + } - @Override - public void enable(int cap) { - GLES20.glEnable(cap); + @Override + public void enable(int cap) { + GLES20.glEnable(cap); - } + } - @Override - public void finish() { - GLES20.glFinish(); + @Override + public void finish() { + GLES20.glFinish(); - } + } - @Override - public void flush() { - GLES20.glFlush(); + @Override + public void flush() { + GLES20.glFlush(); - } + } - @Override - public void frontFace(int mode) { - GLES20.glFrontFace(mode); + @Override + public void frontFace(int mode) { + GLES20.glFrontFace(mode); - } + } - @Override - public void genTextures(int n, IntBuffer textures) { - GLES20.glGenTextures(n, textures); + @Override + public void genTextures(int n, IntBuffer textures) { + GLES20.glGenTextures(n, textures); - } + } - @Override - public int getError() { - return GLES20.glGetError(); - } + @Override + public int getError() { + return GLES20.glGetError(); + } - @Override - public void getIntegerv(int pname, IntBuffer params) { - GLES20.glGetIntegerv(pname, params); + @Override + public void getIntegerv(int pname, IntBuffer params) { + GLES20.glGetIntegerv(pname, params); - } + } - @Override - public String getString(int name) { - return GLES20.glGetString(name); - } + @Override + public String getString(int name) { + return GLES20.glGetString(name); + } - @Override - public void hint(int target, int mode) { - GLES20.glHint(target, mode); - } + @Override + public void hint(int target, int mode) { + GLES20.glHint(target, mode); + } - @Override - public void lineWidth(float width) { - GLES20.glLineWidth(width); + @Override + public void lineWidth(float width) { + GLES20.glLineWidth(width); - } + } - @Override - public void pixelStorei(int pname, int param) { - GLES20.glPixelStorei(pname, param); + @Override + public void pixelStorei(int pname, int param) { + GLES20.glPixelStorei(pname, param); - } + } - @Override - public void polygonOffset(float factor, float units) { - GLES20.glPolygonOffset(factor, units); + @Override + public void polygonOffset(float factor, float units) { + GLES20.glPolygonOffset(factor, units); - } + } - @Override - public void readPixels(int x, int y, int width, int height, int format, int type, - Buffer pixels) { - GLES20.glReadPixels(x, y, width, height, format, type, pixels); - } + @Override + public void readPixels(int x, int y, int width, int height, int format, int type, + Buffer pixels) { + GLES20.glReadPixels(x, y, width, height, format, type, pixels); + } - @Override - public void scissor(int x, int y, int width, int height) { - GLES20.glScissor(x, y, width, height); - } + @Override + public void scissor(int x, int y, int width, int height) { + GLES20.glScissor(x, y, width, height); + } - @Override - public void stencilFunc(int func, int ref, int mask) { - GLES20.glStencilFunc(func, ref, mask); - } + @Override + public void stencilFunc(int func, int ref, int mask) { + GLES20.glStencilFunc(func, ref, mask); + } - @Override - public void stencilMask(int mask) { - GLES20.glStencilMask(mask); - } + @Override + public void stencilMask(int mask) { + GLES20.glStencilMask(mask); + } - @Override - public void stencilOp(int fail, int zfail, int zpass) { - GLES20.glStencilOp(fail, zfail, zpass); - } + @Override + public void stencilOp(int fail, int zfail, int zpass) { + GLES20.glStencilOp(fail, zfail, zpass); + } - @Override - public void texImage2D(int target, int level, int internalformat, int width, int height, - int border, int format, int type, Buffer pixels) { - GLES20.glTexImage2D(target, level, internalformat, width, height, border, format, type, - pixels); - } + @Override + public void texImage2D(int target, int level, int internalformat, int width, int height, + int border, int format, int type, Buffer pixels) { + GLES20.glTexImage2D(target, level, internalformat, width, height, border, format, type, + pixels); + } - @Override - public void texParameterf(int target, int pname, float param) { - GLES20.glTexParameterf(target, pname, param); - } + @Override + public void texParameterf(int target, int pname, float param) { + GLES20.glTexParameterf(target, pname, param); + } - @Override - public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, - int height, int format, int type, Buffer pixels) { - GLES20 - .glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + @Override + public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, + int height, int format, int type, Buffer pixels) { + GLES20 + .glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); - } + } - @Override - public void viewport(int x, int y, int width, int height) { - GLES20.glViewport(x, y, width, height); - } + @Override + public void viewport(int x, int y, int width, int height) { + GLES20.glViewport(x, y, width, height); + } } diff --git a/vtm-android-gdx/src/org/oscim/gdx/MainActivity.java b/vtm-android-gdx/src/org/oscim/gdx/MainActivity.java index 06c3df90..0c43e18c 100644 --- a/vtm-android-gdx/src/org/oscim/gdx/MainActivity.java +++ b/vtm-android-gdx/src/org/oscim/gdx/MainActivity.java @@ -17,42 +17,42 @@ */ package org.oscim.gdx; -import org.oscim.android.canvas.AndroidGraphics; -import org.oscim.backend.GLAdapter; -import org.oscim.core.Tile; -import org.oscim.tiling.TileSource; -import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; - import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.utils.SharedLibraryLoader; +import org.oscim.android.canvas.AndroidGraphics; +import org.oscim.backend.GLAdapter; +import org.oscim.core.Tile; +import org.oscim.tiling.TileSource; +import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; + public class MainActivity extends AndroidApplication { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - AndroidGraphics.init(); - GdxAssets.init(""); - GLAdapter.init(new AndroidGL()); - Tile.SIZE = 400; + AndroidGraphics.init(); + GdxAssets.init(""); + GLAdapter.init(new AndroidGL()); + Tile.SIZE = 400; - AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); - cfg.stencil = 8; + AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); + cfg.stencil = 8; - new SharedLibraryLoader().load("vtm-jni"); + new SharedLibraryLoader().load("vtm-jni"); - initialize(new GdxMapAndroid(), cfg); - } + initialize(new GdxMapAndroid(), cfg); + } - class GdxMapAndroid extends GdxMap { - @Override - public void createLayers() { - TileSource ts = new OSciMap4TileSource(); - initDefaultLayers(ts, true, true, true); - } - } + class GdxMapAndroid extends GdxMap { + @Override + public void createLayers() { + TileSource ts = new OSciMap4TileSource(); + initDefaultLayers(ts, true, true, true); + } + } } diff --git a/vtm-android-start/AndroidManifest.xml b/vtm-android-start/AndroidManifest.xml index 9797dc87..d6fce553 100644 --- a/vtm-android-start/AndroidManifest.xml +++ b/vtm-android-start/AndroidManifest.xml @@ -1,31 +1,31 @@ + package="org.oscim.android.start" + android:versionCode="1" + android:versionName="1.0"> - - - - - + + + - - - - + - - - - + + + + + + + + + diff --git a/vtm-android-start/project.properties b/vtm-android-start/project.properties index 2caff39d..916037e3 100644 --- a/vtm-android-start/project.properties +++ b/vtm-android-start/project.properties @@ -11,6 +11,4 @@ #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. -target=android-21 -android.library.reference.1=../appcompat -android.library.reference.2=../vtm-android +target=android-23 diff --git a/vtm-android-start/res/layout/activity_map.xml b/vtm-android-start/res/layout/activity_map.xml index 126d28a3..25bbde53 100644 --- a/vtm-android-start/res/layout/activity_map.xml +++ b/vtm-android-start/res/layout/activity_map.xml @@ -1,12 +1,10 @@ + android:layout_height="match_parent"> - + android:layout_height="fill_parent"> \ No newline at end of file diff --git a/vtm-android-start/src/org/oscim/android/start/TestActivity.java b/vtm-android-start/src/org/oscim/android/start/TestActivity.java index 7620e785..1f7bd2cb 100644 --- a/vtm-android-start/src/org/oscim/android/start/TestActivity.java +++ b/vtm-android-start/src/org/oscim/android/start/TestActivity.java @@ -1,5 +1,8 @@ package org.oscim.android.start; +import android.os.Bundle; +import android.support.v7.app.ActionBarActivity; + import org.oscim.android.MapPreferences; import org.oscim.android.MapView; import org.oscim.layers.tile.buildings.BuildingLayer; @@ -11,42 +14,39 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; - public class TestActivity extends ActionBarActivity { - public static final Logger log = LoggerFactory.getLogger(TestActivity.class); - MapView mMapView; - MapPreferences mPrefs; + public static final Logger log = LoggerFactory.getLogger(TestActivity.class); + MapView mMapView; + MapPreferences mPrefs; - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_map); + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_map); - mMapView = (MapView) findViewById(R.id.mapView); - Map map = mMapView.map(); - mPrefs = new MapPreferences(TestActivity.class.getName(), this); + mMapView = (MapView) findViewById(R.id.mapView); + Map map = mMapView.map(); + mPrefs = new MapPreferences(TestActivity.class.getName(), this); - VectorTileLayer baseLayer = map.setBaseMap(new OSciMap4TileSource()); - map.layers().add(new BuildingLayer(map, baseLayer)); - map.layers().add(new LabelLayer(map, baseLayer)); - map.setTheme(VtmThemes.DEFAULT); - } + VectorTileLayer baseLayer = map.setBaseMap(new OSciMap4TileSource()); + map.layers().add(new BuildingLayer(map, baseLayer)); + map.layers().add(new LabelLayer(map, baseLayer)); + map.setTheme(VtmThemes.DEFAULT); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); - mPrefs.load(mMapView.map()); - mMapView.onResume(); - } + mPrefs.load(mMapView.map()); + mMapView.onResume(); + } - @Override - protected void onPause() { - super.onPause(); + @Override + protected void onPause() { + super.onPause(); - mMapView.onPause(); - mPrefs.save(mMapView.map()); - } + mMapView.onPause(); + mPrefs.save(mMapView.map()); + } } diff --git a/vtm-android/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch b/vtm-android/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch deleted file mode 100644 index 61c174a5..00000000 --- a/vtm-android/.externalToolBuilders/org.eclipse.cdt.managedbuilder.core.genmakebuilder.launch +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/vtm-android/AndroidManifest.xml b/vtm-android/AndroidManifest.xml index f3787664..c6c0ff91 100644 --- a/vtm-android/AndroidManifest.xml +++ b/vtm-android/AndroidManifest.xml @@ -6,4 +6,4 @@ android:minSdkVersion="10" android:targetSdkVersion="22" /> - \ No newline at end of file + diff --git a/vtm-android/ant.properties b/vtm-android/ant.properties deleted file mode 100644 index 0fb6c493..00000000 --- a/vtm-android/ant.properties +++ /dev/null @@ -1,18 +0,0 @@ -# This file is used to override default values used by the Ant build system. -# -# This file must be checked in Version Control Systems, as it is -# integral to the build system of your project. - -# This file is only used by the Ant script. - -# You can use this to override default values such as -# 'source.dir' for the location of your java source folder and -# 'out.dir' for the location of your output folder. - -# You can also use it define how the release builds are signed by declaring -# the following properties: -# 'key.store' for the location of your keystore and -# 'key.alias' for the name of the key to use. -# The password will be asked during the build when you use the 'release' target. - -#jar.libs.dir= diff --git a/vtm-android/build.xml b/vtm-android/build.xml deleted file mode 100644 index 97be5348..00000000 --- a/vtm-android/build.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vtm-android/lint.xml b/vtm-android/lint.xml deleted file mode 100644 index 8a7b1fac..00000000 --- a/vtm-android/lint.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/vtm-android/proguard.cfg b/vtm-android/proguard.cfg deleted file mode 100644 index a10bf7ac..00000000 --- a/vtm-android/proguard.cfg +++ /dev/null @@ -1,44 +0,0 @@ --optimizationpasses 5 --dontusemixedcaseclassnames --dontskipnonpubliclibraryclasses --dontskipnonpubliclibraryclassmembers --dontpreverify --verbose --libraryjars lib/postgresql-9.0-801.jdbc4.jar --ignorewarnings - --optimizations !code/simplification/arithmetic,!field/*,!class/merging/* - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference --keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native ; -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet); -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet, int); -} - --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} diff --git a/vtm-android/project.properties b/vtm-android/project.properties index 4de101e8..916037e3 100644 --- a/vtm-android/project.properties +++ b/vtm-android/project.properties @@ -3,15 +3,12 @@ # # This file must be checked in Version Control Systems. # -# To customize properties used by the Ant build system use, +# To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt -# Indicates whether an apk should be generated for each density. -split.density=false # Project target. -target=android-21 - -#proguard.config=proguard.cfg -android.library=true -android.library.reference.1=../appcompat +target=android-23 diff --git a/vtm-android/src/org/oscim/android/AndroidAssets.java b/vtm-android/src/org/oscim/android/AndroidAssets.java index 4d1b44a4..f6763a4e 100644 --- a/vtm-android/src/org/oscim/android/AndroidAssets.java +++ b/vtm-android/src/org/oscim/android/AndroidAssets.java @@ -16,31 +16,31 @@ */ package org.oscim.android; -import java.io.IOException; -import java.io.InputStream; +import android.content.Context; import org.oscim.backend.AssetAdapter; -import android.content.Context; +import java.io.IOException; +import java.io.InputStream; public class AndroidAssets extends AssetAdapter { - Context mContext; + Context mContext; - public static void init(Context ctx) { - AssetAdapter.init(new AndroidAssets(ctx)); - } + public static void init(Context ctx) { + AssetAdapter.init(new AndroidAssets(ctx)); + } - private AndroidAssets(Context ctx) { - mContext = ctx; - } + private AndroidAssets(Context ctx) { + mContext = ctx; + } - @Override - public InputStream openFileAsStream(String fileName) { - try { - return mContext.getAssets().open(fileName); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } + @Override + public InputStream openFileAsStream(String fileName) { + try { + return mContext.getAssets().open(fileName); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } } diff --git a/vtm-android/src/org/oscim/android/Compass.java b/vtm-android/src/org/oscim/android/Compass.java index 14f1ed36..c15e4c7f 100644 --- a/vtm-android/src/org/oscim/android/Compass.java +++ b/vtm-android/src/org/oscim/android/Compass.java @@ -16,56 +16,56 @@ */ package org.oscim.android; -import org.oscim.map.Map; - import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; +import org.oscim.map.Map; + public class Compass { - private final SensorEventListener mListener = new SensorEventListener() { - @Override - public void onSensorChanged(SensorEvent event) { - if (Math.abs(event.values[0] - mAngle) > 0.25) { - mAngle = event.values[0]; + private final SensorEventListener mListener = new SensorEventListener() { + @Override + public void onSensorChanged(SensorEvent event) { + if (Math.abs(event.values[0] - mAngle) > 0.25) { + mAngle = event.values[0]; - if (mMap != null) { - mMap.viewport().setRotation(-mAngle); - mMap.updateMap(true); - } - } - } + if (mMap != null) { + mMap.viewport().setRotation(-mAngle); + mMap.updateMap(true); + } + } + } - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - } - }; + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) { + } + }; - /* package */float mAngle = 0; - /* package */Map mMap; + /* package */ float mAngle = 0; + /* package */ Map mMap; - private final SensorManager mSensorManager; - private final Sensor mSensor; + private final SensorManager mSensorManager; + private final Sensor mSensor; - @SuppressWarnings("deprecation") - public Compass(Context context, Map map) { - mMap = map; - mSensorManager = (SensorManager) context - .getSystemService(Context.SENSOR_SERVICE); + @SuppressWarnings("deprecation") + public Compass(Context context, Map map) { + mMap = map; + mSensorManager = (SensorManager) context + .getSystemService(Context.SENSOR_SERVICE); - mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); - } + mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); + } - public void enable() { - mSensorManager.registerListener(mListener, mSensor, - SensorManager.SENSOR_DELAY_UI); - } + public void enable() { + mSensorManager.registerListener(mListener, mSensor, + SensorManager.SENSOR_DELAY_UI); + } - public void disable() { - mSensorManager.unregisterListener(mListener); - mMap.viewport().setRotation(0); - } + public void disable() { + mSensorManager.unregisterListener(mListener); + mMap.viewport().setRotation(0); + } } diff --git a/vtm-android/src/org/oscim/android/MapPreferences.java b/vtm-android/src/org/oscim/android/MapPreferences.java index cf2e59ae..ef384212 100644 --- a/vtm-android/src/org/oscim/android/MapPreferences.java +++ b/vtm-android/src/org/oscim/android/MapPreferences.java @@ -16,80 +16,80 @@ */ package org.oscim.android; -import org.oscim.core.MapPosition; -import org.oscim.map.Map; - import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; +import org.oscim.core.MapPosition; +import org.oscim.map.Map; + public class MapPreferences { - private static final String KEY_LATITUDE = "latitude"; - private static final String KEY_LONGITUDE = "longitude"; - private static final String KEY_SCALE = "scale"; + private static final String KEY_LATITUDE = "latitude"; + private static final String KEY_LONGITUDE = "longitude"; + private static final String KEY_SCALE = "scale"; - private final String PREFERENCES_FILE; - Context ctx; + private final String PREFERENCES_FILE; + Context ctx; - public MapPreferences(String name, Context ctx) { - this.ctx = ctx; - this.PREFERENCES_FILE = name; - } + public MapPreferences(String name, Context ctx) { + this.ctx = ctx; + this.PREFERENCES_FILE = name; + } - public void clear() { - Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, Activity.MODE_PRIVATE).edit(); - editor.clear(); - editor.apply(); - } + public void clear() { + Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, Activity.MODE_PRIVATE).edit(); + editor.clear(); + editor.apply(); + } - private void putDouble(Editor editor, String key, double value) { - editor.putLong(key, Double.doubleToLongBits(value)); - } + private void putDouble(Editor editor, String key, double value) { + editor.putLong(key, Double.doubleToLongBits(value)); + } - private double getDouble(SharedPreferences prefs, String key) { - return Double.longBitsToDouble(prefs.getLong(key, 0)); - } + private double getDouble(SharedPreferences prefs, String key) { + return Double.longBitsToDouble(prefs.getLong(key, 0)); + } - public void save(Map map) { - save(map.getMapPosition()); - } + public void save(Map map) { + save(map.getMapPosition()); + } - public void save(MapPosition pos) { - Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, - Activity.MODE_PRIVATE).edit(); - editor.clear(); - putDouble(editor, KEY_LATITUDE, pos.y); - putDouble(editor, KEY_LONGITUDE, pos.x); - putDouble(editor, KEY_SCALE, pos.scale); - editor.apply(); - } + public void save(MapPosition pos) { + Editor editor = ctx.getSharedPreferences(PREFERENCES_FILE, + Activity.MODE_PRIVATE).edit(); + editor.clear(); + putDouble(editor, KEY_LATITUDE, pos.y); + putDouble(editor, KEY_LONGITUDE, pos.x); + putDouble(editor, KEY_SCALE, pos.scale); + editor.apply(); + } - private static boolean containsViewport(SharedPreferences prefs) { - return prefs.contains(KEY_LATITUDE) - && prefs.contains(KEY_LONGITUDE) - && prefs.contains(KEY_SCALE); - } + private static boolean containsViewport(SharedPreferences prefs) { + return prefs.contains(KEY_LATITUDE) + && prefs.contains(KEY_LONGITUDE) + && prefs.contains(KEY_SCALE); + } - public boolean load(Map map) { - MapPosition pos = map.getMapPosition(); - if (load(pos)) { - map.setMapPosition(pos); - return true; - } - return false; - } + public boolean load(Map map) { + MapPosition pos = map.getMapPosition(); + if (load(pos)) { + map.setMapPosition(pos); + return true; + } + return false; + } - public boolean load(MapPosition pos) { - SharedPreferences prefs = ctx.getSharedPreferences(PREFERENCES_FILE, - Activity.MODE_PRIVATE); + public boolean load(MapPosition pos) { + SharedPreferences prefs = ctx.getSharedPreferences(PREFERENCES_FILE, + Activity.MODE_PRIVATE); - if (containsViewport(prefs)) { - pos.x = getDouble(prefs, KEY_LONGITUDE); - pos.y = getDouble(prefs, KEY_LATITUDE); - pos.scale = getDouble(prefs, KEY_SCALE); - return true; - } - return false; - } + if (containsViewport(prefs)) { + pos.x = getDouble(prefs, KEY_LONGITUDE); + pos.y = getDouble(prefs, KEY_LATITUDE); + pos.scale = getDouble(prefs, KEY_SCALE); + return true; + } + return false; + } } diff --git a/vtm-android/src/org/oscim/android/MapScaleBar.java b/vtm-android/src/org/oscim/android/MapScaleBar.java index 02d224da..4027ae7c 100644 --- a/vtm-android/src/org/oscim/android/MapScaleBar.java +++ b/vtm-android/src/org/oscim/android/MapScaleBar.java @@ -16,7 +16,11 @@ package org.oscim.android; * this program. If not, see . */ -import java.util.HashMap; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Typeface; import org.oscim.android.canvas.AndroidBitmap; import org.oscim.core.MapPosition; @@ -27,11 +31,7 @@ import org.oscim.map.Map; import org.oscim.map.Map.UpdateListener; import org.oscim.renderer.BitmapRenderer; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Typeface; +import java.util.HashMap; /** * A MapScaleBar displays the ratio of a distance on the map to the @@ -39,244 +39,239 @@ import android.graphics.Typeface; */ public class MapScaleBar extends Layer implements UpdateListener { - private static final int BITMAP_HEIGHT = 64; - private static final int BITMAP_WIDTH = 128; - private static final double LATITUDE_REDRAW_THRESHOLD = 0.2; - // private static final int MARGIN_BOTTOM = 5; - // private static final int MARGIN_LEFT = 5; + private static final int BITMAP_HEIGHT = 64; + private static final int BITMAP_WIDTH = 128; + private static final double LATITUDE_REDRAW_THRESHOLD = 0.2; + // private static final int MARGIN_BOTTOM = 5; + // private static final int MARGIN_LEFT = 5; - private static final double METER_FOOT_RATIO = 0.3048; - private static final int ONE_KILOMETER = 1000; - private static final int ONE_MILE = 5280; + private static final double METER_FOOT_RATIO = 0.3048; + private static final int ONE_KILOMETER = 1000; + private static final int ONE_MILE = 5280; - private static final Paint SCALE_BAR = new Paint(Paint.ANTI_ALIAS_FLAG); - private static final Paint SCALE_BAR_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG); - private static final Paint SCALE_TEXT = new Paint(Paint.ANTI_ALIAS_FLAG); - private static final Paint SCALE_TEXT_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG); + private static final Paint SCALE_BAR = new Paint(Paint.ANTI_ALIAS_FLAG); + private static final Paint SCALE_BAR_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG); + private static final Paint SCALE_TEXT = new Paint(Paint.ANTI_ALIAS_FLAG); + private static final Paint SCALE_TEXT_STROKE = new Paint(Paint.ANTI_ALIAS_FLAG); - private static final int[] SCALE_BAR_VALUES_IMPERIAL = { - 26400000, 10560000, 5280000, - 2640000, 1056000, 528000, - 264000, 105600, 52800, 26400, - 10560, 5280, 2000, 1000, 500, - 200, 100, 50, 20, - 10, 5, 2, 1 }; - private static final int[] SCALE_BAR_VALUES_METRIC = { - 10000000, 5000000, 2000000, 1000000, - 500000, 200000, 100000, 50000, - 20000, 10000, 5000, 2000, 1000, - 500, 200, 100, 50, 20, 10, 5, 2, 1 }; + private static final int[] SCALE_BAR_VALUES_IMPERIAL = { + 26400000, 10560000, 5280000, + 2640000, 1056000, 528000, + 264000, 105600, 52800, 26400, + 10560, 5280, 2000, 1000, 500, + 200, 100, 50, 20, + 10, 5, 2, 1}; + private static final int[] SCALE_BAR_VALUES_METRIC = { + 10000000, 5000000, 2000000, 1000000, + 500000, 200000, 100000, 50000, + 20000, 10000, 5000, 2000, 1000, + 500, 200, 100, 50, 20, 10, 5, 2, 1}; - private boolean mImperialUnits; - private final Canvas mMapScaleCanvas; - private boolean mRedrawNeeded; - private double mPrevLatitude = -1; - private final double mPrevScale = -1; - private final HashMap mTextFields; + private boolean mImperialUnits; + private final Canvas mMapScaleCanvas; + private boolean mRedrawNeeded; + private double mPrevLatitude = -1; + private final double mPrevScale = -1; + private final HashMap mTextFields; - private final Bitmap mBitmap; - // passed to BitmapRenderer - need to sync on this object. - private final AndroidBitmap mLayerBitmap; - private final BitmapRenderer mBitmapLayer; + private final Bitmap mBitmap; + // passed to BitmapRenderer - need to sync on this object. + private final AndroidBitmap mLayerBitmap; + private final BitmapRenderer mBitmapLayer; - public MapScaleBar(MapView map) { - super(map.map()); + public MapScaleBar(MapView map) { + super(map.map()); - mBitmap = Bitmap.createBitmap(BITMAP_WIDTH, - BITMAP_HEIGHT, - Bitmap.Config.ARGB_8888); + mBitmap = Bitmap.createBitmap(BITMAP_WIDTH, + BITMAP_HEIGHT, + Bitmap.Config.ARGB_8888); - mMapScaleCanvas = new Canvas(mBitmap); - mTextFields = new HashMap(); + mMapScaleCanvas = new Canvas(mBitmap); + mTextFields = new HashMap(); - setDefaultTexts(); - configurePaints(); + setDefaultTexts(); + configurePaints(); - mRedrawNeeded = true; - mRenderer = mBitmapLayer = new BitmapRenderer(); - mLayerBitmap = new AndroidBitmap(mBitmap); - mBitmapLayer.setBitmap(mLayerBitmap, - BITMAP_WIDTH, - BITMAP_HEIGHT, - (int) (BITMAP_WIDTH * 1.2f), - (int) (BITMAP_HEIGHT * 1.2f)); - } + mRedrawNeeded = true; + mRenderer = mBitmapLayer = new BitmapRenderer(); + mLayerBitmap = new AndroidBitmap(mBitmap); + mBitmapLayer.setBitmap(mLayerBitmap, + BITMAP_WIDTH, + BITMAP_HEIGHT, + (int) (BITMAP_WIDTH * 1.2f), + (int) (BITMAP_HEIGHT * 1.2f)); + } - @Override + @Override public void onMapEvent(Event e, MapPosition mapPosition) { - if (e == Map.UPDATE_EVENT) - return; + if (e == Map.UPDATE_EVENT) + return; - double latitude = MercatorProjection.toLatitude(mapPosition.y); + double latitude = MercatorProjection.toLatitude(mapPosition.y); - if (!mRedrawNeeded) { - double scaleDiff = mPrevScale / mapPosition.scale; - if (scaleDiff < 1.1 && scaleDiff > 0.9) { - double latitudeDiff = Math.abs(mPrevLatitude - latitude); - if (latitudeDiff < LATITUDE_REDRAW_THRESHOLD) - return; - } - } - mPrevLatitude = latitude; + if (!mRedrawNeeded) { + double scaleDiff = mPrevScale / mapPosition.scale; + if (scaleDiff < 1.1 && scaleDiff > 0.9) { + double latitudeDiff = Math.abs(mPrevLatitude - latitude); + if (latitudeDiff < LATITUDE_REDRAW_THRESHOLD) + return; + } + } + mPrevLatitude = latitude; - double groundResolution = MercatorProjection - .groundResolution(latitude, mapPosition.scale); + double groundResolution = MercatorProjection + .groundResolution(latitude, mapPosition.scale); - int[] scaleBarValues; - if (mImperialUnits) { - groundResolution = groundResolution / METER_FOOT_RATIO; - scaleBarValues = SCALE_BAR_VALUES_IMPERIAL; - } else { - scaleBarValues = SCALE_BAR_VALUES_METRIC; - } + int[] scaleBarValues; + if (mImperialUnits) { + groundResolution = groundResolution / METER_FOOT_RATIO; + scaleBarValues = SCALE_BAR_VALUES_IMPERIAL; + } else { + scaleBarValues = SCALE_BAR_VALUES_METRIC; + } - float scaleBarLength = 0; - int mapScaleValue = 0; + float scaleBarLength = 0; + int mapScaleValue = 0; - for (int i = 0; i < scaleBarValues.length; ++i) { - mapScaleValue = scaleBarValues[i]; - scaleBarLength = mapScaleValue / (float) groundResolution; - if (scaleBarLength < (BITMAP_WIDTH - 10)) { - break; - } - } - synchronized (mLayerBitmap) { - redrawMapScaleBitmap(scaleBarLength, mapScaleValue); - } + for (int i = 0; i < scaleBarValues.length; ++i) { + mapScaleValue = scaleBarValues[i]; + scaleBarLength = mapScaleValue / (float) groundResolution; + if (scaleBarLength < (BITMAP_WIDTH - 10)) { + break; + } + } + synchronized (mLayerBitmap) { + redrawMapScaleBitmap(scaleBarLength, mapScaleValue); + } - mBitmapLayer.updateBitmap(); + mBitmapLayer.updateBitmap(); - mRedrawNeeded = false; - } + mRedrawNeeded = false; + } - /** - * @return true if imperial units are used, false otherwise. - */ - public boolean isImperialUnits() { - return mImperialUnits; - } + /** + * @return true if imperial units are used, false otherwise. + */ + public boolean isImperialUnits() { + return mImperialUnits; + } - /** - * @param imperialUnits - * true if imperial units should be used rather than metric - * units. - */ - public void setImperialUnits(boolean imperialUnits) { - mImperialUnits = imperialUnits; - mRedrawNeeded = true; - } + /** + * @param imperialUnits true if imperial units should be used rather than metric + * units. + */ + public void setImperialUnits(boolean imperialUnits) { + mImperialUnits = imperialUnits; + mRedrawNeeded = true; + } - /** - * Overrides the specified text field with the given string. - * - * @param textField - * the text field to override. - * @param value - * the new value of the text field. - */ - public void setText(TextField textField, String value) { - mTextFields.put(textField, value); - mRedrawNeeded = true; - } + /** + * Overrides the specified text field with the given string. + * + * @param textField the text field to override. + * @param value the new value of the text field. + */ + public void setText(TextField textField, String value) { + mTextFields.put(textField, value); + mRedrawNeeded = true; + } - private void drawScaleBar(float scaleBarLength, Paint paint) { - mMapScaleCanvas.drawLine(7, 25, scaleBarLength + 3, 25, paint); - mMapScaleCanvas.drawLine(5, 10, 5, 40, paint); - mMapScaleCanvas.drawLine(scaleBarLength + 5, 10, scaleBarLength + 5, 40, paint); - } + private void drawScaleBar(float scaleBarLength, Paint paint) { + mMapScaleCanvas.drawLine(7, 25, scaleBarLength + 3, 25, paint); + mMapScaleCanvas.drawLine(5, 10, 5, 40, paint); + mMapScaleCanvas.drawLine(scaleBarLength + 5, 10, scaleBarLength + 5, 40, paint); + } - private void drawScaleText(int scaleValue, String unitSymbol, Paint paint) { - mMapScaleCanvas.drawText(scaleValue + unitSymbol, 12, 18, paint); - } + private void drawScaleText(int scaleValue, String unitSymbol, Paint paint) { + mMapScaleCanvas.drawText(scaleValue + unitSymbol, 12, 18, paint); + } - /** - * Redraws the map scale bitmap with the given parameters. - * - * @param scaleBarLength - * the length of the map scale bar in pixels. - * @param mapScaleValue - * the map scale value in meters. - */ - private void redrawMapScaleBitmap(float scaleBarLength, int mapScaleValue) { - mBitmap.eraseColor(Color.TRANSPARENT); + /** + * Redraws the map scale bitmap with the given parameters. + * + * @param scaleBarLength the length of the map scale bar in pixels. + * @param mapScaleValue the map scale value in meters. + */ + private void redrawMapScaleBitmap(float scaleBarLength, int mapScaleValue) { + mBitmap.eraseColor(Color.TRANSPARENT); - // draw the scale bar - drawScaleBar(scaleBarLength, SCALE_BAR_STROKE); - drawScaleBar(scaleBarLength, SCALE_BAR); + // draw the scale bar + drawScaleBar(scaleBarLength, SCALE_BAR_STROKE); + drawScaleBar(scaleBarLength, SCALE_BAR); - int scaleValue; - String unitSymbol; - if (mImperialUnits) { - if (mapScaleValue < ONE_MILE) { - scaleValue = mapScaleValue; - unitSymbol = mTextFields.get(TextField.FOOT); - } else { - scaleValue = mapScaleValue / ONE_MILE; - unitSymbol = mTextFields.get(TextField.MILE); - } - } else { - if (mapScaleValue < ONE_KILOMETER) { - scaleValue = mapScaleValue; - unitSymbol = mTextFields.get(TextField.METER); - } else { - scaleValue = mapScaleValue / ONE_KILOMETER; - unitSymbol = mTextFields.get(TextField.KILOMETER); - } - } + int scaleValue; + String unitSymbol; + if (mImperialUnits) { + if (mapScaleValue < ONE_MILE) { + scaleValue = mapScaleValue; + unitSymbol = mTextFields.get(TextField.FOOT); + } else { + scaleValue = mapScaleValue / ONE_MILE; + unitSymbol = mTextFields.get(TextField.MILE); + } + } else { + if (mapScaleValue < ONE_KILOMETER) { + scaleValue = mapScaleValue; + unitSymbol = mTextFields.get(TextField.METER); + } else { + scaleValue = mapScaleValue / ONE_KILOMETER; + unitSymbol = mTextFields.get(TextField.KILOMETER); + } + } - // draw the scale text - drawScaleText(scaleValue, unitSymbol, SCALE_TEXT_STROKE); - drawScaleText(scaleValue, unitSymbol, SCALE_TEXT); - } + // draw the scale text + drawScaleText(scaleValue, unitSymbol, SCALE_TEXT_STROKE); + drawScaleText(scaleValue, unitSymbol, SCALE_TEXT); + } - private void setDefaultTexts() { - mTextFields.put(TextField.FOOT, " ft"); - mTextFields.put(TextField.MILE, " mi"); + private void setDefaultTexts() { + mTextFields.put(TextField.FOOT, " ft"); + mTextFields.put(TextField.MILE, " mi"); - mTextFields.put(TextField.METER, " m"); - mTextFields.put(TextField.KILOMETER, " km"); - } + mTextFields.put(TextField.METER, " m"); + mTextFields.put(TextField.KILOMETER, " km"); + } - private static void configurePaints() { - SCALE_BAR.setStrokeWidth(2); - SCALE_BAR.setStrokeCap(Paint.Cap.SQUARE); - SCALE_BAR.setColor(Color.BLACK); - SCALE_BAR_STROKE.setStrokeWidth(5); - SCALE_BAR_STROKE.setStrokeCap(Paint.Cap.SQUARE); - SCALE_BAR_STROKE.setColor(Color.WHITE); + private static void configurePaints() { + SCALE_BAR.setStrokeWidth(2); + SCALE_BAR.setStrokeCap(Paint.Cap.SQUARE); + SCALE_BAR.setColor(Color.BLACK); + SCALE_BAR_STROKE.setStrokeWidth(5); + SCALE_BAR_STROKE.setStrokeCap(Paint.Cap.SQUARE); + SCALE_BAR_STROKE.setColor(Color.WHITE); - SCALE_TEXT.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); - SCALE_TEXT.setTextSize(17); - SCALE_TEXT.setColor(Color.BLACK); - SCALE_TEXT_STROKE.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); - SCALE_TEXT_STROKE.setStyle(Paint.Style.STROKE); - SCALE_TEXT_STROKE.setColor(Color.WHITE); - SCALE_TEXT_STROKE.setStrokeWidth(2); - SCALE_TEXT_STROKE.setTextSize(17); - } + SCALE_TEXT.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); + SCALE_TEXT.setTextSize(17); + SCALE_TEXT.setColor(Color.BLACK); + SCALE_TEXT_STROKE.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); + SCALE_TEXT_STROKE.setStyle(Paint.Style.STROKE); + SCALE_TEXT_STROKE.setColor(Color.WHITE); + SCALE_TEXT_STROKE.setStrokeWidth(2); + SCALE_TEXT_STROKE.setTextSize(17); + } - /** - * Enumeration of all text fields. - */ - public enum TextField { - /** - * Unit symbol for one foot. - */ - FOOT, + /** + * Enumeration of all text fields. + */ + public enum TextField { + /** + * Unit symbol for one foot. + */ + FOOT, - /** - * Unit symbol for one kilometer. - */ - KILOMETER, + /** + * Unit symbol for one kilometer. + */ + KILOMETER, - /** - * Unit symbol for one meter. - */ - METER, + /** + * Unit symbol for one meter. + */ + METER, - /** - * Unit symbol for one mile. - */ - MILE; - } + /** + * Unit symbol for one mile. + */ + MILE; + } } diff --git a/vtm-android/src/org/oscim/android/MapView.java b/vtm-android/src/org/oscim/android/MapView.java index d8c7c712..78394002 100644 --- a/vtm-android/src/org/oscim/android/MapView.java +++ b/vtm-android/src/org/oscim/android/MapView.java @@ -16,8 +16,12 @@ */ package org.oscim.android; -import javax.microedition.khronos.egl.EGLConfig; -import javax.microedition.khronos.opengles.GL10; +import android.annotation.SuppressLint; +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.util.AttributeSet; +import android.util.DisplayMetrics; +import android.view.GestureDetector; import org.oscim.android.canvas.AndroidGraphics; import org.oscim.android.gl.AndroidGL; @@ -30,224 +34,220 @@ import org.oscim.map.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.annotation.SuppressLint; -import android.content.Context; -import android.opengl.GLSurfaceView; -import android.util.AttributeSet; -import android.util.DisplayMetrics; -import android.view.GestureDetector; +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; /** * The MapView, - * + *

* add it your App, have a map! - * + *

* Dont forget to call onPause / onResume! */ public class MapView extends GLSurfaceView { - static final Logger log = LoggerFactory.getLogger(MapView.class); + static final Logger log = LoggerFactory.getLogger(MapView.class); - static { - System.loadLibrary("vtm-jni"); - } + static { + System.loadLibrary("vtm-jni"); + } - protected final AndroidMap mMap; - protected final GestureDetector mGestureDetector; - protected final AndroidMotionEvent mMotionEvent; + protected final AndroidMap mMap; + protected final GestureDetector mGestureDetector; + protected final AndroidMotionEvent mMotionEvent; - public MapView(Context context) { - this(context, null); - } + public MapView(Context context) { + this(context, null); + } - public MapView(Context context, AttributeSet attributeSet) { - super(context, attributeSet); + public MapView(Context context, AttributeSet attributeSet) { + super(context, attributeSet); /* Not sure if this makes sense */ - this.setWillNotDraw(true); - this.setClickable(true); - this.setFocusable(true); - this.setFocusableInTouchMode(true); + this.setWillNotDraw(true); + this.setClickable(true); + this.setFocusable(true); + this.setFocusableInTouchMode(true); /* Setup android backedn */ - AndroidGraphics.init(); - AndroidAssets.init(context); - GLAdapter.init(new AndroidGL()); + AndroidGraphics.init(); + AndroidAssets.init(context); + GLAdapter.init(new AndroidGL()); - DisplayMetrics metrics = getResources().getDisplayMetrics(); - CanvasAdapter.dpi = (int) Math.max(metrics.xdpi, metrics.ydpi); + DisplayMetrics metrics = getResources().getDisplayMetrics(); + CanvasAdapter.dpi = (int) Math.max(metrics.xdpi, metrics.ydpi); /* Initialize the Map */ - mMap = new AndroidMap(this); + mMap = new AndroidMap(this); /* Initialize Renderer */ - setEGLConfigChooser(new GlConfigChooser()); - setEGLContextClientVersion(2); + setEGLConfigChooser(new GlConfigChooser()); + setEGLContextClientVersion(2); - if (GLAdapter.debug) - setDebugFlags(GLSurfaceView.DEBUG_CHECK_GL_ERROR - | GLSurfaceView.DEBUG_LOG_GL_CALLS); + if (GLAdapter.debug) + setDebugFlags(GLSurfaceView.DEBUG_CHECK_GL_ERROR + | GLSurfaceView.DEBUG_LOG_GL_CALLS); - setRenderer(new GLRenderer(mMap)); - setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); + setRenderer(new GLRenderer(mMap)); + setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); - mMap.clearMap(); - mMap.updateMap(false); + mMap.clearMap(); + mMap.updateMap(false); - GestureHandler gestureHandler = new GestureHandler(mMap); - mGestureDetector = new GestureDetector(context, gestureHandler); - mGestureDetector.setOnDoubleTapListener(gestureHandler); + GestureHandler gestureHandler = new GestureHandler(mMap); + mGestureDetector = new GestureDetector(context, gestureHandler); + mGestureDetector.setOnDoubleTapListener(gestureHandler); - mMotionEvent = new AndroidMotionEvent(); - } + mMotionEvent = new AndroidMotionEvent(); + } - public void onStop() { + public void onStop() { - } + } - public void onPause() { - mMap.pause(true); - } + public void onPause() { + mMap.pause(true); + } - public void onResume() { - mMap.pause(false); - } + public void onResume() { + mMap.pause(false); + } - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouchEvent(android.view.MotionEvent motionEvent) { + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouchEvent(android.view.MotionEvent motionEvent) { - if (!isClickable()) - return false; + if (!isClickable()) + return false; - if (mGestureDetector.onTouchEvent(motionEvent)) - return true; + if (mGestureDetector.onTouchEvent(motionEvent)) + return true; - mMap.input.fire(null, mMotionEvent.wrap(motionEvent)); - return true; - } + mMap.input.fire(null, mMotionEvent.wrap(motionEvent)); + return true; + } - @Override - protected void onSizeChanged(int width, int height, - int oldWidth, int oldHeight) { + @Override + protected void onSizeChanged(int width, int height, + int oldWidth, int oldHeight) { - super.onSizeChanged(width, height, oldWidth, oldHeight); + super.onSizeChanged(width, height, oldWidth, oldHeight); - if (width > 0 && height > 0) - mMap.viewport().setScreenSize(width, height); - } + if (width > 0 && height > 0) + mMap.viewport().setScreenSize(width, height); + } - public Map map() { - return mMap; - } + public Map map() { + return mMap; + } - static class AndroidMap extends Map { + static class AndroidMap extends Map { - private final MapView mMapView; + private final MapView mMapView; - private boolean mRenderRequest; - private boolean mRenderWait; - private boolean mPausing; + private boolean mRenderRequest; + private boolean mRenderWait; + private boolean mPausing; - public AndroidMap(MapView mapView) { - super(); - mMapView = mapView; - } + public AndroidMap(MapView mapView) { + super(); + mMapView = mapView; + } - @Override - public int getWidth() { - return mMapView.getWidth(); - } + @Override + public int getWidth() { + return mMapView.getWidth(); + } - @Override - public int getHeight() { - return mMapView.getHeight(); - } + @Override + public int getHeight() { + return mMapView.getHeight(); + } - private final Runnable mRedrawCb = new Runnable() { - @Override - public void run() { - prepareFrame(); - mMapView.requestRender(); - } - }; + private final Runnable mRedrawCb = new Runnable() { + @Override + public void run() { + prepareFrame(); + mMapView.requestRender(); + } + }; - @Override - public void updateMap(boolean redraw) { - synchronized (mRedrawCb) { - if (mPausing) - return; + @Override + public void updateMap(boolean redraw) { + synchronized (mRedrawCb) { + if (mPausing) + return; - if (!mRenderRequest) { - mRenderRequest = true; - mMapView.post(mRedrawCb); - } else { - mRenderWait = true; - } - } - } + if (!mRenderRequest) { + mRenderRequest = true; + mMapView.post(mRedrawCb); + } else { + mRenderWait = true; + } + } + } - @Override - public void render() { - if (mPausing) - return; + @Override + public void render() { + if (mPausing) + return; - /** TODO should not need to call prepareFrame in mRedrawCb */ - updateMap(false); - } + /** TODO should not need to call prepareFrame in mRedrawCb */ + updateMap(false); + } - @Override - public void beginFrame() { - } + @Override + public void beginFrame() { + } - @Override - public void doneFrame(boolean animate) { - synchronized (mRedrawCb) { - mRenderRequest = false; - if (animate || mRenderWait) { - mRenderWait = false; - render(); - } - } - } + @Override + public void doneFrame(boolean animate) { + synchronized (mRedrawCb) { + mRenderRequest = false; + if (animate || mRenderWait) { + mRenderWait = false; + render(); + } + } + } - @Override - public boolean post(Runnable runnable) { - return mMapView.post(runnable); - } + @Override + public boolean post(Runnable runnable) { + return mMapView.post(runnable); + } - @Override - public boolean postDelayed(Runnable action, long delay) { - return mMapView.postDelayed(action, delay); - } + @Override + public boolean postDelayed(Runnable action, long delay) { + return mMapView.postDelayed(action, delay); + } - public void pause(boolean pause) { - log.debug("pause... {}", pause); - mPausing = pause; - } - } + public void pause(boolean pause) { + log.debug("pause... {}", pause); + mPausing = pause; + } + } - static class GLRenderer extends org.oscim.renderer.MapRenderer - implements GLSurfaceView.Renderer { + static class GLRenderer extends org.oscim.renderer.MapRenderer + implements GLSurfaceView.Renderer { - public GLRenderer(Map map) { - super(map); - } + public GLRenderer(Map map) { + super(map); + } - @Override - public void onSurfaceCreated(GL10 gl, EGLConfig config) { - super.onSurfaceCreated(); - } + @Override + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + super.onSurfaceCreated(); + } - @Override - public void onSurfaceChanged(GL10 gl, int width, int height) { - super.onSurfaceChanged(width, height); + @Override + public void onSurfaceChanged(GL10 gl, int width, int height) { + super.onSurfaceChanged(width, height); - } + } - @Override - public void onDrawFrame(GL10 gl) { - super.onDrawFrame(); - } - } + @Override + public void onDrawFrame(GL10 gl) { + super.onDrawFrame(); + } + } } diff --git a/vtm-android/src/org/oscim/android/cache/TileCache.java b/vtm-android/src/org/oscim/android/cache/TileCache.java index 6a89b78c..277535ab 100644 --- a/vtm-android/src/org/oscim/android/cache/TileCache.java +++ b/vtm-android/src/org/oscim/android/cache/TileCache.java @@ -16,17 +16,6 @@ */ package org.oscim.android.cache; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; - -import org.oscim.core.Tile; -import org.oscim.tiling.ITileCache; -import org.slf4j.LoggerFactory; - import android.annotation.TargetApi; import android.content.Context; import android.database.Cursor; @@ -37,247 +26,258 @@ import android.database.sqlite.SQLiteStatement; import android.os.Build; import android.os.ParcelFileDescriptor; +import org.oscim.core.Tile; +import org.oscim.tiling.ITileCache; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; + public class TileCache implements ITileCache { - final static org.slf4j.Logger log = LoggerFactory.getLogger(TileCache.class); - final static boolean dbg = false; + final static org.slf4j.Logger log = LoggerFactory.getLogger(TileCache.class); + final static boolean dbg = false; - class CacheTileReader implements TileReader { - final InputStream mInputStream; - final Tile mTile; + class CacheTileReader implements TileReader { + final InputStream mInputStream; + final Tile mTile; - public CacheTileReader(Tile tile, InputStream is) { - mTile = tile; - mInputStream = is; - } + public CacheTileReader(Tile tile, InputStream is) { + mTile = tile; + mInputStream = is; + } - @Override - public Tile getTile() { - return mTile; - } + @Override + public Tile getTile() { + return mTile; + } - @Override - public InputStream getInputStream() { - return mInputStream; - } - } + @Override + public InputStream getInputStream() { + return mInputStream; + } + } - class CacheTileWriter implements TileWriter { - final ByteArrayOutputStream mOutputStream; - final Tile mTile; + class CacheTileWriter implements TileWriter { + final ByteArrayOutputStream mOutputStream; + final Tile mTile; - CacheTileWriter(Tile tile, ByteArrayOutputStream os) { - mTile = tile; - mOutputStream = os; - } + CacheTileWriter(Tile tile, ByteArrayOutputStream os) { + mTile = tile; + mOutputStream = os; + } - @Override - public Tile getTile() { - return mTile; - } + @Override + public Tile getTile() { + return mTile; + } - @Override - public OutputStream getOutputStream() { - return mOutputStream; - } + @Override + public OutputStream getOutputStream() { + return mOutputStream; + } - @Override - public void complete(boolean success) { - saveTile(mTile, mOutputStream, success); - } - } + @Override + public void complete(boolean success) { + saveTile(mTile, mOutputStream, success); + } + } - private final ArrayList mCacheBuffers; - private final SQLiteHelper dbHelper; - private final SQLiteDatabase mDatabase; - private final SQLiteStatement mStmtGetTile; - private final SQLiteStatement mStmtPutTile; + private final ArrayList mCacheBuffers; + private final SQLiteHelper dbHelper; + private final SQLiteDatabase mDatabase; + private final SQLiteStatement mStmtGetTile; + private final SQLiteStatement mStmtPutTile; - //private final SQLiteStatement mStmtUpdateTile; + //private final SQLiteStatement mStmtUpdateTile; - public void dispose() { - if (mDatabase.isOpen()) - mDatabase.close(); - } + public void dispose() { + if (mDatabase.isOpen()) + mDatabase.close(); + } - @TargetApi(Build.VERSION_CODES.JELLY_BEAN) - public TileCache(Context context, String cacheDirectory, String dbName) { - if (dbg) - log.debug("open cache {}, {}", cacheDirectory, dbName); + @TargetApi(Build.VERSION_CODES.JELLY_BEAN) + public TileCache(Context context, String cacheDirectory, String dbName) { + if (dbg) + log.debug("open cache {}, {}", cacheDirectory, dbName); - dbHelper = new SQLiteHelper(context, dbName); + dbHelper = new SQLiteHelper(context, dbName); - if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) - dbHelper.setWriteAheadLoggingEnabled(true); + if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) + dbHelper.setWriteAheadLoggingEnabled(true); - mDatabase = dbHelper.getWritableDatabase(); + mDatabase = dbHelper.getWritableDatabase(); - mStmtGetTile = mDatabase.compileStatement("" + - "SELECT " + COLUMN_DATA + - " FROM " + TABLE_NAME + - " WHERE x=? AND y=? AND z = ?"); + mStmtGetTile = mDatabase.compileStatement("" + + "SELECT " + COLUMN_DATA + + " FROM " + TABLE_NAME + + " WHERE x=? AND y=? AND z = ?"); - mStmtPutTile = mDatabase.compileStatement("" + - "INSERT INTO " + TABLE_NAME + - " (x, y, z, time, last_access, data)" + - " VALUES(?,?,?,?,?,?)"); + mStmtPutTile = mDatabase.compileStatement("" + + "INSERT INTO " + TABLE_NAME + + " (x, y, z, time, last_access, data)" + + " VALUES(?,?,?,?,?,?)"); - //mStmtUpdateTile = mDatabase.compileStatement("" + - // "UPDATE " + TABLE_NAME + - // " SET last_access=?" + - // " WHERE x=? AND y=? AND z=?"); + //mStmtUpdateTile = mDatabase.compileStatement("" + + // "UPDATE " + TABLE_NAME + + // " SET last_access=?" + + // " WHERE x=? AND y=? AND z=?"); - mCacheBuffers = new ArrayList(); - } + mCacheBuffers = new ArrayList(); + } - @Override - public TileWriter writeTile(Tile tile) { - ByteArrayOutputStream os; + @Override + public TileWriter writeTile(Tile tile) { + ByteArrayOutputStream os; - synchronized (mCacheBuffers) { - if (mCacheBuffers.size() == 0) - os = new ByteArrayOutputStream(32 * 1024); - else - os = mCacheBuffers.remove(mCacheBuffers.size() - 1); - } - return new CacheTileWriter(tile, os); - } + synchronized (mCacheBuffers) { + if (mCacheBuffers.size() == 0) + os = new ByteArrayOutputStream(32 * 1024); + else + os = mCacheBuffers.remove(mCacheBuffers.size() - 1); + } + return new CacheTileWriter(tile, os); + } - static final String TABLE_NAME = "tiles"; - static final String COLUMN_TIME = "time"; - static final String COLUMN_ACCESS = "last_access"; - static final String COLUMN_DATA = "data"; + static final String TABLE_NAME = "tiles"; + static final String COLUMN_TIME = "time"; + static final String COLUMN_ACCESS = "last_access"; + static final String COLUMN_DATA = "data"; - //static final String COLUMN_SIZE = "size"; + //static final String COLUMN_SIZE = "size"; - class SQLiteHelper extends SQLiteOpenHelper { + class SQLiteHelper extends SQLiteOpenHelper { - //private static final String DATABASE_NAME = "tile.db"; - private static final int DATABASE_VERSION = 1; + //private static final String DATABASE_NAME = "tile.db"; + private static final int DATABASE_VERSION = 1; - private static final String TILE_SCHEMA = - "CREATE TABLE " - + TABLE_NAME + "(" - + "x INTEGER NOT NULL," - + "y INTEGER NOT NULL," - + "z INTEGER NOT NULL," - + COLUMN_TIME + " LONG NOT NULL," - //+ COLUMN_SIZE + " LONG NOT NULL," - + COLUMN_ACCESS + " LONG NOT NULL," - + COLUMN_DATA + " BLOB," - + "PRIMARY KEY(x,y,z));"; + private static final String TILE_SCHEMA = + "CREATE TABLE " + + TABLE_NAME + "(" + + "x INTEGER NOT NULL," + + "y INTEGER NOT NULL," + + "z INTEGER NOT NULL," + + COLUMN_TIME + " LONG NOT NULL," + //+ COLUMN_SIZE + " LONG NOT NULL," + + COLUMN_ACCESS + " LONG NOT NULL," + + COLUMN_DATA + " BLOB," + + "PRIMARY KEY(x,y,z));"; - public SQLiteHelper(Context context, String dbName) { - super(context, dbName, null, DATABASE_VERSION); - } + public SQLiteHelper(Context context, String dbName) { + super(context, dbName, null, DATABASE_VERSION); + } - @Override - public void onCreate(SQLiteDatabase db) { - log.debug("create table"); - db.execSQL(TILE_SCHEMA); - } + @Override + public void onCreate(SQLiteDatabase db) { + log.debug("create table"); + db.execSQL(TILE_SCHEMA); + } - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - log.debug("drop table"); - db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); - onCreate(db); - } + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + log.debug("drop table"); + db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); + onCreate(db); + } - @Override - public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { - onUpgrade(db, oldVersion, newVersion); - } - } + @Override + public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { + onUpgrade(db, oldVersion, newVersion); + } + } - public void saveTile(Tile tile, ByteArrayOutputStream data, boolean success) { - byte[] bytes = null; + public void saveTile(Tile tile, ByteArrayOutputStream data, boolean success) { + byte[] bytes = null; - if (success) - bytes = data.toByteArray(); + if (success) + bytes = data.toByteArray(); - synchronized (mCacheBuffers) { - data.reset(); - mCacheBuffers.add(data); - } + synchronized (mCacheBuffers) { + data.reset(); + mCacheBuffers.add(data); + } - if (dbg) - log.debug("store tile {} {}", tile, Boolean.valueOf(success)); + if (dbg) + log.debug("store tile {} {}", tile, Boolean.valueOf(success)); - if (!success) - return; + if (!success) + return; - synchronized (mStmtPutTile) { - mStmtPutTile.bindLong(1, tile.tileX); - mStmtPutTile.bindLong(2, tile.tileY); - mStmtPutTile.bindLong(3, tile.zoomLevel); - mStmtPutTile.bindLong(4, 0); - mStmtPutTile.bindLong(5, 0); - mStmtPutTile.bindBlob(6, bytes); + synchronized (mStmtPutTile) { + mStmtPutTile.bindLong(1, tile.tileX); + mStmtPutTile.bindLong(2, tile.tileY); + mStmtPutTile.bindLong(3, tile.zoomLevel); + mStmtPutTile.bindLong(4, 0); + mStmtPutTile.bindLong(5, 0); + mStmtPutTile.bindBlob(6, bytes); - mStmtPutTile.execute(); - mStmtPutTile.clearBindings(); - } - } + mStmtPutTile.execute(); + mStmtPutTile.clearBindings(); + } + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public TileReader getTileApi11(Tile tile) { - InputStream in = null; + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public TileReader getTileApi11(Tile tile) { + InputStream in = null; - mStmtGetTile.bindLong(1, tile.tileX); - mStmtGetTile.bindLong(2, tile.tileY); - mStmtGetTile.bindLong(3, tile.zoomLevel); + mStmtGetTile.bindLong(1, tile.tileX); + mStmtGetTile.bindLong(2, tile.tileY); + mStmtGetTile.bindLong(3, tile.zoomLevel); - try { - ParcelFileDescriptor result = mStmtGetTile.simpleQueryForBlobFileDescriptor(); - in = new FileInputStream(result.getFileDescriptor()); - } catch (SQLiteDoneException e) { - log.debug("not in cache {}", tile); - return null; - } finally { - mStmtGetTile.clearBindings(); - } + try { + ParcelFileDescriptor result = mStmtGetTile.simpleQueryForBlobFileDescriptor(); + in = new FileInputStream(result.getFileDescriptor()); + } catch (SQLiteDoneException e) { + log.debug("not in cache {}", tile); + return null; + } finally { + mStmtGetTile.clearBindings(); + } - if (dbg) - log.debug("load tile {}", tile); + if (dbg) + log.debug("load tile {}", tile); - return new CacheTileReader(tile, in); - } + return new CacheTileReader(tile, in); + } - private final String[] mQueryVals = new String[3]; + private final String[] mQueryVals = new String[3]; - @Override - public synchronized TileReader getTile(Tile tile) { + @Override + public synchronized TileReader getTile(Tile tile) { - //if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) - // return getTileApi11(tile); + //if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) + // return getTileApi11(tile); - mQueryVals[0] = String.valueOf(tile.zoomLevel); - mQueryVals[1] = String.valueOf(tile.tileX); - mQueryVals[2] = String.valueOf(tile.tileY); + mQueryVals[0] = String.valueOf(tile.zoomLevel); + mQueryVals[1] = String.valueOf(tile.tileX); + mQueryVals[2] = String.valueOf(tile.tileY); - Cursor cursor = mDatabase.rawQuery("SELECT " + COLUMN_DATA + - " FROM " + TABLE_NAME + - " WHERE z=? AND x=? AND y=?", mQueryVals); + Cursor cursor = mDatabase.rawQuery("SELECT " + COLUMN_DATA + + " FROM " + TABLE_NAME + + " WHERE z=? AND x=? AND y=?", mQueryVals); - if (!cursor.moveToFirst()) { - if (dbg) - log.debug("not in cache {}", tile); + if (!cursor.moveToFirst()) { + if (dbg) + log.debug("not in cache {}", tile); - cursor.close(); - return null; - } + cursor.close(); + return null; + } - InputStream in = new ByteArrayInputStream(cursor.getBlob(0)); - cursor.close(); + InputStream in = new ByteArrayInputStream(cursor.getBlob(0)); + cursor.close(); - if (dbg) - log.debug("load tile {}", tile); + if (dbg) + log.debug("load tile {}", tile); - return new CacheTileReader(tile, in); - } + return new CacheTileReader(tile, in); + } - @Override - public void setCacheSize(long size) { - } + @Override + public void setCacheSize(long size) { + } } diff --git a/vtm-android/src/org/oscim/android/canvas/AndroidBitmap.java b/vtm-android/src/org/oscim/android/canvas/AndroidBitmap.java index 35b68e5b..0655deb9 100644 --- a/vtm-android/src/org/oscim/android/canvas/AndroidBitmap.java +++ b/vtm-android/src/org/oscim/android/canvas/AndroidBitmap.java @@ -16,88 +16,88 @@ */ package org.oscim.android.canvas; -import static android.graphics.Bitmap.Config.ARGB_8888; - -import java.io.InputStream; - import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLUtils; +import java.io.InputStream; + +import static android.graphics.Bitmap.Config.ARGB_8888; + public class AndroidBitmap implements org.oscim.backend.canvas.Bitmap { - final Bitmap mBitmap; + final Bitmap mBitmap; - public AndroidBitmap(InputStream inputStream) { - Bitmap bitmap = BitmapFactory.decodeStream(inputStream); - try { - GLUtils.getType(bitmap); - } catch (IllegalArgumentException e) { - bitmap = bitmap.copy(ARGB_8888, false); - } - mBitmap = bitmap; - } + public AndroidBitmap(InputStream inputStream) { + Bitmap bitmap = BitmapFactory.decodeStream(inputStream); + try { + GLUtils.getType(bitmap); + } catch (IllegalArgumentException e) { + bitmap = bitmap.copy(ARGB_8888, false); + } + mBitmap = bitmap; + } - @Override - public boolean isValid() { - return mBitmap != null; - } + @Override + public boolean isValid() { + return mBitmap != null; + } - /** - * @param format ignored always ARGB8888 - */ - public AndroidBitmap(int width, int height, int format) { - mBitmap = android.graphics.Bitmap - .createBitmap(width, height, ARGB_8888); - } + /** + * @param format ignored always ARGB8888 + */ + public AndroidBitmap(int width, int height, int format) { + mBitmap = android.graphics.Bitmap + .createBitmap(width, height, ARGB_8888); + } - public AndroidBitmap(android.graphics.Bitmap bitmap) { - mBitmap = bitmap; - } + public AndroidBitmap(android.graphics.Bitmap bitmap) { + mBitmap = bitmap; + } - @Override - public int getWidth() { - return mBitmap.getWidth(); - } + @Override + public int getWidth() { + return mBitmap.getWidth(); + } - @Override - public int getHeight() { - return mBitmap.getHeight(); - } + @Override + public int getHeight() { + return mBitmap.getHeight(); + } - @Override - public int[] getPixels() { - int width = getWidth(); - int height = getHeight(); - int[] colors = new int[width * height]; - mBitmap.getPixels(colors, 0, width, 0, 0, width, height); - return colors; - } + @Override + public int[] getPixels() { + int width = getWidth(); + int height = getHeight(); + int[] colors = new int[width * height]; + mBitmap.getPixels(colors, 0, width, 0, 0, width, height); + return colors; + } - @Override - public void eraseColor(int color) { - //int a = android.graphics.Color.TRANSPARENT; - mBitmap.eraseColor(color); - } + @Override + public void eraseColor(int color) { + //int a = android.graphics.Color.TRANSPARENT; + mBitmap.eraseColor(color); + } - @Override - public void uploadToTexture(boolean replace) { - int format = GLUtils.getInternalFormat(mBitmap); - int type = GLUtils.getType(mBitmap); + @Override + public void uploadToTexture(boolean replace) { + int format = GLUtils.getInternalFormat(mBitmap); + int type = GLUtils.getType(mBitmap); - if (replace) - GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, - mBitmap, format, type); - else - GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format, - mBitmap, type, 0); - } + if (replace) + GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, + mBitmap, format, type); + else + GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, format, + mBitmap, type, 0); + } - @Override - public void recycle() { - if (mBitmap == null) - return; + @Override + public void recycle() { + if (mBitmap == null) + return; - mBitmap.recycle(); - } + mBitmap.recycle(); + } } diff --git a/vtm-android/src/org/oscim/android/canvas/AndroidCanvas.java b/vtm-android/src/org/oscim/android/canvas/AndroidCanvas.java index 1fc8aef4..2ae0e4c2 100644 --- a/vtm-android/src/org/oscim/android/canvas/AndroidCanvas.java +++ b/vtm-android/src/org/oscim/android/canvas/AndroidCanvas.java @@ -21,31 +21,31 @@ import org.oscim.backend.canvas.Canvas; import org.oscim.backend.canvas.Paint; public class AndroidCanvas implements Canvas { - final android.graphics.Canvas canvas; + final android.graphics.Canvas canvas; - public AndroidCanvas() { - canvas = new android.graphics.Canvas(); - } + public AndroidCanvas() { + canvas = new android.graphics.Canvas(); + } - @Override - public void setBitmap(Bitmap bitmap) { - canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap); - } + @Override + public void setBitmap(Bitmap bitmap) { + canvas.setBitmap(((AndroidBitmap) bitmap).mBitmap); + } - @Override - public void drawText(String string, float x, float y, Paint fill, Paint stroke) { - if (string != null) { - if (stroke != null) - canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint); + @Override + public void drawText(String string, float x, float y, Paint fill, Paint stroke) { + if (string != null) { + if (stroke != null) + canvas.drawText(string, x, y, ((AndroidPaint) stroke).mPaint); - canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint); - } - } + canvas.drawText(string, x, y, ((AndroidPaint) fill).mPaint); + } + } - @Override - public void drawBitmap(Bitmap bitmap, float x, float y) { - canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null); + @Override + public void drawBitmap(Bitmap bitmap, float x, float y) { + canvas.drawBitmap(((AndroidBitmap) bitmap).mBitmap, x, y, null); - } + } } diff --git a/vtm-android/src/org/oscim/android/canvas/AndroidGraphics.java b/vtm-android/src/org/oscim/android/canvas/AndroidGraphics.java index 4941634c..45a15738 100644 --- a/vtm-android/src/org/oscim/android/canvas/AndroidGraphics.java +++ b/vtm-android/src/org/oscim/android/canvas/AndroidGraphics.java @@ -17,8 +17,10 @@ */ package org.oscim.android.canvas; -import java.io.IOException; -import java.io.InputStream; +import android.content.res.Resources; +import android.graphics.Bitmap.Config; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Bitmap; @@ -27,99 +29,97 @@ import org.oscim.backend.canvas.Paint; import org.oscim.layers.marker.MarkerItem.HotspotPlace; import org.oscim.layers.marker.MarkerSymbol; -import android.content.res.Resources; -import android.graphics.Bitmap.Config; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; +import java.io.IOException; +import java.io.InputStream; public final class AndroidGraphics extends CanvasAdapter { - public static void init() { - CanvasAdapter.init(new AndroidGraphics()); - } + public static void init() { + CanvasAdapter.init(new AndroidGraphics()); + } - public static android.graphics.Paint getAndroidPaint(Paint paint) { - return ((AndroidPaint) paint).mPaint; - } + public static android.graphics.Paint getAndroidPaint(Paint paint) { + return ((AndroidPaint) paint).mPaint; + } - public static android.graphics.Bitmap getBitmap(Bitmap bitmap) { - return ((AndroidBitmap) bitmap).mBitmap; - } + public static android.graphics.Bitmap getBitmap(Bitmap bitmap) { + return ((AndroidBitmap) bitmap).mBitmap; + } - private AndroidGraphics() { - // do nothing - } + private AndroidGraphics() { + // do nothing + } - @Override - public Bitmap decodeBitmapImpl(InputStream inputStream) { - return new AndroidBitmap(inputStream); - } + @Override + public Bitmap decodeBitmapImpl(InputStream inputStream) { + return new AndroidBitmap(inputStream); + } - @Override - public Bitmap loadBitmapAssetImpl(String fileName) { - try { - return createBitmap(fileName); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + @Override + public Bitmap loadBitmapAssetImpl(String fileName) { + try { + return createBitmap(fileName); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } - @Override - public Paint newPaintImpl() { - return new AndroidPaint(); - } + @Override + public Paint newPaintImpl() { + return new AndroidPaint(); + } - @Override - public Bitmap newBitmapImpl(int width, int height, int format) { - return new AndroidBitmap(width, height, format); - } + @Override + public Bitmap newBitmapImpl(int width, int height, int format) { + return new AndroidBitmap(width, height, format); + } - @Override - public Canvas newCanvasImpl() { - return new AndroidCanvas(); - } + @Override + public Canvas newCanvasImpl() { + return new AndroidCanvas(); + } - //------------------------------------- - public static Bitmap drawableToBitmap(Drawable drawable) { - if (drawable instanceof BitmapDrawable) { - return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap()); - } + //------------------------------------- + public static Bitmap drawableToBitmap(Drawable drawable) { + if (drawable instanceof BitmapDrawable) { + return new AndroidBitmap(((BitmapDrawable) drawable).getBitmap()); + } - android.graphics.Bitmap bitmap = android.graphics.Bitmap - .createBitmap(drawable.getIntrinsicWidth(), - drawable.getIntrinsicHeight(), - Config.ARGB_8888); + android.graphics.Bitmap bitmap = android.graphics.Bitmap + .createBitmap(drawable.getIntrinsicWidth(), + drawable.getIntrinsicHeight(), + Config.ARGB_8888); - android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); + android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); + drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); + drawable.draw(canvas); - return new AndroidBitmap(bitmap); - } + return new AndroidBitmap(bitmap); + } - public static Bitmap drawableToBitmap(Resources res, int resId) { - return new AndroidBitmap(res.openRawResource(resId)); - } + public static Bitmap drawableToBitmap(Resources res, int resId) { + return new AndroidBitmap(res.openRawResource(resId)); + } - /** - * @deprecated - */ - public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) { - if (place == null) - place = HotspotPlace.CENTER; + /** + * @deprecated + */ + public static MarkerSymbol makeMarker(Drawable drawable, HotspotPlace place) { + if (place == null) + place = HotspotPlace.CENTER; - return new MarkerSymbol(drawableToBitmap(drawable), place); - } + return new MarkerSymbol(drawableToBitmap(drawable), place); + } - /** - * @deprecated - */ - public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) { - if (place == null) - place = HotspotPlace.CENTER; + /** + * @deprecated + */ + public static MarkerSymbol makeMarker(Resources res, int resId, HotspotPlace place) { + if (place == null) + place = HotspotPlace.CENTER; - InputStream in = res.openRawResource(resId); - return new MarkerSymbol(new AndroidBitmap(in), place); - } + InputStream in = res.openRawResource(resId); + return new MarkerSymbol(new AndroidBitmap(in), place); + } } diff --git a/vtm-android/src/org/oscim/android/canvas/AndroidPaint.java b/vtm-android/src/org/oscim/android/canvas/AndroidPaint.java index e63e9aeb..e574328e 100644 --- a/vtm-android/src/org/oscim/android/canvas/AndroidPaint.java +++ b/vtm-android/src/org/oscim/android/canvas/AndroidPaint.java @@ -16,110 +16,110 @@ */ package org.oscim.android.canvas; -import org.oscim.backend.canvas.Paint; - import android.graphics.Paint.FontMetrics; import android.graphics.Typeface; +import org.oscim.backend.canvas.Paint; + class AndroidPaint implements Paint { - private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) { - switch (fontStyle) { - case BOLD: - return 1; - case BOLD_ITALIC: - return 3; - case ITALIC: - return 2; - case NORMAL: - return 0; - } + private static int getStyle(org.oscim.backend.canvas.Paint.FontStyle fontStyle) { + switch (fontStyle) { + case BOLD: + return 1; + case BOLD_ITALIC: + return 3; + case ITALIC: + return 2; + case NORMAL: + return 0; + } - throw new IllegalArgumentException("unknown font style: " + fontStyle); - } + throw new IllegalArgumentException("unknown font style: " + fontStyle); + } - private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) { - switch (fontFamily) { - case DEFAULT: - return Typeface.DEFAULT; - case DEFAULT_BOLD: - return Typeface.DEFAULT_BOLD; - case MONOSPACE: - return Typeface.MONOSPACE; - case SANS_SERIF: - return Typeface.SANS_SERIF; - case SERIF: - return Typeface.SERIF; - } + private static Typeface getTypeface(org.oscim.backend.canvas.Paint.FontFamily fontFamily) { + switch (fontFamily) { + case DEFAULT: + return Typeface.DEFAULT; + case DEFAULT_BOLD: + return Typeface.DEFAULT_BOLD; + case MONOSPACE: + return Typeface.MONOSPACE; + case SANS_SERIF: + return Typeface.SANS_SERIF; + case SERIF: + return Typeface.SERIF; + } - throw new IllegalArgumentException("unknown font family: " + fontFamily); - } + throw new IllegalArgumentException("unknown font family: " + fontFamily); + } - final android.graphics.Paint mPaint; + final android.graphics.Paint mPaint; - AndroidPaint() { - mPaint = new android.graphics.Paint( - android.graphics.Paint.ANTI_ALIAS_FLAG); - } + AndroidPaint() { + mPaint = new android.graphics.Paint( + android.graphics.Paint.ANTI_ALIAS_FLAG); + } - @Override - public int getColor() { - return mPaint.getColor(); - } + @Override + public int getColor() { + return mPaint.getColor(); + } - @Override - public void setColor(int color) { - mPaint.setColor(color); - } + @Override + public void setColor(int color) { + mPaint.setColor(color); + } - @Override - public void setStrokeCap(Cap cap) { - android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap - .valueOf(cap.name()); - mPaint.setStrokeCap(androidCap); - } + @Override + public void setStrokeCap(Cap cap) { + android.graphics.Paint.Cap androidCap = android.graphics.Paint.Cap + .valueOf(cap.name()); + mPaint.setStrokeCap(androidCap); + } - @Override - public void setStrokeWidth(float width) { - mPaint.setStrokeWidth(width); - } + @Override + public void setStrokeWidth(float width) { + mPaint.setStrokeWidth(width); + } - @Override - public void setStyle(Style style) { - mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name())); - } + @Override + public void setStyle(Style style) { + mPaint.setStyle(android.graphics.Paint.Style.valueOf(style.name())); + } - @Override - public void setTextAlign(Align align) { - //mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name())); - } + @Override + public void setTextAlign(Align align) { + //mPaint.setTextAlign(android.graphics.Paint.Align.valueOf(align.name())); + } - @Override - public void setTextSize(float textSize) { - mPaint.setTextSize(textSize); - } + @Override + public void setTextSize(float textSize) { + mPaint.setTextSize(textSize); + } - @Override - public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { - Typeface typeface = Typeface.create(getTypeface(fontFamily), - getStyle(fontStyle)); - mPaint.setTypeface(typeface); - } + @Override + public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { + Typeface typeface = Typeface.create(getTypeface(fontFamily), + getStyle(fontStyle)); + mPaint.setTypeface(typeface); + } - @Override - public float measureText(String text) { - return mPaint.measureText(text); - } + @Override + public float measureText(String text) { + return mPaint.measureText(text); + } - @Override - public float getFontHeight() { - FontMetrics fm = mPaint.getFontMetrics(); - return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); - } + @Override + public float getFontHeight() { + FontMetrics fm = mPaint.getFontMetrics(); + return (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); + } - @Override - public float getFontDescent() { - FontMetrics fm = mPaint.getFontMetrics(); - // //fontDescent = (float) Math.ceil(Math.abs(fm.descent)); - return Math.abs(fm.bottom); - } + @Override + public float getFontDescent() { + FontMetrics fm = mPaint.getFontMetrics(); + // //fontDescent = (float) Math.ceil(Math.abs(fm.descent)); + return Math.abs(fm.bottom); + } } diff --git a/vtm-android/src/org/oscim/android/gl/AndroidGL.java b/vtm-android/src/org/oscim/android/gl/AndroidGL.java index 561236aa..0fee0650 100644 --- a/vtm-android/src/org/oscim/android/gl/AndroidGL.java +++ b/vtm-android/src/org/oscim/android/gl/AndroidGL.java @@ -16,835 +16,835 @@ */ package org.oscim.android.gl; +import android.annotation.SuppressLint; +import android.opengl.GLES20; + +import org.oscim.backend.GL; + import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; -import org.oscim.backend.GL; - -import android.annotation.SuppressLint; -import android.opengl.GLES20; - @SuppressLint("NewApi") public class AndroidGL implements GL { - @Override - public void attachShader(int program, int shader) { - GLES20.glAttachShader(program, shader); - } - - @Override - public void bindAttribLocation(int program, int index, String name) { - GLES20.glBindAttribLocation(program, index, name); - } - - @Override - public void bindBuffer(int target, int buffer) { - GLES20.glBindBuffer(target, buffer); - } - - @Override - public void bindFramebuffer(int target, int framebuffer) { - GLES20.glBindFramebuffer(target, framebuffer); - } - - @Override - public void bindRenderbuffer(int target, int renderbuffer) { - GLES20.glBindRenderbuffer(target, renderbuffer); - } - - @Override - public void blendColor(float red, float green, float blue, float alpha) { - GLES20.glBlendColor(red, green, blue, alpha); - } - - @Override - public void blendEquation(int mode) { - GLES20.glBlendEquation(mode); - } - - @Override - public void blendEquationSeparate(int modeRGB, int modeAlpha) { - GLES20.glBlendEquationSeparate(modeRGB, modeAlpha); - } - - @Override - public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { - GLES20.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); - } - - @Override - public void bufferData(int target, int size, Buffer data, int usage) { - GLES20.glBufferData(target, size, data, usage); - } - - @Override - public void bufferSubData(int target, int offset, int size, Buffer data) { - GLES20.glBufferSubData(target, offset, size, data); - } - - @Override - public int checkFramebufferStatus(int target) { - return GLES20.glCheckFramebufferStatus(target); - } - - @Override - public void compileShader(int shader) { - GLES20.glCompileShader(shader); - } - - @Override - public int createProgram() { - return GLES20.glCreateProgram(); - } - - @Override - public int createShader(int type) { - return GLES20.glCreateShader(type); - } - - @Override - public void deleteBuffers(int n, IntBuffer buffers) { - GLES20.glDeleteBuffers(n, buffers); - } - - @Override - public void deleteFramebuffers(int n, IntBuffer framebuffers) { - GLES20.glDeleteFramebuffers(n, framebuffers); - } - - @Override - public void deleteProgram(int program) { - GLES20.glDeleteProgram(program); - } - - @Override - public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { - GLES20.glDeleteRenderbuffers(n, renderbuffers); - } - - @Override - public void deleteShader(int shader) { - GLES20.glDeleteShader(shader); - } - - @Override - public void detachShader(int program, int shader) { - GLES20.glDetachShader(program, shader); - } - - @Override - public void disableVertexAttribArray(int index) { - GLES20.glDisableVertexAttribArray(index); - } - - @Override - public void drawElements(int mode, int count, int type, int offset) { - GLES20.glDrawElements(mode, count, type, offset); - } - - @Override - public void enableVertexAttribArray(int index) { - GLES20.glEnableVertexAttribArray(index); - } - - @Override - public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, - int renderbuffer) { - GLES20.glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); - } - - @Override - public void framebufferTexture2D(int target, int attachment, int textarget, int texture, - int level) { - GLES20.glFramebufferTexture2D(target, attachment, textarget, texture, level); - } - - @Override - public void genBuffers(int n, IntBuffer buffers) { - GLES20.glGenBuffers(n, buffers); - } - - @Override - public void generateMipmap(int target) { - GLES20.glGenerateMipmap(target); - } - - @Override - public void genFramebuffers(int n, IntBuffer framebuffers) { - GLES20.glGenFramebuffers(n, framebuffers); - } - - @Override - public void genRenderbuffers(int n, IntBuffer renderbuffers) { - GLES20.glGenRenderbuffers(n, renderbuffers); - } - - @Override - public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { - return GLES20.glGetActiveAttrib(program, index, size, (IntBuffer) type); - } - - @Override - public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { - //return GLES20.glGetActiveUniform(program, index, bufsize, length, size, type, name); - throw new UnsupportedOperationException("missing implementation"); - } - - @Override - public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { - throw new UnsupportedOperationException("missing implementation"); - //GLES20.glGetAttachedShaders(program, maxcount, count, shaders); - } - - @Override - public int getAttribLocation(int program, String name) { - return GLES20.glGetAttribLocation(program, name); - } - - @Override - public void getBooleanv(int pname, Buffer params) { - throw new UnsupportedOperationException("missing implementation"); - //GLES20.glGetBooleanv(pname, params); - } - - @Override - public void getBufferParameteriv(int target, int pname, IntBuffer params) { - GLES20.glGetBufferParameteriv(target, pname, params); - - } - - @Override - public void getFloatv(int pname, FloatBuffer params) { - GLES20.glGetFloatv(pname, params); - - } - - @Override - public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, - IntBuffer params) { - GLES20.glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); - } - - @Override - public void getProgramiv(int program, int pname, IntBuffer params) { - GLES20.glGetProgramiv(program, pname, params); - - } - - @Override - public String getProgramInfoLog(int program) { - return GLES20.glGetProgramInfoLog(program); - } - - @Override - public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { - GLES20.glGetRenderbufferParameteriv(target, pname, params); - - } - - @Override - public void getShaderiv(int shader, int pname, IntBuffer params) { - GLES20.glGetShaderiv(shader, pname, params); - - } - - @Override - public String getShaderInfoLog(int shader) { - return GLES20.glGetShaderInfoLog(shader); - } - - @Override - public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, - IntBuffer precision) { - GLES20.glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); - } + @Override + public void attachShader(int program, int shader) { + GLES20.glAttachShader(program, shader); + } + + @Override + public void bindAttribLocation(int program, int index, String name) { + GLES20.glBindAttribLocation(program, index, name); + } + + @Override + public void bindBuffer(int target, int buffer) { + GLES20.glBindBuffer(target, buffer); + } + + @Override + public void bindFramebuffer(int target, int framebuffer) { + GLES20.glBindFramebuffer(target, framebuffer); + } + + @Override + public void bindRenderbuffer(int target, int renderbuffer) { + GLES20.glBindRenderbuffer(target, renderbuffer); + } + + @Override + public void blendColor(float red, float green, float blue, float alpha) { + GLES20.glBlendColor(red, green, blue, alpha); + } + + @Override + public void blendEquation(int mode) { + GLES20.glBlendEquation(mode); + } + + @Override + public void blendEquationSeparate(int modeRGB, int modeAlpha) { + GLES20.glBlendEquationSeparate(modeRGB, modeAlpha); + } + + @Override + public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + GLES20.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + + @Override + public void bufferData(int target, int size, Buffer data, int usage) { + GLES20.glBufferData(target, size, data, usage); + } + + @Override + public void bufferSubData(int target, int offset, int size, Buffer data) { + GLES20.glBufferSubData(target, offset, size, data); + } + + @Override + public int checkFramebufferStatus(int target) { + return GLES20.glCheckFramebufferStatus(target); + } + + @Override + public void compileShader(int shader) { + GLES20.glCompileShader(shader); + } + + @Override + public int createProgram() { + return GLES20.glCreateProgram(); + } + + @Override + public int createShader(int type) { + return GLES20.glCreateShader(type); + } + + @Override + public void deleteBuffers(int n, IntBuffer buffers) { + GLES20.glDeleteBuffers(n, buffers); + } + + @Override + public void deleteFramebuffers(int n, IntBuffer framebuffers) { + GLES20.glDeleteFramebuffers(n, framebuffers); + } + + @Override + public void deleteProgram(int program) { + GLES20.glDeleteProgram(program); + } + + @Override + public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { + GLES20.glDeleteRenderbuffers(n, renderbuffers); + } + + @Override + public void deleteShader(int shader) { + GLES20.glDeleteShader(shader); + } + + @Override + public void detachShader(int program, int shader) { + GLES20.glDetachShader(program, shader); + } + + @Override + public void disableVertexAttribArray(int index) { + GLES20.glDisableVertexAttribArray(index); + } + + @Override + public void drawElements(int mode, int count, int type, int offset) { + GLES20.glDrawElements(mode, count, type, offset); + } + + @Override + public void enableVertexAttribArray(int index) { + GLES20.glEnableVertexAttribArray(index); + } + + @Override + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, + int renderbuffer) { + GLES20.glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + } + + @Override + public void framebufferTexture2D(int target, int attachment, int textarget, int texture, + int level) { + GLES20.glFramebufferTexture2D(target, attachment, textarget, texture, level); + } + + @Override + public void genBuffers(int n, IntBuffer buffers) { + GLES20.glGenBuffers(n, buffers); + } + + @Override + public void generateMipmap(int target) { + GLES20.glGenerateMipmap(target); + } + + @Override + public void genFramebuffers(int n, IntBuffer framebuffers) { + GLES20.glGenFramebuffers(n, framebuffers); + } + + @Override + public void genRenderbuffers(int n, IntBuffer renderbuffers) { + GLES20.glGenRenderbuffers(n, renderbuffers); + } + + @Override + public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { + return GLES20.glGetActiveAttrib(program, index, size, (IntBuffer) type); + } + + @Override + public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { + //return GLES20.glGetActiveUniform(program, index, bufsize, length, size, type, name); + throw new UnsupportedOperationException("missing implementation"); + } + + @Override + public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { + throw new UnsupportedOperationException("missing implementation"); + //GLES20.glGetAttachedShaders(program, maxcount, count, shaders); + } + + @Override + public int getAttribLocation(int program, String name) { + return GLES20.glGetAttribLocation(program, name); + } + + @Override + public void getBooleanv(int pname, Buffer params) { + throw new UnsupportedOperationException("missing implementation"); + //GLES20.glGetBooleanv(pname, params); + } + + @Override + public void getBufferParameteriv(int target, int pname, IntBuffer params) { + GLES20.glGetBufferParameteriv(target, pname, params); + + } + + @Override + public void getFloatv(int pname, FloatBuffer params) { + GLES20.glGetFloatv(pname, params); + + } + + @Override + public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, + IntBuffer params) { + GLES20.glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); + } + + @Override + public void getProgramiv(int program, int pname, IntBuffer params) { + GLES20.glGetProgramiv(program, pname, params); + + } + + @Override + public String getProgramInfoLog(int program) { + return GLES20.glGetProgramInfoLog(program); + } + + @Override + public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { + GLES20.glGetRenderbufferParameteriv(target, pname, params); + + } + + @Override + public void getShaderiv(int shader, int pname, IntBuffer params) { + GLES20.glGetShaderiv(shader, pname, params); + + } + + @Override + public String getShaderInfoLog(int shader) { + return GLES20.glGetShaderInfoLog(shader); + } + + @Override + public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, + IntBuffer precision) { + GLES20.glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); + } - @Override - public void getShaderSource(int shader, int bufsize, Buffer length, String source) { - throw new UnsupportedOperationException("missing implementation"); - } + @Override + public void getShaderSource(int shader, int bufsize, Buffer length, String source) { + throw new UnsupportedOperationException("missing implementation"); + } - @Override - public void getTexParameterfv(int target, int pname, FloatBuffer params) { - GLES20.glGetTexParameterfv(target, pname, params); + @Override + public void getTexParameterfv(int target, int pname, FloatBuffer params) { + GLES20.glGetTexParameterfv(target, pname, params); - } + } - @Override - public void getTexParameteriv(int target, int pname, IntBuffer params) { - GLES20.glGetTexParameteriv(target, pname, params); + @Override + public void getTexParameteriv(int target, int pname, IntBuffer params) { + GLES20.glGetTexParameteriv(target, pname, params); - } + } - @Override - public void getUniformfv(int program, int location, FloatBuffer params) { - GLES20.glGetUniformfv(program, location, params); + @Override + public void getUniformfv(int program, int location, FloatBuffer params) { + GLES20.glGetUniformfv(program, location, params); - } + } - @Override - public void getUniformiv(int program, int location, IntBuffer params) { - GLES20.glGetUniformiv(program, location, params); + @Override + public void getUniformiv(int program, int location, IntBuffer params) { + GLES20.glGetUniformiv(program, location, params); - } + } - @Override - public int getUniformLocation(int program, String name) { - return GLES20.glGetUniformLocation(program, name); - } + @Override + public int getUniformLocation(int program, String name) { + return GLES20.glGetUniformLocation(program, name); + } - @Override - public void getVertexAttribfv(int index, int pname, FloatBuffer params) { - GLES20.glGetVertexAttribfv(index, pname, params); + @Override + public void getVertexAttribfv(int index, int pname, FloatBuffer params) { + GLES20.glGetVertexAttribfv(index, pname, params); - } + } - @Override - public void getVertexAttribiv(int index, int pname, IntBuffer params) { - GLES20.glGetVertexAttribiv(index, pname, params); + @Override + public void getVertexAttribiv(int index, int pname, IntBuffer params) { + GLES20.glGetVertexAttribiv(index, pname, params); - } + } - @Override - public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { - //GLES20.glGetVertexAttribPointerv(index, pname, pointer); - throw new UnsupportedOperationException("missing implementation"); - } + @Override + public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { + //GLES20.glGetVertexAttribPointerv(index, pname, pointer); + throw new UnsupportedOperationException("missing implementation"); + } - @Override - public boolean isBuffer(int buffer) { - return GLES20.glIsBuffer(buffer); - } + @Override + public boolean isBuffer(int buffer) { + return GLES20.glIsBuffer(buffer); + } - @Override - public boolean isEnabled(int cap) { - return GLES20.glIsEnabled(cap); - } + @Override + public boolean isEnabled(int cap) { + return GLES20.glIsEnabled(cap); + } - @Override - public boolean isFramebuffer(int framebuffer) { - return GLES20.glIsFramebuffer(framebuffer); - } + @Override + public boolean isFramebuffer(int framebuffer) { + return GLES20.glIsFramebuffer(framebuffer); + } - @Override - public boolean isProgram(int program) { - return GLES20.glIsProgram(program); - } + @Override + public boolean isProgram(int program) { + return GLES20.glIsProgram(program); + } - @Override - public boolean isRenderbuffer(int renderbuffer) { - return GLES20.glIsRenderbuffer(renderbuffer); - } + @Override + public boolean isRenderbuffer(int renderbuffer) { + return GLES20.glIsRenderbuffer(renderbuffer); + } - @Override - public boolean isShader(int shader) { - return GLES20.glIsShader(shader); - } + @Override + public boolean isShader(int shader) { + return GLES20.glIsShader(shader); + } - @Override - public boolean isTexture(int texture) { - return GLES20.glIsTexture(texture); - } + @Override + public boolean isTexture(int texture) { + return GLES20.glIsTexture(texture); + } - @Override - public void linkProgram(int program) { - GLES20.glLinkProgram(program); + @Override + public void linkProgram(int program) { + GLES20.glLinkProgram(program); - } + } - @Override - public void releaseShaderCompiler() { - GLES20.glReleaseShaderCompiler(); + @Override + public void releaseShaderCompiler() { + GLES20.glReleaseShaderCompiler(); - } + } - @Override - public void renderbufferStorage(int target, int internalformat, int width, int height) { - GLES20.glRenderbufferStorage(target, internalformat, width, height); + @Override + public void renderbufferStorage(int target, int internalformat, int width, int height) { + GLES20.glRenderbufferStorage(target, internalformat, width, height); - } + } - @Override - public void sampleCoverage(float value, boolean invert) { - GLES20.glSampleCoverage(value, invert); + @Override + public void sampleCoverage(float value, boolean invert) { + GLES20.glSampleCoverage(value, invert); - } + } - @Override - public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { - GLES20.glShaderBinary(n, shaders, binaryformat, binary, length); + @Override + public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { + GLES20.glShaderBinary(n, shaders, binaryformat, binary, length); - } + } - @Override - public void shaderSource(int shader, String string) { - GLES20.glShaderSource(shader, string); + @Override + public void shaderSource(int shader, String string) { + GLES20.glShaderSource(shader, string); - } + } - @Override - public void stencilFuncSeparate(int face, int func, int ref, int mask) { - GLES20.glStencilFuncSeparate(face, func, ref, mask); + @Override + public void stencilFuncSeparate(int face, int func, int ref, int mask) { + GLES20.glStencilFuncSeparate(face, func, ref, mask); - } + } - @Override - public void stencilMaskSeparate(int face, int mask) { - GLES20.glStencilMaskSeparate(face, mask); + @Override + public void stencilMaskSeparate(int face, int mask) { + GLES20.glStencilMaskSeparate(face, mask); - } + } - @Override - public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { - GLES20.glStencilOpSeparate(face, fail, zfail, zpass); + @Override + public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { + GLES20.glStencilOpSeparate(face, fail, zfail, zpass); - } + } - @Override - public void texParameterfv(int target, int pname, FloatBuffer params) { - GLES20.glTexParameterfv(target, pname, params); + @Override + public void texParameterfv(int target, int pname, FloatBuffer params) { + GLES20.glTexParameterfv(target, pname, params); - } + } - @Override - public void texParameteri(int target, int pname, int param) { - GLES20.glTexParameteri(target, pname, param); + @Override + public void texParameteri(int target, int pname, int param) { + GLES20.glTexParameteri(target, pname, param); - } + } - @Override - public void texParameteriv(int target, int pname, IntBuffer params) { - GLES20.glTexParameteriv(target, pname, params); + @Override + public void texParameteriv(int target, int pname, IntBuffer params) { + GLES20.glTexParameteriv(target, pname, params); - } + } - @Override - public void uniform1f(int location, float x) { - GLES20.glUniform1f(location, x); + @Override + public void uniform1f(int location, float x) { + GLES20.glUniform1f(location, x); - } + } - @Override - public void uniform1fv(int location, int count, FloatBuffer v) { - GLES20.glUniform1fv(location, count, v); + @Override + public void uniform1fv(int location, int count, FloatBuffer v) { + GLES20.glUniform1fv(location, count, v); - } + } - @Override - public void uniform1i(int location, int x) { - GLES20.glUniform1i(location, x); + @Override + public void uniform1i(int location, int x) { + GLES20.glUniform1i(location, x); - } + } - @Override - public void uniform1iv(int location, int count, IntBuffer v) { - GLES20.glUniform1iv(location, count, v); + @Override + public void uniform1iv(int location, int count, IntBuffer v) { + GLES20.glUniform1iv(location, count, v); - } + } - @Override - public void uniform2f(int location, float x, float y) { - GLES20.glUniform2f(location, x, y); + @Override + public void uniform2f(int location, float x, float y) { + GLES20.glUniform2f(location, x, y); - } + } - @Override - public void uniform2fv(int location, int count, FloatBuffer v) { - GLES20.glUniform2fv(location, count, v); + @Override + public void uniform2fv(int location, int count, FloatBuffer v) { + GLES20.glUniform2fv(location, count, v); - } + } - @Override - public void uniform2i(int location, int x, int y) { - GLES20.glUniform2i(location, x, y); + @Override + public void uniform2i(int location, int x, int y) { + GLES20.glUniform2i(location, x, y); - } + } - @Override - public void uniform2iv(int location, int count, IntBuffer v) { - GLES20.glUniform2iv(location, count, v); + @Override + public void uniform2iv(int location, int count, IntBuffer v) { + GLES20.glUniform2iv(location, count, v); - } + } - @Override - public void uniform3f(int location, float x, float y, float z) { - GLES20.glUniform3f(location, x, y, z); + @Override + public void uniform3f(int location, float x, float y, float z) { + GLES20.glUniform3f(location, x, y, z); - } + } - @Override - public void uniform3fv(int location, int count, FloatBuffer v) { - GLES20.glUniform3fv(location, count, v); + @Override + public void uniform3fv(int location, int count, FloatBuffer v) { + GLES20.glUniform3fv(location, count, v); - } + } - @Override - public void uniform3i(int location, int x, int y, int z) { - GLES20.glUniform3i(location, x, y, z); + @Override + public void uniform3i(int location, int x, int y, int z) { + GLES20.glUniform3i(location, x, y, z); - } + } - @Override - public void uniform3iv(int location, int count, IntBuffer v) { - GLES20.glUniform3iv(location, count, v); + @Override + public void uniform3iv(int location, int count, IntBuffer v) { + GLES20.glUniform3iv(location, count, v); - } + } - @Override - public void uniform4f(int location, float x, float y, float z, float w) { - GLES20.glUniform4f(location, x, y, z, w); - } + @Override + public void uniform4f(int location, float x, float y, float z, float w) { + GLES20.glUniform4f(location, x, y, z, w); + } - @Override - public void uniform4fv(int location, int count, FloatBuffer v) { - GLES20.glUniform4fv(location, count, v); - } + @Override + public void uniform4fv(int location, int count, FloatBuffer v) { + GLES20.glUniform4fv(location, count, v); + } - @Override - public void uniform4i(int location, int x, int y, int z, int w) { - GLES20.glUniform4i(location, x, y, z, w); + @Override + public void uniform4i(int location, int x, int y, int z, int w) { + GLES20.glUniform4i(location, x, y, z, w); - } + } - @Override - public void uniform4iv(int location, int count, IntBuffer v) { - GLES20.glUniform4iv(location, count, v); + @Override + public void uniform4iv(int location, int count, IntBuffer v) { + GLES20.glUniform4iv(location, count, v); - } + } - @Override - public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { - GLES20.glUniformMatrix2fv(location, count, transpose, value); + @Override + public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { + GLES20.glUniformMatrix2fv(location, count, transpose, value); - } + } - @Override - public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { - GLES20.glUniformMatrix3fv(location, count, transpose, value); + @Override + public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { + GLES20.glUniformMatrix3fv(location, count, transpose, value); - } + } - @Override - public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { - GLES20.glUniformMatrix4fv(location, count, transpose, value); + @Override + public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { + GLES20.glUniformMatrix4fv(location, count, transpose, value); - } + } - @Override - public void useProgram(int program) { - GLES20.glUseProgram(program); + @Override + public void useProgram(int program) { + GLES20.glUseProgram(program); - } + } - @Override - public void validateProgram(int program) { - GLES20.glValidateProgram(program); + @Override + public void validateProgram(int program) { + GLES20.glValidateProgram(program); - } + } - @Override - public void vertexAttrib1f(int indx, float x) { - GLES20.glVertexAttrib1f(indx, x); + @Override + public void vertexAttrib1f(int indx, float x) { + GLES20.glVertexAttrib1f(indx, x); - } + } - @Override - public void vertexAttrib1fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib1fv(indx, values); + @Override + public void vertexAttrib1fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib1fv(indx, values); - } + } - @Override - public void vertexAttrib2f(int indx, float x, float y) { - GLES20.glVertexAttrib2f(indx, x, y); + @Override + public void vertexAttrib2f(int indx, float x, float y) { + GLES20.glVertexAttrib2f(indx, x, y); - } + } - @Override - public void vertexAttrib2fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib2fv(indx, values); + @Override + public void vertexAttrib2fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib2fv(indx, values); - } + } - @Override - public void vertexAttrib3f(int indx, float x, float y, float z) { - GLES20.glVertexAttrib3f(indx, x, y, z); + @Override + public void vertexAttrib3f(int indx, float x, float y, float z) { + GLES20.glVertexAttrib3f(indx, x, y, z); - } + } - @Override - public void vertexAttrib3fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib3fv(indx, values); + @Override + public void vertexAttrib3fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib3fv(indx, values); - } + } - @Override - public void vertexAttrib4f(int indx, float x, float y, float z, float w) { - GLES20.glVertexAttrib4f(indx, x, y, z, w); + @Override + public void vertexAttrib4f(int indx, float x, float y, float z, float w) { + GLES20.glVertexAttrib4f(indx, x, y, z, w); - } + } - @Override - public void vertexAttrib4fv(int indx, FloatBuffer values) { - GLES20.glVertexAttrib4fv(indx, values); + @Override + public void vertexAttrib4fv(int indx, FloatBuffer values) { + GLES20.glVertexAttrib4fv(indx, values); - } + } - @Override - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - Buffer ptr) { - GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); - } + @Override + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + Buffer ptr) { + GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); + } - @Override - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - int offset) { - // FIXME check implementation! - GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, offset); - //throw new UnsupportedOperationException("missing implementation"); - } + @Override + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + int offset) { + // FIXME check implementation! + GLES20.glVertexAttribPointer(indx, size, type, normalized, stride, offset); + //throw new UnsupportedOperationException("missing implementation"); + } - @Override - public void activeTexture(int texture) { - GLES20.glActiveTexture(texture); + @Override + public void activeTexture(int texture) { + GLES20.glActiveTexture(texture); - } + } - @Override - public void bindTexture(int target, int texture) { - GLES20.glBindTexture(target, texture); + @Override + public void bindTexture(int target, int texture) { + GLES20.glBindTexture(target, texture); - } + } - @Override - public void blendFunc(int sfactor, int dfactor) { - GLES20.glBlendFunc(sfactor, dfactor); + @Override + public void blendFunc(int sfactor, int dfactor) { + GLES20.glBlendFunc(sfactor, dfactor); - } + } - @Override - public void clear(int mask) { - GLES20.glClear(mask); + @Override + public void clear(int mask) { + GLES20.glClear(mask); - } + } - @Override - public void clearColor(float red, float green, float blue, float alpha) { - GLES20.glClearColor(red, green, blue, alpha); + @Override + public void clearColor(float red, float green, float blue, float alpha) { + GLES20.glClearColor(red, green, blue, alpha); - } + } - @Override - public void clearDepthf(float depth) { - GLES20.glClearDepthf(depth); + @Override + public void clearDepthf(float depth) { + GLES20.glClearDepthf(depth); - } + } - @Override - public void clearStencil(int s) { - GLES20.glClearStencil(s); + @Override + public void clearStencil(int s) { + GLES20.glClearStencil(s); - } + } - @Override - public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - GLES20.glColorMask(red, green, blue, alpha); + @Override + public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + GLES20.glColorMask(red, green, blue, alpha); - } + } - @Override - public void compressedTexImage2D(int target, int level, int internalformat, int width, - int height, int border, int imageSize, Buffer data) { - throw new UnsupportedOperationException("missing implementation"); + @Override + public void compressedTexImage2D(int target, int level, int internalformat, int width, + int height, int border, int imageSize, Buffer data) { + throw new UnsupportedOperationException("missing implementation"); - } + } - @Override - public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, - int width, int height, int format, int imageSize, Buffer data) { - throw new UnsupportedOperationException("missing implementation"); + @Override + public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, + int width, int height, int format, int imageSize, Buffer data) { + throw new UnsupportedOperationException("missing implementation"); - } + } - @Override - public void copyTexImage2D(int target, int level, int internalformat, int x, int y, - int width, int height, int border) { - GLES20.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); - } + @Override + public void copyTexImage2D(int target, int level, int internalformat, int x, int y, + int width, int height, int border) { + GLES20.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + } - @Override - public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, - int width, int height) { - GLES20.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); - } + @Override + public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, + int width, int height) { + GLES20.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + } - @Override - public void cullFace(int mode) { - GLES20.glCullFace(mode); + @Override + public void cullFace(int mode) { + GLES20.glCullFace(mode); - } + } - @Override - public void deleteTextures(int n, IntBuffer textures) { - GLES20.glDeleteTextures(n, textures); + @Override + public void deleteTextures(int n, IntBuffer textures) { + GLES20.glDeleteTextures(n, textures); - } + } - @Override - public void depthFunc(int func) { - GLES20.glDepthFunc(func); + @Override + public void depthFunc(int func) { + GLES20.glDepthFunc(func); - } + } - @Override - public void depthMask(boolean flag) { - GLES20.glDepthMask(flag); + @Override + public void depthMask(boolean flag) { + GLES20.glDepthMask(flag); - } + } - @Override - public void depthRangef(float zNear, float zFar) { - GLES20.glDepthRangef(zNear, zFar); + @Override + public void depthRangef(float zNear, float zFar) { + GLES20.glDepthRangef(zNear, zFar); - } + } - @Override - public void disable(int cap) { - GLES20.glDisable(cap); + @Override + public void disable(int cap) { + GLES20.glDisable(cap); - } + } - @Override - public void drawArrays(int mode, int first, int count) { - GLES20.glDrawArrays(mode, first, count); + @Override + public void drawArrays(int mode, int first, int count) { + GLES20.glDrawArrays(mode, first, count); - } + } - @Override - public void drawElements(int mode, int count, int type, Buffer indices) { - GLES20.glDrawElements(mode, count, type, indices); + @Override + public void drawElements(int mode, int count, int type, Buffer indices) { + GLES20.glDrawElements(mode, count, type, indices); - } + } - @Override - public void enable(int cap) { - GLES20.glEnable(cap); + @Override + public void enable(int cap) { + GLES20.glEnable(cap); - } + } - @Override - public void finish() { - GLES20.glFinish(); + @Override + public void finish() { + GLES20.glFinish(); - } + } - @Override - public void flush() { - GLES20.glFlush(); + @Override + public void flush() { + GLES20.glFlush(); - } + } - @Override - public void frontFace(int mode) { - GLES20.glFrontFace(mode); + @Override + public void frontFace(int mode) { + GLES20.glFrontFace(mode); - } + } - @Override - public void genTextures(int n, IntBuffer textures) { - GLES20.glGenTextures(n, textures); + @Override + public void genTextures(int n, IntBuffer textures) { + GLES20.glGenTextures(n, textures); - } + } - @Override - public int getError() { - return GLES20.glGetError(); - } + @Override + public int getError() { + return GLES20.glGetError(); + } - @Override - public void getIntegerv(int pname, IntBuffer params) { - GLES20.glGetIntegerv(pname, params); + @Override + public void getIntegerv(int pname, IntBuffer params) { + GLES20.glGetIntegerv(pname, params); - } + } - @Override - public String getString(int name) { - return GLES20.glGetString(name); - } + @Override + public String getString(int name) { + return GLES20.glGetString(name); + } - @Override - public void hint(int target, int mode) { - GLES20.glHint(target, mode); - } + @Override + public void hint(int target, int mode) { + GLES20.glHint(target, mode); + } - @Override - public void lineWidth(float width) { - GLES20.glLineWidth(width); + @Override + public void lineWidth(float width) { + GLES20.glLineWidth(width); - } + } - @Override - public void pixelStorei(int pname, int param) { - GLES20.glPixelStorei(pname, param); + @Override + public void pixelStorei(int pname, int param) { + GLES20.glPixelStorei(pname, param); - } + } - @Override - public void polygonOffset(float factor, float units) { - GLES20.glPolygonOffset(factor, units); + @Override + public void polygonOffset(float factor, float units) { + GLES20.glPolygonOffset(factor, units); - } + } - @Override - public void readPixels(int x, int y, int width, int height, int format, int type, - Buffer pixels) { - GLES20.glReadPixels(x, y, width, height, format, type, pixels); - } + @Override + public void readPixels(int x, int y, int width, int height, int format, int type, + Buffer pixels) { + GLES20.glReadPixels(x, y, width, height, format, type, pixels); + } - @Override - public void scissor(int x, int y, int width, int height) { - GLES20.glScissor(x, y, width, height); - } + @Override + public void scissor(int x, int y, int width, int height) { + GLES20.glScissor(x, y, width, height); + } - @Override - public void stencilFunc(int func, int ref, int mask) { - GLES20.glStencilFunc(func, ref, mask); - } + @Override + public void stencilFunc(int func, int ref, int mask) { + GLES20.glStencilFunc(func, ref, mask); + } - @Override - public void stencilMask(int mask) { - GLES20.glStencilMask(mask); - } + @Override + public void stencilMask(int mask) { + GLES20.glStencilMask(mask); + } - @Override - public void stencilOp(int fail, int zfail, int zpass) { - GLES20.glStencilOp(fail, zfail, zpass); - } + @Override + public void stencilOp(int fail, int zfail, int zpass) { + GLES20.glStencilOp(fail, zfail, zpass); + } - @Override - public void texImage2D(int target, int level, int internalformat, int width, int height, - int border, int format, int type, Buffer pixels) { - GLES20.glTexImage2D(target, level, internalformat, width, height, border, format, type, - pixels); - } + @Override + public void texImage2D(int target, int level, int internalformat, int width, int height, + int border, int format, int type, Buffer pixels) { + GLES20.glTexImage2D(target, level, internalformat, width, height, border, format, type, + pixels); + } - @Override - public void texParameterf(int target, int pname, float param) { - GLES20.glTexParameterf(target, pname, param); - } + @Override + public void texParameterf(int target, int pname, float param) { + GLES20.glTexParameterf(target, pname, param); + } - @Override - public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, - int height, int format, int type, Buffer pixels) { - GLES20 - .glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); + @Override + public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, + int height, int format, int type, Buffer pixels) { + GLES20 + .glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); - } + } - @Override - public void viewport(int x, int y, int width, int height) { - GLES20.glViewport(x, y, width, height); - } + @Override + public void viewport(int x, int y, int width, int height) { + GLES20.glViewport(x, y, width, height); + } } diff --git a/vtm-android/src/org/oscim/android/gl/GlConfigChooser.java b/vtm-android/src/org/oscim/android/gl/GlConfigChooser.java index 88987ea7..ca33519f 100644 --- a/vtm-android/src/org/oscim/android/gl/GlConfigChooser.java +++ b/vtm-android/src/org/oscim/android/gl/GlConfigChooser.java @@ -1,72 +1,72 @@ package org.oscim.android.gl; +import android.opengl.GLSurfaceView; + import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; -import android.opengl.GLSurfaceView; - public class GlConfigChooser implements GLSurfaceView.EGLConfigChooser { - @Override - public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { - int[] val = new int[1]; + @Override + public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { + int[] val = new int[1]; - // Try to find a normal multisample configuration first. - int[] configSpec = { - EGL10.EGL_RED_SIZE, 5, - EGL10.EGL_GREEN_SIZE, 6, - EGL10.EGL_BLUE_SIZE, 5, - EGL10.EGL_ALPHA_SIZE, 8, - EGL10.EGL_DEPTH_SIZE, 16, - // Requires that setEGLContextClientVersion(2) is called on the view. - EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */, - EGL10.EGL_STENCIL_SIZE, 8, - EGL10.EGL_NONE }; + // Try to find a normal multisample configuration first. + int[] configSpec = { + EGL10.EGL_RED_SIZE, 5, + EGL10.EGL_GREEN_SIZE, 6, + EGL10.EGL_BLUE_SIZE, 5, + EGL10.EGL_ALPHA_SIZE, 8, + EGL10.EGL_DEPTH_SIZE, 16, + // Requires that setEGLContextClientVersion(2) is called on the view. + EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */, + EGL10.EGL_STENCIL_SIZE, 8, + EGL10.EGL_NONE}; - if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) { - throw new IllegalArgumentException("eglChooseConfig failed"); - } - int numConfigs = val[0]; + if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) { + throw new IllegalArgumentException("eglChooseConfig failed"); + } + int numConfigs = val[0]; - if (numConfigs <= 0) { + if (numConfigs <= 0) { - configSpec = new int[] { - // EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_NONE }; - EGL10.EGL_RED_SIZE, 8, - EGL10.EGL_GREEN_SIZE, 8, - EGL10.EGL_BLUE_SIZE, 8, - EGL10.EGL_ALPHA_SIZE, 8, - EGL10.EGL_DEPTH_SIZE, 16, - EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */, - EGL10.EGL_STENCIL_SIZE, 8, - EGL10.EGL_NONE }; + configSpec = new int[]{ + // EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_NONE }; + EGL10.EGL_RED_SIZE, 8, + EGL10.EGL_GREEN_SIZE, 8, + EGL10.EGL_BLUE_SIZE, 8, + EGL10.EGL_ALPHA_SIZE, 8, + EGL10.EGL_DEPTH_SIZE, 16, + EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */, + EGL10.EGL_STENCIL_SIZE, 8, + EGL10.EGL_NONE}; - if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) { - throw new IllegalArgumentException("eglChooseConfig failed"); - } - numConfigs = val[0]; + if (!egl.eglChooseConfig(display, configSpec, null, 0, val)) { + throw new IllegalArgumentException("eglChooseConfig failed"); + } + numConfigs = val[0]; - if (numConfigs <= 0) { - throw new IllegalArgumentException("No configs match configSpec"); - } - } + if (numConfigs <= 0) { + throw new IllegalArgumentException("No configs match configSpec"); + } + } - // Get all matching configurations. - EGLConfig[] configs = new EGLConfig[numConfigs]; - if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, val)) { - throw new IllegalArgumentException("data eglChooseConfig failed"); - } + // Get all matching configurations. + EGLConfig[] configs = new EGLConfig[numConfigs]; + if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, val)) { + throw new IllegalArgumentException("data eglChooseConfig failed"); + } - // CAUTION! eglChooseConfigs returns configs with higher bit depth - // first: Even though we asked for rgb565 configurations, rgb888 - // configurations are considered to be "better" and returned first. - // You need to explicitly filter the data returned by eglChooseConfig! + // CAUTION! eglChooseConfigs returns configs with higher bit depth + // first: Even though we asked for rgb565 configurations, rgb888 + // configurations are considered to be "better" and returned first. + // You need to explicitly filter the data returned by eglChooseConfig! - EGLConfig config = configs.length > 0 ? configs[0] : null; - if (config == null) { - throw new IllegalArgumentException("No config chosen"); - } - return config; - } + EGLConfig config = configs.length > 0 ? configs[0] : null; + if (config == null) { + throw new IllegalArgumentException("No config chosen"); + } + return config; + } } diff --git a/vtm-android/src/org/oscim/android/input/AndroidMotionEvent.java b/vtm-android/src/org/oscim/android/input/AndroidMotionEvent.java index 58e4bda1..06ff61b0 100644 --- a/vtm-android/src/org/oscim/android/input/AndroidMotionEvent.java +++ b/vtm-android/src/org/oscim/android/input/AndroidMotionEvent.java @@ -20,46 +20,46 @@ import org.oscim.event.MotionEvent; public class AndroidMotionEvent extends MotionEvent { - android.view.MotionEvent mEvent; + android.view.MotionEvent mEvent; - public MotionEvent wrap(android.view.MotionEvent e) { - mEvent = e; - return this; - } + public MotionEvent wrap(android.view.MotionEvent e) { + mEvent = e; + return this; + } - @Override - public int getAction() { - return mEvent.getAction(); - } + @Override + public int getAction() { + return mEvent.getAction(); + } - @Override - public float getX() { - return mEvent.getX(); - } + @Override + public float getX() { + return mEvent.getX(); + } - @Override - public float getY() { - return mEvent.getY(); - } + @Override + public float getY() { + return mEvent.getY(); + } - @Override - public float getX(int pointer) { - return mEvent.getX(pointer); - } + @Override + public float getX(int pointer) { + return mEvent.getX(pointer); + } - @Override - public float getY(int pointer) { - return mEvent.getY(pointer); - } + @Override + public float getY(int pointer) { + return mEvent.getY(pointer); + } - @Override - public int getPointerCount() { - return mEvent.getPointerCount(); - } + @Override + public int getPointerCount() { + return mEvent.getPointerCount(); + } - @Override - public long getTime() { - return mEvent.getEventTime(); - } + @Override + public long getTime() { + return mEvent.getEventTime(); + } } diff --git a/vtm-android/src/org/oscim/android/input/GestureHandler.java b/vtm-android/src/org/oscim/android/input/GestureHandler.java index 2840137c..3dd3e97d 100644 --- a/vtm-android/src/org/oscim/android/input/GestureHandler.java +++ b/vtm-android/src/org/oscim/android/input/GestureHandler.java @@ -1,66 +1,66 @@ package org.oscim.android.input; -import org.oscim.event.Gesture; -import org.oscim.map.Map; - import android.view.GestureDetector.OnDoubleTapListener; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; -public class GestureHandler implements OnGestureListener, OnDoubleTapListener { - private final AndroidMotionEvent mMotionEvent; - private final Map mMap; +import org.oscim.event.Gesture; +import org.oscim.map.Map; - public GestureHandler(Map map) { - mMotionEvent = new AndroidMotionEvent(); - mMap = map; - } +public class GestureHandler implements OnGestureListener, OnDoubleTapListener { + private final AndroidMotionEvent mMotionEvent; + private final Map mMap; + + public GestureHandler(Map map) { + mMotionEvent = new AndroidMotionEvent(); + mMap = map; + } /* GesturListener */ - @Override - public boolean onSingleTapUp(MotionEvent e) { - // return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e)); - return false; - } + @Override + public boolean onSingleTapUp(MotionEvent e) { + // return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e)); + return false; + } - @Override - public void onShowPress(MotionEvent e) { - } + @Override + public void onShowPress(MotionEvent e) { + } - @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - return false; - } + @Override + public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { + return false; + } - @Override - public void onLongPress(MotionEvent e) { - mMap.handleGesture(Gesture.LONG_PRESS, mMotionEvent.wrap(e)); - } + @Override + public void onLongPress(MotionEvent e) { + mMap.handleGesture(Gesture.LONG_PRESS, mMotionEvent.wrap(e)); + } - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - return false; - } + @Override + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { + return false; + } - @Override - public boolean onDown(MotionEvent e) { - return mMap.handleGesture(Gesture.PRESS, mMotionEvent.wrap(e)); - } + @Override + public boolean onDown(MotionEvent e) { + return mMap.handleGesture(Gesture.PRESS, mMotionEvent.wrap(e)); + } - /* DoubleTapListener */ - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e)); - } + /* DoubleTapListener */ + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + return mMap.handleGesture(Gesture.TAP, mMotionEvent.wrap(e)); + } - @Override - public boolean onDoubleTapEvent(MotionEvent e) { - return false; - } + @Override + public boolean onDoubleTapEvent(MotionEvent e) { + return false; + } - @Override - public boolean onDoubleTap(MotionEvent e) { - return mMap.handleGesture(Gesture.DOUBLE_TAP, mMotionEvent.wrap(e)); - } + @Override + public boolean onDoubleTap(MotionEvent e) { + return mMap.handleGesture(Gesture.DOUBLE_TAP, mMotionEvent.wrap(e)); + } } diff --git a/vtm-desktop/build.gradle b/vtm-desktop/build.gradle index 897d7555..76171c02 100644 --- a/vtm-desktop/build.gradle +++ b/vtm-desktop/build.gradle @@ -14,7 +14,6 @@ dependencies { sourceSets { main { java.srcDirs = ['src'] - output.resourcesDir = 'assets' } } diff --git a/vtm-desktop/src/org/oscim/awt/AwtBitmap.java b/vtm-desktop/src/org/oscim/awt/AwtBitmap.java index 990cf04a..d442fc77 100644 --- a/vtm-desktop/src/org/oscim/awt/AwtBitmap.java +++ b/vtm-desktop/src/org/oscim/awt/AwtBitmap.java @@ -17,6 +17,13 @@ */ package org.oscim.awt; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.utils.BufferUtils; + +import org.oscim.backend.GL; +import org.oscim.backend.canvas.Bitmap; +import org.oscim.renderer.bucket.TextureBucket; + import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; @@ -25,130 +32,123 @@ import java.nio.IntBuffer; import javax.imageio.ImageIO; -import org.oscim.backend.GL; -import org.oscim.backend.canvas.Bitmap; -import org.oscim.renderer.bucket.TextureBucket; - -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.utils.BufferUtils; - public class AwtBitmap implements Bitmap { - BufferedImage bitmap; - int width; - int height; + BufferedImage bitmap; + int width; + int height; - boolean internal; + boolean internal; - public AwtBitmap(int width, int height, int format) { - bitmap = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - this.width = width; - this.height = height; + public AwtBitmap(int width, int height, int format) { + bitmap = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + this.width = width; + this.height = height; - internal = true; - // if (!this.bitmap.isAlphaPremultiplied()) - // this.bitmap.coerceData(true); - } + internal = true; + // if (!this.bitmap.isAlphaPremultiplied()) + // this.bitmap.coerceData(true); + } - AwtBitmap(InputStream inputStream) throws IOException { + AwtBitmap(InputStream inputStream) throws IOException { - this.bitmap = ImageIO.read(inputStream); - this.width = this.bitmap.getWidth(); - this.height = this.bitmap.getHeight(); - if (!this.bitmap.isAlphaPremultiplied() - && this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB) - this.bitmap.coerceData(true); - } + this.bitmap = ImageIO.read(inputStream); + this.width = this.bitmap.getWidth(); + this.height = this.bitmap.getHeight(); + if (!this.bitmap.isAlphaPremultiplied() + && this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB) + this.bitmap.coerceData(true); + } - public AwtBitmap(BufferedImage bitmap) { - this.bitmap = bitmap; - this.width = this.bitmap.getWidth(); - this.height = this.bitmap.getHeight(); - if (!this.bitmap.isAlphaPremultiplied() - && this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB) - this.bitmap.coerceData(true); - } + public AwtBitmap(BufferedImage bitmap) { + this.bitmap = bitmap; + this.width = this.bitmap.getWidth(); + this.height = this.bitmap.getHeight(); + if (!this.bitmap.isAlphaPremultiplied() + && this.bitmap.getType() == BufferedImage.TYPE_INT_ARGB) + this.bitmap.coerceData(true); + } - @Override - public int getWidth() { - return width; - } + @Override + public int getWidth() { + return width; + } - @Override - public int getHeight() { - return height; - } + @Override + public int getHeight() { + return height; + } - @Override - public int[] getPixels() { - return null; - } + @Override + public int[] getPixels() { + return null; + } - @Override - public void eraseColor(int transparent) { - } + @Override + public void eraseColor(int transparent) { + } - private final static IntBuffer tmpBuffer = BufferUtils - .newIntBuffer(TextureBucket.TEXTURE_HEIGHT - * TextureBucket.TEXTURE_WIDTH); - private final static int[] tmpPixel = new int[TextureBucket.TEXTURE_HEIGHT - * TextureBucket.TEXTURE_WIDTH]; + private final static IntBuffer tmpBuffer = BufferUtils + .newIntBuffer(TextureBucket.TEXTURE_HEIGHT + * TextureBucket.TEXTURE_WIDTH); + private final static int[] tmpPixel = new int[TextureBucket.TEXTURE_HEIGHT + * TextureBucket.TEXTURE_WIDTH]; - private final static boolean WRITE_TEX = false; - private int dbgCnt; + private final static boolean WRITE_TEX = false; + private int dbgCnt; - @Override - public void uploadToTexture(boolean replace) { - int[] pixels; - IntBuffer buffer; + @Override + public void uploadToTexture(boolean replace) { + int[] pixels; + IntBuffer buffer; - if (width * height < TextureBucket.TEXTURE_HEIGHT * TextureBucket.TEXTURE_WIDTH) { - pixels = tmpPixel; - buffer = tmpBuffer; - buffer.clear(); - } else { - pixels = new int[width * height]; - buffer = BufferUtils.newIntBuffer(width * height); - } + if (width * height < TextureBucket.TEXTURE_HEIGHT * TextureBucket.TEXTURE_WIDTH) { + pixels = tmpPixel; + buffer = tmpBuffer; + buffer.clear(); + } else { + pixels = new int[width * height]; + buffer = BufferUtils.newIntBuffer(width * height); + } - // FIXME dont convert to argb when there data is greyscale - bitmap.getRGB(0, 0, width, height, pixels, 0, width); + // FIXME dont convert to argb when there data is greyscale + bitmap.getRGB(0, 0, width, height, pixels, 0, width); - if (WRITE_TEX) { - try { - boolean ok = ImageIO.write(bitmap, "png", new File("texture_" + dbgCnt + ".png")); - System.out.println("write tex " + ok + " " + dbgCnt); - dbgCnt++; - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + if (WRITE_TEX) { + try { + boolean ok = ImageIO.write(bitmap, "png", new File("texture_" + dbgCnt + ".png")); + System.out.println("write tex " + ok + " " + dbgCnt); + dbgCnt++; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - for (int i = 0, n = width * height; i < n; i++) { - int c = pixels[i]; - if (c == 0) - continue; + for (int i = 0, n = width * height; i < n; i++) { + int c = pixels[i]; + if (c == 0) + continue; - float alpha = (c >>> 24) / 255f; - int r = (int) ((c & 0x000000ff) * alpha); - int b = (int) (((c & 0x00ff0000) >>> 16) * alpha); - int g = (int) (((c & 0x0000ff00) >>> 8) * alpha); - pixels[i] = (c & 0xff000000) | r << 16 | g << 8 | b; - } + float alpha = (c >>> 24) / 255f; + int r = (int) ((c & 0x000000ff) * alpha); + int b = (int) (((c & 0x00ff0000) >>> 16) * alpha); + int g = (int) (((c & 0x0000ff00) >>> 8) * alpha); + pixels[i] = (c & 0xff000000) | r << 16 | g << 8 | b; + } - buffer.put(pixels, 0, width * height); - buffer.flip(); + buffer.put(pixels, 0, width * height); + buffer.flip(); - Gdx.gl20.glTexImage2D(GL.TEXTURE_2D, 0, GL.RGBA, width, - height, 0, GL.RGBA, GL.UNSIGNED_BYTE, buffer); - } + Gdx.gl20.glTexImage2D(GL.TEXTURE_2D, 0, GL.RGBA, width, + height, 0, GL.RGBA, GL.UNSIGNED_BYTE, buffer); + } - @Override - public void recycle() { - } + @Override + public void recycle() { + } - @Override - public boolean isValid() { - return true; - } + @Override + public boolean isValid() { + return true; + } } diff --git a/vtm-desktop/src/org/oscim/awt/AwtCanvas.java b/vtm-desktop/src/org/oscim/awt/AwtCanvas.java index 8facc16b..bf7104ab 100644 --- a/vtm-desktop/src/org/oscim/awt/AwtCanvas.java +++ b/vtm-desktop/src/org/oscim/awt/AwtCanvas.java @@ -17,6 +17,10 @@ */ package org.oscim.awt; +import org.oscim.backend.canvas.Bitmap; +import org.oscim.backend.canvas.Canvas; +import org.oscim.backend.canvas.Paint; + import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.RenderingHints; @@ -24,73 +28,69 @@ import java.awt.Shape; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; -import org.oscim.backend.canvas.Bitmap; -import org.oscim.backend.canvas.Canvas; -import org.oscim.backend.canvas.Paint; - public class AwtCanvas implements Canvas { - Graphics2D canvas; + Graphics2D canvas; - public AwtCanvas() { + public AwtCanvas() { - } + } - @Override - public void setBitmap(Bitmap bitmap) { - if (canvas != null) - canvas.dispose(); + @Override + public void setBitmap(Bitmap bitmap) { + if (canvas != null) + canvas.dispose(); - AwtBitmap awtBitamp = (AwtBitmap) bitmap; + AwtBitmap awtBitamp = (AwtBitmap) bitmap; - canvas = awtBitamp.bitmap.createGraphics(); + canvas = awtBitamp.bitmap.createGraphics(); - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0)); - canvas.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight()); + canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0)); + canvas.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight()); - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); + canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); - //canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, - // RenderingHints.VALUE_FRACTIONALMETRICS_ON); - canvas.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); + //canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + // RenderingHints.VALUE_FRACTIONALMETRICS_ON); + canvas.setRenderingHint(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_QUALITY); + canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); - } + } - private final AffineTransform tx = new AffineTransform(); + private final AffineTransform tx = new AffineTransform(); - @Override - public void drawText(String text, float x, float y, Paint fill, Paint stroke) { + @Override + public void drawText(String text, float x, float y, Paint fill, Paint stroke) { - AwtPaint fillPaint = (AwtPaint) fill; + AwtPaint fillPaint = (AwtPaint) fill; - if (stroke == null) { - canvas.setColor(fillPaint.color); - canvas.setFont(fillPaint.font); - canvas.drawString(text, x + AwtPaint.TEXT_OFFSET, y); - } else { - AwtPaint strokePaint = (AwtPaint) stroke; + if (stroke == null) { + canvas.setColor(fillPaint.color); + canvas.setFont(fillPaint.font); + canvas.drawString(text, x + AwtPaint.TEXT_OFFSET, y); + } else { + AwtPaint strokePaint = (AwtPaint) stroke; - canvas.setColor(strokePaint.color); - canvas.setStroke(strokePaint.stroke); + canvas.setColor(strokePaint.color); + canvas.setStroke(strokePaint.stroke); - TextLayout tl = new TextLayout(text, fillPaint.font, - canvas.getFontRenderContext()); - tx.setToIdentity(); - tx.translate(x, y); + TextLayout tl = new TextLayout(text, fillPaint.font, + canvas.getFontRenderContext()); + tx.setToIdentity(); + tx.translate(x, y); - Shape s = tl.getOutline(tx); + Shape s = tl.getOutline(tx); - canvas.draw(s); - canvas.setColor(fillPaint.color); - canvas.fill(s); - } - } + canvas.draw(s); + canvas.setColor(fillPaint.color); + canvas.fill(s); + } + } - @Override - public void drawBitmap(Bitmap bitmap, float x, float y) { - throw new UnknownError("not implemented"); - } + @Override + public void drawBitmap(Bitmap bitmap, float x, float y) { + throw new UnknownError("not implemented"); + } } diff --git a/vtm-desktop/src/org/oscim/awt/AwtGraphics.java b/vtm-desktop/src/org/oscim/awt/AwtGraphics.java index 7906f48f..c4cb8bd5 100644 --- a/vtm-desktop/src/org/oscim/awt/AwtGraphics.java +++ b/vtm-desktop/src/org/oscim/awt/AwtGraphics.java @@ -17,6 +17,11 @@ */ package org.oscim.awt; +import org.oscim.backend.CanvasAdapter; +import org.oscim.backend.canvas.Bitmap; +import org.oscim.backend.canvas.Canvas; +import org.oscim.backend.canvas.Paint; + import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; @@ -25,88 +30,83 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; -import org.oscim.backend.CanvasAdapter; -import org.oscim.backend.canvas.Bitmap; -import org.oscim.backend.canvas.Canvas; -import org.oscim.backend.canvas.Paint; - public class AwtGraphics extends CanvasAdapter { - public static void init() { - CanvasAdapter.init(new AwtGraphics()); - } + public static void init() { + CanvasAdapter.init(new AwtGraphics()); + } - public static BufferedImage getBitmap(Bitmap bitmap) { - return ((AwtBitmap) bitmap).bitmap; - } + public static BufferedImage getBitmap(Bitmap bitmap) { + return ((AwtBitmap) bitmap).bitmap; + } - private AwtGraphics() { - // do nothing - } + private AwtGraphics() { + // do nothing + } - @Override - public Paint newPaintImpl() { - return new AwtPaint(); - } + @Override + public Paint newPaintImpl() { + return new AwtPaint(); + } - @Override - public Bitmap newBitmapImpl(int width, int height, int format) { - return new AwtBitmap(width, height, format); - } + @Override + public Bitmap newBitmapImpl(int width, int height, int format) { + return new AwtBitmap(width, height, format); + } - @Override - public Canvas newCanvasImpl() { - return new AwtCanvas(); - } + @Override + public Canvas newCanvasImpl() { + return new AwtCanvas(); + } - static final BufferedImage image; + static final BufferedImage image; - static final Graphics2D canvas; + static final Graphics2D canvas; - static { - image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); - canvas = image.createGraphics(); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - //canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - //canvas.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - } + static { + image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); + canvas = image.createGraphics(); + canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + //canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + //canvas.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + } - static synchronized FontMetrics getFontMetrics(Font font) { - canvas.setFont(font); - // get character measurements - FontMetrics fm = canvas.getFontMetrics(); - // int ascent = fm.getMaxAscent(); - // int descent = fm.getMaxDescent(); - // int advance = fm.charWidth('W'); // width of widest char, more - // reliable than getMaxAdvance(); - // int leading = fm.getLeading(); - // - return fm; - } + static synchronized FontMetrics getFontMetrics(Font font) { + canvas.setFont(font); + // get character measurements + FontMetrics fm = canvas.getFontMetrics(); + // int ascent = fm.getMaxAscent(); + // int descent = fm.getMaxDescent(); + // int advance = fm.charWidth('W'); // width of widest char, more + // reliable than getMaxAdvance(); + // int leading = fm.getLeading(); + // + return fm; + } - static synchronized float getTextWidth(FontMetrics fm, String text) { - //return (float)fm.getStringBounds(text, canvas).getWidth(); - return fm.stringWidth(text); - } + static synchronized float getTextWidth(FontMetrics fm, String text) { + //return (float)fm.getStringBounds(text, canvas).getWidth(); + return fm.stringWidth(text); + } - @Override - public Bitmap decodeBitmapImpl(InputStream inputStream) { - try { - return new AwtBitmap(inputStream); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } + @Override + public Bitmap decodeBitmapImpl(InputStream inputStream) { + try { + return new AwtBitmap(inputStream); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } - @Override - public Bitmap loadBitmapAssetImpl(String fileName) { - try { - return createBitmap(fileName); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + @Override + public Bitmap loadBitmapAssetImpl(String fileName) { + try { + return createBitmap(fileName); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } } diff --git a/vtm-desktop/src/org/oscim/awt/AwtPaint.java b/vtm-desktop/src/org/oscim/awt/AwtPaint.java index 4ed03049..888895db 100644 --- a/vtm-desktop/src/org/oscim/awt/AwtPaint.java +++ b/vtm-desktop/src/org/oscim/awt/AwtPaint.java @@ -17,6 +17,8 @@ */ package org.oscim.awt; +import org.oscim.backend.canvas.Paint; + import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; @@ -27,136 +29,135 @@ import java.text.AttributedCharacterIterator.Attribute; import java.util.HashMap; import java.util.Map; -import org.oscim.backend.canvas.Paint; - public class AwtPaint implements Paint { - final static float TEXT_OFFSET = 2; + final static float TEXT_OFFSET = 2; - private static int getCap(Cap cap) { - switch (cap) { - case BUTT: - return BasicStroke.CAP_BUTT; - case ROUND: - return BasicStroke.CAP_ROUND; - case SQUARE: - return BasicStroke.CAP_SQUARE; - } + private static int getCap(Cap cap) { + switch (cap) { + case BUTT: + return BasicStroke.CAP_BUTT; + case ROUND: + return BasicStroke.CAP_ROUND; + case SQUARE: + return BasicStroke.CAP_SQUARE; + } - throw new IllegalArgumentException("unknown cap: " + cap); - } + throw new IllegalArgumentException("unknown cap: " + cap); + } - static final Font defaultFont; - static { - Map textAttributes = new HashMap(); - textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - textAttributes.put(TextAttribute.FAMILY, "Arial"); - textAttributes.put(TextAttribute.SIZE, 14); + static final Font defaultFont; - defaultFont = Font.getFont(textAttributes); - } + static { + Map textAttributes = new HashMap(); + textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + textAttributes.put(TextAttribute.FAMILY, "Arial"); + textAttributes.put(TextAttribute.SIZE, 14); - Font font = defaultFont; // new Font("Default", Font.PLAIN, 13); - Stroke stroke; - FontMetrics fm; - Color color = new Color(0.1f, 0.1f, 0.1f, 1); + defaultFont = Font.getFont(textAttributes); + } - private int cap; - private float strokeWidth; + Font font = defaultFont; // new Font("Default", Font.PLAIN, 13); + Stroke stroke; + FontMetrics fm; + Color color = new Color(0.1f, 0.1f, 0.1f, 1); - //private Align mAlign; + private int cap; + private float strokeWidth; - @Override - public int getColor() { - return 0; - } + //private Align mAlign; - @Override - public void setColor(int c) { - color = new Color(((c >> 16) & 0xff) / 255f, - ((c >> 8) & 0xff) / 255f, - ((c >> 0) & 0xff) / 255f, - ((c >> 24) & 0xff) / 255f); - } + @Override + public int getColor() { + return 0; + } - @Override - public void setStrokeCap(Cap cap) { - this.cap = getCap(cap); - createStroke(); - } + @Override + public void setColor(int c) { + color = new Color(((c >> 16) & 0xff) / 255f, + ((c >> 8) & 0xff) / 255f, + ((c >> 0) & 0xff) / 255f, + ((c >> 24) & 0xff) / 255f); + } - @Override - public void setStrokeWidth(float width) { - strokeWidth = width + 1; - createStroke(); + @Override + public void setStrokeCap(Cap cap) { + this.cap = getCap(cap); + createStroke(); + } - // int size = font.getSize(); - // font = font.deriveFont(size + width * 4); + @Override + public void setStrokeWidth(float width) { + strokeWidth = width + 1; + createStroke(); - // TODO Auto-generated method stub + // int size = font.getSize(); + // font = font.deriveFont(size + width * 4); - } + // TODO Auto-generated method stub - @Override - public void setStyle(Style style) { - // TODO Auto-generated method stub + } - } + @Override + public void setStyle(Style style) { + // TODO Auto-generated method stub - @Override - public void setTextAlign(Align align) { - //mAlign = align; - } + } - @Override - public void setTextSize(float textSize) { - font = font.deriveFont(textSize); + @Override + public void setTextAlign(Align align) { + //mAlign = align; + } - } + @Override + public void setTextSize(float textSize) { + font = font.deriveFont(textSize); - @Override - public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { - // TODO Auto-generated method stub + } - } + @Override + public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { + // TODO Auto-generated method stub - @Override - public float measureText(String text) { - if (fm == null) - fm = AwtGraphics.getFontMetrics(this.font); + } - float w = AwtGraphics.getTextWidth(fm, text); - //Gdx.app.log("text width:", text + " " + w); - return w + 4; - // return fm.getStringBounds(text, A).getWidth(); - // return AwtGraphics.getTextWidth(fm, text); - // return fm.stringWidth(text); - } + @Override + public float measureText(String text) { + if (fm == null) + fm = AwtGraphics.getFontMetrics(this.font); - @Override - public float getFontHeight() { - if (fm == null) - fm = AwtGraphics.getFontMetrics(this.font); + float w = AwtGraphics.getTextWidth(fm, text); + //Gdx.app.log("text width:", text + " " + w); + return w + 4; + // return fm.getStringBounds(text, A).getWidth(); + // return AwtGraphics.getTextWidth(fm, text); + // return fm.stringWidth(text); + } - float height = fm.getHeight(); + @Override + public float getFontHeight() { + if (fm == null) + fm = AwtGraphics.getFontMetrics(this.font); - return height; - } + float height = fm.getHeight(); - @Override - public float getFontDescent() { - if (fm == null) - fm = AwtGraphics.getFontMetrics(this.font); + return height; + } - float desc = fm.getDescent(); + @Override + public float getFontDescent() { + if (fm == null) + fm = AwtGraphics.getFontMetrics(this.font); - return desc; - } + float desc = fm.getDescent(); - private void createStroke() { - if (strokeWidth <= 0) { - return; - } - stroke = new BasicStroke(strokeWidth, cap, BasicStroke.JOIN_MITER, 1, null, 0); - } + return desc; + } + + private void createStroke() { + if (strokeWidth <= 0) { + return; + } + stroke = new BasicStroke(strokeWidth, cap, BasicStroke.JOIN_MITER, 1, null, 0); + } } diff --git a/vtm-desktop/src/org/oscim/gdx/GdxGL.java b/vtm-desktop/src/org/oscim/gdx/GdxGL.java index 0ccee49d..0535f6d9 100644 --- a/vtm-desktop/src/org/oscim/gdx/GdxGL.java +++ b/vtm-desktop/src/org/oscim/gdx/GdxGL.java @@ -2,13 +2,13 @@ package org.oscim.gdx; /******************************************************************************* * Copyright 2011 See AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,748 +16,748 @@ package org.oscim.gdx; * limitations under the License. ******************************************************************************/ -import static com.badlogic.jglfw.utils.Memory.getPosition; +import org.oscim.backend.GL; import java.nio.Buffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; -import org.oscim.backend.GL; +import static com.badlogic.jglfw.utils.Memory.getPosition; public class GdxGL implements GL { - public void activeTexture(int texture) { - com.badlogic.jglfw.gl.GL.glActiveTexture(texture); - } - - public void bindTexture(int target, int texture) { - com.badlogic.jglfw.gl.GL.glBindTexture(target, texture); - } - - public void blendFunc(int sfactor, int dfactor) { - com.badlogic.jglfw.gl.GL.glBlendFunc(sfactor, dfactor); - } - - public void clear(int mask) { - com.badlogic.jglfw.gl.GL.glClear(mask); - } - - public void clearColor(float red, float green, float blue, float alpha) { - com.badlogic.jglfw.gl.GL.glClearColor(red, green, blue, alpha); - } - - public void clearDepthf(float depth) { - com.badlogic.jglfw.gl.GL.glClearDepthf(depth); - } - - public void clearStencil(int s) { - com.badlogic.jglfw.gl.GL.glClearStencil(s); - } - - public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - com.badlogic.jglfw.gl.GL.glColorMask(red, green, blue, alpha); - } - - public void compressedTexImage2D(int target, int level, int internalformat, int width, - int height, int border, - int imageSize, Buffer data) { - com.badlogic.jglfw.gl.GL.glCompressedTexImage2D( - target, - level, - internalformat, - width, - height, - border, - imageSize, - data, - getPosition(data)); - } - - public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, - int width, int height, int format, - int imageSize, Buffer data) { - com.badlogic.jglfw.gl.GL.glCompressedTexSubImage2D( - target, - level, - xoffset, - yoffset, - width, - height, - format, - imageSize, - data, - getPosition(data)); - } - - public void copyTexImage2D(int target, int level, int internalformat, int x, int y, - int width, int height, int border) { - com.badlogic.jglfw.gl.GL.glCopyTexImage2D( - target, - level, - internalformat, - x, - y, - width, - height, - border); - } - - public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, - int width, int height) { - com.badlogic.jglfw.gl.GL.glCopyTexSubImage2D( - target, - level, - xoffset, - yoffset, - x, - y, - width, - height); - } - - public void cullFace(int mode) { - com.badlogic.jglfw.gl.GL.glCullFace(mode); - } - - public void deleteTextures(int n, IntBuffer textures) { - com.badlogic.jglfw.gl.GL.glDeleteTextures(n, textures, getPosition(textures)); - } - - public void depthFunc(int func) { - com.badlogic.jglfw.gl.GL.glDepthFunc(func); - } - - public void depthMask(boolean flag) { - com.badlogic.jglfw.gl.GL.glDepthMask(flag); - } - - public void depthRangef(float zNear, float zFar) { - com.badlogic.jglfw.gl.GL.glDepthRangef(zNear, zFar); - } - - public void disable(int cap) { - com.badlogic.jglfw.gl.GL.glDisable(cap); - } - - public void drawArrays(int mode, int first, int count) { - com.badlogic.jglfw.gl.GL.glDrawArrays(mode, first, count); - } - - public void drawElements(int mode, int count, int type, Buffer indices) { - com.badlogic.jglfw.gl.GL.glDrawElements(mode, count, type, indices, getPosition(indices)); - } - - public void enable(int cap) { - com.badlogic.jglfw.gl.GL.glEnable(cap); - } - - public void finish() { - com.badlogic.jglfw.gl.GL.glFinish(); - } - - public void flush() { - com.badlogic.jglfw.gl.GL.glFlush(); - } - - public void frontFace(int mode) { - com.badlogic.jglfw.gl.GL.glFrontFace(mode); - } - - public void genTextures(int n, IntBuffer textures) { - com.badlogic.jglfw.gl.GL.glGenTextures(n, textures, getPosition(textures)); - } - - public int getError() { - return com.badlogic.jglfw.gl.GL.glGetError(); - } - - public void getIntegerv(int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetIntegerv(pname, params, getPosition(params)); - } - - public String getString(int name) { - return com.badlogic.jglfw.gl.GL.glGetString(name); - } - - public void hint(int target, int mode) { - com.badlogic.jglfw.gl.GL.glHint(target, mode); - } - - public void lineWidth(float width) { - com.badlogic.jglfw.gl.GL.glLineWidth(width); - } - - public void pixelStorei(int pname, int param) { - com.badlogic.jglfw.gl.GL.glPixelStorei(pname, param); - } - - public void polygonOffset(float factor, float units) { - com.badlogic.jglfw.gl.GL.glPolygonOffset(factor, units); - } - - public void readPixels(int x, int y, int width, int height, int format, int type, - Buffer pixels) { - com.badlogic.jglfw.gl.GL.glReadPixels( - x, - y, - width, - height, - format, - type, - pixels, - getPosition(pixels)); - } - - public void scissor(int x, int y, int width, int height) { - com.badlogic.jglfw.gl.GL.glScissor(x, y, width, height); - } - - public void stencilFunc(int func, int ref, int mask) { - com.badlogic.jglfw.gl.GL.glStencilFunc(func, ref, mask); - } - - public void stencilMask(int mask) { - com.badlogic.jglfw.gl.GL.glStencilMask(mask); - } - - public void stencilOp(int fail, int zfail, int zpass) { - com.badlogic.jglfw.gl.GL.glStencilOp(fail, zfail, zpass); - } - - public void texImage2D(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, - Buffer pixels) { - com.badlogic.jglfw.gl.GL.glTexImage2D( - target, - level, - internalFormat, - width, - height, - border, - format, - type, - pixels, - getPosition(pixels)); - } - - public void texParameterf(int target, int pname, float param) { - com.badlogic.jglfw.gl.GL.glTexParameterf(target, pname, param); - } - - public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, - int height, int format, int type, - Buffer pixels) { - com.badlogic.jglfw.gl.GL.glTexSubImage2D( - target, - level, - xoffset, - yoffset, - width, - height, - format, - type, - pixels, - getPosition(pixels)); - } - - public void viewport(int x, int y, int width, int height) { - com.badlogic.jglfw.gl.GL.glViewport(x, y, width, height); - } - - public void getFloatv(int pname, FloatBuffer params) { - com.badlogic.jglfw.gl.GL.glGetFloatv(pname, params, getPosition(params)); - } - - public void getTexParameterfv(int target, int pname, FloatBuffer params) { - com.badlogic.jglfw.gl.GL.glGetTexParameterfv(target, pname, params, getPosition(params)); - } - - public void texParameterfv(int target, int pname, FloatBuffer params) { - com.badlogic.jglfw.gl.GL.glTexParameterfv(target, pname, params, getPosition(params)); - } - - public void bindBuffer(int target, int buffer) { - com.badlogic.jglfw.gl.GL.glBindBuffer(target, buffer); - } - - public void bufferData(int target, int size, Buffer data, int usage) { - com.badlogic.jglfw.gl.GL.glBufferData(target, size, data, getPosition(data), usage); - } - - public void bufferSubData(int target, int offset, int size, Buffer data) { - com.badlogic.jglfw.gl.GL.glBufferSubData(target, offset, size, data, getPosition(data)); - } - - public void deleteBuffers(int n, IntBuffer buffers) { - com.badlogic.jglfw.gl.GL.glDeleteBuffers(n, buffers, getPosition(buffers)); - } - - public void getBufferParameteriv(int target, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetBufferParameteriv(target, pname, params, getPosition(params)); - } - - public void genBuffers(int n, IntBuffer buffers) { - com.badlogic.jglfw.gl.GL.glGenBuffers(n, buffers, getPosition(buffers)); - } - - public void getTexParameteriv(int target, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetTexParameteriv(target, pname, params, getPosition(params)); - } - - public boolean isBuffer(int buffer) { - return com.badlogic.jglfw.gl.GL.glIsBuffer(buffer); - } - - public boolean isEnabled(int cap) { - return com.badlogic.jglfw.gl.GL.glIsEnabled(cap); - } - - public boolean isTexture(int texture) { - return com.badlogic.jglfw.gl.GL.glIsTexture(texture); - } - - public void texParameteri(int target, int pname, int param) { - com.badlogic.jglfw.gl.GL.glTexParameteri(target, pname, param); - } - - public void texParameteriv(int target, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glTexParameteriv(target, pname, params, getPosition(params)); - } - - public void drawElements(int mode, int count, int type, int indices) { - com.badlogic.jglfw.gl.GL.glDrawElements(mode, count, type, indices); - } - - public void attachShader(int program, int shader) { - com.badlogic.jglfw.gl.GL.glAttachShader(program, shader); - } - - public void bindAttribLocation(int program, int index, String name) { - com.badlogic.jglfw.gl.GL.glBindAttribLocation(program, index, name); - } - - public void bindFramebuffer(int target, int framebuffer) { - com.badlogic.jglfw.gl.GL.glBindFramebufferEXT(target, framebuffer); - } - - public void bindRenderbuffer(int target, int renderbuffer) { - com.badlogic.jglfw.gl.GL.glBindRenderbufferEXT(target, renderbuffer); - } - - public void blendColor(float red, float green, float blue, float alpha) { - com.badlogic.jglfw.gl.GL.glBlendColor(red, green, blue, alpha); - } - - public void blendEquation(int mode) { - com.badlogic.jglfw.gl.GL.glBlendEquation(mode); - } - - public void blendEquationSeparate(int modeRGB, int modeAlpha) { - com.badlogic.jglfw.gl.GL.glBlendEquationSeparate(modeRGB, modeAlpha); - } - - public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { - com.badlogic.jglfw.gl.GL.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); - } - - public int checkFramebufferStatus(int target) { - return com.badlogic.jglfw.gl.GL.glCheckFramebufferStatusEXT(target); - } - - public void compileShader(int shader) { - com.badlogic.jglfw.gl.GL.glCompileShader(shader); - } - - public int createProgram() { - return com.badlogic.jglfw.gl.GL.glCreateProgram(); - } - - public int createShader(int type) { - return com.badlogic.jglfw.gl.GL.glCreateShader(type); - } - - public void deleteFramebuffers(int n, IntBuffer framebuffers) { - com.badlogic.jglfw.gl.GL - .glDeleteFramebuffersEXT(n, framebuffers, getPosition(framebuffers)); - } - - public void deleteProgram(int program) { - com.badlogic.jglfw.gl.GL.glDeleteProgram(program); - } - - public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { - com.badlogic.jglfw.gl.GL.glDeleteRenderbuffersEXT( - n, - renderbuffers, - getPosition(renderbuffers)); - } - - public void deleteShader(int shader) { - com.badlogic.jglfw.gl.GL.glDeleteShader(shader); - } - - public void detachShader(int program, int shader) { - com.badlogic.jglfw.gl.GL.glDetachShader(program, shader); - } - - public void disableVertexAttribArray(int index) { - com.badlogic.jglfw.gl.GL.glDisableVertexAttribArray(index); - } - - public void enableVertexAttribArray(int index) { - com.badlogic.jglfw.gl.GL.glEnableVertexAttribArray(index); - } - - public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, - int renderbuffer) { - com.badlogic.jglfw.gl.GL.glFramebufferRenderbufferEXT( - target, - attachment, - renderbuffertarget, - renderbuffer); - } - - public void framebufferTexture2D(int target, int attachment, int textarget, int texture, - int level) { - com.badlogic.jglfw.gl.GL.glFramebufferTexture2DEXT( - target, - attachment, - textarget, - texture, - level); - } - - public void generateMipmap(int target) { - com.badlogic.jglfw.gl.GL.glGenerateMipmapEXT(target); - } - - public void genFramebuffers(int n, IntBuffer framebuffers) { - com.badlogic.jglfw.gl.GL.glGenFramebuffersEXT(n, framebuffers, getPosition(framebuffers)); - } - - public void genRenderbuffers(int n, IntBuffer renderbuffers) { - com.badlogic.jglfw.gl.GL - .glGenRenderbuffersEXT(n, renderbuffers, getPosition(renderbuffers)); - } - - public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { - return com.badlogic.jglfw.gl.GL.glGetActiveAttrib( - program, - index, - size, - getPosition(size), - type, - getPosition(type)); - } - - public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { - return com.badlogic.jglfw.gl.GL.glGetActiveUniform( - program, - index, - size, - getPosition(size), - type, - getPosition(type)); - } - - public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { - com.badlogic.jglfw.gl.GL.glGetAttachedShaders( - program, - maxcount, - count, - getPosition(count), - shaders, - getPosition(shaders)); - } - - public int getAttribLocation(int program, String name) { - return com.badlogic.jglfw.gl.GL.glGetAttribLocation(program, name); - } - - public void getBooleanv(int pname, Buffer params) { - com.badlogic.jglfw.gl.GL.glGetBooleanv(pname, params, getPosition(params)); - } - - public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, - IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetFramebufferAttachmentParameterivEXT( - target, - attachment, - pname, - params, - getPosition(params)); - } - - public void getProgramiv(int program, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetProgramiv(program, pname, params, getPosition(params)); - } - - public String getProgramInfoLog(int program) { - return com.badlogic.jglfw.gl.GL.glGetProgramInfoLog(program); - } - - public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetRenderbufferParameterivEXT( - target, - pname, - params, - getPosition(params)); - } - - public void getShaderiv(int shader, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetShaderiv(shader, pname, params, getPosition(params)); - } - - public String getShaderInfoLog(int shader) { - return com.badlogic.jglfw.gl.GL.glGetShaderInfoLog(shader); - } - - public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, - IntBuffer precision) { - com.badlogic.jglfw.gl.GL.glGetShaderPrecisionFormat( - shadertype, - precisiontype, - range, - getPosition(range), - precision, - getPosition(precision)); - } - - public void getShaderSource(int shader, int bufsize, Buffer length, String source) { - throw new UnsupportedOperationException("Not implemented"); - } - - public void getUniformfv(int program, int location, FloatBuffer params) { - com.badlogic.jglfw.gl.GL.glGetUniformfv(program, location, params, getPosition(params)); - } - - public void getUniformiv(int program, int location, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetUniformiv(program, location, params, getPosition(params)); - } - - public int getUniformLocation(int program, String name) { - return com.badlogic.jglfw.gl.GL.glGetUniformLocation(program, name); - } - - public void getVertexAttribfv(int index, int pname, FloatBuffer params) { - com.badlogic.jglfw.gl.GL.glGetVertexAttribfv(index, pname, params, getPosition(params)); - } - - public void getVertexAttribiv(int index, int pname, IntBuffer params) { - com.badlogic.jglfw.gl.GL.glGetVertexAttribiv(index, pname, params, getPosition(params)); - } - - public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { - com.badlogic.jglfw.gl.GL.glGetVertexAttribPointerv( - index, - pname, - pointer, - getPosition(pointer)); - } - - public boolean isFramebuffer(int framebuffer) { - return com.badlogic.jglfw.gl.GL.glIsFramebufferEXT(framebuffer); - } - - public boolean isProgram(int program) { - return com.badlogic.jglfw.gl.GL.glIsProgram(program); - } - - public boolean isRenderbuffer(int renderbuffer) { - return com.badlogic.jglfw.gl.GL.glIsRenderbufferEXT(renderbuffer); - } - - public boolean isShader(int shader) { - return com.badlogic.jglfw.gl.GL.glIsShader(shader); - } - - public void linkProgram(int program) { - com.badlogic.jglfw.gl.GL.glLinkProgram(program); - } - - public void releaseShaderCompiler() { - com.badlogic.jglfw.gl.GL.glReleaseShaderCompiler(); - } - - public void renderbufferStorage(int target, int internalformat, int width, int height) { - com.badlogic.jglfw.gl.GL.glRenderbufferStorageEXT(target, internalformat, width, height); - } - - public void sampleCoverage(float value, boolean invert) { - com.badlogic.jglfw.gl.GL.glSampleCoverage(value, invert); - } - - public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { - com.badlogic.jglfw.gl.GL.glShaderBinary( - n, - shaders, - getPosition(shaders), - binaryformat, - binary, - getPosition(binary), - length); - } - - public void shaderSource(int shader, String string) { - com.badlogic.jglfw.gl.GL.glShaderSource(shader, string); - } - - public void stencilFuncSeparate(int face, int func, int ref, int mask) { - com.badlogic.jglfw.gl.GL.glStencilFuncSeparate(face, func, ref, mask); - } - - public void stencilMaskSeparate(int face, int mask) { - com.badlogic.jglfw.gl.GL.glStencilMaskSeparate(face, mask); - } - - public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { - com.badlogic.jglfw.gl.GL.glStencilOpSeparate(face, fail, zfail, zpass); - } - - public void uniform1f(int location, float x) { - com.badlogic.jglfw.gl.GL.glUniform1f(location, x); - } - - public void uniform1fv(int location, int count, FloatBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform1fv(location, count, v, getPosition(v)); - } - - public void uniform1i(int location, int x) { - com.badlogic.jglfw.gl.GL.glUniform1i(location, x); - } - - public void uniform1iv(int location, int count, IntBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform1iv(location, count, v, getPosition(v)); - } - - public void uniform2f(int location, float x, float y) { - com.badlogic.jglfw.gl.GL.glUniform2f(location, x, y); - } - - public void uniform2fv(int location, int count, FloatBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform2fv(location, count, v, getPosition(v)); - } - - public void uniform2i(int location, int x, int y) { - com.badlogic.jglfw.gl.GL.glUniform2i(location, x, y); - } - - public void uniform2iv(int location, int count, IntBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform2iv(location, count, v, getPosition(v)); - } - - public void uniform3f(int location, float x, float y, float z) { - com.badlogic.jglfw.gl.GL.glUniform3f(location, x, y, z); - } - - public void uniform3fv(int location, int count, FloatBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform3fv(location, count, v, getPosition(v)); - } - - public void uniform3i(int location, int x, int y, int z) { - com.badlogic.jglfw.gl.GL.glUniform3i(location, x, y, z); - } - - public void uniform3iv(int location, int count, IntBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform3iv(location, count, v, getPosition(v)); - } - - public void uniform4f(int location, float x, float y, float z, float w) { - com.badlogic.jglfw.gl.GL.glUniform4f(location, x, y, z, w); - } - - public void uniform4fv(int location, int count, FloatBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform4fv(location, count, v, getPosition(v)); - } - - public void uniform4i(int location, int x, int y, int z, int w) { - com.badlogic.jglfw.gl.GL.glUniform4i(location, x, y, z, w); - } - - public void uniform4iv(int location, int count, IntBuffer v) { - com.badlogic.jglfw.gl.GL.glUniform4iv(location, count, v, getPosition(v)); - } - - public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { - com.badlogic.jglfw.gl.GL.glUniformMatrix2fv( - location, - count, - transpose, - value, - getPosition(value)); - } - - public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { - com.badlogic.jglfw.gl.GL.glUniformMatrix3fv( - location, - count, - transpose, - value, - getPosition(value)); - } - - public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { - com.badlogic.jglfw.gl.GL.glUniformMatrix4fv( - location, - count, - transpose, - value, - getPosition(value)); - } - - public void useProgram(int program) { - com.badlogic.jglfw.gl.GL.glUseProgram(program); - } - - public void validateProgram(int program) { - com.badlogic.jglfw.gl.GL.glValidateProgram(program); - } - - public void vertexAttrib1f(int indx, float x) { - com.badlogic.jglfw.gl.GL.glVertexAttrib1f(indx, x); - } - - public void vertexAttrib1fv(int indx, FloatBuffer values) { - com.badlogic.jglfw.gl.GL.glVertexAttrib1fv(indx, values, getPosition(values)); - } - - public void vertexAttrib2f(int indx, float x, float y) { - com.badlogic.jglfw.gl.GL.glVertexAttrib2f(indx, x, y); - } - - public void vertexAttrib2fv(int indx, FloatBuffer values) { - com.badlogic.jglfw.gl.GL.glVertexAttrib2fv(indx, values, getPosition(values)); - } - - public void vertexAttrib3f(int indx, float x, float y, float z) { - com.badlogic.jglfw.gl.GL.glVertexAttrib3f(indx, x, y, z); - } - - public void vertexAttrib3fv(int indx, FloatBuffer values) { - com.badlogic.jglfw.gl.GL.glVertexAttrib3fv(indx, values, getPosition(values)); - } - - public void vertexAttrib4f(int indx, float x, float y, float z, float w) { - com.badlogic.jglfw.gl.GL.glVertexAttrib4f(indx, x, y, z, w); - } - - public void vertexAttrib4fv(int indx, FloatBuffer values) { - com.badlogic.jglfw.gl.GL.glVertexAttrib4fv(indx, values, getPosition(values)); - } - - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - Buffer ptr) { - com.badlogic.jglfw.gl.GL.glVertexAttribPointer( - indx, - size, - type, - normalized, - stride, - ptr, - getPosition(ptr)); - } - - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - int ptr) { - com.badlogic.jglfw.gl.GL.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); - } + public void activeTexture(int texture) { + com.badlogic.jglfw.gl.GL.glActiveTexture(texture); + } + + public void bindTexture(int target, int texture) { + com.badlogic.jglfw.gl.GL.glBindTexture(target, texture); + } + + public void blendFunc(int sfactor, int dfactor) { + com.badlogic.jglfw.gl.GL.glBlendFunc(sfactor, dfactor); + } + + public void clear(int mask) { + com.badlogic.jglfw.gl.GL.glClear(mask); + } + + public void clearColor(float red, float green, float blue, float alpha) { + com.badlogic.jglfw.gl.GL.glClearColor(red, green, blue, alpha); + } + + public void clearDepthf(float depth) { + com.badlogic.jglfw.gl.GL.glClearDepthf(depth); + } + + public void clearStencil(int s) { + com.badlogic.jglfw.gl.GL.glClearStencil(s); + } + + public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + com.badlogic.jglfw.gl.GL.glColorMask(red, green, blue, alpha); + } + + public void compressedTexImage2D(int target, int level, int internalformat, int width, + int height, int border, + int imageSize, Buffer data) { + com.badlogic.jglfw.gl.GL.glCompressedTexImage2D( + target, + level, + internalformat, + width, + height, + border, + imageSize, + data, + getPosition(data)); + } + + public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, + int width, int height, int format, + int imageSize, Buffer data) { + com.badlogic.jglfw.gl.GL.glCompressedTexSubImage2D( + target, + level, + xoffset, + yoffset, + width, + height, + format, + imageSize, + data, + getPosition(data)); + } + + public void copyTexImage2D(int target, int level, int internalformat, int x, int y, + int width, int height, int border) { + com.badlogic.jglfw.gl.GL.glCopyTexImage2D( + target, + level, + internalformat, + x, + y, + width, + height, + border); + } + + public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, + int width, int height) { + com.badlogic.jglfw.gl.GL.glCopyTexSubImage2D( + target, + level, + xoffset, + yoffset, + x, + y, + width, + height); + } + + public void cullFace(int mode) { + com.badlogic.jglfw.gl.GL.glCullFace(mode); + } + + public void deleteTextures(int n, IntBuffer textures) { + com.badlogic.jglfw.gl.GL.glDeleteTextures(n, textures, getPosition(textures)); + } + + public void depthFunc(int func) { + com.badlogic.jglfw.gl.GL.glDepthFunc(func); + } + + public void depthMask(boolean flag) { + com.badlogic.jglfw.gl.GL.glDepthMask(flag); + } + + public void depthRangef(float zNear, float zFar) { + com.badlogic.jglfw.gl.GL.glDepthRangef(zNear, zFar); + } + + public void disable(int cap) { + com.badlogic.jglfw.gl.GL.glDisable(cap); + } + + public void drawArrays(int mode, int first, int count) { + com.badlogic.jglfw.gl.GL.glDrawArrays(mode, first, count); + } + + public void drawElements(int mode, int count, int type, Buffer indices) { + com.badlogic.jglfw.gl.GL.glDrawElements(mode, count, type, indices, getPosition(indices)); + } + + public void enable(int cap) { + com.badlogic.jglfw.gl.GL.glEnable(cap); + } + + public void finish() { + com.badlogic.jglfw.gl.GL.glFinish(); + } + + public void flush() { + com.badlogic.jglfw.gl.GL.glFlush(); + } + + public void frontFace(int mode) { + com.badlogic.jglfw.gl.GL.glFrontFace(mode); + } + + public void genTextures(int n, IntBuffer textures) { + com.badlogic.jglfw.gl.GL.glGenTextures(n, textures, getPosition(textures)); + } + + public int getError() { + return com.badlogic.jglfw.gl.GL.glGetError(); + } + + public void getIntegerv(int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetIntegerv(pname, params, getPosition(params)); + } + + public String getString(int name) { + return com.badlogic.jglfw.gl.GL.glGetString(name); + } + + public void hint(int target, int mode) { + com.badlogic.jglfw.gl.GL.glHint(target, mode); + } + + public void lineWidth(float width) { + com.badlogic.jglfw.gl.GL.glLineWidth(width); + } + + public void pixelStorei(int pname, int param) { + com.badlogic.jglfw.gl.GL.glPixelStorei(pname, param); + } + + public void polygonOffset(float factor, float units) { + com.badlogic.jglfw.gl.GL.glPolygonOffset(factor, units); + } + + public void readPixels(int x, int y, int width, int height, int format, int type, + Buffer pixels) { + com.badlogic.jglfw.gl.GL.glReadPixels( + x, + y, + width, + height, + format, + type, + pixels, + getPosition(pixels)); + } + + public void scissor(int x, int y, int width, int height) { + com.badlogic.jglfw.gl.GL.glScissor(x, y, width, height); + } + + public void stencilFunc(int func, int ref, int mask) { + com.badlogic.jglfw.gl.GL.glStencilFunc(func, ref, mask); + } + + public void stencilMask(int mask) { + com.badlogic.jglfw.gl.GL.glStencilMask(mask); + } + + public void stencilOp(int fail, int zfail, int zpass) { + com.badlogic.jglfw.gl.GL.glStencilOp(fail, zfail, zpass); + } + + public void texImage2D(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, + Buffer pixels) { + com.badlogic.jglfw.gl.GL.glTexImage2D( + target, + level, + internalFormat, + width, + height, + border, + format, + type, + pixels, + getPosition(pixels)); + } + + public void texParameterf(int target, int pname, float param) { + com.badlogic.jglfw.gl.GL.glTexParameterf(target, pname, param); + } + + public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, + int height, int format, int type, + Buffer pixels) { + com.badlogic.jglfw.gl.GL.glTexSubImage2D( + target, + level, + xoffset, + yoffset, + width, + height, + format, + type, + pixels, + getPosition(pixels)); + } + + public void viewport(int x, int y, int width, int height) { + com.badlogic.jglfw.gl.GL.glViewport(x, y, width, height); + } + + public void getFloatv(int pname, FloatBuffer params) { + com.badlogic.jglfw.gl.GL.glGetFloatv(pname, params, getPosition(params)); + } + + public void getTexParameterfv(int target, int pname, FloatBuffer params) { + com.badlogic.jglfw.gl.GL.glGetTexParameterfv(target, pname, params, getPosition(params)); + } + + public void texParameterfv(int target, int pname, FloatBuffer params) { + com.badlogic.jglfw.gl.GL.glTexParameterfv(target, pname, params, getPosition(params)); + } + + public void bindBuffer(int target, int buffer) { + com.badlogic.jglfw.gl.GL.glBindBuffer(target, buffer); + } + + public void bufferData(int target, int size, Buffer data, int usage) { + com.badlogic.jglfw.gl.GL.glBufferData(target, size, data, getPosition(data), usage); + } + + public void bufferSubData(int target, int offset, int size, Buffer data) { + com.badlogic.jglfw.gl.GL.glBufferSubData(target, offset, size, data, getPosition(data)); + } + + public void deleteBuffers(int n, IntBuffer buffers) { + com.badlogic.jglfw.gl.GL.glDeleteBuffers(n, buffers, getPosition(buffers)); + } + + public void getBufferParameteriv(int target, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetBufferParameteriv(target, pname, params, getPosition(params)); + } + + public void genBuffers(int n, IntBuffer buffers) { + com.badlogic.jglfw.gl.GL.glGenBuffers(n, buffers, getPosition(buffers)); + } + + public void getTexParameteriv(int target, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetTexParameteriv(target, pname, params, getPosition(params)); + } + + public boolean isBuffer(int buffer) { + return com.badlogic.jglfw.gl.GL.glIsBuffer(buffer); + } + + public boolean isEnabled(int cap) { + return com.badlogic.jglfw.gl.GL.glIsEnabled(cap); + } + + public boolean isTexture(int texture) { + return com.badlogic.jglfw.gl.GL.glIsTexture(texture); + } + + public void texParameteri(int target, int pname, int param) { + com.badlogic.jglfw.gl.GL.glTexParameteri(target, pname, param); + } + + public void texParameteriv(int target, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glTexParameteriv(target, pname, params, getPosition(params)); + } + + public void drawElements(int mode, int count, int type, int indices) { + com.badlogic.jglfw.gl.GL.glDrawElements(mode, count, type, indices); + } + + public void attachShader(int program, int shader) { + com.badlogic.jglfw.gl.GL.glAttachShader(program, shader); + } + + public void bindAttribLocation(int program, int index, String name) { + com.badlogic.jglfw.gl.GL.glBindAttribLocation(program, index, name); + } + + public void bindFramebuffer(int target, int framebuffer) { + com.badlogic.jglfw.gl.GL.glBindFramebufferEXT(target, framebuffer); + } + + public void bindRenderbuffer(int target, int renderbuffer) { + com.badlogic.jglfw.gl.GL.glBindRenderbufferEXT(target, renderbuffer); + } + + public void blendColor(float red, float green, float blue, float alpha) { + com.badlogic.jglfw.gl.GL.glBlendColor(red, green, blue, alpha); + } + + public void blendEquation(int mode) { + com.badlogic.jglfw.gl.GL.glBlendEquation(mode); + } + + public void blendEquationSeparate(int modeRGB, int modeAlpha) { + com.badlogic.jglfw.gl.GL.glBlendEquationSeparate(modeRGB, modeAlpha); + } + + public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + com.badlogic.jglfw.gl.GL.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + + public int checkFramebufferStatus(int target) { + return com.badlogic.jglfw.gl.GL.glCheckFramebufferStatusEXT(target); + } + + public void compileShader(int shader) { + com.badlogic.jglfw.gl.GL.glCompileShader(shader); + } + + public int createProgram() { + return com.badlogic.jglfw.gl.GL.glCreateProgram(); + } + + public int createShader(int type) { + return com.badlogic.jglfw.gl.GL.glCreateShader(type); + } + + public void deleteFramebuffers(int n, IntBuffer framebuffers) { + com.badlogic.jglfw.gl.GL + .glDeleteFramebuffersEXT(n, framebuffers, getPosition(framebuffers)); + } + + public void deleteProgram(int program) { + com.badlogic.jglfw.gl.GL.glDeleteProgram(program); + } + + public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { + com.badlogic.jglfw.gl.GL.glDeleteRenderbuffersEXT( + n, + renderbuffers, + getPosition(renderbuffers)); + } + + public void deleteShader(int shader) { + com.badlogic.jglfw.gl.GL.glDeleteShader(shader); + } + + public void detachShader(int program, int shader) { + com.badlogic.jglfw.gl.GL.glDetachShader(program, shader); + } + + public void disableVertexAttribArray(int index) { + com.badlogic.jglfw.gl.GL.glDisableVertexAttribArray(index); + } + + public void enableVertexAttribArray(int index) { + com.badlogic.jglfw.gl.GL.glEnableVertexAttribArray(index); + } + + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, + int renderbuffer) { + com.badlogic.jglfw.gl.GL.glFramebufferRenderbufferEXT( + target, + attachment, + renderbuffertarget, + renderbuffer); + } + + public void framebufferTexture2D(int target, int attachment, int textarget, int texture, + int level) { + com.badlogic.jglfw.gl.GL.glFramebufferTexture2DEXT( + target, + attachment, + textarget, + texture, + level); + } + + public void generateMipmap(int target) { + com.badlogic.jglfw.gl.GL.glGenerateMipmapEXT(target); + } + + public void genFramebuffers(int n, IntBuffer framebuffers) { + com.badlogic.jglfw.gl.GL.glGenFramebuffersEXT(n, framebuffers, getPosition(framebuffers)); + } + + public void genRenderbuffers(int n, IntBuffer renderbuffers) { + com.badlogic.jglfw.gl.GL + .glGenRenderbuffersEXT(n, renderbuffers, getPosition(renderbuffers)); + } + + public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { + return com.badlogic.jglfw.gl.GL.glGetActiveAttrib( + program, + index, + size, + getPosition(size), + type, + getPosition(type)); + } + + public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { + return com.badlogic.jglfw.gl.GL.glGetActiveUniform( + program, + index, + size, + getPosition(size), + type, + getPosition(type)); + } + + public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { + com.badlogic.jglfw.gl.GL.glGetAttachedShaders( + program, + maxcount, + count, + getPosition(count), + shaders, + getPosition(shaders)); + } + + public int getAttribLocation(int program, String name) { + return com.badlogic.jglfw.gl.GL.glGetAttribLocation(program, name); + } + + public void getBooleanv(int pname, Buffer params) { + com.badlogic.jglfw.gl.GL.glGetBooleanv(pname, params, getPosition(params)); + } + + public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, + IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetFramebufferAttachmentParameterivEXT( + target, + attachment, + pname, + params, + getPosition(params)); + } + + public void getProgramiv(int program, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetProgramiv(program, pname, params, getPosition(params)); + } + + public String getProgramInfoLog(int program) { + return com.badlogic.jglfw.gl.GL.glGetProgramInfoLog(program); + } + + public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetRenderbufferParameterivEXT( + target, + pname, + params, + getPosition(params)); + } + + public void getShaderiv(int shader, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetShaderiv(shader, pname, params, getPosition(params)); + } + + public String getShaderInfoLog(int shader) { + return com.badlogic.jglfw.gl.GL.glGetShaderInfoLog(shader); + } + + public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, + IntBuffer precision) { + com.badlogic.jglfw.gl.GL.glGetShaderPrecisionFormat( + shadertype, + precisiontype, + range, + getPosition(range), + precision, + getPosition(precision)); + } + + public void getShaderSource(int shader, int bufsize, Buffer length, String source) { + throw new UnsupportedOperationException("Not implemented"); + } + + public void getUniformfv(int program, int location, FloatBuffer params) { + com.badlogic.jglfw.gl.GL.glGetUniformfv(program, location, params, getPosition(params)); + } + + public void getUniformiv(int program, int location, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetUniformiv(program, location, params, getPosition(params)); + } + + public int getUniformLocation(int program, String name) { + return com.badlogic.jglfw.gl.GL.glGetUniformLocation(program, name); + } + + public void getVertexAttribfv(int index, int pname, FloatBuffer params) { + com.badlogic.jglfw.gl.GL.glGetVertexAttribfv(index, pname, params, getPosition(params)); + } + + public void getVertexAttribiv(int index, int pname, IntBuffer params) { + com.badlogic.jglfw.gl.GL.glGetVertexAttribiv(index, pname, params, getPosition(params)); + } + + public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { + com.badlogic.jglfw.gl.GL.glGetVertexAttribPointerv( + index, + pname, + pointer, + getPosition(pointer)); + } + + public boolean isFramebuffer(int framebuffer) { + return com.badlogic.jglfw.gl.GL.glIsFramebufferEXT(framebuffer); + } + + public boolean isProgram(int program) { + return com.badlogic.jglfw.gl.GL.glIsProgram(program); + } + + public boolean isRenderbuffer(int renderbuffer) { + return com.badlogic.jglfw.gl.GL.glIsRenderbufferEXT(renderbuffer); + } + + public boolean isShader(int shader) { + return com.badlogic.jglfw.gl.GL.glIsShader(shader); + } + + public void linkProgram(int program) { + com.badlogic.jglfw.gl.GL.glLinkProgram(program); + } + + public void releaseShaderCompiler() { + com.badlogic.jglfw.gl.GL.glReleaseShaderCompiler(); + } + + public void renderbufferStorage(int target, int internalformat, int width, int height) { + com.badlogic.jglfw.gl.GL.glRenderbufferStorageEXT(target, internalformat, width, height); + } + + public void sampleCoverage(float value, boolean invert) { + com.badlogic.jglfw.gl.GL.glSampleCoverage(value, invert); + } + + public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { + com.badlogic.jglfw.gl.GL.glShaderBinary( + n, + shaders, + getPosition(shaders), + binaryformat, + binary, + getPosition(binary), + length); + } + + public void shaderSource(int shader, String string) { + com.badlogic.jglfw.gl.GL.glShaderSource(shader, string); + } + + public void stencilFuncSeparate(int face, int func, int ref, int mask) { + com.badlogic.jglfw.gl.GL.glStencilFuncSeparate(face, func, ref, mask); + } + + public void stencilMaskSeparate(int face, int mask) { + com.badlogic.jglfw.gl.GL.glStencilMaskSeparate(face, mask); + } + + public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { + com.badlogic.jglfw.gl.GL.glStencilOpSeparate(face, fail, zfail, zpass); + } + + public void uniform1f(int location, float x) { + com.badlogic.jglfw.gl.GL.glUniform1f(location, x); + } + + public void uniform1fv(int location, int count, FloatBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform1fv(location, count, v, getPosition(v)); + } + + public void uniform1i(int location, int x) { + com.badlogic.jglfw.gl.GL.glUniform1i(location, x); + } + + public void uniform1iv(int location, int count, IntBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform1iv(location, count, v, getPosition(v)); + } + + public void uniform2f(int location, float x, float y) { + com.badlogic.jglfw.gl.GL.glUniform2f(location, x, y); + } + + public void uniform2fv(int location, int count, FloatBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform2fv(location, count, v, getPosition(v)); + } + + public void uniform2i(int location, int x, int y) { + com.badlogic.jglfw.gl.GL.glUniform2i(location, x, y); + } + + public void uniform2iv(int location, int count, IntBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform2iv(location, count, v, getPosition(v)); + } + + public void uniform3f(int location, float x, float y, float z) { + com.badlogic.jglfw.gl.GL.glUniform3f(location, x, y, z); + } + + public void uniform3fv(int location, int count, FloatBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform3fv(location, count, v, getPosition(v)); + } + + public void uniform3i(int location, int x, int y, int z) { + com.badlogic.jglfw.gl.GL.glUniform3i(location, x, y, z); + } + + public void uniform3iv(int location, int count, IntBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform3iv(location, count, v, getPosition(v)); + } + + public void uniform4f(int location, float x, float y, float z, float w) { + com.badlogic.jglfw.gl.GL.glUniform4f(location, x, y, z, w); + } + + public void uniform4fv(int location, int count, FloatBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform4fv(location, count, v, getPosition(v)); + } + + public void uniform4i(int location, int x, int y, int z, int w) { + com.badlogic.jglfw.gl.GL.glUniform4i(location, x, y, z, w); + } + + public void uniform4iv(int location, int count, IntBuffer v) { + com.badlogic.jglfw.gl.GL.glUniform4iv(location, count, v, getPosition(v)); + } + + public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { + com.badlogic.jglfw.gl.GL.glUniformMatrix2fv( + location, + count, + transpose, + value, + getPosition(value)); + } + + public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { + com.badlogic.jglfw.gl.GL.glUniformMatrix3fv( + location, + count, + transpose, + value, + getPosition(value)); + } + + public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { + com.badlogic.jglfw.gl.GL.glUniformMatrix4fv( + location, + count, + transpose, + value, + getPosition(value)); + } + + public void useProgram(int program) { + com.badlogic.jglfw.gl.GL.glUseProgram(program); + } + + public void validateProgram(int program) { + com.badlogic.jglfw.gl.GL.glValidateProgram(program); + } + + public void vertexAttrib1f(int indx, float x) { + com.badlogic.jglfw.gl.GL.glVertexAttrib1f(indx, x); + } + + public void vertexAttrib1fv(int indx, FloatBuffer values) { + com.badlogic.jglfw.gl.GL.glVertexAttrib1fv(indx, values, getPosition(values)); + } + + public void vertexAttrib2f(int indx, float x, float y) { + com.badlogic.jglfw.gl.GL.glVertexAttrib2f(indx, x, y); + } + + public void vertexAttrib2fv(int indx, FloatBuffer values) { + com.badlogic.jglfw.gl.GL.glVertexAttrib2fv(indx, values, getPosition(values)); + } + + public void vertexAttrib3f(int indx, float x, float y, float z) { + com.badlogic.jglfw.gl.GL.glVertexAttrib3f(indx, x, y, z); + } + + public void vertexAttrib3fv(int indx, FloatBuffer values) { + com.badlogic.jglfw.gl.GL.glVertexAttrib3fv(indx, values, getPosition(values)); + } + + public void vertexAttrib4f(int indx, float x, float y, float z, float w) { + com.badlogic.jglfw.gl.GL.glVertexAttrib4f(indx, x, y, z, w); + } + + public void vertexAttrib4fv(int indx, FloatBuffer values) { + com.badlogic.jglfw.gl.GL.glVertexAttrib4fv(indx, values, getPosition(values)); + } + + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + Buffer ptr) { + com.badlogic.jglfw.gl.GL.glVertexAttribPointer( + indx, + size, + type, + normalized, + stride, + ptr, + getPosition(ptr)); + } + + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + int ptr) { + com.badlogic.jglfw.gl.GL.glVertexAttribPointer(indx, size, type, normalized, stride, ptr); + } } diff --git a/vtm-desktop/src/org/oscim/gdx/GdxMapApp.java b/vtm-desktop/src/org/oscim/gdx/GdxMapApp.java index 1054b985..86dea969 100644 --- a/vtm-desktop/src/org/oscim/gdx/GdxMapApp.java +++ b/vtm-desktop/src/org/oscim/gdx/GdxMapApp.java @@ -17,6 +17,10 @@ */ package org.oscim.gdx; +import com.badlogic.gdx.backends.jglfw.JglfwApplication; +import com.badlogic.gdx.backends.jglfw.JglfwApplicationConfiguration; +import com.badlogic.gdx.utils.SharedLibraryLoader; + import org.oscim.awt.AwtGraphics; import org.oscim.backend.GLAdapter; import org.oscim.core.Tile; @@ -26,65 +30,61 @@ import org.oscim.utils.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.backends.jglfw.JglfwApplication; -import com.badlogic.gdx.backends.jglfw.JglfwApplicationConfiguration; -import com.badlogic.gdx.utils.SharedLibraryLoader; - public class GdxMapApp extends GdxMap { - public static final Logger log = LoggerFactory.getLogger(GdxMapApp.class); + public static final Logger log = LoggerFactory.getLogger(GdxMapApp.class); - public static void init() { - // load native library - new SharedLibraryLoader().load("vtm-jni"); - // init globals - AwtGraphics.init(); - GdxAssets.init("assets/"); - GLAdapter.init(new GdxGL()); - GLAdapter.GDX_DESKTOP_QUIRKS = true; - } + public static void init() { + // load native library + new SharedLibraryLoader().load("vtm-jni"); + // init globals + AwtGraphics.init(); + GdxAssets.init("assets/"); + GLAdapter.init(new GdxGL()); + GLAdapter.GDX_DESKTOP_QUIRKS = true; + } - public static void main(String[] args) { - Tile.SIZE = 360; - init(); - new JglfwApplication(new GdxMapApp(), getConfig()); - } + public static void main(String[] args) { + Tile.SIZE = 360; + init(); + new JglfwApplication(new GdxMapApp(), getConfig()); + } - public static void run(GdxMap map, JglfwApplicationConfiguration config, int tileSize) { - Tile.SIZE = FastMath.clamp(tileSize, 128, 512); + public static void run(GdxMap map, JglfwApplicationConfiguration config, int tileSize) { + Tile.SIZE = FastMath.clamp(tileSize, 128, 512); - new JglfwApplication(map, (config == null ? getConfig() : config)); - } + new JglfwApplication(map, (config == null ? getConfig() : config)); + } - public static void run(JglfwApplicationConfiguration config, int tileSize, GdxMap map) { - run(map, config, tileSize); - } + public static void run(JglfwApplicationConfiguration config, int tileSize, GdxMap map) { + run(map, config, tileSize); + } - static protected JglfwApplicationConfiguration getConfig() { - JglfwApplicationConfiguration cfg = new JglfwApplicationConfiguration(); - cfg.title = "vtm-gdx"; - cfg.width = 800; - cfg.height = 600; - cfg.stencil = 8; - //cfg.samples = 2; - cfg.foregroundFPS = 30; - cfg.backgroundFPS = 10; - return cfg; - } + static protected JglfwApplicationConfiguration getConfig() { + JglfwApplicationConfiguration cfg = new JglfwApplicationConfiguration(); + cfg.title = "vtm-gdx"; + cfg.width = 800; + cfg.height = 600; + cfg.stencil = 8; + //cfg.samples = 2; + cfg.foregroundFPS = 30; + cfg.backgroundFPS = 10; + return cfg; + } - @Override - public void createLayers() { - TileSource tileSource = new OSciMap4TileSource(); + @Override + public void createLayers() { + TileSource tileSource = new OSciMap4TileSource(); - // TileSource tileSource = new MapFileTileSource(); - // tileSource.setOption("file", "/home/jeff/germany.map"); + // TileSource tileSource = new MapFileTileSource(); + // tileSource.setOption("file", "/home/jeff/germany.map"); - initDefaultLayers(tileSource, false, true, true); + initDefaultLayers(tileSource, false, true, true); - //mMap.getLayers().add(new BitmapTileLayer(mMap, new ImagicoLandcover(), 20)); - //mMap.getLayers().add(new BitmapTileLayer(mMap, new OSMTileSource(), 20)); - //mMap.getLayers().add(new BitmapTileLayer(mMap, new ArcGISWorldShaded(), 20)); + //mMap.getLayers().add(new BitmapTileLayer(mMap, new ImagicoLandcover(), 20)); + //mMap.getLayers().add(new BitmapTileLayer(mMap, new OSMTileSource(), 20)); + //mMap.getLayers().add(new BitmapTileLayer(mMap, new ArcGISWorldShaded(), 20)); - mMap.setMapPosition(0, 0, 1 << 2); - } + mMap.setMapPosition(0, 0, 1 << 2); + } } diff --git a/vtm-extras/src/org/oscim/core/osm/OsmData.java b/vtm-extras/src/org/oscim/core/osm/OsmData.java index ca69c7fc..67221ac3 100644 --- a/vtm-extras/src/org/oscim/core/osm/OsmData.java +++ b/vtm-extras/src/org/oscim/core/osm/OsmData.java @@ -23,35 +23,35 @@ import java.util.Collection; */ public class OsmData { - private final Collection bounds; - private final Collection nodes; - private final Collection ways; - private final Collection relations; + private final Collection bounds; + private final Collection nodes; + private final Collection ways; + private final Collection relations; - public OsmData(Collection bounds, Collection nodes, - Collection ways, Collection relations) { + public OsmData(Collection bounds, Collection nodes, + Collection ways, Collection relations) { - this.bounds = bounds; - this.nodes = nodes; - this.ways = ways; - this.relations = relations; + this.bounds = bounds; + this.nodes = nodes; + this.ways = ways; + this.relations = relations; - } + } - public Collection getNodes() { - return nodes; - } + public Collection getNodes() { + return nodes; + } - public Collection getWays() { - return ways; - } + public Collection getWays() { + return ways; + } - public Collection getRelations() { - return relations; - } + public Collection getRelations() { + return relations; + } - public Collection getBounds() { - return bounds; - } + public Collection getBounds() { + return bounds; + } } diff --git a/vtm-extras/src/org/oscim/core/osm/OsmElement.java b/vtm-extras/src/org/oscim/core/osm/OsmElement.java index 91b0eb47..07136db9 100644 --- a/vtm-extras/src/org/oscim/core/osm/OsmElement.java +++ b/vtm-extras/src/org/oscim/core/osm/OsmElement.java @@ -16,50 +16,50 @@ */ package org.oscim.core.osm; -import org.oscim.core.TagSet; - import com.vividsolutions.jts.geom.Geometry; +import org.oscim.core.TagSet; + public abstract class OsmElement { - public final TagSet tags; - public final long id; + public final TagSet tags; + public final long id; - public OsmElement(TagSet tags, long id) { - assert tags != null; - this.tags = tags; - this.id = id; - } + public OsmElement(TagSet tags, long id) { + assert tags != null; + this.tags = tags; + this.id = id; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) (id ^ (id >>> 32)); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (id ^ (id >>> 32)); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OsmElement other = (OsmElement) obj; - if (id != other.id) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OsmElement other = (OsmElement) obj; + if (id != other.id) + return false; + return true; + } - /** - * returns the id, plus an one-letter prefix for the element type - */ - @Override - public String toString() { - return "?" + id; - } + /** + * returns the id, plus an one-letter prefix for the element type + */ + @Override + public String toString() { + return "?" + id; + } - public abstract Geometry toJts(); + public abstract Geometry toJts(); } diff --git a/vtm-extras/src/org/oscim/core/osm/OsmMember.java b/vtm-extras/src/org/oscim/core/osm/OsmMember.java index aa04469b..cade5762 100644 --- a/vtm-extras/src/org/oscim/core/osm/OsmMember.java +++ b/vtm-extras/src/org/oscim/core/osm/OsmMember.java @@ -17,24 +17,24 @@ package org.oscim.core.osm; public class OsmMember { - public enum MemberType { - NODE, - WAY, - RELATIOM - } + public enum MemberType { + NODE, + WAY, + RELATIOM + } - public final String role; - public final OsmElement member; + public final String role; + public final OsmElement member; - public OsmMember(String role, OsmElement member) { - assert role != null && member != null; - this.role = role; - this.member = member; - } + public OsmMember(String role, OsmElement member) { + assert role != null && member != null; + this.role = role; + this.member = member; + } - @Override - public String toString() { - return role + ":" + member; - } + @Override + public String toString() { + return role + ":" + member; + } } diff --git a/vtm-extras/src/org/oscim/core/osm/OsmNode.java b/vtm-extras/src/org/oscim/core/osm/OsmNode.java index 94f7d6e2..370b5f84 100644 --- a/vtm-extras/src/org/oscim/core/osm/OsmNode.java +++ b/vtm-extras/src/org/oscim/core/osm/OsmNode.java @@ -16,28 +16,28 @@ */ package org.oscim.core.osm; -import org.oscim.core.TagSet; - import com.vividsolutions.jts.geom.Geometry; +import org.oscim.core.TagSet; + public class OsmNode extends OsmElement { - public final double lat; - public final double lon; + public final double lat; + public final double lon; - public OsmNode(double lat, double lon, TagSet tags, long id) { - super(tags, id); - this.lat = lat; - this.lon = lon; - } + public OsmNode(double lat, double lon, TagSet tags, long id) { + super(tags, id); + this.lat = lat; + this.lon = lon; + } - @Override - public String toString() { - return "n" + id; - } + @Override + public String toString() { + return "n" + id; + } - @Override - public Geometry toJts() { - return null; //bnew Point(new Coordinate(lat, lon), null); - } + @Override + public Geometry toJts() { + return null; //bnew Point(new Coordinate(lat, lon), null); + } } diff --git a/vtm-extras/src/org/oscim/core/osm/OsmRelation.java b/vtm-extras/src/org/oscim/core/osm/OsmRelation.java index 6ef5d356..ec3e71d6 100644 --- a/vtm-extras/src/org/oscim/core/osm/OsmRelation.java +++ b/vtm-extras/src/org/oscim/core/osm/OsmRelation.java @@ -16,32 +16,32 @@ */ package org.oscim.core.osm; -import java.util.ArrayList; -import java.util.List; +import com.vividsolutions.jts.geom.Geometry; import org.oscim.core.TagSet; -import com.vividsolutions.jts.geom.Geometry; +import java.util.ArrayList; +import java.util.List; public class OsmRelation extends OsmElement { - public final List relationMembers; + public final List relationMembers; - // content added after constructor call + // content added after constructor call - public OsmRelation(TagSet tags, long id, int initialMemberSize) { - super(tags, id); - this.relationMembers = - new ArrayList(initialMemberSize); - } + public OsmRelation(TagSet tags, long id, int initialMemberSize) { + super(tags, id); + this.relationMembers = + new ArrayList(initialMemberSize); + } - @Override - public String toString() { - return "r" + id; - } + @Override + public String toString() { + return "r" + id; + } - @Override - public Geometry toJts() { - return null; - } + @Override + public Geometry toJts() { + return null; + } } diff --git a/vtm-extras/src/org/oscim/core/osm/OsmWay.java b/vtm-extras/src/org/oscim/core/osm/OsmWay.java index f5d01991..98e24dc3 100644 --- a/vtm-extras/src/org/oscim/core/osm/OsmWay.java +++ b/vtm-extras/src/org/oscim/core/osm/OsmWay.java @@ -16,43 +16,43 @@ */ package org.oscim.core.osm; -import java.util.List; - -import org.oscim.core.TagSet; - import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory; +import org.oscim.core.TagSet; + +import java.util.List; + public class OsmWay extends OsmElement { - public final List nodes; + public final List nodes; - public OsmWay(TagSet tags, long id, List nodes) { - super(tags, id); - this.nodes = nodes; - } + public OsmWay(TagSet tags, long id, List nodes) { + super(tags, id); + this.nodes = nodes; + } - public boolean isClosed() { - return nodes.size() > 0 && - nodes.get(0).equals(nodes.get(nodes.size() - 1)); - } + public boolean isClosed() { + return nodes.size() > 0 && + nodes.get(0).equals(nodes.get(nodes.size() - 1)); + } - @Override - public String toString() { - return "w" + id; - } + @Override + public String toString() { + return "w" + id; + } - public Geometry toJts() { - double[] coords = new double[nodes.size() * 2]; - int i = 0; - for (OsmNode n : nodes) { - coords[i++] = n.lon; - coords[i++] = n.lat; - } + public Geometry toJts() { + double[] coords = new double[nodes.size() * 2]; + int i = 0; + for (OsmNode n : nodes) { + coords[i++] = n.lon; + coords[i++] = n.lat; + } - CoordinateSequence c = PackedCoordinateSequenceFactory.DOUBLE_FACTORY.create(coords, 2); - return new LineString(c, null); - } + CoordinateSequence c = PackedCoordinateSequenceFactory.DOUBLE_FACTORY.create(coords, 2); + return new LineString(c, null); + } } diff --git a/vtm-extras/src/org/oscim/layers/OsmVectorLayer.java b/vtm-extras/src/org/oscim/layers/OsmVectorLayer.java index 63835ed2..ec00d52a 100644 --- a/vtm-extras/src/org/oscim/layers/OsmVectorLayer.java +++ b/vtm-extras/src/org/oscim/layers/OsmVectorLayer.java @@ -7,13 +7,13 @@ import org.oscim.map.Map; public class OsmVectorLayer extends AbstractVectorLayer { - public OsmVectorLayer(Map map) { - super(map); - } + public OsmVectorLayer(Map map) { + super(map); + } - @Override - protected void processFeatures(Task t, Box b) { + @Override + protected void processFeatures(Task t, Box b) { - } + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java b/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java index f71322d5..4e81d953 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java @@ -16,6 +16,25 @@ */ package org.oscim.tiling.source.geojson; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; + +import org.oscim.core.GeometryBuffer.GeometryType; +import org.oscim.core.MapElement; +import org.oscim.core.Tile; +import org.oscim.tiling.ITileDataSink; +import org.oscim.tiling.source.ITileDecoder; +import org.oscim.utils.ArrayUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.LinkedHashMap; + import static com.fasterxml.jackson.core.JsonToken.END_ARRAY; import static com.fasterxml.jackson.core.JsonToken.END_OBJECT; import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME; @@ -27,324 +46,304 @@ import static com.fasterxml.jackson.core.JsonToken.VALUE_STRING; import static org.oscim.core.MercatorProjection.latitudeToY; import static org.oscim.core.MercatorProjection.longitudeToX; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.LinkedHashMap; - -import org.oscim.core.GeometryBuffer.GeometryType; -import org.oscim.core.MapElement; -import org.oscim.core.Tile; -import org.oscim.tiling.ITileDataSink; -import org.oscim.tiling.source.ITileDecoder; -import org.oscim.utils.ArrayUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; - public class GeoJsonTileDecoder implements ITileDecoder { - static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class); + static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class); - private final MapElement mMapElement; - private final GeoJsonTileSource mTileSource; - private final LinkedHashMap mTagMap; - private final JsonFactory mJsonFactory; + private final MapElement mMapElement; + private final GeoJsonTileSource mTileSource; + private final LinkedHashMap mTagMap; + private final JsonFactory mJsonFactory; - private final static char[] FIELD_FEATURES = "features".toCharArray(); - private final static char[] FIELD_GEOMETRY = "geometry".toCharArray(); - private final static char[] FIELD_PROPERTIES = "properties".toCharArray(); - private final static char[] FIELD_COORDINATES = "coordinates".toCharArray(); - private final static char[] FIELD_TYPE = "type".toCharArray(); + private final static char[] FIELD_FEATURES = "features".toCharArray(); + private final static char[] FIELD_GEOMETRY = "geometry".toCharArray(); + private final static char[] FIELD_PROPERTIES = "properties".toCharArray(); + private final static char[] FIELD_COORDINATES = "coordinates".toCharArray(); + private final static char[] FIELD_TYPE = "type".toCharArray(); - private final static char[] LINETRING = "LineString".toCharArray(); - private final static char[] POLYGON = "Polygon".toCharArray(); - private final static char[] POINT = "Point".toCharArray(); - private final static char[] MULTI_LINESTRING = "MultiLineString".toCharArray(); - private final static char[] MULTI_POLYGON = "MultiPolygon".toCharArray(); - private final static char[] MULTI_POINT = "MultiPoint".toCharArray(); + private final static char[] LINETRING = "LineString".toCharArray(); + private final static char[] POLYGON = "Polygon".toCharArray(); + private final static char[] POINT = "Point".toCharArray(); + private final static char[] MULTI_LINESTRING = "MultiLineString".toCharArray(); + private final static char[] MULTI_POLYGON = "MultiPolygon".toCharArray(); + private final static char[] MULTI_POINT = "MultiPoint".toCharArray(); - private ITileDataSink mTileDataSink; + private ITileDataSink mTileDataSink; - private double mTileY, mTileX, mTileScale; + private double mTileY, mTileX, mTileScale; - public GeoJsonTileDecoder(GeoJsonTileSource tileSource) { - mTileSource = tileSource; - mTagMap = new LinkedHashMap(); - mJsonFactory = new JsonFactory(); + public GeoJsonTileDecoder(GeoJsonTileSource tileSource) { + mTileSource = tileSource; + mTagMap = new LinkedHashMap(); + mJsonFactory = new JsonFactory(); - mMapElement = new MapElement(); - mMapElement.layer = 5; - } + mMapElement = new MapElement(); + mMapElement.layer = 5; + } - @Override - public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException { - mTileDataSink = sink; - mTileScale = 1 << tile.zoomLevel; - mTileX = tile.tileX / mTileScale; - mTileY = tile.tileY / mTileScale; - mTileScale *= Tile.SIZE; + @Override + public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException { + mTileDataSink = sink; + mTileScale = 1 << tile.zoomLevel; + mTileX = tile.tileX / mTileScale; + mTileY = tile.tileY / mTileScale; + mTileScale *= Tile.SIZE; - JsonParser jp = mJsonFactory.createParser(new InputStreamReader(is)); + JsonParser jp = mJsonFactory.createParser(new InputStreamReader(is)); - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == FIELD_NAME) { - if (match(jp, FIELD_FEATURES)) { - if (jp.nextToken() != START_ARRAY) - continue; + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == FIELD_NAME) { + if (match(jp, FIELD_FEATURES)) { + if (jp.nextToken() != START_ARRAY) + continue; - while ((t = jp.nextToken()) != null) { - if (t == START_OBJECT) - parseFeature(jp); + while ((t = jp.nextToken()) != null) { + if (t == START_OBJECT) + parseFeature(jp); - if (t == END_ARRAY) - break; - } - } - } - } - return true; - } + if (t == END_ARRAY) + break; + } + } + } + } + return true; + } - private void parseFeature(JsonParser jp) - throws JsonParseException, IOException { + private void parseFeature(JsonParser jp) + throws JsonParseException, IOException { - mMapElement.clear(); - mMapElement.tags.clear(); - mTagMap.clear(); + mMapElement.clear(); + mMapElement.tags.clear(); + mTagMap.clear(); - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == FIELD_NAME) { - if (match(jp, FIELD_GEOMETRY)) { - if (jp.nextToken() == START_OBJECT) - parseGeometry(jp); - } + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == FIELD_NAME) { + if (match(jp, FIELD_GEOMETRY)) { + if (jp.nextToken() == START_OBJECT) + parseGeometry(jp); + } - if (match(jp, FIELD_PROPERTIES)) { - if (jp.nextToken() == START_OBJECT) - parseProperties(jp); - } - continue; - } - if (t == END_OBJECT) - break; - } + if (match(jp, FIELD_PROPERTIES)) { + if (jp.nextToken() == START_OBJECT) + parseProperties(jp); + } + continue; + } + if (t == END_OBJECT) + break; + } - //add tag information - mTileSource.decodeTags(mMapElement, mTagMap); - if (mMapElement.tags.numTags == 0) - return; + //add tag information + mTileSource.decodeTags(mMapElement, mTagMap); + if (mMapElement.tags.numTags == 0) + return; - mTileSource.postGeomHook(mMapElement); + mTileSource.postGeomHook(mMapElement); - if (mMapElement.type == GeometryType.NONE) - return; + if (mMapElement.type == GeometryType.NONE) + return; - //process this element - mTileDataSink.process(mMapElement); - } + //process this element + mTileDataSink.process(mMapElement); + } - private void parseProperties(JsonParser jp) - throws JsonParseException, IOException { - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == FIELD_NAME) { - String text = jp.getCurrentName(); + private void parseProperties(JsonParser jp) + throws JsonParseException, IOException { + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == FIELD_NAME) { + String text = jp.getCurrentName(); - t = jp.nextToken(); - if (t == VALUE_STRING) { - mTagMap.put(text, jp.getText()); - } else if (t == VALUE_NUMBER_INT) { - mTagMap.put(text, jp.getNumberValue()); - } - continue; - } - if (t == END_OBJECT) - break; - } - } + t = jp.nextToken(); + if (t == VALUE_STRING) { + mTagMap.put(text, jp.getText()); + } else if (t == VALUE_NUMBER_INT) { + mTagMap.put(text, jp.getNumberValue()); + } + continue; + } + if (t == END_OBJECT) + break; + } + } - private void parseGeometry(JsonParser jp) - throws JsonParseException, IOException { + private void parseGeometry(JsonParser jp) + throws JsonParseException, IOException { - boolean multi = false; - GeometryType type = GeometryType.NONE; + boolean multi = false; + GeometryType type = GeometryType.NONE; - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == FIELD_NAME) { - if (match(jp, FIELD_COORDINATES)) { - if (jp.nextToken() != START_ARRAY) - continue; - if (multi) { - parseMulti(jp, type); - } else { - if (type == GeometryType.POLY) - parsePolygon(jp); + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == FIELD_NAME) { + if (match(jp, FIELD_COORDINATES)) { + if (jp.nextToken() != START_ARRAY) + continue; + if (multi) { + parseMulti(jp, type); + } else { + if (type == GeometryType.POLY) + parsePolygon(jp); - if (type == GeometryType.LINE) - parseLineString(jp); + if (type == GeometryType.LINE) + parseLineString(jp); - if (type == GeometryType.POINT) - parseCoordinate(jp); + if (type == GeometryType.POINT) + parseCoordinate(jp); - } - } else if (match(jp, FIELD_TYPE)) { - multi = false; + } + } else if (match(jp, FIELD_TYPE)) { + multi = false; - jp.nextToken(); + jp.nextToken(); - if (match(jp, LINETRING)) - type = GeometryType.LINE; - else if (match(jp, POLYGON)) - type = GeometryType.POLY; - else if (match(jp, POINT)) - type = GeometryType.POINT; - else if (match(jp, MULTI_LINESTRING)) { - type = GeometryType.LINE; - multi = true; - } - else if (match(jp, MULTI_POLYGON)) { - type = GeometryType.POLY; - multi = true; - } - else if (match(jp, MULTI_POINT)) { - type = GeometryType.POINT; - multi = true; - } + if (match(jp, LINETRING)) + type = GeometryType.LINE; + else if (match(jp, POLYGON)) + type = GeometryType.POLY; + else if (match(jp, POINT)) + type = GeometryType.POINT; + else if (match(jp, MULTI_LINESTRING)) { + type = GeometryType.LINE; + multi = true; + } else if (match(jp, MULTI_POLYGON)) { + type = GeometryType.POLY; + multi = true; + } else if (match(jp, MULTI_POINT)) { + type = GeometryType.POINT; + multi = true; + } - if (type == GeometryType.POINT) - mMapElement.startPoints(); - } - continue; - } - if (t == END_OBJECT) - break; - } - } + if (type == GeometryType.POINT) + mMapElement.startPoints(); + } + continue; + } + if (t == END_OBJECT) + break; + } + } - private void parseMulti(JsonParser jp, GeometryType type) - throws JsonParseException, IOException { + private void parseMulti(JsonParser jp, GeometryType type) + throws JsonParseException, IOException { - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == END_ARRAY) - break; + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == END_ARRAY) + break; - if (t == START_ARRAY) { - if (type == GeometryType.POLY) - parsePolygon(jp); + if (t == START_ARRAY) { + if (type == GeometryType.POLY) + parsePolygon(jp); - else if (type == GeometryType.LINE) - parseLineString(jp); + else if (type == GeometryType.LINE) + parseLineString(jp); - else if (type == GeometryType.POINT) - parseCoordinate(jp);; + else if (type == GeometryType.POINT) + parseCoordinate(jp); + ; - } else { - //.... - } - } - } + } else { + //.... + } + } + } - private void parsePolygon(JsonParser jp) - throws JsonParseException, IOException { - int ring = 0; + private void parsePolygon(JsonParser jp) + throws JsonParseException, IOException { + int ring = 0; - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == START_ARRAY) { - if (ring == 0) - mMapElement.startPolygon(); - else - mMapElement.startHole(); + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == START_ARRAY) { + if (ring == 0) + mMapElement.startPolygon(); + else + mMapElement.startHole(); - ring++; - parseCoordSequence(jp); - removeLastPoint(); - continue; - } + ring++; + parseCoordSequence(jp); + removeLastPoint(); + continue; + } - if (t == END_ARRAY) - break; - } - } + if (t == END_ARRAY) + break; + } + } - private void removeLastPoint() { - mMapElement.pointPos -= 2; - mMapElement.index[mMapElement.indexPos] -= 2; - } + private void removeLastPoint() { + mMapElement.pointPos -= 2; + mMapElement.index[mMapElement.indexPos] -= 2; + } - private void parseLineString(JsonParser jp) - throws JsonParseException, IOException { - mMapElement.startLine(); - parseCoordSequence(jp); - } + private void parseLineString(JsonParser jp) + throws JsonParseException, IOException { + mMapElement.startLine(); + parseCoordSequence(jp); + } - private void parseCoordSequence(JsonParser jp) - throws JsonParseException, IOException { + private void parseCoordSequence(JsonParser jp) + throws JsonParseException, IOException { - for (JsonToken t; (t = jp.nextToken()) != null;) { + for (JsonToken t; (t = jp.nextToken()) != null; ) { - if (t == START_ARRAY) { - parseCoordinate(jp); - continue; - } + if (t == START_ARRAY) { + parseCoordinate(jp); + continue; + } - if (t == END_ARRAY) - break; + if (t == END_ARRAY) + break; - } - } + } + } - private void parseCoordinate(JsonParser jp) - throws JsonParseException, IOException { - int pos = 0; - double x = 0, y = 0; //, z = 0; + private void parseCoordinate(JsonParser jp) + throws JsonParseException, IOException { + int pos = 0; + double x = 0, y = 0; //, z = 0; - for (JsonToken t; (t = jp.nextToken()) != null;) { - if (t == VALUE_NUMBER_FLOAT || t == VALUE_NUMBER_INT) { + for (JsonToken t; (t = jp.nextToken()) != null; ) { + if (t == VALUE_NUMBER_FLOAT || t == VALUE_NUMBER_INT) { - // avoid String allocation (by getDouble...) - char[] val = jp.getTextCharacters(); - int offset = jp.getTextOffset(); - int length = jp.getTextLength(); - double c = ArrayUtils.parseNumber(val, offset, offset + length); + // avoid String allocation (by getDouble...) + char[] val = jp.getTextCharacters(); + int offset = jp.getTextOffset(); + int length = jp.getTextLength(); + double c = ArrayUtils.parseNumber(val, offset, offset + length); - if (pos == 0) - x = c; - if (pos == 1) - y = c; - //if (pos == 2) - //z = c; + if (pos == 0) + x = c; + if (pos == 1) + y = c; + //if (pos == 2) + //z = c; - pos++; - continue; - } + pos++; + continue; + } - if (t == END_ARRAY) - break; - } + if (t == END_ARRAY) + break; + } - mMapElement.addPoint((float) ((longitudeToX(x) - mTileX) * mTileScale), - (float) ((latitudeToY(y) - mTileY) * mTileScale)); + mMapElement.addPoint((float) ((longitudeToX(x) - mTileX) * mTileScale), + (float) ((latitudeToY(y) - mTileY) * mTileScale)); - } + } - private final static boolean match(JsonParser jp, char[] fieldName) - throws JsonParseException, IOException { + private final static boolean match(JsonParser jp, char[] fieldName) + throws JsonParseException, IOException { - int length = jp.getTextLength(); - if (length != fieldName.length) - return false; + int length = jp.getTextLength(); + if (length != fieldName.length) + return false; - char[] val = jp.getTextCharacters(); - int offset = jp.getTextOffset(); + char[] val = jp.getTextCharacters(); + int offset = jp.getTextOffset(); - for (int i = 0; i < length; i++) { - if (fieldName[i] != val[i + offset]) - return false; - } + for (int i = 0; i < length; i++) { + if (fieldName[i] != val[i + offset]) + return false; + } - return true; - } + return true; + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileSource.java index 3758c1b7..21b4808e 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/GeoJsonTileSource.java @@ -16,56 +16,60 @@ */ package org.oscim.tiling.source.geojson; -import java.util.HashMap; -import java.util.Map; - import org.oscim.core.MapElement; import org.oscim.core.Tag; import org.oscim.tiling.ITileDataSource; import org.oscim.tiling.source.UrlTileDataSource; import org.oscim.tiling.source.UrlTileSource; +import java.util.HashMap; +import java.util.Map; + public abstract class GeoJsonTileSource extends UrlTileSource { - public GeoJsonTileSource(String url) { - super(url, "/{Z}/{X}/{Y}.json"); - Map opt = new HashMap(); - opt.put("Accept-Encoding", "gzip"); - setHttpRequestHeaders(opt); - } + public GeoJsonTileSource(String url) { + super(url, "/{Z}/{X}/{Y}.json"); + Map opt = new HashMap(); + opt.put("Accept-Encoding", "gzip"); + setHttpRequestHeaders(opt); + } - public GeoJsonTileSource(String url, int zoomMin, int zoomMax) { - super(url, "/{Z}/{X}/{Y}.json", zoomMin, zoomMax); - Map opt = new HashMap(); - opt.put("Accept-Encoding", "gzip"); - setHttpRequestHeaders(opt); - } + public GeoJsonTileSource(String url, int zoomMin, int zoomMax) { + super(url, "/{Z}/{X}/{Y}.json", zoomMin, zoomMax); + Map opt = new HashMap(); + opt.put("Accept-Encoding", "gzip"); + setHttpRequestHeaders(opt); + } - @Override - public ITileDataSource getDataSource() { + @Override + public ITileDataSource getDataSource() { - return new UrlTileDataSource(this, new GeoJsonTileDecoder(this), getHttpEngine()); - } + return new UrlTileDataSource(this, new GeoJsonTileDecoder(this), getHttpEngine()); + } - public Tag getFeatureTag() { - return null; - } + public Tag getFeatureTag() { + return null; + } - /** allow overriding tag handling */ - public abstract void decodeTags(MapElement mapElement, Map properties); + /** + * allow overriding tag handling + */ + public abstract void decodeTags(MapElement mapElement, Map properties); - public Tag rewriteTag(String key, Object value) { + public Tag rewriteTag(String key, Object value) { - if (value == null) - return null; + if (value == null) + return null; - String val = (value instanceof String) ? (String) value : String.valueOf(value); + String val = (value instanceof String) ? (String) value : String.valueOf(value); - return new Tag(key, val); - } + return new Tag(key, val); + } - /** modify mapElement before process() */ - public void postGeomHook(MapElement mapElement) { + /** + * modify mapElement before process() + */ + public void postGeomHook(MapElement mapElement) { - } + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmBuildingJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmBuildingJsonTileSource.java index 9ad02bac..da50e959 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmBuildingJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmBuildingJsonTileSource.java @@ -16,23 +16,23 @@ */ package org.oscim.tiling.source.geojson; -import java.util.Map; - import org.oscim.core.MapElement; import org.oscim.core.Tag; +import java.util.Map; + public class OsmBuildingJsonTileSource extends GeoJsonTileSource { - public OsmBuildingJsonTileSource() { - super("http://tile.openstreetmap.us/vectiles-buildings"); - } + public OsmBuildingJsonTileSource() { + super("http://tile.openstreetmap.us/vectiles-buildings"); + } - Tag mTagBuilding = new Tag("building", "yes"); + Tag mTagBuilding = new Tag("building", "yes"); - @Override - public void decodeTags(MapElement mapElement, Map properties) { + @Override + public void decodeTags(MapElement mapElement, Map properties) { - mapElement.tags.add(mTagBuilding); + mapElement.tags.add(mTagBuilding); - } + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmLanduseJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmLanduseJsonTileSource.java index fb8d7049..e3f12916 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmLanduseJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmLanduseJsonTileSource.java @@ -16,112 +16,112 @@ */ package org.oscim.tiling.source.geojson; -import java.util.LinkedHashMap; -import java.util.Map; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.LinkedHashMap; +import java.util.Map; + public class OsmLanduseJsonTileSource extends GeoJsonTileSource { - static final Logger log = LoggerFactory.getLogger(OsmLanduseJsonTileSource.class); + static final Logger log = LoggerFactory.getLogger(OsmLanduseJsonTileSource.class); - public OsmLanduseJsonTileSource() { - super("http://tile.openstreetmap.us/vectiles-land-usages"); - } + public OsmLanduseJsonTileSource() { + super("http://tile.openstreetmap.us/vectiles-land-usages"); + } - private static LinkedHashMap mappings = - new LinkedHashMap(); + private static LinkedHashMap mappings = + new LinkedHashMap(); - static void addMapping(String key, String val) { - mappings.put(val, new Tag(key, val)); - } + static void addMapping(String key, String val) { + mappings.put(val, new Tag(key, val)); + } - static { - addMapping("landuse", "residential"); - addMapping("landuse", "commercial"); - addMapping("landuse", "retail"); - addMapping("landuse", "railway"); - addMapping("landuse", "grass"); - addMapping("landuse", "meadow"); - addMapping("landuse", "forest"); - addMapping("landuse", "farm"); - addMapping("landuse", "allotments"); - addMapping("landuse", "cemetery"); - addMapping("landuse", "farmyard"); - addMapping("landuse", "farmland"); - addMapping("landuse", "quarry"); - addMapping("landuse", "military"); - addMapping("landuse", "industrial"); - addMapping("landuse", "greenfield"); - addMapping("landuse", "village_green"); - addMapping("landuse", "recreation_ground"); - addMapping("landuse", "conservation"); - addMapping("landuse", "landfill"); - addMapping("landuse", "construction"); + static { + addMapping("landuse", "residential"); + addMapping("landuse", "commercial"); + addMapping("landuse", "retail"); + addMapping("landuse", "railway"); + addMapping("landuse", "grass"); + addMapping("landuse", "meadow"); + addMapping("landuse", "forest"); + addMapping("landuse", "farm"); + addMapping("landuse", "allotments"); + addMapping("landuse", "cemetery"); + addMapping("landuse", "farmyard"); + addMapping("landuse", "farmland"); + addMapping("landuse", "quarry"); + addMapping("landuse", "military"); + addMapping("landuse", "industrial"); + addMapping("landuse", "greenfield"); + addMapping("landuse", "village_green"); + addMapping("landuse", "recreation_ground"); + addMapping("landuse", "conservation"); + addMapping("landuse", "landfill"); + addMapping("landuse", "construction"); - addMapping("leisure", "common"); - addMapping("leisure", "park"); - addMapping("leisure", "pitch"); - addMapping("leisure", "garden"); - addMapping("leisure", "sports_centre"); - addMapping("leisure", "playground"); - addMapping("leisure", "nature_reserve"); - addMapping("leisure", "golf_course"); - addMapping("leisure", "stadium"); + addMapping("leisure", "common"); + addMapping("leisure", "park"); + addMapping("leisure", "pitch"); + addMapping("leisure", "garden"); + addMapping("leisure", "sports_centre"); + addMapping("leisure", "playground"); + addMapping("leisure", "nature_reserve"); + addMapping("leisure", "golf_course"); + addMapping("leisure", "stadium"); - addMapping("amenity", "hospital"); - addMapping("amenity", "cinema"); - addMapping("amenity", "school"); - addMapping("amenity", "college"); - addMapping("amenity", "university"); - addMapping("amenity", "theatre"); - addMapping("amenity", "library"); - addMapping("amenity", "parking"); - addMapping("amenity", "place_of_worship"); + addMapping("amenity", "hospital"); + addMapping("amenity", "cinema"); + addMapping("amenity", "school"); + addMapping("amenity", "college"); + addMapping("amenity", "university"); + addMapping("amenity", "theatre"); + addMapping("amenity", "library"); + addMapping("amenity", "parking"); + addMapping("amenity", "place_of_worship"); - addMapping("highway", "pedestrian"); - addMapping("highway", "footway"); - addMapping("highway", "service"); - addMapping("highway", "street"); + addMapping("highway", "pedestrian"); + addMapping("highway", "footway"); + addMapping("highway", "service"); + addMapping("highway", "street"); - addMapping("natural", "scrub"); - addMapping("natural", "wood"); + addMapping("natural", "scrub"); + addMapping("natural", "wood"); - mappings.put("urban area", new Tag("landuse", "urban")); - mappings.put("park or protected land", new Tag("leisure", "park")); - } + mappings.put("urban area", new Tag("landuse", "urban")); + mappings.put("park or protected land", new Tag("leisure", "park")); + } - private final static Tag mTagArea = new Tag("area", "yes"); + private final static Tag mTagArea = new Tag("area", "yes"); - @Override - public void decodeTags(MapElement mapElement, Map properties) { + @Override + public void decodeTags(MapElement mapElement, Map properties) { - for (Map.Entry entry : properties.entrySet()) { - String key = entry.getKey(); + for (Map.Entry entry : properties.entrySet()) { + String key = entry.getKey(); - if (!"kind".equals(key)) - continue; + if (!"kind".equals(key)) + continue; - String value = (String) entry.getValue(); + String value = (String) entry.getValue(); - Tag tag = mappings.get(value); - if (tag == null) { - System.out.println("unmatched " + value); - } else { - mapElement.tags.add(tag); - } - break; - } - } + Tag tag = mappings.get(value); + if (tag == null) { + System.out.println("unmatched " + value); + } else { + mapElement.tags.add(tag); + } + break; + } + } - @Override - public void postGeomHook(MapElement mapElement) { - //if (mapElement.type != GeometryType.POLY) { - mapElement.type = GeometryType.POLY; - mapElement.tags.add(mTagArea); - //} - } + @Override + public void postGeomHook(MapElement mapElement) { + //if (mapElement.type != GeometryType.POLY) { + mapElement.type = GeometryType.POLY; + mapElement.tags.add(mTagArea); + //} + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLabelJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLabelJsonTileSource.java index 76c87b05..35b042ec 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLabelJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLabelJsonTileSource.java @@ -25,35 +25,34 @@ import java.util.Map; public class OsmRoadLabelJsonTileSource extends GeoJsonTileSource { - static final Logger log = LoggerFactory.getLogger(OsmRoadLabelJsonTileSource.class); + static final Logger log = LoggerFactory.getLogger(OsmRoadLabelJsonTileSource.class); - public OsmRoadLabelJsonTileSource() { - super("http://tile.openstreetmap.us/vectiles-skeletron"); - } + public OsmRoadLabelJsonTileSource() { + super("http://tile.openstreetmap.us/vectiles-skeletron"); + } - @Override - public void decodeTags(MapElement mapElement, Map properties) { - String highway = null; + @Override + public void decodeTags(MapElement mapElement, Map properties) { + String highway = null; - for (Map.Entry entry : properties.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - //log.debug(key + " : " + String.valueOf(value)); + for (Map.Entry entry : properties.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + //log.debug(key + " : " + String.valueOf(value)); - if (value == null) - continue; + if (value == null) + continue; - if ("highway".equals(key) && value instanceof String) { - highway = (String) entry.getValue(); - } - else if ("name".equals(key) && value instanceof String) { - mapElement.tags.add(new Tag("name", (String) value)); - } - } + if ("highway".equals(key) && value instanceof String) { + highway = (String) entry.getValue(); + } else if ("name".equals(key) && value instanceof String) { + mapElement.tags.add(new Tag("name", (String) value)); + } + } - if (highway == null) - return; + if (highway == null) + return; - mapElement.tags.add(new Tag("highway", highway)); - } + mapElement.tags.add(new Tag("highway", highway)); + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLineJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLineJsonTileSource.java index 4c66edee..c33e17f7 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLineJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmRoadLineJsonTileSource.java @@ -16,83 +16,78 @@ */ package org.oscim.tiling.source.geojson; -import java.util.Map; - import org.oscim.core.MapElement; import org.oscim.core.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; + public class OsmRoadLineJsonTileSource extends GeoJsonTileSource { - static final Logger log = LoggerFactory.getLogger(OsmRoadLineJsonTileSource.class); + static final Logger log = LoggerFactory.getLogger(OsmRoadLineJsonTileSource.class); - Tag mTagTunnel = new Tag("tunnel", "yes"); - Tag mTagBridge = new Tag("bridge", "yes"); + Tag mTagTunnel = new Tag("tunnel", "yes"); + Tag mTagBridge = new Tag("bridge", "yes"); - public OsmRoadLineJsonTileSource() { - super("http://tile.openstreetmap.us/vectiles-highroad"); - } + public OsmRoadLineJsonTileSource() { + super("http://tile.openstreetmap.us/vectiles-highroad"); + } - @Override - public void decodeTags(MapElement mapElement, Map properties) { - String highway = null; - boolean isLink = false; + @Override + public void decodeTags(MapElement mapElement, Map properties) { + String highway = null; + boolean isLink = false; - mapElement.layer = 5; + mapElement.layer = 5; - for (Map.Entry entry : properties.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - //log.debug(key + " : " + String.valueOf(value)); + for (Map.Entry entry : properties.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + //log.debug(key + " : " + String.valueOf(value)); - if (value == null) - continue; + if (value == null) + continue; - if ("no".equals(value)) - continue; + if ("no".equals(value)) + continue; - if ("highway".equals(key) && value instanceof String) { - highway = (String) entry.getValue(); - } - else if ("is_link".equals(key)) { - isLink = "yes".equals(value); - } - else if ("is_tunnel".equals(key)) { - mapElement.tags.add(mTagTunnel); - } - else if ("is_bridge".equals(key)) { - mapElement.tags.add(mTagBridge); - } - else if ("sort_key".equals(key)) { - if (value instanceof Integer) - mapElement.layer = 5 + (Integer) value; - } - else if ("railway".equals(key) && value instanceof String) { - mapElement.tags.add(new Tag("railway", (String) value)); - } - } + if ("highway".equals(key) && value instanceof String) { + highway = (String) entry.getValue(); + } else if ("is_link".equals(key)) { + isLink = "yes".equals(value); + } else if ("is_tunnel".equals(key)) { + mapElement.tags.add(mTagTunnel); + } else if ("is_bridge".equals(key)) { + mapElement.tags.add(mTagBridge); + } else if ("sort_key".equals(key)) { + if (value instanceof Integer) + mapElement.layer = 5 + (Integer) value; + } else if ("railway".equals(key) && value instanceof String) { + mapElement.tags.add(new Tag("railway", (String) value)); + } + } - if (highway == null) - return; + if (highway == null) + return; - if (isLink) - highway += "_link"; + if (isLink) + highway += "_link"; - mapElement.tags.add(new Tag("highway", highway)); + mapElement.tags.add(new Tag("highway", highway)); - } + } - @Override - public Tag rewriteTag(String key, Object value) { - if ("kind".equals(key)) - return null; + @Override + public Tag rewriteTag(String key, Object value) { + if ("kind".equals(key)) + return null; - if (value == null) - return null; + if (value == null) + return null; - String val = (value instanceof String) ? (String) value : String.valueOf(value); + String val = (value instanceof String) ? (String) value : String.valueOf(value); - return new Tag(key, val); - } + return new Tag(key, val); + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmWaterJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmWaterJsonTileSource.java index 70a087f9..de6e529d 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/OsmWaterJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/OsmWaterJsonTileSource.java @@ -16,23 +16,23 @@ */ package org.oscim.tiling.source.geojson; -import java.util.Map; - import org.oscim.core.MapElement; import org.oscim.core.Tag; +import java.util.Map; + public class OsmWaterJsonTileSource extends GeoJsonTileSource { - public OsmWaterJsonTileSource() { - super("http://tile.openstreetmap.us/vectiles-water-areas"); - } + public OsmWaterJsonTileSource() { + super("http://tile.openstreetmap.us/vectiles-water-areas"); + } - Tag mTagWater = new Tag("natural", "water"); + Tag mTagWater = new Tag("natural", "water"); - @Override - public void decodeTags(MapElement mapElement, Map properties) { + @Override + public void decodeTags(MapElement mapElement, Map properties) { - mapElement.tags.add(mTagWater); + mapElement.tags.add(mTagWater); - } + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/geojson/RiverJsonTileSource.java b/vtm-extras/src/org/oscim/tiling/source/geojson/RiverJsonTileSource.java index 7db9cc6c..56f7efcf 100644 --- a/vtm-extras/src/org/oscim/tiling/source/geojson/RiverJsonTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/geojson/RiverJsonTileSource.java @@ -1,22 +1,22 @@ package org.oscim.tiling.source.geojson; -import java.util.Map; - import org.oscim.core.MapElement; import org.oscim.core.Tag; +import java.util.Map; + public class RiverJsonTileSource extends GeoJsonTileSource { - public RiverJsonTileSource() { - super("http://www.somebits.com:8001/rivers"); - } + public RiverJsonTileSource() { + super("http://www.somebits.com:8001/rivers"); + } - Tag mTagWater = new Tag("waterway", "river"); + Tag mTagWater = new Tag("waterway", "river"); - @Override - public void decodeTags(MapElement mapElement, Map properties) { + @Override + public void decodeTags(MapElement mapElement, Map properties) { - mapElement.tags.add(mTagWater); + mapElement.tags.add(mTagWater); - } + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/mapnik/MapnikVectorTileSource.java b/vtm-extras/src/org/oscim/tiling/source/mapnik/MapnikVectorTileSource.java index 8bd761aa..995f5573 100644 --- a/vtm-extras/src/org/oscim/tiling/source/mapnik/MapnikVectorTileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/mapnik/MapnikVectorTileSource.java @@ -23,36 +23,36 @@ import org.oscim.tiling.source.UrlTileSource; public class MapnikVectorTileSource extends UrlTileSource { - public MapnikVectorTileSource() { - super("http://d1s11ojcu7opje.cloudfront.net/dev/764e0b8d", ""); - setUrlFormatter(new TileUrlFormatter() { - @Override - public String formatTilePath(UrlTileSource tileSource, Tile tile) { - // url formatter for mapbox streets - byte[] hexTable = { - '0', '1', '2', '3', - '4', '5', '6', '7', - '8', '9', 'a', 'b', - 'c', 'd', 'e', 'f' - }; - StringBuilder sb = new StringBuilder(); - sb.append('/'); - sb.append(hexTable[(tile.tileX) % 16]); - sb.append(hexTable[(tile.tileY) % 16]); - sb.append('/'); - sb.append(tile.zoomLevel); - sb.append('/'); - sb.append(tile.tileX); - sb.append('/'); - sb.append(tile.tileY); + public MapnikVectorTileSource() { + super("http://d1s11ojcu7opje.cloudfront.net/dev/764e0b8d", ""); + setUrlFormatter(new TileUrlFormatter() { + @Override + public String formatTilePath(UrlTileSource tileSource, Tile tile) { + // url formatter for mapbox streets + byte[] hexTable = { + '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f' + }; + StringBuilder sb = new StringBuilder(); + sb.append('/'); + sb.append(hexTable[(tile.tileX) % 16]); + sb.append(hexTable[(tile.tileY) % 16]); + sb.append('/'); + sb.append(tile.zoomLevel); + sb.append('/'); + sb.append(tile.tileX); + sb.append('/'); + sb.append(tile.tileY); - return sb.toString(); - } - }); - } + return sb.toString(); + } + }); + } - @Override - public ITileDataSource getDataSource() { - return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); - } + @Override + public ITileDataSource getDataSource() { + return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/mapnik/TileDecoder.java b/vtm-extras/src/org/oscim/tiling/source/mapnik/TileDecoder.java index dff9a23d..de9eb773 100644 --- a/vtm-extras/src/org/oscim/tiling/source/mapnik/TileDecoder.java +++ b/vtm-extras/src/org/oscim/tiling/source/mapnik/TileDecoder.java @@ -16,11 +16,6 @@ */ package org.oscim.tiling.source.mapnik; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.zip.InflaterInputStream; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.Tag; @@ -32,567 +27,572 @@ import org.oscim.utils.pool.Pool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.zip.InflaterInputStream; + public class TileDecoder extends PbfDecoder { - static final Logger log = LoggerFactory.getLogger(TileDecoder.class); + static final Logger log = LoggerFactory.getLogger(TileDecoder.class); - private static final int TAG_TILE_LAYERS = 3; - - private static final int TAG_LAYER_VERSION = 15; - private static final int TAG_LAYER_NAME = 1; - private static final int TAG_LAYER_FEATURES = 2; - private static final int TAG_LAYER_KEYS = 3; - private static final int TAG_LAYER_VALUES = 4; - private static final int TAG_LAYER_EXTENT = 5; + private static final int TAG_TILE_LAYERS = 3; + + private static final int TAG_LAYER_VERSION = 15; + private static final int TAG_LAYER_NAME = 1; + private static final int TAG_LAYER_FEATURES = 2; + private static final int TAG_LAYER_KEYS = 3; + private static final int TAG_LAYER_VALUES = 4; + private static final int TAG_LAYER_EXTENT = 5; - private static final int TAG_FEATURE_ID = 1; - private static final int TAG_FEATURE_TAGS = 2; - private static final int TAG_FEATURE_TYPE = 3; - private static final int TAG_FEATURE_GEOMETRY = 4; - - private static final int TAG_VALUE_STRING = 1; - private static final int TAG_VALUE_FLOAT = 2; - private static final int TAG_VALUE_DOUBLE = 3; - private static final int TAG_VALUE_LONG = 4; - private static final int TAG_VALUE_UINT = 5; - private static final int TAG_VALUE_SINT = 6; - private static final int TAG_VALUE_BOOL = 7; - - private static final int TAG_GEOM_UNKNOWN = 0; - private static final int TAG_GEOM_POINT = 1; - private static final int TAG_GEOM_LINE = 2; - private static final int TAG_GEOM_POLYGON = 3; - - private short[] mTmpTags = new short[1024]; - - private Tile mTile; - private final String mLocale = "de"; - private ITileDataSink mMapDataCallback; + private static final int TAG_FEATURE_ID = 1; + private static final int TAG_FEATURE_TAGS = 2; + private static final int TAG_FEATURE_TYPE = 3; + private static final int TAG_FEATURE_GEOMETRY = 4; + + private static final int TAG_VALUE_STRING = 1; + private static final int TAG_VALUE_FLOAT = 2; + private static final int TAG_VALUE_DOUBLE = 3; + private static final int TAG_VALUE_LONG = 4; + private static final int TAG_VALUE_UINT = 5; + private static final int TAG_VALUE_SINT = 6; + private static final int TAG_VALUE_BOOL = 7; + + private static final int TAG_GEOM_UNKNOWN = 0; + private static final int TAG_GEOM_POINT = 1; + private static final int TAG_GEOM_LINE = 2; + private static final int TAG_GEOM_POLYGON = 3; + + private short[] mTmpTags = new short[1024]; + + private Tile mTile; + private final String mLocale = "de"; + private ITileDataSink mMapDataCallback; - private final static float REF_TILE_SIZE = 4096.0f; - private float mScale; + private final static float REF_TILE_SIZE = 4096.0f; + private float mScale; - @Override - public boolean decode(Tile tile, ITileDataSink mapDataCallback, InputStream is) - throws IOException { + @Override + public boolean decode(Tile tile, ITileDataSink mapDataCallback, InputStream is) + throws IOException { - if (debug) - log.debug(tile + " decode"); + if (debug) + log.debug(tile + " decode"); - setInputStream(new InflaterInputStream(is)); - mTile = tile; - mMapDataCallback = mapDataCallback; - mScale = REF_TILE_SIZE / Tile.SIZE; - - int val; - - while (hasData() && (val = decodeVarint32()) > 0) { - // read tag and wire type - int tag = (val >> 3); - - switch (tag) { - case TAG_TILE_LAYERS: - decodeLayer(); - break; - - default: - error(mTile + " invalid type for tile: " + tag); - return false; - } - } - - if (hasData()) { - error(tile + " invalid tile"); - return false; - } - return true; - } - - private boolean decodeLayer() throws IOException { - - //int version = 0; - //int extent = 4096; - - int bytes = decodeVarint32(); - - ArrayList keys = new ArrayList(); - ArrayList values = new ArrayList(); - - String name = null; - int numFeatures = 0; - ArrayList features = new ArrayList(); - - int end = position() + bytes; - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >> 3); - - switch (tag) { - case TAG_LAYER_KEYS: - keys.add(decodeString()); - break; - - case TAG_LAYER_VALUES: - values.add(decodeValue()); - break; - - case TAG_LAYER_FEATURES: - numFeatures++; - decodeFeature(features); - break; - - case TAG_LAYER_VERSION: - //version = - decodeVarint32(); - break; - - case TAG_LAYER_NAME: - name = decodeString(); - break; - - case TAG_LAYER_EXTENT: - //extent = - decodeVarint32(); - break; - - default: - error(mTile + " invalid type for layer: " + tag); - break; - } - - } - - Tag layerTag = new Tag(name, Tag.VALUE_YES); - - if (numFeatures == 0) - return true; - - int[] ignoreLocal = new int[20]; - int numIgnore = 0; - - int fallBackLocal = -1; - int matchedLocal = -1; - - for (int i = 0; i < keys.size(); i++) { - String key = keys.get(i); - if (!key.startsWith(Tag.KEY_NAME)) - continue; - int len = key.length(); - if (len == 4) { - fallBackLocal = i; - continue; - } - if (len < 7) { - ignoreLocal[numIgnore++] = i; - continue; - } - - if (mLocale.equals(key.substring(5))) { - //log.debug("found local " + key); - matchedLocal = i; - } else - ignoreLocal[numIgnore++] = i; - - } - - for (Feature f : features) { - - if (f.elem.type == GeometryType.NONE) - continue; - - f.elem.tags.clear(); - f.elem.tags.add(layerTag); - - boolean hasName = false; - String fallbackName = null; - - tagLoop: for (int j = 0; j < (f.numTags << 1); j += 2) { - int keyIdx = f.tags[j]; - for (int i = 0; i < numIgnore; i++) - if (keyIdx == ignoreLocal[i]) - continue tagLoop; - - if (keyIdx == fallBackLocal) { - fallbackName = values.get(f.tags[j + 1]); - continue; - } - - String key; - String val = values.get(f.tags[j + 1]); - - if (keyIdx == matchedLocal) { - hasName = true; - f.elem.tags.add(new Tag(Tag.KEY_NAME, val, false)); - - } else { - key = keys.get(keyIdx); - f.elem.tags.add(new Tag(key, val)); - } - } - - if (!hasName && fallbackName != null) - f.elem.tags.add(new Tag(Tag.KEY_NAME, fallbackName, false)); - - // FIXME extract layer tag here - f.elem.setLayer(5); - mMapDataCallback.process(f.elem); - f = mFeaturePool.release(f); - } - - return true; - } + setInputStream(new InflaterInputStream(is)); + mTile = tile; + mMapDataCallback = mapDataCallback; + mScale = REF_TILE_SIZE / Tile.SIZE; + + int val; + + while (hasData() && (val = decodeVarint32()) > 0) { + // read tag and wire type + int tag = (val >> 3); + + switch (tag) { + case TAG_TILE_LAYERS: + decodeLayer(); + break; + + default: + error(mTile + " invalid type for tile: " + tag); + return false; + } + } + + if (hasData()) { + error(tile + " invalid tile"); + return false; + } + return true; + } + + private boolean decodeLayer() throws IOException { + + //int version = 0; + //int extent = 4096; + + int bytes = decodeVarint32(); + + ArrayList keys = new ArrayList(); + ArrayList values = new ArrayList(); + + String name = null; + int numFeatures = 0; + ArrayList features = new ArrayList(); + + int end = position() + bytes; + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >> 3); + + switch (tag) { + case TAG_LAYER_KEYS: + keys.add(decodeString()); + break; + + case TAG_LAYER_VALUES: + values.add(decodeValue()); + break; + + case TAG_LAYER_FEATURES: + numFeatures++; + decodeFeature(features); + break; + + case TAG_LAYER_VERSION: + //version = + decodeVarint32(); + break; + + case TAG_LAYER_NAME: + name = decodeString(); + break; + + case TAG_LAYER_EXTENT: + //extent = + decodeVarint32(); + break; + + default: + error(mTile + " invalid type for layer: " + tag); + break; + } + + } + + Tag layerTag = new Tag(name, Tag.VALUE_YES); + + if (numFeatures == 0) + return true; + + int[] ignoreLocal = new int[20]; + int numIgnore = 0; + + int fallBackLocal = -1; + int matchedLocal = -1; + + for (int i = 0; i < keys.size(); i++) { + String key = keys.get(i); + if (!key.startsWith(Tag.KEY_NAME)) + continue; + int len = key.length(); + if (len == 4) { + fallBackLocal = i; + continue; + } + if (len < 7) { + ignoreLocal[numIgnore++] = i; + continue; + } + + if (mLocale.equals(key.substring(5))) { + //log.debug("found local " + key); + matchedLocal = i; + } else + ignoreLocal[numIgnore++] = i; + + } + + for (Feature f : features) { + + if (f.elem.type == GeometryType.NONE) + continue; + + f.elem.tags.clear(); + f.elem.tags.add(layerTag); + + boolean hasName = false; + String fallbackName = null; + + tagLoop: + for (int j = 0; j < (f.numTags << 1); j += 2) { + int keyIdx = f.tags[j]; + for (int i = 0; i < numIgnore; i++) + if (keyIdx == ignoreLocal[i]) + continue tagLoop; + + if (keyIdx == fallBackLocal) { + fallbackName = values.get(f.tags[j + 1]); + continue; + } + + String key; + String val = values.get(f.tags[j + 1]); + + if (keyIdx == matchedLocal) { + hasName = true; + f.elem.tags.add(new Tag(Tag.KEY_NAME, val, false)); + + } else { + key = keys.get(keyIdx); + f.elem.tags.add(new Tag(key, val)); + } + } + + if (!hasName && fallbackName != null) + f.elem.tags.add(new Tag(Tag.KEY_NAME, fallbackName, false)); + + // FIXME extract layer tag here + f.elem.setLayer(5); + mMapDataCallback.process(f.elem); + f = mFeaturePool.release(f); + } + + return true; + } - private final Pool mFeaturePool = new Pool() { - int count; + private final Pool mFeaturePool = new Pool() { + int count; - @Override - protected Feature createItem() { - count++; - return new Feature(); - } - - @Override - protected boolean clearItem(Feature item) { - if (count > 100) { - count--; - return false; - } - - item.elem.tags.clear(); - item.elem.clear(); - item.tags = null; - item.type = 0; - item.numTags = 0; - - return true; - } - }; - - static class Feature extends Inlist { - short[] tags; - int numTags; - int type; - - final MapElement elem; - - Feature() { - elem = new MapElement(); - } - - boolean match(short otherTags[], int otherNumTags, int otherType) { - if (numTags != otherNumTags) - return false; - - if (type != otherType) - return false; + @Override + protected Feature createItem() { + count++; + return new Feature(); + } + + @Override + protected boolean clearItem(Feature item) { + if (count > 100) { + count--; + return false; + } + + item.elem.tags.clear(); + item.elem.clear(); + item.tags = null; + item.type = 0; + item.numTags = 0; + + return true; + } + }; + + static class Feature extends Inlist { + short[] tags; + int numTags; + int type; + + final MapElement elem; + + Feature() { + elem = new MapElement(); + } + + boolean match(short otherTags[], int otherNumTags, int otherType) { + if (numTags != otherNumTags) + return false; + + if (type != otherType) + return false; - for (int i = 0; i < numTags << 1; i++) { - if (tags[i] != otherTags[i]) - return false; - } - return true; - } - - } - - private void decodeFeature(ArrayList features) throws IOException { - int bytes = decodeVarint32(); - int end = position() + bytes; - - int type = 0; - //long id; - - lastX = 0; - lastY = 0; - - mTmpTags[0] = -1; - - Feature curFeature = null; - int numTags = 0; - - //log.debug("start feature"); - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >>> 3); - - switch (tag) { - case TAG_FEATURE_ID: - //id = - decodeVarint32(); - break; - - case TAG_FEATURE_TAGS: - mTmpTags = decodeUnsignedVarintArray(mTmpTags); - - for (; numTags < mTmpTags.length && mTmpTags[numTags] >= 0;) - numTags += 2; - - numTags >>= 1; - - break; - - case TAG_FEATURE_TYPE: - type = decodeVarint32(); - //log.debug("got type " + type); - break; - - case TAG_FEATURE_GEOMETRY: - - for (Feature f : features) { - if (f.match(mTmpTags, numTags, type)) { - curFeature = f; - break; - } - } - - if (curFeature == null) { - curFeature = mFeaturePool.get(); - curFeature.tags = new short[numTags << 1]; - System.arraycopy(mTmpTags, 0, curFeature.tags, 0, numTags << 1); - curFeature.numTags = numTags; - curFeature.type = type; - - features.add(curFeature); - } - - decodeCoordinates(type, curFeature); - break; - - default: - error(mTile + " invalid type for feature: " + tag); - break; - } - } - } - - private final static int CLOSE_PATH = 0x07; - private final static int MOVE_TO = 0x01; - //private final static int LINE_TO = 0x02; - - private int lastX, lastY; - - private int decodeCoordinates(int type, Feature feature) throws IOException { - int bytes = decodeVarint32(); - fillBuffer(bytes); - - if (feature == null) { - bufferPos += bytes; - return 0; - } - - MapElement elem = feature.elem; - boolean isPoint = false; - boolean isPoly = false; - boolean isLine = false; - - if (type == TAG_GEOM_LINE) { - elem.startLine(); - isLine = true; - } - else if (type == TAG_GEOM_POLYGON) { - elem.startPolygon(); - isPoly = true; - } else if (type == TAG_GEOM_POINT) { - isPoint = true; - elem.startPoints(); - } else if (type == TAG_GEOM_UNKNOWN) - elem.startPoints(); - - boolean even = true; - int val; - - int curX = 0; - int curY = 0; - int prevX = 0; - int prevY = 0; - - int cmd = 0; - int num = 0, cnt = 0; - - boolean first = true; - boolean lastClip = false; - - // test bbox for outer.. - boolean isOuter = true; - boolean simplify = mTile.zoomLevel < 14; - int pixel = simplify ? 7 : 3; - - int xmin = Integer.MAX_VALUE, xmax = Integer.MIN_VALUE; - int ymin = Integer.MAX_VALUE, ymax = Integer.MIN_VALUE; - - for (int end = bufferPos + bytes; bufferPos < end;) { - val = decodeVarint32Filled(); - - if (num == 0) { - // number of points - num = val >>> 3; - cnt = 0; - // path command - cmd = val & 0x07; - - if (isLine && lastClip) { - elem.addPoint(curX / mScale, curY / mScale); - lastClip = false; - } - - if (cmd == CLOSE_PATH) { - num = 0; - continue; - } - if (first) { - first = false; - continue; - } - if (cmd == MOVE_TO) { - if (type == TAG_GEOM_LINE) - elem.startLine(); - else if (type == TAG_GEOM_POLYGON) { - isOuter = false; - elem.startHole(); - } - } - continue; - } - // zigzag decoding - int s = ((val >>> 1) ^ -(val & 1)); - - if (even) { - // get x coordinate - even = false; - curX = lastX = lastX + s; - continue; - } - // get y coordinate and add point to geometry - num--; - - even = true; - curY = lastY = lastY + s; - - int dx = (curX - prevX); - int dy = (curY - prevY); - - if (isPoly && num == 0 && cnt > 0) { - prevX = curX; - prevY = curY; - - // only add last point if it is di - int ppos = cnt * 2; - if (elem.points[elem.pointPos - ppos] != curX - || elem.points[elem.pointPos - ppos + 1] != curY) - elem.addPoint(curX / mScale, curY / mScale); - - lastClip = false; - continue; - } - - if ((isPoint || cmd == MOVE_TO) - || (dx > pixel || dx < -pixel) - || (dy > pixel || dy < -pixel) - // hack to not clip at tile boundaries - || (curX <= 0 || curX >= 4095) - || (curY <= 0 || curY >= 4095)) { - - prevX = curX; - prevY = curY; - elem.addPoint(curX / mScale, curY / mScale); - cnt++; - - if (simplify && isOuter) { - if (curX < xmin) - xmin = curX; - if (curX > xmax) - xmax = curX; - - if (curY < ymin) - ymin = curY; - if (curY > ymax) - ymax = curY; - } - - lastClip = false; - continue; - } - lastClip = true; - } - - if (isPoly && isOuter && simplify && !testBBox(xmax - xmin, ymax - ymin)) { - //log.debug("skip small poly "+ elem.indexPos + " > " - // + (xmax - xmin) * (ymax - ymin)); - elem.pointPos -= elem.index[elem.indexPos]; - if (elem.indexPos > 0) { - elem.indexPos -= 2; - elem.index[elem.indexPos + 1] = -1; - } else { - elem.type = GeometryType.NONE; - } - return 0; - } - - if (isLine && lastClip) - elem.addPoint(curX / mScale, curY / mScale); - - return 1; - } - - private static boolean testBBox(int dx, int dy) { - return dx * dy > 64 * 64; - } - - private String decodeValue() throws IOException { - int bytes = decodeVarint32(); - - String value = null; - - int end = position() + bytes; - - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >> 3); - - switch (tag) { - case TAG_VALUE_STRING: - value = decodeString(); - break; - - case TAG_VALUE_UINT: - value = String.valueOf(decodeVarint32()); - break; - - case TAG_VALUE_SINT: - value = String.valueOf(deZigZag(decodeVarint32())); - break; - - case TAG_VALUE_LONG: - value = String.valueOf(decodeVarint64()); - break; - - case TAG_VALUE_FLOAT: - value = String.valueOf(decodeFloat()); - break; - - case TAG_VALUE_DOUBLE: - value = String.valueOf(decodeDouble()); - break; - - case TAG_VALUE_BOOL: - value = decodeBool() ? "yes" : "no"; - break; - default: - break; - } - - } - return value; - } + for (int i = 0; i < numTags << 1; i++) { + if (tags[i] != otherTags[i]) + return false; + } + return true; + } + + } + + private void decodeFeature(ArrayList features) throws IOException { + int bytes = decodeVarint32(); + int end = position() + bytes; + + int type = 0; + //long id; + + lastX = 0; + lastY = 0; + + mTmpTags[0] = -1; + + Feature curFeature = null; + int numTags = 0; + + //log.debug("start feature"); + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >>> 3); + + switch (tag) { + case TAG_FEATURE_ID: + //id = + decodeVarint32(); + break; + + case TAG_FEATURE_TAGS: + mTmpTags = decodeUnsignedVarintArray(mTmpTags); + + for (; numTags < mTmpTags.length && mTmpTags[numTags] >= 0; ) + numTags += 2; + + numTags >>= 1; + + break; + + case TAG_FEATURE_TYPE: + type = decodeVarint32(); + //log.debug("got type " + type); + break; + + case TAG_FEATURE_GEOMETRY: + + for (Feature f : features) { + if (f.match(mTmpTags, numTags, type)) { + curFeature = f; + break; + } + } + + if (curFeature == null) { + curFeature = mFeaturePool.get(); + curFeature.tags = new short[numTags << 1]; + System.arraycopy(mTmpTags, 0, curFeature.tags, 0, numTags << 1); + curFeature.numTags = numTags; + curFeature.type = type; + + features.add(curFeature); + } + + decodeCoordinates(type, curFeature); + break; + + default: + error(mTile + " invalid type for feature: " + tag); + break; + } + } + } + + private final static int CLOSE_PATH = 0x07; + private final static int MOVE_TO = 0x01; + //private final static int LINE_TO = 0x02; + + private int lastX, lastY; + + private int decodeCoordinates(int type, Feature feature) throws IOException { + int bytes = decodeVarint32(); + fillBuffer(bytes); + + if (feature == null) { + bufferPos += bytes; + return 0; + } + + MapElement elem = feature.elem; + boolean isPoint = false; + boolean isPoly = false; + boolean isLine = false; + + if (type == TAG_GEOM_LINE) { + elem.startLine(); + isLine = true; + } else if (type == TAG_GEOM_POLYGON) { + elem.startPolygon(); + isPoly = true; + } else if (type == TAG_GEOM_POINT) { + isPoint = true; + elem.startPoints(); + } else if (type == TAG_GEOM_UNKNOWN) + elem.startPoints(); + + boolean even = true; + int val; + + int curX = 0; + int curY = 0; + int prevX = 0; + int prevY = 0; + + int cmd = 0; + int num = 0, cnt = 0; + + boolean first = true; + boolean lastClip = false; + + // test bbox for outer.. + boolean isOuter = true; + boolean simplify = mTile.zoomLevel < 14; + int pixel = simplify ? 7 : 3; + + int xmin = Integer.MAX_VALUE, xmax = Integer.MIN_VALUE; + int ymin = Integer.MAX_VALUE, ymax = Integer.MIN_VALUE; + + for (int end = bufferPos + bytes; bufferPos < end; ) { + val = decodeVarint32Filled(); + + if (num == 0) { + // number of points + num = val >>> 3; + cnt = 0; + // path command + cmd = val & 0x07; + + if (isLine && lastClip) { + elem.addPoint(curX / mScale, curY / mScale); + lastClip = false; + } + + if (cmd == CLOSE_PATH) { + num = 0; + continue; + } + if (first) { + first = false; + continue; + } + if (cmd == MOVE_TO) { + if (type == TAG_GEOM_LINE) + elem.startLine(); + else if (type == TAG_GEOM_POLYGON) { + isOuter = false; + elem.startHole(); + } + } + continue; + } + // zigzag decoding + int s = ((val >>> 1) ^ -(val & 1)); + + if (even) { + // get x coordinate + even = false; + curX = lastX = lastX + s; + continue; + } + // get y coordinate and add point to geometry + num--; + + even = true; + curY = lastY = lastY + s; + + int dx = (curX - prevX); + int dy = (curY - prevY); + + if (isPoly && num == 0 && cnt > 0) { + prevX = curX; + prevY = curY; + + // only add last point if it is di + int ppos = cnt * 2; + if (elem.points[elem.pointPos - ppos] != curX + || elem.points[elem.pointPos - ppos + 1] != curY) + elem.addPoint(curX / mScale, curY / mScale); + + lastClip = false; + continue; + } + + if ((isPoint || cmd == MOVE_TO) + || (dx > pixel || dx < -pixel) + || (dy > pixel || dy < -pixel) + // hack to not clip at tile boundaries + || (curX <= 0 || curX >= 4095) + || (curY <= 0 || curY >= 4095)) { + + prevX = curX; + prevY = curY; + elem.addPoint(curX / mScale, curY / mScale); + cnt++; + + if (simplify && isOuter) { + if (curX < xmin) + xmin = curX; + if (curX > xmax) + xmax = curX; + + if (curY < ymin) + ymin = curY; + if (curY > ymax) + ymax = curY; + } + + lastClip = false; + continue; + } + lastClip = true; + } + + if (isPoly && isOuter && simplify && !testBBox(xmax - xmin, ymax - ymin)) { + //log.debug("skip small poly "+ elem.indexPos + " > " + // + (xmax - xmin) * (ymax - ymin)); + elem.pointPos -= elem.index[elem.indexPos]; + if (elem.indexPos > 0) { + elem.indexPos -= 2; + elem.index[elem.indexPos + 1] = -1; + } else { + elem.type = GeometryType.NONE; + } + return 0; + } + + if (isLine && lastClip) + elem.addPoint(curX / mScale, curY / mScale); + + return 1; + } + + private static boolean testBBox(int dx, int dy) { + return dx * dy > 64 * 64; + } + + private String decodeValue() throws IOException { + int bytes = decodeVarint32(); + + String value = null; + + int end = position() + bytes; + + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >> 3); + + switch (tag) { + case TAG_VALUE_STRING: + value = decodeString(); + break; + + case TAG_VALUE_UINT: + value = String.valueOf(decodeVarint32()); + break; + + case TAG_VALUE_SINT: + value = String.valueOf(deZigZag(decodeVarint32())); + break; + + case TAG_VALUE_LONG: + value = String.valueOf(decodeVarint64()); + break; + + case TAG_VALUE_FLOAT: + value = String.valueOf(decodeFloat()); + break; + + case TAG_VALUE_DOUBLE: + value = String.valueOf(decodeDouble()); + break; + + case TAG_VALUE_BOOL: + value = decodeBool() ? "yes" : "no"; + break; + default: + break; + } + + } + return value; + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/mapnik/carto.xml b/vtm-extras/src/org/oscim/tiling/source/mapnik/carto.xml index 9e9a95a3..e165aae9 100644 --- a/vtm-extras/src/org/oscim/tiling/source/mapnik/carto.xml +++ b/vtm-extras/src/org/oscim/tiling/source/mapnik/carto.xml @@ -1,712 +1,705 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vtm-extras/src/org/oscim/tiling/source/oscimap/OSciMap1TileSource.java b/vtm-extras/src/org/oscim/tiling/source/oscimap/OSciMap1TileSource.java index 32626519..55697e14 100644 --- a/vtm-extras/src/org/oscim/tiling/source/oscimap/OSciMap1TileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/oscimap/OSciMap1TileSource.java @@ -22,16 +22,15 @@ import org.oscim.tiling.source.UrlTileSource; /** * Deprecated - * */ public class OSciMap1TileSource extends UrlTileSource { - public OSciMap1TileSource(String url) { - super(url, "/{Z}/{X}/{Y}.osmtile"); - } + public OSciMap1TileSource(String url) { + super(url, "/{Z}/{X}/{Y}.osmtile"); + } - @Override - public ITileDataSource getDataSource() { - return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); - } + @Override + public ITileDataSource getDataSource() { + return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/oscimap/Tags.java b/vtm-extras/src/org/oscim/tiling/source/oscimap/Tags.java index 165283f5..b3de6603 100644 --- a/vtm-extras/src/org/oscim/tiling/source/oscimap/Tags.java +++ b/vtm-extras/src/org/oscim/tiling/source/oscimap/Tags.java @@ -19,942 +19,942 @@ package org.oscim.tiling.source.oscimap; import org.oscim.core.Tag; public class Tags { - public final static int MAX = 654; - public final static int LIMIT = 1024; + public final static int MAX = 654; + public final static int LIMIT = 1024; - private static final String s_limited = "limited".intern(); - private static final String s_chain = "chain".intern(); - private static final String s_viaduct = "viaduct".intern(); - private static final String s_department_store = "department_store".intern(); - private static final String s_factory = "factory".intern(); - private static final String s_recreation_ground = "recreation_ground".intern(); - private static final String s_nature_reserve = "nature_reserve".intern(); - private static final String s_apartment = "apartment".intern(); - private static final String s_preserved = "preserved".intern(); - private static final String s_stationery = "stationery".intern(); - private static final String s_gravel = "gravel".intern(); - private static final String s_hill = "hill".intern(); - private static final String s_water_well = "water_well".intern(); - private static final String s_garden = "garden".intern(); - private static final String s_permissive = "permissive".intern(); - private static final String s_deli = "deli".intern(); - private static final String s_industrial_retail = "industrial;retail".intern(); - private static final String s_city_wall = "city_wall".intern(); - private static final String s_artwork = "artwork".intern(); - private static final String s_chapel = "chapel".intern(); - private static final String s_school = "school".intern(); - private static final String s_caravan_site = "caravan_site".intern(); - private static final String s_reservoir_watershed = "reservoir_watershed".intern(); - private static final String s_local_authority = "local_authority".intern(); - private static final String s_miniature_golf = "miniature_golf".intern(); - private static final String s_bus_stop = "bus_stop".intern(); - private static final String s_convenience = "convenience".intern(); - private static final String s_kissing_gate = "kissing_gate".intern(); - private static final String s_subway = "subway".intern(); - private static final String s_cutline = "cutline".intern(); - private static final String s_disused = "disused".intern(); - private static final String s_clothes = "clothes".intern(); - private static final String s_bicycle = "bicycle".intern(); - private static final String s_meadow = "meadow".intern(); - private static final String s_fence = "fence".intern(); - private static final String s_video = "video".intern(); - private static final String s_monorail = "monorail".intern(); - private static final String s_clock = "clock".intern(); - private static final String s_dirt = "dirt".intern(); - private static final String s_border_control = "border_control".intern(); - private static final String s_access = "access".intern(); - private static final String s_public = "public".intern(); - private static final String s_fast_food = "fast_food".intern(); - private static final String s_transportation = "transportation".intern(); - private static final String s_commercial = "commercial".intern(); - private static final String s_water = "water".intern(); - private static final String s_beacon = "beacon".intern(); - private static final String s_trunk = "trunk".intern(); - private static final String s_path = "path".intern(); - private static final String s_bicycle_rental = "bicycle_rental".intern(); - private static final String s_miniature = "miniature".intern(); - private static final String s_car_parts = "car_parts".intern(); - private static final String s_light_rail = "light_rail".intern(); - private static final String s_military = "military".intern(); - private static final String s_bog = "bog".intern(); - private static final String s_hiking = "hiking".intern(); - private static final String s_lift_gate = "lift_gate".intern(); - private static final String s_private = "private".intern(); - private static final String s_county = "county".intern(); - private static final String s_secondary_link = "secondary_link".intern(); - private static final String s_marker = "marker".intern(); - private static final String s_islet = "islet".intern(); - private static final String s_holding_position = "holding_position".intern(); - private static final String s_tertiary = "tertiary".intern(); - private static final String s_water_park = "water_park".intern(); - private static final String s_stream = "stream".intern(); - private static final String s_hospital = "hospital".intern(); - private static final String s_destination = "destination".intern(); - private static final String s_MDF = "MDF".intern(); - private static final String s_sports = "sports".intern(); - private static final String s_vineyard = "vineyard".intern(); - private static final String s_music = "music".intern(); - private static final String s_6 = "6".intern(); - private static final String s_entrance = "entrance".intern(); - private static final String s_beauty = "beauty".intern(); - private static final String s_give_way = "give_way".intern(); - private static final String s_kiosk = "kiosk".intern(); - private static final String s_stone = "stone".intern(); - private static final String s_grass_paver = "grass_paver".intern(); - private static final String s_deciduous = "deciduous".intern(); - private static final String s_train = "train".intern(); - private static final String s_organic = "organic".intern(); - private static final String s_farmyard = "farmyard".intern(); - private static final String s_riverbank = "riverbank".intern(); - private static final String s_doityourself = "doityourself".intern(); - private static final String s_town = "town".intern(); - private static final String s_dog_park = "dog_park".intern(); - private static final String s_village_green = "village_green".intern(); - private static final String s_tunnel = "tunnel".intern(); - private static final String s_car = "car".intern(); - private static final String s_roof = "roof".intern(); - private static final String s_mall = "mall".intern(); - private static final String s_ferry_terminal = "ferry_terminal".intern(); - private static final String s_cave_entrance = "cave_entrance".intern(); - private static final String s_detached = "detached".intern(); - private static final String s_concrete_plates = "concrete:plates".intern(); - private static final String s_public_building = "public_building".intern(); - private static final String s_buffer_stop = "buffer_stop".intern(); - private static final String s_lock = "lock".intern(); - private static final String s_dolphin = "dolphin".intern(); - private static final String s_taxiway = "taxiway".intern(); - private static final String s_hunting_stand = "hunting_stand".intern(); - private static final String s_estate_agent = "estate_agent".intern(); - private static final String s_station = "station".intern(); - private static final String s_car_repair = "car_repair".intern(); - private static final String s_dyke = "dyke".intern(); - private static final String s_hangar = "hangar".intern(); - private static final String s_information = "information".intern(); - private static final String s_1 = "1".intern(); - private static final String s_forest = "forest".intern(); - private static final String s_gate = "gate".intern(); - private static final String s_beach = "beach".intern(); - private static final String s_laundry = "laundry".intern(); - private static final String s_speed_camera = "speed_camera".intern(); - private static final String s_staircase = "staircase".intern(); - private static final String s_farm = "farm".intern(); - private static final String s_stop = "stop".intern(); - private static final String s_bump_gate = "bump_gate".intern(); - private static final String s_motorway = "motorway".intern(); - private static final String s_water_tower = "water_tower".intern(); - private static final String s_abutters = "abutters".intern(); - private static final String s_driving_school = "driving_school".intern(); - private static final String s_natural = "natural".intern(); - private static final String s_orchard = "orchard".intern(); - private static final String s_wheelchair = "wheelchair".intern(); - private static final String s_swimming_pool = "swimming_pool".intern(); - private static final String s_switch = "switch".intern(); - private static final String s_block = "block".intern(); - private static final String s_turnstile = "turnstile".intern(); - private static final String s_camp_site = "camp_site".intern(); - private static final String s_shoes = "shoes".intern(); - private static final String s_reservoir = "reservoir".intern(); - private static final String s_pebblestone = "pebblestone".intern(); - private static final String s_stile = "stile".intern(); - private static final String s_embassy = "embassy".intern(); - private static final String s_postal_code = "postal_code".intern(); - private static final String s_retaining_wall = "retaining_wall".intern(); - private static final String s_bridleway = "bridleway".intern(); - private static final String s_pitch = "pitch".intern(); - private static final String s_agricultural = "agricultural".intern(); - private static final String s_post_office = "post_office".intern(); - private static final String s_parking_fuel = "parking;fuel".intern(); - private static final String s_bureau_de_change = "bureau_de_change".intern(); - private static final String s_mini_roundabout = "mini_roundabout".intern(); - private static final String s_hov = "hov".intern(); - private static final String s_police = "police".intern(); - private static final String s_courthouse = "courthouse".intern(); - private static final String s_raceway = "raceway".intern(); - private static final String s_kindergarten = "kindergarten".intern(); - private static final String s_attraction = "attraction".intern(); - private static final String s_marsh = "marsh".intern(); - private static final String s_reservoir_covered = "reservoir_covered".intern(); - private static final String s_petroleum_well = "petroleum_well".intern(); - private static final String s_silo = "silo".intern(); - private static final String s_toys = "toys".intern(); - private static final String s_apron = "apron".intern(); - private static final String s_halt = "halt".intern(); - private static final String s_dam = "dam".intern(); - private static final String s_golf_course = "golf_course".intern(); - private static final String s_detour = "detour".intern(); - private static final String s_tree_row = "tree_row".intern(); - private static final String s_copyshop = "copyshop".intern(); - private static final String s_milestone = "milestone".intern(); - private static final String s_foot = "foot".intern(); - private static final String s_tourism = "tourism".intern(); - private static final String s_bank = "bank".intern(); - private static final String s_dry_cleaning = "dry_cleaning".intern(); - private static final String s_tram = "tram".intern(); - private static final String s_trolleybus = "trolleybus".intern(); - private static final String s_university = "university".intern(); - private static final String s_hampshire_gate = "hampshire_gate".intern(); - private static final String s_embankment = "embankment".intern(); - private static final String s_rock = "rock".intern(); - private static final String s_crossing = "crossing".intern(); - private static final String s_volcano = "volcano".intern(); - private static final String s_greengrocer = "greengrocer".intern(); - private static final String s_kerb = "kerb".intern(); - private static final String s_waste_disposal = "waste_disposal".intern(); - private static final String s_grave_yard = "grave_yard".intern(); - private static final String s_coniferous = "coniferous".intern(); - private static final String s_house = "house".intern(); - private static final String s_books = "books".intern(); - private static final String s_neighbourhood = "neighbourhood".intern(); - private static final String s_hostel = "hostel".intern(); - private static final String s_alcohol = "alcohol".intern(); - private static final String s_restricted = "restricted".intern(); - private static final String s_motel = "motel".intern(); - private static final String s_sand = "sand".intern(); - private static final String s_fishmonger = "fishmonger".intern(); - private static final String s_fountain = "fountain".intern(); - private static final String s_playground = "playground".intern(); - private static final String s_7 = "7".intern(); - private static final String s_parking_aisle = "parking_aisle".intern(); - private static final String s_protected_area = "protected_area".intern(); - private static final String s_electronics = "electronics".intern(); - private static final String s_Paved = "Paved".intern(); - private static final String s_highway = "highway".intern(); - private static final String s_fine_gravel = "fine_gravel".intern(); - private static final String s_barrier = "barrier".intern(); - private static final String s_hairdresser = "hairdresser".intern(); - private static final String s_post_box = "post_box".intern(); - private static final String s_pub = "pub".intern(); - private static final String s_coastline = "coastline".intern(); - private static final String s_marina = "marina".intern(); - private static final String s_reedbed = "reedbed".intern(); - private static final String s_biergarten = "biergarten".intern(); - private static final String s_dismantled = "dismantled".intern(); - private static final String s_farmland = "farmland".intern(); - private static final String s_yard = "yard".intern(); - private static final String s_route = "route".intern(); - private static final String s_atm = "atm".intern(); - private static final String s_place = "place".intern(); - private static final String s_bus_station = "bus_station".intern(); - private static final String s_retail = "retail".intern(); - private static final String s_industrial = "industrial".intern(); - private static final String s_municipality = "municipality".intern(); - private static final String s_primary = "primary".intern(); - private static final String s_nursing_home = "nursing_home".intern(); - private static final String s_florist = "florist".intern(); - private static final String s_ditch = "ditch".intern(); - private static final String s_national_park = "national_park".intern(); - private static final String s_city = "city".intern(); - private static final String s_confectionery = "confectionery".intern(); - private static final String s_service = "service".intern(); - private static final String s_unknown = "unknown".intern(); - private static final String s_cycle_barrier = "cycle_barrier".intern(); - private static final String s_elevator = "elevator".intern(); - private static final String s_2 = "2".intern(); - private static final String s_car_rental = "car_rental".intern(); - private static final String s_flagpole = "flagpole".intern(); - private static final String s_cabin = "cabin".intern(); - private static final String s_paved = "paved".intern(); - private static final String s_guest_house = "guest_house".intern(); - private static final String s_mobile_phone = "mobile_phone".intern(); - private static final String s_lot = "lot".intern(); - private static final String s_quarry = "quarry".intern(); - private static final String s_train_station = "train_station".intern(); - private static final String s_hotel = "hotel".intern(); - private static final String s_park = "park".intern(); - private static final String s_hut = "hut".intern(); - private static final String s_dentist = "dentist".intern(); - private static final String s_doctors = "doctors".intern(); - private static final String s_greenhouse = "greenhouse".intern(); - private static final String s_11 = "11".intern(); - private static final String s_10 = "10".intern(); - private static final String s_theme_park = "theme_park".intern(); - private static final String s_tree = "tree".intern(); - private static final String s_shower = "shower".intern(); - private static final String s_siding = "siding".intern(); - private static final String s_aeroway = "aeroway".intern(); - private static final String s_emergency_access_point = "emergency_access_point" - .intern(); - private static final String s_watermill = "watermill".intern(); - private static final String s_college = "college".intern(); - private static final String s_landuse = "landuse".intern(); - private static final String s_tracktype = "tracktype".intern(); - private static final String s_ferry = "ferry".intern(); - private static final String s_bridge = "bridge".intern(); - private static final String s_vacant = "vacant".intern(); - private static final String s_cattle_grid = "cattle_grid".intern(); - private static final String s_brownfield = "brownfield".intern(); - private static final String s_allotments = "allotments".intern(); - private static final String s_alley = "alley".intern(); - private static final String s_pedestrian = "pedestrian".intern(); - private static final String s_borough = "borough".intern(); - private static final String s_bare_rock = "bare_rock".intern(); - private static final String s_motorcycle = "motorcycle".intern(); - private static final String s_bakery = "bakery".intern(); - private static final String s_zoo = "zoo".intern(); - private static final String s_scree = "scree".intern(); - private static final String s_fire_station = "fire_station".intern(); - private static final String s_theatre = "theatre".intern(); - private static final String s_track = "track".intern(); - private static final String s_reinforced_slope = "reinforced_slope".intern(); - private static final String s_slipway = "slipway".intern(); - private static final String s_mangrove = "mangrove".intern(); - private static final String s_aerodrome = "aerodrome".intern(); - private static final String s_byway = "byway".intern(); - private static final String s_metal = "metal".intern(); - private static final String s_swamp = "swamp".intern(); - private static final String s_construction = "construction".intern(); - private static final String s_grassland = "grassland".intern(); - private static final String s_shop = "shop".intern(); - private static final String s_soakhole = "soakhole".intern(); - private static final String s_asphalt = "asphalt".intern(); - private static final String s_social_facility = "social_facility".intern(); - private static final String s_isolated_dwelling = "isolated_dwelling".intern(); - private static final String s_hamlet = "hamlet".intern(); - private static final String s_picnic_table = "picnic_table".intern(); - private static final String s_artificial = "artificial".intern(); - private static final String s_earth = "earth".intern(); - private static final String s_grit_bin = "grit_bin".intern(); - private static final String s_ground = "ground".intern(); - private static final String s_groyne = "groyne".intern(); - private static final String s_office = "office".intern(); - private static final String s_state = "state".intern(); - private static final String s_terminal = "terminal".intern(); - private static final String s_wood = "wood".intern(); - private static final String s_fuel = "fuel".intern(); - private static final String s_8 = "8".intern(); - private static final String s_garden_centre = "garden_centre".intern(); - private static final String s_horse_riding = "horse_riding".intern(); - private static final String s_viewpoint = "viewpoint".intern(); - private static final String s_designated = "designated".intern(); - private static final String s_leisure = "leisure".intern(); - private static final String s_waste_basket = "waste_basket".intern(); - private static final String s_hifi = "hifi".intern(); - private static final String s_hedge = "hedge".intern(); - private static final String s_spur = "spur".intern(); - private static final String s_chimney = "chimney".intern(); - private static final String s_secondary = "secondary".intern(); - private static final String s_rest_area = "rest_area".intern(); - private static final String s_bar = "bar".intern(); - private static final String s_bay = "bay".intern(); - private static final String s_common = "common".intern(); - private static final String s_river = "river".intern(); - private static final String s_ruins = "ruins".intern(); - private static final String s_terrace = "terrace".intern(); - private static final String s_art = "art".intern(); - private static final String s_residental = "residental".intern(); - private static final String s_newsagent = "newsagent".intern(); - private static final String s_turntable = "turntable".intern(); - private static final String s_computer = "computer".intern(); - private static final String s_wetland = "wetland".intern(); - private static final String s_driveway = "driveway".intern(); - private static final String s_parking = "parking".intern(); - private static final String s_compacted = "compacted".intern(); - private static final String s_barn = "barn".intern(); - private static final String s_alpine_hut = "alpine_hut".intern(); - private static final String s_wire_fence = "wire_fence".intern(); - private static final String s_unpaved = "unpaved".intern(); - private static final String s_dormitory = "dormitory".intern(); - private static final String s_mud = "mud".intern(); - private static final String s_3 = "3".intern(); - private static final String s_semi = "semi".intern(); - private static final String s_boundary = "boundary".intern(); - private static final String s_field_boundary = "field_boundary".intern(); - private static final String s_beverages = "beverages".intern(); - private static final String s_supermarket = "supermarket".intern(); - private static final String s_store = "store".intern(); - private static final String s_restaurant = "restaurant".intern(); - private static final String s_region = "region".intern(); - private static final String s_variety_store = "variety_store".intern(); - private static final String s_saltmarsh = "saltmarsh".intern(); - private static final String s_landform = "landform".intern(); - private static final String s_helipad = "helipad".intern(); - private static final String s_railway = "railway".intern(); - private static final String s_greenhouse_horticulture = "greenhouse_horticulture" - .intern(); - private static final String s_wall = "wall".intern(); - private static final String s_recycling = "recycling".intern(); - private static final String s_passing_place = "passing_place".intern(); - private static final String s_church = "church".intern(); - private static final String s_pharmacy = "pharmacy".intern(); - private static final String s_lighthouse = "lighthouse".intern(); - private static final String s_platform = "platform".intern(); - private static final String s_cinema = "cinema".intern(); - private static final String s_political = "political".intern(); - private static final String s_stadium = "stadium".intern(); - private static final String s_basin = "basin".intern(); - private static final String s_gasometer = "gasometer".intern(); - private static final String s_bicycle_parking = "bicycle_parking".intern(); - private static final String s_bbq = "bbq".intern(); - private static final String s_incline_steep = "incline_steep".intern(); - private static final String s_drinking_water = "drinking_water".intern(); - private static final String s_living_street = "living_street".intern(); - private static final String s_chalet = "chalet".intern(); - private static final String s_narrow_gauge = "narrow_gauge".intern(); - private static final String s_prison = "prison".intern(); - private static final String s_mine = "mine".intern(); - private static final String s_level_crossing = "level_crossing".intern(); - private static final String s_water_works = "water_works".intern(); - private static final String s_street_lamp = "street_lamp".intern(); - private static final String s_main = "main".intern(); - private static final String s_tank = "tank".intern(); - private static final String s_abandoned = "abandoned".intern(); - private static final String s_ski = "ski".intern(); - private static final String s_runway = "runway".intern(); - private static final String s_parking_space = "parking_space".intern(); - private static final String s_dirt_sand = "dirt/sand".intern(); - private static final String s_salt_pond = "salt_pond".intern(); - private static final String s_hedge_bank = "hedge_bank".intern(); - private static final String s_amenity = "amenity".intern(); - private static final String s_telephone = "telephone".intern(); - private static final String s_surface = "surface".intern(); - private static final String s_travel_agency = "travel_agency".intern(); - private static final String s_hardware = "hardware".intern(); - private static final String s_wastewater_plant = "wastewater_plant".intern(); - private static final String s_waterway = "waterway".intern(); - private static final String s_butcher = "butcher".intern(); - private static final String s_surveillance = "surveillance".intern(); - private static final String s_Dirt_Sand = "Dirt/Sand".intern(); - private static final String s_9 = "9".intern(); - private static final String s_windmill = "windmill".intern(); - private static final String s_picnic_site = "picnic_site".intern(); - private static final String s_rail = "rail".intern(); - private static final String s_cement = "cement".intern(); - private static final String s_sauna = "sauna".intern(); - private static final String s_suburb = "suburb".intern(); - private static final String s_waterfall = "waterfall".intern(); - private static final String s_bunker = "bunker".intern(); - private static final String s_ice_cream = "ice_cream".intern(); - private static final String s_culvert = "culvert".intern(); - private static final String s_drain = "drain".intern(); - private static final String s_dock = "dock".intern(); - private static final String s_glasshouse = "glasshouse".intern(); - private static final String s_no = "no".intern(); - private static final String s_well = "well".intern(); - private static final String s_wet_meadow = "wet_meadow".intern(); - private static final String s_concrete = "concrete".intern(); - private static final String s_dismount = "dismount".intern(); - private static final String s_vending_machine = "vending_machine".intern(); - private static final String s_oneway = "oneway".intern(); - private static final String s_taxi = "taxi".intern(); - private static final String s_outdoor = "outdoor".intern(); - private static final String s_proposed = "proposed".intern(); - private static final String s_sally_port = "sally_port".intern(); - private static final String s_photo = "photo".intern(); - private static final String s_plant_nursery = "plant_nursery".intern(); - private static final String s_clinic = "clinic".intern(); - private static final String s_fishing = "fishing".intern(); - private static final String s_yes = "yes".intern(); - private static final String s_turning_circle = "turning_circle".intern(); - private static final String s_toilets = "toilets".intern(); - private static final String s_guard_rail = "guard_rail".intern(); - private static final String s_townhall = "townhall".intern(); - private static final String s_community_centre = "community_centre".intern(); - private static final String s_residential = "residential".intern(); - private static final String s_cemetery = "cemetery".intern(); - private static final String s_survey_point = "survey_point".intern(); - private static final String s_bench = "bench".intern(); - private static final String s_4 = "4".intern(); - private static final String s_bollard = "bollard".intern(); - private static final String s_sports_centre = "sports_centre".intern(); - private static final String s_paving_stones_30 = "paving_stones:30".intern(); - private static final String s_administrative = "administrative".intern(); - private static final String s_Building = "Building".intern(); - private static final String s_customers = "customers".intern(); - private static final String s_emergency = "emergency".intern(); - private static final String s_motorway_junction = "motorway_junction".intern(); - private static final String s_grade1 = "grade1".intern(); - private static final String s_grade3 = "grade3".intern(); - private static final String s_grade2 = "grade2".intern(); - private static final String s_grade5 = "grade5".intern(); - private static final String s_grade4 = "grade4".intern(); - private static final String s_lock_gate = "lock_gate".intern(); - private static final String s_furniture = "furniture".intern(); - private static final String s_place_of_worship = "place_of_worship".intern(); - private static final String s_optician = "optician".intern(); - private static final String s_gift = "gift".intern(); - private static final String s_parking_entrance = "parking_entrance".intern(); - private static final String s_garage = "garage".intern(); - private static final String s_tram_stop = "tram_stop".intern(); - private static final String s_steps = "steps".intern(); - private static final String s_tower = "tower".intern(); - private static final String s_works = "works".intern(); - private static final String s_shed = "shed".intern(); - private static final String s_car_sharing = "car_sharing".intern(); - private static final String s_apartments = "apartments".intern(); - private static final String s_spring = "spring".intern(); - private static final String s_village = "village".intern(); - private static final String s_library = "library".intern(); - private static final String s_emergency_access = "emergency_access".intern(); - private static final String s_home = "home".intern(); - private static final String s_farm_auxiliary = "farm_auxiliary".intern(); - private static final String s_primary_link = "primary_link".intern(); - private static final String s_toll_booth = "toll_booth".intern(); - private static final String s_jewelry = "jewelry".intern(); - private static final String s_pet = "pet".intern(); - private static final String s_veterinary = "veterinary".intern(); - private static final String s_man_made = "man_made".intern(); - private static final String s_motorway_link = "motorway_link".intern(); - private static final String s_offices = "offices".intern(); - private static final String s_power = "power".intern(); - private static final String s_weir = "weir".intern(); - private static final String s_unsurfaced = "unsurfaced".intern(); - private static final String s_tertiary_link = "tertiary_link".intern(); - private static final String s_trunk_link = "trunk_link".intern(); - private static final String s_tyres = "tyres".intern(); - private static final String s_paving_stones = "paving_stones".intern(); - private static final String s_pipeline = "pipeline".intern(); - private static final String s_census = "census".intern(); - private static final String s_incline = "incline".intern(); - private static final String s_footway = "footway".intern(); - private static final String s_drive_through = "drive-through".intern(); - private static final String s_island = "island".intern(); - private static final String s_monitoring_station = "monitoring_station".intern(); - private static final String s_nightclub = "nightclub".intern(); - private static final String s_unclassified = "unclassified".intern(); - private static final String s_aquaculture = "aquaculture".intern(); - private static final String s_mixed = "mixed".intern(); - private static final String s_road = "road".intern(); - private static final String s_greenfield = "greenfield".intern(); - private static final String s_breakwater = "breakwater".intern(); - private static final String s_services = "services".intern(); - private static final String s_railway_crossing = "railway_crossing".intern(); - private static final String s_residentiel1 = "residentiel1".intern(); - private static final String s_canal = "canal".intern(); - private static final String s__1 = "-1".intern(); - private static final String s_ridge = "ridge".intern(); - private static final String s_fabric = "fabric".intern(); - private static final String s_museum = "museum".intern(); - private static final String s_communications_tower = "communications_tower".intern(); - private static final String s_semi_detached = "semi-detached".intern(); - private static final String s_conservation = "conservation".intern(); - private static final String s_way = "way".intern(); - private static final String s_wood_fence = "wood_fence".intern(); - private static final String s_manufacture = "manufacture".intern(); - private static final String s_admin_level = "admin_level".intern(); - private static final String s_building_concrete = "building_concrete".intern(); - private static final String s_bus = "bus".intern(); - private static final String s_collapsed = "collapsed".intern(); - private static final String s_ford = "ford".intern(); - private static final String s_delivery = "delivery".intern(); - private static final String s_garages = "garages".intern(); - private static final String s_funeral_directors = "funeral_directors".intern(); - private static final String s_land = "land".intern(); - private static final String s_interlock = "interlock".intern(); - private static final String s_reef = "reef".intern(); - private static final String s_crane = "crane".intern(); - private static final String s_true = "true".intern(); - private static final String s_storage_tank = "storage_tank".intern(); - private static final String s_official = "official".intern(); - private static final String s_subway_entrance = "subway_entrance".intern(); - private static final String s_mtb = "mtb".intern(); - private static final String s_grass = "grass".intern(); - private static final String s_marketplace = "marketplace".intern(); - private static final String s_rapids = "rapids".intern(); - private static final String s_car_wash = "car_wash".intern(); - private static final String s_general = "general".intern(); - private static final String s_cafe = "cafe".intern(); - private static final String s_locality = "locality".intern(); - private static final String s_glacier = "glacier".intern(); - private static final String s_storage = "storage".intern(); - private static final String s_cycleway = "cycleway".intern(); - private static final String s_forestry = "forestry".intern(); - private static final String s_field = "field".intern(); - private static final String s_5 = "5".intern(); - private static final String s_arts_centre = "arts_centre".intern(); - private static final String s_warehouse = "warehouse".intern(); - private static final String s_chemist = "chemist".intern(); - private static final String s_pier = "pier".intern(); - private static final String s_scrub = "scrub".intern(); - private static final String s_shelter = "shelter".intern(); - private static final String s_emergency_phone = "emergency_phone".intern(); - private static final String s_tidalflat = "tidalflat".intern(); - private static final String s_cobblestone = "cobblestone".intern(); - private static final String s_fell = "fell".intern(); - private static final String s_peak = "peak".intern(); - private static final String s_charging_station = "charging_station".intern(); - private static final String s_cliff = "cliff".intern(); - private static final String s_building = "building".intern(); - private static final String s_fire_hydrant = "fire_hydrant".intern(); - private static final String s_traffic_signals = "traffic_signals".intern(); - private static final String s_heath = "heath".intern(); - private static final String s_landfill = "landfill".intern(); - private static final String s_mast = "mast".intern(); - private static final String s_boutique = "boutique".intern(); - private static final String s_boat_storage = "boat_storage".intern(); + private static final String s_limited = "limited".intern(); + private static final String s_chain = "chain".intern(); + private static final String s_viaduct = "viaduct".intern(); + private static final String s_department_store = "department_store".intern(); + private static final String s_factory = "factory".intern(); + private static final String s_recreation_ground = "recreation_ground".intern(); + private static final String s_nature_reserve = "nature_reserve".intern(); + private static final String s_apartment = "apartment".intern(); + private static final String s_preserved = "preserved".intern(); + private static final String s_stationery = "stationery".intern(); + private static final String s_gravel = "gravel".intern(); + private static final String s_hill = "hill".intern(); + private static final String s_water_well = "water_well".intern(); + private static final String s_garden = "garden".intern(); + private static final String s_permissive = "permissive".intern(); + private static final String s_deli = "deli".intern(); + private static final String s_industrial_retail = "industrial;retail".intern(); + private static final String s_city_wall = "city_wall".intern(); + private static final String s_artwork = "artwork".intern(); + private static final String s_chapel = "chapel".intern(); + private static final String s_school = "school".intern(); + private static final String s_caravan_site = "caravan_site".intern(); + private static final String s_reservoir_watershed = "reservoir_watershed".intern(); + private static final String s_local_authority = "local_authority".intern(); + private static final String s_miniature_golf = "miniature_golf".intern(); + private static final String s_bus_stop = "bus_stop".intern(); + private static final String s_convenience = "convenience".intern(); + private static final String s_kissing_gate = "kissing_gate".intern(); + private static final String s_subway = "subway".intern(); + private static final String s_cutline = "cutline".intern(); + private static final String s_disused = "disused".intern(); + private static final String s_clothes = "clothes".intern(); + private static final String s_bicycle = "bicycle".intern(); + private static final String s_meadow = "meadow".intern(); + private static final String s_fence = "fence".intern(); + private static final String s_video = "video".intern(); + private static final String s_monorail = "monorail".intern(); + private static final String s_clock = "clock".intern(); + private static final String s_dirt = "dirt".intern(); + private static final String s_border_control = "border_control".intern(); + private static final String s_access = "access".intern(); + private static final String s_public = "public".intern(); + private static final String s_fast_food = "fast_food".intern(); + private static final String s_transportation = "transportation".intern(); + private static final String s_commercial = "commercial".intern(); + private static final String s_water = "water".intern(); + private static final String s_beacon = "beacon".intern(); + private static final String s_trunk = "trunk".intern(); + private static final String s_path = "path".intern(); + private static final String s_bicycle_rental = "bicycle_rental".intern(); + private static final String s_miniature = "miniature".intern(); + private static final String s_car_parts = "car_parts".intern(); + private static final String s_light_rail = "light_rail".intern(); + private static final String s_military = "military".intern(); + private static final String s_bog = "bog".intern(); + private static final String s_hiking = "hiking".intern(); + private static final String s_lift_gate = "lift_gate".intern(); + private static final String s_private = "private".intern(); + private static final String s_county = "county".intern(); + private static final String s_secondary_link = "secondary_link".intern(); + private static final String s_marker = "marker".intern(); + private static final String s_islet = "islet".intern(); + private static final String s_holding_position = "holding_position".intern(); + private static final String s_tertiary = "tertiary".intern(); + private static final String s_water_park = "water_park".intern(); + private static final String s_stream = "stream".intern(); + private static final String s_hospital = "hospital".intern(); + private static final String s_destination = "destination".intern(); + private static final String s_MDF = "MDF".intern(); + private static final String s_sports = "sports".intern(); + private static final String s_vineyard = "vineyard".intern(); + private static final String s_music = "music".intern(); + private static final String s_6 = "6".intern(); + private static final String s_entrance = "entrance".intern(); + private static final String s_beauty = "beauty".intern(); + private static final String s_give_way = "give_way".intern(); + private static final String s_kiosk = "kiosk".intern(); + private static final String s_stone = "stone".intern(); + private static final String s_grass_paver = "grass_paver".intern(); + private static final String s_deciduous = "deciduous".intern(); + private static final String s_train = "train".intern(); + private static final String s_organic = "organic".intern(); + private static final String s_farmyard = "farmyard".intern(); + private static final String s_riverbank = "riverbank".intern(); + private static final String s_doityourself = "doityourself".intern(); + private static final String s_town = "town".intern(); + private static final String s_dog_park = "dog_park".intern(); + private static final String s_village_green = "village_green".intern(); + private static final String s_tunnel = "tunnel".intern(); + private static final String s_car = "car".intern(); + private static final String s_roof = "roof".intern(); + private static final String s_mall = "mall".intern(); + private static final String s_ferry_terminal = "ferry_terminal".intern(); + private static final String s_cave_entrance = "cave_entrance".intern(); + private static final String s_detached = "detached".intern(); + private static final String s_concrete_plates = "concrete:plates".intern(); + private static final String s_public_building = "public_building".intern(); + private static final String s_buffer_stop = "buffer_stop".intern(); + private static final String s_lock = "lock".intern(); + private static final String s_dolphin = "dolphin".intern(); + private static final String s_taxiway = "taxiway".intern(); + private static final String s_hunting_stand = "hunting_stand".intern(); + private static final String s_estate_agent = "estate_agent".intern(); + private static final String s_station = "station".intern(); + private static final String s_car_repair = "car_repair".intern(); + private static final String s_dyke = "dyke".intern(); + private static final String s_hangar = "hangar".intern(); + private static final String s_information = "information".intern(); + private static final String s_1 = "1".intern(); + private static final String s_forest = "forest".intern(); + private static final String s_gate = "gate".intern(); + private static final String s_beach = "beach".intern(); + private static final String s_laundry = "laundry".intern(); + private static final String s_speed_camera = "speed_camera".intern(); + private static final String s_staircase = "staircase".intern(); + private static final String s_farm = "farm".intern(); + private static final String s_stop = "stop".intern(); + private static final String s_bump_gate = "bump_gate".intern(); + private static final String s_motorway = "motorway".intern(); + private static final String s_water_tower = "water_tower".intern(); + private static final String s_abutters = "abutters".intern(); + private static final String s_driving_school = "driving_school".intern(); + private static final String s_natural = "natural".intern(); + private static final String s_orchard = "orchard".intern(); + private static final String s_wheelchair = "wheelchair".intern(); + private static final String s_swimming_pool = "swimming_pool".intern(); + private static final String s_switch = "switch".intern(); + private static final String s_block = "block".intern(); + private static final String s_turnstile = "turnstile".intern(); + private static final String s_camp_site = "camp_site".intern(); + private static final String s_shoes = "shoes".intern(); + private static final String s_reservoir = "reservoir".intern(); + private static final String s_pebblestone = "pebblestone".intern(); + private static final String s_stile = "stile".intern(); + private static final String s_embassy = "embassy".intern(); + private static final String s_postal_code = "postal_code".intern(); + private static final String s_retaining_wall = "retaining_wall".intern(); + private static final String s_bridleway = "bridleway".intern(); + private static final String s_pitch = "pitch".intern(); + private static final String s_agricultural = "agricultural".intern(); + private static final String s_post_office = "post_office".intern(); + private static final String s_parking_fuel = "parking;fuel".intern(); + private static final String s_bureau_de_change = "bureau_de_change".intern(); + private static final String s_mini_roundabout = "mini_roundabout".intern(); + private static final String s_hov = "hov".intern(); + private static final String s_police = "police".intern(); + private static final String s_courthouse = "courthouse".intern(); + private static final String s_raceway = "raceway".intern(); + private static final String s_kindergarten = "kindergarten".intern(); + private static final String s_attraction = "attraction".intern(); + private static final String s_marsh = "marsh".intern(); + private static final String s_reservoir_covered = "reservoir_covered".intern(); + private static final String s_petroleum_well = "petroleum_well".intern(); + private static final String s_silo = "silo".intern(); + private static final String s_toys = "toys".intern(); + private static final String s_apron = "apron".intern(); + private static final String s_halt = "halt".intern(); + private static final String s_dam = "dam".intern(); + private static final String s_golf_course = "golf_course".intern(); + private static final String s_detour = "detour".intern(); + private static final String s_tree_row = "tree_row".intern(); + private static final String s_copyshop = "copyshop".intern(); + private static final String s_milestone = "milestone".intern(); + private static final String s_foot = "foot".intern(); + private static final String s_tourism = "tourism".intern(); + private static final String s_bank = "bank".intern(); + private static final String s_dry_cleaning = "dry_cleaning".intern(); + private static final String s_tram = "tram".intern(); + private static final String s_trolleybus = "trolleybus".intern(); + private static final String s_university = "university".intern(); + private static final String s_hampshire_gate = "hampshire_gate".intern(); + private static final String s_embankment = "embankment".intern(); + private static final String s_rock = "rock".intern(); + private static final String s_crossing = "crossing".intern(); + private static final String s_volcano = "volcano".intern(); + private static final String s_greengrocer = "greengrocer".intern(); + private static final String s_kerb = "kerb".intern(); + private static final String s_waste_disposal = "waste_disposal".intern(); + private static final String s_grave_yard = "grave_yard".intern(); + private static final String s_coniferous = "coniferous".intern(); + private static final String s_house = "house".intern(); + private static final String s_books = "books".intern(); + private static final String s_neighbourhood = "neighbourhood".intern(); + private static final String s_hostel = "hostel".intern(); + private static final String s_alcohol = "alcohol".intern(); + private static final String s_restricted = "restricted".intern(); + private static final String s_motel = "motel".intern(); + private static final String s_sand = "sand".intern(); + private static final String s_fishmonger = "fishmonger".intern(); + private static final String s_fountain = "fountain".intern(); + private static final String s_playground = "playground".intern(); + private static final String s_7 = "7".intern(); + private static final String s_parking_aisle = "parking_aisle".intern(); + private static final String s_protected_area = "protected_area".intern(); + private static final String s_electronics = "electronics".intern(); + private static final String s_Paved = "Paved".intern(); + private static final String s_highway = "highway".intern(); + private static final String s_fine_gravel = "fine_gravel".intern(); + private static final String s_barrier = "barrier".intern(); + private static final String s_hairdresser = "hairdresser".intern(); + private static final String s_post_box = "post_box".intern(); + private static final String s_pub = "pub".intern(); + private static final String s_coastline = "coastline".intern(); + private static final String s_marina = "marina".intern(); + private static final String s_reedbed = "reedbed".intern(); + private static final String s_biergarten = "biergarten".intern(); + private static final String s_dismantled = "dismantled".intern(); + private static final String s_farmland = "farmland".intern(); + private static final String s_yard = "yard".intern(); + private static final String s_route = "route".intern(); + private static final String s_atm = "atm".intern(); + private static final String s_place = "place".intern(); + private static final String s_bus_station = "bus_station".intern(); + private static final String s_retail = "retail".intern(); + private static final String s_industrial = "industrial".intern(); + private static final String s_municipality = "municipality".intern(); + private static final String s_primary = "primary".intern(); + private static final String s_nursing_home = "nursing_home".intern(); + private static final String s_florist = "florist".intern(); + private static final String s_ditch = "ditch".intern(); + private static final String s_national_park = "national_park".intern(); + private static final String s_city = "city".intern(); + private static final String s_confectionery = "confectionery".intern(); + private static final String s_service = "service".intern(); + private static final String s_unknown = "unknown".intern(); + private static final String s_cycle_barrier = "cycle_barrier".intern(); + private static final String s_elevator = "elevator".intern(); + private static final String s_2 = "2".intern(); + private static final String s_car_rental = "car_rental".intern(); + private static final String s_flagpole = "flagpole".intern(); + private static final String s_cabin = "cabin".intern(); + private static final String s_paved = "paved".intern(); + private static final String s_guest_house = "guest_house".intern(); + private static final String s_mobile_phone = "mobile_phone".intern(); + private static final String s_lot = "lot".intern(); + private static final String s_quarry = "quarry".intern(); + private static final String s_train_station = "train_station".intern(); + private static final String s_hotel = "hotel".intern(); + private static final String s_park = "park".intern(); + private static final String s_hut = "hut".intern(); + private static final String s_dentist = "dentist".intern(); + private static final String s_doctors = "doctors".intern(); + private static final String s_greenhouse = "greenhouse".intern(); + private static final String s_11 = "11".intern(); + private static final String s_10 = "10".intern(); + private static final String s_theme_park = "theme_park".intern(); + private static final String s_tree = "tree".intern(); + private static final String s_shower = "shower".intern(); + private static final String s_siding = "siding".intern(); + private static final String s_aeroway = "aeroway".intern(); + private static final String s_emergency_access_point = "emergency_access_point" + .intern(); + private static final String s_watermill = "watermill".intern(); + private static final String s_college = "college".intern(); + private static final String s_landuse = "landuse".intern(); + private static final String s_tracktype = "tracktype".intern(); + private static final String s_ferry = "ferry".intern(); + private static final String s_bridge = "bridge".intern(); + private static final String s_vacant = "vacant".intern(); + private static final String s_cattle_grid = "cattle_grid".intern(); + private static final String s_brownfield = "brownfield".intern(); + private static final String s_allotments = "allotments".intern(); + private static final String s_alley = "alley".intern(); + private static final String s_pedestrian = "pedestrian".intern(); + private static final String s_borough = "borough".intern(); + private static final String s_bare_rock = "bare_rock".intern(); + private static final String s_motorcycle = "motorcycle".intern(); + private static final String s_bakery = "bakery".intern(); + private static final String s_zoo = "zoo".intern(); + private static final String s_scree = "scree".intern(); + private static final String s_fire_station = "fire_station".intern(); + private static final String s_theatre = "theatre".intern(); + private static final String s_track = "track".intern(); + private static final String s_reinforced_slope = "reinforced_slope".intern(); + private static final String s_slipway = "slipway".intern(); + private static final String s_mangrove = "mangrove".intern(); + private static final String s_aerodrome = "aerodrome".intern(); + private static final String s_byway = "byway".intern(); + private static final String s_metal = "metal".intern(); + private static final String s_swamp = "swamp".intern(); + private static final String s_construction = "construction".intern(); + private static final String s_grassland = "grassland".intern(); + private static final String s_shop = "shop".intern(); + private static final String s_soakhole = "soakhole".intern(); + private static final String s_asphalt = "asphalt".intern(); + private static final String s_social_facility = "social_facility".intern(); + private static final String s_isolated_dwelling = "isolated_dwelling".intern(); + private static final String s_hamlet = "hamlet".intern(); + private static final String s_picnic_table = "picnic_table".intern(); + private static final String s_artificial = "artificial".intern(); + private static final String s_earth = "earth".intern(); + private static final String s_grit_bin = "grit_bin".intern(); + private static final String s_ground = "ground".intern(); + private static final String s_groyne = "groyne".intern(); + private static final String s_office = "office".intern(); + private static final String s_state = "state".intern(); + private static final String s_terminal = "terminal".intern(); + private static final String s_wood = "wood".intern(); + private static final String s_fuel = "fuel".intern(); + private static final String s_8 = "8".intern(); + private static final String s_garden_centre = "garden_centre".intern(); + private static final String s_horse_riding = "horse_riding".intern(); + private static final String s_viewpoint = "viewpoint".intern(); + private static final String s_designated = "designated".intern(); + private static final String s_leisure = "leisure".intern(); + private static final String s_waste_basket = "waste_basket".intern(); + private static final String s_hifi = "hifi".intern(); + private static final String s_hedge = "hedge".intern(); + private static final String s_spur = "spur".intern(); + private static final String s_chimney = "chimney".intern(); + private static final String s_secondary = "secondary".intern(); + private static final String s_rest_area = "rest_area".intern(); + private static final String s_bar = "bar".intern(); + private static final String s_bay = "bay".intern(); + private static final String s_common = "common".intern(); + private static final String s_river = "river".intern(); + private static final String s_ruins = "ruins".intern(); + private static final String s_terrace = "terrace".intern(); + private static final String s_art = "art".intern(); + private static final String s_residental = "residental".intern(); + private static final String s_newsagent = "newsagent".intern(); + private static final String s_turntable = "turntable".intern(); + private static final String s_computer = "computer".intern(); + private static final String s_wetland = "wetland".intern(); + private static final String s_driveway = "driveway".intern(); + private static final String s_parking = "parking".intern(); + private static final String s_compacted = "compacted".intern(); + private static final String s_barn = "barn".intern(); + private static final String s_alpine_hut = "alpine_hut".intern(); + private static final String s_wire_fence = "wire_fence".intern(); + private static final String s_unpaved = "unpaved".intern(); + private static final String s_dormitory = "dormitory".intern(); + private static final String s_mud = "mud".intern(); + private static final String s_3 = "3".intern(); + private static final String s_semi = "semi".intern(); + private static final String s_boundary = "boundary".intern(); + private static final String s_field_boundary = "field_boundary".intern(); + private static final String s_beverages = "beverages".intern(); + private static final String s_supermarket = "supermarket".intern(); + private static final String s_store = "store".intern(); + private static final String s_restaurant = "restaurant".intern(); + private static final String s_region = "region".intern(); + private static final String s_variety_store = "variety_store".intern(); + private static final String s_saltmarsh = "saltmarsh".intern(); + private static final String s_landform = "landform".intern(); + private static final String s_helipad = "helipad".intern(); + private static final String s_railway = "railway".intern(); + private static final String s_greenhouse_horticulture = "greenhouse_horticulture" + .intern(); + private static final String s_wall = "wall".intern(); + private static final String s_recycling = "recycling".intern(); + private static final String s_passing_place = "passing_place".intern(); + private static final String s_church = "church".intern(); + private static final String s_pharmacy = "pharmacy".intern(); + private static final String s_lighthouse = "lighthouse".intern(); + private static final String s_platform = "platform".intern(); + private static final String s_cinema = "cinema".intern(); + private static final String s_political = "political".intern(); + private static final String s_stadium = "stadium".intern(); + private static final String s_basin = "basin".intern(); + private static final String s_gasometer = "gasometer".intern(); + private static final String s_bicycle_parking = "bicycle_parking".intern(); + private static final String s_bbq = "bbq".intern(); + private static final String s_incline_steep = "incline_steep".intern(); + private static final String s_drinking_water = "drinking_water".intern(); + private static final String s_living_street = "living_street".intern(); + private static final String s_chalet = "chalet".intern(); + private static final String s_narrow_gauge = "narrow_gauge".intern(); + private static final String s_prison = "prison".intern(); + private static final String s_mine = "mine".intern(); + private static final String s_level_crossing = "level_crossing".intern(); + private static final String s_water_works = "water_works".intern(); + private static final String s_street_lamp = "street_lamp".intern(); + private static final String s_main = "main".intern(); + private static final String s_tank = "tank".intern(); + private static final String s_abandoned = "abandoned".intern(); + private static final String s_ski = "ski".intern(); + private static final String s_runway = "runway".intern(); + private static final String s_parking_space = "parking_space".intern(); + private static final String s_dirt_sand = "dirt/sand".intern(); + private static final String s_salt_pond = "salt_pond".intern(); + private static final String s_hedge_bank = "hedge_bank".intern(); + private static final String s_amenity = "amenity".intern(); + private static final String s_telephone = "telephone".intern(); + private static final String s_surface = "surface".intern(); + private static final String s_travel_agency = "travel_agency".intern(); + private static final String s_hardware = "hardware".intern(); + private static final String s_wastewater_plant = "wastewater_plant".intern(); + private static final String s_waterway = "waterway".intern(); + private static final String s_butcher = "butcher".intern(); + private static final String s_surveillance = "surveillance".intern(); + private static final String s_Dirt_Sand = "Dirt/Sand".intern(); + private static final String s_9 = "9".intern(); + private static final String s_windmill = "windmill".intern(); + private static final String s_picnic_site = "picnic_site".intern(); + private static final String s_rail = "rail".intern(); + private static final String s_cement = "cement".intern(); + private static final String s_sauna = "sauna".intern(); + private static final String s_suburb = "suburb".intern(); + private static final String s_waterfall = "waterfall".intern(); + private static final String s_bunker = "bunker".intern(); + private static final String s_ice_cream = "ice_cream".intern(); + private static final String s_culvert = "culvert".intern(); + private static final String s_drain = "drain".intern(); + private static final String s_dock = "dock".intern(); + private static final String s_glasshouse = "glasshouse".intern(); + private static final String s_no = "no".intern(); + private static final String s_well = "well".intern(); + private static final String s_wet_meadow = "wet_meadow".intern(); + private static final String s_concrete = "concrete".intern(); + private static final String s_dismount = "dismount".intern(); + private static final String s_vending_machine = "vending_machine".intern(); + private static final String s_oneway = "oneway".intern(); + private static final String s_taxi = "taxi".intern(); + private static final String s_outdoor = "outdoor".intern(); + private static final String s_proposed = "proposed".intern(); + private static final String s_sally_port = "sally_port".intern(); + private static final String s_photo = "photo".intern(); + private static final String s_plant_nursery = "plant_nursery".intern(); + private static final String s_clinic = "clinic".intern(); + private static final String s_fishing = "fishing".intern(); + private static final String s_yes = "yes".intern(); + private static final String s_turning_circle = "turning_circle".intern(); + private static final String s_toilets = "toilets".intern(); + private static final String s_guard_rail = "guard_rail".intern(); + private static final String s_townhall = "townhall".intern(); + private static final String s_community_centre = "community_centre".intern(); + private static final String s_residential = "residential".intern(); + private static final String s_cemetery = "cemetery".intern(); + private static final String s_survey_point = "survey_point".intern(); + private static final String s_bench = "bench".intern(); + private static final String s_4 = "4".intern(); + private static final String s_bollard = "bollard".intern(); + private static final String s_sports_centre = "sports_centre".intern(); + private static final String s_paving_stones_30 = "paving_stones:30".intern(); + private static final String s_administrative = "administrative".intern(); + private static final String s_Building = "Building".intern(); + private static final String s_customers = "customers".intern(); + private static final String s_emergency = "emergency".intern(); + private static final String s_motorway_junction = "motorway_junction".intern(); + private static final String s_grade1 = "grade1".intern(); + private static final String s_grade3 = "grade3".intern(); + private static final String s_grade2 = "grade2".intern(); + private static final String s_grade5 = "grade5".intern(); + private static final String s_grade4 = "grade4".intern(); + private static final String s_lock_gate = "lock_gate".intern(); + private static final String s_furniture = "furniture".intern(); + private static final String s_place_of_worship = "place_of_worship".intern(); + private static final String s_optician = "optician".intern(); + private static final String s_gift = "gift".intern(); + private static final String s_parking_entrance = "parking_entrance".intern(); + private static final String s_garage = "garage".intern(); + private static final String s_tram_stop = "tram_stop".intern(); + private static final String s_steps = "steps".intern(); + private static final String s_tower = "tower".intern(); + private static final String s_works = "works".intern(); + private static final String s_shed = "shed".intern(); + private static final String s_car_sharing = "car_sharing".intern(); + private static final String s_apartments = "apartments".intern(); + private static final String s_spring = "spring".intern(); + private static final String s_village = "village".intern(); + private static final String s_library = "library".intern(); + private static final String s_emergency_access = "emergency_access".intern(); + private static final String s_home = "home".intern(); + private static final String s_farm_auxiliary = "farm_auxiliary".intern(); + private static final String s_primary_link = "primary_link".intern(); + private static final String s_toll_booth = "toll_booth".intern(); + private static final String s_jewelry = "jewelry".intern(); + private static final String s_pet = "pet".intern(); + private static final String s_veterinary = "veterinary".intern(); + private static final String s_man_made = "man_made".intern(); + private static final String s_motorway_link = "motorway_link".intern(); + private static final String s_offices = "offices".intern(); + private static final String s_power = "power".intern(); + private static final String s_weir = "weir".intern(); + private static final String s_unsurfaced = "unsurfaced".intern(); + private static final String s_tertiary_link = "tertiary_link".intern(); + private static final String s_trunk_link = "trunk_link".intern(); + private static final String s_tyres = "tyres".intern(); + private static final String s_paving_stones = "paving_stones".intern(); + private static final String s_pipeline = "pipeline".intern(); + private static final String s_census = "census".intern(); + private static final String s_incline = "incline".intern(); + private static final String s_footway = "footway".intern(); + private static final String s_drive_through = "drive-through".intern(); + private static final String s_island = "island".intern(); + private static final String s_monitoring_station = "monitoring_station".intern(); + private static final String s_nightclub = "nightclub".intern(); + private static final String s_unclassified = "unclassified".intern(); + private static final String s_aquaculture = "aquaculture".intern(); + private static final String s_mixed = "mixed".intern(); + private static final String s_road = "road".intern(); + private static final String s_greenfield = "greenfield".intern(); + private static final String s_breakwater = "breakwater".intern(); + private static final String s_services = "services".intern(); + private static final String s_railway_crossing = "railway_crossing".intern(); + private static final String s_residentiel1 = "residentiel1".intern(); + private static final String s_canal = "canal".intern(); + private static final String s__1 = "-1".intern(); + private static final String s_ridge = "ridge".intern(); + private static final String s_fabric = "fabric".intern(); + private static final String s_museum = "museum".intern(); + private static final String s_communications_tower = "communications_tower".intern(); + private static final String s_semi_detached = "semi-detached".intern(); + private static final String s_conservation = "conservation".intern(); + private static final String s_way = "way".intern(); + private static final String s_wood_fence = "wood_fence".intern(); + private static final String s_manufacture = "manufacture".intern(); + private static final String s_admin_level = "admin_level".intern(); + private static final String s_building_concrete = "building_concrete".intern(); + private static final String s_bus = "bus".intern(); + private static final String s_collapsed = "collapsed".intern(); + private static final String s_ford = "ford".intern(); + private static final String s_delivery = "delivery".intern(); + private static final String s_garages = "garages".intern(); + private static final String s_funeral_directors = "funeral_directors".intern(); + private static final String s_land = "land".intern(); + private static final String s_interlock = "interlock".intern(); + private static final String s_reef = "reef".intern(); + private static final String s_crane = "crane".intern(); + private static final String s_true = "true".intern(); + private static final String s_storage_tank = "storage_tank".intern(); + private static final String s_official = "official".intern(); + private static final String s_subway_entrance = "subway_entrance".intern(); + private static final String s_mtb = "mtb".intern(); + private static final String s_grass = "grass".intern(); + private static final String s_marketplace = "marketplace".intern(); + private static final String s_rapids = "rapids".intern(); + private static final String s_car_wash = "car_wash".intern(); + private static final String s_general = "general".intern(); + private static final String s_cafe = "cafe".intern(); + private static final String s_locality = "locality".intern(); + private static final String s_glacier = "glacier".intern(); + private static final String s_storage = "storage".intern(); + private static final String s_cycleway = "cycleway".intern(); + private static final String s_forestry = "forestry".intern(); + private static final String s_field = "field".intern(); + private static final String s_5 = "5".intern(); + private static final String s_arts_centre = "arts_centre".intern(); + private static final String s_warehouse = "warehouse".intern(); + private static final String s_chemist = "chemist".intern(); + private static final String s_pier = "pier".intern(); + private static final String s_scrub = "scrub".intern(); + private static final String s_shelter = "shelter".intern(); + private static final String s_emergency_phone = "emergency_phone".intern(); + private static final String s_tidalflat = "tidalflat".intern(); + private static final String s_cobblestone = "cobblestone".intern(); + private static final String s_fell = "fell".intern(); + private static final String s_peak = "peak".intern(); + private static final String s_charging_station = "charging_station".intern(); + private static final String s_cliff = "cliff".intern(); + private static final String s_building = "building".intern(); + private static final String s_fire_hydrant = "fire_hydrant".intern(); + private static final String s_traffic_signals = "traffic_signals".intern(); + private static final String s_heath = "heath".intern(); + private static final String s_landfill = "landfill".intern(); + private static final String s_mast = "mast".intern(); + private static final String s_boutique = "boutique".intern(); + private static final String s_boat_storage = "boat_storage".intern(); - public static final Tag[] tags = { + public static final Tag[] tags = { - new Tag(s_building, s_yes, false), new Tag(s_highway, s_residential, false), - new Tag(s_highway, s_service, false), new Tag(s_waterway, s_stream, false), - new Tag(s_highway, s_unclassified, false), new Tag(s_highway, s_track, false), - new Tag(s_oneway, s_yes, false), new Tag(s_natural, s_water, false), - new Tag(s_highway, s_footway, false), new Tag(s_access, s_private, false), - new Tag(s_highway, s_tertiary, false), new Tag(s_highway, s_path, false), - new Tag(s_highway, s_secondary, false), new Tag(s_landuse, s_forest, false), - new Tag(s_bridge, s_yes, false), new Tag(s_natural, s_tree, false), - new Tag(s_surface, s_paved, false), new Tag(s_natural, s_wood, false), - new Tag(s_highway, s_primary, false), new Tag(s_landuse, s_grass, false), - new Tag(s_landuse, s_residential, false), new Tag(s_surface, s_unpaved, false), - new Tag(s_highway, s_bus_stop, false), new Tag(s_surface, s_asphalt, false), - new Tag(s_bicycle, s_yes, false), new Tag(s_amenity, s_parking, false), - new Tag(s_place, s_locality, false), new Tag(s_railway, s_rail, false), - new Tag(s_service, s_parking_aisle, false), - new Tag(s_boundary, s_administrative, false), - new Tag(s_building, s_house, false), new Tag(s_place, s_village, false), - new Tag(s_natural, s_coastline, false), new Tag(s_tracktype, s_grade2, false), - new Tag(s_oneway, s_no, false), new Tag(s_service, s_driveway, false), - new Tag(s_highway, s_turning_circle, false), new Tag(s_place, s_hamlet, false), - new Tag(s_natural, s_wetland, false), new Tag(s_tracktype, s_grade3, false), - new Tag(s_waterway, s_river, false), new Tag(s_highway, s_cycleway, false), - new Tag(s_barrier, s_fence, false), new Tag(s_building, s_residential, false), - new Tag(s_amenity, s_school, false), new Tag(s_highway, s_crossing, false), - new Tag(s_admin_level, s_8, false), new Tag(s_highway, s_trunk, false), - new Tag(s_amenity, s_place_of_worship, false), - new Tag(s_landuse, s_farmland, false), new Tag(s_tracktype, s_grade1, false), - new Tag(s_highway, s_road, false), new Tag(s_landuse, s_farm, false), - new Tag(s_surface, s_gravel, false), new Tag(s_landuse, s_meadow, false), - new Tag(s_highway, s_motorway, false), - new Tag(s_highway, s_traffic_signals, false), - new Tag(s_building, s_hut, false), new Tag(s_highway, s_motorway_link, false), - new Tag(s_tracktype, s_grade4, false), new Tag(s_barrier, s_gate, false), - new Tag(s_highway, s_living_street, false), new Tag(s_bicycle, s_no, false), - new Tag(s_leisure, s_pitch, false), new Tag(s_tunnel, s_yes, false), - new Tag(s_surface, s_ground, false), new Tag(s_highway, s_steps, false), - new Tag(s_natural, s_land, false), new Tag(s_man_made, s_survey_point, false), - new Tag(s_tracktype, s_grade5, false), new Tag(s_waterway, s_ditch, false), - new Tag(s_leisure, s_park, false), new Tag(s_amenity, s_restaurant, false), - new Tag(s_barrier, s_wall, false), new Tag(s_waterway, s_riverbank, false), - new Tag(s_amenity, s_bench, false), new Tag(s_building, s_garage, false), - new Tag(s_natural, s_scrub, false), new Tag(s_highway, s_pedestrian, false), - new Tag(s_natural, s_peak, false), new Tag(s_building, s_entrance, false), - new Tag(s_landuse, s_reservoir, false), new Tag(s_access, s_yes, false), - new Tag(s_bicycle, s_designated, false), - new Tag(s_leisure, s_swimming_pool, false), - new Tag(s_landuse, s_farmyard, false), - new Tag(s_railway, s_level_crossing, false), - new Tag(s_building, s_apartments, false), new Tag(s_surface, s_grass, false), - new Tag(s_wheelchair, s_yes, false), new Tag(s_service, s_alley, false), - new Tag(s_landuse, s_industrial, false), new Tag(s_amenity, s_fuel, false), - new Tag(s_surface, s_dirt, false), new Tag(s_highway, s_trunk_link, false), - new Tag(s_waterway, s_drain, false), new Tag(s_barrier, s_hedge, false), - new Tag(s_amenity, s_grave_yard, false), - new Tag(s_tourism, s_information, false), - new Tag(s_shop, s_supermarket, false), - new Tag(s_highway, s_primary_link, false), new Tag(s_wood, s_deciduous, false), - new Tag(s_leisure, s_playground, false), new Tag(s_building, s_roof, false), - new Tag(s_building, s_industrial, false), - new Tag(s_amenity, s_post_box, false), new Tag(s_waterway, s_canal, false), - new Tag(s_barrier, s_bollard, false), new Tag(s_leisure, s_garden, false), - new Tag(s_wood, s_mixed, false), new Tag(s_landuse, s_cemetery, false), - new Tag(s_landuse, s_orchard, false), new Tag(s_shop, s_convenience, false), - new Tag(s_access, s_permissive, false), new Tag(s_surface, s_concrete, false), - new Tag(s_surface, s_paving_stones, false), new Tag(s_service, s_spur, false), - new Tag(s_building, s_garages, false), new Tag(s_amenity, s_bank, false), - new Tag(s_tourism, s_hotel, false), new Tag(s_access, s_no, false), - new Tag(s_amenity, s_fast_food, false), new Tag(s_man_made, s_pier, false), - new Tag(s_amenity, s_kindergarten, false), - new Tag(s_access, s_agricultural, false), - new Tag(s_surface, s_cobblestone, false), new Tag(s_wheelchair, s_no, false), - new Tag(s_amenity, s_cafe, false), new Tag(s_amenity, s_hospital, false), - new Tag(s_amenity, s_post_office, false), - new Tag(s_amenity, s_public_building, false), - new Tag(s_amenity, s_recycling, false), - new Tag(s_highway, s_street_lamp, false), new Tag(s_man_made, s_tower, false), - new Tag(s_waterway, s_dam, false), new Tag(s_amenity, s_pub, false), - new Tag(s_wood, s_coniferous, false), new Tag(s_access, s_destination, false), - new Tag(s_admin_level, s_6, false), new Tag(s_landuse, s_commercial, false), - new Tag(s_amenity, s_pharmacy, false), new Tag(s_railway, s_abandoned, false), - new Tag(s_service, s_yard, false), new Tag(s_place, s_island, false), - new Tag(s_oneway, s__1, false), new Tag(s_landuse, s_quarry, false), - new Tag(s_landuse, s_vineyard, false), - new Tag(s_highway, s_motorway_junction, false), - new Tag(s_railway, s_station, false), new Tag(s_landuse, s_allotments, false), - new Tag(s_barrier, s_lift_gate, false), new Tag(s_admin_level, s_10, false), - new Tag(s_amenity, s_telephone, false), new Tag(s_place, s_town, false), - new Tag(s_man_made, s_cutline, false), new Tag(s_place, s_suburb, false), - new Tag(s_aeroway, s_taxiway, false), new Tag(s_wheelchair, s_limited, false), - new Tag(s_highway, s_secondary_link, false), - new Tag(s_leisure, s_sports_centre, false), - new Tag(s_amenity, s_bicycle_parking, false), - new Tag(s_surface, s_sand, false), new Tag(s_highway, s_stop, false), - new Tag(s_man_made, s_works, false), new Tag(s_landuse, s_retail, false), - new Tag(s_amenity, s_fire_station, false), new Tag(s_service, s_siding, false), - new Tag(s_amenity, s_toilets, false), new Tag(s_bench, s_yes, false), - new Tag(s_oneway, s_1, false), new Tag(s_surface, s_compacted, false), - new Tag(s_landuse, s_basin, false), new Tag(s_amenity, s_police, false), - new Tag(s_railway, s_tram, false), new Tag(s_route, s_road, false), - new Tag(s_natural, s_cliff, false), new Tag(s_highway, s_construction, false), - new Tag(s_aeroway, s_aerodrome, false), new Tag(s_entrance, s_yes, false), - new Tag(s_man_made, s_storage_tank, false), new Tag(s_amenity, s_atm, false), - new Tag(s_tourism, s_attraction, false), new Tag(s_route, s_bus, false), - new Tag(s_shop, s_bakery, false), new Tag(s_tourism, s_viewpoint, false), - new Tag(s_amenity, s_swimming_pool, false), new Tag(s_natural, s_beach, false), - new Tag(s_tourism, s_picnic_site, false), new Tag(s_oneway, s_true, false), - new Tag(s_highway, s_bridleway, false), new Tag(s_tourism, s_camp_site, false), - new Tag(s_abutters, s_residential, false), - new Tag(s_leisure, s_nature_reserve, false), - new Tag(s_amenity, s_drinking_water, false), new Tag(s_shop, s_clothes, false), - new Tag(s_natural, s_heath, false), - new Tag(s_highway, s_mini_roundabout, false), - new Tag(s_landuse, s_construction, false), - new Tag(s_amenity, s_waste_basket, false), - new Tag(s_railway, s_platform, false), new Tag(s_amenity, s_townhall, false), - new Tag(s_shop, s_hairdresser, false), new Tag(s_amenity, s_shelter, false), - new Tag(s_admin_level, s_9, false), - new Tag(s_building, s_farm_auxiliary, false), - new Tag(s_amenity, s_library, false), new Tag(s_building, s_detached, false), - new Tag(s_admin_level, s_4, false), new Tag(s_landuse, s_village_green, false), - new Tag(s_barrier, s_stile, false), new Tag(s_landuse, s_garages, false), - new Tag(s_amenity, s_bar, false), new Tag(s_railway, s_buffer_stop, false), - new Tag(s_wetland, s_marsh, false), new Tag(s_tourism, s_museum, false), - new Tag(s_barrier, s_cycle_barrier, false), new Tag(s_route, s_bicycle, false), - new Tag(s_railway, s_tram_stop, false), - new Tag(s_amenity, s_parking_space, false), - new Tag(s_barrier, s_retaining_wall, false), - new Tag(s_landuse, s_recreation_ground, false), - new Tag(s_amenity, s_university, false), - new Tag(s_highway, s_tertiary_link, false), - new Tag(s_building, s_terrace, false), new Tag(s_shop, s_car_repair, false), - new Tag(s_amenity, s_hunting_stand, false), - new Tag(s_amenity, s_fountain, false), new Tag(s_man_made, s_pipeline, false), - new Tag(s_wetland, s_swamp, false), new Tag(s_shop, s_car, false), - new Tag(s_bench, s_no, false), new Tag(s_tunnel, s_culvert, false), - new Tag(s_building, s_school, false), new Tag(s_barrier, s_entrance, false), - new Tag(s_railway, s_disused, false), new Tag(s_railway, s_crossing, false), - new Tag(s_building, s_church, false), - new Tag(s_amenity, s_social_facility, false), new Tag(s_natural, s_bay, false), - new Tag(s_shop, s_kiosk, false), new Tag(s_amenity, s_vending_machine, false), - new Tag(s_route, s_hiking, false), new Tag(s_natural, s_spring, false), - new Tag(s_leisure, s_common, false), new Tag(s_railway, s_switch, false), - new Tag(s_waterway, s_rapids, false), new Tag(s_admin_level, s_7, false), - new Tag(s_leisure, s_stadium, false), new Tag(s_leisure, s_track, false), - new Tag(s_place, s_isolated_dwelling, false), new Tag(s_place, s_islet, false), - new Tag(s_waterway, s_weir, false), new Tag(s_amenity, s_doctors, false), - new Tag(s_access, s_designated, false), - new Tag(s_landuse, s_conservation, false), - new Tag(s_waterway, s_artificial, false), - new Tag(s_amenity, s_bus_station, false), - new Tag(s_leisure, s_golf_course, false), - new Tag(s_shop, s_doityourself, false), new Tag(s_building, s_service, false), - new Tag(s_tourism, s_guest_house, false), new Tag(s_aeroway, s_runway, false), - new Tag(s_place, s_city, false), new Tag(s_railway, s_subway, false), - new Tag(s_man_made, s_wastewater_plant, false), - new Tag(s_building, s_commercial, false), new Tag(s_railway, s_halt, false), - new Tag(s_amenity, s_emergency_phone, false), - new Tag(s_building, s_retail, false), new Tag(s_barrier, s_block, false), - new Tag(s_leisure, s_recreation_ground, false), - new Tag(s_access, s_forestry, false), new Tag(s_amenity, s_college, false), - new Tag(s_highway, s_platform, false), new Tag(s_access, s_unknown, false), - new Tag(s_man_made, s_water_tower, false), - new Tag(s_surface, s_pebblestone, false), new Tag(s_bridge, s_viaduct, false), - new Tag(s_shop, s_butcher, false), new Tag(s_shop, s_florist, false), - new Tag(s_boundary, s_landuse, false), new Tag(s_aeroway, s_helipad, false), - new Tag(s_building, s_hangar, false), new Tag(s_natural, s_glacier, false), - new Tag(s_highway, s_proposed, false), new Tag(s_shop, s_mall, false), - new Tag(s_barrier, s_toll_booth, false), - new Tag(s_amenity, s_fire_hydrant, false), - new Tag(s_building, s_manufacture, false), new Tag(s_building, s_farm, false), - new Tag(s_surface, s_wood, false), new Tag(s_amenity, s_car_wash, false), - new Tag(s_amenity, s_dentist, false), new Tag(s_natural, s_marsh, false), - new Tag(s_man_made, s_surveillance, false), new Tag(s_shop, s_bicycle, false), - new Tag(s_route, s_foot, false), new Tag(s_amenity, s_theatre, false), - new Tag(s_building, s_office, false), new Tag(s_railway, s_light_rail, false), - new Tag(s_man_made, s_petroleum_well, false), - new Tag(s_amenity, s_taxi, false), new Tag(s_building, s_greenhouse, false), - new Tag(s_landuse, s_brownfield, false), - new Tag(s_bicycle, s_permissive, false), new Tag(s_admin_level, s_2, false), - new Tag(s_aeroway, s_apron, false), new Tag(s_building, s_cabin, false), - new Tag(s_amenity, s_cinema, false), new Tag(s_access, s_customers, false), - new Tag(s_tourism, s_motel, false), new Tag(s_railway, s_narrow_gauge, false), - new Tag(s_amenity, s_marketplace, false), new Tag(s_shop, s_furniture, false), - new Tag(s_entrance, s_staircase, false), new Tag(s_tourism, s_artwork, false), - new Tag(s_natural, s_grassland, false), new Tag(s_shop, s_books, false), - new Tag(s_admin_level, s_5, false), new Tag(s_man_made, s_groyne, false), - new Tag(s_waterway, s_lock_gate, false), - new Tag(s_highway, s_emergency_access_point, false), - new Tag(s_natural, s_sand, false), new Tag(s_landuse, s_military, false), - new Tag(s_boundary, s_protected_area, false), - new Tag(s_amenity, s_community_centre, false), - new Tag(s_barrier, s_kissing_gate, false), - new Tag(s_highway, s_speed_camera, false), - new Tag(s_boundary, s_national_park, false), - new Tag(s_railway, s_subway_entrance, false), - new Tag(s_man_made, s_silo, false), new Tag(s_shop, s_alcohol, false), - new Tag(s_highway, s_give_way, false), new Tag(s_leisure, s_slipway, false), - new Tag(s_shop, s_electronics, false), new Tag(s_bicycle, s_dismount, false), - new Tag(s_leisure, s_marina, false), new Tag(s_entrance, s_main, false), - new Tag(s_boundary, s_postal_code, false), - new Tag(s_landuse, s_greenhouse_horticulture, false), - new Tag(s_highway, s_milestone, false), - new Tag(s_natural, s_cave_entrance, false), - new Tag(s_landuse, s_landfill, false), new Tag(s_shop, s_chemist, false), - new Tag(s_shop, s_shoes, false), new Tag(s_barrier, s_cattle_grid, false), - new Tag(s_landuse, s_railway, false), new Tag(s_tourism, s_hostel, false), - new Tag(s_tourism, s_chalet, false), new Tag(s_place, s_county, false), - new Tag(s_shop, s_department_store, false), new Tag(s_highway, s_ford, false), - new Tag(s_natural, s_scree, false), new Tag(s_landuse, s_greenfield, false), - new Tag(s_amenity, s_nursing_home, false), - new Tag(s_barrier, s_wire_fence, false), - new Tag(s_access, s_restricted, false), - new Tag(s_man_made, s_reservoir_covered, false), - new Tag(s_amenity, s_bicycle_rental, false), new Tag(s_man_made, s_MDF, false), - new Tag(s_man_made, s_water_well, false), new Tag(s_landuse, s_field, false), - new Tag(s_landuse, s_wood, false), new Tag(s_shop, s_hardware, false), - new Tag(s_tourism, s_alpine_hut, false), new Tag(s_natural, s_tree_row, false), - new Tag(s_tourism, s_caravan_site, false), new Tag(s_bridge, s_no, false), - new Tag(s_wetland, s_bog, false), new Tag(s_amenity, s_courthouse, false), - new Tag(s_route, s_ferry, false), new Tag(s_barrier, s_city_wall, false), - new Tag(s_amenity, s_veterinary, false), new Tag(s_shop, s_jewelry, false), - new Tag(s_building, s_transportation, false), - new Tag(s_amenity, s_arts_centre, false), - new Tag(s_bicycle, s_official, false), new Tag(s_shop, s_optician, false), - new Tag(s_shop, s_yes, false), new Tag(s_building, s_collapsed, false), - new Tag(s_shop, s_garden_centre, false), new Tag(s_man_made, s_chimney, false), - new Tag(s_man_made, s_mine, false), new Tag(s_bench, s_unknown, false), - new Tag(s_railway, s_preserved, false), new Tag(s_building, s_public, false), - new Tag(s_amenity, s_ferry_terminal, false), - new Tag(s_highway, s_raceway, false), new Tag(s_natural, s_rock, false), - new Tag(s_tunnel, s_no, false), new Tag(s_building, s_university, false), - new Tag(s_shop, s_beverages, false), - new Tag(s_amenity, s_waste_disposal, false), - new Tag(s_building, s_warehouse, false), - new Tag(s_leisure, s_water_park, false), new Tag(s_shop, s_gift, false), - new Tag(s_place, s_farm, false), new Tag(s_wetland, s_tidalflat, false), - new Tag(s_waterway, s_waterfall, false), new Tag(s_man_made, s_dolphin, false), - new Tag(s_service, s_drive_through, false), - new Tag(s_amenity, s_nightclub, false), new Tag(s_building, s_shed, false), - new Tag(s_shop, s_greengrocer, false), new Tag(s_natural, s_fell, false), - new Tag(s_wetland, s_wet_meadow, false), new Tag(s_aeroway, s_gate, false), - new Tag(s_shop, s_computer, false), new Tag(s_man_made, s_lighthouse, false), - new Tag(s_wetland, s_reedbed, false), new Tag(s_man_made, s_breakwater, false), - new Tag(s_surface, s_Dirt_Sand, false), new Tag(s_barrier, s_ditch, false), - new Tag(s_barrier, s_yes, false), new Tag(s_amenity, s_biergarten, false), - new Tag(s_shop, s_mobile_phone, false), new Tag(s_route, s_mtb, false), - new Tag(s_amenity, s_grit_bin, false), new Tag(s_amenity, s_bbq, false), - new Tag(s_shop, s_sports, false), new Tag(s_barrier, s_wood_fence, false), - new Tag(s_entrance, s_home, false), new Tag(s_shop, s_laundry, false), - new Tag(s_man_made, s_gasometer, false), - new Tag(s_barrier, s_embankment, false), new Tag(s_shop, s_toys, false), - new Tag(s_wetland, s_saltmarsh, false), new Tag(s_waterway, s_soakhole, false), - new Tag(s_shop, s_travel_agency, false), - new Tag(s_man_made, s_water_works, false), new Tag(s_route, s_railway, false), - new Tag(s_amenity, s_prison, false), new Tag(s_highway, s_rest_area, false), - new Tag(s_shop, s_stationery, false), new Tag(s_admin_level, s_11, false), - new Tag(s_building, s_train_station, false), - new Tag(s_building, s_storage_tank, false), - new Tag(s_man_made, s_windmill, false), new Tag(s_shop, s_beauty, false), - new Tag(s_building, s_semi, false), new Tag(s_highway, s_services, false), - new Tag(s_bicycle, s_private, false), new Tag(s_route, s_ski, false), - new Tag(s_service, s_emergency_access, false), - new Tag(s_building, s_factory, false), - new Tag(s_man_made, s_reinforced_slope, false), - new Tag(s_amenity, s_car_sharing, false), new Tag(s_surface, s_earth, false), - new Tag(s_shop, s_hifi, false), new Tag(s_amenity, s_car_rental, false), - new Tag(s_barrier, s_hedge_bank, false), - new Tag(s_shop, s_confectionery, false), new Tag(s_aeroway, s_terminal, false), - new Tag(s_highway, s_passing_place, false), - new Tag(s_building, s_building, false), new Tag(s_man_made, s_dyke, false), - new Tag(s_building, s_construction, false), new Tag(s_building, s_shop, false), - new Tag(s_natural, s_reef, false), new Tag(s_landuse, s_aquaculture, false), - new Tag(s_shop, s_dry_cleaning, false), new Tag(s_amenity, s_embassy, false), - new Tag(s_shop, s_newsagent, false), new Tag(s_landuse, s_salt_pond, false), - new Tag(s_railway, s_spur, false), new Tag(s_wheelchair, s_unknown, false), - new Tag(s_tourism, s_zoo, false), new Tag(s_man_made, s_waterway, false), - new Tag(s_surface, s_fine_gravel, false), new Tag(s_shop, s_motorcycle, false), - new Tag(s_building, s_Building, false), - new Tag(s_railway, s_construction, false), - new Tag(s_place, s_neighbourhood, false), new Tag(s_route, s_train, false), - new Tag(s_building, s_no, false), new Tag(s_natural, s_mud, false), - new Tag(s_place, s_region, false), - new Tag(s_landuse, s_reservoir_watershed, false), - new Tag(s_boundary, s_marker, false), new Tag(s_man_made, s_beacon, false), - new Tag(s_shop, s_outdoor, false), new Tag(s_access, s_public, false), - new Tag(s_abutters, s_industrial, false), new Tag(s_building, s_barn, false), - new Tag(s_leisure, s_picnic_table, false), - new Tag(s_building, s_hospital, false), new Tag(s_access, s_official, false), - new Tag(s_shop, s_variety_store, false), new Tag(s_man_made, s_crane, false), - new Tag(s_amenity, s_parking_fuel, false), new Tag(s_route, s_tram, false), - new Tag(s_tourism, s_theme_park, false), new Tag(s_shop, s_pet, false), - new Tag(s_building, s_kindergarten, false), - new Tag(s_man_made, s_storage, false), new Tag(s_man_made, s_mast, false), - new Tag(s_amenity, s_parking_entrance, false), - new Tag(s_amenity, s_clock, false), - new Tag(s_landuse, s_industrial_retail, false), - new Tag(s_shop, s_video, false), new Tag(s_access, s_delivery, false), - new Tag(s_amenity, s_driving_school, false), new Tag(s_service, s_yes, false), - new Tag(s_natural, s_bare_rock, false), new Tag(s_building, s_chapel, false), - new Tag(s_natural, s_volcano, false), new Tag(s_waterway, s_dock, false), - new Tag(s_building, s_dormitory, false), - new Tag(s_amenity, s_boat_storage, false), new Tag(s_man_made, s_tank, false), - new Tag(s_man_made, s_flagpole, false), - new Tag(s_surface, s_grass_paver, false), new Tag(s_shop, s_organic, false), - new Tag(s_natural, s_landform, false), new Tag(s_highway, s_unsurfaced, false), - new Tag(s_route, s_power, false), new Tag(s_surface, s_mud, false), - new Tag(s_building, s_building_concrete, false), - new Tag(s_abutters, s_retail, false), new Tag(s_building, s_store, false), - new Tag(s_shop, s_vacant, false), new Tag(s_leisure, s_miniature_golf, false), - new Tag(s_man_made, s_monitoring_station, false), - new Tag(s_natural, s_waterfall, false), new Tag(s_aeroway, s_hangar, false), - new Tag(s_shop, s_boutique, false), new Tag(s_route, s_detour, false), - new Tag(s_building, s_way, false), new Tag(s_railway, s_stop, false), - new Tag(s_amenity, s_ice_cream, false), new Tag(s_building, s_storage, false), - new Tag(s_shop, s_car_parts, false), new Tag(s_natural, s_ridge, false), - new Tag(s_shop, s_tyres, false), new Tag(s_railway, s_dismantled, false), - new Tag(s_amenity, s_shop, false), new Tag(s_landuse, s_plant_nursery, false), - new Tag(s_building, s_residentiel1, false), - new Tag(s_barrier, s_field_boundary, false), - new Tag(s_barrier, s_border_control, false), - new Tag(s_surface, s_Paved, false), new Tag(s_barrier, s_sally_port, false), - new Tag(s_amenity, s_bureau_de_change, false), - new Tag(s_leisure, s_fishing, false), - new Tag(s_amenity, s_charging_station, false), - new Tag(s_building, s_supermarket, false), new Tag(s_highway, s_stile, false), - new Tag(s_amenity, s_sauna, false), new Tag(s_place, s_municipality, false), - new Tag(s_building, s_hotel, false), new Tag(s_surface, s_metal, false), - new Tag(s_highway, s_incline_steep, false), - new Tag(s_shop, s_estate_agent, false), new Tag(s_natural, s_grass, false), - new Tag(s_shop, s_pharmacy, false), - new Tag(s_surface, s_concrete_plates, false), - new Tag(s_shop, s_copyshop, false), - new Tag(s_surface, s_paving_stones_30, false), - new Tag(s_surface, s_interlock, false), new Tag(s_access, s_hov, false), - new Tag(s_highway, s_elevator, false), - new Tag(s_boundary, s_local_authority, false), - new Tag(s_man_made, s_communications_tower, false), - new Tag(s_shop, s_deli, false), new Tag(s_barrier, s_turnstile, false), - new Tag(s_building, s_offices, false), new Tag(s_building, s_bunker, false), - new Tag(s_natural, s_stone, false), - new Tag(s_railway, s_railway_crossing, false), - new Tag(s_leisure, s_dog_park, false), - new Tag(s_building, s_semi_detached, false), - new Tag(s_man_made, s_watermill, false), new Tag(s_route, s_trolleybus, false), - new Tag(s_admin_level, s_3, false), new Tag(s_building, s_block, false), - new Tag(s_barrier, s_guard_rail, false), new Tag(s_bicycle, s_unknown, false), - new Tag(s_highway, s_abandoned, false), new Tag(s_surface, s_dirt_sand, false), - new Tag(s_barrier, s_chain, false), new Tag(s_barrier, s_bump_gate, false), - new Tag(s_building, s_residental, false), new Tag(s_surface, s_cement, false), - new Tag(s_man_made, s_embankment, false), new Tag(s_building, s_ruins, false), - new Tag(s_highway, s_incline, false), new Tag(s_abutters, s_commercial, false), - new Tag(s_barrier, s_hampshire_gate, false), new Tag(s_shop, s_music, false), - new Tag(s_shop, s_funeral_directors, false), - new Tag(s_wetland, s_mangrove, false), new Tag(s_place, s_borough, false), - new Tag(s_building, s_apartment, false), new Tag(s_boundary, s_census, false), - new Tag(s_barrier, s_kerb, false), new Tag(s_building, s_glasshouse, false), - new Tag(s_aeroway, s_holding_position, false), - new Tag(s_shop, s_general, false), new Tag(s_building, s_tank, false), - new Tag(s_railway, s_monorail, false), new Tag(s_service, s_parking, false), - new Tag(s_place, s_state, false), new Tag(s_railway, s_proposed, false), - new Tag(s_shop, s_art, false), new Tag(s_natural, s_hill, false), - new Tag(s_railway, s_turntable, false), new Tag(s_tourism, s_cabin, false), - new Tag(s_shop, s_photo, false), new Tag(s_boundary, s_lot, false), - new Tag(s_shop, s_fishmonger, false), new Tag(s_amenity, s_clinic, false), - new Tag(s_boundary, s_political, false), new Tag(s_man_made, s_well, false), - new Tag(s_highway, s_byway, false), new Tag(s_leisure, s_horse_riding, false), - new Tag(s_service, s_bus, false), new Tag(s_building, s_tower, false), - new Tag(s_entrance, s_service, false), new Tag(s_shop, s_fabric, false), - new Tag(s_railway, s_miniature, false), new Tag(s_abutters, s_mixed, false), - new Tag(s_surface, s_stone, false), new Tag(s_access, s_emergency, false), - new Tag(s_landuse, s_mine, false), new Tag(s_amenity, s_shower, false), - new Tag(s_waterway, s_lock, false) - }; + new Tag(s_building, s_yes, false), new Tag(s_highway, s_residential, false), + new Tag(s_highway, s_service, false), new Tag(s_waterway, s_stream, false), + new Tag(s_highway, s_unclassified, false), new Tag(s_highway, s_track, false), + new Tag(s_oneway, s_yes, false), new Tag(s_natural, s_water, false), + new Tag(s_highway, s_footway, false), new Tag(s_access, s_private, false), + new Tag(s_highway, s_tertiary, false), new Tag(s_highway, s_path, false), + new Tag(s_highway, s_secondary, false), new Tag(s_landuse, s_forest, false), + new Tag(s_bridge, s_yes, false), new Tag(s_natural, s_tree, false), + new Tag(s_surface, s_paved, false), new Tag(s_natural, s_wood, false), + new Tag(s_highway, s_primary, false), new Tag(s_landuse, s_grass, false), + new Tag(s_landuse, s_residential, false), new Tag(s_surface, s_unpaved, false), + new Tag(s_highway, s_bus_stop, false), new Tag(s_surface, s_asphalt, false), + new Tag(s_bicycle, s_yes, false), new Tag(s_amenity, s_parking, false), + new Tag(s_place, s_locality, false), new Tag(s_railway, s_rail, false), + new Tag(s_service, s_parking_aisle, false), + new Tag(s_boundary, s_administrative, false), + new Tag(s_building, s_house, false), new Tag(s_place, s_village, false), + new Tag(s_natural, s_coastline, false), new Tag(s_tracktype, s_grade2, false), + new Tag(s_oneway, s_no, false), new Tag(s_service, s_driveway, false), + new Tag(s_highway, s_turning_circle, false), new Tag(s_place, s_hamlet, false), + new Tag(s_natural, s_wetland, false), new Tag(s_tracktype, s_grade3, false), + new Tag(s_waterway, s_river, false), new Tag(s_highway, s_cycleway, false), + new Tag(s_barrier, s_fence, false), new Tag(s_building, s_residential, false), + new Tag(s_amenity, s_school, false), new Tag(s_highway, s_crossing, false), + new Tag(s_admin_level, s_8, false), new Tag(s_highway, s_trunk, false), + new Tag(s_amenity, s_place_of_worship, false), + new Tag(s_landuse, s_farmland, false), new Tag(s_tracktype, s_grade1, false), + new Tag(s_highway, s_road, false), new Tag(s_landuse, s_farm, false), + new Tag(s_surface, s_gravel, false), new Tag(s_landuse, s_meadow, false), + new Tag(s_highway, s_motorway, false), + new Tag(s_highway, s_traffic_signals, false), + new Tag(s_building, s_hut, false), new Tag(s_highway, s_motorway_link, false), + new Tag(s_tracktype, s_grade4, false), new Tag(s_barrier, s_gate, false), + new Tag(s_highway, s_living_street, false), new Tag(s_bicycle, s_no, false), + new Tag(s_leisure, s_pitch, false), new Tag(s_tunnel, s_yes, false), + new Tag(s_surface, s_ground, false), new Tag(s_highway, s_steps, false), + new Tag(s_natural, s_land, false), new Tag(s_man_made, s_survey_point, false), + new Tag(s_tracktype, s_grade5, false), new Tag(s_waterway, s_ditch, false), + new Tag(s_leisure, s_park, false), new Tag(s_amenity, s_restaurant, false), + new Tag(s_barrier, s_wall, false), new Tag(s_waterway, s_riverbank, false), + new Tag(s_amenity, s_bench, false), new Tag(s_building, s_garage, false), + new Tag(s_natural, s_scrub, false), new Tag(s_highway, s_pedestrian, false), + new Tag(s_natural, s_peak, false), new Tag(s_building, s_entrance, false), + new Tag(s_landuse, s_reservoir, false), new Tag(s_access, s_yes, false), + new Tag(s_bicycle, s_designated, false), + new Tag(s_leisure, s_swimming_pool, false), + new Tag(s_landuse, s_farmyard, false), + new Tag(s_railway, s_level_crossing, false), + new Tag(s_building, s_apartments, false), new Tag(s_surface, s_grass, false), + new Tag(s_wheelchair, s_yes, false), new Tag(s_service, s_alley, false), + new Tag(s_landuse, s_industrial, false), new Tag(s_amenity, s_fuel, false), + new Tag(s_surface, s_dirt, false), new Tag(s_highway, s_trunk_link, false), + new Tag(s_waterway, s_drain, false), new Tag(s_barrier, s_hedge, false), + new Tag(s_amenity, s_grave_yard, false), + new Tag(s_tourism, s_information, false), + new Tag(s_shop, s_supermarket, false), + new Tag(s_highway, s_primary_link, false), new Tag(s_wood, s_deciduous, false), + new Tag(s_leisure, s_playground, false), new Tag(s_building, s_roof, false), + new Tag(s_building, s_industrial, false), + new Tag(s_amenity, s_post_box, false), new Tag(s_waterway, s_canal, false), + new Tag(s_barrier, s_bollard, false), new Tag(s_leisure, s_garden, false), + new Tag(s_wood, s_mixed, false), new Tag(s_landuse, s_cemetery, false), + new Tag(s_landuse, s_orchard, false), new Tag(s_shop, s_convenience, false), + new Tag(s_access, s_permissive, false), new Tag(s_surface, s_concrete, false), + new Tag(s_surface, s_paving_stones, false), new Tag(s_service, s_spur, false), + new Tag(s_building, s_garages, false), new Tag(s_amenity, s_bank, false), + new Tag(s_tourism, s_hotel, false), new Tag(s_access, s_no, false), + new Tag(s_amenity, s_fast_food, false), new Tag(s_man_made, s_pier, false), + new Tag(s_amenity, s_kindergarten, false), + new Tag(s_access, s_agricultural, false), + new Tag(s_surface, s_cobblestone, false), new Tag(s_wheelchair, s_no, false), + new Tag(s_amenity, s_cafe, false), new Tag(s_amenity, s_hospital, false), + new Tag(s_amenity, s_post_office, false), + new Tag(s_amenity, s_public_building, false), + new Tag(s_amenity, s_recycling, false), + new Tag(s_highway, s_street_lamp, false), new Tag(s_man_made, s_tower, false), + new Tag(s_waterway, s_dam, false), new Tag(s_amenity, s_pub, false), + new Tag(s_wood, s_coniferous, false), new Tag(s_access, s_destination, false), + new Tag(s_admin_level, s_6, false), new Tag(s_landuse, s_commercial, false), + new Tag(s_amenity, s_pharmacy, false), new Tag(s_railway, s_abandoned, false), + new Tag(s_service, s_yard, false), new Tag(s_place, s_island, false), + new Tag(s_oneway, s__1, false), new Tag(s_landuse, s_quarry, false), + new Tag(s_landuse, s_vineyard, false), + new Tag(s_highway, s_motorway_junction, false), + new Tag(s_railway, s_station, false), new Tag(s_landuse, s_allotments, false), + new Tag(s_barrier, s_lift_gate, false), new Tag(s_admin_level, s_10, false), + new Tag(s_amenity, s_telephone, false), new Tag(s_place, s_town, false), + new Tag(s_man_made, s_cutline, false), new Tag(s_place, s_suburb, false), + new Tag(s_aeroway, s_taxiway, false), new Tag(s_wheelchair, s_limited, false), + new Tag(s_highway, s_secondary_link, false), + new Tag(s_leisure, s_sports_centre, false), + new Tag(s_amenity, s_bicycle_parking, false), + new Tag(s_surface, s_sand, false), new Tag(s_highway, s_stop, false), + new Tag(s_man_made, s_works, false), new Tag(s_landuse, s_retail, false), + new Tag(s_amenity, s_fire_station, false), new Tag(s_service, s_siding, false), + new Tag(s_amenity, s_toilets, false), new Tag(s_bench, s_yes, false), + new Tag(s_oneway, s_1, false), new Tag(s_surface, s_compacted, false), + new Tag(s_landuse, s_basin, false), new Tag(s_amenity, s_police, false), + new Tag(s_railway, s_tram, false), new Tag(s_route, s_road, false), + new Tag(s_natural, s_cliff, false), new Tag(s_highway, s_construction, false), + new Tag(s_aeroway, s_aerodrome, false), new Tag(s_entrance, s_yes, false), + new Tag(s_man_made, s_storage_tank, false), new Tag(s_amenity, s_atm, false), + new Tag(s_tourism, s_attraction, false), new Tag(s_route, s_bus, false), + new Tag(s_shop, s_bakery, false), new Tag(s_tourism, s_viewpoint, false), + new Tag(s_amenity, s_swimming_pool, false), new Tag(s_natural, s_beach, false), + new Tag(s_tourism, s_picnic_site, false), new Tag(s_oneway, s_true, false), + new Tag(s_highway, s_bridleway, false), new Tag(s_tourism, s_camp_site, false), + new Tag(s_abutters, s_residential, false), + new Tag(s_leisure, s_nature_reserve, false), + new Tag(s_amenity, s_drinking_water, false), new Tag(s_shop, s_clothes, false), + new Tag(s_natural, s_heath, false), + new Tag(s_highway, s_mini_roundabout, false), + new Tag(s_landuse, s_construction, false), + new Tag(s_amenity, s_waste_basket, false), + new Tag(s_railway, s_platform, false), new Tag(s_amenity, s_townhall, false), + new Tag(s_shop, s_hairdresser, false), new Tag(s_amenity, s_shelter, false), + new Tag(s_admin_level, s_9, false), + new Tag(s_building, s_farm_auxiliary, false), + new Tag(s_amenity, s_library, false), new Tag(s_building, s_detached, false), + new Tag(s_admin_level, s_4, false), new Tag(s_landuse, s_village_green, false), + new Tag(s_barrier, s_stile, false), new Tag(s_landuse, s_garages, false), + new Tag(s_amenity, s_bar, false), new Tag(s_railway, s_buffer_stop, false), + new Tag(s_wetland, s_marsh, false), new Tag(s_tourism, s_museum, false), + new Tag(s_barrier, s_cycle_barrier, false), new Tag(s_route, s_bicycle, false), + new Tag(s_railway, s_tram_stop, false), + new Tag(s_amenity, s_parking_space, false), + new Tag(s_barrier, s_retaining_wall, false), + new Tag(s_landuse, s_recreation_ground, false), + new Tag(s_amenity, s_university, false), + new Tag(s_highway, s_tertiary_link, false), + new Tag(s_building, s_terrace, false), new Tag(s_shop, s_car_repair, false), + new Tag(s_amenity, s_hunting_stand, false), + new Tag(s_amenity, s_fountain, false), new Tag(s_man_made, s_pipeline, false), + new Tag(s_wetland, s_swamp, false), new Tag(s_shop, s_car, false), + new Tag(s_bench, s_no, false), new Tag(s_tunnel, s_culvert, false), + new Tag(s_building, s_school, false), new Tag(s_barrier, s_entrance, false), + new Tag(s_railway, s_disused, false), new Tag(s_railway, s_crossing, false), + new Tag(s_building, s_church, false), + new Tag(s_amenity, s_social_facility, false), new Tag(s_natural, s_bay, false), + new Tag(s_shop, s_kiosk, false), new Tag(s_amenity, s_vending_machine, false), + new Tag(s_route, s_hiking, false), new Tag(s_natural, s_spring, false), + new Tag(s_leisure, s_common, false), new Tag(s_railway, s_switch, false), + new Tag(s_waterway, s_rapids, false), new Tag(s_admin_level, s_7, false), + new Tag(s_leisure, s_stadium, false), new Tag(s_leisure, s_track, false), + new Tag(s_place, s_isolated_dwelling, false), new Tag(s_place, s_islet, false), + new Tag(s_waterway, s_weir, false), new Tag(s_amenity, s_doctors, false), + new Tag(s_access, s_designated, false), + new Tag(s_landuse, s_conservation, false), + new Tag(s_waterway, s_artificial, false), + new Tag(s_amenity, s_bus_station, false), + new Tag(s_leisure, s_golf_course, false), + new Tag(s_shop, s_doityourself, false), new Tag(s_building, s_service, false), + new Tag(s_tourism, s_guest_house, false), new Tag(s_aeroway, s_runway, false), + new Tag(s_place, s_city, false), new Tag(s_railway, s_subway, false), + new Tag(s_man_made, s_wastewater_plant, false), + new Tag(s_building, s_commercial, false), new Tag(s_railway, s_halt, false), + new Tag(s_amenity, s_emergency_phone, false), + new Tag(s_building, s_retail, false), new Tag(s_barrier, s_block, false), + new Tag(s_leisure, s_recreation_ground, false), + new Tag(s_access, s_forestry, false), new Tag(s_amenity, s_college, false), + new Tag(s_highway, s_platform, false), new Tag(s_access, s_unknown, false), + new Tag(s_man_made, s_water_tower, false), + new Tag(s_surface, s_pebblestone, false), new Tag(s_bridge, s_viaduct, false), + new Tag(s_shop, s_butcher, false), new Tag(s_shop, s_florist, false), + new Tag(s_boundary, s_landuse, false), new Tag(s_aeroway, s_helipad, false), + new Tag(s_building, s_hangar, false), new Tag(s_natural, s_glacier, false), + new Tag(s_highway, s_proposed, false), new Tag(s_shop, s_mall, false), + new Tag(s_barrier, s_toll_booth, false), + new Tag(s_amenity, s_fire_hydrant, false), + new Tag(s_building, s_manufacture, false), new Tag(s_building, s_farm, false), + new Tag(s_surface, s_wood, false), new Tag(s_amenity, s_car_wash, false), + new Tag(s_amenity, s_dentist, false), new Tag(s_natural, s_marsh, false), + new Tag(s_man_made, s_surveillance, false), new Tag(s_shop, s_bicycle, false), + new Tag(s_route, s_foot, false), new Tag(s_amenity, s_theatre, false), + new Tag(s_building, s_office, false), new Tag(s_railway, s_light_rail, false), + new Tag(s_man_made, s_petroleum_well, false), + new Tag(s_amenity, s_taxi, false), new Tag(s_building, s_greenhouse, false), + new Tag(s_landuse, s_brownfield, false), + new Tag(s_bicycle, s_permissive, false), new Tag(s_admin_level, s_2, false), + new Tag(s_aeroway, s_apron, false), new Tag(s_building, s_cabin, false), + new Tag(s_amenity, s_cinema, false), new Tag(s_access, s_customers, false), + new Tag(s_tourism, s_motel, false), new Tag(s_railway, s_narrow_gauge, false), + new Tag(s_amenity, s_marketplace, false), new Tag(s_shop, s_furniture, false), + new Tag(s_entrance, s_staircase, false), new Tag(s_tourism, s_artwork, false), + new Tag(s_natural, s_grassland, false), new Tag(s_shop, s_books, false), + new Tag(s_admin_level, s_5, false), new Tag(s_man_made, s_groyne, false), + new Tag(s_waterway, s_lock_gate, false), + new Tag(s_highway, s_emergency_access_point, false), + new Tag(s_natural, s_sand, false), new Tag(s_landuse, s_military, false), + new Tag(s_boundary, s_protected_area, false), + new Tag(s_amenity, s_community_centre, false), + new Tag(s_barrier, s_kissing_gate, false), + new Tag(s_highway, s_speed_camera, false), + new Tag(s_boundary, s_national_park, false), + new Tag(s_railway, s_subway_entrance, false), + new Tag(s_man_made, s_silo, false), new Tag(s_shop, s_alcohol, false), + new Tag(s_highway, s_give_way, false), new Tag(s_leisure, s_slipway, false), + new Tag(s_shop, s_electronics, false), new Tag(s_bicycle, s_dismount, false), + new Tag(s_leisure, s_marina, false), new Tag(s_entrance, s_main, false), + new Tag(s_boundary, s_postal_code, false), + new Tag(s_landuse, s_greenhouse_horticulture, false), + new Tag(s_highway, s_milestone, false), + new Tag(s_natural, s_cave_entrance, false), + new Tag(s_landuse, s_landfill, false), new Tag(s_shop, s_chemist, false), + new Tag(s_shop, s_shoes, false), new Tag(s_barrier, s_cattle_grid, false), + new Tag(s_landuse, s_railway, false), new Tag(s_tourism, s_hostel, false), + new Tag(s_tourism, s_chalet, false), new Tag(s_place, s_county, false), + new Tag(s_shop, s_department_store, false), new Tag(s_highway, s_ford, false), + new Tag(s_natural, s_scree, false), new Tag(s_landuse, s_greenfield, false), + new Tag(s_amenity, s_nursing_home, false), + new Tag(s_barrier, s_wire_fence, false), + new Tag(s_access, s_restricted, false), + new Tag(s_man_made, s_reservoir_covered, false), + new Tag(s_amenity, s_bicycle_rental, false), new Tag(s_man_made, s_MDF, false), + new Tag(s_man_made, s_water_well, false), new Tag(s_landuse, s_field, false), + new Tag(s_landuse, s_wood, false), new Tag(s_shop, s_hardware, false), + new Tag(s_tourism, s_alpine_hut, false), new Tag(s_natural, s_tree_row, false), + new Tag(s_tourism, s_caravan_site, false), new Tag(s_bridge, s_no, false), + new Tag(s_wetland, s_bog, false), new Tag(s_amenity, s_courthouse, false), + new Tag(s_route, s_ferry, false), new Tag(s_barrier, s_city_wall, false), + new Tag(s_amenity, s_veterinary, false), new Tag(s_shop, s_jewelry, false), + new Tag(s_building, s_transportation, false), + new Tag(s_amenity, s_arts_centre, false), + new Tag(s_bicycle, s_official, false), new Tag(s_shop, s_optician, false), + new Tag(s_shop, s_yes, false), new Tag(s_building, s_collapsed, false), + new Tag(s_shop, s_garden_centre, false), new Tag(s_man_made, s_chimney, false), + new Tag(s_man_made, s_mine, false), new Tag(s_bench, s_unknown, false), + new Tag(s_railway, s_preserved, false), new Tag(s_building, s_public, false), + new Tag(s_amenity, s_ferry_terminal, false), + new Tag(s_highway, s_raceway, false), new Tag(s_natural, s_rock, false), + new Tag(s_tunnel, s_no, false), new Tag(s_building, s_university, false), + new Tag(s_shop, s_beverages, false), + new Tag(s_amenity, s_waste_disposal, false), + new Tag(s_building, s_warehouse, false), + new Tag(s_leisure, s_water_park, false), new Tag(s_shop, s_gift, false), + new Tag(s_place, s_farm, false), new Tag(s_wetland, s_tidalflat, false), + new Tag(s_waterway, s_waterfall, false), new Tag(s_man_made, s_dolphin, false), + new Tag(s_service, s_drive_through, false), + new Tag(s_amenity, s_nightclub, false), new Tag(s_building, s_shed, false), + new Tag(s_shop, s_greengrocer, false), new Tag(s_natural, s_fell, false), + new Tag(s_wetland, s_wet_meadow, false), new Tag(s_aeroway, s_gate, false), + new Tag(s_shop, s_computer, false), new Tag(s_man_made, s_lighthouse, false), + new Tag(s_wetland, s_reedbed, false), new Tag(s_man_made, s_breakwater, false), + new Tag(s_surface, s_Dirt_Sand, false), new Tag(s_barrier, s_ditch, false), + new Tag(s_barrier, s_yes, false), new Tag(s_amenity, s_biergarten, false), + new Tag(s_shop, s_mobile_phone, false), new Tag(s_route, s_mtb, false), + new Tag(s_amenity, s_grit_bin, false), new Tag(s_amenity, s_bbq, false), + new Tag(s_shop, s_sports, false), new Tag(s_barrier, s_wood_fence, false), + new Tag(s_entrance, s_home, false), new Tag(s_shop, s_laundry, false), + new Tag(s_man_made, s_gasometer, false), + new Tag(s_barrier, s_embankment, false), new Tag(s_shop, s_toys, false), + new Tag(s_wetland, s_saltmarsh, false), new Tag(s_waterway, s_soakhole, false), + new Tag(s_shop, s_travel_agency, false), + new Tag(s_man_made, s_water_works, false), new Tag(s_route, s_railway, false), + new Tag(s_amenity, s_prison, false), new Tag(s_highway, s_rest_area, false), + new Tag(s_shop, s_stationery, false), new Tag(s_admin_level, s_11, false), + new Tag(s_building, s_train_station, false), + new Tag(s_building, s_storage_tank, false), + new Tag(s_man_made, s_windmill, false), new Tag(s_shop, s_beauty, false), + new Tag(s_building, s_semi, false), new Tag(s_highway, s_services, false), + new Tag(s_bicycle, s_private, false), new Tag(s_route, s_ski, false), + new Tag(s_service, s_emergency_access, false), + new Tag(s_building, s_factory, false), + new Tag(s_man_made, s_reinforced_slope, false), + new Tag(s_amenity, s_car_sharing, false), new Tag(s_surface, s_earth, false), + new Tag(s_shop, s_hifi, false), new Tag(s_amenity, s_car_rental, false), + new Tag(s_barrier, s_hedge_bank, false), + new Tag(s_shop, s_confectionery, false), new Tag(s_aeroway, s_terminal, false), + new Tag(s_highway, s_passing_place, false), + new Tag(s_building, s_building, false), new Tag(s_man_made, s_dyke, false), + new Tag(s_building, s_construction, false), new Tag(s_building, s_shop, false), + new Tag(s_natural, s_reef, false), new Tag(s_landuse, s_aquaculture, false), + new Tag(s_shop, s_dry_cleaning, false), new Tag(s_amenity, s_embassy, false), + new Tag(s_shop, s_newsagent, false), new Tag(s_landuse, s_salt_pond, false), + new Tag(s_railway, s_spur, false), new Tag(s_wheelchair, s_unknown, false), + new Tag(s_tourism, s_zoo, false), new Tag(s_man_made, s_waterway, false), + new Tag(s_surface, s_fine_gravel, false), new Tag(s_shop, s_motorcycle, false), + new Tag(s_building, s_Building, false), + new Tag(s_railway, s_construction, false), + new Tag(s_place, s_neighbourhood, false), new Tag(s_route, s_train, false), + new Tag(s_building, s_no, false), new Tag(s_natural, s_mud, false), + new Tag(s_place, s_region, false), + new Tag(s_landuse, s_reservoir_watershed, false), + new Tag(s_boundary, s_marker, false), new Tag(s_man_made, s_beacon, false), + new Tag(s_shop, s_outdoor, false), new Tag(s_access, s_public, false), + new Tag(s_abutters, s_industrial, false), new Tag(s_building, s_barn, false), + new Tag(s_leisure, s_picnic_table, false), + new Tag(s_building, s_hospital, false), new Tag(s_access, s_official, false), + new Tag(s_shop, s_variety_store, false), new Tag(s_man_made, s_crane, false), + new Tag(s_amenity, s_parking_fuel, false), new Tag(s_route, s_tram, false), + new Tag(s_tourism, s_theme_park, false), new Tag(s_shop, s_pet, false), + new Tag(s_building, s_kindergarten, false), + new Tag(s_man_made, s_storage, false), new Tag(s_man_made, s_mast, false), + new Tag(s_amenity, s_parking_entrance, false), + new Tag(s_amenity, s_clock, false), + new Tag(s_landuse, s_industrial_retail, false), + new Tag(s_shop, s_video, false), new Tag(s_access, s_delivery, false), + new Tag(s_amenity, s_driving_school, false), new Tag(s_service, s_yes, false), + new Tag(s_natural, s_bare_rock, false), new Tag(s_building, s_chapel, false), + new Tag(s_natural, s_volcano, false), new Tag(s_waterway, s_dock, false), + new Tag(s_building, s_dormitory, false), + new Tag(s_amenity, s_boat_storage, false), new Tag(s_man_made, s_tank, false), + new Tag(s_man_made, s_flagpole, false), + new Tag(s_surface, s_grass_paver, false), new Tag(s_shop, s_organic, false), + new Tag(s_natural, s_landform, false), new Tag(s_highway, s_unsurfaced, false), + new Tag(s_route, s_power, false), new Tag(s_surface, s_mud, false), + new Tag(s_building, s_building_concrete, false), + new Tag(s_abutters, s_retail, false), new Tag(s_building, s_store, false), + new Tag(s_shop, s_vacant, false), new Tag(s_leisure, s_miniature_golf, false), + new Tag(s_man_made, s_monitoring_station, false), + new Tag(s_natural, s_waterfall, false), new Tag(s_aeroway, s_hangar, false), + new Tag(s_shop, s_boutique, false), new Tag(s_route, s_detour, false), + new Tag(s_building, s_way, false), new Tag(s_railway, s_stop, false), + new Tag(s_amenity, s_ice_cream, false), new Tag(s_building, s_storage, false), + new Tag(s_shop, s_car_parts, false), new Tag(s_natural, s_ridge, false), + new Tag(s_shop, s_tyres, false), new Tag(s_railway, s_dismantled, false), + new Tag(s_amenity, s_shop, false), new Tag(s_landuse, s_plant_nursery, false), + new Tag(s_building, s_residentiel1, false), + new Tag(s_barrier, s_field_boundary, false), + new Tag(s_barrier, s_border_control, false), + new Tag(s_surface, s_Paved, false), new Tag(s_barrier, s_sally_port, false), + new Tag(s_amenity, s_bureau_de_change, false), + new Tag(s_leisure, s_fishing, false), + new Tag(s_amenity, s_charging_station, false), + new Tag(s_building, s_supermarket, false), new Tag(s_highway, s_stile, false), + new Tag(s_amenity, s_sauna, false), new Tag(s_place, s_municipality, false), + new Tag(s_building, s_hotel, false), new Tag(s_surface, s_metal, false), + new Tag(s_highway, s_incline_steep, false), + new Tag(s_shop, s_estate_agent, false), new Tag(s_natural, s_grass, false), + new Tag(s_shop, s_pharmacy, false), + new Tag(s_surface, s_concrete_plates, false), + new Tag(s_shop, s_copyshop, false), + new Tag(s_surface, s_paving_stones_30, false), + new Tag(s_surface, s_interlock, false), new Tag(s_access, s_hov, false), + new Tag(s_highway, s_elevator, false), + new Tag(s_boundary, s_local_authority, false), + new Tag(s_man_made, s_communications_tower, false), + new Tag(s_shop, s_deli, false), new Tag(s_barrier, s_turnstile, false), + new Tag(s_building, s_offices, false), new Tag(s_building, s_bunker, false), + new Tag(s_natural, s_stone, false), + new Tag(s_railway, s_railway_crossing, false), + new Tag(s_leisure, s_dog_park, false), + new Tag(s_building, s_semi_detached, false), + new Tag(s_man_made, s_watermill, false), new Tag(s_route, s_trolleybus, false), + new Tag(s_admin_level, s_3, false), new Tag(s_building, s_block, false), + new Tag(s_barrier, s_guard_rail, false), new Tag(s_bicycle, s_unknown, false), + new Tag(s_highway, s_abandoned, false), new Tag(s_surface, s_dirt_sand, false), + new Tag(s_barrier, s_chain, false), new Tag(s_barrier, s_bump_gate, false), + new Tag(s_building, s_residental, false), new Tag(s_surface, s_cement, false), + new Tag(s_man_made, s_embankment, false), new Tag(s_building, s_ruins, false), + new Tag(s_highway, s_incline, false), new Tag(s_abutters, s_commercial, false), + new Tag(s_barrier, s_hampshire_gate, false), new Tag(s_shop, s_music, false), + new Tag(s_shop, s_funeral_directors, false), + new Tag(s_wetland, s_mangrove, false), new Tag(s_place, s_borough, false), + new Tag(s_building, s_apartment, false), new Tag(s_boundary, s_census, false), + new Tag(s_barrier, s_kerb, false), new Tag(s_building, s_glasshouse, false), + new Tag(s_aeroway, s_holding_position, false), + new Tag(s_shop, s_general, false), new Tag(s_building, s_tank, false), + new Tag(s_railway, s_monorail, false), new Tag(s_service, s_parking, false), + new Tag(s_place, s_state, false), new Tag(s_railway, s_proposed, false), + new Tag(s_shop, s_art, false), new Tag(s_natural, s_hill, false), + new Tag(s_railway, s_turntable, false), new Tag(s_tourism, s_cabin, false), + new Tag(s_shop, s_photo, false), new Tag(s_boundary, s_lot, false), + new Tag(s_shop, s_fishmonger, false), new Tag(s_amenity, s_clinic, false), + new Tag(s_boundary, s_political, false), new Tag(s_man_made, s_well, false), + new Tag(s_highway, s_byway, false), new Tag(s_leisure, s_horse_riding, false), + new Tag(s_service, s_bus, false), new Tag(s_building, s_tower, false), + new Tag(s_entrance, s_service, false), new Tag(s_shop, s_fabric, false), + new Tag(s_railway, s_miniature, false), new Tag(s_abutters, s_mixed, false), + new Tag(s_surface, s_stone, false), new Tag(s_access, s_emergency, false), + new Tag(s_landuse, s_mine, false), new Tag(s_amenity, s_shower, false), + new Tag(s_waterway, s_lock, false) + }; } diff --git a/vtm-extras/src/org/oscim/tiling/source/oscimap/TileDecoder.java b/vtm-extras/src/org/oscim/tiling/source/oscimap/TileDecoder.java index 66e8948a..32e986e7 100644 --- a/vtm-extras/src/org/oscim/tiling/source/oscimap/TileDecoder.java +++ b/vtm-extras/src/org/oscim/tiling/source/oscimap/TileDecoder.java @@ -16,12 +16,6 @@ */ package org.oscim.tiling.source.oscimap; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.Tag; @@ -31,427 +25,433 @@ import org.oscim.tiling.source.PbfDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + public class TileDecoder extends PbfDecoder { - static final Logger log = LoggerFactory.getLogger(TileDecoder.class); - - private final static float REF_TILE_SIZE = 4096.0f; - - private static final int TAG_TILE_TAGS = 1; - private static final int TAG_TILE_WAYS = 2; - private static final int TAG_TILE_POLY = 3; - private static final int TAG_TILE_NODES = 4; - private static final int TAG_WAY_TAGS = 11; - private static final int TAG_WAY_INDEX = 12; - private static final int TAG_WAY_COORDS = 13; - private static final int TAG_WAY_LAYER = 21; - private static final int TAG_WAY_NUM_TAGS = 1; - private static final int TAG_WAY_NUM_INDICES = 2; - private static final int TAG_WAY_NUM_COORDS = 3; - - private static final int TAG_NODE_TAGS = 11; - private static final int TAG_NODE_COORDS = 12; - private static final int TAG_NODE_LAYER = 21; - private static final int TAG_NODE_NUM_TAGS = 1; - private static final int TAG_NODE_NUM_COORDS = 2; - - private int MAX_TILE_TAGS = 100; - private Tag[] curTags = new Tag[MAX_TILE_TAGS]; - private int mCurTagCnt; - - private ITileDataSink mSink; - private float mScale; - private Tile mTile; - private final MapElement mElem; - - TileDecoder() { - mElem = new MapElement(); - } - - @Override - public boolean decode(Tile tile, ITileDataSink sink, InputStream is) - throws IOException { - - setInputStream(is); - - mTile = tile; - mSink = sink; - mScale = REF_TILE_SIZE / Tile.SIZE; - return decode(); - } - - private static final int MAX_TAGS_CACHE = 100; - private static Map tagHash = - Collections.synchronizedMap(new LinkedHashMap(MAX_TAGS_CACHE, - 0.75f, - true) { - - private static final long serialVersionUID = 1L; - - //@Override - //protected boolean removeEldestEntry(Entry e) { - //if (size() < MAX_TAGS_CACHE) - //return false; - //return true; - //} - }); - - private boolean decode() throws IOException { - int val; - mCurTagCnt = 0; - - while (hasData() && (val = decodeVarint32()) > 0) { - // read tag and wire type - int tag = (val >> 3); - - switch (tag) { - case TAG_TILE_TAGS: - decodeTileTags(); - break; - - case TAG_TILE_WAYS: - decodeTileWays(false); - break; - - case TAG_TILE_POLY: - decodeTileWays(true); - break; - - case TAG_TILE_NODES: - decodeTileNodes(); - break; - - default: - log.debug("invalid type for tile: " + tag); - return false; - } - } - return true; - } - - private boolean decodeTileTags() throws IOException { - String tagString = decodeString(); - - if (tagString == null || tagString.length() == 0) { - curTags[mCurTagCnt++] = new Tag(Tag.KEY_NAME, "..."); - return false; - } - - Tag tag = tagHash.get(tagString); - - if (tag == null) { - if (tagString.startsWith(Tag.KEY_NAME)) - tag = new Tag(Tag.KEY_NAME, tagString.substring(5), false); - else - tag = Tag.parse(tagString); - - if (tag != null) - tagHash.put(tagString, tag); - } - - if (mCurTagCnt >= MAX_TILE_TAGS) { - MAX_TILE_TAGS = mCurTagCnt + 10; - Tag[] tmp = new Tag[MAX_TILE_TAGS]; - System.arraycopy(curTags, 0, tmp, 0, mCurTagCnt); - curTags = tmp; - } - curTags[mCurTagCnt++] = tag; - - return true; - } - - private boolean decodeTileWays(boolean polygon) throws IOException { - int bytes = decodeVarint32(); - - int end = position() + bytes; - int indexCnt = 0; - int tagCnt = 0; - int coordCnt = 0; - int layer = 5; - - boolean fail = false; - - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >> 3); - - switch (tag) { - case TAG_WAY_TAGS: - if (!decodeWayTags(tagCnt)) - return false; - break; - - case TAG_WAY_INDEX: - decodeWayIndices(indexCnt); - break; - - case TAG_WAY_COORDS: - if (coordCnt == 0) { - log.debug(mTile + " no coordinates"); - } - - mElem.ensurePointSize(coordCnt, false); - int cnt = decodeInterleavedPoints(mElem.points, mScale); - - if (cnt != coordCnt) { - log.debug(mTile + " wrong number of coordintes " - + coordCnt + "/" + cnt); - fail = true; - } - - break; - - case TAG_WAY_LAYER: - layer = decodeVarint32(); - break; - - case TAG_WAY_NUM_TAGS: - tagCnt = decodeVarint32(); - break; - - case TAG_WAY_NUM_INDICES: - indexCnt = decodeVarint32(); - break; - - case TAG_WAY_NUM_COORDS: - coordCnt = decodeVarint32(); - break; - - default: - log.debug("X invalid type for way: " + tag); - } - } - - if (fail || indexCnt == 0 || tagCnt == 0) { - log.debug("failed reading way: bytes:" + bytes + " index:" - //+ (tags != null ? tags.toString() : "...") + " " - + indexCnt + " " + coordCnt + " " + tagCnt); - return false; - } - - // FIXME, remove all tiles from cache then remove this below - //if (layer == 0) - // layer = 5; - mElem.type = polygon ? GeometryType.POLY : GeometryType.LINE; - mElem.setLayer(layer); - mSink.process(mElem); - return true; - } - - private boolean decodeTileNodes() throws IOException { - int bytes = decodeVarint32(); - - int end = position() + bytes; - int tagCnt = 0; - int coordCnt = 0; - byte layer = 0; - - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >> 3); - - switch (tag) { - case TAG_NODE_TAGS: - if (!decodeWayTags(tagCnt)) - return false; - break; - - case TAG_NODE_COORDS: - int cnt = decodeNodeCoordinates(coordCnt, layer); - if (cnt != coordCnt) { - log.debug("X wrong number of coordintes"); - return false; - } - break; - - case TAG_NODE_LAYER: - layer = (byte) decodeVarint32(); - break; - - case TAG_NODE_NUM_TAGS: - tagCnt = decodeVarint32(); - break; - - case TAG_NODE_NUM_COORDS: - coordCnt = decodeVarint32(); - break; - - default: - log.debug("X invalid type for node: " + tag); - } - } - - return true; - } - - private int decodeNodeCoordinates(int numNodes, byte layer) - throws IOException { - int bytes = decodeVarint32(); - - fillBuffer(bytes); - int cnt = 0; - int end = position() + bytes; - // read repeated sint32 - int lastX = 0; - int lastY = 0; - float[] coords = mElem.ensurePointSize(numNodes, false); - - while (position() < end && cnt < numNodes) { - int lon = deZigZag(decodeVarint32()); - int lat = deZigZag(decodeVarint32()); - lastX = lon + lastX; - lastY = lat + lastY; - coords[cnt++] = lastX / mScale; - coords[cnt++] = Tile.SIZE - lastY / mScale; - } - - mElem.index[0] = (short) numNodes; - mElem.type = GeometryType.POINT; - mElem.setLayer(layer); - mSink.process(mElem); - - return cnt; - } - - private boolean decodeWayTags(int tagCnt) throws IOException { - int bytes = decodeVarint32(); - - mElem.tags.clear(); - - int cnt = 0; - int end = position() + bytes; - int max = mCurTagCnt; - - for (; position() < end; cnt++) { - int tagNum = decodeVarint32(); - - if (tagNum < 0 || cnt == tagCnt) { - log.debug("NULL TAG: " + mTile - + " invalid tag:" + tagNum - + " " + tagCnt + "/" + cnt); - continue; - } - - if (tagNum < Tags.MAX) { - mElem.tags.add(Tags.tags[tagNum]); - continue; - } - - tagNum -= Tags.LIMIT; - - if (tagNum >= 0 && tagNum < max) { - mElem.tags.add(curTags[tagNum]); - } else { - log.debug("NULL TAG: " + mTile - + " could find tag:" - + tagNum + " " + tagCnt - + "/" + cnt); - } - } - - if (tagCnt != cnt) { - log.debug("NULL TAG: " + mTile); - return false; - } - - return true; - } - - private int decodeWayIndices(int indexCnt) throws IOException { - mElem.ensureIndexSize(indexCnt, false); - - decodeVarintArray(indexCnt, mElem.index); - - int[] index = mElem.index; - int coordCnt = 0; - - for (int i = 0; i < indexCnt; i++) { - coordCnt += index[i]; - index[i] *= 2; - } - - // set end marker - if (indexCnt < index.length) - index[indexCnt] = -1; - - return coordCnt; - } - - //@Override - protected int decodeInterleavedPoints(float[] coords, float scale) - throws IOException { - - int bytes = decodeVarint32(); - fillBuffer(bytes); - - int cnt = 0; - int lastX = 0; - int lastY = 0; - boolean even = true; - - byte[] buf = buffer; - int pos = bufferPos; - int end = pos + bytes; - int val; - - while (pos < end) { - if (buf[pos] >= 0) { - val = buf[pos++]; - - } else if (buf[pos + 1] >= 0) { - val = (buf[pos++] & 0x7f) - | buf[pos++] << 7; - - } else if (buf[pos + 2] >= 0) { - val = (buf[pos++] & 0x7f) - | (buf[pos++] & 0x7f) << 7 - | (buf[pos++]) << 14; - - } else if (buf[pos + 3] >= 0) { - val = (buf[pos++] & 0x7f) - | (buf[pos++] & 0x7f) << 7 - | (buf[pos++] & 0x7f) << 14 - | (buf[pos++]) << 21; - - } else { - val = (buf[pos++] & 0x7f) - | (buf[pos++] & 0x7f) << 7 - | (buf[pos++] & 0x7f) << 14 - | (buf[pos++] & 0x7f) << 21 - | (buf[pos]) << 28; - - if (buf[pos++] < 0) - throw INVALID_VARINT; - } - - // zigzag decoding - int s = ((val >>> 1) ^ -(val & 1)); - - if (even) { - lastX = lastX + s; - coords[cnt++] = lastX / scale; - even = false; - } else { - lastY = lastY + s; - coords[cnt++] = Tile.SIZE - lastY / scale; - even = true; - } - } - - if (pos != bufferPos + bytes) - throw INVALID_PACKED_SIZE; - - bufferPos = pos; - - // return number of points read - return cnt; - } + static final Logger log = LoggerFactory.getLogger(TileDecoder.class); + + private final static float REF_TILE_SIZE = 4096.0f; + + private static final int TAG_TILE_TAGS = 1; + private static final int TAG_TILE_WAYS = 2; + private static final int TAG_TILE_POLY = 3; + private static final int TAG_TILE_NODES = 4; + private static final int TAG_WAY_TAGS = 11; + private static final int TAG_WAY_INDEX = 12; + private static final int TAG_WAY_COORDS = 13; + private static final int TAG_WAY_LAYER = 21; + private static final int TAG_WAY_NUM_TAGS = 1; + private static final int TAG_WAY_NUM_INDICES = 2; + private static final int TAG_WAY_NUM_COORDS = 3; + + private static final int TAG_NODE_TAGS = 11; + private static final int TAG_NODE_COORDS = 12; + private static final int TAG_NODE_LAYER = 21; + private static final int TAG_NODE_NUM_TAGS = 1; + private static final int TAG_NODE_NUM_COORDS = 2; + + private int MAX_TILE_TAGS = 100; + private Tag[] curTags = new Tag[MAX_TILE_TAGS]; + private int mCurTagCnt; + + private ITileDataSink mSink; + private float mScale; + private Tile mTile; + private final MapElement mElem; + + TileDecoder() { + mElem = new MapElement(); + } + + @Override + public boolean decode(Tile tile, ITileDataSink sink, InputStream is) + throws IOException { + + setInputStream(is); + + mTile = tile; + mSink = sink; + mScale = REF_TILE_SIZE / Tile.SIZE; + return decode(); + } + + private static final int MAX_TAGS_CACHE = 100; + private static Map tagHash = + Collections.synchronizedMap(new LinkedHashMap(MAX_TAGS_CACHE, + 0.75f, + true) { + + private static final long serialVersionUID = 1L; + + //@Override + //protected boolean removeEldestEntry(Entry e) { + //if (size() < MAX_TAGS_CACHE) + //return false; + //return true; + //} + }); + + private boolean decode() throws IOException { + int val; + mCurTagCnt = 0; + + while (hasData() && (val = decodeVarint32()) > 0) { + // read tag and wire type + int tag = (val >> 3); + + switch (tag) { + case TAG_TILE_TAGS: + decodeTileTags(); + break; + + case TAG_TILE_WAYS: + decodeTileWays(false); + break; + + case TAG_TILE_POLY: + decodeTileWays(true); + break; + + case TAG_TILE_NODES: + decodeTileNodes(); + break; + + default: + log.debug("invalid type for tile: " + tag); + return false; + } + } + return true; + } + + private boolean decodeTileTags() throws IOException { + String tagString = decodeString(); + + if (tagString == null || tagString.length() == 0) { + curTags[mCurTagCnt++] = new Tag(Tag.KEY_NAME, "..."); + return false; + } + + Tag tag = tagHash.get(tagString); + + if (tag == null) { + if (tagString.startsWith(Tag.KEY_NAME)) + tag = new Tag(Tag.KEY_NAME, tagString.substring(5), false); + else + tag = Tag.parse(tagString); + + if (tag != null) + tagHash.put(tagString, tag); + } + + if (mCurTagCnt >= MAX_TILE_TAGS) { + MAX_TILE_TAGS = mCurTagCnt + 10; + Tag[] tmp = new Tag[MAX_TILE_TAGS]; + System.arraycopy(curTags, 0, tmp, 0, mCurTagCnt); + curTags = tmp; + } + curTags[mCurTagCnt++] = tag; + + return true; + } + + private boolean decodeTileWays(boolean polygon) throws IOException { + int bytes = decodeVarint32(); + + int end = position() + bytes; + int indexCnt = 0; + int tagCnt = 0; + int coordCnt = 0; + int layer = 5; + + boolean fail = false; + + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >> 3); + + switch (tag) { + case TAG_WAY_TAGS: + if (!decodeWayTags(tagCnt)) + return false; + break; + + case TAG_WAY_INDEX: + decodeWayIndices(indexCnt); + break; + + case TAG_WAY_COORDS: + if (coordCnt == 0) { + log.debug(mTile + " no coordinates"); + } + + mElem.ensurePointSize(coordCnt, false); + int cnt = decodeInterleavedPoints(mElem.points, mScale); + + if (cnt != coordCnt) { + log.debug(mTile + " wrong number of coordintes " + + coordCnt + "/" + cnt); + fail = true; + } + + break; + + case TAG_WAY_LAYER: + layer = decodeVarint32(); + break; + + case TAG_WAY_NUM_TAGS: + tagCnt = decodeVarint32(); + break; + + case TAG_WAY_NUM_INDICES: + indexCnt = decodeVarint32(); + break; + + case TAG_WAY_NUM_COORDS: + coordCnt = decodeVarint32(); + break; + + default: + log.debug("X invalid type for way: " + tag); + } + } + + if (fail || indexCnt == 0 || tagCnt == 0) { + log.debug("failed reading way: bytes:" + bytes + " index:" + //+ (tags != null ? tags.toString() : "...") + " " + + indexCnt + " " + coordCnt + " " + tagCnt); + return false; + } + + // FIXME, remove all tiles from cache then remove this below + //if (layer == 0) + // layer = 5; + mElem.type = polygon ? GeometryType.POLY : GeometryType.LINE; + mElem.setLayer(layer); + mSink.process(mElem); + return true; + } + + private boolean decodeTileNodes() throws IOException { + int bytes = decodeVarint32(); + + int end = position() + bytes; + int tagCnt = 0; + int coordCnt = 0; + byte layer = 0; + + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >> 3); + + switch (tag) { + case TAG_NODE_TAGS: + if (!decodeWayTags(tagCnt)) + return false; + break; + + case TAG_NODE_COORDS: + int cnt = decodeNodeCoordinates(coordCnt, layer); + if (cnt != coordCnt) { + log.debug("X wrong number of coordintes"); + return false; + } + break; + + case TAG_NODE_LAYER: + layer = (byte) decodeVarint32(); + break; + + case TAG_NODE_NUM_TAGS: + tagCnt = decodeVarint32(); + break; + + case TAG_NODE_NUM_COORDS: + coordCnt = decodeVarint32(); + break; + + default: + log.debug("X invalid type for node: " + tag); + } + } + + return true; + } + + private int decodeNodeCoordinates(int numNodes, byte layer) + throws IOException { + int bytes = decodeVarint32(); + + fillBuffer(bytes); + int cnt = 0; + int end = position() + bytes; + // read repeated sint32 + int lastX = 0; + int lastY = 0; + float[] coords = mElem.ensurePointSize(numNodes, false); + + while (position() < end && cnt < numNodes) { + int lon = deZigZag(decodeVarint32()); + int lat = deZigZag(decodeVarint32()); + lastX = lon + lastX; + lastY = lat + lastY; + coords[cnt++] = lastX / mScale; + coords[cnt++] = Tile.SIZE - lastY / mScale; + } + + mElem.index[0] = (short) numNodes; + mElem.type = GeometryType.POINT; + mElem.setLayer(layer); + mSink.process(mElem); + + return cnt; + } + + private boolean decodeWayTags(int tagCnt) throws IOException { + int bytes = decodeVarint32(); + + mElem.tags.clear(); + + int cnt = 0; + int end = position() + bytes; + int max = mCurTagCnt; + + for (; position() < end; cnt++) { + int tagNum = decodeVarint32(); + + if (tagNum < 0 || cnt == tagCnt) { + log.debug("NULL TAG: " + mTile + + " invalid tag:" + tagNum + + " " + tagCnt + "/" + cnt); + continue; + } + + if (tagNum < Tags.MAX) { + mElem.tags.add(Tags.tags[tagNum]); + continue; + } + + tagNum -= Tags.LIMIT; + + if (tagNum >= 0 && tagNum < max) { + mElem.tags.add(curTags[tagNum]); + } else { + log.debug("NULL TAG: " + mTile + + " could find tag:" + + tagNum + " " + tagCnt + + "/" + cnt); + } + } + + if (tagCnt != cnt) { + log.debug("NULL TAG: " + mTile); + return false; + } + + return true; + } + + private int decodeWayIndices(int indexCnt) throws IOException { + mElem.ensureIndexSize(indexCnt, false); + + decodeVarintArray(indexCnt, mElem.index); + + int[] index = mElem.index; + int coordCnt = 0; + + for (int i = 0; i < indexCnt; i++) { + coordCnt += index[i]; + index[i] *= 2; + } + + // set end marker + if (indexCnt < index.length) + index[indexCnt] = -1; + + return coordCnt; + } + + //@Override + protected int decodeInterleavedPoints(float[] coords, float scale) + throws IOException { + + int bytes = decodeVarint32(); + fillBuffer(bytes); + + int cnt = 0; + int lastX = 0; + int lastY = 0; + boolean even = true; + + byte[] buf = buffer; + int pos = bufferPos; + int end = pos + bytes; + int val; + + while (pos < end) { + if (buf[pos] >= 0) { + val = buf[pos++]; + + } else if (buf[pos + 1] >= 0) { + val = (buf[pos++] & 0x7f) + | buf[pos++] << 7; + + } else if (buf[pos + 2] >= 0) { + val = (buf[pos++] & 0x7f) + | (buf[pos++] & 0x7f) << 7 + | (buf[pos++]) << 14; + + } else if (buf[pos + 3] >= 0) { + val = (buf[pos++] & 0x7f) + | (buf[pos++] & 0x7f) << 7 + | (buf[pos++] & 0x7f) << 14 + | (buf[pos++]) << 21; + + } else { + val = (buf[pos++] & 0x7f) + | (buf[pos++] & 0x7f) << 7 + | (buf[pos++] & 0x7f) << 14 + | (buf[pos++] & 0x7f) << 21 + | (buf[pos]) << 28; + + if (buf[pos++] < 0) + throw INVALID_VARINT; + } + + // zigzag decoding + int s = ((val >>> 1) ^ -(val & 1)); + + if (even) { + lastX = lastX + s; + coords[cnt++] = lastX / scale; + even = false; + } else { + lastY = lastY + s; + coords[cnt++] = Tile.SIZE - lastY / scale; + even = true; + } + } + + if (pos != bufferPos + bytes) + throw INVALID_PACKED_SIZE; + + bufferPos = pos; + + // return number of points read + return cnt; + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/oscimap2/OSciMap2TileSource.java b/vtm-extras/src/org/oscim/tiling/source/oscimap2/OSciMap2TileSource.java index cfaf7142..c5f4e286 100644 --- a/vtm-extras/src/org/oscim/tiling/source/oscimap2/OSciMap2TileSource.java +++ b/vtm-extras/src/org/oscim/tiling/source/oscimap2/OSciMap2TileSource.java @@ -16,10 +16,6 @@ */ package org.oscim.tiling.source.oscimap2; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.Tag; @@ -33,295 +29,299 @@ import org.oscim.tiling.source.UrlTileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + public class OSciMap2TileSource extends UrlTileSource { - public OSciMap2TileSource(String url) { - super(url, "/{Z}/{X}/{Y}.osmtile"); - } - - @Override - public ITileDataSource getDataSource() { - return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); - } + public OSciMap2TileSource(String url) { + super(url, "/{Z}/{X}/{Y}.osmtile"); + } + + @Override + public ITileDataSource getDataSource() { + return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); + } - static class TileDecoder extends PbfDecoder { - static final Logger log = LoggerFactory.getLogger(TileDecoder.class); - private static final int TAG_TILE_NUM_TAGS = 1; - private static final int TAG_TILE_TAG_KEYS = 2; - private static final int TAG_TILE_TAG_VALUES = 3; + static class TileDecoder extends PbfDecoder { + static final Logger log = LoggerFactory.getLogger(TileDecoder.class); + private static final int TAG_TILE_NUM_TAGS = 1; + private static final int TAG_TILE_TAG_KEYS = 2; + private static final int TAG_TILE_TAG_VALUES = 3; - private static final int TAG_TILE_LINE = 11; - private static final int TAG_TILE_POLY = 12; - private static final int TAG_TILE_POINT = 13; - // private static final int TAG_TILE_LABEL = 21; - // private static final int TAG_TILE_WATER = 31; + private static final int TAG_TILE_LINE = 11; + private static final int TAG_TILE_POLY = 12; + private static final int TAG_TILE_POINT = 13; + // private static final int TAG_TILE_LABEL = 21; + // private static final int TAG_TILE_WATER = 31; - private static final int TAG_ELEM_NUM_INDICES = 1; - private static final int TAG_ELEM_TAGS = 11; - private static final int TAG_ELEM_INDEX = 12; - private static final int TAG_ELEM_COORDS = 13; - private static final int TAG_ELEM_LAYER = 21; - private static final int TAG_ELEM_HEIGHT = 31; - private static final int TAG_ELEM_MIN_HEIGHT = 32; - private static final int TAG_ELEM_PRIORITY = 41; + private static final int TAG_ELEM_NUM_INDICES = 1; + private static final int TAG_ELEM_TAGS = 11; + private static final int TAG_ELEM_INDEX = 12; + private static final int TAG_ELEM_COORDS = 13; + private static final int TAG_ELEM_LAYER = 21; + private static final int TAG_ELEM_HEIGHT = 31; + private static final int TAG_ELEM_MIN_HEIGHT = 32; + private static final int TAG_ELEM_PRIORITY = 41; - private int[] mSArray; - private final TagSet mTileTags; - private final MapElement mElem; + private int[] mSArray; + private final TagSet mTileTags; + private final MapElement mElem; - private Tile mTile; - - private ITileDataSink mMapDataSink; - - // scale coordinates to tile size - private final static float REF_TILE_SIZE = 4096.0f; - private float mScale; + private Tile mTile; + + private ITileDataSink mMapDataSink; + + // scale coordinates to tile size + private final static float REF_TILE_SIZE = 4096.0f; + private float mScale; - TileDecoder() { - mElem = new MapElement(); - mTileTags = new TagSet(20); + TileDecoder() { + mElem = new MapElement(); + mTileTags = new TagSet(20); - // temp array for decoding shorts - mSArray = new int[100]; - } + // temp array for decoding shorts + mSArray = new int[100]; + } - @Override - public boolean decode(Tile tile, ITileDataSink sink, InputStream is) - throws IOException { + @Override + public boolean decode(Tile tile, ITileDataSink sink, InputStream is) + throws IOException { - readUnsignedInt(is, buffer); + readUnsignedInt(is, buffer); - setInputStream(is); + setInputStream(is); - mTile = tile; - mMapDataSink = sink; + mTile = tile; + mMapDataSink = sink; - mScale = REF_TILE_SIZE / Tile.SIZE; + mScale = REF_TILE_SIZE / Tile.SIZE; - mTileTags.clear(); + mTileTags.clear(); - int val; - int numTags = 0; + int val; + int numTags = 0; - while (hasData() && (val = decodeVarint32()) > 0) { - // read tag and wire type - int tag = (val >> 3); + while (hasData() && (val = decodeVarint32()) > 0) { + // read tag and wire type + int tag = (val >> 3); - switch (tag) { - case TAG_TILE_NUM_TAGS: - numTags = decodeVarint32(); - break; + switch (tag) { + case TAG_TILE_NUM_TAGS: + numTags = decodeVarint32(); + break; - case TAG_TILE_TAG_KEYS: - int len = numTags; - if (mSArray.length < len) - mSArray = new int[len]; + case TAG_TILE_TAG_KEYS: + int len = numTags; + if (mSArray.length < len) + mSArray = new int[len]; - decodeVarintArray(numTags, mSArray); - break; + decodeVarintArray(numTags, mSArray); + break; - case TAG_TILE_TAG_VALUES: - // this wastes one byte, as there is no packed string... - decodeTileTags(); - break; + case TAG_TILE_TAG_VALUES: + // this wastes one byte, as there is no packed string... + decodeTileTags(); + break; - case TAG_TILE_LINE: - case TAG_TILE_POLY: - case TAG_TILE_POINT: - decodeTileElement(tag); - break; - - default: - log.debug(mTile + " invalid type for tile: " + tag); - return false; - } - } - return true; - } + case TAG_TILE_LINE: + case TAG_TILE_POLY: + case TAG_TILE_POINT: + decodeTileElement(tag); + break; + + default: + log.debug(mTile + " invalid type for tile: " + tag); + return false; + } + } + return true; + } - private boolean decodeTileTags() throws IOException { - String tagString = decodeString(); + private boolean decodeTileTags() throws IOException { + String tagString = decodeString(); - int curTag = mTileTags.numTags; + int curTag = mTileTags.numTags; - String key = Tags.keys[mSArray[curTag]]; - Tag tag; + String key = Tags.keys[mSArray[curTag]]; + Tag tag; - if (key == Tag.KEY_NAME) - tag = new Tag(key, tagString, false); - else - tag = new Tag(key, tagString, true); - if (debug) - log.debug(mTile + " add tag: " + curTag + " " + tag); + if (key == Tag.KEY_NAME) + tag = new Tag(key, tagString, false); + else + tag = new Tag(key, tagString, true); + if (debug) + log.debug(mTile + " add tag: " + curTag + " " + tag); - mTileTags.add(tag); + mTileTags.add(tag); - return true; - } + return true; + } - private int decodeWayIndices(int indexCnt) throws IOException { - mElem.ensureIndexSize(indexCnt, false); - decodeVarintArray(indexCnt, mElem.index); + private int decodeWayIndices(int indexCnt) throws IOException { + mElem.ensureIndexSize(indexCnt, false); + decodeVarintArray(indexCnt, mElem.index); - int[] index = mElem.index; - int coordCnt = 0; + int[] index = mElem.index; + int coordCnt = 0; - for (int i = 0; i < indexCnt; i++) { - coordCnt += index[i]; - index[i] *= 2; - } - // set end marker - if (indexCnt < index.length) - index[indexCnt] = -1; - - return coordCnt; - } - - private boolean decodeTileElement(int type) throws IOException { - - int bytes = decodeVarint32(); - short[] index = null; - - int end = position() + bytes; - int indexCnt = 1; - - boolean fail = false; - - int coordCnt = 0; - if (type == TAG_TILE_POINT) { - coordCnt = 1; - mElem.index[0] = 2; - } - - mElem.layer = 5; - //mElem.height = 0; - //mElem.minHeight = 0; - - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >> 3); - - switch (tag) { - case TAG_ELEM_TAGS: - if (!decodeElementTags()) - return false; - break; - - case TAG_ELEM_NUM_INDICES: - indexCnt = decodeVarint32(); - break; - - case TAG_ELEM_INDEX: - coordCnt = decodeWayIndices(indexCnt); - break; - - case TAG_ELEM_COORDS: - if (coordCnt == 0) { - log.debug(mTile + " no coordinates"); - } - - mElem.ensurePointSize(coordCnt, false); - int cnt = decodeInterleavedPoints(mElem, mScale); - - if (cnt != coordCnt) { - log.debug(mTile + " wrong number of coordintes"); - fail = true; - } - break; - - case TAG_ELEM_LAYER: - mElem.layer = decodeVarint32(); - break; - - case TAG_ELEM_HEIGHT: - //mElem.height = - decodeVarint32(); - break; - - case TAG_ELEM_MIN_HEIGHT: - //mElem.minHeight = - decodeVarint32(); - break; - - case TAG_ELEM_PRIORITY: - //mElem.priority = - decodeVarint32(); - break; - - default: - log.debug(mTile + " invalid type for way: " + tag); - } - } - - if (fail || indexCnt == 0) { - log.debug(mTile + " failed reading way: bytes:" + bytes + " index:" - + (Arrays.toString(index)) + " tag:" - + (mElem.tags.numTags > 0 ? Arrays.deepToString(mElem.tags.tags) : "null") - + " " + indexCnt + " " + coordCnt); - return false; - } - - switch (type) { - case TAG_TILE_LINE: - mElem.type = GeometryType.LINE; - break; - case TAG_TILE_POLY: - mElem.type = GeometryType.POLY; - break; - case TAG_TILE_POINT: - mElem.type = GeometryType.POINT; - break; - } - - mMapDataSink.process(mElem); - - return true; - } - - private boolean decodeElementTags() throws IOException { - int bytes = decodeVarint32(); - - mElem.tags.clear(); - - int cnt = 0; - int end = position() + bytes; - int max = mTileTags.numTags - 1; - - for (; position() < end; cnt++) { - int tagNum = decodeVarint32(); - - if (tagNum < 0) { - log.debug("NULL TAG: " + mTile - + " invalid tag:" - + tagNum + " " + cnt); - return false; - } - - if (tagNum < Tags.MAX) { - mElem.tags.add(Tags.tags[tagNum]); - continue; - } - tagNum -= Tags.LIMIT; - - if (tagNum < 0 || tagNum > max) { - log.debug("NULL TAG: " + mTile - + " could not find tag:" - + tagNum + " " + cnt); - return false; - } - - mElem.tags.add(mTileTags.tags[tagNum]); - } - - if (cnt == 0) { - log.debug("got no TAG!"); - return false; - } - return true; - } - } + for (int i = 0; i < indexCnt; i++) { + coordCnt += index[i]; + index[i] *= 2; + } + // set end marker + if (indexCnt < index.length) + index[indexCnt] = -1; + + return coordCnt; + } + + private boolean decodeTileElement(int type) throws IOException { + + int bytes = decodeVarint32(); + short[] index = null; + + int end = position() + bytes; + int indexCnt = 1; + + boolean fail = false; + + int coordCnt = 0; + if (type == TAG_TILE_POINT) { + coordCnt = 1; + mElem.index[0] = 2; + } + + mElem.layer = 5; + //mElem.height = 0; + //mElem.minHeight = 0; + + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >> 3); + + switch (tag) { + case TAG_ELEM_TAGS: + if (!decodeElementTags()) + return false; + break; + + case TAG_ELEM_NUM_INDICES: + indexCnt = decodeVarint32(); + break; + + case TAG_ELEM_INDEX: + coordCnt = decodeWayIndices(indexCnt); + break; + + case TAG_ELEM_COORDS: + if (coordCnt == 0) { + log.debug(mTile + " no coordinates"); + } + + mElem.ensurePointSize(coordCnt, false); + int cnt = decodeInterleavedPoints(mElem, mScale); + + if (cnt != coordCnt) { + log.debug(mTile + " wrong number of coordintes"); + fail = true; + } + break; + + case TAG_ELEM_LAYER: + mElem.layer = decodeVarint32(); + break; + + case TAG_ELEM_HEIGHT: + //mElem.height = + decodeVarint32(); + break; + + case TAG_ELEM_MIN_HEIGHT: + //mElem.minHeight = + decodeVarint32(); + break; + + case TAG_ELEM_PRIORITY: + //mElem.priority = + decodeVarint32(); + break; + + default: + log.debug(mTile + " invalid type for way: " + tag); + } + } + + if (fail || indexCnt == 0) { + log.debug(mTile + " failed reading way: bytes:" + bytes + " index:" + + (Arrays.toString(index)) + " tag:" + + (mElem.tags.numTags > 0 ? Arrays.deepToString(mElem.tags.tags) : "null") + + " " + indexCnt + " " + coordCnt); + return false; + } + + switch (type) { + case TAG_TILE_LINE: + mElem.type = GeometryType.LINE; + break; + case TAG_TILE_POLY: + mElem.type = GeometryType.POLY; + break; + case TAG_TILE_POINT: + mElem.type = GeometryType.POINT; + break; + } + + mMapDataSink.process(mElem); + + return true; + } + + private boolean decodeElementTags() throws IOException { + int bytes = decodeVarint32(); + + mElem.tags.clear(); + + int cnt = 0; + int end = position() + bytes; + int max = mTileTags.numTags - 1; + + for (; position() < end; cnt++) { + int tagNum = decodeVarint32(); + + if (tagNum < 0) { + log.debug("NULL TAG: " + mTile + + " invalid tag:" + + tagNum + " " + cnt); + return false; + } + + if (tagNum < Tags.MAX) { + mElem.tags.add(Tags.tags[tagNum]); + continue; + } + tagNum -= Tags.LIMIT; + + if (tagNum < 0 || tagNum > max) { + log.debug("NULL TAG: " + mTile + + " could not find tag:" + + tagNum + " " + cnt); + return false; + } + + mElem.tags.add(mTileTags.tags[tagNum]); + } + + if (cnt == 0) { + log.debug("got no TAG!"); + return false; + } + return true; + } + } } diff --git a/vtm-extras/src/org/oscim/tiling/source/oscimap2/Tags.java b/vtm-extras/src/org/oscim/tiling/source/oscimap2/Tags.java index 43fe8a82..f371a1e2 100644 --- a/vtm-extras/src/org/oscim/tiling/source/oscimap2/Tags.java +++ b/vtm-extras/src/org/oscim/tiling/source/oscimap2/Tags.java @@ -19,1266 +19,1266 @@ package org.oscim.tiling.source.oscimap2; import org.oscim.core.Tag; public class Tags { - public final static int MAX = 628; - public final static int LIMIT = 1024; + public final static int MAX = 628; + public final static int LIMIT = 1024; - private static final String s_limited = "limited"; - private static final String s_chain = "chain"; - private static final String s_viaduct = "viaduct"; - private static final String s_department_store = "department_store"; - private static final String s_factory = "factory"; - private static final String s_recreation_ground = "recreation_ground"; - private static final String s_nature_reserve = "nature_reserve"; - private static final String s_apartment = "apartment"; - private static final String s_preserved = "preserved"; - private static final String s_stationery = "stationery"; - private static final String s_gravel = "gravel"; - private static final String s_hill = "hill"; - private static final String s_water_well = "water_well"; - private static final String s_garden = "garden"; - private static final String s_permissive = "permissive"; - private static final String s_deli = "deli"; - private static final String s_industrial_retail = "industrial;retail"; - private static final String s_city_wall = "city_wall"; - private static final String s_artwork = "artwork"; - private static final String s_chapel = "chapel"; - private static final String s_school = "school"; - private static final String s_caravan_site = "caravan_site"; - private static final String s_reservoir_watershed = "reservoir_watershed"; - private static final String s_local_authority = "local_authority"; - private static final String s_miniature_golf = "miniature_golf"; - private static final String s_bus_stop = "bus_stop"; - private static final String s_convenience = "convenience"; - private static final String s_kissing_gate = "kissing_gate"; - private static final String s_subway = "subway"; - private static final String s_cutline = "cutline"; - private static final String s_disused = "disused"; - private static final String s_clothes = "clothes"; - private static final String s_bicycle = "bicycle"; - private static final String s_meadow = "meadow"; - private static final String s_fence = "fence"; - private static final String s_video = "video"; - private static final String s_monorail = "monorail"; - private static final String s_clock = "clock"; - private static final String s_dirt = "dirt"; - private static final String s_border_control = "border_control"; - private static final String s_access = "access"; - private static final String s_public = "public"; - private static final String s_fast_food = "fast_food"; - private static final String s_transportation = "transportation"; - private static final String s_commercial = "commercial"; - private static final String s_water = "water"; - private static final String s_beacon = "beacon"; - private static final String s_trunk = "trunk"; - private static final String s_path = "path"; - private static final String s_bicycle_rental = "bicycle_rental"; - private static final String s_miniature = "miniature"; - private static final String s_car_parts = "car_parts"; - private static final String s_light_rail = "light_rail"; - private static final String s_military = "military"; - private static final String s_bog = "bog"; - private static final String s_hiking = "hiking"; - private static final String s_lift_gate = "lift_gate"; - private static final String s_private = "private"; - private static final String s_county = "county"; - private static final String s_secondary_link = "secondary_link"; - private static final String s_marker = "marker"; - private static final String s_islet = "islet"; - private static final String s_holding_position = "holding_position"; - private static final String s_tertiary = "tertiary"; - private static final String s_water_park = "water_park"; - private static final String s_stream = "stream"; - private static final String s_hospital = "hospital"; - private static final String s_destination = "destination"; - private static final String s_MDF = "MDF"; - private static final String s_sports = "sports"; - private static final String s_vineyard = "vineyard"; - private static final String s_music = "music"; - private static final String s_6 = "6"; - private static final String s_entrance = "entrance"; - private static final String s_beauty = "beauty"; - private static final String s_give_way = "give_way"; - private static final String s_kiosk = "kiosk"; - private static final String s_stone = "stone"; - private static final String s_grass_paver = "grass_paver"; - private static final String s_deciduous = "deciduous"; - private static final String s_train = "train"; - private static final String s_organic = "organic"; - private static final String s_farmyard = "farmyard"; - private static final String s_riverbank = "riverbank"; - private static final String s_doityourself = "doityourself"; - private static final String s_town = "town"; - private static final String s_dog_park = "dog_park"; - private static final String s_village_green = "village_green"; - private static final String s_tunnel = "tunnel"; - private static final String s_car = "car"; - private static final String s_roof = "roof"; - private static final String s_mall = "mall"; - private static final String s_ferry_terminal = "ferry_terminal"; - private static final String s_cave_entrance = "cave_entrance"; - private static final String s_detached = "detached"; - private static final String s_concrete_plates = "concrete:plates"; - private static final String s_public_building = "public_building"; - private static final String s_buffer_stop = "buffer_stop"; - private static final String s_lock = "lock"; - private static final String s_dolphin = "dolphin"; - private static final String s_taxiway = "taxiway"; - private static final String s_hunting_stand = "hunting_stand"; - private static final String s_estate_agent = "estate_agent"; - private static final String s_station = "station"; - private static final String s_car_repair = "car_repair"; - private static final String s_dyke = "dyke"; - private static final String s_hangar = "hangar"; - private static final String s_information = "information"; - private static final String s_1 = "1"; - private static final String s_forest = "forest"; - private static final String s_gate = "gate"; - private static final String s_beach = "beach"; - private static final String s_laundry = "laundry"; - private static final String s_speed_camera = "speed_camera"; - private static final String s_staircase = "staircase"; - private static final String s_farm = "farm"; - private static final String s_stop = "stop"; - private static final String s_bump_gate = "bump_gate"; - private static final String s_motorway = "motorway"; - private static final String s_water_tower = "water_tower"; - private static final String s_abutters = "abutters"; - private static final String s_driving_school = "driving_school"; - private static final String s_natural = "natural"; - private static final String s_orchard = "orchard"; - private static final String s_wheelchair = "wheelchair"; - private static final String s_swimming_pool = "swimming_pool"; - private static final String s_switch = "switch"; - private static final String s_block = "block"; - private static final String s_turnstile = "turnstile"; - private static final String s_camp_site = "camp_site"; - private static final String s_shoes = "shoes"; - private static final String s_reservoir = "reservoir"; - private static final String s_pebblestone = "pebblestone"; - private static final String s_stile = "stile"; - private static final String s_embassy = "embassy"; - private static final String s_postal_code = "postal_code"; - private static final String s_retaining_wall = "retaining_wall"; - private static final String s_bridleway = "bridleway"; - private static final String s_pitch = "pitch"; - private static final String s_agricultural = "agricultural"; - private static final String s_post_office = "post_office"; - private static final String s_parking_fuel = "parking;fuel"; - private static final String s_bureau_de_change = "bureau_de_change"; - private static final String s_mini_roundabout = "mini_roundabout"; - private static final String s_hov = "hov"; - private static final String s_police = "police"; - private static final String s_courthouse = "courthouse"; - private static final String s_raceway = "raceway"; - private static final String s_kindergarten = "kindergarten"; - private static final String s_attraction = "attraction"; - private static final String s_marsh = "marsh"; - private static final String s_reservoir_covered = "reservoir_covered"; - private static final String s_petroleum_well = "petroleum_well"; - private static final String s_silo = "silo"; - private static final String s_toys = "toys"; - private static final String s_apron = "apron"; - private static final String s_halt = "halt"; - private static final String s_dam = "dam"; - private static final String s_golf_course = "golf_course"; - private static final String s_detour = "detour"; - private static final String s_tree_row = "tree_row"; - private static final String s_copyshop = "copyshop"; - private static final String s_milestone = "milestone"; - private static final String s_foot = "foot"; - private static final String s_tourism = "tourism"; - private static final String s_bank = "bank"; - private static final String s_dry_cleaning = "dry_cleaning"; - private static final String s_tram = "tram"; - private static final String s_trolleybus = "trolleybus"; - private static final String s_university = "university"; - private static final String s_hampshire_gate = "hampshire_gate"; - private static final String s_embankment = "embankment"; - private static final String s_rock = "rock"; - private static final String s_crossing = "crossing"; - private static final String s_volcano = "volcano"; - private static final String s_greengrocer = "greengrocer"; - private static final String s_kerb = "kerb"; - private static final String s_waste_disposal = "waste_disposal"; - private static final String s_grave_yard = "grave_yard"; - private static final String s_coniferous = "coniferous"; - private static final String s_house = "house"; - private static final String s_books = "books"; - private static final String s_neighbourhood = "neighbourhood"; - private static final String s_hostel = "hostel"; - private static final String s_alcohol = "alcohol"; - private static final String s_restricted = "restricted"; - private static final String s_motel = "motel"; - private static final String s_sand = "sand"; - private static final String s_fishmonger = "fishmonger"; - private static final String s_fountain = "fountain"; - private static final String s_playground = "playground"; - private static final String s_7 = "7"; - private static final String s_parking_aisle = "parking_aisle"; - private static final String s_protected_area = "protected_area"; - private static final String s_electronics = "electronics"; - private static final String s_Paved = "Paved"; - private static final String s_highway = "highway"; - private static final String s_fine_gravel = "fine_gravel"; - private static final String s_barrier = "barrier"; - private static final String s_hairdresser = "hairdresser"; - private static final String s_post_box = "post_box"; - private static final String s_pub = "pub"; - private static final String s_coastline = "coastline"; - private static final String s_marina = "marina"; - private static final String s_reedbed = "reedbed"; - private static final String s_biergarten = "biergarten"; - private static final String s_dismantled = "dismantled"; - private static final String s_farmland = "farmland"; - private static final String s_yard = "yard"; - private static final String s_route = "route"; - private static final String s_atm = "atm"; - private static final String s_place = "place"; - private static final String s_bus_station = "bus_station"; - private static final String s_retail = "retail"; - private static final String s_industrial = "industrial"; - private static final String s_municipality = "municipality"; - private static final String s_primary = "primary"; - private static final String s_nursing_home = "nursing_home"; - private static final String s_florist = "florist"; - private static final String s_ditch = "ditch"; - private static final String s_national_park = "national_park"; - private static final String s_city = "city"; - private static final String s_confectionery = "confectionery"; - private static final String s_service = "service"; - private static final String s_unknown = "unknown"; - private static final String s_cycle_barrier = "cycle_barrier"; - private static final String s_elevator = "elevator"; - private static final String s_2 = "2"; - private static final String s_car_rental = "car_rental"; - private static final String s_flagpole = "flagpole"; - private static final String s_cabin = "cabin"; - private static final String s_paved = "paved"; - private static final String s_guest_house = "guest_house"; - private static final String s_mobile_phone = "mobile_phone"; - private static final String s_lot = "lot"; - private static final String s_quarry = "quarry"; - private static final String s_train_station = "train_station"; - private static final String s_hotel = "hotel"; - private static final String s_park = "park"; - private static final String s_hut = "hut"; - private static final String s_dentist = "dentist"; - private static final String s_doctors = "doctors"; - private static final String s_greenhouse = "greenhouse"; - private static final String s_11 = "11"; - private static final String s_10 = "10"; - private static final String s_theme_park = "theme_park"; - private static final String s_tree = "tree"; - private static final String s_shower = "shower"; - private static final String s_siding = "siding"; - private static final String s_aeroway = "aeroway"; - private static final String s_emergency_access_point = "emergency_access_point"; - private static final String s_watermill = "watermill"; - private static final String s_college = "college"; - private static final String s_landuse = "landuse"; - private static final String s_tracktype = "tracktype"; - private static final String s_ferry = "ferry"; - private static final String s_bridge = "bridge"; - private static final String s_vacant = "vacant"; - private static final String s_cattle_grid = "cattle_grid"; - private static final String s_brownfield = "brownfield"; - private static final String s_allotments = "allotments"; - private static final String s_alley = "alley"; - private static final String s_pedestrian = "pedestrian"; - private static final String s_borough = "borough"; - private static final String s_bare_rock = "bare_rock"; - private static final String s_motorcycle = "motorcycle"; - private static final String s_bakery = "bakery"; - private static final String s_zoo = "zoo"; - private static final String s_scree = "scree"; - private static final String s_fire_station = "fire_station"; - private static final String s_theatre = "theatre"; - private static final String s_track = "track"; - private static final String s_reinforced_slope = "reinforced_slope"; - private static final String s_slipway = "slipway"; - private static final String s_mangrove = "mangrove"; - private static final String s_aerodrome = "aerodrome"; - private static final String s_byway = "byway"; - private static final String s_metal = "metal"; - private static final String s_swamp = "swamp"; - private static final String s_construction = "construction"; - private static final String s_grassland = "grassland"; - private static final String s_shop = "shop"; - private static final String s_soakhole = "soakhole"; - private static final String s_asphalt = "asphalt"; - private static final String s_social_facility = "social_facility"; - private static final String s_isolated_dwelling = "isolated_dwelling"; - private static final String s_hamlet = "hamlet"; - private static final String s_picnic_table = "picnic_table"; - private static final String s_artificial = "artificial"; - private static final String s_earth = "earth"; - private static final String s_grit_bin = "grit_bin"; - private static final String s_ground = "ground"; - private static final String s_groyne = "groyne"; - private static final String s_office = "office"; - private static final String s_state = "state"; - private static final String s_terminal = "terminal"; - private static final String s_wood = "wood"; - private static final String s_fuel = "fuel"; - private static final String s_8 = "8"; - private static final String s_garden_centre = "garden_centre"; - private static final String s_horse_riding = "horse_riding"; - private static final String s_viewpoint = "viewpoint"; - private static final String s_designated = "designated"; - private static final String s_leisure = "leisure"; - private static final String s_waste_basket = "waste_basket"; - private static final String s_hifi = "hifi"; - private static final String s_hedge = "hedge"; - private static final String s_spur = "spur"; - private static final String s_chimney = "chimney"; - private static final String s_secondary = "secondary"; - private static final String s_rest_area = "rest_area"; - private static final String s_bar = "bar"; - private static final String s_bay = "bay"; - private static final String s_common = "common"; - private static final String s_river = "river"; - private static final String s_ruins = "ruins"; - private static final String s_terrace = "terrace"; - private static final String s_art = "art"; - private static final String s_residental = "residental"; - private static final String s_newsagent = "newsagent"; - private static final String s_turntable = "turntable"; - private static final String s_computer = "computer"; - private static final String s_wetland = "wetland"; - private static final String s_driveway = "driveway"; - private static final String s_parking = "parking"; - private static final String s_compacted = "compacted"; - private static final String s_barn = "barn"; - private static final String s_alpine_hut = "alpine_hut"; - private static final String s_wire_fence = "wire_fence"; - private static final String s_unpaved = "unpaved"; - private static final String s_dormitory = "dormitory"; - private static final String s_mud = "mud"; - private static final String s_3 = "3"; - private static final String s_semi = "semi"; - private static final String s_boundary = "boundary"; - private static final String s_field_boundary = "field_boundary"; - private static final String s_beverages = "beverages"; - private static final String s_supermarket = "supermarket"; - private static final String s_store = "store"; - private static final String s_restaurant = "restaurant"; - private static final String s_region = "region"; - private static final String s_variety_store = "variety_store"; - private static final String s_saltmarsh = "saltmarsh"; - private static final String s_landform = "landform"; - private static final String s_helipad = "helipad"; - private static final String s_railway = "railway"; - private static final String s_greenhouse_horticulture = "greenhouse_horticulture"; - private static final String s_wall = "wall"; - private static final String s_recycling = "recycling"; - private static final String s_passing_place = "passing_place"; - private static final String s_church = "church"; - private static final String s_pharmacy = "pharmacy"; - private static final String s_lighthouse = "lighthouse"; - private static final String s_platform = "platform"; - private static final String s_cinema = "cinema"; - private static final String s_political = "political"; - private static final String s_stadium = "stadium"; - private static final String s_basin = "basin"; - private static final String s_gasometer = "gasometer"; - private static final String s_bicycle_parking = "bicycle_parking"; - private static final String s_bbq = "bbq"; - private static final String s_incline_steep = "incline_steep"; - private static final String s_drinking_water = "drinking_water"; - private static final String s_living_street = "living_street"; - private static final String s_chalet = "chalet"; - private static final String s_narrow_gauge = "narrow_gauge"; - private static final String s_prison = "prison"; - private static final String s_mine = "mine"; - private static final String s_level_crossing = "level_crossing"; - private static final String s_water_works = "water_works"; - private static final String s_street_lamp = "street_lamp"; - private static final String s_main = "main"; - private static final String s_tank = "tank"; - private static final String s_abandoned = "abandoned"; - private static final String s_ski = "ski"; - private static final String s_runway = "runway"; - private static final String s_parking_space = "parking_space"; - private static final String s_dirt_sand = "dirt/sand"; - private static final String s_salt_pond = "salt_pond"; - private static final String s_hedge_bank = "hedge_bank"; - private static final String s_amenity = "amenity"; - private static final String s_telephone = "telephone"; - private static final String s_surface = "surface"; - private static final String s_travel_agency = "travel_agency"; - private static final String s_hardware = "hardware"; - private static final String s_wastewater_plant = "wastewater_plant"; - private static final String s_waterway = "waterway"; - private static final String s_butcher = "butcher"; - private static final String s_surveillance = "surveillance"; - private static final String s_Dirt_Sand = "Dirt/Sand"; - private static final String s_9 = "9"; - private static final String s_windmill = "windmill"; - private static final String s_picnic_site = "picnic_site"; - private static final String s_rail = "rail"; - private static final String s_cement = "cement"; - private static final String s_sauna = "sauna"; - private static final String s_suburb = "suburb"; - private static final String s_waterfall = "waterfall"; - private static final String s_bunker = "bunker"; - private static final String s_ice_cream = "ice_cream"; - private static final String s_culvert = "culvert"; - private static final String s_drain = "drain"; - private static final String s_dock = "dock"; - private static final String s_glasshouse = "glasshouse"; - private static final String s_no = "no"; - private static final String s_well = "well"; - private static final String s_wet_meadow = "wet_meadow"; - private static final String s_concrete = "concrete"; - private static final String s_dismount = "dismount"; - private static final String s_vending_machine = "vending_machine"; - private static final String s_oneway = "oneway"; - private static final String s_taxi = "taxi"; - private static final String s_outdoor = "outdoor"; - private static final String s_proposed = "proposed"; - private static final String s_sally_port = "sally_port"; - private static final String s_photo = "photo"; - private static final String s_plant_nursery = "plant_nursery"; - private static final String s_clinic = "clinic"; - private static final String s_fishing = "fishing"; - private static final String s_yes = "yes"; - private static final String s_turning_circle = "turning_circle"; - private static final String s_toilets = "toilets"; - private static final String s_guard_rail = "guard_rail"; - private static final String s_townhall = "townhall"; - private static final String s_community_centre = "community_centre"; - private static final String s_residential = "residential"; - private static final String s_cemetery = "cemetery"; - private static final String s_survey_point = "survey_point"; - private static final String s_bench = "bench"; - private static final String s_4 = "4"; - private static final String s_bollard = "bollard"; - private static final String s_sports_centre = "sports_centre"; - private static final String s_paving_stones_30 = "paving_stones:30"; - private static final String s_administrative = "administrative"; - private static final String s_Building = "Building"; - private static final String s_customers = "customers"; - private static final String s_emergency = "emergency"; - private static final String s_motorway_junction = "motorway_junction"; - private static final String s_grade1 = "grade1"; - private static final String s_grade3 = "grade3"; - private static final String s_grade2 = "grade2"; - private static final String s_grade5 = "grade5"; - private static final String s_grade4 = "grade4"; - private static final String s_lock_gate = "lock_gate"; - private static final String s_furniture = "furniture"; - private static final String s_place_of_worship = "place_of_worship"; - private static final String s_optician = "optician"; - private static final String s_gift = "gift"; - private static final String s_parking_entrance = "parking_entrance"; - private static final String s_garage = "garage"; - private static final String s_tram_stop = "tram_stop"; - private static final String s_steps = "steps"; - private static final String s_tower = "tower"; - private static final String s_works = "works"; - private static final String s_shed = "shed"; - private static final String s_car_sharing = "car_sharing"; - private static final String s_apartments = "apartments"; - private static final String s_spring = "spring"; - private static final String s_village = "village"; - private static final String s_library = "library"; - private static final String s_emergency_access = "emergency_access"; - private static final String s_home = "home"; - private static final String s_farm_auxiliary = "farm_auxiliary"; - private static final String s_primary_link = "primary_link"; - private static final String s_toll_booth = "toll_booth"; - private static final String s_jewelry = "jewelry"; - private static final String s_pet = "pet"; - private static final String s_veterinary = "veterinary"; - private static final String s_man_made = "man_made"; - private static final String s_motorway_link = "motorway_link"; - private static final String s_offices = "offices"; - private static final String s_power = "power"; - private static final String s_weir = "weir"; - private static final String s_unsurfaced = "unsurfaced"; - private static final String s_tertiary_link = "tertiary_link"; - private static final String s_trunk_link = "trunk_link"; - private static final String s_tyres = "tyres"; - private static final String s_paving_stones = "paving_stones"; - private static final String s_pipeline = "pipeline"; - private static final String s_census = "census"; - private static final String s_incline = "incline"; - private static final String s_footway = "footway"; - private static final String s_drive_through = "drive-through"; - private static final String s_island = "island"; - private static final String s_monitoring_station = "monitoring_station"; - private static final String s_nightclub = "nightclub"; - private static final String s_unclassified = "unclassified"; - private static final String s_aquaculture = "aquaculture"; - private static final String s_mixed = "mixed"; - private static final String s_road = "road"; - private static final String s_greenfield = "greenfield"; - private static final String s_breakwater = "breakwater"; - private static final String s_services = "services"; - private static final String s_railway_crossing = "railway_crossing"; - private static final String s_residentiel1 = "residentiel1"; - private static final String s_canal = "canal"; - private static final String s__1 = "-1"; - private static final String s_ridge = "ridge"; - private static final String s_fabric = "fabric"; - private static final String s_museum = "museum"; - private static final String s_communications_tower = "communications_tower"; - private static final String s_semi_detached = "semi-detached"; - private static final String s_conservation = "conservation"; - private static final String s_way = "way"; - private static final String s_wood_fence = "wood_fence"; - private static final String s_manufacture = "manufacture"; - private static final String s_admin_level = "admin_level"; - private static final String s_building_concrete = "building_concrete"; - private static final String s_bus = "bus"; - private static final String s_collapsed = "collapsed"; - private static final String s_ford = "ford"; - private static final String s_delivery = "delivery"; - private static final String s_garages = "garages"; - private static final String s_funeral_directors = "funeral_directors"; - private static final String s_land = "land"; - private static final String s_interlock = "interlock"; - private static final String s_reef = "reef"; - private static final String s_crane = "crane"; - private static final String s_true = "true"; - private static final String s_storage_tank = "storage_tank"; - private static final String s_official = "official"; - private static final String s_subway_entrance = "subway_entrance"; - private static final String s_mtb = "mtb"; - private static final String s_grass = "grass"; - private static final String s_marketplace = "marketplace"; - private static final String s_rapids = "rapids"; - private static final String s_car_wash = "car_wash"; - private static final String s_general = "general"; - private static final String s_cafe = "cafe"; - private static final String s_locality = "locality"; - private static final String s_glacier = "glacier"; - private static final String s_storage = "storage"; - private static final String s_cycleway = "cycleway"; - private static final String s_forestry = "forestry"; - private static final String s_field = "field"; - private static final String s_5 = "5"; - private static final String s_arts_centre = "arts_centre"; - private static final String s_warehouse = "warehouse"; - private static final String s_chemist = "chemist"; - private static final String s_pier = "pier"; - private static final String s_scrub = "scrub"; - private static final String s_shelter = "shelter"; - private static final String s_emergency_phone = "emergency_phone"; - private static final String s_tidalflat = "tidalflat"; - private static final String s_cobblestone = "cobblestone"; - private static final String s_fell = "fell"; - private static final String s_peak = "peak"; - private static final String s_charging_station = "charging_station"; - private static final String s_cliff = "cliff"; - private static final String s_building = "building"; - private static final String s_fire_hydrant = "fire_hydrant"; - private static final String s_traffic_signals = "traffic_signals"; - private static final String s_heath = "heath"; - private static final String s_landfill = "landfill"; - private static final String s_mast = "mast"; - private static final String s_boutique = "boutique"; - private static final String s_boat_storage = "boat_storage"; - private static final String s_area = "area"; - private static final String s_urban = "urban"; + private static final String s_limited = "limited"; + private static final String s_chain = "chain"; + private static final String s_viaduct = "viaduct"; + private static final String s_department_store = "department_store"; + private static final String s_factory = "factory"; + private static final String s_recreation_ground = "recreation_ground"; + private static final String s_nature_reserve = "nature_reserve"; + private static final String s_apartment = "apartment"; + private static final String s_preserved = "preserved"; + private static final String s_stationery = "stationery"; + private static final String s_gravel = "gravel"; + private static final String s_hill = "hill"; + private static final String s_water_well = "water_well"; + private static final String s_garden = "garden"; + private static final String s_permissive = "permissive"; + private static final String s_deli = "deli"; + private static final String s_industrial_retail = "industrial;retail"; + private static final String s_city_wall = "city_wall"; + private static final String s_artwork = "artwork"; + private static final String s_chapel = "chapel"; + private static final String s_school = "school"; + private static final String s_caravan_site = "caravan_site"; + private static final String s_reservoir_watershed = "reservoir_watershed"; + private static final String s_local_authority = "local_authority"; + private static final String s_miniature_golf = "miniature_golf"; + private static final String s_bus_stop = "bus_stop"; + private static final String s_convenience = "convenience"; + private static final String s_kissing_gate = "kissing_gate"; + private static final String s_subway = "subway"; + private static final String s_cutline = "cutline"; + private static final String s_disused = "disused"; + private static final String s_clothes = "clothes"; + private static final String s_bicycle = "bicycle"; + private static final String s_meadow = "meadow"; + private static final String s_fence = "fence"; + private static final String s_video = "video"; + private static final String s_monorail = "monorail"; + private static final String s_clock = "clock"; + private static final String s_dirt = "dirt"; + private static final String s_border_control = "border_control"; + private static final String s_access = "access"; + private static final String s_public = "public"; + private static final String s_fast_food = "fast_food"; + private static final String s_transportation = "transportation"; + private static final String s_commercial = "commercial"; + private static final String s_water = "water"; + private static final String s_beacon = "beacon"; + private static final String s_trunk = "trunk"; + private static final String s_path = "path"; + private static final String s_bicycle_rental = "bicycle_rental"; + private static final String s_miniature = "miniature"; + private static final String s_car_parts = "car_parts"; + private static final String s_light_rail = "light_rail"; + private static final String s_military = "military"; + private static final String s_bog = "bog"; + private static final String s_hiking = "hiking"; + private static final String s_lift_gate = "lift_gate"; + private static final String s_private = "private"; + private static final String s_county = "county"; + private static final String s_secondary_link = "secondary_link"; + private static final String s_marker = "marker"; + private static final String s_islet = "islet"; + private static final String s_holding_position = "holding_position"; + private static final String s_tertiary = "tertiary"; + private static final String s_water_park = "water_park"; + private static final String s_stream = "stream"; + private static final String s_hospital = "hospital"; + private static final String s_destination = "destination"; + private static final String s_MDF = "MDF"; + private static final String s_sports = "sports"; + private static final String s_vineyard = "vineyard"; + private static final String s_music = "music"; + private static final String s_6 = "6"; + private static final String s_entrance = "entrance"; + private static final String s_beauty = "beauty"; + private static final String s_give_way = "give_way"; + private static final String s_kiosk = "kiosk"; + private static final String s_stone = "stone"; + private static final String s_grass_paver = "grass_paver"; + private static final String s_deciduous = "deciduous"; + private static final String s_train = "train"; + private static final String s_organic = "organic"; + private static final String s_farmyard = "farmyard"; + private static final String s_riverbank = "riverbank"; + private static final String s_doityourself = "doityourself"; + private static final String s_town = "town"; + private static final String s_dog_park = "dog_park"; + private static final String s_village_green = "village_green"; + private static final String s_tunnel = "tunnel"; + private static final String s_car = "car"; + private static final String s_roof = "roof"; + private static final String s_mall = "mall"; + private static final String s_ferry_terminal = "ferry_terminal"; + private static final String s_cave_entrance = "cave_entrance"; + private static final String s_detached = "detached"; + private static final String s_concrete_plates = "concrete:plates"; + private static final String s_public_building = "public_building"; + private static final String s_buffer_stop = "buffer_stop"; + private static final String s_lock = "lock"; + private static final String s_dolphin = "dolphin"; + private static final String s_taxiway = "taxiway"; + private static final String s_hunting_stand = "hunting_stand"; + private static final String s_estate_agent = "estate_agent"; + private static final String s_station = "station"; + private static final String s_car_repair = "car_repair"; + private static final String s_dyke = "dyke"; + private static final String s_hangar = "hangar"; + private static final String s_information = "information"; + private static final String s_1 = "1"; + private static final String s_forest = "forest"; + private static final String s_gate = "gate"; + private static final String s_beach = "beach"; + private static final String s_laundry = "laundry"; + private static final String s_speed_camera = "speed_camera"; + private static final String s_staircase = "staircase"; + private static final String s_farm = "farm"; + private static final String s_stop = "stop"; + private static final String s_bump_gate = "bump_gate"; + private static final String s_motorway = "motorway"; + private static final String s_water_tower = "water_tower"; + private static final String s_abutters = "abutters"; + private static final String s_driving_school = "driving_school"; + private static final String s_natural = "natural"; + private static final String s_orchard = "orchard"; + private static final String s_wheelchair = "wheelchair"; + private static final String s_swimming_pool = "swimming_pool"; + private static final String s_switch = "switch"; + private static final String s_block = "block"; + private static final String s_turnstile = "turnstile"; + private static final String s_camp_site = "camp_site"; + private static final String s_shoes = "shoes"; + private static final String s_reservoir = "reservoir"; + private static final String s_pebblestone = "pebblestone"; + private static final String s_stile = "stile"; + private static final String s_embassy = "embassy"; + private static final String s_postal_code = "postal_code"; + private static final String s_retaining_wall = "retaining_wall"; + private static final String s_bridleway = "bridleway"; + private static final String s_pitch = "pitch"; + private static final String s_agricultural = "agricultural"; + private static final String s_post_office = "post_office"; + private static final String s_parking_fuel = "parking;fuel"; + private static final String s_bureau_de_change = "bureau_de_change"; + private static final String s_mini_roundabout = "mini_roundabout"; + private static final String s_hov = "hov"; + private static final String s_police = "police"; + private static final String s_courthouse = "courthouse"; + private static final String s_raceway = "raceway"; + private static final String s_kindergarten = "kindergarten"; + private static final String s_attraction = "attraction"; + private static final String s_marsh = "marsh"; + private static final String s_reservoir_covered = "reservoir_covered"; + private static final String s_petroleum_well = "petroleum_well"; + private static final String s_silo = "silo"; + private static final String s_toys = "toys"; + private static final String s_apron = "apron"; + private static final String s_halt = "halt"; + private static final String s_dam = "dam"; + private static final String s_golf_course = "golf_course"; + private static final String s_detour = "detour"; + private static final String s_tree_row = "tree_row"; + private static final String s_copyshop = "copyshop"; + private static final String s_milestone = "milestone"; + private static final String s_foot = "foot"; + private static final String s_tourism = "tourism"; + private static final String s_bank = "bank"; + private static final String s_dry_cleaning = "dry_cleaning"; + private static final String s_tram = "tram"; + private static final String s_trolleybus = "trolleybus"; + private static final String s_university = "university"; + private static final String s_hampshire_gate = "hampshire_gate"; + private static final String s_embankment = "embankment"; + private static final String s_rock = "rock"; + private static final String s_crossing = "crossing"; + private static final String s_volcano = "volcano"; + private static final String s_greengrocer = "greengrocer"; + private static final String s_kerb = "kerb"; + private static final String s_waste_disposal = "waste_disposal"; + private static final String s_grave_yard = "grave_yard"; + private static final String s_coniferous = "coniferous"; + private static final String s_house = "house"; + private static final String s_books = "books"; + private static final String s_neighbourhood = "neighbourhood"; + private static final String s_hostel = "hostel"; + private static final String s_alcohol = "alcohol"; + private static final String s_restricted = "restricted"; + private static final String s_motel = "motel"; + private static final String s_sand = "sand"; + private static final String s_fishmonger = "fishmonger"; + private static final String s_fountain = "fountain"; + private static final String s_playground = "playground"; + private static final String s_7 = "7"; + private static final String s_parking_aisle = "parking_aisle"; + private static final String s_protected_area = "protected_area"; + private static final String s_electronics = "electronics"; + private static final String s_Paved = "Paved"; + private static final String s_highway = "highway"; + private static final String s_fine_gravel = "fine_gravel"; + private static final String s_barrier = "barrier"; + private static final String s_hairdresser = "hairdresser"; + private static final String s_post_box = "post_box"; + private static final String s_pub = "pub"; + private static final String s_coastline = "coastline"; + private static final String s_marina = "marina"; + private static final String s_reedbed = "reedbed"; + private static final String s_biergarten = "biergarten"; + private static final String s_dismantled = "dismantled"; + private static final String s_farmland = "farmland"; + private static final String s_yard = "yard"; + private static final String s_route = "route"; + private static final String s_atm = "atm"; + private static final String s_place = "place"; + private static final String s_bus_station = "bus_station"; + private static final String s_retail = "retail"; + private static final String s_industrial = "industrial"; + private static final String s_municipality = "municipality"; + private static final String s_primary = "primary"; + private static final String s_nursing_home = "nursing_home"; + private static final String s_florist = "florist"; + private static final String s_ditch = "ditch"; + private static final String s_national_park = "national_park"; + private static final String s_city = "city"; + private static final String s_confectionery = "confectionery"; + private static final String s_service = "service"; + private static final String s_unknown = "unknown"; + private static final String s_cycle_barrier = "cycle_barrier"; + private static final String s_elevator = "elevator"; + private static final String s_2 = "2"; + private static final String s_car_rental = "car_rental"; + private static final String s_flagpole = "flagpole"; + private static final String s_cabin = "cabin"; + private static final String s_paved = "paved"; + private static final String s_guest_house = "guest_house"; + private static final String s_mobile_phone = "mobile_phone"; + private static final String s_lot = "lot"; + private static final String s_quarry = "quarry"; + private static final String s_train_station = "train_station"; + private static final String s_hotel = "hotel"; + private static final String s_park = "park"; + private static final String s_hut = "hut"; + private static final String s_dentist = "dentist"; + private static final String s_doctors = "doctors"; + private static final String s_greenhouse = "greenhouse"; + private static final String s_11 = "11"; + private static final String s_10 = "10"; + private static final String s_theme_park = "theme_park"; + private static final String s_tree = "tree"; + private static final String s_shower = "shower"; + private static final String s_siding = "siding"; + private static final String s_aeroway = "aeroway"; + private static final String s_emergency_access_point = "emergency_access_point"; + private static final String s_watermill = "watermill"; + private static final String s_college = "college"; + private static final String s_landuse = "landuse"; + private static final String s_tracktype = "tracktype"; + private static final String s_ferry = "ferry"; + private static final String s_bridge = "bridge"; + private static final String s_vacant = "vacant"; + private static final String s_cattle_grid = "cattle_grid"; + private static final String s_brownfield = "brownfield"; + private static final String s_allotments = "allotments"; + private static final String s_alley = "alley"; + private static final String s_pedestrian = "pedestrian"; + private static final String s_borough = "borough"; + private static final String s_bare_rock = "bare_rock"; + private static final String s_motorcycle = "motorcycle"; + private static final String s_bakery = "bakery"; + private static final String s_zoo = "zoo"; + private static final String s_scree = "scree"; + private static final String s_fire_station = "fire_station"; + private static final String s_theatre = "theatre"; + private static final String s_track = "track"; + private static final String s_reinforced_slope = "reinforced_slope"; + private static final String s_slipway = "slipway"; + private static final String s_mangrove = "mangrove"; + private static final String s_aerodrome = "aerodrome"; + private static final String s_byway = "byway"; + private static final String s_metal = "metal"; + private static final String s_swamp = "swamp"; + private static final String s_construction = "construction"; + private static final String s_grassland = "grassland"; + private static final String s_shop = "shop"; + private static final String s_soakhole = "soakhole"; + private static final String s_asphalt = "asphalt"; + private static final String s_social_facility = "social_facility"; + private static final String s_isolated_dwelling = "isolated_dwelling"; + private static final String s_hamlet = "hamlet"; + private static final String s_picnic_table = "picnic_table"; + private static final String s_artificial = "artificial"; + private static final String s_earth = "earth"; + private static final String s_grit_bin = "grit_bin"; + private static final String s_ground = "ground"; + private static final String s_groyne = "groyne"; + private static final String s_office = "office"; + private static final String s_state = "state"; + private static final String s_terminal = "terminal"; + private static final String s_wood = "wood"; + private static final String s_fuel = "fuel"; + private static final String s_8 = "8"; + private static final String s_garden_centre = "garden_centre"; + private static final String s_horse_riding = "horse_riding"; + private static final String s_viewpoint = "viewpoint"; + private static final String s_designated = "designated"; + private static final String s_leisure = "leisure"; + private static final String s_waste_basket = "waste_basket"; + private static final String s_hifi = "hifi"; + private static final String s_hedge = "hedge"; + private static final String s_spur = "spur"; + private static final String s_chimney = "chimney"; + private static final String s_secondary = "secondary"; + private static final String s_rest_area = "rest_area"; + private static final String s_bar = "bar"; + private static final String s_bay = "bay"; + private static final String s_common = "common"; + private static final String s_river = "river"; + private static final String s_ruins = "ruins"; + private static final String s_terrace = "terrace"; + private static final String s_art = "art"; + private static final String s_residental = "residental"; + private static final String s_newsagent = "newsagent"; + private static final String s_turntable = "turntable"; + private static final String s_computer = "computer"; + private static final String s_wetland = "wetland"; + private static final String s_driveway = "driveway"; + private static final String s_parking = "parking"; + private static final String s_compacted = "compacted"; + private static final String s_barn = "barn"; + private static final String s_alpine_hut = "alpine_hut"; + private static final String s_wire_fence = "wire_fence"; + private static final String s_unpaved = "unpaved"; + private static final String s_dormitory = "dormitory"; + private static final String s_mud = "mud"; + private static final String s_3 = "3"; + private static final String s_semi = "semi"; + private static final String s_boundary = "boundary"; + private static final String s_field_boundary = "field_boundary"; + private static final String s_beverages = "beverages"; + private static final String s_supermarket = "supermarket"; + private static final String s_store = "store"; + private static final String s_restaurant = "restaurant"; + private static final String s_region = "region"; + private static final String s_variety_store = "variety_store"; + private static final String s_saltmarsh = "saltmarsh"; + private static final String s_landform = "landform"; + private static final String s_helipad = "helipad"; + private static final String s_railway = "railway"; + private static final String s_greenhouse_horticulture = "greenhouse_horticulture"; + private static final String s_wall = "wall"; + private static final String s_recycling = "recycling"; + private static final String s_passing_place = "passing_place"; + private static final String s_church = "church"; + private static final String s_pharmacy = "pharmacy"; + private static final String s_lighthouse = "lighthouse"; + private static final String s_platform = "platform"; + private static final String s_cinema = "cinema"; + private static final String s_political = "political"; + private static final String s_stadium = "stadium"; + private static final String s_basin = "basin"; + private static final String s_gasometer = "gasometer"; + private static final String s_bicycle_parking = "bicycle_parking"; + private static final String s_bbq = "bbq"; + private static final String s_incline_steep = "incline_steep"; + private static final String s_drinking_water = "drinking_water"; + private static final String s_living_street = "living_street"; + private static final String s_chalet = "chalet"; + private static final String s_narrow_gauge = "narrow_gauge"; + private static final String s_prison = "prison"; + private static final String s_mine = "mine"; + private static final String s_level_crossing = "level_crossing"; + private static final String s_water_works = "water_works"; + private static final String s_street_lamp = "street_lamp"; + private static final String s_main = "main"; + private static final String s_tank = "tank"; + private static final String s_abandoned = "abandoned"; + private static final String s_ski = "ski"; + private static final String s_runway = "runway"; + private static final String s_parking_space = "parking_space"; + private static final String s_dirt_sand = "dirt/sand"; + private static final String s_salt_pond = "salt_pond"; + private static final String s_hedge_bank = "hedge_bank"; + private static final String s_amenity = "amenity"; + private static final String s_telephone = "telephone"; + private static final String s_surface = "surface"; + private static final String s_travel_agency = "travel_agency"; + private static final String s_hardware = "hardware"; + private static final String s_wastewater_plant = "wastewater_plant"; + private static final String s_waterway = "waterway"; + private static final String s_butcher = "butcher"; + private static final String s_surveillance = "surveillance"; + private static final String s_Dirt_Sand = "Dirt/Sand"; + private static final String s_9 = "9"; + private static final String s_windmill = "windmill"; + private static final String s_picnic_site = "picnic_site"; + private static final String s_rail = "rail"; + private static final String s_cement = "cement"; + private static final String s_sauna = "sauna"; + private static final String s_suburb = "suburb"; + private static final String s_waterfall = "waterfall"; + private static final String s_bunker = "bunker"; + private static final String s_ice_cream = "ice_cream"; + private static final String s_culvert = "culvert"; + private static final String s_drain = "drain"; + private static final String s_dock = "dock"; + private static final String s_glasshouse = "glasshouse"; + private static final String s_no = "no"; + private static final String s_well = "well"; + private static final String s_wet_meadow = "wet_meadow"; + private static final String s_concrete = "concrete"; + private static final String s_dismount = "dismount"; + private static final String s_vending_machine = "vending_machine"; + private static final String s_oneway = "oneway"; + private static final String s_taxi = "taxi"; + private static final String s_outdoor = "outdoor"; + private static final String s_proposed = "proposed"; + private static final String s_sally_port = "sally_port"; + private static final String s_photo = "photo"; + private static final String s_plant_nursery = "plant_nursery"; + private static final String s_clinic = "clinic"; + private static final String s_fishing = "fishing"; + private static final String s_yes = "yes"; + private static final String s_turning_circle = "turning_circle"; + private static final String s_toilets = "toilets"; + private static final String s_guard_rail = "guard_rail"; + private static final String s_townhall = "townhall"; + private static final String s_community_centre = "community_centre"; + private static final String s_residential = "residential"; + private static final String s_cemetery = "cemetery"; + private static final String s_survey_point = "survey_point"; + private static final String s_bench = "bench"; + private static final String s_4 = "4"; + private static final String s_bollard = "bollard"; + private static final String s_sports_centre = "sports_centre"; + private static final String s_paving_stones_30 = "paving_stones:30"; + private static final String s_administrative = "administrative"; + private static final String s_Building = "Building"; + private static final String s_customers = "customers"; + private static final String s_emergency = "emergency"; + private static final String s_motorway_junction = "motorway_junction"; + private static final String s_grade1 = "grade1"; + private static final String s_grade3 = "grade3"; + private static final String s_grade2 = "grade2"; + private static final String s_grade5 = "grade5"; + private static final String s_grade4 = "grade4"; + private static final String s_lock_gate = "lock_gate"; + private static final String s_furniture = "furniture"; + private static final String s_place_of_worship = "place_of_worship"; + private static final String s_optician = "optician"; + private static final String s_gift = "gift"; + private static final String s_parking_entrance = "parking_entrance"; + private static final String s_garage = "garage"; + private static final String s_tram_stop = "tram_stop"; + private static final String s_steps = "steps"; + private static final String s_tower = "tower"; + private static final String s_works = "works"; + private static final String s_shed = "shed"; + private static final String s_car_sharing = "car_sharing"; + private static final String s_apartments = "apartments"; + private static final String s_spring = "spring"; + private static final String s_village = "village"; + private static final String s_library = "library"; + private static final String s_emergency_access = "emergency_access"; + private static final String s_home = "home"; + private static final String s_farm_auxiliary = "farm_auxiliary"; + private static final String s_primary_link = "primary_link"; + private static final String s_toll_booth = "toll_booth"; + private static final String s_jewelry = "jewelry"; + private static final String s_pet = "pet"; + private static final String s_veterinary = "veterinary"; + private static final String s_man_made = "man_made"; + private static final String s_motorway_link = "motorway_link"; + private static final String s_offices = "offices"; + private static final String s_power = "power"; + private static final String s_weir = "weir"; + private static final String s_unsurfaced = "unsurfaced"; + private static final String s_tertiary_link = "tertiary_link"; + private static final String s_trunk_link = "trunk_link"; + private static final String s_tyres = "tyres"; + private static final String s_paving_stones = "paving_stones"; + private static final String s_pipeline = "pipeline"; + private static final String s_census = "census"; + private static final String s_incline = "incline"; + private static final String s_footway = "footway"; + private static final String s_drive_through = "drive-through"; + private static final String s_island = "island"; + private static final String s_monitoring_station = "monitoring_station"; + private static final String s_nightclub = "nightclub"; + private static final String s_unclassified = "unclassified"; + private static final String s_aquaculture = "aquaculture"; + private static final String s_mixed = "mixed"; + private static final String s_road = "road"; + private static final String s_greenfield = "greenfield"; + private static final String s_breakwater = "breakwater"; + private static final String s_services = "services"; + private static final String s_railway_crossing = "railway_crossing"; + private static final String s_residentiel1 = "residentiel1"; + private static final String s_canal = "canal"; + private static final String s__1 = "-1"; + private static final String s_ridge = "ridge"; + private static final String s_fabric = "fabric"; + private static final String s_museum = "museum"; + private static final String s_communications_tower = "communications_tower"; + private static final String s_semi_detached = "semi-detached"; + private static final String s_conservation = "conservation"; + private static final String s_way = "way"; + private static final String s_wood_fence = "wood_fence"; + private static final String s_manufacture = "manufacture"; + private static final String s_admin_level = "admin_level"; + private static final String s_building_concrete = "building_concrete"; + private static final String s_bus = "bus"; + private static final String s_collapsed = "collapsed"; + private static final String s_ford = "ford"; + private static final String s_delivery = "delivery"; + private static final String s_garages = "garages"; + private static final String s_funeral_directors = "funeral_directors"; + private static final String s_land = "land"; + private static final String s_interlock = "interlock"; + private static final String s_reef = "reef"; + private static final String s_crane = "crane"; + private static final String s_true = "true"; + private static final String s_storage_tank = "storage_tank"; + private static final String s_official = "official"; + private static final String s_subway_entrance = "subway_entrance"; + private static final String s_mtb = "mtb"; + private static final String s_grass = "grass"; + private static final String s_marketplace = "marketplace"; + private static final String s_rapids = "rapids"; + private static final String s_car_wash = "car_wash"; + private static final String s_general = "general"; + private static final String s_cafe = "cafe"; + private static final String s_locality = "locality"; + private static final String s_glacier = "glacier"; + private static final String s_storage = "storage"; + private static final String s_cycleway = "cycleway"; + private static final String s_forestry = "forestry"; + private static final String s_field = "field"; + private static final String s_5 = "5"; + private static final String s_arts_centre = "arts_centre"; + private static final String s_warehouse = "warehouse"; + private static final String s_chemist = "chemist"; + private static final String s_pier = "pier"; + private static final String s_scrub = "scrub"; + private static final String s_shelter = "shelter"; + private static final String s_emergency_phone = "emergency_phone"; + private static final String s_tidalflat = "tidalflat"; + private static final String s_cobblestone = "cobblestone"; + private static final String s_fell = "fell"; + private static final String s_peak = "peak"; + private static final String s_charging_station = "charging_station"; + private static final String s_cliff = "cliff"; + private static final String s_building = "building"; + private static final String s_fire_hydrant = "fire_hydrant"; + private static final String s_traffic_signals = "traffic_signals"; + private static final String s_heath = "heath"; + private static final String s_landfill = "landfill"; + private static final String s_mast = "mast"; + private static final String s_boutique = "boutique"; + private static final String s_boat_storage = "boat_storage"; + private static final String s_area = "area"; + private static final String s_urban = "urban"; - // only the keys that were imported via osm2pgsql - // FIXME add whats missing, e.g. wheelchair - public final static String[] keys = { - "access", - "addr:housename", - "addr:housenumber", - "addr:interpolation", - "admin_level", - "aerialway", - "aeroway", - "amenity", - "area", - "barrier", - "bicycle", - "brand", - "bridge", - "boundary", - "building", - "construction", - "covered", - "culvert", - "cutting", - "denomination", - "disused", - "embankment", - "foot", - "generator:source", - "harbour", - "highway", - "historic", - "horse", - "intermittent", - "junction", - "landuse", - "layer", - "leisure", - "lock", - "man_made", - "military", - "motorcar", - "name", - "natural", - "oneway", - "operator", - "population", - "power", - "power_source", - "place", - "railway", - "ref", - "religion", - "route", - "service", - "shop", - "sport", - "surface", - "toll", - "tourism", - "tower:type", - "tracktype", - "tunnel", - "water", - "waterway", - "wetland", - "width", - "wood" - }; + // only the keys that were imported via osm2pgsql + // FIXME add whats missing, e.g. wheelchair + public final static String[] keys = { + "access", + "addr:housename", + "addr:housenumber", + "addr:interpolation", + "admin_level", + "aerialway", + "aeroway", + "amenity", + "area", + "barrier", + "bicycle", + "brand", + "bridge", + "boundary", + "building", + "construction", + "covered", + "culvert", + "cutting", + "denomination", + "disused", + "embankment", + "foot", + "generator:source", + "harbour", + "highway", + "historic", + "horse", + "intermittent", + "junction", + "landuse", + "layer", + "leisure", + "lock", + "man_made", + "military", + "motorcar", + "name", + "natural", + "oneway", + "operator", + "population", + "power", + "power_source", + "place", + "railway", + "ref", + "religion", + "route", + "service", + "shop", + "sport", + "surface", + "toll", + "tourism", + "tower:type", + "tracktype", + "tunnel", + "water", + "waterway", + "wetland", + "width", + "wood" + }; - // most common tags, ordered by tag count - public final static Tag[] tags = { - new Tag(s_building, s_yes, false), - new Tag(s_highway, s_residential, false), - new Tag(s_highway, s_service, false), - new Tag(s_waterway, s_stream, false), - new Tag(s_highway, s_unclassified, false), - new Tag(s_highway, s_track, false), - new Tag(s_oneway, s_yes, false), - new Tag(s_natural, s_water, false), - new Tag(s_highway, s_footway, false), - new Tag(s_access, s_private, false), - new Tag(s_highway, s_tertiary, false), - new Tag(s_highway, s_path, false), - new Tag(s_highway, s_secondary, false), - new Tag(s_landuse, s_forest, false), - new Tag(s_bridge, s_yes, false), - new Tag(s_natural, s_tree, false), - new Tag(s_surface, s_paved, false), - new Tag(s_natural, s_wood, false), - new Tag(s_highway, s_primary, false), - new Tag(s_landuse, s_grass, false), - new Tag(s_landuse, s_residential, false), - new Tag(s_surface, s_unpaved, false), - new Tag(s_highway, s_bus_stop, false), - new Tag(s_surface, s_asphalt, false), - new Tag(s_bicycle, s_yes, false), - new Tag(s_amenity, s_parking, false), - new Tag(s_place, s_locality, false), - new Tag(s_railway, s_rail, false), - new Tag(s_service, s_parking_aisle, false), - new Tag(s_boundary, s_administrative, false), - new Tag(s_building, s_house, false), - new Tag(s_place, s_village, false), - new Tag(s_natural, s_coastline, false), - new Tag(s_tracktype, s_grade2, false), - new Tag(s_oneway, s_no, false), - new Tag(s_service, s_driveway, false), - new Tag(s_highway, s_turning_circle, false), - new Tag(s_place, s_hamlet, false), - new Tag(s_natural, s_wetland, false), - new Tag(s_tracktype, s_grade3, false), - new Tag(s_waterway, s_river, false), - new Tag(s_highway, s_cycleway, false), - new Tag(s_barrier, s_fence, false), - new Tag(s_building, s_residential, false), - new Tag(s_amenity, s_school, false), - new Tag(s_highway, s_crossing, false), - new Tag(s_admin_level, s_8, false), - new Tag(s_highway, s_trunk, false), - new Tag(s_amenity, s_place_of_worship, false), - new Tag(s_landuse, s_farmland, false), - new Tag(s_tracktype, s_grade1, false), - new Tag(s_highway, s_road, false), - new Tag(s_landuse, s_farm, false), - new Tag(s_surface, s_gravel, false), - new Tag(s_landuse, s_meadow, false), - new Tag(s_highway, s_motorway, false), - new Tag(s_highway, s_traffic_signals, false), - new Tag(s_building, s_hut, false), - new Tag(s_highway, s_motorway_link, false), - new Tag(s_tracktype, s_grade4, false), - new Tag(s_barrier, s_gate, false), - new Tag(s_highway, s_living_street, false), - new Tag(s_bicycle, s_no, false), - new Tag(s_leisure, s_pitch, false), - new Tag(s_tunnel, s_yes, false), - new Tag(s_surface, s_ground, false), - new Tag(s_highway, s_steps, false), - new Tag(s_natural, s_land, false), - new Tag(s_man_made, s_survey_point, false), - new Tag(s_tracktype, s_grade5, false), - new Tag(s_waterway, s_ditch, false), - new Tag(s_leisure, s_park, false), - new Tag(s_amenity, s_restaurant, false), - new Tag(s_barrier, s_wall, false), - new Tag(s_waterway, s_riverbank, false), - new Tag(s_amenity, s_bench, false), - new Tag(s_building, s_garage, false), - new Tag(s_natural, s_scrub, false), - new Tag(s_highway, s_pedestrian, false), - new Tag(s_natural, s_peak, false), - new Tag(s_building, s_entrance, false), - new Tag(s_landuse, s_reservoir, false), - new Tag(s_access, s_yes, false), - new Tag(s_bicycle, s_designated, false), - new Tag(s_leisure, s_swimming_pool, false), - new Tag(s_landuse, s_farmyard, false), - new Tag(s_railway, s_level_crossing, false), - new Tag(s_building, s_apartments, false), - new Tag(s_surface, s_grass, false), - new Tag(s_wheelchair, s_yes, false), - new Tag(s_service, s_alley, false), - new Tag(s_landuse, s_industrial, false), - new Tag(s_amenity, s_fuel, false), - new Tag(s_surface, s_dirt, false), - new Tag(s_highway, s_trunk_link, false), - new Tag(s_waterway, s_drain, false), - new Tag(s_barrier, s_hedge, false), - new Tag(s_amenity, s_grave_yard, false), - new Tag(s_tourism, s_information, false), - new Tag(s_shop, s_supermarket, false), - new Tag(s_highway, s_primary_link, false), - new Tag(s_wood, s_deciduous, false), - new Tag(s_leisure, s_playground, false), - new Tag(s_building, s_roof, false), - new Tag(s_building, s_industrial, false), - new Tag(s_amenity, s_post_box, false), - new Tag(s_waterway, s_canal, false), - new Tag(s_barrier, s_bollard, false), - new Tag(s_leisure, s_garden, false), - new Tag(s_wood, s_mixed, false), - new Tag(s_landuse, s_cemetery, false), - new Tag(s_landuse, s_orchard, false), - new Tag(s_shop, s_convenience, false), - new Tag(s_access, s_permissive, false), - new Tag(s_surface, s_concrete, false), - new Tag(s_surface, s_paving_stones, false), - new Tag(s_service, s_spur, false), - new Tag(s_building, s_garages, false), - new Tag(s_amenity, s_bank, false), - new Tag(s_tourism, s_hotel, false), - new Tag(s_access, s_no, false), - new Tag(s_amenity, s_fast_food, false), - new Tag(s_man_made, s_pier, false), - new Tag(s_amenity, s_kindergarten, false), - new Tag(s_access, s_agricultural, false), - new Tag(s_surface, s_cobblestone, false), - new Tag(s_wheelchair, s_no, false), - new Tag(s_amenity, s_cafe, false), - new Tag(s_amenity, s_hospital, false), - new Tag(s_amenity, s_post_office, false), - new Tag(s_amenity, s_public_building, false), - new Tag(s_amenity, s_recycling, false), - new Tag(s_highway, s_street_lamp, false), - new Tag(s_man_made, s_tower, false), - new Tag(s_waterway, s_dam, false), - new Tag(s_amenity, s_pub, false), - new Tag(s_wood, s_coniferous, false), - new Tag(s_access, s_destination, false), - new Tag(s_admin_level, s_6, false), - new Tag(s_landuse, s_commercial, false), - new Tag(s_amenity, s_pharmacy, false), - new Tag(s_railway, s_abandoned, false), - new Tag(s_service, s_yard, false), - new Tag(s_place, s_island, false), - new Tag(s_oneway, s__1, false), - new Tag(s_landuse, s_quarry, false), - new Tag(s_landuse, s_vineyard, false), - new Tag(s_highway, s_motorway_junction, false), - new Tag(s_railway, s_station, false), - new Tag(s_landuse, s_allotments, false), - new Tag(s_barrier, s_lift_gate, false), - new Tag(s_admin_level, s_10, false), - new Tag(s_amenity, s_telephone, false), - new Tag(s_place, s_town, false), - new Tag(s_man_made, s_cutline, false), - new Tag(s_place, s_suburb, false), - new Tag(s_aeroway, s_taxiway, false), - new Tag(s_wheelchair, s_limited, false), - new Tag(s_highway, s_secondary_link, false), - new Tag(s_leisure, s_sports_centre, false), - new Tag(s_amenity, s_bicycle_parking, false), - new Tag(s_surface, s_sand, false), - new Tag(s_highway, s_stop, false), - new Tag(s_man_made, s_works, false), - new Tag(s_landuse, s_retail, false), - new Tag(s_amenity, s_fire_station, false), - new Tag(s_service, s_siding, false), - new Tag(s_amenity, s_toilets, false), - new Tag(s_bench, s_yes, false), - new Tag(s_oneway, s_1, false), - new Tag(s_surface, s_compacted, false), - new Tag(s_landuse, s_basin, false), - new Tag(s_amenity, s_police, false), - new Tag(s_railway, s_tram, false), - new Tag(s_route, s_road, false), - new Tag(s_natural, s_cliff, false), - new Tag(s_highway, s_construction, false), - new Tag(s_aeroway, s_aerodrome, false), - new Tag(s_entrance, s_yes, false), - new Tag(s_man_made, s_storage_tank, false), - new Tag(s_amenity, s_atm, false), - new Tag(s_tourism, s_attraction, false), - new Tag(s_route, s_bus, false), - new Tag(s_shop, s_bakery, false), - new Tag(s_tourism, s_viewpoint, false), - new Tag(s_amenity, s_swimming_pool, false), - new Tag(s_natural, s_beach, false), - new Tag(s_tourism, s_picnic_site, false), - new Tag(s_oneway, s_true, false), - new Tag(s_highway, s_bridleway, false), - new Tag(s_tourism, s_camp_site, false), - new Tag(s_abutters, s_residential, false), - new Tag(s_leisure, s_nature_reserve, false), - new Tag(s_amenity, s_drinking_water, false), - new Tag(s_shop, s_clothes, false), - new Tag(s_natural, s_heath, false), - new Tag(s_highway, s_mini_roundabout, false), - new Tag(s_landuse, s_construction, false), - new Tag(s_amenity, s_waste_basket, false), - new Tag(s_railway, s_platform, false), - new Tag(s_amenity, s_townhall, false), - new Tag(s_shop, s_hairdresser, false), - new Tag(s_amenity, s_shelter, false), - new Tag(s_admin_level, s_9, false), - new Tag(s_building, s_farm_auxiliary, false), - new Tag(s_amenity, s_library, false), - new Tag(s_building, s_detached, false), - new Tag(s_admin_level, s_4, false), - new Tag(s_landuse, s_village_green, false), - new Tag(s_barrier, s_stile, false), - new Tag(s_landuse, s_garages, false), - new Tag(s_amenity, s_bar, false), - new Tag(s_railway, s_buffer_stop, false), - new Tag(s_wetland, s_marsh, false), - new Tag(s_tourism, s_museum, false), - new Tag(s_barrier, s_cycle_barrier, false), - new Tag(s_route, s_bicycle, false), - new Tag(s_railway, s_tram_stop, false), - new Tag(s_amenity, s_parking_space, false), - new Tag(s_barrier, s_retaining_wall, false), - new Tag(s_landuse, s_recreation_ground, false), - new Tag(s_amenity, s_university, false), - new Tag(s_highway, s_tertiary_link, false), - new Tag(s_building, s_terrace, false), - new Tag(s_shop, s_car_repair, false), - new Tag(s_amenity, s_hunting_stand, false), - new Tag(s_amenity, s_fountain, false), - new Tag(s_man_made, s_pipeline, false), - new Tag(s_wetland, s_swamp, false), - new Tag(s_shop, s_car, false), - new Tag(s_bench, s_no, false), - new Tag(s_tunnel, s_culvert, false), - new Tag(s_building, s_school, false), - new Tag(s_barrier, s_entrance, false), - new Tag(s_railway, s_disused, false), - new Tag(s_railway, s_crossing, false), - new Tag(s_building, s_church, false), - new Tag(s_amenity, s_social_facility, false), - new Tag(s_natural, s_bay, false), - new Tag(s_shop, s_kiosk, false), - new Tag(s_amenity, s_vending_machine, false), - new Tag(s_route, s_hiking, false), - new Tag(s_natural, s_spring, false), - new Tag(s_leisure, s_common, false), - new Tag(s_railway, s_switch, false), - new Tag(s_waterway, s_rapids, false), - new Tag(s_admin_level, s_7, false), - new Tag(s_leisure, s_stadium, false), - new Tag(s_leisure, s_track, false), - new Tag(s_place, s_isolated_dwelling, false), - new Tag(s_place, s_islet, false), - new Tag(s_waterway, s_weir, false), - new Tag(s_amenity, s_doctors, false), - new Tag(s_access, s_designated, false), - new Tag(s_landuse, s_conservation, false), - new Tag(s_waterway, s_artificial, false), - new Tag(s_amenity, s_bus_station, false), - new Tag(s_leisure, s_golf_course, false), - new Tag(s_shop, s_doityourself, false), - new Tag(s_building, s_service, false), - new Tag(s_tourism, s_guest_house, false), - new Tag(s_aeroway, s_runway, false), - new Tag(s_place, s_city, false), - new Tag(s_railway, s_subway, false), - new Tag(s_man_made, s_wastewater_plant, false), - new Tag(s_building, s_commercial, false), - new Tag(s_railway, s_halt, false), - new Tag(s_amenity, s_emergency_phone, false), - new Tag(s_building, s_retail, false), - new Tag(s_barrier, s_block, false), - new Tag(s_leisure, s_recreation_ground, false), - new Tag(s_access, s_forestry, false), - new Tag(s_amenity, s_college, false), - new Tag(s_highway, s_platform, false), - new Tag(s_access, s_unknown, false), - new Tag(s_man_made, s_water_tower, false), - new Tag(s_surface, s_pebblestone, false), - new Tag(s_bridge, s_viaduct, false), - new Tag(s_shop, s_butcher, false), - new Tag(s_shop, s_florist, false), - new Tag(s_boundary, s_landuse, false), - new Tag(s_aeroway, s_helipad, false), - new Tag(s_building, s_hangar, false), - new Tag(s_natural, s_glacier, false), - new Tag(s_highway, s_proposed, false), - new Tag(s_shop, s_mall, false), - new Tag(s_barrier, s_toll_booth, false), - new Tag(s_amenity, s_fire_hydrant, false), - new Tag(s_building, s_manufacture, false), - new Tag(s_building, s_farm, false), - new Tag(s_surface, s_wood, false), - new Tag(s_amenity, s_car_wash, false), - new Tag(s_amenity, s_dentist, false), - new Tag(s_natural, s_marsh, false), - new Tag(s_man_made, s_surveillance, false), - new Tag(s_shop, s_bicycle, false), - new Tag(s_route, s_foot, false), - new Tag(s_amenity, s_theatre, false), - new Tag(s_building, s_office, false), - new Tag(s_railway, s_light_rail, false), - new Tag(s_man_made, s_petroleum_well, false), - new Tag(s_amenity, s_taxi, false), - new Tag(s_building, s_greenhouse, false), - new Tag(s_landuse, s_brownfield, false), - new Tag(s_bicycle, s_permissive, false), - new Tag(s_admin_level, s_2, false), - new Tag(s_aeroway, s_apron, false), - new Tag(s_building, s_cabin, false), - new Tag(s_amenity, s_cinema, false), - new Tag(s_access, s_customers, false), - new Tag(s_tourism, s_motel, false), - new Tag(s_railway, s_narrow_gauge, false), - new Tag(s_amenity, s_marketplace, false), - new Tag(s_shop, s_furniture, false), - new Tag(s_entrance, s_staircase, false), - new Tag(s_tourism, s_artwork, false), - new Tag(s_natural, s_grassland, false), - new Tag(s_shop, s_books, false), - new Tag(s_admin_level, s_5, false), - new Tag(s_man_made, s_groyne, false), - new Tag(s_waterway, s_lock_gate, false), - new Tag(s_highway, s_emergency_access_point, false), - new Tag(s_natural, s_sand, false), - new Tag(s_landuse, s_military, false), - new Tag(s_boundary, s_protected_area, false), - new Tag(s_amenity, s_community_centre, false), - new Tag(s_barrier, s_kissing_gate, false), - new Tag(s_highway, s_speed_camera, false), - new Tag(s_boundary, s_national_park, false), - new Tag(s_railway, s_subway_entrance, false), - new Tag(s_man_made, s_silo, false), - new Tag(s_shop, s_alcohol, false), - new Tag(s_highway, s_give_way, false), - new Tag(s_leisure, s_slipway, false), - new Tag(s_shop, s_electronics, false), - new Tag(s_bicycle, s_dismount, false), - new Tag(s_leisure, s_marina, false), - new Tag(s_entrance, s_main, false), - new Tag(s_boundary, s_postal_code, false), - new Tag(s_landuse, s_greenhouse_horticulture, false), - new Tag(s_highway, s_milestone, false), - new Tag(s_natural, s_cave_entrance, false), - new Tag(s_landuse, s_landfill, false), - new Tag(s_shop, s_chemist, false), - new Tag(s_shop, s_shoes, false), - new Tag(s_barrier, s_cattle_grid, false), - new Tag(s_landuse, s_railway, false), - new Tag(s_tourism, s_hostel, false), - new Tag(s_tourism, s_chalet, false), - new Tag(s_place, s_county, false), - new Tag(s_shop, s_department_store, false), - new Tag(s_highway, s_ford, false), - new Tag(s_natural, s_scree, false), - new Tag(s_landuse, s_greenfield, false), - new Tag(s_amenity, s_nursing_home, false), - new Tag(s_barrier, s_wire_fence, false), - new Tag(s_access, s_restricted, false), - new Tag(s_man_made, s_reservoir_covered, false), - new Tag(s_amenity, s_bicycle_rental, false), - new Tag(s_man_made, s_MDF, false), - new Tag(s_man_made, s_water_well, false), - new Tag(s_landuse, s_field, false), - new Tag(s_landuse, s_wood, false), - new Tag(s_shop, s_hardware, false), - new Tag(s_tourism, s_alpine_hut, false), - new Tag(s_natural, s_tree_row, false), - new Tag(s_tourism, s_caravan_site, false), - new Tag(s_bridge, s_no, false), - new Tag(s_wetland, s_bog, false), - new Tag(s_amenity, s_courthouse, false), - new Tag(s_route, s_ferry, false), - new Tag(s_barrier, s_city_wall, false), - new Tag(s_amenity, s_veterinary, false), - new Tag(s_shop, s_jewelry, false), - new Tag(s_building, s_transportation, false), - new Tag(s_amenity, s_arts_centre, false), - new Tag(s_bicycle, s_official, false), - new Tag(s_shop, s_optician, false), - new Tag(s_shop, s_yes, false), - new Tag(s_building, s_collapsed, false), - new Tag(s_shop, s_garden_centre, false), - new Tag(s_man_made, s_chimney, false), - new Tag(s_man_made, s_mine, false), - new Tag(s_bench, s_unknown, false), - new Tag(s_railway, s_preserved, false), - new Tag(s_building, s_public, false), - new Tag(s_amenity, s_ferry_terminal, false), - new Tag(s_highway, s_raceway, false), - new Tag(s_natural, s_rock, false), - new Tag(s_tunnel, s_no, false), - new Tag(s_building, s_university, false), - new Tag(s_shop, s_beverages, false), - new Tag(s_amenity, s_waste_disposal, false), - new Tag(s_building, s_warehouse, false), - new Tag(s_leisure, s_water_park, false), - new Tag(s_shop, s_gift, false), - new Tag(s_place, s_farm, false), - new Tag(s_wetland, s_tidalflat, false), - new Tag(s_waterway, s_waterfall, false), - new Tag(s_man_made, s_dolphin, false), - new Tag(s_service, s_drive_through, false), - new Tag(s_amenity, s_nightclub, false), - new Tag(s_building, s_shed, false), - new Tag(s_shop, s_greengrocer, false), - new Tag(s_natural, s_fell, false), - new Tag(s_wetland, s_wet_meadow, false), - new Tag(s_aeroway, s_gate, false), - new Tag(s_shop, s_computer, false), - new Tag(s_man_made, s_lighthouse, false), - new Tag(s_wetland, s_reedbed, false), - new Tag(s_man_made, s_breakwater, false), - new Tag(s_surface, s_Dirt_Sand, false), - new Tag(s_barrier, s_ditch, false), - new Tag(s_barrier, s_yes, false), - new Tag(s_amenity, s_biergarten, false), - new Tag(s_shop, s_mobile_phone, false), - new Tag(s_route, s_mtb, false), - new Tag(s_amenity, s_grit_bin, false), - new Tag(s_amenity, s_bbq, false), - new Tag(s_shop, s_sports, false), - new Tag(s_barrier, s_wood_fence, false), - new Tag(s_entrance, s_home, false), - new Tag(s_shop, s_laundry, false), - new Tag(s_man_made, s_gasometer, false), - new Tag(s_barrier, s_embankment, false), - new Tag(s_shop, s_toys, false), - new Tag(s_wetland, s_saltmarsh, false), - new Tag(s_waterway, s_soakhole, false), - new Tag(s_shop, s_travel_agency, false), - new Tag(s_man_made, s_water_works, false), - new Tag(s_route, s_railway, false), - new Tag(s_amenity, s_prison, false), - new Tag(s_highway, s_rest_area, false), - new Tag(s_shop, s_stationery, false), - new Tag(s_admin_level, s_11, false), - new Tag(s_building, s_train_station, false), - new Tag(s_building, s_storage_tank, false), - new Tag(s_man_made, s_windmill, false), - new Tag(s_shop, s_beauty, false), - new Tag(s_building, s_semi, false), - new Tag(s_highway, s_services, false), - new Tag(s_bicycle, s_private, false), - new Tag(s_route, s_ski, false), - new Tag(s_service, s_emergency_access, false), - new Tag(s_building, s_factory, false), - new Tag(s_man_made, s_reinforced_slope, false), - new Tag(s_amenity, s_car_sharing, false), - new Tag(s_surface, s_earth, false), - new Tag(s_shop, s_hifi, false), - new Tag(s_amenity, s_car_rental, false), - new Tag(s_barrier, s_hedge_bank, false), - new Tag(s_shop, s_confectionery, false), - new Tag(s_aeroway, s_terminal, false), - new Tag(s_highway, s_passing_place, false), - new Tag(s_building, s_building, false), - new Tag(s_man_made, s_dyke, false), - new Tag(s_building, s_construction, false), - new Tag(s_building, s_shop, false), - new Tag(s_natural, s_reef, false), - new Tag(s_landuse, s_aquaculture, false), - new Tag(s_shop, s_dry_cleaning, false), - new Tag(s_amenity, s_embassy, false), - new Tag(s_shop, s_newsagent, false), - new Tag(s_landuse, s_salt_pond, false), - new Tag(s_railway, s_spur, false), - new Tag(s_wheelchair, s_unknown, false), - new Tag(s_tourism, s_zoo, false), - new Tag(s_man_made, s_waterway, false), - new Tag(s_surface, s_fine_gravel, false), - new Tag(s_shop, s_motorcycle, false), - new Tag(s_building, s_Building, false), - new Tag(s_railway, s_construction, false), - new Tag(s_place, s_neighbourhood, false), - new Tag(s_route, s_train, false), - new Tag(s_building, s_no, false), - new Tag(s_natural, s_mud, false), - new Tag(s_place, s_region, false), - new Tag(s_landuse, s_reservoir_watershed, false), - new Tag(s_boundary, s_marker, false), - new Tag(s_man_made, s_beacon, false), - new Tag(s_shop, s_outdoor, false), - new Tag(s_access, s_public, false), - new Tag(s_abutters, s_industrial, false), - new Tag(s_building, s_barn, false), - new Tag(s_leisure, s_picnic_table, false), - new Tag(s_building, s_hospital, false), - new Tag(s_access, s_official, false), - new Tag(s_shop, s_variety_store, false), - new Tag(s_man_made, s_crane, false), - new Tag(s_amenity, s_parking_fuel, false), - new Tag(s_route, s_tram, false), - new Tag(s_tourism, s_theme_park, false), - new Tag(s_shop, s_pet, false), - new Tag(s_building, s_kindergarten, false), - new Tag(s_man_made, s_storage, false), - new Tag(s_man_made, s_mast, false), - new Tag(s_amenity, s_parking_entrance, false), - new Tag(s_amenity, s_clock, false), - new Tag(s_landuse, s_industrial_retail, false), - new Tag(s_shop, s_video, false), - new Tag(s_access, s_delivery, false), - new Tag(s_amenity, s_driving_school, false), - new Tag(s_service, s_yes, false), - new Tag(s_natural, s_bare_rock, false), - new Tag(s_building, s_chapel, false), - new Tag(s_natural, s_volcano, false), - new Tag(s_waterway, s_dock, false), - new Tag(s_building, s_dormitory, false), - new Tag(s_amenity, s_boat_storage, false), - new Tag(s_man_made, s_tank, false), - new Tag(s_man_made, s_flagpole, false), - new Tag(s_surface, s_grass_paver, false), - new Tag(s_shop, s_organic, false), - new Tag(s_natural, s_landform, false), - new Tag(s_highway, s_unsurfaced, false), - new Tag(s_route, s_power, false), - new Tag(s_surface, s_mud, false), - new Tag(s_building, s_building_concrete, false), - new Tag(s_abutters, s_retail, false), - new Tag(s_building, s_store, false), - new Tag(s_shop, s_vacant, false), - new Tag(s_leisure, s_miniature_golf, false), - new Tag(s_man_made, s_monitoring_station, false), - new Tag(s_natural, s_waterfall, false), - new Tag(s_aeroway, s_hangar, false), - new Tag(s_shop, s_boutique, false), - new Tag(s_route, s_detour, false), - new Tag(s_building, s_way, false), - new Tag(s_railway, s_stop, false), - new Tag(s_amenity, s_ice_cream, false), - new Tag(s_building, s_storage, false), - new Tag(s_shop, s_car_parts, false), - new Tag(s_natural, s_ridge, false), - new Tag(s_shop, s_tyres, false), - new Tag(s_railway, s_dismantled, false), - new Tag(s_amenity, s_shop, false), - new Tag(s_landuse, s_plant_nursery, false), - new Tag(s_building, s_residentiel1, false), - new Tag(s_barrier, s_field_boundary, false), - new Tag(s_barrier, s_border_control, false), - new Tag(s_surface, s_Paved, false), - new Tag(s_barrier, s_sally_port, false), - new Tag(s_amenity, s_bureau_de_change, false), - new Tag(s_leisure, s_fishing, false), - new Tag(s_amenity, s_charging_station, false), - new Tag(s_building, s_supermarket, false), - new Tag(s_highway, s_stile, false), - new Tag(s_amenity, s_sauna, false), - new Tag(s_place, s_municipality, false), - new Tag(s_building, s_hotel, false), - new Tag(s_surface, s_metal, false), - new Tag(s_highway, s_incline_steep, false), - new Tag(s_shop, s_estate_agent, false), - new Tag(s_natural, s_grass, false), - new Tag(s_shop, s_pharmacy, false), - new Tag(s_surface, s_concrete_plates, false), - new Tag(s_shop, s_copyshop, false), - new Tag(s_surface, s_paving_stones_30, false), - new Tag(s_surface, s_interlock, false), - new Tag(s_access, s_hov, false), - new Tag(s_highway, s_elevator, false), - new Tag(s_boundary, s_local_authority, false), - new Tag(s_man_made, s_communications_tower, false), - new Tag(s_shop, s_deli, false), - new Tag(s_barrier, s_turnstile, false), - new Tag(s_building, s_offices, false), - new Tag(s_building, s_bunker, false), - new Tag(s_natural, s_stone, false), - new Tag(s_railway, s_railway_crossing, false), - new Tag(s_leisure, s_dog_park, false), - new Tag(s_building, s_semi_detached, false), - new Tag(s_man_made, s_watermill, false), - new Tag(s_route, s_trolleybus, false), - new Tag(s_admin_level, s_3, false), - new Tag(s_building, s_block, false), - new Tag(s_barrier, s_guard_rail, false), - new Tag(s_bicycle, s_unknown, false), - new Tag(s_highway, s_abandoned, false), - new Tag(s_surface, s_dirt_sand, false), - new Tag(s_barrier, s_chain, false), - new Tag(s_barrier, s_bump_gate, false), - new Tag(s_building, s_residental, false), - new Tag(s_surface, s_cement, false), - new Tag(s_man_made, s_embankment, false), - new Tag(s_building, s_ruins, false), - new Tag(s_highway, s_incline, false), - new Tag(s_abutters, s_commercial, false), - new Tag(s_barrier, s_hampshire_gate, false), - new Tag(s_shop, s_music, false), - new Tag(s_shop, s_funeral_directors, false), - new Tag(s_wetland, s_mangrove, false), - new Tag(s_place, s_borough, false), - new Tag(s_building, s_apartment, false), - new Tag(s_boundary, s_census, false), - new Tag(s_barrier, s_kerb, false), - new Tag(s_building, s_glasshouse, false), - new Tag(s_aeroway, s_holding_position, false), - new Tag(s_shop, s_general, false), - new Tag(s_building, s_tank, false), - new Tag(s_railway, s_monorail, false), - new Tag(s_service, s_parking, false), - new Tag(s_place, s_state, false), - new Tag(s_railway, s_proposed, false), - new Tag(s_shop, s_art, false), - new Tag(s_natural, s_hill, false), - new Tag(s_railway, s_turntable, false), - new Tag(s_tourism, s_cabin, false), - new Tag(s_shop, s_photo, false), - new Tag(s_boundary, s_lot, false), - new Tag(s_shop, s_fishmonger, false), - new Tag(s_amenity, s_clinic, false), - new Tag(s_boundary, s_political, false), - new Tag(s_man_made, s_well, false), - new Tag(s_highway, s_byway, false), - new Tag(s_leisure, s_horse_riding, false), - new Tag(s_service, s_bus, false), - new Tag(s_building, s_tower, false), - new Tag(s_entrance, s_service, false), - new Tag(s_shop, s_fabric, false), - new Tag(s_railway, s_miniature, false), - new Tag(s_abutters, s_mixed, false), - new Tag(s_surface, s_stone, false), - new Tag(s_access, s_emergency, false), - new Tag(s_landuse, s_mine, false), - new Tag(s_amenity, s_shower, false), - new Tag(s_waterway, s_lock, false), - new Tag(s_area, s_yes, false), - new Tag(s_landuse, s_urban, false), - }; + // most common tags, ordered by tag count + public final static Tag[] tags = { + new Tag(s_building, s_yes, false), + new Tag(s_highway, s_residential, false), + new Tag(s_highway, s_service, false), + new Tag(s_waterway, s_stream, false), + new Tag(s_highway, s_unclassified, false), + new Tag(s_highway, s_track, false), + new Tag(s_oneway, s_yes, false), + new Tag(s_natural, s_water, false), + new Tag(s_highway, s_footway, false), + new Tag(s_access, s_private, false), + new Tag(s_highway, s_tertiary, false), + new Tag(s_highway, s_path, false), + new Tag(s_highway, s_secondary, false), + new Tag(s_landuse, s_forest, false), + new Tag(s_bridge, s_yes, false), + new Tag(s_natural, s_tree, false), + new Tag(s_surface, s_paved, false), + new Tag(s_natural, s_wood, false), + new Tag(s_highway, s_primary, false), + new Tag(s_landuse, s_grass, false), + new Tag(s_landuse, s_residential, false), + new Tag(s_surface, s_unpaved, false), + new Tag(s_highway, s_bus_stop, false), + new Tag(s_surface, s_asphalt, false), + new Tag(s_bicycle, s_yes, false), + new Tag(s_amenity, s_parking, false), + new Tag(s_place, s_locality, false), + new Tag(s_railway, s_rail, false), + new Tag(s_service, s_parking_aisle, false), + new Tag(s_boundary, s_administrative, false), + new Tag(s_building, s_house, false), + new Tag(s_place, s_village, false), + new Tag(s_natural, s_coastline, false), + new Tag(s_tracktype, s_grade2, false), + new Tag(s_oneway, s_no, false), + new Tag(s_service, s_driveway, false), + new Tag(s_highway, s_turning_circle, false), + new Tag(s_place, s_hamlet, false), + new Tag(s_natural, s_wetland, false), + new Tag(s_tracktype, s_grade3, false), + new Tag(s_waterway, s_river, false), + new Tag(s_highway, s_cycleway, false), + new Tag(s_barrier, s_fence, false), + new Tag(s_building, s_residential, false), + new Tag(s_amenity, s_school, false), + new Tag(s_highway, s_crossing, false), + new Tag(s_admin_level, s_8, false), + new Tag(s_highway, s_trunk, false), + new Tag(s_amenity, s_place_of_worship, false), + new Tag(s_landuse, s_farmland, false), + new Tag(s_tracktype, s_grade1, false), + new Tag(s_highway, s_road, false), + new Tag(s_landuse, s_farm, false), + new Tag(s_surface, s_gravel, false), + new Tag(s_landuse, s_meadow, false), + new Tag(s_highway, s_motorway, false), + new Tag(s_highway, s_traffic_signals, false), + new Tag(s_building, s_hut, false), + new Tag(s_highway, s_motorway_link, false), + new Tag(s_tracktype, s_grade4, false), + new Tag(s_barrier, s_gate, false), + new Tag(s_highway, s_living_street, false), + new Tag(s_bicycle, s_no, false), + new Tag(s_leisure, s_pitch, false), + new Tag(s_tunnel, s_yes, false), + new Tag(s_surface, s_ground, false), + new Tag(s_highway, s_steps, false), + new Tag(s_natural, s_land, false), + new Tag(s_man_made, s_survey_point, false), + new Tag(s_tracktype, s_grade5, false), + new Tag(s_waterway, s_ditch, false), + new Tag(s_leisure, s_park, false), + new Tag(s_amenity, s_restaurant, false), + new Tag(s_barrier, s_wall, false), + new Tag(s_waterway, s_riverbank, false), + new Tag(s_amenity, s_bench, false), + new Tag(s_building, s_garage, false), + new Tag(s_natural, s_scrub, false), + new Tag(s_highway, s_pedestrian, false), + new Tag(s_natural, s_peak, false), + new Tag(s_building, s_entrance, false), + new Tag(s_landuse, s_reservoir, false), + new Tag(s_access, s_yes, false), + new Tag(s_bicycle, s_designated, false), + new Tag(s_leisure, s_swimming_pool, false), + new Tag(s_landuse, s_farmyard, false), + new Tag(s_railway, s_level_crossing, false), + new Tag(s_building, s_apartments, false), + new Tag(s_surface, s_grass, false), + new Tag(s_wheelchair, s_yes, false), + new Tag(s_service, s_alley, false), + new Tag(s_landuse, s_industrial, false), + new Tag(s_amenity, s_fuel, false), + new Tag(s_surface, s_dirt, false), + new Tag(s_highway, s_trunk_link, false), + new Tag(s_waterway, s_drain, false), + new Tag(s_barrier, s_hedge, false), + new Tag(s_amenity, s_grave_yard, false), + new Tag(s_tourism, s_information, false), + new Tag(s_shop, s_supermarket, false), + new Tag(s_highway, s_primary_link, false), + new Tag(s_wood, s_deciduous, false), + new Tag(s_leisure, s_playground, false), + new Tag(s_building, s_roof, false), + new Tag(s_building, s_industrial, false), + new Tag(s_amenity, s_post_box, false), + new Tag(s_waterway, s_canal, false), + new Tag(s_barrier, s_bollard, false), + new Tag(s_leisure, s_garden, false), + new Tag(s_wood, s_mixed, false), + new Tag(s_landuse, s_cemetery, false), + new Tag(s_landuse, s_orchard, false), + new Tag(s_shop, s_convenience, false), + new Tag(s_access, s_permissive, false), + new Tag(s_surface, s_concrete, false), + new Tag(s_surface, s_paving_stones, false), + new Tag(s_service, s_spur, false), + new Tag(s_building, s_garages, false), + new Tag(s_amenity, s_bank, false), + new Tag(s_tourism, s_hotel, false), + new Tag(s_access, s_no, false), + new Tag(s_amenity, s_fast_food, false), + new Tag(s_man_made, s_pier, false), + new Tag(s_amenity, s_kindergarten, false), + new Tag(s_access, s_agricultural, false), + new Tag(s_surface, s_cobblestone, false), + new Tag(s_wheelchair, s_no, false), + new Tag(s_amenity, s_cafe, false), + new Tag(s_amenity, s_hospital, false), + new Tag(s_amenity, s_post_office, false), + new Tag(s_amenity, s_public_building, false), + new Tag(s_amenity, s_recycling, false), + new Tag(s_highway, s_street_lamp, false), + new Tag(s_man_made, s_tower, false), + new Tag(s_waterway, s_dam, false), + new Tag(s_amenity, s_pub, false), + new Tag(s_wood, s_coniferous, false), + new Tag(s_access, s_destination, false), + new Tag(s_admin_level, s_6, false), + new Tag(s_landuse, s_commercial, false), + new Tag(s_amenity, s_pharmacy, false), + new Tag(s_railway, s_abandoned, false), + new Tag(s_service, s_yard, false), + new Tag(s_place, s_island, false), + new Tag(s_oneway, s__1, false), + new Tag(s_landuse, s_quarry, false), + new Tag(s_landuse, s_vineyard, false), + new Tag(s_highway, s_motorway_junction, false), + new Tag(s_railway, s_station, false), + new Tag(s_landuse, s_allotments, false), + new Tag(s_barrier, s_lift_gate, false), + new Tag(s_admin_level, s_10, false), + new Tag(s_amenity, s_telephone, false), + new Tag(s_place, s_town, false), + new Tag(s_man_made, s_cutline, false), + new Tag(s_place, s_suburb, false), + new Tag(s_aeroway, s_taxiway, false), + new Tag(s_wheelchair, s_limited, false), + new Tag(s_highway, s_secondary_link, false), + new Tag(s_leisure, s_sports_centre, false), + new Tag(s_amenity, s_bicycle_parking, false), + new Tag(s_surface, s_sand, false), + new Tag(s_highway, s_stop, false), + new Tag(s_man_made, s_works, false), + new Tag(s_landuse, s_retail, false), + new Tag(s_amenity, s_fire_station, false), + new Tag(s_service, s_siding, false), + new Tag(s_amenity, s_toilets, false), + new Tag(s_bench, s_yes, false), + new Tag(s_oneway, s_1, false), + new Tag(s_surface, s_compacted, false), + new Tag(s_landuse, s_basin, false), + new Tag(s_amenity, s_police, false), + new Tag(s_railway, s_tram, false), + new Tag(s_route, s_road, false), + new Tag(s_natural, s_cliff, false), + new Tag(s_highway, s_construction, false), + new Tag(s_aeroway, s_aerodrome, false), + new Tag(s_entrance, s_yes, false), + new Tag(s_man_made, s_storage_tank, false), + new Tag(s_amenity, s_atm, false), + new Tag(s_tourism, s_attraction, false), + new Tag(s_route, s_bus, false), + new Tag(s_shop, s_bakery, false), + new Tag(s_tourism, s_viewpoint, false), + new Tag(s_amenity, s_swimming_pool, false), + new Tag(s_natural, s_beach, false), + new Tag(s_tourism, s_picnic_site, false), + new Tag(s_oneway, s_true, false), + new Tag(s_highway, s_bridleway, false), + new Tag(s_tourism, s_camp_site, false), + new Tag(s_abutters, s_residential, false), + new Tag(s_leisure, s_nature_reserve, false), + new Tag(s_amenity, s_drinking_water, false), + new Tag(s_shop, s_clothes, false), + new Tag(s_natural, s_heath, false), + new Tag(s_highway, s_mini_roundabout, false), + new Tag(s_landuse, s_construction, false), + new Tag(s_amenity, s_waste_basket, false), + new Tag(s_railway, s_platform, false), + new Tag(s_amenity, s_townhall, false), + new Tag(s_shop, s_hairdresser, false), + new Tag(s_amenity, s_shelter, false), + new Tag(s_admin_level, s_9, false), + new Tag(s_building, s_farm_auxiliary, false), + new Tag(s_amenity, s_library, false), + new Tag(s_building, s_detached, false), + new Tag(s_admin_level, s_4, false), + new Tag(s_landuse, s_village_green, false), + new Tag(s_barrier, s_stile, false), + new Tag(s_landuse, s_garages, false), + new Tag(s_amenity, s_bar, false), + new Tag(s_railway, s_buffer_stop, false), + new Tag(s_wetland, s_marsh, false), + new Tag(s_tourism, s_museum, false), + new Tag(s_barrier, s_cycle_barrier, false), + new Tag(s_route, s_bicycle, false), + new Tag(s_railway, s_tram_stop, false), + new Tag(s_amenity, s_parking_space, false), + new Tag(s_barrier, s_retaining_wall, false), + new Tag(s_landuse, s_recreation_ground, false), + new Tag(s_amenity, s_university, false), + new Tag(s_highway, s_tertiary_link, false), + new Tag(s_building, s_terrace, false), + new Tag(s_shop, s_car_repair, false), + new Tag(s_amenity, s_hunting_stand, false), + new Tag(s_amenity, s_fountain, false), + new Tag(s_man_made, s_pipeline, false), + new Tag(s_wetland, s_swamp, false), + new Tag(s_shop, s_car, false), + new Tag(s_bench, s_no, false), + new Tag(s_tunnel, s_culvert, false), + new Tag(s_building, s_school, false), + new Tag(s_barrier, s_entrance, false), + new Tag(s_railway, s_disused, false), + new Tag(s_railway, s_crossing, false), + new Tag(s_building, s_church, false), + new Tag(s_amenity, s_social_facility, false), + new Tag(s_natural, s_bay, false), + new Tag(s_shop, s_kiosk, false), + new Tag(s_amenity, s_vending_machine, false), + new Tag(s_route, s_hiking, false), + new Tag(s_natural, s_spring, false), + new Tag(s_leisure, s_common, false), + new Tag(s_railway, s_switch, false), + new Tag(s_waterway, s_rapids, false), + new Tag(s_admin_level, s_7, false), + new Tag(s_leisure, s_stadium, false), + new Tag(s_leisure, s_track, false), + new Tag(s_place, s_isolated_dwelling, false), + new Tag(s_place, s_islet, false), + new Tag(s_waterway, s_weir, false), + new Tag(s_amenity, s_doctors, false), + new Tag(s_access, s_designated, false), + new Tag(s_landuse, s_conservation, false), + new Tag(s_waterway, s_artificial, false), + new Tag(s_amenity, s_bus_station, false), + new Tag(s_leisure, s_golf_course, false), + new Tag(s_shop, s_doityourself, false), + new Tag(s_building, s_service, false), + new Tag(s_tourism, s_guest_house, false), + new Tag(s_aeroway, s_runway, false), + new Tag(s_place, s_city, false), + new Tag(s_railway, s_subway, false), + new Tag(s_man_made, s_wastewater_plant, false), + new Tag(s_building, s_commercial, false), + new Tag(s_railway, s_halt, false), + new Tag(s_amenity, s_emergency_phone, false), + new Tag(s_building, s_retail, false), + new Tag(s_barrier, s_block, false), + new Tag(s_leisure, s_recreation_ground, false), + new Tag(s_access, s_forestry, false), + new Tag(s_amenity, s_college, false), + new Tag(s_highway, s_platform, false), + new Tag(s_access, s_unknown, false), + new Tag(s_man_made, s_water_tower, false), + new Tag(s_surface, s_pebblestone, false), + new Tag(s_bridge, s_viaduct, false), + new Tag(s_shop, s_butcher, false), + new Tag(s_shop, s_florist, false), + new Tag(s_boundary, s_landuse, false), + new Tag(s_aeroway, s_helipad, false), + new Tag(s_building, s_hangar, false), + new Tag(s_natural, s_glacier, false), + new Tag(s_highway, s_proposed, false), + new Tag(s_shop, s_mall, false), + new Tag(s_barrier, s_toll_booth, false), + new Tag(s_amenity, s_fire_hydrant, false), + new Tag(s_building, s_manufacture, false), + new Tag(s_building, s_farm, false), + new Tag(s_surface, s_wood, false), + new Tag(s_amenity, s_car_wash, false), + new Tag(s_amenity, s_dentist, false), + new Tag(s_natural, s_marsh, false), + new Tag(s_man_made, s_surveillance, false), + new Tag(s_shop, s_bicycle, false), + new Tag(s_route, s_foot, false), + new Tag(s_amenity, s_theatre, false), + new Tag(s_building, s_office, false), + new Tag(s_railway, s_light_rail, false), + new Tag(s_man_made, s_petroleum_well, false), + new Tag(s_amenity, s_taxi, false), + new Tag(s_building, s_greenhouse, false), + new Tag(s_landuse, s_brownfield, false), + new Tag(s_bicycle, s_permissive, false), + new Tag(s_admin_level, s_2, false), + new Tag(s_aeroway, s_apron, false), + new Tag(s_building, s_cabin, false), + new Tag(s_amenity, s_cinema, false), + new Tag(s_access, s_customers, false), + new Tag(s_tourism, s_motel, false), + new Tag(s_railway, s_narrow_gauge, false), + new Tag(s_amenity, s_marketplace, false), + new Tag(s_shop, s_furniture, false), + new Tag(s_entrance, s_staircase, false), + new Tag(s_tourism, s_artwork, false), + new Tag(s_natural, s_grassland, false), + new Tag(s_shop, s_books, false), + new Tag(s_admin_level, s_5, false), + new Tag(s_man_made, s_groyne, false), + new Tag(s_waterway, s_lock_gate, false), + new Tag(s_highway, s_emergency_access_point, false), + new Tag(s_natural, s_sand, false), + new Tag(s_landuse, s_military, false), + new Tag(s_boundary, s_protected_area, false), + new Tag(s_amenity, s_community_centre, false), + new Tag(s_barrier, s_kissing_gate, false), + new Tag(s_highway, s_speed_camera, false), + new Tag(s_boundary, s_national_park, false), + new Tag(s_railway, s_subway_entrance, false), + new Tag(s_man_made, s_silo, false), + new Tag(s_shop, s_alcohol, false), + new Tag(s_highway, s_give_way, false), + new Tag(s_leisure, s_slipway, false), + new Tag(s_shop, s_electronics, false), + new Tag(s_bicycle, s_dismount, false), + new Tag(s_leisure, s_marina, false), + new Tag(s_entrance, s_main, false), + new Tag(s_boundary, s_postal_code, false), + new Tag(s_landuse, s_greenhouse_horticulture, false), + new Tag(s_highway, s_milestone, false), + new Tag(s_natural, s_cave_entrance, false), + new Tag(s_landuse, s_landfill, false), + new Tag(s_shop, s_chemist, false), + new Tag(s_shop, s_shoes, false), + new Tag(s_barrier, s_cattle_grid, false), + new Tag(s_landuse, s_railway, false), + new Tag(s_tourism, s_hostel, false), + new Tag(s_tourism, s_chalet, false), + new Tag(s_place, s_county, false), + new Tag(s_shop, s_department_store, false), + new Tag(s_highway, s_ford, false), + new Tag(s_natural, s_scree, false), + new Tag(s_landuse, s_greenfield, false), + new Tag(s_amenity, s_nursing_home, false), + new Tag(s_barrier, s_wire_fence, false), + new Tag(s_access, s_restricted, false), + new Tag(s_man_made, s_reservoir_covered, false), + new Tag(s_amenity, s_bicycle_rental, false), + new Tag(s_man_made, s_MDF, false), + new Tag(s_man_made, s_water_well, false), + new Tag(s_landuse, s_field, false), + new Tag(s_landuse, s_wood, false), + new Tag(s_shop, s_hardware, false), + new Tag(s_tourism, s_alpine_hut, false), + new Tag(s_natural, s_tree_row, false), + new Tag(s_tourism, s_caravan_site, false), + new Tag(s_bridge, s_no, false), + new Tag(s_wetland, s_bog, false), + new Tag(s_amenity, s_courthouse, false), + new Tag(s_route, s_ferry, false), + new Tag(s_barrier, s_city_wall, false), + new Tag(s_amenity, s_veterinary, false), + new Tag(s_shop, s_jewelry, false), + new Tag(s_building, s_transportation, false), + new Tag(s_amenity, s_arts_centre, false), + new Tag(s_bicycle, s_official, false), + new Tag(s_shop, s_optician, false), + new Tag(s_shop, s_yes, false), + new Tag(s_building, s_collapsed, false), + new Tag(s_shop, s_garden_centre, false), + new Tag(s_man_made, s_chimney, false), + new Tag(s_man_made, s_mine, false), + new Tag(s_bench, s_unknown, false), + new Tag(s_railway, s_preserved, false), + new Tag(s_building, s_public, false), + new Tag(s_amenity, s_ferry_terminal, false), + new Tag(s_highway, s_raceway, false), + new Tag(s_natural, s_rock, false), + new Tag(s_tunnel, s_no, false), + new Tag(s_building, s_university, false), + new Tag(s_shop, s_beverages, false), + new Tag(s_amenity, s_waste_disposal, false), + new Tag(s_building, s_warehouse, false), + new Tag(s_leisure, s_water_park, false), + new Tag(s_shop, s_gift, false), + new Tag(s_place, s_farm, false), + new Tag(s_wetland, s_tidalflat, false), + new Tag(s_waterway, s_waterfall, false), + new Tag(s_man_made, s_dolphin, false), + new Tag(s_service, s_drive_through, false), + new Tag(s_amenity, s_nightclub, false), + new Tag(s_building, s_shed, false), + new Tag(s_shop, s_greengrocer, false), + new Tag(s_natural, s_fell, false), + new Tag(s_wetland, s_wet_meadow, false), + new Tag(s_aeroway, s_gate, false), + new Tag(s_shop, s_computer, false), + new Tag(s_man_made, s_lighthouse, false), + new Tag(s_wetland, s_reedbed, false), + new Tag(s_man_made, s_breakwater, false), + new Tag(s_surface, s_Dirt_Sand, false), + new Tag(s_barrier, s_ditch, false), + new Tag(s_barrier, s_yes, false), + new Tag(s_amenity, s_biergarten, false), + new Tag(s_shop, s_mobile_phone, false), + new Tag(s_route, s_mtb, false), + new Tag(s_amenity, s_grit_bin, false), + new Tag(s_amenity, s_bbq, false), + new Tag(s_shop, s_sports, false), + new Tag(s_barrier, s_wood_fence, false), + new Tag(s_entrance, s_home, false), + new Tag(s_shop, s_laundry, false), + new Tag(s_man_made, s_gasometer, false), + new Tag(s_barrier, s_embankment, false), + new Tag(s_shop, s_toys, false), + new Tag(s_wetland, s_saltmarsh, false), + new Tag(s_waterway, s_soakhole, false), + new Tag(s_shop, s_travel_agency, false), + new Tag(s_man_made, s_water_works, false), + new Tag(s_route, s_railway, false), + new Tag(s_amenity, s_prison, false), + new Tag(s_highway, s_rest_area, false), + new Tag(s_shop, s_stationery, false), + new Tag(s_admin_level, s_11, false), + new Tag(s_building, s_train_station, false), + new Tag(s_building, s_storage_tank, false), + new Tag(s_man_made, s_windmill, false), + new Tag(s_shop, s_beauty, false), + new Tag(s_building, s_semi, false), + new Tag(s_highway, s_services, false), + new Tag(s_bicycle, s_private, false), + new Tag(s_route, s_ski, false), + new Tag(s_service, s_emergency_access, false), + new Tag(s_building, s_factory, false), + new Tag(s_man_made, s_reinforced_slope, false), + new Tag(s_amenity, s_car_sharing, false), + new Tag(s_surface, s_earth, false), + new Tag(s_shop, s_hifi, false), + new Tag(s_amenity, s_car_rental, false), + new Tag(s_barrier, s_hedge_bank, false), + new Tag(s_shop, s_confectionery, false), + new Tag(s_aeroway, s_terminal, false), + new Tag(s_highway, s_passing_place, false), + new Tag(s_building, s_building, false), + new Tag(s_man_made, s_dyke, false), + new Tag(s_building, s_construction, false), + new Tag(s_building, s_shop, false), + new Tag(s_natural, s_reef, false), + new Tag(s_landuse, s_aquaculture, false), + new Tag(s_shop, s_dry_cleaning, false), + new Tag(s_amenity, s_embassy, false), + new Tag(s_shop, s_newsagent, false), + new Tag(s_landuse, s_salt_pond, false), + new Tag(s_railway, s_spur, false), + new Tag(s_wheelchair, s_unknown, false), + new Tag(s_tourism, s_zoo, false), + new Tag(s_man_made, s_waterway, false), + new Tag(s_surface, s_fine_gravel, false), + new Tag(s_shop, s_motorcycle, false), + new Tag(s_building, s_Building, false), + new Tag(s_railway, s_construction, false), + new Tag(s_place, s_neighbourhood, false), + new Tag(s_route, s_train, false), + new Tag(s_building, s_no, false), + new Tag(s_natural, s_mud, false), + new Tag(s_place, s_region, false), + new Tag(s_landuse, s_reservoir_watershed, false), + new Tag(s_boundary, s_marker, false), + new Tag(s_man_made, s_beacon, false), + new Tag(s_shop, s_outdoor, false), + new Tag(s_access, s_public, false), + new Tag(s_abutters, s_industrial, false), + new Tag(s_building, s_barn, false), + new Tag(s_leisure, s_picnic_table, false), + new Tag(s_building, s_hospital, false), + new Tag(s_access, s_official, false), + new Tag(s_shop, s_variety_store, false), + new Tag(s_man_made, s_crane, false), + new Tag(s_amenity, s_parking_fuel, false), + new Tag(s_route, s_tram, false), + new Tag(s_tourism, s_theme_park, false), + new Tag(s_shop, s_pet, false), + new Tag(s_building, s_kindergarten, false), + new Tag(s_man_made, s_storage, false), + new Tag(s_man_made, s_mast, false), + new Tag(s_amenity, s_parking_entrance, false), + new Tag(s_amenity, s_clock, false), + new Tag(s_landuse, s_industrial_retail, false), + new Tag(s_shop, s_video, false), + new Tag(s_access, s_delivery, false), + new Tag(s_amenity, s_driving_school, false), + new Tag(s_service, s_yes, false), + new Tag(s_natural, s_bare_rock, false), + new Tag(s_building, s_chapel, false), + new Tag(s_natural, s_volcano, false), + new Tag(s_waterway, s_dock, false), + new Tag(s_building, s_dormitory, false), + new Tag(s_amenity, s_boat_storage, false), + new Tag(s_man_made, s_tank, false), + new Tag(s_man_made, s_flagpole, false), + new Tag(s_surface, s_grass_paver, false), + new Tag(s_shop, s_organic, false), + new Tag(s_natural, s_landform, false), + new Tag(s_highway, s_unsurfaced, false), + new Tag(s_route, s_power, false), + new Tag(s_surface, s_mud, false), + new Tag(s_building, s_building_concrete, false), + new Tag(s_abutters, s_retail, false), + new Tag(s_building, s_store, false), + new Tag(s_shop, s_vacant, false), + new Tag(s_leisure, s_miniature_golf, false), + new Tag(s_man_made, s_monitoring_station, false), + new Tag(s_natural, s_waterfall, false), + new Tag(s_aeroway, s_hangar, false), + new Tag(s_shop, s_boutique, false), + new Tag(s_route, s_detour, false), + new Tag(s_building, s_way, false), + new Tag(s_railway, s_stop, false), + new Tag(s_amenity, s_ice_cream, false), + new Tag(s_building, s_storage, false), + new Tag(s_shop, s_car_parts, false), + new Tag(s_natural, s_ridge, false), + new Tag(s_shop, s_tyres, false), + new Tag(s_railway, s_dismantled, false), + new Tag(s_amenity, s_shop, false), + new Tag(s_landuse, s_plant_nursery, false), + new Tag(s_building, s_residentiel1, false), + new Tag(s_barrier, s_field_boundary, false), + new Tag(s_barrier, s_border_control, false), + new Tag(s_surface, s_Paved, false), + new Tag(s_barrier, s_sally_port, false), + new Tag(s_amenity, s_bureau_de_change, false), + new Tag(s_leisure, s_fishing, false), + new Tag(s_amenity, s_charging_station, false), + new Tag(s_building, s_supermarket, false), + new Tag(s_highway, s_stile, false), + new Tag(s_amenity, s_sauna, false), + new Tag(s_place, s_municipality, false), + new Tag(s_building, s_hotel, false), + new Tag(s_surface, s_metal, false), + new Tag(s_highway, s_incline_steep, false), + new Tag(s_shop, s_estate_agent, false), + new Tag(s_natural, s_grass, false), + new Tag(s_shop, s_pharmacy, false), + new Tag(s_surface, s_concrete_plates, false), + new Tag(s_shop, s_copyshop, false), + new Tag(s_surface, s_paving_stones_30, false), + new Tag(s_surface, s_interlock, false), + new Tag(s_access, s_hov, false), + new Tag(s_highway, s_elevator, false), + new Tag(s_boundary, s_local_authority, false), + new Tag(s_man_made, s_communications_tower, false), + new Tag(s_shop, s_deli, false), + new Tag(s_barrier, s_turnstile, false), + new Tag(s_building, s_offices, false), + new Tag(s_building, s_bunker, false), + new Tag(s_natural, s_stone, false), + new Tag(s_railway, s_railway_crossing, false), + new Tag(s_leisure, s_dog_park, false), + new Tag(s_building, s_semi_detached, false), + new Tag(s_man_made, s_watermill, false), + new Tag(s_route, s_trolleybus, false), + new Tag(s_admin_level, s_3, false), + new Tag(s_building, s_block, false), + new Tag(s_barrier, s_guard_rail, false), + new Tag(s_bicycle, s_unknown, false), + new Tag(s_highway, s_abandoned, false), + new Tag(s_surface, s_dirt_sand, false), + new Tag(s_barrier, s_chain, false), + new Tag(s_barrier, s_bump_gate, false), + new Tag(s_building, s_residental, false), + new Tag(s_surface, s_cement, false), + new Tag(s_man_made, s_embankment, false), + new Tag(s_building, s_ruins, false), + new Tag(s_highway, s_incline, false), + new Tag(s_abutters, s_commercial, false), + new Tag(s_barrier, s_hampshire_gate, false), + new Tag(s_shop, s_music, false), + new Tag(s_shop, s_funeral_directors, false), + new Tag(s_wetland, s_mangrove, false), + new Tag(s_place, s_borough, false), + new Tag(s_building, s_apartment, false), + new Tag(s_boundary, s_census, false), + new Tag(s_barrier, s_kerb, false), + new Tag(s_building, s_glasshouse, false), + new Tag(s_aeroway, s_holding_position, false), + new Tag(s_shop, s_general, false), + new Tag(s_building, s_tank, false), + new Tag(s_railway, s_monorail, false), + new Tag(s_service, s_parking, false), + new Tag(s_place, s_state, false), + new Tag(s_railway, s_proposed, false), + new Tag(s_shop, s_art, false), + new Tag(s_natural, s_hill, false), + new Tag(s_railway, s_turntable, false), + new Tag(s_tourism, s_cabin, false), + new Tag(s_shop, s_photo, false), + new Tag(s_boundary, s_lot, false), + new Tag(s_shop, s_fishmonger, false), + new Tag(s_amenity, s_clinic, false), + new Tag(s_boundary, s_political, false), + new Tag(s_man_made, s_well, false), + new Tag(s_highway, s_byway, false), + new Tag(s_leisure, s_horse_riding, false), + new Tag(s_service, s_bus, false), + new Tag(s_building, s_tower, false), + new Tag(s_entrance, s_service, false), + new Tag(s_shop, s_fabric, false), + new Tag(s_railway, s_miniature, false), + new Tag(s_abutters, s_mixed, false), + new Tag(s_surface, s_stone, false), + new Tag(s_access, s_emergency, false), + new Tag(s_landuse, s_mine, false), + new Tag(s_amenity, s_shower, false), + new Tag(s_waterway, s_lock, false), + new Tag(s_area, s_yes, false), + new Tag(s_landuse, s_urban, false), + }; } diff --git a/vtm-extras/src/org/oscim/utils/Triangulator.java b/vtm-extras/src/org/oscim/utils/Triangulator.java index 0f9291d0..d09b8ba9 100644 --- a/vtm-extras/src/org/oscim/utils/Triangulator.java +++ b/vtm-extras/src/org/oscim/utils/Triangulator.java @@ -5,362 +5,376 @@ import java.util.ArrayList; /** * Triangulates a polygon into triangles - duh. Doesn't handle * holes in polys - * + * * @author Public Source from FlipCode */ public class Triangulator { - /** The accepted error value */ - private static final float EPSILON = 0.0000000001f; - /** The list of points to be triangulated */ - private final PointList poly = new PointList(); - /** The list of points describing the triangles */ - private final PointList tris = new PointList(); - /** True if we've tried to triangulate */ - private boolean tried; + /** + * The accepted error value + */ + private static final float EPSILON = 0.0000000001f; + /** + * The list of points to be triangulated + */ + private final PointList poly = new PointList(); + /** + * The list of points describing the triangles + */ + private final PointList tris = new PointList(); + /** + * True if we've tried to triangulate + */ + private boolean tried; - /** - * Create a new triangulator - */ - public Triangulator() { - } + /** + * Create a new triangulator + */ + public Triangulator() { + } - /** - * Add a point describing the polygon to be triangulated - * - * @param x The x coordinate of the point - * @param y the y coordinate of the point - */ - public void addPolyPoint(float x, float y) { - poly.add(new Point(x, y)); - } + /** + * Add a point describing the polygon to be triangulated + * + * @param x The x coordinate of the point + * @param y the y coordinate of the point + */ + public void addPolyPoint(float x, float y) { + poly.add(new Point(x, y)); + } - /** - * Cause the triangulator to split the polygon - * - * @return True if we managed the task - */ - public boolean triangulate() { - tried = true; + /** + * Cause the triangulator to split the polygon + * + * @return True if we managed the task + */ + public boolean triangulate() { + tried = true; - boolean worked = process(poly, tris); - return worked; - } + boolean worked = process(poly, tris); + return worked; + } - /** - * Get a count of the number of triangles produced - * - * @return The number of triangles produced - */ - public int getTriangleCount() { - if (!tried) { - throw new RuntimeException("Call triangulate() before accessing triangles"); - } - return tris.size() / 3; - } + /** + * Get a count of the number of triangles produced + * + * @return The number of triangles produced + */ + public int getTriangleCount() { + if (!tried) { + throw new RuntimeException("Call triangulate() before accessing triangles"); + } + return tris.size() / 3; + } - /** - * Get a point on a specified generated triangle - * - * @param tri The index of the triangle to interegate - * @param i The index of the point within the triangle to retrieve - * (0 - 2) - * @return The x,y coordinate pair for the point - */ - public float[] getTrianglePoint(int tri, int i) { - if (!tried) { - throw new RuntimeException("Call triangulate() before accessing triangles"); - } - return tris.get((tri * 3) + i).toArray(); - } + /** + * Get a point on a specified generated triangle + * + * @param tri The index of the triangle to interegate + * @param i The index of the point within the triangle to retrieve + * (0 - 2) + * @return The x,y coordinate pair for the point + */ + public float[] getTrianglePoint(int tri, int i) { + if (!tried) { + throw new RuntimeException("Call triangulate() before accessing triangles"); + } + return tris.get((tri * 3) + i).toArray(); + } - /** - * Find the area of a polygon defined by the series of points - * in the list - * - * @param contour The list of points defined the contour of the polygon - * (Vector2f) - * @return The area of the polygon defined - */ - private static float area(PointList contour) { - int n = contour.size(); + /** + * Find the area of a polygon defined by the series of points + * in the list + * + * @param contour The list of points defined the contour of the polygon + * (Vector2f) + * @return The area of the polygon defined + */ + private static float area(PointList contour) { + int n = contour.size(); - float A = 0.0f; + float A = 0.0f; - for (int p = n - 1, q = 0; q < n; p = q++) { - Point contourP = contour.get(p); - Point contourQ = contour.get(q); + for (int p = n - 1, q = 0; q < n; p = q++) { + Point contourP = contour.get(p); + Point contourQ = contour.get(q); - A += contourP.getX() * contourQ.getY() - contourQ.getX() - * contourP.getY(); - } - return A * 0.5f; - } + A += contourP.getX() * contourQ.getY() - contourQ.getX() + * contourP.getY(); + } + return A * 0.5f; + } - /** - * Check if the point P is inside the triangle defined by - * the points A,B,C - * - * @param Ax Point A x-coordinate - * @param Ay Point A y-coordinate - * @param Bx Point B x-coordinate - * @param By Point B y-coordinate - * @param Cx Point C x-coordinate - * @param Cy Point C y-coordinate - * @param Px Point P x-coordinate - * @param Py Point P y-coordinate - * @return True if the point specified is within the triangle - */ - private static boolean insideTriangle(float Ax, float Ay, float Bx, - float By, float Cx, float Cy, float Px, float Py) { - float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; - float cCROSSap, bCROSScp, aCROSSbp; + /** + * Check if the point P is inside the triangle defined by + * the points A,B,C + * + * @param Ax Point A x-coordinate + * @param Ay Point A y-coordinate + * @param Bx Point B x-coordinate + * @param By Point B y-coordinate + * @param Cx Point C x-coordinate + * @param Cy Point C y-coordinate + * @param Px Point P x-coordinate + * @param Py Point P y-coordinate + * @return True if the point specified is within the triangle + */ + private static boolean insideTriangle(float Ax, float Ay, float Bx, + float By, float Cx, float Cy, float Px, float Py) { + float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; + float cCROSSap, bCROSScp, aCROSSbp; - ax = Cx - Bx; - ay = Cy - By; - bx = Ax - Cx; - by = Ay - Cy; - cx = Bx - Ax; - cy = By - Ay; - apx = Px - Ax; - apy = Py - Ay; - bpx = Px - Bx; - bpy = Py - By; - cpx = Px - Cx; - cpy = Py - Cy; + ax = Cx - Bx; + ay = Cy - By; + bx = Ax - Cx; + by = Ay - Cy; + cx = Bx - Ax; + cy = By - Ay; + apx = Px - Ax; + apy = Py - Ay; + bpx = Px - Bx; + bpy = Py - By; + cpx = Px - Cx; + cpy = Py - Cy; - aCROSSbp = ax * bpy - ay * bpx; - cCROSSap = cx * apy - cy * apx; - bCROSScp = bx * cpy - by * cpx; + aCROSSbp = ax * bpy - ay * bpx; + cCROSSap = cx * apy - cy * apx; + bCROSScp = bx * cpy - by * cpx; - return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); - } + return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); + } - /** - * Cut a the contour and add a triangle into V to describe the - * location of the cut - * - * @param contour The list of points defining the polygon - * @param u The index of the first point - * @param v The index of the second point - * @param w The index of the third point - * @param n ? - * @param V The array to populate with indicies of triangles - * @return True if a triangle was found - */ - private static boolean snip(PointList contour, int u, int v, int w, int n, - int[] V) { - int p; - float Ax, Ay, Bx, By, Cx, Cy, Px, Py; + /** + * Cut a the contour and add a triangle into V to describe the + * location of the cut + * + * @param contour The list of points defining the polygon + * @param u The index of the first point + * @param v The index of the second point + * @param w The index of the third point + * @param n ? + * @param V The array to populate with indicies of triangles + * @return True if a triangle was found + */ + private static boolean snip(PointList contour, int u, int v, int w, int n, + int[] V) { + int p; + float Ax, Ay, Bx, By, Cx, Cy, Px, Py; - Ax = contour.get(V[u]).getX(); - Ay = contour.get(V[u]).getY(); + Ax = contour.get(V[u]).getX(); + Ay = contour.get(V[u]).getY(); - Bx = contour.get(V[v]).getX(); - By = contour.get(V[v]).getY(); + Bx = contour.get(V[v]).getX(); + By = contour.get(V[v]).getY(); - Cx = contour.get(V[w]).getX(); - Cy = contour.get(V[w]).getY(); + Cx = contour.get(V[w]).getX(); + Cy = contour.get(V[w]).getY(); - if (EPSILON > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax)))) { - return false; - } + if (EPSILON > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax)))) { + return false; + } - for (p = 0; p < n; p++) { - if ((p == u) || (p == v) || (p == w)) { - continue; - } + for (p = 0; p < n; p++) { + if ((p == u) || (p == v) || (p == w)) { + continue; + } - Px = contour.get(V[p]).getX(); - Py = contour.get(V[p]).getY(); + Px = contour.get(V[p]).getX(); + Py = contour.get(V[p]).getY(); - if (insideTriangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py)) { - return false; - } - } + if (insideTriangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py)) { + return false; + } + } - return true; - } + return true; + } - /** - * Process a list of points defining a polygon - * - * @param contour The list of points describing the polygon - * @param result The list of points describing the triangles. Groups - * of 3 describe each triangle - * @return True if we succeeded in completing triangulation - */ - private static boolean process(PointList contour, PointList result) { - /* allocate and initialize list of Vertices in polygon */ + /** + * Process a list of points defining a polygon + * + * @param contour The list of points describing the polygon + * @param result The list of points describing the triangles. Groups + * of 3 describe each triangle + * @return True if we succeeded in completing triangulation + */ + private static boolean process(PointList contour, PointList result) { + /* allocate and initialize list of Vertices in polygon */ - int n = contour.size(); - if (n < 3) - return false; + int n = contour.size(); + if (n < 3) + return false; - int[] V = new int[n]; + int[] V = new int[n]; /* we want a counter-clockwise polygon in V */ - if (0.0f < area(contour)) { - for (int v = 0; v < n; v++) - V[v] = v; - } else { - for (int v = 0; v < n; v++) - V[v] = (n - 1) - v; - } + if (0.0f < area(contour)) { + for (int v = 0; v < n; v++) + V[v] = v; + } else { + for (int v = 0; v < n; v++) + V[v] = (n - 1) - v; + } - int nv = n; + int nv = n; /* remove nv-2 Vertices, creating 1 triangle every time */ - int count = 2 * nv; /* error detection */ + int count = 2 * nv; /* error detection */ - //for (int m = 0, v = nv - 1; nv > 2;) { - for (int v = nv - 1; nv > 2;) { - /* if we loop, it is probably a non-simple polygon */ - if (0 >= (count--)) { - //** Triangulate: ERROR - probable bad polygon! - return false; - } + //for (int m = 0, v = nv - 1; nv > 2;) { + for (int v = nv - 1; nv > 2; ) { + /* if we loop, it is probably a non-simple polygon */ + if (0 >= (count--)) { + //** Triangulate: ERROR - probable bad polygon! + return false; + } /* three consecutive vertices in current polygon, */ - int u = v; - if (nv <= u) - u = 0; /* previous */ - v = u + 1; - if (nv <= v) - v = 0; /* new v */ - int w = v + 1; - if (nv <= w) - w = 0; /* next */ + int u = v; + if (nv <= u) + u = 0; /* previous */ + v = u + 1; + if (nv <= v) + v = 0; /* new v */ + int w = v + 1; + if (nv <= w) + w = 0; /* next */ - if (snip(contour, u, v, w, nv, V)) { - int a, b, c, s, t; + if (snip(contour, u, v, w, nv, V)) { + int a, b, c, s, t; /* true names of the vertices */ - a = V[u]; - b = V[v]; - c = V[w]; + a = V[u]; + b = V[v]; + c = V[w]; /* output Triangle */ - result.add(contour.get(a)); - result.add(contour.get(b)); - result.add(contour.get(c)); + result.add(contour.get(a)); + result.add(contour.get(b)); + result.add(contour.get(c)); - //m++; + //m++; /* remove v from remaining polygon */ - for (s = v, t = v + 1; t < nv; s++, t++) { - V[s] = V[t]; - } - nv--; + for (s = v, t = v + 1; t < nv; s++, t++) { + V[s] = V[t]; + } + nv--; /* resest error detection counter */ - count = 2 * nv; - } - } + count = 2 * nv; + } + } - return true; - } + return true; + } - /** - * A single point handled by the triangulator - * - * @author Kevin Glass - */ - private class Point { - /** The x coorindate of this point */ - private final float x; - /** The y coorindate of this point */ - private final float y; + /** + * A single point handled by the triangulator + * + * @author Kevin Glass + */ + private class Point { + /** + * The x coorindate of this point + */ + private final float x; + /** + * The y coorindate of this point + */ + private final float y; - /** - * Create a new point - * - * @param x The x coordindate of the point - * @param y The y coordindate of the point - */ - public Point(float x, float y) { - this.x = x; - this.y = y; - } + /** + * Create a new point + * + * @param x The x coordindate of the point + * @param y The y coordindate of the point + */ + public Point(float x, float y) { + this.x = x; + this.y = y; + } - /** - * Get the x coordinate of the point - * - * @return The x coordinate of the point - */ - public float getX() { - return x; - } + /** + * Get the x coordinate of the point + * + * @return The x coordinate of the point + */ + public float getX() { + return x; + } - /** - * Get the y coordinate of the point - * - * @return The y coordinate of the point - */ - public float getY() { - return y; - } + /** + * Get the y coordinate of the point + * + * @return The y coordinate of the point + */ + public float getY() { + return y; + } - /** - * Convert this point into a float array - * - * @return The contents of this point as a float array - */ - public float[] toArray() { - return new float[] { x, y }; - } - } + /** + * Convert this point into a float array + * + * @return The contents of this point as a float array + */ + public float[] toArray() { + return new float[]{x, y}; + } + } - /** - * A list of type Point - * - * @author Kevin Glass - */ - private class PointList { - /** The list of points */ - private final ArrayList points = new ArrayList(); + /** + * A list of type Point + * + * @author Kevin Glass + */ + private class PointList { + /** + * The list of points + */ + private final ArrayList points = new ArrayList(); - /** - * Create a new empty list - */ - public PointList() { - } + /** + * Create a new empty list + */ + public PointList() { + } - /** - * Add a point to the list - * - * @param point The point to add - */ - public void add(Point point) { - points.add(point); - } + /** + * Add a point to the list + * + * @param point The point to add + */ + public void add(Point point) { + points.add(point); + } - ///** - // * Remove a point from the list - // * - // * @param point The point to remove - // */ - //public void remove(Point point) { - // points.remove(point); - //} + ///** + // * Remove a point from the list + // * + // * @param point The point to remove + // */ + //public void remove(Point point) { + // points.remove(point); + //} - /** - * Get the size of the list - * - * @return The size of the list - */ - public int size() { - return points.size(); - } + /** + * Get the size of the list + * + * @return The size of the list + */ + public int size() { + return points.size(); + } - /** - * Get a point a specific index in the list - * - * @param i The index of the point to retrieve - * @return The point - */ - public Point get(int i) { - return points.get(i); - } - } + /** + * Get a point a specific index in the list + * + * @param i The index of the point to retrieve + * @return The point + */ + public Point get(int i) { + return points.get(i); + } + } } diff --git a/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfParser.java b/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfParser.java index 248585ea..eee264fa 100644 --- a/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfParser.java +++ b/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfParser.java @@ -17,10 +17,6 @@ package org.oscim.utils.osmpbf; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import org.openstreetmap.osmosis.osmbinary.BinaryParser; import org.openstreetmap.osmosis.osmbinary.Osmformat; import org.oscim.core.Tag; @@ -31,303 +27,309 @@ import org.oscim.core.osm.OsmNode; import org.oscim.core.osm.OsmRelation; import org.oscim.core.osm.OsmWay; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + /** * Class that reads and parses binary files and sends the contained entities to * the sink. */ public class OsmPbfParser extends BinaryParser { - @Override - public void complete() { - //sink.complete(); - } + @Override + public void complete() { + //sink.complete(); + } - // /** Get the osmosis object representing a the user in a given Info protobuf. - // * @param info The info protobuf. - // * @return The OsmUser object */ - // OsmUser getUser(Osmformat.Info info) { - // // System.out.println(info); - // if (info.hasUid() && info.hasUserSid()) { - // if (info.getUid() < 0) { - // return OsmUser.NONE; - // } - // return new OsmUser(info.getUid(), getStringById(info.getUserSid())); - // } else { - // return OsmUser.NONE; - // } - // } + // /** Get the osmosis object representing a the user in a given Info protobuf. + // * @param info The info protobuf. + // * @return The OsmUser object */ + // OsmUser getUser(Osmformat.Info info) { + // // System.out.println(info); + // if (info.hasUid() && info.hasUserSid()) { + // if (info.getUid() < 0) { + // return OsmUser.NONE; + // } + // return new OsmUser(info.getUid(), getStringById(info.getUserSid())); + // } else { + // return OsmUser.NONE; + // } + // } - /** - * The magic number used to indicate no version number metadata for this - * entity. - */ - static final int NOVERSION = -1; - /** The magic number used to indicate no changeset metadata for this entity. */ - static final int NOCHANGESET = -1; + /** + * The magic number used to indicate no version number metadata for this + * entity. + */ + static final int NOVERSION = -1; + /** + * The magic number used to indicate no changeset metadata for this entity. + */ + static final int NOCHANGESET = -1; - HashMap mNodeMap = new HashMap(); - HashMap mWayMap = new HashMap(); + HashMap mNodeMap = new HashMap(); + HashMap mWayMap = new HashMap(); - @Override - protected void parseNodes(List nodes) { - for (Osmformat.Node i : nodes) { - int tagCnt = i.getKeysCount(); + @Override + protected void parseNodes(List nodes) { + for (Osmformat.Node i : nodes) { + int tagCnt = i.getKeysCount(); - TagSet tags = new TagSet(tagCnt); + TagSet tags = new TagSet(tagCnt); - // List tags = new ArrayList(); - for (int j = 0; j < tagCnt; j++) { - tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); - } - // long id, int version, Date timestamp, OsmUser user, - // long changesetId, Collection tags, - // double latitude, double longitude - OsmNode tmp; - long id = i.getId(); - double latf = parseLat(i.getLat()), lonf = parseLon(i.getLon()); + // List tags = new ArrayList(); + for (int j = 0; j < tagCnt; j++) { + tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); + } + // long id, int version, Date timestamp, OsmUser user, + // long changesetId, Collection tags, + // double latitude, double longitude + OsmNode tmp; + long id = i.getId(); + double latf = parseLat(i.getLat()), lonf = parseLon(i.getLon()); - // if (i.hasInfo()) { - // Osmformat.Info info = i.getInfo(); - // tmp = new OsmNode(new CommonEntityData(id, info.getVersion(), getDate(info), - // getUser(info), info.getChangeset(), tags), latf, lonf); - // } else { - tmp = new OsmNode(latf, lonf, tags, id); - // tmp = new Node(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE, - // NOCHANGESET, tags), latf, lonf); - // } - //sink.process(new NodeContainer(tmp)); - mNodeMap.put(Long.valueOf(id), tmp); - } - } + // if (i.hasInfo()) { + // Osmformat.Info info = i.getInfo(); + // tmp = new OsmNode(new CommonEntityData(id, info.getVersion(), getDate(info), + // getUser(info), info.getChangeset(), tags), latf, lonf); + // } else { + tmp = new OsmNode(latf, lonf, tags, id); + // tmp = new Node(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE, + // NOCHANGESET, tags), latf, lonf); + // } + //sink.process(new NodeContainer(tmp)); + mNodeMap.put(Long.valueOf(id), tmp); + } + } - @Override - protected void parseDense(Osmformat.DenseNodes nodes) { - long lastId = 0, lastLat = 0, lastLon = 0; + @Override + protected void parseDense(Osmformat.DenseNodes nodes) { + long lastId = 0, lastLat = 0, lastLon = 0; - int j = 0; // Index into the keysvals array. + int j = 0; // Index into the keysvals array. - // Stuff for dense info - // long lasttimestamp = 0, lastchangeset = 0; - // int lastuserSid = 0, lastuid = 0; - // DenseInfo di = null; - // if (nodes.hasDenseinfo()) { - // di = nodes.getDenseinfo(); - // } + // Stuff for dense info + // long lasttimestamp = 0, lastchangeset = 0; + // int lastuserSid = 0, lastuid = 0; + // DenseInfo di = null; + // if (nodes.hasDenseinfo()) { + // di = nodes.getDenseinfo(); + // } - for (int i = 0; i < nodes.getIdCount(); i++) { - OsmNode tmp; - TagSet tags = new TagSet(4); - long lat = nodes.getLat(i) + lastLat; - lastLat = lat; - long lon = nodes.getLon(i) + lastLon; - lastLon = lon; - long id = nodes.getId(i) + lastId; - lastId = id; - double latf = parseLat(lat), lonf = parseLon(lon); - // If empty, assume that nothing here has keys or vals. - if (nodes.getKeysValsCount() > 0) { - while (nodes.getKeysVals(j) != 0) { - int keyid = nodes.getKeysVals(j++); - int valid = nodes.getKeysVals(j++); - tags.add(new Tag(getStringById(keyid), getStringById(valid))); - } - j++; // Skip over the '0' delimiter. - } - // Handle dense info. - // if (di != null) { - // int uid = di.getUid(i) + lastuid; lastuid = uid; - // int userSid = di.getUserSid(i) + lastuserSid; lastuserSid = userSid; - // long timestamp = di.getTimestamp(i) + lasttimestamp; lasttimestamp = timestamp; - // int version = di.getVersion(i); - // long changeset = di.getChangeset(i) + lastchangeset; lastchangeset = changeset; - // - // Date date = new Date(date_granularity * timestamp); + for (int i = 0; i < nodes.getIdCount(); i++) { + OsmNode tmp; + TagSet tags = new TagSet(4); + long lat = nodes.getLat(i) + lastLat; + lastLat = lat; + long lon = nodes.getLon(i) + lastLon; + lastLon = lon; + long id = nodes.getId(i) + lastId; + lastId = id; + double latf = parseLat(lat), lonf = parseLon(lon); + // If empty, assume that nothing here has keys or vals. + if (nodes.getKeysValsCount() > 0) { + while (nodes.getKeysVals(j) != 0) { + int keyid = nodes.getKeysVals(j++); + int valid = nodes.getKeysVals(j++); + tags.add(new Tag(getStringById(keyid), getStringById(valid))); + } + j++; // Skip over the '0' delimiter. + } + // Handle dense info. + // if (di != null) { + // int uid = di.getUid(i) + lastuid; lastuid = uid; + // int userSid = di.getUserSid(i) + lastuserSid; lastuserSid = userSid; + // long timestamp = di.getTimestamp(i) + lasttimestamp; lasttimestamp = timestamp; + // int version = di.getVersion(i); + // long changeset = di.getChangeset(i) + lastchangeset; lastchangeset = changeset; + // + // Date date = new Date(date_granularity * timestamp); - //OsmUser user; - // if (uid < 0) { - // user = OsmUser.NONE; - // } else { - // user = new OsmUser(uid, getStringById(userSid)); - // } - // - // tmp = new OsmNode(id, tags, latf, lonf); - // } else { - tmp = new OsmNode(latf, lonf, tags, id); + //OsmUser user; + // if (uid < 0) { + // user = OsmUser.NONE; + // } else { + // user = new OsmUser(uid, getStringById(userSid)); + // } + // + // tmp = new OsmNode(id, tags, latf, lonf); + // } else { + tmp = new OsmNode(latf, lonf, tags, id); - mNodeMap.put(Long.valueOf(id), tmp); + mNodeMap.put(Long.valueOf(id), tmp); - // } + // } - //sink.process(new NodeContainer(tmp)); - } - } + //sink.process(new NodeContainer(tmp)); + } + } - @Override - protected void parseWays(List ways) { - for (Osmformat.Way i : ways) { - int tagCnt = i.getKeysCount(); - TagSet tags = new TagSet(tagCnt); + @Override + protected void parseWays(List ways) { + for (Osmformat.Way i : ways) { + int tagCnt = i.getKeysCount(); + TagSet tags = new TagSet(tagCnt); - // List tags = new ArrayList(); - for (int j = 0; j < tagCnt; j++) { - tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); - } - // List tags = new ArrayList(); - // for (int j = 0; j < ; j++) { - // tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); - // } + // List tags = new ArrayList(); + for (int j = 0; j < tagCnt; j++) { + tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); + } + // List tags = new ArrayList(); + // for (int j = 0; j < ; j++) { + // tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); + // } - long lastId = 0; - List nodes = new ArrayList(); - for (long j : i.getRefsList()) { - OsmNode n = mNodeMap.get(Long.valueOf(j + lastId)); - if (n == null) - n = new OsmNode(Double.NaN, Double.NaN, null, j + lastId); + long lastId = 0; + List nodes = new ArrayList(); + for (long j : i.getRefsList()) { + OsmNode n = mNodeMap.get(Long.valueOf(j + lastId)); + if (n == null) + n = new OsmNode(Double.NaN, Double.NaN, null, j + lastId); - nodes.add(n); - lastId = j + lastId; - } + nodes.add(n); + lastId = j + lastId; + } - long id = i.getId(); + long id = i.getId(); - // long id, int version, Date timestamp, OsmUser user, - // long changesetId, Collection tags, - // List wayNodes - OsmWay tmp; - // if (i.hasInfo()) { - // Osmformat.Info info = i.getInfo(); - // tmp = new Way(new CommonEntityData(id, info.getVersion(), getDate(info), - // getUser(info), info.getChangeset(), tags), nodes); - // } else { - tmp = new OsmWay(tags, id, nodes); - // } + // long id, int version, Date timestamp, OsmUser user, + // long changesetId, Collection tags, + // List wayNodes + OsmWay tmp; + // if (i.hasInfo()) { + // Osmformat.Info info = i.getInfo(); + // tmp = new Way(new CommonEntityData(id, info.getVersion(), getDate(info), + // getUser(info), info.getChangeset(), tags), nodes); + // } else { + tmp = new OsmWay(tags, id, nodes); + // } - mWayMap.put(Long.valueOf(id), tmp); + mWayMap.put(Long.valueOf(id), tmp); - //sink.process(new WayContainer(tmp)); - } - } + //sink.process(new WayContainer(tmp)); + } + } - @Override - protected void parseRelations(List rels) { - for (Osmformat.Relation i : rels) { - int tagCnt = i.getKeysCount(); - TagSet tags = new TagSet(tagCnt); + @Override + protected void parseRelations(List rels) { + for (Osmformat.Relation i : rels) { + int tagCnt = i.getKeysCount(); + TagSet tags = new TagSet(tagCnt); - for (int j = 0; j < tagCnt; j++) - tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); + for (int j = 0; j < tagCnt; j++) + tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j)))); - long id = i.getId(); + long id = i.getId(); - long lastMid = 0; - List nodes = new ArrayList(); - int memberCnt = i.getMemidsCount(); + long lastMid = 0; + List nodes = new ArrayList(); + int memberCnt = i.getMemidsCount(); - // for (int j = 0; j < memberCnt; j++) { - // long mid = lastMid + i.getMemids(j); - // lastMid = mid; - // String role = getStringById(i.getRolesSid(j)); - // - // Osmformat.Relation.MemberType t = i.getTypes(j); - // - // if (t == Osmformat.Relation.MemberType.NODE) { - // etype = EntityType.Node; - // } else if (t == Osmformat.Relation.MemberType.WAY) { - // etype = EntityType.Way; - // } else if (t == Osmformat.Relation.MemberType.RELATION) { - // etype = EntityType.Relation; - // } else { - // assert false; // TODO; Illegal file? - // } - // - // nodes.add(new OsmMember(mid, etype, role)); - // } + // for (int j = 0; j < memberCnt; j++) { + // long mid = lastMid + i.getMemids(j); + // lastMid = mid; + // String role = getStringById(i.getRolesSid(j)); + // + // Osmformat.Relation.MemberType t = i.getTypes(j); + // + // if (t == Osmformat.Relation.MemberType.NODE) { + // etype = EntityType.Node; + // } else if (t == Osmformat.Relation.MemberType.WAY) { + // etype = EntityType.Way; + // } else if (t == Osmformat.Relation.MemberType.RELATION) { + // etype = EntityType.Relation; + // } else { + // assert false; // TODO; Illegal file? + // } + // + // nodes.add(new OsmMember(mid, etype, role)); + // } - // long id, int version, TimestampContainer timestampContainer, - // OsmUser user, - // long changesetId, Collection tags, - // List members - OsmRelation tmp = new OsmRelation(tags, id, memberCnt); + // long id, int version, TimestampContainer timestampContainer, + // OsmUser user, + // long changesetId, Collection tags, + // List members + OsmRelation tmp = new OsmRelation(tags, id, memberCnt); - // if (i.hasInfo()) { - // Osmformat.Info info = i.getInfo(); - // tmp = new Relation(new CommonEntityData(id, info.getVersion(), getDate(info), - // getUser(info), info.getChangeset(), tags), nodes); - // } else { - // tmp = new Relation(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE, - // NOCHANGESET, tags), nodes); - // } - // sink.process(new RelationContainer(tmp)); - } - } + // if (i.hasInfo()) { + // Osmformat.Info info = i.getInfo(); + // tmp = new Relation(new CommonEntityData(id, info.getVersion(), getDate(info), + // getUser(info), info.getChangeset(), tags), nodes); + // } else { + // tmp = new Relation(new CommonEntityData(id, NOVERSION, NODATE, OsmUser.NONE, + // NOCHANGESET, tags), nodes); + // } + // sink.process(new RelationContainer(tmp)); + } + } - @Override - public void parse(Osmformat.HeaderBlock block) { - for (String s : block.getRequiredFeaturesList()) { - if (s.equals("OsmSchema-V0.6")) { - continue; // We can parse this. - } - if (s.equals("DenseNodes")) { - continue; // We can parse this. - } - throw new RuntimeException("File requires unknown feature: " + s); - } + @Override + public void parse(Osmformat.HeaderBlock block) { + for (String s : block.getRequiredFeaturesList()) { + if (s.equals("OsmSchema-V0.6")) { + continue; // We can parse this. + } + if (s.equals("DenseNodes")) { + continue; // We can parse this. + } + throw new RuntimeException("File requires unknown feature: " + s); + } - // if (block.hasBbox()) { - // String source = OsmosisConstants.VERSION; - // if (block.hasSource()) { - // source = block.getSource(); - // } - // - // double multiplier = .000000001; - // double rightf = block.getBbox().getRight() * multiplier; - // double leftf = block.getBbox().getLeft() * multiplier; - // double topf = block.getBbox().getTop() * multiplier; - // double bottomf = block.getBbox().getBottom() * multiplier; - // - // Bound bounds = new Bound(rightf, leftf, topf, bottomf, source); - // sink.process(new BoundContainer(bounds)); - // } - } + // if (block.hasBbox()) { + // String source = OsmosisConstants.VERSION; + // if (block.hasSource()) { + // source = block.getSource(); + // } + // + // double multiplier = .000000001; + // double rightf = block.getBbox().getRight() * multiplier; + // double leftf = block.getBbox().getLeft() * multiplier; + // double topf = block.getBbox().getTop() * multiplier; + // double bottomf = block.getBbox().getBottom() * multiplier; + // + // Bound bounds = new Bound(rightf, leftf, topf, bottomf, source); + // sink.process(new BoundContainer(bounds)); + // } + } - public OsmData getData() { + public OsmData getData() { - // for (Entry> entry : relationMembersForRelation - // .entrySet()) { - // - // OsmRelation relation = entry.getKey(); - // - // for (TmpRelation member : entry.getValue()) { - // - // OsmElement memberObject = null; - // - // if ("node".equals(member)) { - // memberObject = nodesById.get(member.id); - // } else if ("way".equals(member)) { - // memberObject = waysById.get(member.id); - // } else if ("relation".equals(member)) { - // memberObject = relationsById.get(member.id); - // } else { - // // log("missing relation " + member.id); - // continue; - // } - // - // if (memberObject != null) { - // OsmMember ownMember = new OsmMember(member.role, - // memberObject); - // - // relation.relationMembers.add(ownMember); - // } - // } - // } + // for (Entry> entry : relationMembersForRelation + // .entrySet()) { + // + // OsmRelation relation = entry.getKey(); + // + // for (TmpRelation member : entry.getValue()) { + // + // OsmElement memberObject = null; + // + // if ("node".equals(member)) { + // memberObject = nodesById.get(member.id); + // } else if ("way".equals(member)) { + // memberObject = waysById.get(member.id); + // } else if ("relation".equals(member)) { + // memberObject = relationsById.get(member.id); + // } else { + // // log("missing relation " + member.id); + // continue; + // } + // + // if (memberObject != null) { + // OsmMember ownMember = new OsmMember(member.role, + // memberObject); + // + // relation.relationMembers.add(ownMember); + // } + // } + // } - // give up references to original collections + // give up references to original collections - ArrayList ways = new ArrayList(mWayMap.values()); - ArrayList nodes = new ArrayList(mNodeMap.values()); + ArrayList ways = new ArrayList(mWayMap.values()); + ArrayList nodes = new ArrayList(mNodeMap.values()); - //log.debug("nodes: " + nodes.size() + " ways: " + ways.size()); + //log.debug("nodes: " + nodes.size() + " ways: " + ways.size()); - return new OsmData(null, nodes, ways, null); - } + return new OsmData(null, nodes, ways, null); + } } diff --git a/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfReader.java b/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfReader.java index 7e62b602..3dcb6731 100644 --- a/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfReader.java +++ b/vtm-extras/src/org/oscim/utils/osmpbf/OsmPbfReader.java @@ -16,25 +16,25 @@ */ package org.oscim.utils.osmpbf; -import java.io.IOException; -import java.io.InputStream; - import org.openstreetmap.osmosis.osmbinary.file.BlockInputStream; import org.oscim.core.osm.OsmData; +import java.io.IOException; +import java.io.InputStream; + public class OsmPbfReader { - public static OsmData process(InputStream is) { - OsmPbfParser parser = new OsmPbfParser(); + public static OsmData process(InputStream is) { + OsmPbfParser parser = new OsmPbfParser(); - try { - (new BlockInputStream(is, parser)).process(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return null; - } + try { + (new BlockInputStream(is, parser)).process(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return null; + } - return parser.getData(); - } + return parser.getData(); + } } diff --git a/vtm-extras/src/org/oscim/utils/overpass/OverpassAPIReader.java b/vtm-extras/src/org/oscim/utils/overpass/OverpassAPIReader.java index 64ea2b11..e0d1df6f 100644 --- a/vtm-extras/src/org/oscim/utils/overpass/OverpassAPIReader.java +++ b/vtm-extras/src/org/oscim/utils/overpass/OverpassAPIReader.java @@ -17,6 +17,21 @@ package org.oscim.utils.overpass; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; + +import org.oscim.core.Tag; +import org.oscim.core.TagSet; +import org.oscim.core.osm.Bound; +import org.oscim.core.osm.OsmData; +import org.oscim.core.osm.OsmElement; +import org.oscim.core.osm.OsmMember; +import org.oscim.core.osm.OsmNode; +import org.oscim.core.osm.OsmRelation; +import org.oscim.core.osm.OsmWay; + import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; @@ -33,381 +48,359 @@ import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; -import org.oscim.core.Tag; -import org.oscim.core.TagSet; -import org.oscim.core.osm.Bound; -import org.oscim.core.osm.OsmData; -import org.oscim.core.osm.OsmElement; -import org.oscim.core.osm.OsmMember; -import org.oscim.core.osm.OsmNode; -import org.oscim.core.osm.OsmRelation; -import org.oscim.core.osm.OsmWay; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; - public class OverpassAPIReader { - private static final String OVERPASS_API = "http://city.informatik.uni-bremen.de/oapi/interpreter"; - private static final int RESPONSECODE_OK = 200; - - /** - * The timeout we use for the HttpURLConnection. - */ - private static final int TIMEOUT = 15000; - - /** - * The base url of the server. Defaults to. - * "http://www.openstreetmap.org/api/0.5". - */ - private final String myBaseUrl = OVERPASS_API; - - /** - * The http connection used to retrieve data. - */ - private HttpURLConnection myActiveConnection; - - /** - * The stream providing response data. - */ - private InputStream responseStream; - - private final String query; - - /** - * Creates a new instance with the specified geographical coordinates. - * - * @param left - * The longitude marking the left edge of the bounding box. - * @param right - * The longitude marking the right edge of the bounding box. - * @param top - * The latitude marking the top edge of the bounding box. - * @param bottom - * The latitude marking the bottom edge of the bounding box. - * @param baseUrl - * (optional) The base url of the server (eg. - * http://www.openstreetmap.org/api/0.5). - */ - public OverpassAPIReader(final double left, final double right, - final double top, final double bottom, final String baseUrl, - final String query) { - - String bbox = "(" + Math.min(top, bottom) + "," + Math.min(left, right) - + "," + Math.max(top, bottom) + "," + Math.max(left, right) - + ")"; - - this.query = query.replaceAll("\\{\\{bbox\\}\\}", bbox); - - } - - /** - * Open a connection to the given url and return a reader on the input - * stream from that connection. - * - * @param pUrlStr - * The exact url to connect to. - * @return An reader reading the input stream (servers answer) or - * null. - * @throws IOException - * on io-errors - */ - private InputStream getInputStream(final String pUrlStr) throws IOException { - URL url; - int responseCode; - String encoding; - - url = new URL(pUrlStr); - myActiveConnection = (HttpURLConnection) url.openConnection(); - - myActiveConnection.setRequestProperty("Accept-Encoding", - "gzip, deflate"); - - responseCode = myActiveConnection.getResponseCode(); - - if (responseCode != RESPONSECODE_OK) { - String message; - String apiErrorMessage; - - apiErrorMessage = myActiveConnection.getHeaderField("Error"); - - if (apiErrorMessage != null) { - message = "Received API HTTP response code " + responseCode - + " with message \"" + apiErrorMessage - + "\" for URL \"" + pUrlStr + "\"."; - } else { - message = "Received API HTTP response code " + responseCode - + " for URL \"" + pUrlStr + "\"."; - } - - throw new IOException(message); - } - - myActiveConnection.setConnectTimeout(TIMEOUT); - - encoding = myActiveConnection.getContentEncoding(); - - responseStream = myActiveConnection.getInputStream(); - if (encoding != null && encoding.equalsIgnoreCase("gzip")) { - responseStream = new GZIPInputStream(responseStream); - } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { - responseStream = new InflaterInputStream(responseStream, - new Inflater(true)); - } - - return responseStream; - } - - class TmpRelation { - Long id; - String type; - String role; - } - - private final List bounds = new ArrayList(); - private Map nodesById = new HashMap(); - private Map waysById = new HashMap(); - private Map relationsById = new HashMap(); - private Map> relationMembersForRelation = - new HashMap>(); - - private final Collection ownNodes = new ArrayList(10000); - private final Collection ownWays = new ArrayList(1000); - private final Collection ownRelations = new ArrayList( - 100); - - public void parse(InputStream in) throws IOException { - JsonFactory jsonFactory = new JsonFactory(); - try { - JsonParser jp = jsonFactory.createJsonParser(in); - - JsonToken t; - while ((t = jp.nextToken()) != null) { - if (t == JsonToken.START_OBJECT) { - jp.nextToken(); - - String name = jp.getCurrentName(); - jp.nextToken(); - - if ("type".equals(name)) { - String type = jp.getText(); - - if ("node".equals(type)) - parseNode(jp); - - else if ("way".equals(type)) - parseWay(jp); - - else if ("relation".equals(type)) - parseRelation(jp); - } - } - } - } catch (JsonParseException e) { - e.printStackTrace(); - } - } - - private void parseNode(JsonParser jp) throws JsonParseException, - IOException { - - long id = 0; - double lat = 0, lon = 0; - TagSet tags = null; + private static final String OVERPASS_API = "http://city.informatik.uni-bremen.de/oapi/interpreter"; + private static final int RESPONSECODE_OK = 200; + + /** + * The timeout we use for the HttpURLConnection. + */ + private static final int TIMEOUT = 15000; + + /** + * The base url of the server. Defaults to. + * "http://www.openstreetmap.org/api/0.5". + */ + private final String myBaseUrl = OVERPASS_API; + + /** + * The http connection used to retrieve data. + */ + private HttpURLConnection myActiveConnection; + + /** + * The stream providing response data. + */ + private InputStream responseStream; + + private final String query; + + /** + * Creates a new instance with the specified geographical coordinates. + * + * @param left The longitude marking the left edge of the bounding box. + * @param right The longitude marking the right edge of the bounding box. + * @param top The latitude marking the top edge of the bounding box. + * @param bottom The latitude marking the bottom edge of the bounding box. + * @param baseUrl (optional) The base url of the server (eg. + * http://www.openstreetmap.org/api/0.5). + */ + public OverpassAPIReader(final double left, final double right, + final double top, final double bottom, final String baseUrl, + final String query) { + + String bbox = "(" + Math.min(top, bottom) + "," + Math.min(left, right) + + "," + Math.max(top, bottom) + "," + Math.max(left, right) + + ")"; + + this.query = query.replaceAll("\\{\\{bbox\\}\\}", bbox); + + } + + /** + * Open a connection to the given url and return a reader on the input + * stream from that connection. + * + * @param pUrlStr The exact url to connect to. + * @return An reader reading the input stream (servers answer) or + * null. + * @throws IOException on io-errors + */ + private InputStream getInputStream(final String pUrlStr) throws IOException { + URL url; + int responseCode; + String encoding; + + url = new URL(pUrlStr); + myActiveConnection = (HttpURLConnection) url.openConnection(); + + myActiveConnection.setRequestProperty("Accept-Encoding", + "gzip, deflate"); + + responseCode = myActiveConnection.getResponseCode(); + + if (responseCode != RESPONSECODE_OK) { + String message; + String apiErrorMessage; + + apiErrorMessage = myActiveConnection.getHeaderField("Error"); + + if (apiErrorMessage != null) { + message = "Received API HTTP response code " + responseCode + + " with message \"" + apiErrorMessage + + "\" for URL \"" + pUrlStr + "\"."; + } else { + message = "Received API HTTP response code " + responseCode + + " for URL \"" + pUrlStr + "\"."; + } + + throw new IOException(message); + } + + myActiveConnection.setConnectTimeout(TIMEOUT); + + encoding = myActiveConnection.getContentEncoding(); + + responseStream = myActiveConnection.getInputStream(); + if (encoding != null && encoding.equalsIgnoreCase("gzip")) { + responseStream = new GZIPInputStream(responseStream); + } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { + responseStream = new InflaterInputStream(responseStream, + new Inflater(true)); + } + + return responseStream; + } + + class TmpRelation { + Long id; + String type; + String role; + } + + private final List bounds = new ArrayList(); + private Map nodesById = new HashMap(); + private Map waysById = new HashMap(); + private Map relationsById = new HashMap(); + private Map> relationMembersForRelation = + new HashMap>(); + + private final Collection ownNodes = new ArrayList(10000); + private final Collection ownWays = new ArrayList(1000); + private final Collection ownRelations = new ArrayList( + 100); + + public void parse(InputStream in) throws IOException { + JsonFactory jsonFactory = new JsonFactory(); + try { + JsonParser jp = jsonFactory.createJsonParser(in); + + JsonToken t; + while ((t = jp.nextToken()) != null) { + if (t == JsonToken.START_OBJECT) { + jp.nextToken(); + + String name = jp.getCurrentName(); + jp.nextToken(); + + if ("type".equals(name)) { + String type = jp.getText(); + + if ("node".equals(type)) + parseNode(jp); - while (jp.nextToken() != JsonToken.END_OBJECT) { + else if ("way".equals(type)) + parseWay(jp); - String name = jp.getCurrentName(); - jp.nextToken(); + else if ("relation".equals(type)) + parseRelation(jp); + } + } + } + } catch (JsonParseException e) { + e.printStackTrace(); + } + } + + private void parseNode(JsonParser jp) throws JsonParseException, + IOException { + + long id = 0; + double lat = 0, lon = 0; + TagSet tags = null; - if ("id".equals(name)) - id = jp.getLongValue(); + while (jp.nextToken() != JsonToken.END_OBJECT) { - else if ("lat".equals(name)) - lat = jp.getDoubleValue(); - - else if ("lon".equals(name)) - lon = jp.getDoubleValue(); - - else if ("tags".equals(name)) - tags = parseTags(jp); - - } + String name = jp.getCurrentName(); + jp.nextToken(); - // log("node: "+id + " "+ lat + " " + lon); - OsmNode node = new OsmNode(lat, lon, tags, id); - ownNodes.add(node); - nodesById.put(Long.valueOf(id), node); - } + if ("id".equals(name)) + id = jp.getLongValue(); - private void parseWay(JsonParser jp) throws JsonParseException, IOException { + else if ("lat".equals(name)) + lat = jp.getDoubleValue(); + + else if ("lon".equals(name)) + lon = jp.getDoubleValue(); + + else if ("tags".equals(name)) + tags = parseTags(jp); + + } - long id = 0; - TagSet tags = null; - ArrayList wayNodes = new ArrayList(); + // log("node: "+id + " "+ lat + " " + lon); + OsmNode node = new OsmNode(lat, lon, tags, id); + ownNodes.add(node); + nodesById.put(Long.valueOf(id), node); + } - while (jp.nextToken() != JsonToken.END_OBJECT) { - - String name = jp.getCurrentName(); - jp.nextToken(); - - if ("id".equals(name)) - id = jp.getLongValue(); + private void parseWay(JsonParser jp) throws JsonParseException, IOException { - else if ("nodes".equals(name)) { - while (jp.nextToken() != JsonToken.END_ARRAY) { - Long nodeId = Long.valueOf(jp.getLongValue()); + long id = 0; + TagSet tags = null; + ArrayList wayNodes = new ArrayList(); - OsmNode node = nodesById.get(nodeId); - if (node != null) - // log("missing node " + nodeId); - // else - wayNodes.add(node); - } - } else if ("tags".equals(name)) - tags = parseTags(jp); - } - - // log("way: "+ id + " " + wayNodes.size()); - OsmWay way = new OsmWay(tags, id, wayNodes); - ownWays.add(way); - waysById.put(Long.valueOf(id), way); - } + while (jp.nextToken() != JsonToken.END_OBJECT) { + + String name = jp.getCurrentName(); + jp.nextToken(); + + if ("id".equals(name)) + id = jp.getLongValue(); - private void parseRelation(JsonParser jp) throws JsonParseException, - IOException { + else if ("nodes".equals(name)) { + while (jp.nextToken() != JsonToken.END_ARRAY) { + Long nodeId = Long.valueOf(jp.getLongValue()); - long id = 0; - TagSet tags = null; - ArrayList members = new ArrayList(); + OsmNode node = nodesById.get(nodeId); + if (node != null) + // log("missing node " + nodeId); + // else + wayNodes.add(node); + } + } else if ("tags".equals(name)) + tags = parseTags(jp); + } + + // log("way: "+ id + " " + wayNodes.size()); + OsmWay way = new OsmWay(tags, id, wayNodes); + ownWays.add(way); + waysById.put(Long.valueOf(id), way); + } - while (jp.nextToken() != JsonToken.END_OBJECT) { + private void parseRelation(JsonParser jp) throws JsonParseException, + IOException { - String name = jp.getCurrentName(); - jp.nextToken(); + long id = 0; + TagSet tags = null; + ArrayList members = new ArrayList(); - if ("id".equals(name)) - id = jp.getLongValue(); + while (jp.nextToken() != JsonToken.END_OBJECT) { - else if ("members".equals(name)) { - while (jp.nextToken() != JsonToken.END_ARRAY) { - TmpRelation member = new TmpRelation(); - - while (jp.nextToken() != JsonToken.END_OBJECT) { - name = jp.getCurrentName(); - jp.nextToken(); - - if ("type".equals(name)) - member.type = jp.getText(); - - else if ("ref".equals(name)) - member.id = Long.valueOf(jp.getLongValue()); - - else if ("role".equals(name)) - member.role = jp.getText(); - } - members.add(member); - } - } else if ("tags".equals(name)) - tags = parseTags(jp); - } - - OsmRelation relation = new OsmRelation(tags, id, members.size()); - ownRelations.add(relation); - relationsById.put(Long.valueOf(id), relation); - relationMembersForRelation.put(relation, members); - } - - private static TagSet parseTags(JsonParser jp) throws JsonParseException, - IOException { - - TagSet tags = null; - - while (jp.nextToken() != JsonToken.END_OBJECT) { - String key = jp.getCurrentName(); - jp.nextToken(); - String val = jp.getText(); - if (tags == null) - tags = new TagSet(4); - - tags.add(new Tag(key, val, false)); - - } - - return tags; - } - - private static void log(String msg) { - System.out.println(msg); - } - - public OsmData getData() { - - String encoded; - try { - encoded = URLEncoder.encode(this.query, "utf-8"); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - return null; - } - System.out.println(myBaseUrl + "?data=" + encoded); - - InputStream inputStream = null; - - try { - inputStream = getInputStream(myBaseUrl + "?data=[out:json];" + encoded); - - parse(inputStream); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (inputStream != null) - try { - inputStream.close(); - } catch (IOException e) { - //... - } - inputStream = null; - } - - for (Entry> entry : relationMembersForRelation - .entrySet()) { - - OsmRelation relation = entry.getKey(); - - for (TmpRelation member : entry.getValue()) { - - OsmElement memberObject = null; - - if ("node".equals(member)) { - memberObject = nodesById.get(member.id); - } else if ("way".equals(member)) { - memberObject = waysById.get(member.id); - } else if ("relation".equals(member)) { - memberObject = relationsById.get(member.id); - } else { - // log("missing relation " + member.id); - continue; - } - - if (memberObject != null) { - OsmMember ownMember = new OsmMember(member.role, - memberObject); - - relation.relationMembers.add(ownMember); - } - } - } - log("nodes: " + ownNodes.size() + " ways: " + ownWays.size() - + " relations: " + ownRelations.size()); - - // give up references to original collections - nodesById = null; - waysById = null; - relationsById = null; - relationMembersForRelation = null; - - return new OsmData(bounds, ownNodes, ownWays, ownRelations); - } + String name = jp.getCurrentName(); + jp.nextToken(); + + if ("id".equals(name)) + id = jp.getLongValue(); + + else if ("members".equals(name)) { + while (jp.nextToken() != JsonToken.END_ARRAY) { + TmpRelation member = new TmpRelation(); + + while (jp.nextToken() != JsonToken.END_OBJECT) { + name = jp.getCurrentName(); + jp.nextToken(); + + if ("type".equals(name)) + member.type = jp.getText(); + + else if ("ref".equals(name)) + member.id = Long.valueOf(jp.getLongValue()); + + else if ("role".equals(name)) + member.role = jp.getText(); + } + members.add(member); + } + } else if ("tags".equals(name)) + tags = parseTags(jp); + } + + OsmRelation relation = new OsmRelation(tags, id, members.size()); + ownRelations.add(relation); + relationsById.put(Long.valueOf(id), relation); + relationMembersForRelation.put(relation, members); + } + + private static TagSet parseTags(JsonParser jp) throws JsonParseException, + IOException { + + TagSet tags = null; + + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + jp.nextToken(); + String val = jp.getText(); + if (tags == null) + tags = new TagSet(4); + + tags.add(new Tag(key, val, false)); + + } + + return tags; + } + + private static void log(String msg) { + System.out.println(msg); + } + + public OsmData getData() { + + String encoded; + try { + encoded = URLEncoder.encode(this.query, "utf-8"); + } catch (UnsupportedEncodingException e1) { + e1.printStackTrace(); + return null; + } + System.out.println(myBaseUrl + "?data=" + encoded); + + InputStream inputStream = null; + + try { + inputStream = getInputStream(myBaseUrl + "?data=[out:json];" + encoded); + + parse(inputStream); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (inputStream != null) + try { + inputStream.close(); + } catch (IOException e) { + //... + } + inputStream = null; + } + + for (Entry> entry : relationMembersForRelation + .entrySet()) { + + OsmRelation relation = entry.getKey(); + + for (TmpRelation member : entry.getValue()) { + + OsmElement memberObject = null; + + if ("node".equals(member)) { + memberObject = nodesById.get(member.id); + } else if ("way".equals(member)) { + memberObject = waysById.get(member.id); + } else if ("relation".equals(member)) { + memberObject = relationsById.get(member.id); + } else { + // log("missing relation " + member.id); + continue; + } + + if (memberObject != null) { + OsmMember ownMember = new OsmMember(member.role, + memberObject); + + relation.relationMembers.add(ownMember); + } + } + } + log("nodes: " + ownNodes.size() + " ways: " + ownWays.size() + + " relations: " + ownRelations.size()); + + // give up references to original collections + nodesById = null; + waysById = null; + relationsById = null; + relationMembersForRelation = null; + + return new OsmData(bounds, ownNodes, ownWays, ownRelations); + } } diff --git a/vtm-extras/src/org/oscim/utils/wkb/Geometry.java b/vtm-extras/src/org/oscim/utils/wkb/Geometry.java index fd315f23..c800090c 100644 --- a/vtm-extras/src/org/oscim/utils/wkb/Geometry.java +++ b/vtm-extras/src/org/oscim/utils/wkb/Geometry.java @@ -28,357 +28,350 @@ package org.oscim.utils.wkb; import java.io.Serializable; -/** The base class of all geometries */ +/** + * The base class of all geometries + */ abstract class Geometry implements Serializable { - /* JDK 1.5 Serialization */ - private static final long serialVersionUID = 0x100; + /* JDK 1.5 Serialization */ + private static final long serialVersionUID = 0x100; - // OpenGIS Geometry types as defined in the OGC WKB Spec - // (May we replace this with an ENUM as soon as JDK 1.5 - // has gained widespread usage?) + // OpenGIS Geometry types as defined in the OGC WKB Spec + // (May we replace this with an ENUM as soon as JDK 1.5 + // has gained widespread usage?) - /** Fake type for linear ring */ - static final int LINEARRING = 0; - /** - * The OGIS geometry type number for points. - */ - static final int POINT = 1; + /** + * Fake type for linear ring + */ + static final int LINEARRING = 0; + /** + * The OGIS geometry type number for points. + */ + static final int POINT = 1; - /** - * The OGIS geometry type number for lines. - */ - static final int LINESTRING = 2; + /** + * The OGIS geometry type number for lines. + */ + static final int LINESTRING = 2; - /** - * The OGIS geometry type number for polygons. - */ - static final int POLYGON = 3; + /** + * The OGIS geometry type number for polygons. + */ + static final int POLYGON = 3; - /** - * The OGIS geometry type number for aggregate points. - */ - static final int MULTIPOINT = 4; + /** + * The OGIS geometry type number for aggregate points. + */ + static final int MULTIPOINT = 4; - /** - * The OGIS geometry type number for aggregate lines. - */ - static final int MULTILINESTRING = 5; + /** + * The OGIS geometry type number for aggregate lines. + */ + static final int MULTILINESTRING = 5; - /** - * The OGIS geometry type number for aggregate polygons. - */ - static final int MULTIPOLYGON = 6; + /** + * The OGIS geometry type number for aggregate polygons. + */ + static final int MULTIPOLYGON = 6; - /** - * The OGIS geometry type number for feature collections. - */ - static final int GEOMETRYCOLLECTION = 7; + /** + * The OGIS geometry type number for feature collections. + */ + static final int GEOMETRYCOLLECTION = 7; - static final String[] ALLTYPES = new String[] { - "", // internally used LinearRing does not have any text in front of - // it - "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", - "MULTIPOLYGON", "GEOMETRYCOLLECTION" }; + static final String[] ALLTYPES = new String[]{ + "", // internally used LinearRing does not have any text in front of + // it + "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", + "MULTIPOLYGON", "GEOMETRYCOLLECTION"}; - /** - * The Text representations of the geometry types - * - * @param type - * ... - * @return ... - */ - static String getTypeString(int type) { - if (type >= 0 && type <= 7) - return ALLTYPES[type]; + /** + * The Text representations of the geometry types + * + * @param type ... + * @return ... + */ + static String getTypeString(int type) { + if (type >= 0 && type <= 7) + return ALLTYPES[type]; - throw new IllegalArgumentException("Unknown Geometry type" + type); + throw new IllegalArgumentException("Unknown Geometry type" + type); - } + } - // Properties common to all geometries - /** - * The dimensionality of this feature (2,3) - */ - int dimension; + // Properties common to all geometries + /** + * The dimensionality of this feature (2,3) + */ + int dimension; - /** - * Do we have a measure (4th dimension) - */ - boolean haveMeasure = false; + /** + * Do we have a measure (4th dimension) + */ + boolean haveMeasure = false; - /** - * The OGIS geometry type of this feature. this is final as it never - * changes, it is bound to the subclass of the - * instance. - */ - final int type; + /** + * The OGIS geometry type of this feature. this is final as it never + * changes, it is bound to the subclass of the + * instance. + */ + final int type; - /** - * Official UNKNOWN srid value - */ - final static int UNKNOWN_SRID = 0; + /** + * Official UNKNOWN srid value + */ + final static int UNKNOWN_SRID = 0; - /** - * The spacial reference system id of this geometry, default is no srid - */ - int srid = UNKNOWN_SRID; + /** + * The spacial reference system id of this geometry, default is no srid + */ + int srid = UNKNOWN_SRID; - /** - * Parse a SRID value, anything <= 0 is unknown - * - * @param srid - * ... - * @return ... - */ - static int parseSRID(int srid) { - if (srid < 0) { - /* TODO: raise a warning ? */ - return 0; - } - return srid; - } + /** + * Parse a SRID value, anything <= 0 is unknown + * + * @param srid ... + * @return ... + */ + static int parseSRID(int srid) { + if (srid < 0) { + /* TODO: raise a warning ? */ + return 0; + } + return srid; + } - /** - * Constructor for subclasses - * - * @param type - * has to be given by all subclasses. - */ - protected Geometry(int type) { - this.type = type; - } + /** + * Constructor for subclasses + * + * @param type has to be given by all subclasses. + */ + protected Geometry(int type) { + this.type = type; + } - /** - * java.lang.Object hashCode implementation - */ - @Override - public int hashCode() { - return dimension | (type * 4) | (srid * 32); - } + /** + * java.lang.Object hashCode implementation + */ + @Override + public int hashCode() { + return dimension | (type * 4) | (srid * 32); + } - /** - * java.lang.Object equals implementation - */ - @Override - public boolean equals(Object other) { - return (other != null) && (other instanceof Geometry) - && equals((Geometry) other); - } + /** + * java.lang.Object equals implementation + */ + @Override + public boolean equals(Object other) { + return (other != null) && (other instanceof Geometry) + && equals((Geometry) other); + } - /** - * geometry specific equals implementation - only defined for non-null - * values - * - * @param other - * ... - * @return ... - */ - public boolean equals(Geometry other) { - return (other != null) && (this.dimension == other.dimension) - && (this.type == other.type) && (this.srid == other.srid) - && (this.haveMeasure == other.haveMeasure) - && other.getClass().equals(this.getClass()) - && this.equalsintern(other); - } + /** + * geometry specific equals implementation - only defined for non-null + * values + * + * @param other ... + * @return ... + */ + public boolean equals(Geometry other) { + return (other != null) && (this.dimension == other.dimension) + && (this.type == other.type) && (this.srid == other.srid) + && (this.haveMeasure == other.haveMeasure) + && other.getClass().equals(this.getClass()) + && this.equalsintern(other); + } - /** - * Whether test coordinates for geometry - subclass specific code - * Implementors can assume that dimensin, type, srid - * and haveMeasure are equal, other != null and other is the same subclass. - * - * @param other - * ... - * @return ... - */ - protected abstract boolean equalsintern(Geometry other); + /** + * Whether test coordinates for geometry - subclass specific code + * Implementors can assume that dimensin, type, srid + * and haveMeasure are equal, other != null and other is the same subclass. + * + * @param other ... + * @return ... + */ + protected abstract boolean equalsintern(Geometry other); - /** - * Return the number of Points of the geometry - * - * @return ... - */ - abstract int numPoints(); + /** + * Return the number of Points of the geometry + * + * @return ... + */ + abstract int numPoints(); - /** - * Get the nth Point of the geometry - * - * @param n - * the index of the point, from 0 to numPoints()-1; - * @throws ArrayIndexOutOfBoundsException - * in case of an emtpy geometry or bad index. - */ - // abstract Point getPoint(int n); + /** + * Get the nth Point of the geometry + * + * @param n + * the index of the point, from 0 to numPoints()-1; + * @throws ArrayIndexOutOfBoundsException + * in case of an emtpy geometry or bad index. + */ + // abstract Point getPoint(int n); - // - // /** - // * Same as getPoint(0); - // */ - // abstract Point getFirstPoint(); - // - // /** - // * Same as getPoint(numPoints()-1); - // */ - // abstract Point getLastPoint(); + // + // /** + // * Same as getPoint(0); + // */ + // abstract Point getFirstPoint(); + // + // /** + // * Same as getPoint(numPoints()-1); + // */ + // abstract Point getLastPoint(); - /** - * The OGIS geometry type number of this geometry. - * - * @return ... - */ - int getType() { - return this.type; - } + /** + * The OGIS geometry type number of this geometry. + * + * @return ... + */ + int getType() { + return this.type; + } - /** - * Return the Type as String - * - * @return ... - */ - String getTypeString() { - return getTypeString(this.type); - } + /** + * Return the Type as String + * + * @return ... + */ + String getTypeString() { + return getTypeString(this.type); + } - /** - * Returns whether we have a measure - * - * @return .... - */ - boolean isMeasured() { - return haveMeasure; - } + /** + * Returns whether we have a measure + * + * @return .... + */ + boolean isMeasured() { + return haveMeasure; + } - /** - * Queries the number of geometric dimensions of this geometry. This does - * not include measures, as opposed to the - * server. - * - * @return The dimensionality (eg, 2D or 3D) of this geometry. - */ - int getDimension() { - return this.dimension; - } + /** + * Queries the number of geometric dimensions of this geometry. This does + * not include measures, as opposed to the + * server. + * + * @return The dimensionality (eg, 2D or 3D) of this geometry. + */ + int getDimension() { + return this.dimension; + } - /** - * The OGIS geometry type number of this geometry. - * - * @return ... - */ - int getSrid() { - return this.srid; - } + /** + * The OGIS geometry type number of this geometry. + * + * @return ... + */ + int getSrid() { + return this.srid; + } - /** - * Recursively sets the srid on this geometry and all contained - * subgeometries - * - * @param srid - * ... - */ - void setSrid(int srid) { - this.srid = srid; - } + /** + * Recursively sets the srid on this geometry and all contained + * subgeometries + * + * @param srid ... + */ + void setSrid(int srid) { + this.srid = srid; + } - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - if (srid != UNKNOWN_SRID) { - sb.append("SRID="); - sb.append(srid); - sb.append(';'); - } - outerWKT(sb, true); - return sb.toString(); - } + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + if (srid != UNKNOWN_SRID) { + sb.append("SRID="); + sb.append(srid); + sb.append(';'); + } + outerWKT(sb, true); + return sb.toString(); + } - /** - * Render the WKT version of this Geometry (without SRID) into the given - * StringBuffer. - * - * @param sb - * ... - * @param putM - * ... - */ - void outerWKT(StringBuffer sb, boolean putM) { - sb.append(getTypeString()); - if (putM && haveMeasure && dimension == 2) { - sb.append('M'); - } - mediumWKT(sb); - } + /** + * Render the WKT version of this Geometry (without SRID) into the given + * StringBuffer. + * + * @param sb ... + * @param putM ... + */ + void outerWKT(StringBuffer sb, boolean putM) { + sb.append(getTypeString()); + if (putM && haveMeasure && dimension == 2) { + sb.append('M'); + } + mediumWKT(sb); + } - final void outerWKT(StringBuffer sb) { - outerWKT(sb, true); - } + final void outerWKT(StringBuffer sb) { + outerWKT(sb, true); + } - /** - * Render the WKT without the type name, but including the brackets into the - * StringBuffer - * - * @param sb - * ... - */ - protected void mediumWKT(StringBuffer sb) { - sb.append('('); - innerWKT(sb); - sb.append(')'); - } + /** + * Render the WKT without the type name, but including the brackets into the + * StringBuffer + * + * @param sb ... + */ + protected void mediumWKT(StringBuffer sb) { + sb.append('('); + innerWKT(sb); + sb.append(')'); + } - /** - * Render the "inner" part of the WKT (inside the brackets) into the - * StringBuffer. - * - * @param SB - * ... - */ - protected abstract void innerWKT(StringBuffer SB); + /** + * Render the "inner" part of the WKT (inside the brackets) into the + * StringBuffer. + * + * @param SB ... + */ + protected abstract void innerWKT(StringBuffer SB); - /** - * backwards compatibility method - * - * @return ... - */ - String getValue() { - StringBuffer sb = new StringBuffer(); - mediumWKT(sb); - return sb.toString(); - } + /** + * backwards compatibility method + * + * @return ... + */ + String getValue() { + StringBuffer sb = new StringBuffer(); + mediumWKT(sb); + return sb.toString(); + } - /** - * Do some internal consistency checks on the geometry. Currently, all - * Geometries must have a valid dimension (2 or - * 3) and a valid type. 2-dimensional Points must have Z=0.0, as well as - * non-measured Points must have m=0.0. - * Composed geometries must have all equal SRID, dimensionality and - * measures, as well as that they do not contain - * NULL or inconsistent subgeometries. BinaryParser and WKTParser should - * only generate consistent geometries. - * BinaryWriter may produce invalid results on inconsistent geometries. - * - * @return true if all checks are passed. - */ - boolean checkConsistency() { - return (dimension >= 2 && dimension <= 3) && (type >= 0 && type <= 7); - } + /** + * Do some internal consistency checks on the geometry. Currently, all + * Geometries must have a valid dimension (2 or + * 3) and a valid type. 2-dimensional Points must have Z=0.0, as well as + * non-measured Points must have m=0.0. + * Composed geometries must have all equal SRID, dimensionality and + * measures, as well as that they do not contain + * NULL or inconsistent subgeometries. BinaryParser and WKTParser should + * only generate consistent geometries. + * BinaryWriter may produce invalid results on inconsistent geometries. + * + * @return true if all checks are passed. + */ + boolean checkConsistency() { + return (dimension >= 2 && dimension <= 3) && (type >= 0 && type <= 7); + } - /** - * Splits the SRID=4711; part of a EWKT rep if present and sets the srid. - * - * @param value - * ... - * @return value without the SRID=4711; part - */ - protected String initSRID(String value) { - String v = value.trim(); - if (v.startsWith("SRID=")) { - int index = v.indexOf(';', 5); // sridprefix length is 5 - if (index == -1) { - throw new IllegalArgumentException( - "Error parsing Geometry - SRID not delimited with ';' "); - } - this.srid = Integer.parseInt(v.substring(5, index)); - return v.substring(index + 1).trim(); - } - return v; - } + /** + * Splits the SRID=4711; part of a EWKT rep if present and sets the srid. + * + * @param value ... + * @return value without the SRID=4711; part + */ + protected String initSRID(String value) { + String v = value.trim(); + if (v.startsWith("SRID=")) { + int index = v.indexOf(';', 5); // sridprefix length is 5 + if (index == -1) { + throw new IllegalArgumentException( + "Error parsing Geometry - SRID not delimited with ';' "); + } + this.srid = Integer.parseInt(v.substring(5, index)); + return v.substring(index + 1).trim(); + } + return v; + } } diff --git a/vtm-extras/src/org/oscim/utils/wkb/ValueGetter.java b/vtm-extras/src/org/oscim/utils/wkb/ValueGetter.java index 37284bbf..a15bd89e 100644 --- a/vtm-extras/src/org/oscim/utils/wkb/ValueGetter.java +++ b/vtm-extras/src/org/oscim/utils/wkb/ValueGetter.java @@ -25,115 +25,113 @@ package org.oscim.utils.wkb; abstract class ValueGetter { - byte[] data; - int position; - final byte endian; + byte[] data; + int position; + final byte endian; - ValueGetter(byte[] data, byte endian) { - this.data = data; + ValueGetter(byte[] data, byte endian) { + this.data = data; - this.endian = endian; - } + this.endian = endian; + } - /** - * Get a byte, should be equal for all endians - * - * @return ... - */ - byte getByte() { - return data[position++]; - } + /** + * Get a byte, should be equal for all endians + * + * @return ... + */ + byte getByte() { + return data[position++]; + } - int getInt() { - int res = getInt(position); - position += 4; - return res; - } + int getInt() { + int res = getInt(position); + position += 4; + return res; + } - long getLong() { - long res = getLong(position); - position += 8; - return res; - } + long getLong() { + long res = getLong(position); + position += 8; + return res; + } - /** - * Get a 32-Bit integer - * - * @param index - * ... - * @return ... - */ - protected abstract int getInt(int index); + /** + * Get a 32-Bit integer + * + * @param index ... + * @return ... + */ + protected abstract int getInt(int index); - /** - * Get a long value. This is not needed directly, but as a nice side-effect - * from GetDouble. - * - * @param index - * ... - * @return ... - */ - protected abstract long getLong(int index); + /** + * Get a long value. This is not needed directly, but as a nice side-effect + * from GetDouble. + * + * @param index ... + * @return ... + */ + protected abstract long getLong(int index); - /** - * Get a double. - * - * @return ... - */ - double getDouble() { - long bitrep = getLong(); - return Double.longBitsToDouble(bitrep); - } + /** + * Get a double. + * + * @return ... + */ + double getDouble() { + long bitrep = getLong(); + return Double.longBitsToDouble(bitrep); + } - static class XDR extends ValueGetter { - static final byte NUMBER = 0; + static class XDR extends ValueGetter { + static final byte NUMBER = 0; - XDR(byte[] data) { - super(data, NUMBER); - } + XDR(byte[] data) { + super(data, NUMBER); + } - @Override - protected int getInt(int index) { - return ((data[index] & 0xFF) << 24) + ((data[index + 1] & 0xFF) << 16) - + ((data[index + 2] & 0xFF) << 8) + (data[index + 3] & 0xFF); - } + @Override + protected int getInt(int index) { + return ((data[index] & 0xFF) << 24) + ((data[index + 1] & 0xFF) << 16) + + ((data[index + 2] & 0xFF) << 8) + (data[index + 3] & 0xFF); + } - @Override - protected long getLong(int index) { + @Override + protected long getLong(int index) { - return ((long) (data[index] & 0xFF) << 56) | ((long) (data[index + 1] & 0xFF) << 48) - | ((long) (data[index + 2] & 0xFF) << 40) - | ((long) (data[index + 3] & 0xFF) << 32) - | ((long) (data[index + 4] & 0xFF) << 24) - | ((long) (data[index + 5] & 0xFF) << 16) - | ((long) (data[index + 6] & 0xFF) << 8) - | ((long) (data[index + 7] & 0xFF) << 0); - } - } + return ((long) (data[index] & 0xFF) << 56) | ((long) (data[index + 1] & 0xFF) << 48) + | ((long) (data[index + 2] & 0xFF) << 40) + | ((long) (data[index + 3] & 0xFF) << 32) + | ((long) (data[index + 4] & 0xFF) << 24) + | ((long) (data[index + 5] & 0xFF) << 16) + | ((long) (data[index + 6] & 0xFF) << 8) + | ((long) (data[index + 7] & 0xFF) << 0); + } + } - static class NDR extends ValueGetter { - static final byte NUMBER = 1; + static class NDR extends ValueGetter { + static final byte NUMBER = 1; - NDR(byte[] data) { - super(data, NUMBER); - } + NDR(byte[] data) { + super(data, NUMBER); + } - @Override - protected int getInt(int index) { - return ((data[index + 3] & 0xFF) << 24) + ((data[index + 2] & 0xFF) << 16) - + ((data[index + 1] & 0xFF) << 8) + (data[index] & 0xFF); - } + @Override + protected int getInt(int index) { + return ((data[index + 3] & 0xFF) << 24) + ((data[index + 2] & 0xFF) << 16) + + ((data[index + 1] & 0xFF) << 8) + (data[index] & 0xFF); + } - @Override - protected long getLong(int index) { - return ((long) (data[index + 7] & 0xFF) << 56) - | ((long) (data[index + 6] & 0xFF) << 48) - | ((long) (data[index + 5] & 0xFF) << 40) - | ((long) (data[index + 4] & 0xFF) << 32) - | ((long) (data[index + 3] & 0xFF) << 24) - | ((long) (data[index + 2] & 0xFF) << 16) - | ((long) (data[index + 1] & 0xFF) << 8) | ((long) (data[index] & 0xFF) << 0); + @Override + protected long getLong(int index) { + return ((long) (data[index + 7] & 0xFF) << 56) + | ((long) (data[index + 6] & 0xFF) << 48) + | ((long) (data[index + 5] & 0xFF) << 40) + | ((long) (data[index + 4] & 0xFF) << 32) + | ((long) (data[index + 3] & 0xFF) << 24) + | ((long) (data[index + 2] & 0xFF) << 16) + | ((long) (data[index + 1] & 0xFF) << 8) | ((long) (data[index] & 0xFF) << 0); - } - } + } + } } diff --git a/vtm-extras/src/org/oscim/utils/wkb/WKBReader.java b/vtm-extras/src/org/oscim/utils/wkb/WKBReader.java index 879047e7..a7d2c9bb 100644 --- a/vtm-extras/src/org/oscim/utils/wkb/WKBReader.java +++ b/vtm-extras/src/org/oscim/utils/wkb/WKBReader.java @@ -20,257 +20,255 @@ import org.oscim.core.GeometryBuffer; import org.oscim.core.Tile; public class WKBReader { - public interface Callback { - public void process(GeometryBuffer geom); - } + public interface Callback { + public void process(GeometryBuffer geom); + } - private final GeometryBuffer mGeom; - private final boolean mFlipY; + private final GeometryBuffer mGeom; + private final boolean mFlipY; - private WKBReader.Callback mCallback; + private WKBReader.Callback mCallback; - public WKBReader(GeometryBuffer geom, boolean flipY) { - mGeom = geom; - mFlipY = flipY; - } + public WKBReader(GeometryBuffer geom, boolean flipY) { + mGeom = geom; + mFlipY = flipY; + } - public void setCallback(WKBReader.Callback cb) { - mCallback = cb; - } + public void setCallback(WKBReader.Callback cb) { + mCallback = cb; + } - /** - * Parse a binary encoded geometry. - */ - public void parse(byte[] value) { - parseGeometry(valueGetterForEndian(value), 0); - } + /** + * Parse a binary encoded geometry. + */ + public void parse(byte[] value) { + parseGeometry(valueGetterForEndian(value), 0); + } - /** - * Parse a hex encoded geometry. - */ - public void parse(String value) { - byte[] b = hexStringToByteArray(value); - if (b == null) - return; + /** + * Parse a hex encoded geometry. + */ + public void parse(String value) { + byte[] b = hexStringToByteArray(value); + if (b == null) + return; - parse(b); - } + parse(b); + } - private void parseGeometry(ValueGetter data, int count) { - byte endian = data.getByte(); // skip and test endian flag - if (endian != data.endian) { - throw new IllegalArgumentException("Endian inconsistency!"); - } - int typeword = data.getInt(); + private void parseGeometry(ValueGetter data, int count) { + byte endian = data.getByte(); // skip and test endian flag + if (endian != data.endian) { + throw new IllegalArgumentException("Endian inconsistency!"); + } + int typeword = data.getInt(); - int realtype = typeword & 0x1FFFFFFF; // cut off high flag bits + int realtype = typeword & 0x1FFFFFFF; // cut off high flag bits - boolean haveZ = (typeword & 0x80000000) != 0; - boolean haveM = (typeword & 0x40000000) != 0; - boolean haveS = (typeword & 0x20000000) != 0; + boolean haveZ = (typeword & 0x80000000) != 0; + boolean haveM = (typeword & 0x40000000) != 0; + boolean haveS = (typeword & 0x20000000) != 0; - // int srid = Geometry.UNKNOWN_SRID; - if (haveS) { - // srid = Geometry.parseSRID(data.getInt()); - data.getInt(); - } - switch (realtype) { - case Geometry.POINT: - mGeom.startPoints(); - parsePoint(data, haveZ, haveM); - break; - case Geometry.LINESTRING: - mGeom.startLine(); - parseLineString(data, haveZ, haveM); - break; - case Geometry.POLYGON: - mGeom.startPolygon(); - parsePolygon(data, haveZ, haveM); - break; - case Geometry.MULTIPOINT: - mGeom.startPoints(); - parseMultiPoint(data); - break; - case Geometry.MULTILINESTRING: - mGeom.startLine(); - parseMultiLineString(data); - break; - case Geometry.MULTIPOLYGON: - mGeom.startPolygon(); - parseMultiPolygon(data); - break; - case Geometry.GEOMETRYCOLLECTION: - parseCollection(data); - break; - default: - throw new IllegalArgumentException("Unknown Geometry Type: " + realtype); - } + // int srid = Geometry.UNKNOWN_SRID; + if (haveS) { + // srid = Geometry.parseSRID(data.getInt()); + data.getInt(); + } + switch (realtype) { + case Geometry.POINT: + mGeom.startPoints(); + parsePoint(data, haveZ, haveM); + break; + case Geometry.LINESTRING: + mGeom.startLine(); + parseLineString(data, haveZ, haveM); + break; + case Geometry.POLYGON: + mGeom.startPolygon(); + parsePolygon(data, haveZ, haveM); + break; + case Geometry.MULTIPOINT: + mGeom.startPoints(); + parseMultiPoint(data); + break; + case Geometry.MULTILINESTRING: + mGeom.startLine(); + parseMultiLineString(data); + break; + case Geometry.MULTIPOLYGON: + mGeom.startPolygon(); + parseMultiPolygon(data); + break; + case Geometry.GEOMETRYCOLLECTION: + parseCollection(data); + break; + default: + throw new IllegalArgumentException("Unknown Geometry Type: " + realtype); + } - if (count == 0) { - mCallback.process(mGeom); + if (count == 0) { + mCallback.process(mGeom); - mGeom.clear(); - } - // if (srid != Geometry.UNKNOWN_SRID) { - // result.setSrid(srid); - // } - } + mGeom.clear(); + } + // if (srid != Geometry.UNKNOWN_SRID) { + // result.setSrid(srid); + // } + } - private void parsePoint(ValueGetter data, boolean haveZ, boolean haveM) { + private void parsePoint(ValueGetter data, boolean haveZ, boolean haveM) { - float x = (float) data.getDouble(); - float y = (float) data.getDouble(); - if (mFlipY) - y = Tile.SIZE - y; + float x = (float) data.getDouble(); + float y = (float) data.getDouble(); + if (mFlipY) + y = Tile.SIZE - y; - mGeom.addPoint(x, y); + mGeom.addPoint(x, y); - if (haveZ) - data.getDouble(); + if (haveZ) + data.getDouble(); - if (haveM) - data.getDouble(); - } + if (haveM) + data.getDouble(); + } - /** - * Parse an Array of "full" Geometries - * - * @param data - * ... - * @param count - * ... - */ - private void parseGeometryArray(ValueGetter data, int count, int type) { - mGeom.clear(); + /** + * Parse an Array of "full" Geometries + * + * @param data ... + * @param count ... + */ + private void parseGeometryArray(ValueGetter data, int count, int type) { + mGeom.clear(); - for (int i = 0; i < count; i++) { - if (i > 0) { - if (type == Geometry.LINESTRING) - mGeom.startLine(); - else if (type == Geometry.POLYGON) - mGeom.startPolygon(); - else { - mCallback.process(mGeom); - mGeom.clear(); - } - } - parseGeometry(data, count); - // mGeom.index[++mGeom.indexPos] = -1; - } + for (int i = 0; i < count; i++) { + if (i > 0) { + if (type == Geometry.LINESTRING) + mGeom.startLine(); + else if (type == Geometry.POLYGON) + mGeom.startPolygon(); + else { + mCallback.process(mGeom); + mGeom.clear(); + } + } + parseGeometry(data, count); + // mGeom.index[++mGeom.indexPos] = -1; + } - mCallback.process(mGeom); - mGeom.clear(); - } + mCallback.process(mGeom); + mGeom.clear(); + } - private void parseMultiPoint(ValueGetter data) { - parseGeometryArray(data, data.getInt(), Geometry.POINT); - } + private void parseMultiPoint(ValueGetter data) { + parseGeometryArray(data, data.getInt(), Geometry.POINT); + } - private void parseLineString(ValueGetter data, boolean haveZ, boolean haveM) { + private void parseLineString(ValueGetter data, boolean haveZ, boolean haveM) { - int count = data.getInt(); + int count = data.getInt(); - for (int i = 0; i < count; i++) { - float x = (float) data.getDouble(); - float y = (float) data.getDouble(); + for (int i = 0; i < count; i++) { + float x = (float) data.getDouble(); + float y = (float) data.getDouble(); - if (mFlipY) - y = Tile.SIZE - y; + if (mFlipY) + y = Tile.SIZE - y; - mGeom.addPoint(x, y); + mGeom.addPoint(x, y); - // ignore - if (haveZ) - data.getDouble(); - if (haveM) - data.getDouble(); - } - } + // ignore + if (haveZ) + data.getDouble(); + if (haveM) + data.getDouble(); + } + } - private void parsePolygon(ValueGetter data, boolean haveZ, boolean haveM) { - int count = data.getInt(); + private void parsePolygon(ValueGetter data, boolean haveZ, boolean haveM) { + int count = data.getInt(); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { - if (i > 0) - mGeom.startHole(); + if (i > 0) + mGeom.startHole(); - int points = data.getInt(); + int points = data.getInt(); - for (int j = 0; j < points; j++) { - float x = (float) data.getDouble(); - float y = (float) data.getDouble(); + for (int j = 0; j < points; j++) { + float x = (float) data.getDouble(); + float y = (float) data.getDouble(); - if (mFlipY) - y = Tile.SIZE - y; + if (mFlipY) + y = Tile.SIZE - y; - // drop redundant closing point - if (j < points - 1) - mGeom.addPoint(x, y); + // drop redundant closing point + if (j < points - 1) + mGeom.addPoint(x, y); - // ignore - if (haveZ) - data.getDouble(); - if (haveM) - data.getDouble(); - } - } - } + // ignore + if (haveZ) + data.getDouble(); + if (haveM) + data.getDouble(); + } + } + } - private void parseMultiLineString(ValueGetter data) { + private void parseMultiLineString(ValueGetter data) { - int count = data.getInt(); - if (count <= 0) - return; + int count = data.getInt(); + if (count <= 0) + return; - parseGeometryArray(data, count, Geometry.LINESTRING); - } + parseGeometryArray(data, count, Geometry.LINESTRING); + } - private void parseMultiPolygon(ValueGetter data) { - int count = data.getInt(); - if (count <= 0) - return; + private void parseMultiPolygon(ValueGetter data) { + int count = data.getInt(); + if (count <= 0) + return; - parseGeometryArray(data, count, Geometry.POLYGON); - } + parseGeometryArray(data, count, Geometry.POLYGON); + } - private void parseCollection(ValueGetter data) { - int count = data.getInt(); + private void parseCollection(ValueGetter data) { + int count = data.getInt(); - parseGeometryArray(data, count, Geometry.GEOMETRYCOLLECTION); + parseGeometryArray(data, count, Geometry.GEOMETRYCOLLECTION); - mCallback.process(mGeom); - mGeom.clear(); - } + mCallback.process(mGeom); + mGeom.clear(); + } - private static ValueGetter valueGetterForEndian(byte[] bytes) { - if (bytes[0] == ValueGetter.XDR.NUMBER) { // XDR - return new ValueGetter.XDR(bytes); - } else if (bytes[0] == ValueGetter.NDR.NUMBER) { - return new ValueGetter.NDR(bytes); - } else { - throw new IllegalArgumentException("Unknown Endian type:" + bytes[0]); - } - } + private static ValueGetter valueGetterForEndian(byte[] bytes) { + if (bytes[0] == ValueGetter.XDR.NUMBER) { // XDR + return new ValueGetter.XDR(bytes); + } else if (bytes[0] == ValueGetter.NDR.NUMBER) { + return new ValueGetter.NDR(bytes); + } else { + throw new IllegalArgumentException("Unknown Endian type:" + bytes[0]); + } + } - /** - * Converting a string of hex character to bytes - * - * from http://stackoverflow.com/questions/140131/convert-a-string- - * representation-of-a-hex-dump-to-a-byte-array-using-java - */ - public static byte[] hexStringToByteArray(String s) { + /** + * Converting a string of hex character to bytes + *

+ * from http://stackoverflow.com/questions/140131/convert-a-string- + * representation-of-a-hex-dump-to-a-byte-array-using-java + */ + public static byte[] hexStringToByteArray(String s) { - int len = s.length(); - if (len < 2) - return null; + int len = s.length(); + if (len < 2) + return null; - byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) - + Character.digit(s.charAt(i + 1), 16)); - } - return data; - } + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } } diff --git a/vtm-gdx/src/VtmGdx.gwt.xml b/vtm-gdx/src/VtmGdx.gwt.xml index 787f3b3d..ab0231da 100644 --- a/vtm-gdx/src/VtmGdx.gwt.xml +++ b/vtm-gdx/src/VtmGdx.gwt.xml @@ -1,5 +1,6 @@ - - + - + \ No newline at end of file diff --git a/vtm-gdx/src/org/oscim/gdx/GdxAssets.java b/vtm-gdx/src/org/oscim/gdx/GdxAssets.java index 41b5f582..aad9abf2 100644 --- a/vtm-gdx/src/org/oscim/gdx/GdxAssets.java +++ b/vtm-gdx/src/org/oscim/gdx/GdxAssets.java @@ -16,36 +16,36 @@ */ package org.oscim.gdx; -import java.io.InputStream; - -import org.oscim.backend.AssetAdapter; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; +import org.oscim.backend.AssetAdapter; + +import java.io.InputStream; + public class GdxAssets extends AssetAdapter { - static String pathPrefix = ""; + static String pathPrefix = ""; - private GdxAssets(String path) { - pathPrefix = path; - } + private GdxAssets(String path) { + pathPrefix = path; + } - @Override - public InputStream openFileAsStream(String fileName) { - FileHandle file = Gdx.files.internal(pathPrefix + fileName); - if (file == null) - throw new IllegalArgumentException("missing file " + fileName); + @Override + public InputStream openFileAsStream(String fileName) { + FileHandle file = Gdx.files.internal(pathPrefix + fileName); + if (file == null) + throw new IllegalArgumentException("missing file " + fileName); - try { - return file.read(); - } catch (GdxRuntimeException e) { - e.printStackTrace(); - return null; - } - } + try { + return file.read(); + } catch (GdxRuntimeException e) { + e.printStackTrace(); + return null; + } + } - public static void init(String path) { - AssetAdapter.init(new GdxAssets(path)); - } + public static void init(String path) { + AssetAdapter.init(new GdxAssets(path)); + } } diff --git a/vtm-gdx/src/org/oscim/gdx/GdxMap.java b/vtm-gdx/src/org/oscim/gdx/GdxMap.java index 89922df9..9ffbe359 100644 --- a/vtm-gdx/src/org/oscim/gdx/GdxMap.java +++ b/vtm-gdx/src/org/oscim/gdx/GdxMap.java @@ -16,6 +16,13 @@ */ package org.oscim.gdx; +import com.badlogic.gdx.Application; +import com.badlogic.gdx.ApplicationListener; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.InputMultiplexer; +import com.badlogic.gdx.utils.Timer; +import com.badlogic.gdx.utils.Timer.Task; + import org.oscim.layers.TileGridLayer; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.VectorTileLayer; @@ -28,187 +35,180 @@ import org.oscim.tiling.TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.Application; -import com.badlogic.gdx.ApplicationListener; -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.InputMultiplexer; -import com.badlogic.gdx.utils.Timer; -import com.badlogic.gdx.utils.Timer.Task; - public abstract class GdxMap implements ApplicationListener { - final static Logger log = LoggerFactory.getLogger(GdxMap.class); + final static Logger log = LoggerFactory.getLogger(GdxMap.class); - protected Map mMap; + protected Map mMap; - VectorTileLayer mMapLayer; - private MapRenderer mMapRenderer; + VectorTileLayer mMapLayer; + private MapRenderer mMapRenderer; - public GdxMap() { - } + public GdxMap() { + } - protected void initDefaultLayers(TileSource tileSource, boolean tileGrid, boolean labels, - boolean buildings) { - Layers layers = mMap.layers(); + protected void initDefaultLayers(TileSource tileSource, boolean tileGrid, boolean labels, + boolean buildings) { + Layers layers = mMap.layers(); - if (tileSource != null) { - mMapLayer = mMap.setBaseMap(tileSource); - mMap.setTheme(VtmThemes.DEFAULT); + if (tileSource != null) { + mMapLayer = mMap.setBaseMap(tileSource); + mMap.setTheme(VtmThemes.DEFAULT); - if (buildings) - layers.add(new BuildingLayer(mMap, mMapLayer)); + if (buildings) + layers.add(new BuildingLayer(mMap, mMapLayer)); - if (labels) - layers.add(new LabelLayer(mMap, mMapLayer)); - } + if (labels) + layers.add(new LabelLayer(mMap, mMapLayer)); + } - if (tileGrid) - layers.add(new TileGridLayer(mMap)); - } + if (tileGrid) + layers.add(new TileGridLayer(mMap)); + } - @Override - public void create() { - mMap = new MapAdapter(); - mMapRenderer = new MapRenderer(mMap); + @Override + public void create() { + mMap = new MapAdapter(); + mMapRenderer = new MapRenderer(mMap); - Gdx.graphics.setContinuousRendering(false); - Gdx.app.setLogLevel(Application.LOG_DEBUG); + Gdx.graphics.setContinuousRendering(false); + Gdx.app.setLogLevel(Application.LOG_DEBUG); - int w = Gdx.graphics.getWidth(); - int h = Gdx.graphics.getHeight(); + int w = Gdx.graphics.getWidth(); + int h = Gdx.graphics.getHeight(); - mMap.viewport().setScreenSize(w, h); - mMapRenderer.onSurfaceCreated(); - mMapRenderer.onSurfaceChanged(w, h); + mMap.viewport().setScreenSize(w, h); + mMapRenderer.onSurfaceCreated(); + mMapRenderer.onSurfaceChanged(w, h); - InputMultiplexer mux = new InputMultiplexer(); - mux.addProcessor(new InputHandler(this)); - //mux.addProcessor(new GestureDetector(20, 0.5f, 2, 0.05f, - // new MapController(mMap))); - mux.addProcessor(new MotionHandler(mMap)); + InputMultiplexer mux = new InputMultiplexer(); + mux.addProcessor(new InputHandler(this)); + //mux.addProcessor(new GestureDetector(20, 0.5f, 2, 0.05f, + // new MapController(mMap))); + mux.addProcessor(new MotionHandler(mMap)); - Gdx.input.setInputProcessor(mux); + Gdx.input.setInputProcessor(mux); - createLayers(); - } + createLayers(); + } - protected void createLayers() { - mMap.layers().add(new TileGridLayer(mMap)); - } + protected void createLayers() { + mMap.layers().add(new TileGridLayer(mMap)); + } - @Override - public void dispose() { + @Override + public void dispose() { - } + } - /* private */boolean mRenderWait; - /* private */boolean mRenderRequest; - /* private */boolean mUpdateRequest; + /* private */ boolean mRenderWait; + /* private */ boolean mRenderRequest; + /* private */ boolean mUpdateRequest; - @Override - public void render() { - if (!mRenderRequest) - return; + @Override + public void render() { + if (!mRenderRequest) + return; - mMapRenderer.onDrawFrame(); - } + mMapRenderer.onDrawFrame(); + } - @Override - public void resize(int w, int h) { - mMap.viewport().setScreenSize(w, h); - mMapRenderer.onSurfaceChanged(w, h); - mMap.render(); - } + @Override + public void resize(int w, int h) { + mMap.viewport().setScreenSize(w, h); + mMapRenderer.onSurfaceChanged(w, h); + mMap.render(); + } - @Override - public void pause() { - } + @Override + public void pause() { + } - @Override - public void resume() { - } + @Override + public void resume() { + } - protected boolean onKeyDown(int keycode) { - return false; - } + protected boolean onKeyDown(int keycode) { + return false; + } - public Map getMap() { - return mMap; - } + public Map getMap() { + return mMap; + } - class MapAdapter extends Map { + class MapAdapter extends Map { - @Override - public int getWidth() { - return Gdx.graphics.getWidth(); - } + @Override + public int getWidth() { + return Gdx.graphics.getWidth(); + } - @Override - public int getHeight() { - return Gdx.graphics.getHeight(); - } + @Override + public int getHeight() { + return Gdx.graphics.getHeight(); + } - private final Runnable mRedrawCb = new Runnable() { - @Override - public void run() { - prepareFrame(); - Gdx.graphics.requestRendering(); - } - }; + private final Runnable mRedrawCb = new Runnable() { + @Override + public void run() { + prepareFrame(); + Gdx.graphics.requestRendering(); + } + }; - @Override - public void updateMap(boolean forceRender) { - synchronized (mRedrawCb) { - if (!mRenderRequest) { - mRenderRequest = true; - Gdx.app.postRunnable(mRedrawCb); - } else { - mRenderWait = true; - } - } - } + @Override + public void updateMap(boolean forceRender) { + synchronized (mRedrawCb) { + if (!mRenderRequest) { + mRenderRequest = true; + Gdx.app.postRunnable(mRedrawCb); + } else { + mRenderWait = true; + } + } + } - @Override - public void render() { - synchronized (mRedrawCb) { - mRenderRequest = true; - if (mClearMap) - updateMap(false); - else { - Gdx.graphics.requestRendering(); - } - } - } + @Override + public void render() { + synchronized (mRedrawCb) { + mRenderRequest = true; + if (mClearMap) + updateMap(false); + else { + Gdx.graphics.requestRendering(); + } + } + } - @Override - public boolean post(Runnable runnable) { - Gdx.app.postRunnable(runnable); - return true; - } + @Override + public boolean post(Runnable runnable) { + Gdx.app.postRunnable(runnable); + return true; + } - @Override - public boolean postDelayed(final Runnable action, long delay) { - Timer.schedule(new Task() { - @Override - public void run() { - action.run(); - } - }, delay / 1000f); - return true; - } + @Override + public boolean postDelayed(final Runnable action, long delay) { + Timer.schedule(new Task() { + @Override + public void run() { + action.run(); + } + }, delay / 1000f); + return true; + } - @Override - public void beginFrame() { - } + @Override + public void beginFrame() { + } - @Override - public void doneFrame(boolean animate) { - synchronized (mRedrawCb) { - mRenderRequest = false; - if (animate || mRenderWait) { - mRenderWait = false; - updateMap(true); - } - } - } - } + @Override + public void doneFrame(boolean animate) { + synchronized (mRedrawCb) { + mRenderRequest = false; + if (animate || mRenderWait) { + mRenderWait = false; + updateMap(true); + } + } + } + } } diff --git a/vtm-gdx/src/org/oscim/gdx/GestureHandler.java b/vtm-gdx/src/org/oscim/gdx/GestureHandler.java index e183e48a..41793dff 100644 --- a/vtm-gdx/src/org/oscim/gdx/GestureHandler.java +++ b/vtm-gdx/src/org/oscim/gdx/GestureHandler.java @@ -16,237 +16,237 @@ */ package org.oscim.gdx; -import org.oscim.core.Tile; -import org.oscim.map.Map; - import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.input.GestureDetector.GestureListener; import com.badlogic.gdx.math.Vector2; +import org.oscim.core.Tile; +import org.oscim.map.Map; + public class GestureHandler implements GestureListener { - private boolean mayFling = true; + private boolean mayFling = true; - private boolean mPinch; + private boolean mPinch; - private boolean mBeginScale; - private float mSumScale; - private float mSumRotate; + private boolean mBeginScale; + private float mSumScale; + private float mSumRotate; - private boolean mBeginRotate; - private boolean mBeginTilt; + private boolean mBeginRotate; + private boolean mBeginTilt; - private float mPrevX; - private float mPrevY; + private float mPrevX; + private float mPrevY; - private float mPrevX2; - private float mPrevY2; + private float mPrevX2; + private float mPrevY2; - private float mFocusX; - private float mFocusY; + private float mFocusX; + private float mFocusY; - private double mAngle; - protected double mPrevPinchWidth = -1; + private double mAngle; + protected double mPrevPinchWidth = -1; - protected static final int JUMP_THRESHOLD = 100; - protected static final double PINCH_ZOOM_THRESHOLD = 5; - protected static final double PINCH_ROTATE_THRESHOLD = 0.02; - protected static final float PINCH_TILT_THRESHOLD = 1f; + protected static final int JUMP_THRESHOLD = 100; + protected static final double PINCH_ZOOM_THRESHOLD = 5; + protected static final double PINCH_ROTATE_THRESHOLD = 0.02; + protected static final float PINCH_TILT_THRESHOLD = 1f; - //private ViewController mViewport; - private final Map mMap; + //private ViewController mViewport; + private final Map mMap; - public GestureHandler(Map map) { - //mViewport = mMap.viewport(); - mMap = map; - } + public GestureHandler(Map map) { + //mViewport = mMap.viewport(); + mMap = map; + } - @Override - public boolean touchDown(float x, float y, int pointer, int button) { - mayFling = true; - mPinch = false; + @Override + public boolean touchDown(float x, float y, int pointer, int button) { + mayFling = true; + mPinch = false; - return false; - } + return false; + } - @Override - public boolean tap(float x, float y, int count, int button) { - return false; - } + @Override + public boolean tap(float x, float y, int count, int button) { + return false; + } - @Override - public boolean longPress(float x, float y) { - return false; - } + @Override + public boolean longPress(float x, float y) { + return false; + } - @Override - public boolean fling(final float velocityX, final float velocityY, - int button) { - //log.debug("fling " + button + " " + velocityX + "/" + velocityY); - if (mayFling && button == Buttons.LEFT) { - int m = Tile.SIZE * 4; - mMap.animator().animateFling((int) velocityX, (int) velocityY, -m, m, -m, m); - return true; - } - return false; - } + @Override + public boolean fling(final float velocityX, final float velocityY, + int button) { + //log.debug("fling " + button + " " + velocityX + "/" + velocityY); + if (mayFling && button == Buttons.LEFT) { + int m = Tile.SIZE * 4; + mMap.animator().animateFling((int) velocityX, (int) velocityY, -m, m, -m, m); + return true; + } + return false; + } - @Override - public boolean pan(float x, float y, float deltaX, float deltaY) { - if (mPinch) - return true; + @Override + public boolean pan(float x, float y, float deltaX, float deltaY) { + if (mPinch) + return true; - mMap.viewport().moveMap(deltaX, deltaY); - mMap.updateMap(true); + mMap.viewport().moveMap(deltaX, deltaY); + mMap.updateMap(true); - return false; - } + return false; + } - @Override - public boolean zoom(float initialDistance, float distance) { - return false; - } + @Override + public boolean zoom(float initialDistance, float distance) { + return false; + } - @Override - public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, - Vector2 pointer1, Vector2 pointer2) { - mayFling = false; + @Override + public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, + Vector2 pointer1, Vector2 pointer2) { + mayFling = false; - if (!mPinch) { - mPrevX = pointer1.x; - mPrevY = pointer1.y; - mPrevX2 = pointer2.x; - mPrevY2 = pointer2.y; + if (!mPinch) { + mPrevX = pointer1.x; + mPrevY = pointer1.y; + mPrevX2 = pointer2.x; + mPrevY2 = pointer2.y; - double dx = mPrevX - mPrevX2; - double dy = mPrevY - mPrevY2; + double dx = mPrevX - mPrevX2; + double dy = mPrevY - mPrevY2; - mAngle = Math.atan2(dy, dx); - mPrevPinchWidth = Math.sqrt(dx * dx + dy * dy); + mAngle = Math.atan2(dy, dx); + mPrevPinchWidth = Math.sqrt(dx * dx + dy * dy); - mPinch = true; + mPinch = true; - mBeginTilt = false; - mBeginRotate = false; - mBeginScale = false; + mBeginTilt = false; + mBeginRotate = false; + mBeginScale = false; - return true; - } + return true; + } - float x1 = pointer1.x; - float y1 = pointer1.y; + float x1 = pointer1.x; + float y1 = pointer1.y; - //float mx = x1 - mPrevX; - float my = y1 - mPrevY; + //float mx = x1 - mPrevX; + float my = y1 - mPrevY; - float x2 = pointer2.x; - float y2 = pointer2.y; + float x2 = pointer2.x; + float y2 = pointer2.y; - float dx = (x1 - x2); - float dy = (y1 - y2); - float slope = 0; + float dx = (x1 - x2); + float dy = (y1 - y2); + float slope = 0; - if (dx != 0) - slope = dy / dx; + if (dx != 0) + slope = dy / dx; - double pinchWidth = Math.sqrt(dx * dx + dy * dy); + double pinchWidth = Math.sqrt(dx * dx + dy * dy); - final double deltaPinchWidth = pinchWidth - mPrevPinchWidth; + final double deltaPinchWidth = pinchWidth - mPrevPinchWidth; - double rad = Math.atan2(dy, dx); - double r = rad - mAngle; + double rad = Math.atan2(dy, dx); + double r = rad - mAngle; - boolean startScale = (Math.abs(deltaPinchWidth) > PINCH_ZOOM_THRESHOLD); + boolean startScale = (Math.abs(deltaPinchWidth) > PINCH_ZOOM_THRESHOLD); - boolean changed = false; + boolean changed = false; - if (!mBeginTilt && (mBeginScale || startScale)) { - mBeginScale = true; + if (!mBeginTilt && (mBeginScale || startScale)) { + mBeginScale = true; - float scale = (float) (pinchWidth / mPrevPinchWidth); + float scale = (float) (pinchWidth / mPrevPinchWidth); - // decrease change of scale by the change of rotation - // * 20 is just arbitrary - if (mBeginRotate) - scale = 1 + ((scale - 1) * Math.max((1 - (float) Math.abs(r) * 20), 0)); + // decrease change of scale by the change of rotation + // * 20 is just arbitrary + if (mBeginRotate) + scale = 1 + ((scale - 1) * Math.max((1 - (float) Math.abs(r) * 20), 0)); - mSumScale *= scale; + mSumScale *= scale; - if ((mSumScale < 0.99 || mSumScale > 1.01) - && mSumRotate < Math.abs(0.02)) - mBeginRotate = false; + if ((mSumScale < 0.99 || mSumScale > 1.01) + && mSumRotate < Math.abs(0.02)) + mBeginRotate = false; - float fx = (x2 + x1) / 2 - mMap.getWidth() / 2; - float fy = (y2 + y1) / 2 - mMap.getHeight() / 2; + float fx = (x2 + x1) / 2 - mMap.getWidth() / 2; + float fy = (y2 + y1) / 2 - mMap.getHeight() / 2; - // log.debug("zoom " + deltaPinchWidth + " " + scale + " " + - // mSumScale); - changed = mMap.viewport().scaleMap(scale, fx, fy); - } + // log.debug("zoom " + deltaPinchWidth + " " + scale + " " + + // mSumScale); + changed = mMap.viewport().scaleMap(scale, fx, fy); + } - if (!mBeginRotate && Math.abs(slope) < 1) { - float my2 = y2 - mPrevY2; - float threshold = PINCH_TILT_THRESHOLD; + if (!mBeginRotate && Math.abs(slope) < 1) { + float my2 = y2 - mPrevY2; + float threshold = PINCH_TILT_THRESHOLD; - // log.debug(r + " " + slope + " m1:" + my + " m2:" + my2); + // log.debug(r + " " + slope + " m1:" + my + " m2:" + my2); - if ((my > threshold && my2 > threshold) - || (my < -threshold && my2 < -threshold)) { - mBeginTilt = true; - changed = mMap.viewport().tiltMap(my / 5); - } - } + if ((my > threshold && my2 > threshold) + || (my < -threshold && my2 < -threshold)) { + mBeginTilt = true; + changed = mMap.viewport().tiltMap(my / 5); + } + } - if (!mBeginTilt - && (mBeginRotate || (Math.abs(slope) > 1 && Math.abs(r) > PINCH_ROTATE_THRESHOLD))) { - // log.debug("rotate: " + mBeginRotate + " " + - // Math.toDegrees(rad)); - if (!mBeginRotate) { - mAngle = rad; + if (!mBeginTilt + && (mBeginRotate || (Math.abs(slope) > 1 && Math.abs(r) > PINCH_ROTATE_THRESHOLD))) { + // log.debug("rotate: " + mBeginRotate + " " + + // Math.toDegrees(rad)); + if (!mBeginRotate) { + mAngle = rad; - mSumScale = 1; - mSumRotate = 0; + mSumScale = 1; + mSumRotate = 0; - mBeginRotate = true; + mBeginRotate = true; - mFocusX = (x1 + x2) / 2 - (mMap.getWidth() / 2); - mFocusY = (y1 + y2) / 2 - (mMap.getHeight() / 2); - } else { - double da = rad - mAngle; - mSumRotate += da; + mFocusX = (x1 + x2) / 2 - (mMap.getWidth() / 2); + mFocusY = (y1 + y2) / 2 - (mMap.getHeight() / 2); + } else { + double da = rad - mAngle; + mSumRotate += da; - if (Math.abs(da) > 0.001) { - double rsin = Math.sin(r); - double rcos = Math.cos(r); - float x = (float) (mFocusX * rcos + mFocusY * -rsin - mFocusX); - float y = (float) (mFocusX * rsin + mFocusY * rcos - mFocusY); + if (Math.abs(da) > 0.001) { + double rsin = Math.sin(r); + double rcos = Math.cos(r); + float x = (float) (mFocusX * rcos + mFocusY * -rsin - mFocusX); + float y = (float) (mFocusX * rsin + mFocusY * rcos - mFocusY); - mMap.viewport().rotateMap(da, x, y); - changed = true; - } - } - mAngle = rad; - } + mMap.viewport().rotateMap(da, x, y); + changed = true; + } + } + mAngle = rad; + } - if (changed) { - mMap.updateMap(true); - mPrevPinchWidth = pinchWidth; - mPrevY2 = y2; + if (changed) { + mMap.updateMap(true); + mPrevPinchWidth = pinchWidth; + mPrevY2 = y2; - } + } - mPrevX = x1; - mPrevY = y1; - mPrevX2 = x2; + mPrevX = x1; + mPrevY = y1; + mPrevX2 = x2; - return true; - } + return true; + } - @Override - public boolean panStop(float x, float y, int pointer, int button) { - return false; - } + @Override + public boolean panStop(float x, float y, int pointer, int button) { + return false; + } - @Override - public void pinchStop () { - } + @Override + public void pinchStop() { + } } diff --git a/vtm-gdx/src/org/oscim/gdx/InputHandler.java b/vtm-gdx/src/org/oscim/gdx/InputHandler.java index e1a005e7..e98046de 100644 --- a/vtm-gdx/src/org/oscim/gdx/InputHandler.java +++ b/vtm-gdx/src/org/oscim/gdx/InputHandler.java @@ -16,226 +16,226 @@ */ package org.oscim.gdx; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.Input; +import com.badlogic.gdx.Input.Buttons; +import com.badlogic.gdx.InputProcessor; + import org.oscim.layers.GenericLayer; import org.oscim.layers.TileGridLayer; import org.oscim.map.Map; import org.oscim.map.ViewController; import org.oscim.theme.VtmThemes; -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.Input; -import com.badlogic.gdx.Input.Buttons; -import com.badlogic.gdx.InputProcessor; - public class InputHandler implements InputProcessor { - private ViewController mViewport; - private final Map mMap; - private GenericLayer mGridLayer; - private final GdxMap mGdxApp; + private ViewController mViewport; + private final Map mMap; + private GenericLayer mGridLayer; + private final GdxMap mGdxApp; - public InputHandler(GdxMap map) { - mMap = map.getMap(); - mViewport = mMap.viewport(); - mGdxApp = map; - } + public InputHandler(GdxMap map) { + mMap = map.getMap(); + mViewport = mMap.viewport(); + mGdxApp = map; + } - private boolean mActiveScale; - private boolean mActiveTilt; - private boolean mActiveRotate; + private boolean mActiveScale; + private boolean mActiveTilt; + private boolean mActiveRotate; - private int mPosX, mPosY; + private int mPosX, mPosY; - @Override - public boolean keyDown(int keycode) { - if (mGdxApp.onKeyDown(keycode)) - return true; + @Override + public boolean keyDown(int keycode) { + if (mGdxApp.onKeyDown(keycode)) + return true; - switch (keycode) { - case Input.Keys.ESCAPE: - Gdx.app.exit(); - break; + switch (keycode) { + case Input.Keys.ESCAPE: + Gdx.app.exit(); + break; - case Input.Keys.SHIFT_LEFT: - case Input.Keys.SHIFT_RIGHT: - mActiveScale = true; - mPosY = Gdx.input.getY(); - break; + case Input.Keys.SHIFT_LEFT: + case Input.Keys.SHIFT_RIGHT: + mActiveScale = true; + mPosY = Gdx.input.getY(); + break; - case Input.Keys.CONTROL_LEFT: - case Input.Keys.CONTROL_RIGHT: - mActiveRotate = true; - mActiveTilt = true; - mPosX = Gdx.input.getX(); - mPosY = Gdx.input.getY(); - break; + case Input.Keys.CONTROL_LEFT: + case Input.Keys.CONTROL_RIGHT: + mActiveRotate = true; + mActiveTilt = true; + mPosX = Gdx.input.getX(); + mPosY = Gdx.input.getY(); + break; - case Input.Keys.UP: - mViewport.moveMap(0, -50); - mMap.updateMap(true); - break; - case Input.Keys.DOWN: - mViewport.moveMap(0, 50); - mMap.updateMap(true); - break; - case Input.Keys.LEFT: - mViewport.moveMap(-50, 0); - mMap.updateMap(true); - break; - case Input.Keys.RIGHT: - mViewport.moveMap(50, 0); - mMap.updateMap(true); - break; - case Input.Keys.M: - mViewport.scaleMap(1.05f, 0, 0); - mMap.updateMap(true); - break; - case Input.Keys.N: - mViewport.scaleMap(0.95f, 0, 0); - mMap.updateMap(true); - break; - case Input.Keys.NUM_1: - mMap.animator().animateZoom(500, 0.5, 0, 0); - break; - case Input.Keys.NUM_2: - mMap.animator().animateZoom(500, 2, 0, 0); - break; + case Input.Keys.UP: + mViewport.moveMap(0, -50); + mMap.updateMap(true); + break; + case Input.Keys.DOWN: + mViewport.moveMap(0, 50); + mMap.updateMap(true); + break; + case Input.Keys.LEFT: + mViewport.moveMap(-50, 0); + mMap.updateMap(true); + break; + case Input.Keys.RIGHT: + mViewport.moveMap(50, 0); + mMap.updateMap(true); + break; + case Input.Keys.M: + mViewport.scaleMap(1.05f, 0, 0); + mMap.updateMap(true); + break; + case Input.Keys.N: + mViewport.scaleMap(0.95f, 0, 0); + mMap.updateMap(true); + break; + case Input.Keys.NUM_1: + mMap.animator().animateZoom(500, 0.5, 0, 0); + break; + case Input.Keys.NUM_2: + mMap.animator().animateZoom(500, 2, 0, 0); + break; - case Input.Keys.D: - mMap.setTheme(VtmThemes.DEFAULT); - mMap.updateMap(false); - break; + case Input.Keys.D: + mMap.setTheme(VtmThemes.DEFAULT); + mMap.updateMap(false); + break; - case Input.Keys.T: - mMap.setTheme(VtmThemes.TRONRENDER); - mMap.updateMap(false); - break; + case Input.Keys.T: + mMap.setTheme(VtmThemes.TRONRENDER); + mMap.updateMap(false); + break; - case Input.Keys.R: - mMap.setTheme(VtmThemes.OSMARENDER); - mMap.updateMap(false); - break; + case Input.Keys.R: + mMap.setTheme(VtmThemes.OSMARENDER); + mMap.updateMap(false); + break; - case Input.Keys.G: - if (mGridLayer == null) { - mGridLayer = new TileGridLayer(mMap); - mGridLayer.setEnabled(true); - mMap.layers().add(mGridLayer); - } else { - if (mGridLayer.isEnabled()) { - mGridLayer.setEnabled(false); - mMap.layers().remove(mGridLayer); - } else { - mGridLayer.setEnabled(true); - mMap.layers().add(mGridLayer); - } - } - mMap.render(); - break; - } - return false; - } + case Input.Keys.G: + if (mGridLayer == null) { + mGridLayer = new TileGridLayer(mMap); + mGridLayer.setEnabled(true); + mMap.layers().add(mGridLayer); + } else { + if (mGridLayer.isEnabled()) { + mGridLayer.setEnabled(false); + mMap.layers().remove(mGridLayer); + } else { + mGridLayer.setEnabled(true); + mMap.layers().add(mGridLayer); + } + } + mMap.render(); + break; + } + return false; + } - @Override - public boolean keyUp(int keycode) { - switch (keycode) { - case Input.Keys.SHIFT_LEFT: - case Input.Keys.SHIFT_RIGHT: - mActiveScale = false; - break; - case Input.Keys.CONTROL_LEFT: - case Input.Keys.CONTROL_RIGHT: - mActiveRotate = false; - mActiveTilt = false; - break; + @Override + public boolean keyUp(int keycode) { + switch (keycode) { + case Input.Keys.SHIFT_LEFT: + case Input.Keys.SHIFT_RIGHT: + mActiveScale = false; + break; + case Input.Keys.CONTROL_LEFT: + case Input.Keys.CONTROL_RIGHT: + mActiveRotate = false; + mActiveTilt = false; + break; - } + } - return false; - } + return false; + } - @Override - public boolean keyTyped(char character) { - return false; - } + @Override + public boolean keyTyped(char character) { + return false; + } - @Override - public boolean touchDown(int screenX, int screenY, int pointer, int button) { - if (button == Buttons.MIDDLE) { - mActiveScale = true; - mPosY = screenY; - } else if (button == Buttons.RIGHT) { - mActiveRotate = true; - mPosX = screenX; - mPosY = screenY; - return true; - } - return false; - } + @Override + public boolean touchDown(int screenX, int screenY, int pointer, int button) { + if (button == Buttons.MIDDLE) { + mActiveScale = true; + mPosY = screenY; + } else if (button == Buttons.RIGHT) { + mActiveRotate = true; + mPosX = screenX; + mPosY = screenY; + return true; + } + return false; + } - @Override - public boolean touchUp(int screenX, int screenY, int pointer, int button) { - mActiveScale = false; - mActiveRotate = false; - mActiveTilt = false; + @Override + public boolean touchUp(int screenX, int screenY, int pointer, int button) { + mActiveScale = false; + mActiveRotate = false; + mActiveTilt = false; - return false; - } + return false; + } - @Override - public boolean touchDragged(int screenX, int screenY, int pointer) { - boolean changed = false; + @Override + public boolean touchDragged(int screenX, int screenY, int pointer) { + boolean changed = false; - if (!(mActiveScale || mActiveRotate || mActiveTilt)) - return false; + if (!(mActiveScale || mActiveRotate || mActiveTilt)) + return false; - if (mActiveTilt) { - changed = mViewport.tiltMap((screenY - mPosY) / 5f); - mPosY = screenY; + if (mActiveTilt) { + changed = mViewport.tiltMap((screenY - mPosY) / 5f); + mPosY = screenY; - } + } - if (mActiveScale) { - changed = mViewport.scaleMap(1 - (screenY - mPosY) / 100f, 0, 0); - mPosY = screenY; - } + if (mActiveScale) { + changed = mViewport.scaleMap(1 - (screenY - mPosY) / 100f, 0, 0); + mPosY = screenY; + } - if (mActiveRotate) { - mViewport.rotateMap((screenX - mPosX) / 500f, 0, 0); - mPosX = screenX; - mViewport.tiltMap((screenY - mPosY) / 10f); - mPosY = screenY; - changed = true; - } + if (mActiveRotate) { + mViewport.rotateMap((screenX - mPosX) / 500f, 0, 0); + mPosX = screenX; + mViewport.tiltMap((screenY - mPosY) / 10f); + mPosY = screenY; + changed = true; + } - if (changed) { - mMap.updateMap(true); - } - return true; - } + if (changed) { + mMap.updateMap(true); + } + return true; + } - @Override - public boolean mouseMoved(int screenX, int screenY) { + @Override + public boolean mouseMoved(int screenX, int screenY) { - mPosX = screenX; - mPosY = screenY; - return false; - } + mPosX = screenX; + mPosY = screenY; + return false; + } - @Override - public boolean scrolled(int amount) { + @Override + public boolean scrolled(int amount) { - if (amount > 0) { + if (amount > 0) { - mMap.animator().animateZoom(250, 0.75f, 0, 0); - } else { - float fx = mPosX - mMap.getWidth() / 2; - float fy = mPosY - mMap.getHeight() / 2; + mMap.animator().animateZoom(250, 0.75f, 0, 0); + } else { + float fx = mPosX - mMap.getWidth() / 2; + float fy = mPosY - mMap.getHeight() / 2; - mMap.animator().animateZoom(250, 1.333f, fx, fy); - } - mMap.updateMap(false); + mMap.animator().animateZoom(250, 1.333f, fx, fy); + } + mMap.updateMap(false); - return true; - } + return true; + } } diff --git a/vtm-gdx/src/org/oscim/gdx/MotionHandler.java b/vtm-gdx/src/org/oscim/gdx/MotionHandler.java index f5e22975..430aff09 100644 --- a/vtm-gdx/src/org/oscim/gdx/MotionHandler.java +++ b/vtm-gdx/src/org/oscim/gdx/MotionHandler.java @@ -16,184 +16,184 @@ */ package org.oscim.gdx; -import org.oscim.event.MotionEvent; -import org.oscim.map.Map; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.InputProcessor; +import org.oscim.event.MotionEvent; +import org.oscim.map.Map; + public class MotionHandler extends MotionEvent implements InputProcessor { - private final Map mMap; + private final Map mMap; - public MotionHandler(Map map) { - mMap = map; - } + public MotionHandler(Map map) { + mMap = map; + } - int mPointerDown; - long mDownTime; + int mPointerDown; + long mDownTime; - int mType; + int mType; - int mPointer; - int mCurX; - int mCurY; - int mPointerX[] = new int[10]; - int mPointerY[] = new int[10]; + int mPointer; + int mCurX; + int mCurY; + int mPointerX[] = new int[10]; + int mPointerY[] = new int[10]; - @Override - public int getAction() { - return mType; - } + @Override + public int getAction() { + return mType; + } - @Override - public float getX() { - return mCurX; - } + @Override + public float getX() { + return mCurX; + } - @Override - public float getY() { - return mCurY; - } + @Override + public float getY() { + return mCurY; + } - @Override - public float getX(int idx) { - if (idx >= 10) - return 0; + @Override + public float getX(int idx) { + if (idx >= 10) + return 0; - return mPointerX[idx]; - } + return mPointerX[idx]; + } - @Override - public float getY(int idx) { - if (idx >= 10) - return 0; + @Override + public float getY(int idx) { + if (idx >= 10) + return 0; - return mPointerY[idx]; - } + return mPointerY[idx]; + } - @Override - public int getPointerCount() { - return mPointerDown; - } + @Override + public int getPointerCount() { + return mPointerDown; + } - @Override - public long getTime() { - return (long) (mTime / 1000000d); - } + @Override + public long getTime() { + return (long) (mTime / 1000000d); + } - // -------- InputProcessor ---------- - @Override - public boolean keyDown(int keycode) { - return false; - } + // -------- InputProcessor ---------- + @Override + public boolean keyDown(int keycode) { + return false; + } - @Override - public boolean keyUp(int keycode) { - return false; - } + @Override + public boolean keyUp(int keycode) { + return false; + } - @Override - public boolean keyTyped(char character) { - return false; - } + @Override + public boolean keyTyped(char character) { + return false; + } - long mTime = System.currentTimeMillis(); + long mTime = System.currentTimeMillis(); - @Override - public boolean touchDown(int screenX, int screenY, int pointer, int button) { - if (pointer >= 10) - return true; + @Override + public boolean touchDown(int screenX, int screenY, int pointer, int button) { + if (pointer >= 10) + return true; - if (button != Buttons.LEFT) - return false; + if (button != Buttons.LEFT) + return false; - mTime = Gdx.input.getCurrentEventTime(); - if (mPointerDown++ == 0) { - mDownTime = getTime(); - mType = MotionEvent.ACTION_DOWN; - } else { - mType = MotionEvent.ACTION_POINTER_DOWN; - } + mTime = Gdx.input.getCurrentEventTime(); + if (mPointerDown++ == 0) { + mDownTime = getTime(); + mType = MotionEvent.ACTION_DOWN; + } else { + mType = MotionEvent.ACTION_POINTER_DOWN; + } - mPointerX[pointer] = mCurX = screenX; - mPointerY[pointer] = mCurY = screenY; - mPointer = pointer; - //GdxMap.log.debug("down " + screenX + ":" + screenY - // + " / " + pointer + " " + mPointerDown - // + " " + (getTime() - mDownTime)); + mPointerX[pointer] = mCurX = screenX; + mPointerY[pointer] = mCurY = screenY; + mPointer = pointer; + //GdxMap.log.debug("down " + screenX + ":" + screenY + // + " / " + pointer + " " + mPointerDown + // + " " + (getTime() - mDownTime)); - mMap.input.fire(null, this); - return true; - } + mMap.input.fire(null, this); + return true; + } - @Override - public boolean touchUp(int screenX, int screenY, int pointer, int button) { - if (pointer >= 10) - return true; + @Override + public boolean touchUp(int screenX, int screenY, int pointer, int button) { + if (pointer >= 10) + return true; - if (button != Buttons.LEFT) - return false; + if (button != Buttons.LEFT) + return false; - if (mPointerDown == 0) - return true; + if (mPointerDown == 0) + return true; - mTime = Gdx.input.getCurrentEventTime(); - mType = (--mPointerDown == 0) ? - MotionEvent.ACTION_UP : - MotionEvent.ACTION_POINTER_UP; + mTime = Gdx.input.getCurrentEventTime(); + mType = (--mPointerDown == 0) ? + MotionEvent.ACTION_UP : + MotionEvent.ACTION_POINTER_UP; - mPointerX[pointer] = mCurX = screenX; - mPointerY[pointer] = mCurY = screenY; - mPointer = pointer; + mPointerX[pointer] = mCurX = screenX; + mPointerY[pointer] = mCurY = screenY; + mPointer = pointer; - //GdxMap.log.debug("up " + screenX + ":" + screenY - // + " / " + pointer + " " + mPointerDown - // + " " + (getTime() - mDownTime)); + //GdxMap.log.debug("up " + screenX + ":" + screenY + // + " / " + pointer + " " + mPointerDown + // + " " + (getTime() - mDownTime)); - mMap.input.fire(null, this); - return true; - } + mMap.input.fire(null, this); + return true; + } - @Override - public boolean touchDragged(int screenX, int screenY, int pointer) { - if (pointer >= 10) - return true; + @Override + public boolean touchDragged(int screenX, int screenY, int pointer) { + if (pointer >= 10) + return true; - mTime = Gdx.input.getCurrentEventTime(); - mType = MotionEvent.ACTION_MOVE; + mTime = Gdx.input.getCurrentEventTime(); + mType = MotionEvent.ACTION_MOVE; - mPointerX[pointer] = mCurX = screenX; - mPointerY[pointer] = mCurY = screenY; - mPointer = pointer; + mPointerX[pointer] = mCurX = screenX; + mPointerY[pointer] = mCurY = screenY; + mPointer = pointer; - //GdxMap.log.debug("dragged " + screenX + ":" + screenY - // + " / " + pointer + " " + (getTime() - mDownTime)); + //GdxMap.log.debug("dragged " + screenX + ":" + screenY + // + " / " + pointer + " " + (getTime() - mDownTime)); - mMap.input.fire(null, this); - return true; - } + mMap.input.fire(null, this); + return true; + } - @Override - public boolean mouseMoved(int screenX, int screenY) { - mTime = Gdx.input.getCurrentEventTime(); - mType = MotionEvent.ACTION_MOVE; + @Override + public boolean mouseMoved(int screenX, int screenY) { + mTime = Gdx.input.getCurrentEventTime(); + mType = MotionEvent.ACTION_MOVE; - mPointerX[Buttons.LEFT] = mCurX = screenX; - mPointerY[Buttons.LEFT] = mCurY = screenY; - mPointer = Buttons.LEFT; + mPointerX[Buttons.LEFT] = mCurX = screenX; + mPointerY[Buttons.LEFT] = mCurY = screenY; + mPointer = Buttons.LEFT; - //GdxMap.log.debug("moved " + screenX + ":" + screenY); + //GdxMap.log.debug("moved " + screenX + ":" + screenY); - mMap.input.fire(null, this); - return true; - } + mMap.input.fire(null, this); + return true; + } - @Override - public boolean scrolled(int amount) { - mTime = Gdx.input.getCurrentEventTime(); + @Override + public boolean scrolled(int amount) { + mTime = Gdx.input.getCurrentEventTime(); - return false; - } + return false; + } } diff --git a/vtm-ios/Info.plist.xml b/vtm-ios/Info.plist.xml index 414332e3..c2d27626 100644 --- a/vtm-ios/Info.plist.xml +++ b/vtm-ios/Info.plist.xml @@ -1,62 +1,62 @@ - - + - - CFBundleDevelopmentRegion - en - CFBundleDisplayName - ${app.name} - CFBundleExecutable - ${app.executable} - CFBundleIdentifier - ${app.id} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${app.name} - CFBundlePackageType - APPL - CFBundleShortVersionString - ${app.version} - CFBundleSignature - ???? - CFBundleVersion - ${app.build} - LSRequiresIPhoneOS - - UIStatusBarHidden - - UIViewControllerBasedStatusBarAppearance - - UIDeviceFamily - - 1 - 2 - - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - CFBundleIcons - - CFBundlePrimaryIcon - - CFBundleIconFiles - - Icon - Icon-72 - - - - + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + ${app.name} + CFBundleExecutable + ${app.executable} + CFBundleIdentifier + ${app.id} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${app.name} + CFBundlePackageType + APPL + CFBundleShortVersionString + ${app.version} + CFBundleSignature + ???? + CFBundleVersion + ${app.build} + LSRequiresIPhoneOS + + UIStatusBarHidden + + UIViewControllerBasedStatusBarAppearance + + UIDeviceFamily + + 1 + 2 + + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CFBundleIcons + + CFBundlePrimaryIcon + + CFBundleIconFiles + + Icon + Icon-72 + + + + diff --git a/vtm-ios/robovm.xml b/vtm-ios/robovm.xml index ff0a8149..5f502da2 100644 --- a/vtm-ios/robovm.xml +++ b/vtm-ios/robovm.xml @@ -26,7 +26,8 @@ com.android.org.bouncycastle.jce.provider.BouncyCastleProvider com.android.org.bouncycastle.jcajce.provider.keystore.BC$Mappings com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi - com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi$Std + com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi$Std + com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL org.apache.harmony.security.provider.cert.DRLCertFactory @@ -44,4 +45,4 @@ AudioToolbox AVFoundation - \ No newline at end of file + diff --git a/vtm-ios/src/org/oscim/ios/RobovmLauncher.java b/vtm-ios/src/org/oscim/ios/RobovmLauncher.java index 1b157a34..88c6a8db 100644 --- a/vtm-ios/src/org/oscim/ios/RobovmLauncher.java +++ b/vtm-ios/src/org/oscim/ios/RobovmLauncher.java @@ -2,6 +2,7 @@ package org.oscim.ios; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; + import org.oscim.backend.CanvasAdapter; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.VectorTileLayer; @@ -25,7 +26,7 @@ public class RobovmLauncher extends IOSApplication.Delegate { config.orientationPortrait = true; config.stencilFormat = GLKViewDrawableStencilFormat._8; - float scale = (float)(getIosVersion() >= 8 ? UIScreen.getMainScreen().getNativeScale() : UIScreen.getMainScreen() + float scale = (float) (getIosVersion() >= 8 ? UIScreen.getMainScreen().getNativeScale() : UIScreen.getMainScreen() .getScale()); CanvasAdapter.dpi *= scale; @@ -53,7 +54,7 @@ public class RobovmLauncher extends IOSApplication.Delegate { } - private int getIosVersion () { + private int getIosVersion() { String systemVersion = UIDevice.getCurrentDevice().getSystemVersion(); return Integer.parseInt(systemVersion.split("\\.")[0]); } diff --git a/vtm-ios/src/org/oscim/ios/backend/IosBitmap.java b/vtm-ios/src/org/oscim/ios/backend/IosBitmap.java index 8394145c..a5dcfac9 100644 --- a/vtm-ios/src/org/oscim/ios/backend/IosBitmap.java +++ b/vtm-ios/src/org/oscim/ios/backend/IosBitmap.java @@ -16,11 +16,18 @@ package org.oscim.ios.backend; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Pixmap; + import org.oscim.backend.AssetAdapter; import org.oscim.backend.GL; import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Color; -import org.robovm.apple.coregraphics.*; +import org.robovm.apple.coregraphics.CGBitmapContext; +import org.robovm.apple.coregraphics.CGBlendMode; +import org.robovm.apple.coregraphics.CGColor; +import org.robovm.apple.coregraphics.CGColorSpace; +import org.robovm.apple.coregraphics.CGImage; +import org.robovm.apple.coregraphics.CGImageAlphaInfo; +import org.robovm.apple.coregraphics.CGRect; import org.robovm.apple.foundation.NSData; import org.robovm.apple.uikit.UIColor; import org.robovm.apple.uikit.UIImage; diff --git a/vtm-ios/src/org/oscim/ios/backend/IosGraphics.java b/vtm-ios/src/org/oscim/ios/backend/IosGraphics.java index 18ffc3f4..8f8a1bea 100644 --- a/vtm-ios/src/org/oscim/ios/backend/IosGraphics.java +++ b/vtm-ios/src/org/oscim/ios/backend/IosGraphics.java @@ -14,17 +14,16 @@ */ package org.oscim.ios.backend; -import java.io.IOException; -import java.io.InputStream; - import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Canvas; import org.oscim.backend.canvas.Paint; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; + /** * iOS specific implementation of {@link CanvasAdapter}
*
@@ -32,44 +31,44 @@ import org.slf4j.LoggerFactory; */ public class IosGraphics extends CanvasAdapter { - static final Logger log = LoggerFactory.getLogger(IosGraphics.class); + static final Logger log = LoggerFactory.getLogger(IosGraphics.class); - public static void init() { - CanvasAdapter.init(new IosGraphics()); - } + public static void init() { + CanvasAdapter.init(new IosGraphics()); + } - @Override - protected Canvas newCanvasImpl() { - return new IosCanvas(); - } + @Override + protected Canvas newCanvasImpl() { + return new IosCanvas(); + } - @Override - protected Paint newPaintImpl() { - return new IosPaint(); - } + @Override + protected Paint newPaintImpl() { + return new IosPaint(); + } - @Override - protected Bitmap newBitmapImpl(int width, int height, int format) { - return new IosBitmap(width, height, format); - } + @Override + protected Bitmap newBitmapImpl(int width, int height, int format) { + return new IosBitmap(width, height, format); + } - @Override - protected Bitmap decodeBitmapImpl(InputStream inputStream) { - try { - return new IosBitmap(inputStream); - } catch (IOException e) { - log.error("decodeBitmapImpl",e); - return null; - } - } + @Override + protected Bitmap decodeBitmapImpl(InputStream inputStream) { + try { + return new IosBitmap(inputStream); + } catch (IOException e) { + log.error("decodeBitmapImpl", e); + return null; + } + } - @Override - protected Bitmap loadBitmapAssetImpl(String fileName) { - try { - return new IosBitmap(fileName); - } catch (IOException e) { - log.error("loadBitmapAssetImpl",e); - return null; - } - } + @Override + protected Bitmap loadBitmapAssetImpl(String fileName) { + try { + return new IosBitmap(fileName); + } catch (IOException e) { + log.error("loadBitmapAssetImpl", e); + return null; + } + } } diff --git a/vtm-ios/src/org/oscim/ios/backend/IosPaint.java b/vtm-ios/src/org/oscim/ios/backend/IosPaint.java index b580115c..b791334f 100644 --- a/vtm-ios/src/org/oscim/ios/backend/IosPaint.java +++ b/vtm-ios/src/org/oscim/ios/backend/IosPaint.java @@ -15,7 +15,6 @@ package org.oscim.ios.backend; import org.oscim.backend.canvas.Paint; - import org.robovm.apple.coregraphics.CGAffineTransform; import org.robovm.apple.coregraphics.CGBitmapContext; import org.robovm.apple.coregraphics.CGBlendMode; @@ -27,7 +26,6 @@ import org.robovm.apple.uikit.NSAttributedStringAttributes; import org.robovm.apple.uikit.UIColor; import org.robovm.apple.uikit.UIFont; import org.robovm.apple.uikit.UIFontWeight; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/vtm-jeo/src/org/oscim/jeo/JeoUtils.java b/vtm-jeo/src/org/oscim/jeo/JeoUtils.java index 0395d589..def14a68 100644 --- a/vtm-jeo/src/org/oscim/jeo/JeoUtils.java +++ b/vtm-jeo/src/org/oscim/jeo/JeoUtils.java @@ -3,10 +3,10 @@ package org.oscim.jeo; import org.jeo.map.RGB; public class JeoUtils { - public static int color(RGB rgb) { - return rgb.getAlpha() << 24 - | rgb.getRed() << 16 - | rgb.getGreen() << 8 - | rgb.getBlue(); - } + public static int color(RGB rgb) { + return rgb.getAlpha() << 24 + | rgb.getRed() << 16 + | rgb.getGreen() << 8 + | rgb.getBlue(); + } } diff --git a/vtm-jeo/src/org/oscim/layers/JeoTileSource.java b/vtm-jeo/src/org/oscim/layers/JeoTileSource.java index 3ff258d3..a0cea10e 100644 --- a/vtm-jeo/src/org/oscim/layers/JeoTileSource.java +++ b/vtm-jeo/src/org/oscim/layers/JeoTileSource.java @@ -16,15 +16,8 @@ */ package org.oscim.layers; -import static org.oscim.tiling.QueryResult.FAILED; -import static org.oscim.tiling.QueryResult.SUCCESS; -import static org.oscim.tiling.QueryResult.TILE_NOT_FOUND; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.jeo.tile.TileDataset; import org.jeo.tile.Tile; +import org.jeo.tile.TileDataset; import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Bitmap; import org.oscim.layers.tile.MapTile; @@ -34,73 +27,80 @@ import org.oscim.tiling.TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import static org.oscim.tiling.QueryResult.FAILED; +import static org.oscim.tiling.QueryResult.SUCCESS; +import static org.oscim.tiling.QueryResult.TILE_NOT_FOUND; + public class JeoTileSource extends TileSource { - final static Logger log = LoggerFactory.getLogger(JeoTileSource.class); + final static Logger log = LoggerFactory.getLogger(JeoTileSource.class); - final TileDataset mTileDataset; + final TileDataset mTileDataset; - public JeoTileSource(TileDataset tileDataset) { - log.debug("load tileset {}", tileDataset.name()); - mTileDataset = tileDataset; - //mTileDataset.pyramid(). - mZoomMax = 1; - mZoomMin = 0; - } + public JeoTileSource(TileDataset tileDataset) { + log.debug("load tileset {}", tileDataset.name()); + mTileDataset = tileDataset; + //mTileDataset.pyramid(). + mZoomMax = 1; + mZoomMin = 0; + } - @Override - public ITileDataSource getDataSource() { - return new ITileDataSource() { + @Override + public ITileDataSource getDataSource() { + return new ITileDataSource() { - @Override - public void query(MapTile tile, ITileDataSink sink) { - log.debug("query {}", tile); - try { - Tile t = mTileDataset.read(tile.zoomLevel, tile.tileX, - // flip Y axis - (1 << tile.zoomLevel) - 1 - tile.tileY); - if (t == null) { - log.debug("not found {}", tile); - sink.completed(TILE_NOT_FOUND); - return; - } - Bitmap b = CanvasAdapter.decodeBitmap(new ByteArrayInputStream(t.data())); - sink.setTileImage(b); - log.debug("success {}", tile); - sink.completed(SUCCESS); - return; + @Override + public void query(MapTile tile, ITileDataSink sink) { + log.debug("query {}", tile); + try { + Tile t = mTileDataset.read(tile.zoomLevel, tile.tileX, + // flip Y axis + (1 << tile.zoomLevel) - 1 - tile.tileY); + if (t == null) { + log.debug("not found {}", tile); + sink.completed(TILE_NOT_FOUND); + return; + } + Bitmap b = CanvasAdapter.decodeBitmap(new ByteArrayInputStream(t.data())); + sink.setTileImage(b); + log.debug("success {}", tile); + sink.completed(SUCCESS); + return; - } catch (IOException e) { - e.printStackTrace(); - } - log.debug("fail {}", tile); - sink.completed(FAILED); - } + } catch (IOException e) { + e.printStackTrace(); + } + log.debug("fail {}", tile); + sink.completed(FAILED); + } - @Override - public void dispose() { + @Override + public void dispose() { - } + } - @Override - public void cancel() { + @Override + public void cancel() { - } + } - }; - } + }; + } - int mRefs; + int mRefs; - @Override - public OpenResult open() { - mRefs++; - return OpenResult.SUCCESS; - } + @Override + public OpenResult open() { + mRefs++; + return OpenResult.SUCCESS; + } - @Override - public void close() { - if (--mRefs == 0) - mTileDataset.close(); - } + @Override + public void close() { + if (--mRefs == 0) + mTileDataset.close(); + } } diff --git a/vtm-jeo/src/org/oscim/layers/JeoVectorLayer.java b/vtm-jeo/src/org/oscim/layers/JeoVectorLayer.java index 41231aa4..4a6339fa 100644 --- a/vtm-jeo/src/org/oscim/layers/JeoVectorLayer.java +++ b/vtm-jeo/src/org/oscim/layers/JeoVectorLayer.java @@ -16,17 +16,19 @@ */ package org.oscim.layers; -import java.io.IOException; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.LineString; -import org.jeo.vector.VectorQuery; -import org.jeo.vector.VectorDataset; -import org.jeo.vector.Feature; import org.jeo.geom.Geom; import org.jeo.map.CartoCSS; import org.jeo.map.RGB; import org.jeo.map.Rule; import org.jeo.map.RuleList; import org.jeo.map.Style; +import org.jeo.vector.Feature; +import org.jeo.vector.VectorDataset; +import org.jeo.vector.VectorQuery; import org.oscim.jeo.JeoUtils; import org.oscim.map.Map; import org.oscim.renderer.bucket.LineBucket; @@ -36,133 +38,131 @@ import org.oscim.theme.styles.LineStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.vividsolutions.jts.geom.Envelope; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.LineString; +import java.io.IOException; public class JeoVectorLayer extends JtsLayer { - public static final Logger log = LoggerFactory.getLogger(JeoVectorLayer.class); - static final boolean dbg = false; + public static final Logger log = LoggerFactory.getLogger(JeoVectorLayer.class); + static final boolean dbg = false; - private final VectorDataset mDataset; - private final RuleList mRules; + private final VectorDataset mDataset; + private final RuleList mRules; - protected double mDropPointDistance = 0.01; - private double mMinX; - private double mMinY; + protected double mDropPointDistance = 0.01; + private double mMinX; + private double mMinY; - public JeoVectorLayer(Map map, VectorDataset data, Style style) { - super(map); - mDataset = data; + public JeoVectorLayer(Map map, VectorDataset data, Style style) { + super(map); + mDataset = data; - mRules = style.getRules().selectById(data.name(), true).flatten(); - //mRules = style.getRules().selectById("way", true).flatten(); - log.debug(mRules.toString()); + mRules = style.getRules().selectById(data.name(), true).flatten(); + //mRules = style.getRules().selectById("way", true).flatten(); + log.debug(mRules.toString()); - mRenderer = new Renderer(); - } + mRenderer = new Renderer(); + } - @Override - protected void processFeatures(Task t, Envelope b) { - if (mDropPointDistance > 0) { - /* reduce lines points min distance */ - mMinX = ((b.getMaxX() - b.getMinX()) / mMap.getWidth()); - mMinY = ((b.getMaxY() - b.getMinY()) / mMap.getHeight()); - mMinX *= mDropPointDistance; - mMinY *= mDropPointDistance; - } + @Override + protected void processFeatures(Task t, Envelope b) { + if (mDropPointDistance > 0) { + /* reduce lines points min distance */ + mMinX = ((b.getMaxX() - b.getMinX()) / mMap.getWidth()); + mMinY = ((b.getMaxY() - b.getMinY()) / mMap.getHeight()); + mMinX *= mDropPointDistance; + mMinY *= mDropPointDistance; + } - try { - VectorQuery q = new VectorQuery().bounds(b); - if (dbg) - log.debug("query {}", b); - for (Feature f : mDataset.cursor(q)) { - if (dbg) - log.debug("feature {}", f); + try { + VectorQuery q = new VectorQuery().bounds(b); + if (dbg) + log.debug("query {}", b); + for (Feature f : mDataset.cursor(q)) { + if (dbg) + log.debug("feature {}", f); - RuleList rs = mRules.match(f); - if (rs.isEmpty()) - continue; + RuleList rs = mRules.match(f); + if (rs.isEmpty()) + continue; - Rule r = rs.collapse(); - if (r == null) - continue; + Rule r = rs.collapse(); + if (r == null) + continue; - Geometry g = f.geometry(); - if (g == null) - continue; + Geometry g = f.geometry(); + if (g == null) + continue; - switch (Geom.Type.from(g)) { - case POINT: - addPoint(t, f, r, g); - break; - case MULTIPOINT: - for (int i = 0, n = g.getNumGeometries(); i < n; i++) - addPoint(t, f, r, g.getGeometryN(i)); - break; - case LINESTRING: - addLine(t, f, r, g); - break; - case MULTILINESTRING: - for (int i = 0, n = g.getNumGeometries(); i < n; i++) - addLine(t, f, r, g.getGeometryN(i)); - break; - case POLYGON: - addPolygon(t, f, r, g); - break; - case MULTIPOLYGON: - for (int i = 0, n = g.getNumGeometries(); i < n; i++) - addPolygon(t, f, r, g.getGeometryN(i)); - break; - default: - break; - } - } - } catch (IOException e) { - log.error("Error querying layer " + mDataset.name() + e); - } - } + switch (Geom.Type.from(g)) { + case POINT: + addPoint(t, f, r, g); + break; + case MULTIPOINT: + for (int i = 0, n = g.getNumGeometries(); i < n; i++) + addPoint(t, f, r, g.getGeometryN(i)); + break; + case LINESTRING: + addLine(t, f, r, g); + break; + case MULTILINESTRING: + for (int i = 0, n = g.getNumGeometries(); i < n; i++) + addLine(t, f, r, g.getGeometryN(i)); + break; + case POLYGON: + addPolygon(t, f, r, g); + break; + case MULTIPOLYGON: + for (int i = 0, n = g.getNumGeometries(); i < n; i++) + addPolygon(t, f, r, g.getGeometryN(i)); + break; + default: + break; + } + } + } catch (IOException e) { + log.error("Error querying layer " + mDataset.name() + e); + } + } - protected void addLine(Task t, Feature f, Rule rule, Geometry g) { + protected void addLine(Task t, Feature f, Rule rule, Geometry g) { - if (((LineString) g).isClosed()) { - addPolygon(t, f, rule, g); - return; - } + if (((LineString) g).isClosed()) { + addPolygon(t, f, rule, g); + return; + } - LineBucket ll = t.buckets.getLineBucket(2); - if (ll.line == null) { - RGB color = rule.color(f, CartoCSS.LINE_COLOR, RGB.black); - float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); - ll.line = new LineStyle(0, JeoUtils.color(color), width); - ll.setDropDistance(0.5f); - } + LineBucket ll = t.buckets.getLineBucket(2); + if (ll.line == null) { + RGB color = rule.color(f, CartoCSS.LINE_COLOR, RGB.black); + float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); + ll.line = new LineStyle(0, JeoUtils.color(color), width); + ll.setDropDistance(0.5f); + } - addLine(t, g, ll); - } + addLine(t, g, ll); + } - protected void addPolygon(Task t, Feature f, Rule rule, Geometry g) { + protected void addPolygon(Task t, Feature f, Rule rule, Geometry g) { - LineBucket ll = t.buckets.getLineBucket(1); + LineBucket ll = t.buckets.getLineBucket(1); - if (ll.line == null) { - float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); - RGB color = rule.color(f, CartoCSS.LINE_COLOR, RGB.black); - ll.line = new LineStyle(0, JeoUtils.color(color), width); - ll.setDropDistance(0.5f); - } + if (ll.line == null) { + float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); + RGB color = rule.color(f, CartoCSS.LINE_COLOR, RGB.black); + ll.line = new LineStyle(0, JeoUtils.color(color), width); + ll.setDropDistance(0.5f); + } - MeshBucket mesh = t.buckets.getMeshBucket(0); - if (mesh.area == null) { - int color = JeoUtils.color(rule.color(f, CartoCSS.POLYGON_FILL, RGB.red)); - mesh.area = new AreaStyle(color); - } + MeshBucket mesh = t.buckets.getMeshBucket(0); + if (mesh.area == null) { + int color = JeoUtils.color(rule.color(f, CartoCSS.POLYGON_FILL, RGB.red)); + mesh.area = new AreaStyle(color); + } - addPolygon(t, g, mesh, ll); - } + addPolygon(t, g, mesh, ll); + } - protected void addPoint(Task t, Feature f, Rule rule, Geometry g) { + protected void addPoint(Task t, Feature f, Rule rule, Geometry g) { - } + } } diff --git a/vtm-jeo/src/org/oscim/layers/JtsLayer.java b/vtm-jeo/src/org/oscim/layers/JtsLayer.java index ddfa3913..62747ebc 100644 --- a/vtm-jeo/src/org/oscim/layers/JtsLayer.java +++ b/vtm-jeo/src/org/oscim/layers/JtsLayer.java @@ -16,6 +16,10 @@ */ package org.oscim.layers; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; + import org.jeo.geom.CoordinatePath; import org.oscim.core.Box; import org.oscim.core.GeometryBuffer; @@ -29,92 +33,89 @@ import org.oscim.renderer.bucket.MeshBucket; import org.oscim.utils.geom.SimplifyDP; import org.oscim.utils.geom.SimplifyVW; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Envelope; -import com.vividsolutions.jts.geom.Geometry; - public abstract class JtsLayer extends AbstractVectorLayer { - private double mMinX; - private double mMinY; + private double mMinX; + private double mMinY; - public JtsLayer(Map map) { - super(map); - } + public JtsLayer(Map map) { + super(map); + } - @Override - protected void processFeatures(Task t, Box bbox) { - processFeatures(t, new Envelope(bbox.xmin, bbox.ymin, bbox.xmax, bbox.ymax)); + @Override + protected void processFeatures(Task t, Box bbox) { + processFeatures(t, new Envelope(bbox.xmin, bbox.ymin, bbox.xmax, bbox.ymax)); - } + } - protected abstract void processFeatures(Task t, Envelope e); + protected abstract void processFeatures(Task t, Envelope e); - protected int transformPath(MapPosition pos, GeometryBuffer g, CoordinatePath path) { + protected int transformPath(MapPosition pos, GeometryBuffer g, CoordinatePath path) { - double scale = pos.scale * Tile.SIZE / UNSCALE_COORD; - int cnt = 0; - O: while (path.hasNext()) { - Coordinate c = path.next(); - float x = (float) ((MercatorProjection.longitudeToX(c.x) - pos.x) * scale); - float y = (float) ((MercatorProjection.latitudeToY(c.y) - pos.y) * scale); + double scale = pos.scale * Tile.SIZE / UNSCALE_COORD; + int cnt = 0; + O: + while (path.hasNext()) { + Coordinate c = path.next(); + float x = (float) ((MercatorProjection.longitudeToX(c.x) - pos.x) * scale); + float y = (float) ((MercatorProjection.latitudeToY(c.y) - pos.y) * scale); - switch (path.step()) { - case MOVE_TO: - if (g.isPoly()) - g.startPolygon(); - else if (g.isLine()) - g.startLine(); + switch (path.step()) { + case MOVE_TO: + if (g.isPoly()) + g.startPolygon(); + else if (g.isLine()) + g.startLine(); - cnt++; - g.addPoint(x, y); - break; - case LINE_TO: - cnt++; - g.addPoint(x, y); - break; - case CLOSE: - //g.addPoint(x, y); - //if (g.type == GeometryType.POLY) - break; - case STOP: - break O; - } - } - return cnt; - } + cnt++; + g.addPoint(x, y); + break; + case LINE_TO: + cnt++; + g.addPoint(x, y); + break; + case CLOSE: + //g.addPoint(x, y); + //if (g.type == GeometryType.POLY) + break; + case STOP: + break O; + } + } + return cnt; + } - SimplifyDP mSimpDP = new SimplifyDP(); - SimplifyVW mSimpVW = new SimplifyVW(); + SimplifyDP mSimpDP = new SimplifyDP(); + SimplifyVW mSimpVW = new SimplifyVW(); - protected void addPolygon(Task t, Geometry g, MeshBucket ml, LineBucket ll) { - mGeom.clear(); - mGeom.startPolygon(); + protected void addPolygon(Task t, Geometry g, MeshBucket ml, LineBucket ll) { + mGeom.clear(); + mGeom.startPolygon(); - CoordinatePath p = CoordinatePath.create(g); - if (mMinX > 0 || mMinY > 0) - p.generalize(mMinX, mMinY); + CoordinatePath p = CoordinatePath.create(g); + if (mMinX > 0 || mMinY > 0) + p.generalize(mMinX, mMinY); - if (transformPath(t.position, mGeom, p) < 3) - return; + if (transformPath(t.position, mGeom, p) < 3) + return; - if (!mClipper.clip(mGeom)) - return; + if (!mClipper.clip(mGeom)) + return; - mSimpVW.simplify(mGeom, 0.1f); - mSimpDP.simplify(mGeom, 0.5f); + mSimpVW.simplify(mGeom, 0.1f); + mSimpDP.simplify(mGeom, 0.5f); - ll.addLine(mGeom); - ml.addMesh(mGeom); - } + ll.addLine(mGeom); + ml.addMesh(mGeom); + } - protected void addLine(Task t, Geometry g, LineBucket ll) { - mGeom.clear(); - mGeom.startLine(); + protected void addLine(Task t, Geometry g, LineBucket ll) { + mGeom.clear(); + mGeom.startLine(); - CoordinatePath p = CoordinatePath.create(g); - transformPath(t.position, mGeom, p); + CoordinatePath p = CoordinatePath.create(g); + transformPath(t.position, mGeom, p); - ll.addLine(mGeom); - } + ll.addLine(mGeom); + } } diff --git a/vtm-jeo/src/org/oscim/layers/OSMIndoorLayer.java b/vtm-jeo/src/org/oscim/layers/OSMIndoorLayer.java index 5885aab1..cfd7a131 100644 --- a/vtm-jeo/src/org/oscim/layers/OSMIndoorLayer.java +++ b/vtm-jeo/src/org/oscim/layers/OSMIndoorLayer.java @@ -16,14 +16,16 @@ */ package org.oscim.layers; -import java.util.HashMap; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.LineString; -import org.jeo.vector.VectorDataset; -import org.jeo.vector.Feature; import org.jeo.map.CartoCSS; import org.jeo.map.RGB; import org.jeo.map.Rule; import org.jeo.map.Style; +import org.jeo.vector.Feature; +import org.jeo.vector.VectorDataset; import org.oscim.backend.canvas.Color; import org.oscim.jeo.JeoUtils; import org.oscim.map.Map; @@ -35,132 +37,130 @@ import org.oscim.theme.styles.AreaStyle; import org.oscim.theme.styles.LineStyle; import org.oscim.theme.styles.TextStyle; -import com.vividsolutions.jts.geom.Envelope; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.LineString; +import java.util.HashMap; public class OSMIndoorLayer extends JeoVectorLayer { - protected TextBucket mTextLayer; - protected TextStyle mText = TextStyle.builder() - .fontSize(16).color(Color.BLACK) - .strokeWidth(2.2f).strokeColor(Color.WHITE) - .build(); + protected TextBucket mTextLayer; + protected TextStyle mText = TextStyle.builder() + .fontSize(16).color(Color.BLACK) + .strokeWidth(2.2f).strokeColor(Color.WHITE) + .build(); - public OSMIndoorLayer(Map map, VectorDataset data, Style style) { - super(map, data, style); - } + public OSMIndoorLayer(Map map, VectorDataset data, Style style) { + super(map, data, style); + } - public boolean[] activeLevels = new boolean[10]; + public boolean[] activeLevels = new boolean[10]; - @Override - protected void processFeatures(Task t, Envelope b) { - mTextLayer = new TextBucket(); + @Override + protected void processFeatures(Task t, Envelope b) { + mTextLayer = new TextBucket(); - t.buckets.set(mTextLayer); + t.buckets.set(mTextLayer); - super.processFeatures(t, b); + super.processFeatures(t, b); - //render TextItems to a bitmap and prepare vertex buffer data. - mTextLayer.prepare(); - mTextLayer.clearLabels(); - } + //render TextItems to a bitmap and prepare vertex buffer data. + mTextLayer.prepare(); + mTextLayer.clearLabels(); + } - protected void addLine(Task t, Feature f, Rule rule, Geometry g) { + protected void addLine(Task t, Feature f, Rule rule, Geometry g) { - if (((LineString) g).isClosed()) { - addPolygon(t, f, rule, g); - return; - } + if (((LineString) g).isClosed()) { + addPolygon(t, f, rule, g); + return; + } - int level = getLevel(f); + int level = getLevel(f); - LineBucket ll = t.buckets.getLineBucket(level * 3 + 2); - if (ll.line == null) { - RGB color = rule.color(f, CartoCSS.LINE_COLOR, RGB.black); - float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); - ll.line = new LineStyle(0, JeoUtils.color(color), width); - ll.heightOffset = level * 4; - ll.setDropDistance(0); - } + LineBucket ll = t.buckets.getLineBucket(level * 3 + 2); + if (ll.line == null) { + RGB color = rule.color(f, CartoCSS.LINE_COLOR, RGB.black); + float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); + ll.line = new LineStyle(0, JeoUtils.color(color), width); + ll.heightOffset = level * 4; + ll.setDropDistance(0); + } - addLine(t, g, ll); - } + addLine(t, g, ll); + } - protected void addPolygon(Task t, Feature f, Rule rule, Geometry g) { - int level = getLevel(f); + protected void addPolygon(Task t, Feature f, Rule rule, Geometry g) { + int level = getLevel(f); - LineBucket ll = t.buckets.getLineBucket(level * 3 + 1); + LineBucket ll = t.buckets.getLineBucket(level * 3 + 1); - boolean active = activeLevels[level + 1]; + boolean active = activeLevels[level + 1]; - if (ll.line == null) { - float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); - int color = Color.rainbow((level + 1) / 10f); + if (ll.line == null) { + float width = rule.number(f, CartoCSS.LINE_WIDTH, 1.2f); + int color = Color.rainbow((level + 1) / 10f); - if (level > -2 && !active) - color = Color.fade(color, 0.1f); + if (level > -2 && !active) + color = Color.fade(color, 0.1f); - ll.line = new LineStyle(0, color, width); - ll.heightOffset = level * 4; - ll.setDropDistance(0); - } + ll.line = new LineStyle(0, color, width); + ll.heightOffset = level * 4; + ll.setDropDistance(0); + } - MeshBucket mesh = t.buckets.getMeshBucket(level * 3); - if (mesh.area == null) { - int color = JeoUtils.color(rule.color(f, CartoCSS.POLYGON_FILL, RGB.red)); - if (level > -2 && !active) - color = Color.fade(color, 0.1f); + MeshBucket mesh = t.buckets.getMeshBucket(level * 3); + if (mesh.area == null) { + int color = JeoUtils.color(rule.color(f, CartoCSS.POLYGON_FILL, RGB.red)); + if (level > -2 && !active) + color = Color.fade(color, 0.1f); - mesh.area = new AreaStyle(color); - //mesh.area = new Area(Color.fade(Color.DKGRAY, 0.1f)); - mesh.heightOffset = level * 4f; - } + mesh.area = new AreaStyle(color); + //mesh.area = new Area(Color.fade(Color.DKGRAY, 0.1f)); + mesh.heightOffset = level * 4f; + } - addPolygon(t, g, mesh, ll); + addPolygon(t, g, mesh, ll); - if (active) { - Object o = f.get("name"); - if (o instanceof String) { - float x = 0; - float y = 0; - int n = mGeom.index[0]; - for (int i = 0; i < n;) { - x += mGeom.points[i++]; - y += mGeom.points[i++]; - } + if (active) { + Object o = f.get("name"); + if (o instanceof String) { + float x = 0; + float y = 0; + int n = mGeom.index[0]; + for (int i = 0; i < n; ) { + x += mGeom.points[i++]; + y += mGeom.points[i++]; + } - TextItem ti = TextItem.pool.get(); - ti.set(x / (n / 2) / 8, y / (n / 2) / 8, (String) o, mText); + TextItem ti = TextItem.pool.get(); + ti.set(x / (n / 2) / 8, y / (n / 2) / 8, (String) o, mText); - mTextLayer.addText(ti); - } - } - } + mTextLayer.addText(ti); + } + } + } - @Override - protected void addPoint(Task t, Feature f, Rule rule, Geometry g) { + @Override + protected void addPoint(Task t, Feature f, Rule rule, Geometry g) { - } + } - private int getLevel(Feature f) { - /* not sure if one could match these geojson properties with cartocss */ - Object o = f.get("@relations"); - if (o instanceof HashMap) { - @SuppressWarnings("unchecked") - HashMap tags = (HashMap) o; - @SuppressWarnings("unchecked") - HashMap reltags = (HashMap) tags.get("reltags"); + private int getLevel(Feature f) { + /* not sure if one could match these geojson properties with cartocss */ + Object o = f.get("@relations"); + if (o instanceof HashMap) { + @SuppressWarnings("unchecked") + HashMap tags = (HashMap) o; + @SuppressWarnings("unchecked") + HashMap reltags = (HashMap) tags.get("reltags"); - if (reltags != null) { - o = reltags.get("level"); - if (o instanceof String) { - //log.debug("got level {}", o); - return Integer.parseInt((String) o); - } - } - } - return 0; - } + if (reltags != null) { + o = reltags.get("level"); + if (o instanceof String) { + //log.debug("got level {}", o); + return Integer.parseInt((String) o); + } + } + } + return 0; + } } diff --git a/vtm-jeo/src/org/oscim/test/JeoTest.java b/vtm-jeo/src/org/oscim/test/JeoTest.java index c07323a0..494bd04c 100644 --- a/vtm-jeo/src/org/oscim/test/JeoTest.java +++ b/vtm-jeo/src/org/oscim/test/JeoTest.java @@ -16,26 +16,22 @@ */ package org.oscim.test; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +import com.vividsolutions.jts.geom.Geometry; import org.jeo.carto.Carto; import org.jeo.data.Dataset; -import org.jeo.vector.VectorQuery; -import org.jeo.vector.VectorDataset; import org.jeo.data.mem.MemVector; import org.jeo.data.mem.MemWorkspace; -import org.jeo.vector.Feature; -import org.jeo.vector.Features; -import org.jeo.vector.Schema; -import org.jeo.vector.SchemaBuilder; import org.jeo.geojson.GeoJSONDataset; import org.jeo.geojson.GeoJSONReader; import org.jeo.geom.GeomBuilder; import org.jeo.map.Style; +import org.jeo.vector.Feature; +import org.jeo.vector.Features; +import org.jeo.vector.Schema; +import org.jeo.vector.SchemaBuilder; +import org.jeo.vector.VectorDataset; +import org.jeo.vector.VectorQuery; import org.oscim.layers.OSMIndoorLayer; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.VectorTileLayer; @@ -43,157 +39,161 @@ import org.oscim.map.Map; import org.oscim.renderer.MapRenderer; import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; -import com.vividsolutions.jts.geom.Geometry; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; public class JeoTest { - public static void indoorSketch(Map map, String file) { - MapRenderer.setBackgroundColor(0xff909090); - VectorTileLayer baseLayer = map.setBaseMap(new OSciMap4TileSource()); - map.layers().add(new BuildingLayer(map, baseLayer)); + public static void indoorSketch(Map map, String file) { + MapRenderer.setBackgroundColor(0xff909090); + VectorTileLayer baseLayer = map.setBaseMap(new OSciMap4TileSource()); + map.layers().add(new BuildingLayer(map, baseLayer)); - VectorDataset data = null; - try { - data = JeoTest.readGeoJson(new FileInputStream(new File(file))); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } + VectorDataset data = null; + try { + data = JeoTest.readGeoJson(new FileInputStream(new File(file))); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } - Style style = JeoTest.getStyle(); - map.layers().add(new OSMIndoorLayer(map, data, style)); - } + Style style = JeoTest.getStyle(); + map.layers().add(new OSMIndoorLayer(map, data, style)); + } - public static Style getStyle() { - Style style = null; + public static Style getStyle() { + Style style = null; - try { - style = Carto.parse("" + - "#way {" + - " line-width: 2;" + - " line-color: #c80;" + - " polygon-fill: #44111111;" + - " " + - "}" + - "#states {" + - " line-width: 2.2;" + - " line-color: #c80;" + - " polygon-fill: #44111111;" + - " " + - "}" - ); + try { + style = Carto.parse("" + + "#way {" + + " line-width: 2;" + + " line-color: #c80;" + + " polygon-fill: #44111111;" + + " " + + "}" + + "#states {" + + " line-width: 2.2;" + + " line-color: #c80;" + + " polygon-fill: #44111111;" + + " " + + "}" + ); - return style; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + return style; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } - public static VectorDataset readGeoJson(InputStream is) { - GeoJSONReader r = new GeoJSONReader(); + public static VectorDataset readGeoJson(InputStream is) { + GeoJSONReader r = new GeoJSONReader(); - @SuppressWarnings("resource") - MemWorkspace mem = new MemWorkspace(); + @SuppressWarnings("resource") + MemWorkspace mem = new MemWorkspace(); - //mem.put("layer", data); - try { - Schema s = new SchemaBuilder("way").schema(); + //mem.put("layer", data); + try { + Schema s = new SchemaBuilder("way").schema(); - MemVector memData = mem.create(s); + MemVector memData = mem.create(s); - for (Feature f : r.features(is)) { - //System.out.println("loaded: " + f); - memData.add(f); - } - return memData; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + for (Feature f : r.features(is)) { + //System.out.println("loaded: " + f); + memData.add(f); + } + return memData; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } - public static Dataset getJsonData(String file, boolean memory) { - GeoJSONDataset data = null; + public static Dataset getJsonData(String file, boolean memory) { + GeoJSONDataset data = null; - try { - data = new GeoJSONDataset(new File(file)); - } catch (UnsupportedOperationException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } + try { + data = new GeoJSONDataset(new File(file)); + } catch (UnsupportedOperationException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } - if (memory) { - @SuppressWarnings("resource") - MemWorkspace mem = new MemWorkspace(); + if (memory) { + @SuppressWarnings("resource") + MemWorkspace mem = new MemWorkspace(); - //mem.put("layer", data); - try { + //mem.put("layer", data); + try { - Schema s = data.schema(); - VectorQuery q = new VectorQuery(); + Schema s = data.schema(); + VectorQuery q = new VectorQuery(); - MemVector memData = mem.create(s); + MemVector memData = mem.create(s); - for (Feature f : data.cursor(q)) { - memData.add(f); - } + for (Feature f : data.cursor(q)) { + memData.add(f); + } - //return mem.get("layer"); - return memData; - } catch (IOException e) { - e.printStackTrace(); - } - } - return data; - } + //return mem.get("layer"); + return memData; + } catch (IOException e) { + e.printStackTrace(); + } + } + return data; + } - public static Dataset getMemWorkspace(String layer) { - GeomBuilder gb = new GeomBuilder(4326); + public static Dataset getMemWorkspace(String layer) { + GeomBuilder gb = new GeomBuilder(4326); - @SuppressWarnings("resource") - MemWorkspace mem = new MemWorkspace(); - Schema schema = new SchemaBuilder(layer) - .field("geometry", Geometry.class) - .field("id", Integer.class) - .field("name", String.class) - .field("cost", Double.class).schema(); + @SuppressWarnings("resource") + MemWorkspace mem = new MemWorkspace(); + Schema schema = new SchemaBuilder(layer) + .field("geometry", Geometry.class) + .field("id", Integer.class) + .field("name", String.class) + .field("cost", Double.class).schema(); - MemVector data; - try { - data = mem.create(schema); - } catch (UnsupportedOperationException e) { - e.printStackTrace(); - return null; - } catch (IOException e) { - e.printStackTrace(); - return null; - } + MemVector data; + try { + data = mem.create(schema); + } catch (UnsupportedOperationException e) { + e.printStackTrace(); + return null; + } catch (IOException e) { + e.printStackTrace(); + return null; + } - Geometry g = gb.point(0, 0).toPoint(); - //g.setSRID(4326); + Geometry g = gb.point(0, 0).toPoint(); + //g.setSRID(4326); - data.add(Features.create(null, data.schema(), - g, 1, "anvil", - 10.99)); + data.add(Features.create(null, data.schema(), + g, 1, "anvil", + 10.99)); - data.add(Features.create(null, data.schema(), - gb.points(10, 10, 20, 20).toLineString(), - 2, "bomb", 11.99)); + data.add(Features.create(null, data.schema(), + gb.points(10, 10, 20, 20).toLineString(), + 2, "bomb", 11.99)); - data.add(Features.create(null, data.schema(), - gb.point(100, 10).toPoint().buffer(10), - 3, "dynamite", 12.99)); + data.add(Features.create(null, data.schema(), + gb.point(100, 10).toPoint().buffer(10), + 3, "dynamite", 12.99)); - //Dataset jsonData = new GeoJSONDataset(new File("states.json")); - //mem.put("states", jsonData); + //Dataset jsonData = new GeoJSONDataset(new File("states.json")); + //mem.put("states", jsonData); - try { - return mem.get(layer); - } catch (IOException e) { - e.printStackTrace(); - } + try { + return mem.get(layer); + } catch (IOException e) { + e.printStackTrace(); + } - return null; - } + return null; + } } diff --git a/vtm-jeo/src/org/oscim/theme/carto/MatcherFeature.java b/vtm-jeo/src/org/oscim/theme/carto/MatcherFeature.java index 6eee23c0..1c68832d 100644 --- a/vtm-jeo/src/org/oscim/theme/carto/MatcherFeature.java +++ b/vtm-jeo/src/org/oscim/theme/carto/MatcherFeature.java @@ -16,75 +16,75 @@ */ package org.oscim.theme.carto; -import static java.lang.System.out; - -import java.util.List; -import java.util.Map; - import org.jeo.vector.BasicFeature; import org.oscim.core.Tag; import org.oscim.core.TagSet; +import java.util.List; +import java.util.Map; + +import static java.lang.System.out; + //imitate Feature behaviour for tags and zoom-level class MatcherFeature extends BasicFeature { - TagSet mTags; - Integer mZoom; + TagSet mTags; + Integer mZoom; - void setTags(TagSet tags) { - mTags = tags; - } + void setTags(TagSet tags) { + mTags = tags; + } - void setZoom(int zoom) { - mZoom = Integer.valueOf(zoom); - } + void setZoom(int zoom) { + mZoom = Integer.valueOf(zoom); + } - protected MatcherFeature() { - super(""); - } + protected MatcherFeature() { + super(""); + } - @Override - public Object get(String key) { - //out.println("get(" + key + ")"); + @Override + public Object get(String key) { + //out.println("get(" + key + ")"); - if (key.equals("zoom")) - return mZoom; + if (key.equals("zoom")) + return mZoom; - Tag t = mTags.get(key.intern()); - if (t == null) - return null; + Tag t = mTags.get(key.intern()); + if (t == null) + return null; - //out.println("value: " + t.value); + //out.println("value: " + t.value); - return t.value; - } + return t.value; + } - @Override - public BasicFeature put(String key, Object val) { - out.println("EEEK put()"); - return null; - } + @Override + public BasicFeature put(String key, Object val) { + out.println("EEEK put()"); + return null; + } - @Override - public List list() { - out.println("EEEK list()"); - return null; - } + @Override + public List list() { + out.println("EEEK list()"); + return null; + } - @Override - public Map map() { - out.println("EEEK map()"); - return null; - } + @Override + public Map map() { + out.println("EEEK map()"); + return null; + } - @Override - public Object get(int arg0) { - // TODO Auto-generated method stub - return null; - } + @Override + public Object get(int arg0) { + // TODO Auto-generated method stub + return null; + } - @Override - public BasicFeature set(int arg0, Object arg1) { - // TODO Auto-generated method stub - return null; - } + @Override + public BasicFeature set(int arg0, Object arg1) { + // TODO Auto-generated method stub + return null; + } } diff --git a/vtm-jeo/src/org/oscim/theme/carto/RenderTheme.java b/vtm-jeo/src/org/oscim/theme/carto/RenderTheme.java index a9278fe1..2e10043a 100644 --- a/vtm-jeo/src/org/oscim/theme/carto/RenderTheme.java +++ b/vtm-jeo/src/org/oscim/theme/carto/RenderTheme.java @@ -1,13 +1,5 @@ package org.oscim.theme.carto; -import static java.lang.System.out; -import static org.jeo.map.CartoCSS.BACKGROUND_COLOR; -import static org.jeo.map.CartoCSS.OPACITY; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import org.jeo.carto.Carto; import org.jeo.map.CartoCSS; import org.jeo.map.RGB; @@ -23,244 +15,252 @@ import org.oscim.theme.styles.AreaStyle; import org.oscim.theme.styles.LineStyle; import org.oscim.theme.styles.RenderStyle; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static java.lang.System.out; +import static org.jeo.map.CartoCSS.BACKGROUND_COLOR; +import static org.jeo.map.CartoCSS.OPACITY; + public class RenderTheme implements IRenderTheme { - final String STYLE = "" + + final String STYLE = "" + - "[building = 'yes'] {" + - " z: 1;" + - " polygon-fill: #eee;" + - " [zoom >= 16] {" + - " polygon-fill: #c00;" + - " }" + - "}" + + "[building = 'yes'] {" + + " z: 1;" + + " polygon-fill: #eee;" + + " [zoom >= 16] {" + + " polygon-fill: #c00;" + + " }" + + "}" + - "[admin_level = '2'] {" + - " line-color: #000;" + - " line-width: 1;" + - " z: 1;" + - "}" + + "[admin_level = '2'] {" + + " line-color: #000;" + + " line-width: 1;" + + " z: 1;" + + "}" + - "[admin_level = '2'] {" + - " line-color: #000;" + - " line-width: 1;" + - " z: 1;" + - "}" + + "[admin_level = '2'] {" + + " line-color: #000;" + + " line-width: 1;" + + " z: 1;" + + "}" + - "[admin_level = '4'] {" + - " line-color: #aaa;" + - " line-width: 1;" + - " z: 2;" + - "}" + + "[admin_level = '4'] {" + + " line-color: #aaa;" + + " line-width: 1;" + + " z: 2;" + + "}" + - "[highway = 'motorway'] {" + - " line-color: #a00;" + - " z: 10;" + - "}" + + "[highway = 'motorway'] {" + + " line-color: #a00;" + + " z: 10;" + + "}" + - "[highway = 'primary'] {" + - " line-color: #aa0;" + - " z: 11;" + - "}" + + "[highway = 'primary'] {" + + " line-color: #aa0;" + + " z: 11;" + + "}" + - "[highway = 'residential'],[highway = 'road'],[highway = 'secondary'] {" + - " line-color: #fff;" + - " z: 12;" + - "}" + + "[highway = 'residential'],[highway = 'road'],[highway = 'secondary'] {" + + " line-color: #fff;" + + " z: 12;" + + "}" + - " [landuse = 'forest'] {" + - " polygon-fill: #0a0;" + - " z: 2;" + - "}" + + " [landuse = 'forest'] {" + + " polygon-fill: #0a0;" + + " z: 2;" + + "}" + - "[natural = 'water'] {" + - " polygon-fill: #00a;" + - " z: 3;" + - "}"; + "[natural = 'water'] {" + + " polygon-fill: #00a;" + + " z: 3;" + + "}"; - private Style mStyle; - private RuleList mRules; + private Style mStyle; + private RuleList mRules; - MatcherFeature mMatchFeature = new MatcherFeature(); - private int mBackground; + MatcherFeature mMatchFeature = new MatcherFeature(); + private int mBackground; - public RenderTheme() { + public RenderTheme() { - try { - mStyle = loadStyle(); - } catch (IOException e) { - e.printStackTrace(); - } + try { + mStyle = loadStyle(); + } catch (IOException e) { + e.printStackTrace(); + } - // get map background - RuleList rules = mStyle.getRules().selectByName("Map", false, false); - if (!rules.isEmpty()) { - Rule rule = rules.collapse(); - RGB bgColor = rule.color(null, BACKGROUND_COLOR, null); - if (bgColor != null) { - bgColor = bgColor.alpha(rule.number(null, OPACITY, 1f)); - mBackground = color(bgColor); - } - } + // get map background + RuleList rules = mStyle.getRules().selectByName("Map", false, false); + if (!rules.isEmpty()) { + Rule rule = rules.collapse(); + RGB bgColor = rule.color(null, BACKGROUND_COLOR, null); + if (bgColor != null) { + bgColor = bgColor.alpha(rule.number(null, OPACITY, 1f)); + mBackground = color(bgColor); + } + } - mRules = mStyle.getRules(); + mRules = mStyle.getRules(); - //out.println(mRules); - //out.println(); - if (mRules.get(1).equals(mRules.get(2))) - out.println("ok"); + //out.println(mRules); + //out.println(); + if (mRules.get(1).equals(mRules.get(2))) + out.println("ok"); - for (Rule r : mRules) - out.println(formatRule(r, 0)); - } + for (Rule r : mRules) + out.println(formatRule(r, 0)); + } - class StyleSet { - int level; - RenderStyle[] ri = new RenderStyle[2]; - } + class StyleSet { + int level; + RenderStyle[] ri = new RenderStyle[2]; + } - Map mStyleSets = new HashMap(); - int mCurLevel = 0; + Map mStyleSets = new HashMap(); + int mCurLevel = 0; - public String formatRule(Rule r, int indent) { - StringBuilder sb = new StringBuilder(); + public String formatRule(Rule r, int indent) { + StringBuilder sb = new StringBuilder(); - String pad = ""; - for (int i = 0; i < indent; i++) - pad += " "; + String pad = ""; + for (int i = 0; i < indent; i++) + pad += " "; - sb.append(pad); + sb.append(pad); - if (sb.length() > 0) - sb.setLength(sb.length() - 1); + if (sb.length() > 0) + sb.setLength(sb.length() - 1); - sb.append(pad).append(" {").append("\n"); + sb.append(pad).append(" {").append("\n"); - StyleSet s = new StyleSet(); - RGB l = null; - RGB p = null; - if (r.properties().containsKey(CartoCSS.LINE_COLOR)) { - l = r.color(null, CartoCSS.LINE_COLOR, RGB.black); - } - if (r.properties().containsKey(CartoCSS.POLYGON_FILL)) { - p = r.color(null, CartoCSS.POLYGON_FILL, RGB.black); - } + StyleSet s = new StyleSet(); + RGB l = null; + RGB p = null; + if (r.properties().containsKey(CartoCSS.LINE_COLOR)) { + l = r.color(null, CartoCSS.LINE_COLOR, RGB.black); + } + if (r.properties().containsKey(CartoCSS.POLYGON_FILL)) { + p = r.color(null, CartoCSS.POLYGON_FILL, RGB.black); + } - if (p != null) { - s.ri[0] = new AreaStyle(mCurLevel++, color(p)); - } + if (p != null) { + s.ri[0] = new AreaStyle(mCurLevel++, color(p)); + } - if (l != null) { - s.ri[1] = new LineStyle(mCurLevel++, color(l), 1); - } + if (l != null) { + s.ri[1] = new LineStyle(mCurLevel++, color(l), 1); + } - if (p != null || l != null) { - mStyleSets.put(r, s); - out.println("put " + s.ri[0] + s.ri[1]); - } + if (p != null || l != null) { + mStyleSets.put(r, s); + out.println("put " + s.ri[0] + s.ri[1]); + } - for (Map.Entry e : r.properties().entrySet()) { - sb.append(pad).append(" ").append(e.getKey()).append(": ").append(e.getValue()) - .append(";\n"); - } + for (Map.Entry e : r.properties().entrySet()) { + sb.append(pad).append(" ").append(e.getKey()).append(": ").append(e.getValue()) + .append(";\n"); + } - for (Rule nested : r.nested()) { - sb.append(formatRule(nested, indent + 2)).append("\n"); - } + for (Rule nested : r.nested()) { + sb.append(formatRule(nested, indent + 2)).append("\n"); + } - sb.append(pad).append("}"); - return sb.toString(); - } + sb.append(pad).append("}"); + return sb.toString(); + } - Style loadStyle() throws IOException { - return Carto.parse(STYLE); - } + Style loadStyle() throws IOException { + return Carto.parse(STYLE); + } - @Override - public synchronized RenderStyle[] matchElement(GeometryType type, TagSet tags, - int zoomLevel) { - MatcherFeature f = mMatchFeature; + @Override + public synchronized RenderStyle[] matchElement(GeometryType type, TagSet tags, + int zoomLevel) { + MatcherFeature f = mMatchFeature; - f.setTags(tags); - f.setZoom(zoomLevel); + f.setTags(tags); + f.setZoom(zoomLevel); - RuleList rules = mRules.match(f); + RuleList rules = mRules.match(f); - Rule r = rules.collapse(); + Rule r = rules.collapse(); - //out.println(r); - if (rules.isEmpty()) - return null; + //out.println(r); + if (rules.isEmpty()) + return null; - int z = r.number(f, "z", 0f).intValue(); + int z = r.number(f, "z", 0f).intValue(); - if (type == GeometryType.POLY) { - RGB c = r.color(f, CartoCSS.POLYGON_FILL, RGB.black); - out.println(z + " " + c); - return new RenderStyle[] { - new AreaStyle(z, color(c)) - }; + if (type == GeometryType.POLY) { + RGB c = r.color(f, CartoCSS.POLYGON_FILL, RGB.black); + out.println(z + " " + c); + return new RenderStyle[]{ + new AreaStyle(z, color(c)) + }; - } else if (type == GeometryType.LINE) { - RGB c = r.color(f, CartoCSS.LINE_COLOR, RGB.black); - float width = r.number(f, CartoCSS.LINE_WIDTH, 2f); - //out.println(z + " " + c); + } else if (type == GeometryType.LINE) { + RGB c = r.color(f, CartoCSS.LINE_COLOR, RGB.black); + float width = r.number(f, CartoCSS.LINE_WIDTH, 2f); + //out.println(z + " " + c); - return new RenderStyle[] { - new LineStyle(100 + z, color(c), width) - }; + return new RenderStyle[]{ + new LineStyle(100 + z, color(c), width) + }; - } else if (type == GeometryType.POINT) { - //RGB c = r.color(f, CartoCSS.MARKER_FILL, RGB.black); - //out.println(c); - //return new RenderInstruction[] { - // new Caption(color(c), width) - //}; - } + } else if (type == GeometryType.POINT) { + //RGB c = r.color(f, CartoCSS.MARKER_FILL, RGB.black); + //out.println(c); + //return new RenderInstruction[] { + // new Caption(color(c), width) + //}; + } - return null; - } + return null; + } - public static int color(RGB rgb) { - return rgb.getAlpha() << 24 - | rgb.getRed() << 16 - | rgb.getGreen() << 8 - | rgb.getBlue(); - } + public static int color(RGB rgb) { + return rgb.getAlpha() << 24 + | rgb.getRed() << 16 + | rgb.getGreen() << 8 + | rgb.getBlue(); + } - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public int getLevels() { - return 1; - } + @Override + public int getLevels() { + return 1; + } - @Override - public int getMapBackground() { - return mBackground; - } + @Override + public int getMapBackground() { + return mBackground; + } - @Override - public void scaleTextSize(float scaleFactor) { - } + @Override + public void scaleTextSize(float scaleFactor) { + } - public static void main(String[] args) { - RenderTheme t = new RenderTheme(); + public static void main(String[] args) { + RenderTheme t = new RenderTheme(); - MapElement e = new MapElement(); - e.startPolygon(); - e.tags.add(new Tag("building", "yes")); + MapElement e = new MapElement(); + e.startPolygon(); + e.tags.add(new Tag("building", "yes")); - t.matchElement(GeometryType.POLY, e.tags, 16); - t.matchElement(GeometryType.POLY, e.tags, 15); - } + t.matchElement(GeometryType.POLY, e.tags, 16); + t.matchElement(GeometryType.POLY, e.tags, 15); + } - @Override - public void updateStyles() { - // TODO Auto-generated method stub + @Override + public void updateStyles() { + // TODO Auto-generated method stub - } + } } diff --git a/vtm-jts/src/org/oscim/layers/JtsPathLayer.java b/vtm-jts/src/org/oscim/layers/JtsPathLayer.java index 0e544f51..6c63c63d 100644 --- a/vtm-jts/src/org/oscim/layers/JtsPathLayer.java +++ b/vtm-jts/src/org/oscim/layers/JtsPathLayer.java @@ -18,8 +18,7 @@ package org.oscim.layers; -import java.util.ArrayList; -import java.util.List; +import com.vividsolutions.jts.geom.LineString; import org.oscim.core.GeoPoint; import org.oscim.layers.vector.VectorLayer; @@ -28,177 +27,175 @@ import org.oscim.layers.vector.geometries.Style; import org.oscim.map.Map; import org.oscim.utils.geom.GeomBuilder; -import com.vividsolutions.jts.geom.LineString; +import java.util.ArrayList; +import java.util.List; -/** This class draws a path line in given color. */ +/** + * This class draws a path line in given color. + */ public class JtsPathLayer extends VectorLayer { - protected final ArrayList mPoints; + protected final ArrayList mPoints; - protected Style mStyle; - protected LineDrawable mDrawable; + protected Style mStyle; + protected LineDrawable mDrawable; - public JtsPathLayer(Map map, int lineColor, float lineWidth) { - super(map); - mStyle = Style.builder() - .strokeColor(lineColor) - .strokeWidth(lineWidth) - .build(); + public JtsPathLayer(Map map, int lineColor, float lineWidth) { + super(map); + mStyle = Style.builder() + .strokeColor(lineColor) + .strokeWidth(lineWidth) + .build(); - mPoints = new ArrayList(); - } + mPoints = new ArrayList(); + } - public JtsPathLayer(Map map, int lineColor) { - this(map, lineColor, 2); - } + public JtsPathLayer(Map map, int lineColor) { + this(map, lineColor, 2); + } - public void setStyle(int lineColor, float lineWidth) { - mStyle = Style.builder() - .strokeColor(lineColor) - .strokeWidth(lineWidth) - .build(); - } + public void setStyle(int lineColor, float lineWidth) { + mStyle = Style.builder() + .strokeColor(lineColor) + .strokeWidth(lineWidth) + .build(); + } - public void clearPath() { - if (!mPoints.isEmpty()) - mPoints.clear(); + public void clearPath() { + if (!mPoints.isEmpty()) + mPoints.clear(); - updatePoints(); - } + updatePoints(); + } - public void setPoints(List pts) { - mPoints.clear(); - mPoints.addAll(pts); - updatePoints(); - } + public void setPoints(List pts) { + mPoints.clear(); + mPoints.addAll(pts); + updatePoints(); + } - public void addPoint(GeoPoint pt) { - mPoints.add(pt); - updatePoints(); - } + public void addPoint(GeoPoint pt) { + mPoints.add(pt); + updatePoints(); + } - public void addPoint(int latitudeE6, int longitudeE6) { - mPoints.add(new GeoPoint(latitudeE6, longitudeE6)); - updatePoints(); - } + public void addPoint(int latitudeE6, int longitudeE6) { + mPoints.add(new GeoPoint(latitudeE6, longitudeE6)); + updatePoints(); + } - private void updatePoints() { - synchronized (this) { + private void updatePoints() { + synchronized (this) { - if (mDrawable != null) { - remove(mDrawable); - mDrawable = null; - } + if (mDrawable != null) { + remove(mDrawable); + mDrawable = null; + } - if (!mPoints.isEmpty()) { - mDrawable = new LineDrawable(mPoints, mStyle); - if (mDrawable.getGeometry() == null) - mDrawable = null; - else - add(mDrawable); - } - } - mWorker.submit(0); - } + if (!mPoints.isEmpty()) { + mDrawable = new LineDrawable(mPoints, mStyle); + if (mDrawable.getGeometry() == null) + mDrawable = null; + else + add(mDrawable); + } + } + mWorker.submit(0); + } - public List getPoints() { - return mPoints; - } + public List getPoints() { + return mPoints; + } - /** - * Draw a great circle. Calculate a point for every 100km along the path. - * - * @param startPoint - * start point of the great circle - * @param endPoint - * end point of the great circle - */ - public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint) { - synchronized (mPoints) { + /** + * Draw a great circle. Calculate a point for every 100km along the path. + * + * @param startPoint start point of the great circle + * @param endPoint end point of the great circle + */ + public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint) { + synchronized (mPoints) { /* get the great circle path length in meters */ - double length = startPoint.distanceTo(endPoint); + double length = startPoint.distanceTo(endPoint); /* add one point for every 100kms of the great circle path */ - int numberOfPoints = (int) (length / 100000); + int numberOfPoints = (int) (length / 100000); - addGreatCircle(startPoint, endPoint, numberOfPoints); - } - } + addGreatCircle(startPoint, endPoint, numberOfPoints); + } + } - /** - * Draw a great circle. - * - * @param startPoint - * start point of the great circle - * @param endPoint - * end point of the great circle - * @param numberOfPoints - * number of points to calculate along the path - */ - public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint, - final int numberOfPoints) { - /* adapted from page - * http://compastic.blogspot.co.uk/2011/07/how-to-draw-great-circle-on-map + /** + * Draw a great circle. + * + * @param startPoint start point of the great circle + * @param endPoint end point of the great circle + * @param numberOfPoints number of points to calculate along the path + */ + public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint, + final int numberOfPoints) { + /* adapted from page + * http://compastic.blogspot.co.uk/2011/07/how-to-draw-great-circle-on-map * -in.html * which was adapted from page http://maps.forum.nu/gm_flight_path.html */ - GeomBuilder gb = new GeomBuilder(); + GeomBuilder gb = new GeomBuilder(); /* convert to radians */ - double lat1 = startPoint.getLatitude() * Math.PI / 180; - double lon1 = startPoint.getLongitude() * Math.PI / 180; - double lat2 = endPoint.getLatitude() * Math.PI / 180; - double lon2 = endPoint.getLongitude() * Math.PI / 180; + double lat1 = startPoint.getLatitude() * Math.PI / 180; + double lon1 = startPoint.getLongitude() * Math.PI / 180; + double lat2 = endPoint.getLatitude() * Math.PI / 180; + double lon2 = endPoint.getLongitude() * Math.PI / 180; - double d = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) - + Math.cos(lat1) * Math.cos(lat2) - * Math.pow(Math.sin((lon1 - lon2) / 2), 2))); - double bearing = Math.atan2( - Math.sin(lon1 - lon2) * Math.cos(lat2), - Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) - * Math.cos(lat2) - * Math.cos(lon1 - lon2)) - / -(Math.PI / 180); - bearing = bearing < 0 ? 360 + bearing : bearing; + double d = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + + Math.cos(lat1) * Math.cos(lat2) + * Math.pow(Math.sin((lon1 - lon2) / 2), 2))); + double bearing = Math.atan2( + Math.sin(lon1 - lon2) * Math.cos(lat2), + Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) + * Math.cos(lat2) + * Math.cos(lon1 - lon2)) + / -(Math.PI / 180); + bearing = bearing < 0 ? 360 + bearing : bearing; - for (int i = 0, j = numberOfPoints + 1; i < j; i++) { - double f = 1.0 / numberOfPoints * i; - double A = Math.sin((1 - f) * d) / Math.sin(d); - double B = Math.sin(f * d) / Math.sin(d); - double x = A * Math.cos(lat1) * Math.cos(lon1) + B * Math.cos(lat2) - * Math.cos(lon2); - double y = A * Math.cos(lat1) * Math.sin(lon1) + B * Math.cos(lat2) - * Math.sin(lon2); - double z = A * Math.sin(lat1) + B * Math.sin(lat2); + for (int i = 0, j = numberOfPoints + 1; i < j; i++) { + double f = 1.0 / numberOfPoints * i; + double A = Math.sin((1 - f) * d) / Math.sin(d); + double B = Math.sin(f * d) / Math.sin(d); + double x = A * Math.cos(lat1) * Math.cos(lon1) + B * Math.cos(lat2) + * Math.cos(lon2); + double y = A * Math.cos(lat1) * Math.sin(lon1) + B * Math.cos(lat2) + * Math.sin(lon2); + double z = A * Math.sin(lat1) + B * Math.sin(lat2); - double latN = Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))); - double lonN = Math.atan2(y, x); + double latN = Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))); + double lonN = Math.atan2(y, x); - gb.point(latN / (Math.PI / 180), lonN / (Math.PI / 180)); - } + gb.point(latN / (Math.PI / 180), lonN / (Math.PI / 180)); + } - setLineString(gb.toLineString()); - } + setLineString(gb.toLineString()); + } - public void setLineString(LineString path) { - synchronized (this) { - if (mDrawable != null) - remove(mDrawable); - mDrawable = new LineDrawable(path, mStyle); - add(mDrawable); - } - mWorker.submit(0); - } + public void setLineString(LineString path) { + synchronized (this) { + if (mDrawable != null) + remove(mDrawable); + mDrawable = new LineDrawable(path, mStyle); + add(mDrawable); + } + mWorker.submit(0); + } - public void setLineString(double[] lonLat) { - synchronized (this) { - if (mDrawable != null) - remove(mDrawable); - mDrawable = new LineDrawable(lonLat, mStyle); - add(mDrawable); - } - mWorker.submit(0); - } + public void setLineString(double[] lonLat) { + synchronized (this) { + if (mDrawable != null) + remove(mDrawable); + mDrawable = new LineDrawable(lonLat, mStyle); + add(mDrawable); + } + mWorker.submit(0); + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/JtsConverter.java b/vtm-jts/src/org/oscim/layers/vector/JtsConverter.java index ec62c535..9741457b 100644 --- a/vtm-jts/src/org/oscim/layers/vector/JtsConverter.java +++ b/vtm-jts/src/org/oscim/layers/vector/JtsConverter.java @@ -1,81 +1,81 @@ package org.oscim.layers.vector; -import static org.oscim.core.MercatorProjection.latitudeToY; -import static org.oscim.core.MercatorProjection.longitudeToX; - -import org.oscim.core.GeometryBuffer; - import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; +import org.oscim.core.GeometryBuffer; + +import static org.oscim.core.MercatorProjection.latitudeToY; +import static org.oscim.core.MercatorProjection.longitudeToX; + public class JtsConverter { - double x, y, scale; - final double outScale; + double x, y, scale; + final double outScale; - public void setPosition(double x, double y, double scale) { - this.x = x; - this.y = y; - this.scale = scale * outScale; - } + public void setPosition(double x, double y, double scale) { + this.x = x; + this.y = y; + this.scale = scale * outScale; + } - public JtsConverter(double outScale) { - this.outScale = outScale; - } + public JtsConverter(double outScale) { + this.outScale = outScale; + } - private final Coordinate mTmpCoord = new Coordinate(); + private final Coordinate mTmpCoord = new Coordinate(); - public void transformPolygon(GeometryBuffer g, Polygon polygon) { - Coordinate coord = mTmpCoord; + public void transformPolygon(GeometryBuffer g, Polygon polygon) { + Coordinate coord = mTmpCoord; - CoordinateSequence ring = polygon.getExteriorRing().getCoordinateSequence(); + CoordinateSequence ring = polygon.getExteriorRing().getCoordinateSequence(); - g.startPolygon(); - for (int j = 0; j < ring.size() - 1; j++) { - ring.getCoordinate(j, coord); - addPoint(g, coord); - } - for (int j = 0, n = polygon.getNumInteriorRing(); j < n; j++) { - g.startHole(); - ring = polygon.getInteriorRingN(j).getCoordinateSequence(); - for (int k = 0; k < ring.size() - 1; k++) { - ring.getCoordinate(k, coord); - addPoint(g, coord); - } - } - } + g.startPolygon(); + for (int j = 0; j < ring.size() - 1; j++) { + ring.getCoordinate(j, coord); + addPoint(g, coord); + } + for (int j = 0, n = polygon.getNumInteriorRing(); j < n; j++) { + g.startHole(); + ring = polygon.getInteriorRingN(j).getCoordinateSequence(); + for (int k = 0; k < ring.size() - 1; k++) { + ring.getCoordinate(k, coord); + addPoint(g, coord); + } + } + } - public void transformLineString(GeometryBuffer g, LineString linestring) { - Coordinate coord = mTmpCoord; + public void transformLineString(GeometryBuffer g, LineString linestring) { + Coordinate coord = mTmpCoord; - CoordinateSequence line = linestring.getCoordinateSequence(); + CoordinateSequence line = linestring.getCoordinateSequence(); - g.startLine(); - for (int j = 0, n = line.size(); j < n; j++) { - line.getCoordinate(j, coord); - addPoint(g, coord); - } - } + g.startLine(); + for (int j = 0, n = line.size(); j < n; j++) { + line.getCoordinate(j, coord); + addPoint(g, coord); + } + } - public void transformPoint(GeometryBuffer g, Point point) { - Coordinate coord = mTmpCoord; + public void transformPoint(GeometryBuffer g, Point point) { + Coordinate coord = mTmpCoord; - g.startPoints(); - coord.x = point.getX(); - coord.y = point.getY(); - addPoint(g, coord); - } + g.startPoints(); + coord.x = point.getX(); + coord.y = point.getY(); + addPoint(g, coord); + } - public void addPoint(GeometryBuffer g, Coordinate coord) { - g.addPoint((float) ((longitudeToX(coord.x) - x) * scale), - (float) ((latitudeToY(coord.y) - y) * scale)); - } + public void addPoint(GeometryBuffer g, Coordinate coord) { + g.addPoint((float) ((longitudeToX(coord.x) - x) * scale), + (float) ((latitudeToY(coord.y) - y) * scale)); + } - public void addPoint(GeometryBuffer g, double lon, double lat) { - g.addPoint((float) ((longitudeToX(lon) - x) * scale), - (float) ((latitudeToY(lat) - y) * scale)); - } + public void addPoint(GeometryBuffer g, double lon, double lat) { + g.addPoint((float) ((longitudeToX(lon) - x) * scale), + (float) ((latitudeToY(lat) - y) * scale)); + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/VectorLayer.java b/vtm-jts/src/org/oscim/layers/vector/VectorLayer.java index a4067c22..c8050fde 100644 --- a/vtm-jts/src/org/oscim/layers/vector/VectorLayer.java +++ b/vtm-jts/src/org/oscim/layers/vector/VectorLayer.java @@ -1,10 +1,11 @@ package org.oscim.layers.vector; -import static org.oscim.core.MercatorProjection.latitudeToY; -import static org.oscim.core.MercatorProjection.longitudeToX; - -import java.util.ArrayList; -import java.util.List; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.LineString; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; +import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier; import org.oscim.backend.canvas.Color; import org.oscim.core.Box; @@ -26,12 +27,11 @@ import org.oscim.utils.SpatialIndex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.vividsolutions.jts.geom.Envelope; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.LineString; -import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; -import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier; +import java.util.ArrayList; +import java.util.List; + +import static org.oscim.core.MercatorProjection.latitudeToY; +import static org.oscim.core.MercatorProjection.longitudeToX; /* TODO keep bounding box of geometries - only try to render when bbox intersects viewport */ @@ -39,283 +39,282 @@ import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier; * Use this layer to draw predefined geometries from layers.vector.geometries * package and * JTS geometries together with a GeometryStyle - * */ public class VectorLayer extends AbstractVectorLayer { - public static final Logger log = LoggerFactory.getLogger(VectorLayer.class); + public static final Logger log = LoggerFactory.getLogger(VectorLayer.class); - //private final SpatialIndex mDrawables = new RTree(); - protected final SpatialIndex mDrawables = new QuadTree(1 << 30, 18); + //private final SpatialIndex mDrawables = new RTree(); + protected final SpatialIndex mDrawables = new QuadTree(1 << 30, 18); - protected final List tmpDrawables = new ArrayList(128); + protected final List tmpDrawables = new ArrayList(128); - protected final JtsConverter mConverter; - protected double mMinX; - protected double mMinY; + protected final JtsConverter mConverter; + protected double mMinX; + protected double mMinY; - private static class GeometryWithStyle implements Drawable { - final Geometry geometry; - final Style style; + private static class GeometryWithStyle implements Drawable { + final Geometry geometry; + final Style style; - GeometryWithStyle(Geometry g, Style s) { - geometry = g; - style = s; - } + GeometryWithStyle(Geometry g, Style s) { + geometry = g; + style = s; + } - @Override - public Style getStyle() { - return style; - } + @Override + public Style getStyle() { + return style; + } - @Override - public Geometry getGeometry() { - return geometry; - } - } + @Override + public Geometry getGeometry() { + return geometry; + } + } - protected Polygon mEnvelope; + protected Polygon mEnvelope; - public VectorLayer(Map map, SpatialIndex index) { - this(map); - } + public VectorLayer(Map map, SpatialIndex index) { + this(map); + } - public VectorLayer(Map map) { - super(map); - mConverter = new JtsConverter(Tile.SIZE / UNSCALE_COORD); - } + public VectorLayer(Map map) { + super(map); + mConverter = new JtsConverter(Tile.SIZE / UNSCALE_COORD); + } - private static Box bbox(Geometry geometry, Style style) { - Envelope e = geometry.getEnvelopeInternal(); - Box bbox = new Box(e.getMinX(), e.getMinY(), e.getMaxX(), e.getMaxY()); - //if ("Point".equals(geometry.getGeometryType())){ - // bbox. - //} + private static Box bbox(Geometry geometry, Style style) { + Envelope e = geometry.getEnvelopeInternal(); + Box bbox = new Box(e.getMinX(), e.getMinY(), e.getMaxX(), e.getMaxY()); + //if ("Point".equals(geometry.getGeometryType())){ + // bbox. + //} - bbox.scale(1E6); - return bbox; - } + bbox.scale(1E6); + return bbox; + } - /** - * Adds a drawable to a list of geometries that have to be drawn in the next - * map update. - * - * @param drawable - */ - public void add(Drawable drawable) { - mDrawables.insert(bbox(drawable.getGeometry(), drawable.getStyle()), drawable); - } + /** + * Adds a drawable to a list of geometries that have to be drawn in the next + * map update. + * + * @param drawable + */ + public void add(Drawable drawable) { + mDrawables.insert(bbox(drawable.getGeometry(), drawable.getStyle()), drawable); + } - /** - * Adds a JTS geometry and a style to a list of geometries that have to be - * drawn in the next map update. - * - * @param geometry - * @param style - */ - public synchronized void add(Geometry geometry, Style style) { - mDrawables.insert(bbox(geometry, style), new GeometryWithStyle(geometry, style)); - } + /** + * Adds a JTS geometry and a style to a list of geometries that have to be + * drawn in the next map update. + * + * @param geometry + * @param style + */ + public synchronized void add(Geometry geometry, Style style) { + mDrawables.insert(bbox(geometry, style), new GeometryWithStyle(geometry, style)); + } - /** - * Removes the drawable from the list of drawn geometries. - * - * @param drawable - */ - public synchronized void remove(Drawable drawable) { - mDrawables.remove(bbox(drawable.getGeometry(), drawable.getStyle()), drawable); - } + /** + * Removes the drawable from the list of drawn geometries. + * + * @param drawable + */ + public synchronized void remove(Drawable drawable) { + mDrawables.remove(bbox(drawable.getGeometry(), drawable.getStyle()), drawable); + } - /** - * removes the JTS geometry and its style from the list of drawn geometries. - * - * @param geometry - */ - public synchronized void remove(Geometry geometry) { - Drawable toRemove = null; - Box bbox = bbox(geometry, null); + /** + * removes the JTS geometry and its style from the list of drawn geometries. + * + * @param geometry + */ + public synchronized void remove(Geometry geometry) { + Drawable toRemove = null; + Box bbox = bbox(geometry, null); - synchronized (this) { - tmpDrawables.clear(); - mDrawables.search(bbox, tmpDrawables); - for (Drawable d : tmpDrawables) { - if (d.getGeometry() == geometry) - toRemove = d; - } - } + synchronized (this) { + tmpDrawables.clear(); + mDrawables.search(bbox, tmpDrawables); + for (Drawable d : tmpDrawables) { + if (d.getGeometry() == geometry) + toRemove = d; + } + } - if (toRemove == null) { - log.error("Can't find geometry to remove."); - return; - } + if (toRemove == null) { + log.error("Can't find geometry to remove."); + return; + } - mDrawables.remove(bbox, toRemove); - //mMap.render(); - } + mDrawables.remove(bbox, toRemove); + //mMap.render(); + } - @Override - protected void processFeatures(Task t, Box bbox) { - //log.debug("bbox {}", bbox); - if (Double.isNaN(bbox.xmin)) - return; + @Override + protected void processFeatures(Task t, Box bbox) { + //log.debug("bbox {}", bbox); + if (Double.isNaN(bbox.xmin)) + return; - // mEnvelope = new GeomBuilder() - // .point(bbox.xmin, bbox.ymin) - // .point(bbox.xmin, bbox.ymax) - // .point(bbox.xmax, bbox.ymax) - // .point(bbox.xmax, bbox.ymin) - // .point(bbox.xmin, bbox.ymin) - // .toPolygon(); + // mEnvelope = new GeomBuilder() + // .point(bbox.xmin, bbox.ymin) + // .point(bbox.xmin, bbox.ymax) + // .point(bbox.xmax, bbox.ymax) + // .point(bbox.xmax, bbox.ymin) + // .point(bbox.xmin, bbox.ymin) + // .toPolygon(); /* reduce lines points min distance */ - mMinX = ((bbox.xmax - bbox.xmin) / mMap.getWidth()); - mMinY = ((bbox.ymax - bbox.ymin) / mMap.getHeight()); + mMinX = ((bbox.xmax - bbox.xmin) / mMap.getWidth()); + mMinY = ((bbox.ymax - bbox.ymin) / mMap.getHeight()); - mConverter.setPosition(t.position.x, t.position.y, t.position.scale); + mConverter.setPosition(t.position.x, t.position.y, t.position.scale); - bbox.scale(1E6); + bbox.scale(1E6); - int level = 0; - Style lastStyle = null; + int level = 0; + Style lastStyle = null; /* go through features, find the matching style and draw */ - synchronized (this) { - tmpDrawables.clear(); - mDrawables.search(bbox, tmpDrawables); - // TODO sort by some order... + synchronized (this) { + tmpDrawables.clear(); + mDrawables.search(bbox, tmpDrawables); + // TODO sort by some order... - for (Drawable d : tmpDrawables) { - Style style = d.getStyle(); - draw(t, level, d, style); + for (Drawable d : tmpDrawables) { + Style style = d.getStyle(); + draw(t, level, d, style); - if (style != lastStyle) - level += 2; + if (style != lastStyle) + level += 2; - lastStyle = style; - } - } - } + lastStyle = style; + } + } + } - protected void draw(Task task, int level, Drawable d, Style style) { - Geometry geom = d.getGeometry(); + protected void draw(Task task, int level, Drawable d, Style style) { + Geometry geom = d.getGeometry(); - if (d instanceof LineDrawable) { - drawLine(task, level, geom, style); - } else if (d instanceof PointDrawable) { - drawPoint(task, level, geom, style); - } else { - drawPolygon(task, level, geom, style); - } - } + if (d instanceof LineDrawable) { + drawLine(task, level, geom, style); + } else if (d instanceof PointDrawable) { + drawPoint(task, level, geom, style); + } else { + drawPolygon(task, level, geom, style); + } + } - protected void drawPoint(Task t, int level, Geometry points, Style style) { + protected void drawPoint(Task t, int level, Geometry points, Style style) { - MeshBucket mesh = t.buckets.getMeshBucket(level); - if (mesh.area == null) { - mesh.area = new AreaStyle(Color.fade(style.fillColor, - style.fillAlpha)); - } + MeshBucket mesh = t.buckets.getMeshBucket(level); + if (mesh.area == null) { + mesh.area = new AreaStyle(Color.fade(style.fillColor, + style.fillAlpha)); + } - LineBucket ll = t.buckets.getLineBucket(level + 1); - if (ll.line == null) { - ll.line = new LineStyle(2, style.strokeColor, style.strokeWidth); - } + LineBucket ll = t.buckets.getLineBucket(level + 1); + if (ll.line == null) { + ll.line = new LineStyle(2, style.strokeColor, style.strokeWidth); + } - for (int i = 0; i < points.getNumGeometries(); i++) { - Point p = (Point) points.getGeometryN(i); - addCircle(mGeom.clear(), t.position, p.getX(), p.getY(), style); + for (int i = 0; i < points.getNumGeometries(); i++) { + Point p = (Point) points.getGeometryN(i); + addCircle(mGeom.clear(), t.position, p.getX(), p.getY(), style); - if (!mClipper.clip(mGeom)) - continue; + if (!mClipper.clip(mGeom)) + continue; - mesh.addConvexMesh(mGeom); - ll.addLine(mGeom); - } - } + mesh.addConvexMesh(mGeom); + ll.addLine(mGeom); + } + } - protected void drawLine(Task t, int level, Geometry line, Style style) { + protected void drawLine(Task t, int level, Geometry line, Style style) { - LineBucket ll = t.buckets.getLineBucket(level); - if (ll.line == null) { - ll.line = new LineStyle(0, style.strokeColor, style.strokeWidth); - } + LineBucket ll = t.buckets.getLineBucket(level); + if (ll.line == null) { + ll.line = new LineStyle(0, style.strokeColor, style.strokeWidth); + } - if (style.generalization != Style.GENERALIZATION_NONE) { - line = DouglasPeuckerSimplifier.simplify(line, mMinX * style.generalization); - } + if (style.generalization != Style.GENERALIZATION_NONE) { + line = DouglasPeuckerSimplifier.simplify(line, mMinX * style.generalization); + } - //line = line.intersection(mEnvelope); + //line = line.intersection(mEnvelope); - for (int i = 0; i < line.getNumGeometries(); i++) { - mConverter.transformLineString(mGeom.clear(), (LineString) line.getGeometryN(i)); - if (!mClipper.clip(mGeom)) - continue; + for (int i = 0; i < line.getNumGeometries(); i++) { + mConverter.transformLineString(mGeom.clear(), (LineString) line.getGeometryN(i)); + if (!mClipper.clip(mGeom)) + continue; - ll.addLine(mGeom); - } - } + ll.addLine(mGeom); + } + } - protected void drawPolygon(Task t, int level, Geometry polygon, Style style) { + protected void drawPolygon(Task t, int level, Geometry polygon, Style style) { - MeshBucket mesh = t.buckets.getMeshBucket(level); - if (mesh.area == null) { - mesh.area = new AreaStyle(Color.fade(style.fillColor, - style.fillAlpha)); - } + MeshBucket mesh = t.buckets.getMeshBucket(level); + if (mesh.area == null) { + mesh.area = new AreaStyle(Color.fade(style.fillColor, + style.fillAlpha)); + } - LineBucket ll = t.buckets.getLineBucket(level + 1); - if (ll.line == null) { - ll.line = new LineStyle(2, style.strokeColor, style.strokeWidth); - } + LineBucket ll = t.buckets.getLineBucket(level + 1); + if (ll.line == null) { + ll.line = new LineStyle(2, style.strokeColor, style.strokeWidth); + } - if (style.generalization != Style.GENERALIZATION_NONE) { - polygon = DouglasPeuckerSimplifier.simplify(polygon, mMinX * style.generalization); - } + if (style.generalization != Style.GENERALIZATION_NONE) { + polygon = DouglasPeuckerSimplifier.simplify(polygon, mMinX * style.generalization); + } - // if (polygon.isRectangle()) + // if (polygon.isRectangle()) - for (int i = 0; i < polygon.getNumGeometries(); i++) { - mConverter.transformPolygon(mGeom.clear(), (Polygon) polygon.getGeometryN(i)); + for (int i = 0; i < polygon.getNumGeometries(); i++) { + mConverter.transformPolygon(mGeom.clear(), (Polygon) polygon.getGeometryN(i)); - if (mGeom.getNumPoints() < 3) - continue; + if (mGeom.getNumPoints() < 3) + continue; - if (!mClipper.clip(mGeom)) - continue; + if (!mClipper.clip(mGeom)) + continue; - mesh.addMesh(mGeom); - ll.addLine(mGeom); - } - } + mesh.addMesh(mGeom); + ll.addLine(mGeom); + } + } - protected void addCircle(GeometryBuffer g, MapPosition pos, - double px, double py, Style style) { + protected void addCircle(GeometryBuffer g, MapPosition pos, + double px, double py, Style style) { - double scale = pos.scale * Tile.SIZE / UNSCALE_COORD; - double x = (longitudeToX(px) - pos.x) * scale; - double y = (latitudeToY(py) - pos.y) * scale; + double scale = pos.scale * Tile.SIZE / UNSCALE_COORD; + double x = (longitudeToX(px) - pos.x) * scale; + double y = (latitudeToY(py) - pos.y) * scale; /* TODO in the next line I was only able to interpolate a function - * that makes up for the zoom level. The circle should not grow, it + * that makes up for the zoom level. The circle should not grow, it * should stickto the map. 0.01 / (1 << startLvl) makes it retain * its size. Correction? */ - int zoomScale = (1 << style.scalingZoomLevel); + int zoomScale = (1 << style.scalingZoomLevel); /* Keep the circle's size constant in relation to the underlying map */ - double radius = style.buffer; + double radius = style.buffer; - if (pos.scale > zoomScale) - radius = (radius * 0.01) / zoomScale * (scale - zoomScale); + if (pos.scale > zoomScale) + radius = (radius * 0.01) / zoomScale * (scale - zoomScale); - int quality = (int) (Math.sqrt(radius) * 8); - quality = FastMath.clamp(quality, 4, 32); + int quality = (int) (Math.sqrt(radius) * 8); + quality = FastMath.clamp(quality, 4, 32); - double step = 2.0 * Math.PI / quality; + double step = 2.0 * Math.PI / quality; - g.startPolygon(); - for (int i = 0; i < quality; i++) { - g.addPoint((float) (x + radius * Math.cos(i * step)), - (float) (y + radius * Math.sin(i * step))); - } - } + g.startPolygon(); + for (int i = 0; i < quality; i++) { + g.addPoint((float) (x + radius * Math.cos(i * step)), + (float) (y + radius * Math.sin(i * step))); + } + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/CircleDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/CircleDrawable.java index 916b15d6..6d719127 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/CircleDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/CircleDrawable.java @@ -9,141 +9,138 @@ import org.oscim.utils.geom.GeomBuilder; */ public class CircleDrawable extends JtsDrawable { - public static int MEDIUM_QUALITY = 32; - public static int HIGH_QUALITY = 64; + public static int MEDIUM_QUALITY = 32; + public static int HIGH_QUALITY = 64; - /** - * Constructs a circle given the real-world radius in km. Keep in mind that - * this technique is computationally costly for circles with huge number or - * segments. - * - * @param center GeoPoint - center of the circle - * @param radiusKm Radius of the circle in kilometers. - */ - public CircleDrawable(GeoPoint center, double radiusKm) { - super(Style.DEFAULT_STYLE); - GeomBuilder gb = new GeomBuilder(); - for (int i = 0; i < MEDIUM_QUALITY; i++) { - GeoPoint point = findGeoPointWithGivenDistance(center, - i * Math.PI / MEDIUM_QUALITY * 2, - radiusKm); - gb.points(point.getLongitude(), point.getLatitude()); - } - geometry = gb.toPolygon(); - } + /** + * Constructs a circle given the real-world radius in km. Keep in mind that + * this technique is computationally costly for circles with huge number or + * segments. + * + * @param center GeoPoint - center of the circle + * @param radiusKm Radius of the circle in kilometers. + */ + public CircleDrawable(GeoPoint center, double radiusKm) { + super(Style.DEFAULT_STYLE); + GeomBuilder gb = new GeomBuilder(); + for (int i = 0; i < MEDIUM_QUALITY; i++) { + GeoPoint point = findGeoPointWithGivenDistance(center, + i * Math.PI / MEDIUM_QUALITY * 2, + radiusKm); + gb.points(point.getLongitude(), point.getLatitude()); + } + geometry = gb.toPolygon(); + } - /** - * Constructs a circle given the real-world radius in km. Keep in mind that - * this technique is computationally costly for circles with huge number or - * segments. - * - * @param center GeoPoint - center of the circle - * @param radiusKm Radius of the circle in kilometers. The size of the - * circle may be distorted due to the Mercator projections - * properties. - * @param style FillableGeometryStyle with color and transparency - * information for the circle - */ - public CircleDrawable(GeoPoint center, double radiusKm, Style style) { - super(style); - GeomBuilder gb = new GeomBuilder(); - for (int i = 0; i < MEDIUM_QUALITY; i++) { - GeoPoint point = findGeoPointWithGivenDistance(center, - i * Math.PI / MEDIUM_QUALITY * 2, - radiusKm); - gb.points(point.getLongitude(), point.getLatitude()); - } - geometry = gb.toPolygon(); - } + /** + * Constructs a circle given the real-world radius in km. Keep in mind that + * this technique is computationally costly for circles with huge number or + * segments. + * + * @param center GeoPoint - center of the circle + * @param radiusKm Radius of the circle in kilometers. The size of the + * circle may be distorted due to the Mercator projections + * properties. + * @param style FillableGeometryStyle with color and transparency + * information for the circle + */ + public CircleDrawable(GeoPoint center, double radiusKm, Style style) { + super(style); + GeomBuilder gb = new GeomBuilder(); + for (int i = 0; i < MEDIUM_QUALITY; i++) { + GeoPoint point = findGeoPointWithGivenDistance(center, + i * Math.PI / MEDIUM_QUALITY * 2, + radiusKm); + gb.points(point.getLongitude(), point.getLatitude()); + } + geometry = gb.toPolygon(); + } - /** - * Constructs a circle given the real-world radius in km. Keep in mind that - * this technique is computationally costly for circles with huge number or - * segments. - * - * @param center GeoPoint - center of the circle - * @param radiusKm Radius of the circle in kilometers. The size of the - * circle may be distorted due to the Mercator projections - * properties. - * @param quadrantSegments the number of segments a quarter of circle will - * have. Use Circle.LOW_PRECISION for quick rendering, - * Circle.MEDIUM_PRECISION for good rendering and quality or - * Circle.HIGH_PRECISION for high quality. - * @param style FillableGeometryStyle with color and transparency - * information for the circle - */ - public CircleDrawable(GeoPoint center, double radiusKm, int quadrantSegments, - Style style) { - super(style); - GeomBuilder gb = new GeomBuilder(); - for (int i = 0; i < quadrantSegments; i++) { - GeoPoint point = findGeoPointWithGivenDistance(center, - i * Math.PI / quadrantSegments * 2, - radiusKm); - gb.points(point.getLongitude(), point.getLatitude()); - } - geometry = gb.toPolygon(); - } + /** + * Constructs a circle given the real-world radius in km. Keep in mind that + * this technique is computationally costly for circles with huge number or + * segments. + * + * @param center GeoPoint - center of the circle + * @param radiusKm Radius of the circle in kilometers. The size of the + * circle may be distorted due to the Mercator projections + * properties. + * @param quadrantSegments the number of segments a quarter of circle will + * have. Use Circle.LOW_PRECISION for quick rendering, + * Circle.MEDIUM_PRECISION for good rendering and quality or + * Circle.HIGH_PRECISION for high quality. + * @param style FillableGeometryStyle with color and transparency + * information for the circle + */ + public CircleDrawable(GeoPoint center, double radiusKm, int quadrantSegments, + Style style) { + super(style); + GeomBuilder gb = new GeomBuilder(); + for (int i = 0; i < quadrantSegments; i++) { + GeoPoint point = findGeoPointWithGivenDistance(center, + i * Math.PI / quadrantSegments * 2, + radiusKm); + gb.points(point.getLongitude(), point.getLatitude()); + } + geometry = gb.toPolygon(); + } - /** - * This function finds a GeoPoint offset by a distance in the direction - * given in the bearing parameter. It is an approximation due to the - * Mercator projections properties - * - * @param startPoint - * @param initialBearingRadians - * @param distanceKilometres - * @return a new GeoPoint located distanceKilometers away from the - * startPoint in the direction of the initialBearing - */ - private static GeoPoint findGeoPointWithGivenDistance(GeoPoint startPoint, - double initialBearingRadians, double distanceKilometres) - { - double radiusEarthKilometres = 6371.01; - double distRatio = distanceKilometres / radiusEarthKilometres; - double distRatioSine = Math.sin(distRatio); - double distRatioCosine = Math.cos(distRatio); + /** + * This function finds a GeoPoint offset by a distance in the direction + * given in the bearing parameter. It is an approximation due to the + * Mercator projections properties + * + * @param startPoint + * @param initialBearingRadians + * @param distanceKilometres + * @return a new GeoPoint located distanceKilometers away from the + * startPoint in the direction of the initialBearing + */ + private static GeoPoint findGeoPointWithGivenDistance(GeoPoint startPoint, + double initialBearingRadians, double distanceKilometres) { + double radiusEarthKilometres = 6371.01; + double distRatio = distanceKilometres / radiusEarthKilometres; + double distRatioSine = Math.sin(distRatio); + double distRatioCosine = Math.cos(distRatio); - double startLatRad = degreesToRadians(startPoint.getLatitude()); - double startLonRad = degreesToRadians(startPoint.getLongitude()); + double startLatRad = degreesToRadians(startPoint.getLatitude()); + double startLonRad = degreesToRadians(startPoint.getLongitude()); - double startLatCos = Math.cos(startLatRad); - double startLatSin = Math.sin(startLatRad); + double startLatCos = Math.cos(startLatRad); + double startLatSin = Math.sin(startLatRad); - double endLatRads = Math.asin((startLatSin * distRatioCosine) - + (startLatCos * distRatioSine * Math.cos(initialBearingRadians))); + double endLatRads = Math.asin((startLatSin * distRatioCosine) + + (startLatCos * distRatioSine * Math.cos(initialBearingRadians))); - double endLonRads = startLonRad - + Math.atan2( - Math.sin(initialBearingRadians) * distRatioSine * startLatCos, - distRatioCosine - startLatSin * Math.sin(endLatRads)); + double endLonRads = startLonRad + + Math.atan2( + Math.sin(initialBearingRadians) * distRatioSine * startLatCos, + distRatioCosine - startLatSin * Math.sin(endLatRads)); - return new GeoPoint(radiansToDegrees(endLatRads), radiansToDegrees(endLonRads)); + return new GeoPoint(radiansToDegrees(endLatRads), radiansToDegrees(endLonRads)); - } + } - /** - * translates an angle from degrees to radians - * - * @param degrees - * @return the angle in radians - */ - private static double degreesToRadians(double degrees) - { - double degToRadFactor = Math.PI / 180; - return degrees * degToRadFactor; - } + /** + * translates an angle from degrees to radians + * + * @param degrees + * @return the angle in radians + */ + private static double degreesToRadians(double degrees) { + double degToRadFactor = Math.PI / 180; + return degrees * degToRadFactor; + } - /** - * translates an angle from radians to degrees - * - * @param radians - * @return the angle in degrees - */ - private static double radiansToDegrees(double radians) - { - double radToDegFactor = 180 / Math.PI; - return radians * radToDegFactor; - } + /** + * translates an angle from radians to degrees + * + * @param radians + * @return the angle in degrees + */ + private static double radiansToDegrees(double radians) { + double radToDegFactor = 180 / Math.PI; + return radians * radToDegFactor; + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/Drawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/Drawable.java index 9214e1e4..07bff0ac 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/Drawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/Drawable.java @@ -4,13 +4,13 @@ import com.vividsolutions.jts.geom.Geometry; public interface Drawable { - /** - * @return - */ - public Style getStyle(); + /** + * @return + */ + public Style getStyle(); - /** - * @return - */ - public Geometry getGeometry(); + /** + * @return + */ + public Geometry getGeometry(); } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/HexagonDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/HexagonDrawable.java index 74d919e0..76752d38 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/HexagonDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/HexagonDrawable.java @@ -10,79 +10,78 @@ import org.oscim.utils.geom.GeomBuilder; */ public class HexagonDrawable extends JtsDrawable { - /** - * @param center GeoPoint - center of the hexagon - * @param radiusKm Radius of the hexagon in kilometers. The size of the - * hexagon may be distorted due to the Mercator projections - * properties. - */ - public HexagonDrawable(GeoPoint center, double radiusKm) { - super(Style.DEFAULT_STYLE); - GeomBuilder gb = new GeomBuilder(); + /** + * @param center GeoPoint - center of the hexagon + * @param radiusKm Radius of the hexagon in kilometers. The size of the + * hexagon may be distorted due to the Mercator projections + * properties. + */ + public HexagonDrawable(GeoPoint center, double radiusKm) { + super(Style.DEFAULT_STYLE); + GeomBuilder gb = new GeomBuilder(); - for (int i = 0; i < 6; i++) { - GeoPoint point = findGeoPointWithGivenDistance(center, i * Math.PI / 3, radiusKm); - gb.points(point.getLongitude(), point.getLatitude()); - } - geometry = gb.toPolygon(); - } + for (int i = 0; i < 6; i++) { + GeoPoint point = findGeoPointWithGivenDistance(center, i * Math.PI / 3, radiusKm); + gb.points(point.getLongitude(), point.getLatitude()); + } + geometry = gb.toPolygon(); + } - /** - * @param center GeoPoint - center of the hexagon - * @param radiusKm Radius of the hexagon in kilometers. The size of the - * hexagon may be distorted due to the Mercator projections - * properties. - * @param rotationRad rotation of the hexagon in radians - * @param style - */ - public HexagonDrawable(GeoPoint center, double radiusKm, double rotationRad, Style style) { - super(style); - GeomBuilder gb = new GeomBuilder(); - Point tmp = new Point(); + /** + * @param center GeoPoint - center of the hexagon + * @param radiusKm Radius of the hexagon in kilometers. The size of the + * hexagon may be distorted due to the Mercator projections + * properties. + * @param rotationRad rotation of the hexagon in radians + * @param style + */ + public HexagonDrawable(GeoPoint center, double radiusKm, double rotationRad, Style style) { + super(style); + GeomBuilder gb = new GeomBuilder(); + Point tmp = new Point(); - for (int i = 0; i < 6; i++) { - GeoPoint point = findGeoPointWithGivenDistance(center, - rotationRad + i * Math.PI / 3, - radiusKm); - MercatorProjection.project(point, tmp); - gb.points(tmp.x, tmp.y); - } - geometry = gb.toPolygon(); - } + for (int i = 0; i < 6; i++) { + GeoPoint point = findGeoPointWithGivenDistance(center, + rotationRad + i * Math.PI / 3, + radiusKm); + MercatorProjection.project(point, tmp); + gb.points(tmp.x, tmp.y); + } + geometry = gb.toPolygon(); + } - /** - * This function finds a GeoPoint offset by a distance in the direction - * given in the bearing parameter. It is an approximation due to the - * Mercator projections properties - * - * @param startPoint - * @param initialBearingRadians - * @param distanceKilometres - * @return a new GeoPoint located distanceKilometers away from the - * startPoint in the direction of the initialBearing - */ - private static GeoPoint findGeoPointWithGivenDistance(GeoPoint startPoint, - double initialBearingRadians, double distanceKilometres) - { - double radiusEarthKilometres = 6371.01; - double distRatio = distanceKilometres / radiusEarthKilometres; - double distRatioSine = Math.sin(distRatio); - double distRatioCosine = Math.cos(distRatio); + /** + * This function finds a GeoPoint offset by a distance in the direction + * given in the bearing parameter. It is an approximation due to the + * Mercator projections properties + * + * @param startPoint + * @param initialBearingRadians + * @param distanceKilometres + * @return a new GeoPoint located distanceKilometers away from the + * startPoint in the direction of the initialBearing + */ + private static GeoPoint findGeoPointWithGivenDistance(GeoPoint startPoint, + double initialBearingRadians, double distanceKilometres) { + double radiusEarthKilometres = 6371.01; + double distRatio = distanceKilometres / radiusEarthKilometres; + double distRatioSine = Math.sin(distRatio); + double distRatioCosine = Math.cos(distRatio); - double startLatRad = Math.toRadians(startPoint.getLatitude()); - double startLonRad = Math.toRadians(startPoint.getLongitude()); + double startLatRad = Math.toRadians(startPoint.getLatitude()); + double startLonRad = Math.toRadians(startPoint.getLongitude()); - double startLatCos = Math.cos(startLatRad); - double startLatSin = Math.sin(startLatRad); + double startLatCos = Math.cos(startLatRad); + double startLatSin = Math.sin(startLatRad); - double endLatRads = Math.asin((startLatSin * distRatioCosine) - + (startLatCos * distRatioSine * Math.cos(initialBearingRadians))); + double endLatRads = Math.asin((startLatSin * distRatioCosine) + + (startLatCos * distRatioSine * Math.cos(initialBearingRadians))); - double endLonRads = startLonRad - + Math.atan2( - Math.sin(initialBearingRadians) * distRatioSine * startLatCos, - distRatioCosine - startLatSin * Math.sin(endLatRads)); + double endLonRads = startLonRad + + Math.atan2( + Math.sin(initialBearingRadians) * distRatioSine * startLatCos, + distRatioCosine - startLatSin * Math.sin(endLatRads)); - return new GeoPoint(Math.toDegrees(endLatRads), Math.toDegrees(endLonRads)); - } + return new GeoPoint(Math.toDegrees(endLatRads), Math.toDegrees(endLonRads)); + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/JtsDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/JtsDrawable.java index beea3093..e3a8faae 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/JtsDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/JtsDrawable.java @@ -1,64 +1,65 @@ package org.oscim.layers.vector.geometries; -import java.util.List; - -import org.oscim.core.GeoPoint; -import org.oscim.utils.geom.GeomBuilder; - import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory; +import org.oscim.core.GeoPoint; +import org.oscim.utils.geom.GeomBuilder; + +import java.util.List; + public class JtsDrawable implements Drawable { - public static final PackedCoordinateSequenceFactory coordFactory; - public static final GeometryFactory geomFactory; - static { - coordFactory = new PackedCoordinateSequenceFactory(); - geomFactory = new GeometryFactory(coordFactory); - } + public static final PackedCoordinateSequenceFactory coordFactory; + public static final GeometryFactory geomFactory; - protected Style style; - protected Geometry geometry; + static { + coordFactory = new PackedCoordinateSequenceFactory(); + geomFactory = new GeometryFactory(coordFactory); + } - public JtsDrawable(Style style) { - this.style = style; - } + protected Style style; + protected Geometry geometry; - public JtsDrawable(Geometry geometry, Style style) { - this.geometry = geometry; - this.style = style; - } + public JtsDrawable(Style style) { + this.style = style; + } - /** - * @param style - */ - public void setStyle(Style style) { - this.style = style; - } + public JtsDrawable(Geometry geometry, Style style) { + this.geometry = geometry; + this.style = style; + } - /* (non-Javadoc) - * - * @see org.oscim.core.geometries.Drawable#getStyle() */ - @Override - public Style getStyle() { - return style; - } + /** + * @param style + */ + public void setStyle(Style style) { + this.style = style; + } - /* (non-Javadoc) - * - * @see org.oscim.core.geometries.Drawable#getGeometry() */ - @Override - public Geometry getGeometry() { - return geometry; - } + /* (non-Javadoc) + * + * @see org.oscim.core.geometries.Drawable#getStyle() */ + @Override + public Style getStyle() { + return style; + } - protected static GeomBuilder loadPoints(GeomBuilder gb, List points) { - for (GeoPoint point : points) { - gb.point(point.getLongitude(), - point.getLatitude()); - } - return gb; - } + /* (non-Javadoc) + * + * @see org.oscim.core.geometries.Drawable#getGeometry() */ + @Override + public Geometry getGeometry() { + return geometry; + } + + protected static GeomBuilder loadPoints(GeomBuilder gb, List points) { + for (GeoPoint point : points) { + gb.point(point.getLongitude(), + point.getLatitude()); + } + return gb; + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/LineDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/LineDrawable.java index ed608ef3..8d91fcf5 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/LineDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/LineDrawable.java @@ -1,44 +1,44 @@ package org.oscim.layers.vector.geometries; -import java.util.List; - -import org.oscim.core.GeoPoint; - import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LineString; +import org.oscim.core.GeoPoint; + +import java.util.List; + /** * Predefined class for drawing lines and line strings on the map. */ public class LineDrawable extends JtsDrawable { - public LineDrawable(Geometry line, Style style) { - super(style); - if (line.getDimension() != 1) - throw new IllegalArgumentException("Geometry not a Line"); + public LineDrawable(Geometry line, Style style) { + super(style); + if (line.getDimension() != 1) + throw new IllegalArgumentException("Geometry not a Line"); - this.geometry = line; - } + this.geometry = line; + } - public LineDrawable(List points) { - this(points, Style.defaultStyle()); - } + public LineDrawable(List points) { + this(points, Style.defaultStyle()); + } - public LineDrawable(List points, Style style) { - super(style); - if (points.size() < 2) - return; + public LineDrawable(List points, Style style) { + super(style); + if (points.size() < 2) + return; - double[] coords = new double[points.size() * 2]; - int c = 0; - for (GeoPoint p : points) { - coords[c++] = p.getLongitude(); - coords[c++] = p.getLatitude(); - } - this.geometry = new LineString(coordFactory.create(coords, 2), geomFactory); - } + double[] coords = new double[points.size() * 2]; + int c = 0; + for (GeoPoint p : points) { + coords[c++] = p.getLongitude(); + coords[c++] = p.getLatitude(); + } + this.geometry = new LineString(coordFactory.create(coords, 2), geomFactory); + } - public LineDrawable(double[] lonLat, Style style) { - this(new LineString(coordFactory.create(lonLat, 2), geomFactory), style); - } + public LineDrawable(double[] lonLat, Style style) { + this(new LineString(coordFactory.create(lonLat, 2), geomFactory), style); + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/PointDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/PointDrawable.java index b410f57c..d71bdc84 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/PointDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/PointDrawable.java @@ -11,9 +11,9 @@ import org.oscim.utils.geom.GeomBuilder; * a buffer area is built around it. * To give the point custom size, create a GeometryBuffer with, set buffer to * your value and assign the point the final style. - * + *

* Note that since points do not have any area, they are not generalized. - * + *

* Normally points retain their size in the screen units across all zoom levels * but this can be customized. Use setStartLevel on the point's style to specify * from which zoom level the point should "stick to the map" and not decrease in @@ -21,16 +21,16 @@ import org.oscim.utils.geom.GeomBuilder; */ public class PointDrawable extends JtsDrawable { - public PointDrawable(GeoPoint point) { - this(point, Style.defaultStyle()); - } + public PointDrawable(GeoPoint point) { + this(point, Style.defaultStyle()); + } - public PointDrawable(GeoPoint point, Style style) { - this(point.getLongitude(), point.getLatitude(), style); - } + public PointDrawable(GeoPoint point, Style style) { + this(point.getLongitude(), point.getLatitude(), style); + } - public PointDrawable(double lat, double lon, Style style) { - super(style); - this.geometry = new GeomBuilder().points(lon, lat).toPoint(); - } + public PointDrawable(double lat, double lon, Style style) { + super(style); + this.geometry = new GeomBuilder().points(lon, lat).toPoint(); + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/PolygonDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/PolygonDrawable.java index febe2d46..b83079af 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/PolygonDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/PolygonDrawable.java @@ -1,116 +1,116 @@ package org.oscim.layers.vector.geometries; -import java.util.Arrays; -import java.util.List; +import com.vividsolutions.jts.geom.Geometry; import org.oscim.core.GeoPoint; import org.oscim.utils.geom.GeomBuilder; -import com.vividsolutions.jts.geom.Geometry; +import java.util.Arrays; +import java.util.List; /** * Predefined class to draw polygons on the map. */ public class PolygonDrawable extends JtsDrawable { - /** - * Creates a polygon using a JTS geometry and a FillableGeometryStyle - * - * @param polygon - * @param style - */ - public PolygonDrawable(Geometry polygon, Style style) { - super(style); + /** + * Creates a polygon using a JTS geometry and a FillableGeometryStyle + * + * @param polygon + * @param style + */ + public PolygonDrawable(Geometry polygon, Style style) { + super(style); - if (polygon.getDimension() != 2) - throw new IllegalArgumentException("Geometry not a Polygon"); + if (polygon.getDimension() != 2) + throw new IllegalArgumentException("Geometry not a Polygon"); - this.geometry = polygon; - } + this.geometry = polygon; + } - /** - * Creates a polygon using the coordinates provided in the List - * - * @param points - */ - public PolygonDrawable(List points) { - this(points, Style.defaultStyle()); - } + /** + * Creates a polygon using the coordinates provided in the List + * + * @param points + */ + public PolygonDrawable(List points) { + this(points, Style.defaultStyle()); + } - /** - * Create a polygon given the array of GeoPoints and a FillableGeometryStyle - * - * @param points - * @param style - */ - public PolygonDrawable(Style style, GeoPoint... points) { - this(Arrays.asList(points), style); - } + /** + * Create a polygon given the array of GeoPoints and a FillableGeometryStyle + * + * @param points + * @param style + */ + public PolygonDrawable(Style style, GeoPoint... points) { + this(Arrays.asList(points), style); + } - /** - * @param points - * @param style - */ - public PolygonDrawable(List points, Style style) { - this(loadPoints(new GeomBuilder(), points).toPolygon(), style); - } + /** + * @param points + * @param style + */ + public PolygonDrawable(List points, Style style) { + this(loadPoints(new GeomBuilder(), points).toPolygon(), style); + } - /** - * Create a polygon given the array of GeoPoints for the boundary, the array - * of GeoPoints for the hole and outline and fill color and alpha - * - * @param points - * @param holePoints - * @param outlineColor - * @param outlineAlpha - * @param fillColor - * @param fillAlpha - */ - public PolygonDrawable(GeoPoint[] points, GeoPoint[] holePoints, float lineWidth, - int lineColor, - int fillColor, float fillAlpha) { - this(Arrays.asList(points), - Arrays.asList(holePoints), - lineWidth, lineColor, fillColor, fillAlpha); - } + /** + * Create a polygon given the array of GeoPoints for the boundary, the array + * of GeoPoints for the hole and outline and fill color and alpha + * + * @param points + * @param holePoints + * @param outlineColor + * @param outlineAlpha + * @param fillColor + * @param fillAlpha + */ + public PolygonDrawable(GeoPoint[] points, GeoPoint[] holePoints, float lineWidth, + int lineColor, + int fillColor, float fillAlpha) { + this(Arrays.asList(points), + Arrays.asList(holePoints), + lineWidth, lineColor, fillColor, fillAlpha); + } - /** - * Create a polygon using the Coordinates provided in the first List, with a - * hole build from the Coordinates in the second List and outline and fill - - * color and alpha - * - * @param points - * @param holePoints - * @param outlineColor - * @param outlineAlpha - * @param fillColor - * @param fillAlpha - */ - public PolygonDrawable(List points, List holePoints, - float lineWidth, int lineColor, int fillColor, float fillAlpha) { - this(points, holePoints, new Style.Builder() - .strokeWidth(lineWidth) - .strokeColor(lineColor) - .fillColor(fillColor) - .fillAlpha(fillAlpha) - .build()); - } + /** + * Create a polygon using the Coordinates provided in the first List, with a + * hole build from the Coordinates in the second List and outline and fill - + * color and alpha + * + * @param points + * @param holePoints + * @param outlineColor + * @param outlineAlpha + * @param fillColor + * @param fillAlpha + */ + public PolygonDrawable(List points, List holePoints, + float lineWidth, int lineColor, int fillColor, float fillAlpha) { + this(points, holePoints, new Style.Builder() + .strokeWidth(lineWidth) + .strokeColor(lineColor) + .fillColor(fillColor) + .fillAlpha(fillAlpha) + .build()); + } - /** - * Creates a polygon from a List of coordinates in the first List, with a - * hole from coordinates in the second List and requires a - * FillableGeometryStyle for the color information - * - * @param points - * @param holePoints - * @param style - */ - public PolygonDrawable(List points, List holePoints, Style style) { - super(style); - GeomBuilder gb = new GeomBuilder(); - loadPoints(gb, points).ring(); - loadPoints(gb, holePoints).ring(); - this.geometry = gb.toPolygon(); - this.style = style; - } + /** + * Creates a polygon from a List of coordinates in the first List, with a + * hole from coordinates in the second List and requires a + * FillableGeometryStyle for the color information + * + * @param points + * @param holePoints + * @param style + */ + public PolygonDrawable(List points, List holePoints, Style style) { + super(style); + GeomBuilder gb = new GeomBuilder(); + loadPoints(gb, points).ring(); + loadPoints(gb, holePoints).ring(); + this.geometry = gb.toPolygon(); + this.style = style; + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/RectangleDrawable.java b/vtm-jts/src/org/oscim/layers/vector/geometries/RectangleDrawable.java index 7f8472b0..a97659eb 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/RectangleDrawable.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/RectangleDrawable.java @@ -8,48 +8,48 @@ import org.oscim.utils.geom.GeomBuilder; */ public class RectangleDrawable extends JtsDrawable { - /** - * Creates a Rectangle given the top-left and the bottom-right coordinate of - * it - * - * @param topLeft - * @param bottomRight - */ - public RectangleDrawable(GeoPoint topLeft, GeoPoint bottomRight) { - this(topLeft, bottomRight, Style.defaultStyle()); - } + /** + * Creates a Rectangle given the top-left and the bottom-right coordinate of + * it + * + * @param topLeft + * @param bottomRight + */ + public RectangleDrawable(GeoPoint topLeft, GeoPoint bottomRight) { + this(topLeft, bottomRight, Style.defaultStyle()); + } - /** - * Creates a Rectangle given the top-left and the bottom-right coordinate of - * it - * - * @param topLeft - * @param bottomRight - */ - public RectangleDrawable(GeoPoint topLeft, GeoPoint bottomRight, Style style) { - super(style); - geometry = new GeomBuilder() - .point(topLeft.getLongitude(), topLeft.getLatitude()) - .point(bottomRight.getLongitude(), topLeft.getLatitude()) - .point(bottomRight.getLongitude(), bottomRight.getLatitude()) - .point(topLeft.getLongitude(), bottomRight.getLatitude()) - .toPolygon(); - } + /** + * Creates a Rectangle given the top-left and the bottom-right coordinate of + * it + * + * @param topLeft + * @param bottomRight + */ + public RectangleDrawable(GeoPoint topLeft, GeoPoint bottomRight, Style style) { + super(style); + geometry = new GeomBuilder() + .point(topLeft.getLongitude(), topLeft.getLatitude()) + .point(bottomRight.getLongitude(), topLeft.getLatitude()) + .point(bottomRight.getLongitude(), bottomRight.getLatitude()) + .point(topLeft.getLongitude(), bottomRight.getLatitude()) + .toPolygon(); + } - /** - * Creates a Rectangle given the top-left and the bottom-right coordinate of - * it - * - * @param topLeft - * @param bottomRight - */ - public RectangleDrawable(double minLat, double minLon, double maxLat, double maxLon, Style style) { - super(style); - geometry = new GeomBuilder() - .point(minLon, minLat) - .point(minLon, maxLat) - .point(maxLon, maxLat) - .point(maxLon, minLat) - .toPolygon(); - } + /** + * Creates a Rectangle given the top-left and the bottom-right coordinate of + * it + * + * @param topLeft + * @param bottomRight + */ + public RectangleDrawable(double minLat, double minLon, double maxLat, double maxLon, Style style) { + super(style); + geometry = new GeomBuilder() + .point(minLon, minLat) + .point(minLon, maxLat) + .point(maxLon, maxLat) + .point(maxLon, minLat) + .toPolygon(); + } } diff --git a/vtm-jts/src/org/oscim/layers/vector/geometries/Style.java b/vtm-jts/src/org/oscim/layers/vector/geometries/Style.java index 7298dc23..3d89708a 100644 --- a/vtm-jts/src/org/oscim/layers/vector/geometries/Style.java +++ b/vtm-jts/src/org/oscim/layers/vector/geometries/Style.java @@ -7,192 +7,192 @@ import org.oscim.backend.canvas.Color; */ public class Style { - public static final int GENERALIZATION_HIGH = 1 << 3; - public static final int GENERALIZATION_MEDIUM = 1 << 2; - public static final int GENERALIZATION_SMALL = 1 << 0; - public static final int GENERALIZATION_NONE = 0; + public static final int GENERALIZATION_HIGH = 1 << 3; + public static final int GENERALIZATION_MEDIUM = 1 << 2; + public static final int GENERALIZATION_SMALL = 1 << 0; + public static final int GENERALIZATION_NONE = 0; - public final float strokeWidth; - public final int strokeColor; + public final float strokeWidth; + public final int strokeColor; - public final int fillColor; - public final float fillAlpha; + public final int fillColor; + public final float fillAlpha; - public final double buffer; - public final int scalingZoomLevel; + public final double buffer; + public final int scalingZoomLevel; - public final int generalization; + public final int generalization; - private Style(Builder builder) { - strokeWidth = builder.strokeWidth; - strokeColor = builder.strokeColor; + private Style(Builder builder) { + strokeWidth = builder.strokeWidth; + strokeColor = builder.strokeColor; - fillColor = builder.fillColor; - fillAlpha = builder.fillAlpha; + fillColor = builder.fillColor; + fillAlpha = builder.fillAlpha; - buffer = builder.buffer; - scalingZoomLevel = builder.scalingZoomLevel; + buffer = builder.buffer; + scalingZoomLevel = builder.scalingZoomLevel; - generalization = builder.generalization; - } + generalization = builder.generalization; + } - /** - * Geometry style builder. Usage example: - * - *

-	 * {
-	 * 	Style style = Style.builder()
-	 * 	    .strokeWidth(1f).strokeColor(Color.BLACK).build();
-	 * }
-	 * 
- */ - public static class Builder { + /** + * Geometry style builder. Usage example: + *

+ *

+     * {
+     * 	Style style = Style.builder()
+     * 	    .strokeWidth(1f).strokeColor(Color.BLACK).build();
+     * }
+     * 
+ */ + public static class Builder { - private float strokeWidth = 1f; - private int strokeColor = Color.GRAY; - private int fillColor = Color.GRAY; - private float fillAlpha = 0.25f; + private float strokeWidth = 1f; + private int strokeColor = Color.GRAY; + private int fillColor = Color.GRAY; + private float fillAlpha = 0.25f; - private double buffer = 1; - private int scalingZoomLevel = 1; + private double buffer = 1; + private int scalingZoomLevel = 1; - private int generalization = GENERALIZATION_NONE; + private int generalization = GENERALIZATION_NONE; - protected Builder() { + protected Builder() { - } + } - /** - * Builds the GeometryStyle from the specified parameters. - * - * @return - */ - public Style build() { - return new Style(this); - } + /** + * Builds the GeometryStyle from the specified parameters. + * + * @return + */ + public Style build() { + return new Style(this); + } - /** - * Sets the line width for the geometry's line or outline. - * - * @param lineWidth - * @return - */ - public Builder strokeWidth(float lineWidth) { - this.strokeWidth = lineWidth; - return this; - } + /** + * Sets the line width for the geometry's line or outline. + * + * @param lineWidth + * @return + */ + public Builder strokeWidth(float lineWidth) { + this.strokeWidth = lineWidth; + return this; + } - /** - * Sets the color for the geometry's line or outline. - * - * @param stokeColor - * @return - */ - public Builder strokeColor(int stokeColor) { - this.strokeColor = stokeColor; - return this; - } + /** + * Sets the color for the geometry's line or outline. + * + * @param stokeColor + * @return + */ + public Builder strokeColor(int stokeColor) { + this.strokeColor = stokeColor; + return this; + } - /** - * Sets the color for the geometry's area. - * - * @param fillColor - * @return - */ - public Builder fillColor(int fillColor) { - this.fillColor = fillColor; - return this; - } + /** + * Sets the color for the geometry's area. + * + * @param fillColor + * @return + */ + public Builder fillColor(int fillColor) { + this.fillColor = fillColor; + return this; + } - /** - * Sets alpha channel value for the geometry's area. - * - * @param fillAlpha - * @return - */ - public Builder fillAlpha(double fillAlpha) { - this.fillAlpha = (float) fillAlpha; - return this; - } + /** + * Sets alpha channel value for the geometry's area. + * + * @param fillAlpha + * @return + */ + public Builder fillAlpha(double fillAlpha) { + this.fillAlpha = (float) fillAlpha; + return this; + } - /** - * This function has effect only on Points: - * use it to control the size on the circle that - * will be built from a buffer around the point. - * - * @param buffer - * @return itself - */ - public Builder buffer(double buffer) { - this.buffer = buffer; - return this; - } + /** + * This function has effect only on Points: + * use it to control the size on the circle that + * will be built from a buffer around the point. + * + * @param buffer + * @return itself + */ + public Builder buffer(double buffer) { + this.buffer = buffer; + return this; + } - /** - * This function has effect only on Points: - * use it to specify from which zoom level the point - * should stop decreasing in size and "stick to the map". - * - * @param zoomlvl - */ - public Builder scaleZoomLevel(int zoomlvl) { - this.scalingZoomLevel = zoomlvl; - return this; - } + /** + * This function has effect only on Points: + * use it to specify from which zoom level the point + * should stop decreasing in size and "stick to the map". + * + * @param zoomlvl + */ + public Builder scaleZoomLevel(int zoomlvl) { + this.scalingZoomLevel = zoomlvl; + return this; + } - /** - * Sets generalization factor for the geometry. - * Use predefined GeometryStyle.GENERALIZATION_HIGH, - * GENERALIZATION_MEDIUM or GENERALIZATION_SMALL - * - * @param generalization - * @return - */ - public Builder generalization(int generalization) { - this.generalization = generalization; - return this; - } - } + /** + * Sets generalization factor for the geometry. + * Use predefined GeometryStyle.GENERALIZATION_HIGH, + * GENERALIZATION_MEDIUM or GENERALIZATION_SMALL + * + * @param generalization + * @return + */ + public Builder generalization(int generalization) { + this.generalization = generalization; + return this; + } + } - public float getStrokeWidth() { - return strokeWidth; - } + public float getStrokeWidth() { + return strokeWidth; + } - public int getStrokeColor() { - return strokeColor; - } + public int getStrokeColor() { + return strokeColor; + } - public int getFillColor() { - return fillColor; - } + public int getFillColor() { + return fillColor; + } - public float getFillAlpha() { - return fillAlpha; - } + public float getFillAlpha() { + return fillAlpha; + } - public int getGeneralization() { - return generalization; - } + public int getGeneralization() { + return generalization; + } - public double getBuffer() { - return buffer; - } + public double getBuffer() { + return buffer; + } - public int getScalingZoomLevel() { - return scalingZoomLevel; - } + public int getScalingZoomLevel() { + return scalingZoomLevel; + } - static final Style DEFAULT_STYLE = new Builder() - .fillColor(0xcccccccc) - .fillAlpha(1) - .build(); + static final Style DEFAULT_STYLE = new Builder() + .fillColor(0xcccccccc) + .fillAlpha(1) + .build(); - public static Style defaultStyle() { - return DEFAULT_STYLE; - } + public static Style defaultStyle() { + return DEFAULT_STYLE; + } - public static Style.Builder builder() { - return new Style.Builder(); - } + public static Style.Builder builder() { + return new Style.Builder(); + } } diff --git a/vtm-jts/src/org/oscim/utils/geom/GeomBuilder.java b/vtm-jts/src/org/oscim/utils/geom/GeomBuilder.java index b79cffc3..ff46acaa 100644 --- a/vtm-jts/src/org/oscim/utils/geom/GeomBuilder.java +++ b/vtm-jts/src/org/oscim/utils/geom/GeomBuilder.java @@ -14,12 +14,6 @@ */ package org.oscim.utils.geom; -import java.lang.reflect.Array; -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Deque; -import java.util.Iterator; - import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; @@ -33,421 +27,425 @@ import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.PrecisionModel; +import java.lang.reflect.Array; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; +import java.util.Iterator; + /** * Builder for geometry objects. *

* Example usage: - * + *

*

  * 
  * GeometryBuilder gb = new GeometryBuilder();
- * 
+ *
  * // create array two 2d points and turn into a line string
  * gb.points(1,2,3,4,5,6).toLineString();
- * 
+ *
  * // build a polygon with holes
  * gb.points(0,0,10,0,10,10,0,10,0,0).ring()
  *   .points(4,4,6,4,6,6,4,6,4,4).ring()
  *   .toPolygon();
- *   
+ *
  * 
  * 
- * + *

*

- * + * * @author Justin Deoliveira, OpenGeo - * */ public class GeomBuilder { - GeometryFactory factory; - Deque cstack = new ArrayDeque(); - Deque gstack = new ArrayDeque(); + GeometryFactory factory; + Deque cstack = new ArrayDeque(); + Deque gstack = new ArrayDeque(); - /** - * Constructs a builder with the default geometry factory. - */ - public GeomBuilder() { - this(new GeometryFactory()); - } + /** + * Constructs a builder with the default geometry factory. + */ + public GeomBuilder() { + this(new GeometryFactory()); + } - /** - * Constructs a builder with an explicit geometry factory. - */ - public GeomBuilder(GeometryFactory factory) { - this.factory = factory; - } + /** + * Constructs a builder with an explicit geometry factory. + */ + public GeomBuilder(GeometryFactory factory) { + this.factory = factory; + } - /** - * Constructs a builder with a specific srid for geometry objects. - */ - public GeomBuilder(int srid) { - this.factory = new GeometryFactory(new PrecisionModel(), srid); - } + /** + * Constructs a builder with a specific srid for geometry objects. + */ + public GeomBuilder(int srid) { + this.factory = new GeometryFactory(new PrecisionModel(), srid); + } - /** - * Adds a 2d point to the coordinate stack. - */ - public GeomBuilder point(double x, double y) { - cstack.push(new Coordinate(x, y)); - return this; - } + /** + * Adds a 2d point to the coordinate stack. + */ + public GeomBuilder point(double x, double y) { + cstack.push(new Coordinate(x, y)); + return this; + } - /** - * Adds a 3d point to the coordinate stack. - */ - public GeomBuilder pointz(double x, double y, double z) { - cstack.push(new Coordinate(x, y, z)); - return this; - } + /** + * Adds a 3d point to the coordinate stack. + */ + public GeomBuilder pointz(double x, double y, double z) { + cstack.push(new Coordinate(x, y, z)); + return this; + } - /** - * Adds an array of 2d points to the coordinate stack. - */ - public GeomBuilder points(double... ord) { - if (ord.length % 2 != 0) { - throw new IllegalArgumentException("Must specify even number of ordinates"); - } + /** + * Adds an array of 2d points to the coordinate stack. + */ + public GeomBuilder points(double... ord) { + if (ord.length % 2 != 0) { + throw new IllegalArgumentException("Must specify even number of ordinates"); + } - for (int i = 0; i < ord.length; i += 2) { - point(ord[i], ord[i + 1]); - } + for (int i = 0; i < ord.length; i += 2) { + point(ord[i], ord[i + 1]); + } - return this; - } + return this; + } - /** - * Adds an array of 3d points to the coordinate stack. - */ - public GeomBuilder pointsz(double... ord) { - if (ord.length % 3 != 0) { - throw new IllegalArgumentException("Must specify ordinates as triples"); - } + /** + * Adds an array of 3d points to the coordinate stack. + */ + public GeomBuilder pointsz(double... ord) { + if (ord.length % 3 != 0) { + throw new IllegalArgumentException("Must specify ordinates as triples"); + } - for (int i = 0; i < ord.length; i += 3) { - pointz(ord[i], ord[i + 1], ord[i + 2]); - } + for (int i = 0; i < ord.length; i += 3) { + pointz(ord[i], ord[i + 1], ord[i + 2]); + } - return this; - } + return this; + } - /** - * Creates a Point from the last point on the coordinate stack, and places - * the result - * on the geometry stack. - */ - public GeomBuilder point() { - gstack.push(factory.createPoint(cpop())); - return this; - } + /** + * Creates a Point from the last point on the coordinate stack, and places + * the result + * on the geometry stack. + */ + public GeomBuilder point() { + gstack.push(factory.createPoint(cpop())); + return this; + } - /** - * Creates a LineString from all points on the coordinate stack, and places - * the result - * on the geometry stack. - */ - public GeomBuilder lineString() { - gstack.push(factory.createLineString(cpopAll())); - return this; - } + /** + * Creates a LineString from all points on the coordinate stack, and places + * the result + * on the geometry stack. + */ + public GeomBuilder lineString() { + gstack.push(factory.createLineString(cpopAll())); + return this; + } - /** - * Creates a LinearRing from all points on the coordinate stack, and places - * the result - * on the geometry stack. - *

- * If the first and last coordinate on the point stack are not equal an - * additional point will be added. - *

- */ - public GeomBuilder ring() { - Coordinate[] coords = cpopAll(); - if (coords.length > 1 && !coords[0].equals(coords[coords.length - 1])) { - Coordinate[] tmp = new Coordinate[coords.length + 1]; - System.arraycopy(coords, 0, tmp, 0, coords.length); - tmp[tmp.length - 1] = new Coordinate(tmp[0]); - coords = tmp; - } + /** + * Creates a LinearRing from all points on the coordinate stack, and places + * the result + * on the geometry stack. + *

+ * If the first and last coordinate on the point stack are not equal an + * additional point will be added. + *

+ */ + public GeomBuilder ring() { + Coordinate[] coords = cpopAll(); + if (coords.length > 1 && !coords[0].equals(coords[coords.length - 1])) { + Coordinate[] tmp = new Coordinate[coords.length + 1]; + System.arraycopy(coords, 0, tmp, 0, coords.length); + tmp[tmp.length - 1] = new Coordinate(tmp[0]); + coords = tmp; + } - gstack.push(factory.createLinearRing(coords)); - return this; - } + gstack.push(factory.createLinearRing(coords)); + return this; + } - /** - * Creates a Polygon from all LinearRings on the geometry stack and places - * the result back - * on the geometry stack. - */ - public GeomBuilder polygon() { - if (gstack.isEmpty() || !(gstack.peek() instanceof LinearRing)) { - ring(); - } + /** + * Creates a Polygon from all LinearRings on the geometry stack and places + * the result back + * on the geometry stack. + */ + public GeomBuilder polygon() { + if (gstack.isEmpty() || !(gstack.peek() instanceof LinearRing)) { + ring(); + } - LinearRing[] rings = gpopAll(LinearRing.class); - LinearRing outer = rings[0]; - LinearRing[] inner = null; - if (rings.length > 1) { - inner = Arrays.copyOfRange(rings, 1, rings.length); - } + LinearRing[] rings = gpopAll(LinearRing.class); + LinearRing outer = rings[0]; + LinearRing[] inner = null; + if (rings.length > 1) { + inner = Arrays.copyOfRange(rings, 1, rings.length); + } - gstack.push(factory.createPolygon(outer, inner)); - return this; - } + gstack.push(factory.createPolygon(outer, inner)); + return this; + } - /** - * Creates a MultiPoint from all coordinates on the coordinate stack, - * plaching the result - * back on the geometry stack. - *

- * If the coordinate stack is empty this method will consume all Point - * geometries on the geometry stack. - *

- */ - public GeomBuilder multiPoint() { - if (!cstack.isEmpty()) { - gstack.push(factory.createMultiPoint(cpopAll())); - } - else { - gstack.push(factory.createMultiPoint(gpopAll(Point.class))); - } - return this; - } + /** + * Creates a MultiPoint from all coordinates on the coordinate stack, + * plaching the result + * back on the geometry stack. + *

+ * If the coordinate stack is empty this method will consume all Point + * geometries on the geometry stack. + *

+ */ + public GeomBuilder multiPoint() { + if (!cstack.isEmpty()) { + gstack.push(factory.createMultiPoint(cpopAll())); + } else { + gstack.push(factory.createMultiPoint(gpopAll(Point.class))); + } + return this; + } - /** - * Creates a MultiLineString from all LineStrings on the geometry stack and - * places the result - * back on the geometry stack. - */ - public GeomBuilder multiLineString() { - gstack.push(factory.createMultiLineString(gpopAll(LineString.class))); - return this; - } + /** + * Creates a MultiLineString from all LineStrings on the geometry stack and + * places the result + * back on the geometry stack. + */ + public GeomBuilder multiLineString() { + gstack.push(factory.createMultiLineString(gpopAll(LineString.class))); + return this; + } - /** - * Creates a MultiPolygon from all Polygons on the geometry stack and places - * the result - * back on the geometry stack. - */ - public GeomBuilder multiPolygon() { - gstack.push(factory.createMultiPolygon(gpopAll(Polygon.class))); - return this; - } + /** + * Creates a MultiPolygon from all Polygons on the geometry stack and places + * the result + * back on the geometry stack. + */ + public GeomBuilder multiPolygon() { + gstack.push(factory.createMultiPolygon(gpopAll(Polygon.class))); + return this; + } - /** - * Creates a GeometryCollection from all Geometries on the geometry stack - * and places the result - * back on the geometry stack. - */ - public GeomBuilder collection() { - gstack.push(factory.createGeometryCollection(gpopAll(Geometry.class))); - return this; - } + /** + * Creates a GeometryCollection from all Geometries on the geometry stack + * and places the result + * back on the geometry stack. + */ + public GeomBuilder collection() { + gstack.push(factory.createGeometryCollection(gpopAll(Geometry.class))); + return this; + } - /** - * Buffers the geometry at the top of the geometry stack, and places the - * result back on the - * geometry stack. - */ - public GeomBuilder buffer(double amt) { - gstack.push(gpop(Geometry.class).buffer(amt)); - return this; - } + /** + * Buffers the geometry at the top of the geometry stack, and places the + * result back on the + * geometry stack. + */ + public GeomBuilder buffer(double amt) { + gstack.push(gpop(Geometry.class).buffer(amt)); + return this; + } - /** - * Consumes the top of the geometry stack. - */ - public Geometry get() { - return gpop(Geometry.class); - } + /** + * Consumes the top of the geometry stack. + */ + public Geometry get() { + return gpop(Geometry.class); + } - /** - * Builds and returns a Point. - *

- * This method is equivalent to: - * - *

-	 *   (Point) point().get();
-	 * 
- * - *

- */ - public Point toPoint() { - return point().gpop(Point.class); - } + /** + * Builds and returns a Point. + *

+ * This method is equivalent to: + *

+ *

+     *   (Point) point().get();
+     * 
+ *

+ *

+ */ + public Point toPoint() { + return point().gpop(Point.class); + } - /** - * Builds and returns a LineString. - *

- * This method is equivalent to: - * - *

-	 *   (LineString) lineString().get();
-	 * 
- * - *

- */ - public LineString toLineString() { - return lineString().gpop(LineString.class); - } + /** + * Builds and returns a LineString. + *

+ * This method is equivalent to: + *

+ *

+     *   (LineString) lineString().get();
+     * 
+ *

+ *

+ */ + public LineString toLineString() { + return lineString().gpop(LineString.class); + } - /** - * Builds and returns a LineString. - *

- * This method is equivalent to: - * - *

-	 *   (LinearRing) ring().get();
-	 * 
- * - *

- */ - public LinearRing toLinearRing() { - return ring().gpop(LinearRing.class); - } + /** + * Builds and returns a LineString. + *

+ * This method is equivalent to: + *

+ *

+     *   (LinearRing) ring().get();
+     * 
+ *

+ *

+ */ + public LinearRing toLinearRing() { + return ring().gpop(LinearRing.class); + } - /** - * Builds and returns a Polygon. - *

- * This method is equivalent to: - * - *

-	 *   (Polygon) polygon().get();
-	 * 
- * - *

- */ - public Polygon toPolygon() { - return polygon().gpop(Polygon.class); - } + /** + * Builds and returns a Polygon. + *

+ * This method is equivalent to: + *

+ *

+     *   (Polygon) polygon().get();
+     * 
+ *

+ *

+ */ + public Polygon toPolygon() { + return polygon().gpop(Polygon.class); + } - /** - * Builds and returns a MultiPoint. - *

- * This method is equivalent to: - * - *

-	 *   (MultiPoint) multiPoint().get();
-	 * 
- * - *

- */ - public MultiPoint toMultiPoint() { - return multiPoint().gpop(MultiPoint.class); - } + /** + * Builds and returns a MultiPoint. + *

+ * This method is equivalent to: + *

+ *

+     *   (MultiPoint) multiPoint().get();
+     * 
+ *

+ *

+ */ + public MultiPoint toMultiPoint() { + return multiPoint().gpop(MultiPoint.class); + } - /** - * Builds and returns a MultiLineString. - *

- * This method is equivalent to: - * - *

-	 *   (MultiLineString) multiLineString().get();
-	 * 
- * - *

- */ - public MultiLineString toMultiLineString() { - return multiLineString().gpop(MultiLineString.class); - } + /** + * Builds and returns a MultiLineString. + *

+ * This method is equivalent to: + *

+ *

+     *   (MultiLineString) multiLineString().get();
+     * 
+ *

+ *

+ */ + public MultiLineString toMultiLineString() { + return multiLineString().gpop(MultiLineString.class); + } - /** - * Builds and returns a MultiPolygon. - *

- * This method is equivalent to: - * - *

-	 *   (MultiPolygon) multiPolygon().get();
-	 * 
- * - *

- */ - public MultiPolygon toMultiPolygon() { - return multiPolygon().gpop(MultiPolygon.class); - } + /** + * Builds and returns a MultiPolygon. + *

+ * This method is equivalent to: + *

+ *

+     *   (MultiPolygon) multiPolygon().get();
+     * 
+ *

+ *

+ */ + public MultiPolygon toMultiPolygon() { + return multiPolygon().gpop(MultiPolygon.class); + } - /** - * Builds and returns a GEometryCollection. - *

- * This method is equivalent to: - * - *

-	 *   (GeometryCollection) collection().get();
-	 * 
- * - *

- */ - public GeometryCollection toCollection() { - return collection().gpop(GeometryCollection.class); - } + /** + * Builds and returns a GEometryCollection. + *

+ * This method is equivalent to: + *

+ *

+     *   (GeometryCollection) collection().get();
+     * 
+ *

+ *

+ */ + public GeometryCollection toCollection() { + return collection().gpop(GeometryCollection.class); + } - Coordinate cpop() { - return cpop(1)[0]; - } + Coordinate cpop() { + return cpop(1)[0]; + } - Coordinate[] cpop(int n) { - if (cstack.size() < n) { - throw new IllegalStateException(String.format("Expected %d values on coordinate stack, " - + "but found %d", - n, - cstack.size())); - } + Coordinate[] cpop(int n) { + if (cstack.size() < n) { + throw new IllegalStateException(String.format("Expected %d values on coordinate stack, " + + "but found %d", + n, + cstack.size())); + } - Coordinate[] c = new Coordinate[n]; - for (int i = 0; i < n; i++) { - c[n - i - 1] = cstack.pop(); - } - return c; - } + Coordinate[] c = new Coordinate[n]; + for (int i = 0; i < n; i++) { + c[n - i - 1] = cstack.pop(); + } + return c; + } - Coordinate[] cpopAll() { - if (cstack.isEmpty()) { - throw new IllegalStateException("Coordinate stack is empty"); - } + Coordinate[] cpopAll() { + if (cstack.isEmpty()) { + throw new IllegalStateException("Coordinate stack is empty"); + } - return cpop(cstack.size()); - } + return cpop(cstack.size()); + } - T gpop(Class clazz) { - return gpop(1, clazz)[0]; - } + T gpop(Class clazz) { + return gpop(1, clazz)[0]; + } - T[] gpop(int n, Class clazz) { - if (gstack.size() < n) { - throw new IllegalStateException(String.format("Expected %d values on geometry stack, " - + "but found %d", n, gstack.size())); - } + T[] gpop(int n, Class clazz) { + if (gstack.size() < n) { + throw new IllegalStateException(String.format("Expected %d values on geometry stack, " + + "but found %d", n, gstack.size())); + } - @SuppressWarnings("unchecked") - T[] l = (T[]) Array.newInstance(clazz, n); - for (int i = 0; i < n; i++) { - Object g = gstack.pop(); - if (!clazz.isInstance(g)) { - throw new IllegalStateException(String.format("Expected %s on geometry stack, but " - + "found %s", clazz.getSimpleName(), g.getClass().getSimpleName())); - } + @SuppressWarnings("unchecked") + T[] l = (T[]) Array.newInstance(clazz, n); + for (int i = 0; i < n; i++) { + Object g = gstack.pop(); + if (!clazz.isInstance(g)) { + throw new IllegalStateException(String.format("Expected %s on geometry stack, but " + + "found %s", clazz.getSimpleName(), g.getClass().getSimpleName())); + } - l[n - i - 1] = clazz.cast(g); - } - return l; - } + l[n - i - 1] = clazz.cast(g); + } + return l; + } - T[] gpopAll(Class clazz) { - if (gstack.isEmpty()) { - throw new IllegalArgumentException("Geometry stack is empty"); - } + T[] gpopAll(Class clazz) { + if (gstack.isEmpty()) { + throw new IllegalArgumentException("Geometry stack is empty"); + } - int n = 0; - Iterator it = gstack.iterator(); - while (it.hasNext() && clazz.isInstance(it.next())) { - n++; - } + int n = 0; + Iterator it = gstack.iterator(); + while (it.hasNext() && clazz.isInstance(it.next())) { + n++; + } - if (n == 0) { - throw new IllegalArgumentException( - String.format("Expected %s on geometry stack", - clazz.getSimpleName())); - } + if (n == 0) { + throw new IllegalArgumentException( + String.format("Expected %s on geometry stack", + clazz.getSimpleName())); + } - return gpop(n, clazz); - } + return gpop(n, clazz); + } } diff --git a/vtm-playground/data/g3d/test.g3db b/vtm-playground/data/g3d/test.g3db deleted file mode 100644 index b6bd6857..00000000 Binary files a/vtm-playground/data/g3d/test.g3db and /dev/null differ diff --git a/vtm-playground/data/g3d/test.g3dj b/vtm-playground/data/g3d/test.g3dj deleted file mode 100644 index 143395e3..00000000 --- a/vtm-playground/data/g3d/test.g3dj +++ /dev/null @@ -1,4748 +0,0 @@ -{ - "version": [ 0, 1], - "id": "", - "meshes": [ - { - "attributes": ["POSITION"], - "vertices": [ - -44.509998, 15.000000, -48.078999, - -44.509998, 0.000000, -48.078999, - -43.915001, 15.000000, -52.787998, - -43.915001, 0.000000, -52.787998, - -41.426998, 15.000000, -54.946999, - -41.426998, 0.000000, -54.946999, - -39.555000, 15.000000, -52.331001, - -39.555000, 0.000000, -52.331001, - -27.945999, 15.000000, -62.484001, - -27.945999, 0.000000, -62.484001, - -27.465000, 15.000000, -65.924004, - -27.465000, 0.000000, -65.924004, - -25.465000, 15.000000, -67.649002, - -25.465000, 0.000000, -67.649002, - -35.355000, 15.000000, -80.039001, - -35.355000, 0.000000, -80.039001, - -38.505001, 15.000000, -80.440002, - -38.505001, 0.000000, -80.440002, - -74.762001, 15.000000, -84.570000, - -74.762001, 0.000000, -84.570000, - -75.042999, 15.000000, -82.355003, - -75.042999, 0.000000, -82.355003, - -139.567001, 15.000000, -81.752998, - -139.567001, 0.000000, -81.752998, - -144.876007, 15.000000, -67.615997, - -144.876007, 0.000000, -67.615997, - -150.720993, 15.000000, -56.105000, - -150.720993, 0.000000, -56.105000, - -156.759003, 15.000000, -44.205002, - -156.759003, 0.000000, -44.205002, - -158.550995, 15.000000, -46.576000, - -158.550995, 0.000000, -46.576000, - -160.832001, 15.000000, -41.756001, - -160.832001, 0.000000, -41.756001, - -179.602005, 15.000000, -2.182000, - -179.602005, 0.000000, -2.182000, - -152.699997, 15.000000, 8.160000, - -152.699997, 0.000000, 8.160000, - -150.587006, 15.000000, 2.984000, - -150.587006, 0.000000, 2.984000, - -148.065994, 15.000000, 3.930000, - -148.065994, 0.000000, 3.930000, - -150.292999, 15.000000, 9.084000, - -150.292999, 0.000000, 9.084000, - -144.227997, 15.000000, 11.388000, - -144.227997, 0.000000, 11.388000, - -137.654007, 15.000000, 13.893000, - -137.654007, 0.000000, 13.893000, - -137.279999, 15.000000, 13.013000, - -137.279999, 0.000000, 13.013000, - -136.136002, 15.000000, 14.238000, - -136.136002, 0.000000, 14.238000, - -134.585007, 15.000000, 15.095000, - -134.585007, 0.000000, 15.095000, - -132.806000, 15.000000, 15.496000, - -132.806000, 0.000000, 15.496000, - -130.725998, 15.000000, 15.507000, - -130.725998, 0.000000, 15.507000, - -129.362000, 15.000000, 15.173000, - -129.362000, 0.000000, 15.173000, - -127.764000, 15.000000, 14.483000, - -127.764000, 0.000000, 14.483000, - -126.607002, 15.000000, 13.693000, - -126.607002, 0.000000, 13.693000, - -125.651001, 15.000000, 12.590000, - -125.651001, 0.000000, 12.590000, - -125.102997, 15.000000, 11.399000, - -125.102997, 0.000000, 11.399000, - -124.420998, 15.000000, 12.023000, - -124.420998, 0.000000, 12.023000, - -90.463997, 15.000000, -14.816000, - -90.463997, 0.000000, -14.816000, - -90.189003, 15.000000, -14.416000, - -90.189003, 0.000000, -14.416000, - -82.660004, 15.000000, -20.271000, - -82.660004, 0.000000, -20.271000, - -84.825996, 15.000000, -22.931999, - -84.825996, 0.000000, -22.931999, - -79.911003, 15.000000, -26.705000, - -79.911003, 0.000000, -26.705000, - -75.846001, 15.000000, -26.049000, - -75.846001, 0.000000, -26.049000, - -74.348000, 15.000000, -23.677000, - -74.348000, 0.000000, -23.677000, - -62.124001, 15.000000, -33.741001, - -62.124001, 0.000000, -33.741001, - -61.467999, 15.000000, -38.426998, - -61.467999, 0.000000, -38.426998, - -59.061001, 15.000000, -40.554001, - -59.061001, 0.000000, -40.554001, - -57.127998, 15.000000, -37.915001, - -57.127998, 0.000000, -37.915001, - -158.798996, 27.000000, 128.639008, - -158.798996, 0.000000, 128.639008, - -158.457993, 27.000000, 128.115997, - -158.457993, 0.000000, 128.115997, - -175.410004, 27.000000, 116.528000, - -175.410004, 0.000000, 116.528000, - -188.804001, 27.000000, 136.298004, - -188.804001, 0.000000, 136.298004, - -172.761002, 27.000000, 147.139999, - -172.761002, 0.000000, 147.139999, - -167.011002, 27.000000, 139.380997, - -167.011002, 0.000000, 139.380997, - -170.013000, 27.000000, 137.367004, - -170.013000, 0.000000, 137.367004, - -167.345001, 27.000000, 133.192001, - -167.345001, 0.000000, 133.192001, - -164.195007, 27.000000, 135.417999, - -164.195007, 0.000000, 135.417999, - -108.244003, 10.000000, 115.526001, - -108.244003, 0.000000, 115.526001, - -119.900002, 10.000000, 132.623993, - -119.900002, 0.000000, 132.623993, - -124.133003, 10.000000, 138.925003, - -124.133003, 0.000000, 138.925003, - -107.628998, 10.000000, 150.001007, - -107.628998, 0.000000, 150.001007, - -93.559998, 10.000000, 159.440002, - -93.559998, 0.000000, 159.440002, - -82.981003, 10.000000, 139.481995, - -82.981003, 0.000000, 139.481995, - 27.530001, 20.000000, 83.933998, - 27.530001, 0.000000, 83.933998, - 38.791000, 20.000000, 91.336998, - 38.791000, 0.000000, 91.336998, - 49.911999, 20.000000, 99.563004, - 49.911999, 0.000000, 99.563004, - 63.660000, 20.000000, 111.796997, - 63.660000, 0.000000, 111.796997, - 74.139000, 20.000000, 121.860001, - 74.139000, 0.000000, 121.860001, - 102.873001, 20.000000, 91.805000, - 102.873001, 0.000000, 91.805000, - 105.086998, 20.000000, 81.485001, - 105.086998, 0.000000, 81.485001, - 89.098000, 20.000000, 65.856003, - 89.098000, 0.000000, 65.856003, - 55.255001, 20.000000, 49.091999, - 55.255001, 0.000000, 49.091999, - 47.458000, 20.000000, 50.283001, - 47.458000, 0.000000, 50.283001, - -15.889000, 29.500000, -22.754000, - -15.889000, 0.000000, -22.754000, - -7.784000, 29.500000, -18.846001, - -7.784000, 0.000000, -18.846001, - 0.635000, 29.500000, -20.983999, - 0.635000, 0.000000, -20.983999, - 5.837000, 29.500000, -28.063000, - 5.837000, 0.000000, -28.063000, - 5.202000, 29.500000, -37.103001, - 5.202000, 0.000000, -37.103001, - -0.977000, 29.500000, -43.391998, - -0.977000, 0.000000, -43.391998, - -9.871000, 29.500000, -44.237999, - -9.871000, 0.000000, -44.237999, - -16.959000, 29.500000, -39.439999, - -16.959000, 0.000000, -39.439999, - -19.433001, 29.500000, -30.346001, - -19.433001, 0.000000, -30.346001, - 1.350000, 24.500000, -5.187000, - 1.350000, 0.000000, -5.187000, - 26.280001, 24.500000, 4.119000, - 26.280001, 0.000000, 4.119000, - 26.500000, 24.500000, 3.652000, - 26.500000, 0.000000, 3.652000, - 41.431999, 24.500000, -26.459999, - 41.431999, 0.000000, -26.459999, - 51.991001, 24.500000, -51.662998, - 51.991001, 0.000000, -51.662998, - 21.504999, 24.500000, -63.831001, - 21.504999, 0.000000, -63.831001, - -3.404000, 24.500000, -49.848999, - -3.404000, 0.000000, -49.848999, - -9.750000, 24.500000, -44.883999, - -9.750000, 0.000000, -44.883999, - -10.747000, 24.500000, -46.174999, - -10.747000, 0.000000, -46.174999, - -12.693000, 24.500000, -48.702000, - -12.693000, 0.000000, -48.702000, - -27.157000, 24.500000, -37.470001, - -27.157000, 0.000000, -37.470001, - -25.111000, 24.500000, -34.854000, - -25.111000, 0.000000, -34.854000, - -24.141001, 24.500000, -33.606998, - -24.141001, 0.000000, -33.606998, - -55.362999, 24.500000, -9.161000, - -55.362999, 0.000000, -9.161000, - -50.681999, 24.500000, -3.017000, - -50.681999, 0.000000, -3.017000, - -21.212000, 24.500000, 10.876000, - -21.212000, 0.000000, 10.876000, - -9.824000, 24.500000, 1.425000, - -9.824000, 0.000000, 1.425000, - -10.954000, 24.500000, -2.716000, - -10.954000, 0.000000, -2.716000, - -7.691000, 24.500000, -4.753000, - -7.691000, 0.000000, -4.753000, - -4.815000, 24.500000, -7.280000, - -4.815000, 0.000000, -7.280000, - -15.889000, 24.500000, -22.754000, - -19.433001, 24.500000, -30.346001, - -16.959000, 24.500000, -39.439999, - -9.871000, 24.500000, -44.237999, - -0.977000, 24.500000, -43.391998, - 5.202000, 24.500000, -37.103001, - 5.837000, 24.500000, -28.063000, - 0.635000, 24.500000, -20.983999, - -7.784000, 24.500000, -18.846001, - 159.667007, 10.000000, -8.349000, - 159.667007, 0.000000, -8.349000, - 164.889008, 10.000000, -15.674000, - 164.889008, 0.000000, -15.674000, - 165.330994, 10.000000, -16.275000, - 165.330994, 0.000000, -16.275000, - 164.307999, 10.000000, -16.976000, - 164.307999, 0.000000, -16.976000, - 165.604996, 10.000000, -18.934999, - 165.604996, 0.000000, -18.934999, - 166.701996, 10.000000, -18.267000, - 166.701996, 0.000000, -18.267000, - 170.921005, 10.000000, -24.212000, - 170.921005, 0.000000, -24.212000, - 168.641006, 10.000000, -24.802000, - 168.641006, 0.000000, -24.802000, - 166.005997, 10.000000, -25.481001, - 166.005997, 0.000000, -25.481001, - 155.675003, 10.000000, -11.699000, - 155.675003, 0.000000, -11.699000, - 157.681000, 10.000000, -10.019000, - 157.681000, 0.000000, -10.019000, - -162.149002, 15.000000, -42.457001, - -162.149002, 0.000000, -42.457001, - -152.927994, 15.000000, -57.273998, - -152.927994, 0.000000, -57.273998, - -155.468994, 15.000000, -58.620998, - -155.468994, 0.000000, -58.620998, - -146.869003, 15.000000, -74.405998, - -146.869003, 0.000000, -74.405998, - -151.496994, 15.000000, -76.944000, - -151.496994, 0.000000, -76.944000, - -155.194000, 15.000000, -78.982002, - -155.194000, 0.000000, -78.982002, - -170.087006, 15.000000, -73.626999, - -170.087006, 0.000000, -73.626999, - -184.764999, 15.000000, -66.792000, - -184.764999, 0.000000, -66.792000, - -187.132004, 15.000000, -65.690002, - -187.132004, 0.000000, -65.690002, - -199.376007, 15.000000, -58.499001, - -199.376007, 0.000000, -58.499001, - -187.626999, 15.000000, -48.324001, - -187.626999, 0.000000, -48.324001, - -167.231003, 15.000000, -36.847000, - -167.231003, 0.000000, -36.847000, - -163.848007, 15.000000, -43.415001, - -163.848007, 0.000000, -43.415001, - -69.639999, 7.500000, -94.532997, - -69.639999, 0.000000, -94.532997, - -61.054001, 7.500000, -93.910004, - -61.054001, 0.000000, -93.910004, - -60.036999, 7.500000, -104.318001, - -60.036999, 0.000000, -104.318001, - -69.057999, 7.500000, -104.852997, - -69.057999, 0.000000, -104.852997, - -71.170998, 7.500000, -104.974998, - -71.170998, 0.000000, -104.974998, - -93.044998, 7.500000, -106.266998, - -93.044998, 0.000000, -106.266998, - -94.676003, 7.500000, -106.366997, - -94.676003, 0.000000, -106.366997, - -94.556000, 7.500000, -96.314003, - -94.556000, 0.000000, -96.314003, - -152.199005, 10.000000, -187.910995, - -152.199005, 0.000000, -187.910995, - -157.160004, 10.000000, -181.520996, - -157.160004, 0.000000, -181.520996, - -142.154999, 10.000000, -169.865005, - -142.154999, 0.000000, -169.865005, - -137.192993, 10.000000, -176.266006, - -137.192993, 0.000000, -176.266006, - -185.574005, 5.000000, -176.634003, - -185.574005, 0.000000, -176.634003, - -171.177002, 5.000000, -161.817001, - -171.177002, 0.000000, -161.817001, - -165.518997, 5.000000, -167.315994, - -165.518997, 0.000000, -167.315994, - -164.998001, 5.000000, -167.817001, - -164.998001, 0.000000, -167.817001, - -179.388000, 5.000000, -182.634003, - -179.388000, 0.000000, -182.634003, - -197.972000, 10.000000, -10.887000, - -197.972000, 0.000000, -10.887000, - -191.117004, 10.000000, -6.423000, - -191.117004, 0.000000, -6.423000, - -178.117996, 10.000000, -32.037998, - -178.117996, 0.000000, -32.037998, - -181.388000, 10.000000, -33.819000, - -181.388000, 0.000000, -33.819000, - -187.158997, 10.000000, -23.177000, - -187.158997, 0.000000, -23.177000, - -189.699997, 10.000000, -24.613001, - -189.699997, 0.000000, -24.613001, - -190.481995, 10.000000, -23.177000, - -190.481995, 0.000000, -23.177000, - -194.735001, 10.000000, -167.727997, - -194.735001, 0.000000, -167.727997, - -180.345001, 10.000000, -152.910995, - -180.345001, 0.000000, -152.910995, - -171.177002, 10.000000, -161.817001, - -185.574005, 10.000000, -176.634003, - 93.318001, 5.000000, 113.432999, - 93.318001, 0.000000, 113.432999, - 80.539001, 5.000000, 127.113998, - 80.539001, 0.000000, 127.113998, - 85.982002, 5.000000, 132.190002, - 85.982002, 0.000000, 132.190002, - 98.767998, 5.000000, 118.510002, - 98.767998, 0.000000, 118.510002, - -15.040000, 44.000000, 62.573002, - -15.040000, 41.000000, 62.573002, - -6.106000, 44.000000, 41.154999, - -6.106000, 41.000000, 41.154999, - -19.841000, 44.000000, 35.422001, - -19.841000, 41.000000, 35.422001, - -28.782000, 44.000000, 56.840000, - -28.782000, 41.000000, 56.840000, - -19.781000, 41.000000, 34.341999, - -19.781000, 0.000000, 34.341999, - -24.101000, 41.000000, 44.827999, - -24.101000, 0.000000, 44.827999, - -29.209999, 41.000000, 57.217999, - -29.209999, 0.000000, 57.217999, - -14.913000, 41.000000, 63.118000, - -14.913000, 0.000000, 63.118000, - -5.484000, 41.000000, 40.230999, - -5.484000, 0.000000, 40.230999, - -16.906000, 41.000000, 35.521999, - -16.906000, 0.000000, 35.521999, - -19.781000, 7.500000, 34.341999, - -16.906000, 7.500000, 35.521999, - -16.163000, 7.500000, 33.719002, - -16.163000, 0.000000, 33.719002, - -19.039000, 7.500000, 32.539001, - -19.039000, 0.000000, 32.539001, - -34.405998, 22.000000, -142.623993, - -34.405998, 0.000000, -142.623993, - -40.931999, 22.000000, -130.869003, - -40.931999, 0.000000, -130.869003, - -41.527000, 22.000000, -129.800003, - -41.527000, 0.000000, -129.800003, - -29.812000, 22.000000, -123.288002, - -29.812000, 0.000000, -123.288002, - -20.289000, 22.000000, -118.011002, - -20.289000, 0.000000, -118.011002, - -7.838000, 22.000000, -111.098000, - -7.838000, 0.000000, -111.098000, - 0.635000, 22.000000, -106.400002, - 0.635000, 0.000000, -106.400002, - 3.009000, 22.000000, -110.664001, - 3.009000, 0.000000, -110.664001, - 3.316000, 22.000000, -111.220001, - 3.316000, 0.000000, -111.220001, - 7.750000, 22.000000, -119.212997, - 7.750000, 0.000000, -119.212997, - -22.730000, 22.000000, -136.134003, - -22.730000, 0.000000, -136.134003, - -30.728001, 22.000000, -140.576004, - -30.728001, 0.000000, -140.576004, - 3.009000, 20.000000, -110.664001, - 0.635000, 20.000000, -106.400002, - -7.838000, 20.000000, -111.098000, - -20.289000, 20.000000, -118.011002, - -29.812000, 20.000000, -123.288002, - -41.527000, 20.000000, -129.800003, - -42.155998, 20.000000, -130.145004, - -42.155998, 0.000000, -130.145004, - -53.491001, 20.000000, -109.718002, - -53.491001, 0.000000, -109.718002, - -41.085999, 20.000000, -102.827003, - -41.085999, 0.000000, -102.827003, - -18.049000, 20.000000, -90.046997, - -18.049000, 0.000000, -90.046997, - -19.039000, 20.000000, -88.254997, - -19.039000, 0.000000, -88.254997, - -7.965000, 20.000000, -82.110001, - -7.965000, 0.000000, -82.110001, - 6.733000, 20.000000, -108.603996, - 6.733000, 0.000000, -108.603996, - -69.753998, 15.000000, 42.847000, - -69.753998, 0.000000, 42.847000, - -64.824997, 15.000000, 28.565001, - -64.824997, 0.000000, 28.565001, - -66.872002, 15.000000, 27.863001, - -66.872002, 0.000000, 27.863001, - -69.038002, 15.000000, 27.106001, - -69.038002, 0.000000, 27.106001, - -74.689003, 15.000000, 25.158001, - -74.689003, 0.000000, 25.158001, - -79.683998, 15.000000, 39.318001, - -79.683998, 0.000000, 39.318001, - -97.544998, 10.000000, 199.057999, - -97.544998, 0.000000, 199.057999, - -108.097000, 10.000000, 184.408997, - -108.097000, 0.000000, 184.408997, - -110.724998, 10.000000, 185.867004, - -110.724998, 0.000000, 185.867004, - -112.136002, 10.000000, 183.261993, - -112.136002, 0.000000, 183.261993, - -120.067001, 10.000000, 191.856003, - -120.067001, 0.000000, 191.856003, - -107.148003, 10.000000, 209.197998, - -107.148003, 0.000000, 209.197998, - -99.565002, 10.000000, 201.595993, - -99.565002, 0.000000, 201.595993, - -99.110001, 10.000000, 201.149994, - -99.110001, 0.000000, 201.149994, - -177.675995, 18.000000, 38.283001, - -177.675995, 0.000000, 38.283001, - -183.380997, 18.000000, 31.270000, - -183.380997, 0.000000, 31.270000, - -184.718002, 18.000000, 32.728001, - -184.718002, 0.000000, 32.728001, - -192.809006, 18.000000, 41.533001, - -192.809006, 0.000000, 41.533001, - -194.360992, 18.000000, 40.242001, - -194.360992, 0.000000, 40.242001, - -202.438995, 18.000000, 50.683998, - -202.438995, 0.000000, 50.683998, - -194.313995, 18.000000, 57.185001, - -194.313995, 0.000000, 57.185001, - -187.647003, 18.000000, 48.747002, - -187.647003, 0.000000, 48.747002, - -178.880005, 18.000000, 39.551998, - -178.880005, 0.000000, 39.551998, - -194.313995, 28.000000, 57.185001, - -199.268997, 28.000000, 63.708000, - -199.268997, 0.000000, 63.708000, - -209.701004, 28.000000, 78.445999, - -209.701004, 0.000000, 78.445999, - -199.403000, 28.000000, 87.619003, - -199.403000, 0.000000, 87.619003, - -182.565002, 28.000000, 66.346001, - -182.565002, 0.000000, 66.346001, - -169.873001, 28.000000, 50.293999, - -169.873001, 0.000000, 50.293999, - -168.701996, 28.000000, 48.813999, - -168.701996, 0.000000, 48.813999, - -177.675995, 28.000000, 38.283001, - -178.880005, 28.000000, 39.551998, - -187.647003, 28.000000, 48.747002, - -183.380997, 21.000000, 31.270000, - -189.947006, 21.000000, 24.357000, - -189.947006, 0.000000, 24.357000, - -199.796997, 21.000000, 15.462000, - -199.796997, 0.000000, 15.462000, - -212.048004, 21.000000, 6.679000, - -212.048004, 0.000000, 6.679000, - -212.931000, 21.000000, 8.327000, - -212.931000, 0.000000, 8.327000, - -214.421997, 21.000000, 11.110000, - -214.421997, 0.000000, 11.110000, - -217.457993, 21.000000, 16.709000, - -217.457993, 0.000000, 16.709000, - -225.395004, 21.000000, 30.613001, - -225.395004, 0.000000, 30.613001, - -232.804993, 21.000000, 41.366001, - -232.804993, 0.000000, 41.366001, - -239.806000, 21.000000, 50.951000, - -239.806000, 0.000000, 50.951000, - -240.354004, 21.000000, 51.863998, - -240.354004, 0.000000, 51.863998, - -222.513000, 21.000000, 67.415001, - -222.513000, 0.000000, 67.415001, - -209.701004, 21.000000, 78.445999, - -199.268997, 21.000000, 63.708000, - -194.313995, 21.000000, 57.185001, - -202.438995, 21.000000, 50.683998, - -194.360992, 21.000000, 40.242001, - -192.809006, 21.000000, 41.533001, - -184.718002, 21.000000, 32.728001, - -182.718994, 10.000000, -2.827000, - -182.718994, 0.000000, -2.827000, - -170.735001, 10.000000, -28.041000, - -170.735001, 0.000000, -28.041000, - -190.429001, 10.000000, -38.706001, - -190.429001, 0.000000, -38.706001, - -197.584000, 10.000000, -27.372999, - -197.584000, 0.000000, -27.372999, - -170.975998, 7.500000, -118.345001, - -170.975998, 0.000000, -118.345001, - -180.845993, 7.500000, -110.307999, - -180.845993, 0.000000, -110.307999, - -173.009003, 7.500000, -96.057999, - -173.009003, 0.000000, -96.057999, - -161.681000, 7.500000, -101.045998, - -161.681000, 0.000000, -101.045998, - -178.158005, 7.500000, -93.920998, - -178.158005, 0.000000, -93.920998, - -174.011993, 7.500000, -84.347000, - -174.011993, 0.000000, -84.347000, - -157.421005, 7.500000, -90.481003, - -157.421005, 0.000000, -90.481003, - -191.651993, 7.500000, -76.710999, - -191.651993, 0.000000, -76.710999, - -179.375000, 7.500000, -96.725998, - -179.375000, 0.000000, -96.725998, - -197.014999, 7.500000, -89.089996, - -197.014999, 0.000000, -89.089996, - -80.680000, 15.000000, 79.025002, - -80.680000, 0.000000, 79.025002, - -83.989998, 15.000000, 77.556000, - -83.989998, 0.000000, 77.556000, - -92.958000, 15.000000, 92.818001, - -92.958000, 0.000000, 92.818001, - -82.874001, 15.000000, 102.703003, - -82.874001, 0.000000, 102.703003, - -73.905998, 15.000000, 93.508003, - -73.905998, 0.000000, 93.508003, - -72.615997, 15.000000, 90.824997, - -72.615997, 0.000000, 90.824997, - -81.958000, 15.000000, 81.608002, - -81.958000, 0.000000, 81.608002, - -53.563999, 7.500000, 113.055000, - -53.563999, 0.000000, 113.055000, - -48.997002, 7.500000, 114.713997, - -48.997002, 0.000000, 114.713997, - -46.876999, 7.500000, 112.253998, - -46.876999, 0.000000, 112.253998, - -40.931999, 7.500000, 115.125000, - -40.931999, 0.000000, 115.125000, - -34.271999, 7.500000, 107.889999, - -34.271999, 0.000000, 107.889999, - -30.306999, 7.500000, 98.349998, - -30.306999, 0.000000, 98.349998, - -31.209000, 7.500000, 97.871002, - -31.209000, 0.000000, 97.871002, - -28.722000, 7.500000, 92.338997, - -28.722000, 0.000000, 92.338997, - -42.283001, 7.500000, 86.683998, - -42.283001, 0.000000, 86.683998, - -45.827000, 7.500000, 94.364998, - -45.827000, 0.000000, 94.364998, - -47.372002, 7.500000, 97.972000, - -47.372002, 0.000000, 97.972000, - -52.334000, 7.500000, 109.526001, - -52.334000, 0.000000, 109.526001, - -54.146000, 7.500000, 112.498001, - -54.146000, 0.000000, 112.498001, - -143.839996, 10.000000, 125.377998, - -143.839996, 0.000000, 125.377998, - -141.031006, 10.000000, 127.315002, - -141.031006, 0.000000, 127.315002, - -138.557007, 10.000000, 129.007004, - -138.557007, 0.000000, 129.007004, - -135.854996, 10.000000, 130.865997, - -135.854996, 0.000000, 130.865997, - -111.834999, 10.000000, 112.231003, - -111.834999, 0.000000, 112.231003, - -119.994003, 10.000000, 104.750999, - -119.994003, 0.000000, 104.750999, - -122.821999, 10.000000, 102.156998, - -122.821999, 0.000000, 102.156998, - -126.432999, 10.000000, 98.839996, - -126.432999, 0.000000, 98.839996, - -139.934998, 10.000000, 86.449997, - -139.934998, 0.000000, 86.449997, - -141.091003, 10.000000, 85.392998, - -141.091003, 0.000000, 85.392998, - -145.337997, 10.000000, 85.614998, - -145.337997, 0.000000, 85.614998, - -164.535995, 10.000000, 107.968002, - -164.535995, 0.000000, 107.968002, - -164.147995, 10.000000, 111.406998, - -164.147995, 0.000000, 111.406998, - -54.186001, 15.000000, 129.552002, - -54.186001, 0.000000, 129.552002, - -36.205002, 15.000000, 146.360992, - -36.205002, 0.000000, 146.360992, - -35.616001, 15.000000, 145.792999, - -35.616001, 0.000000, 145.792999, - -24.863001, 15.000000, 135.485001, - -24.863001, 0.000000, 135.485001, - -26.181000, 15.000000, 134.205002, - -26.181000, 0.000000, 134.205002, - -25.511999, 15.000000, 133.559998, - -25.511999, 0.000000, 133.559998, - -28.962000, 15.000000, 130.108994, - -28.962000, 0.000000, 130.108994, - -29.691000, 15.000000, 130.776993, - -29.691000, 0.000000, 130.776993, - -31.577000, 15.000000, 128.951004, - -31.577000, 0.000000, 128.951004, - -29.457001, 15.000000, 126.334999, - -29.457001, 0.000000, 126.334999, - -26.007000, 15.000000, 121.514999, - -26.007000, 0.000000, 121.514999, - -25.518999, 15.000000, 121.882004, - -25.518999, 0.000000, 121.882004, - -22.542999, 15.000000, 117.842003, - -22.542999, 0.000000, 117.842003, - -23.091000, 15.000000, 117.441002, - -23.091000, 0.000000, 117.441002, - -20.370001, 15.000000, 113.644997, - -20.370001, 0.000000, 113.644997, - -34.271999, 15.000000, 107.889999, - -40.931999, 15.000000, 115.125000, - -3.645000, 15.000000, 179.143005, - -3.645000, 0.000000, 179.143005, - 8.064000, 15.000000, 168.858002, - 8.064000, 0.000000, 168.858002, - -16.049999, 15.000000, 143.544998, - -16.049999, 0.000000, 143.544998, - -24.247999, 15.000000, 134.951004, - -24.247999, 0.000000, 134.951004, - -69.198997, 7.500000, 79.771004, - -69.198997, 0.000000, 79.771004, - -79.209000, 7.500000, 76.053001, - -79.209000, 0.000000, 76.053001, - -80.680000, 7.500000, 79.025002, - -81.958000, 7.500000, 81.608002, - -72.615997, 7.500000, 90.824997, - -16.371000, 15.000000, 104.550003, - -16.371000, 0.000000, 104.550003, - -30.306999, 15.000000, 98.349998, - -79.476997, 15.000000, 57.764000, - -79.476997, 0.000000, 57.764000, - -88.417000, 15.000000, 54.914001, - -88.417000, 0.000000, 54.914001, - -96.113998, 15.000000, 71.544998, - -96.113998, 0.000000, 71.544998, - -87.688004, 15.000000, 75.719002, - -87.688004, 0.000000, 75.719002, - -22.235001, 15.000000, 78.068001, - -22.235001, 0.000000, 78.068001, - -28.722000, 15.000000, 92.338997, - -31.209000, 15.000000, 97.871002, - -15.722000, 15.000000, 104.762001, - -15.722000, 0.000000, 104.762001, - -6.748000, 15.000000, 84.424004, - -6.748000, 0.000000, 84.424004, - -43.012001, 15.000000, 69.552002, - -43.012001, 0.000000, 69.552002, - -47.578999, 15.000000, 82.698997, - -47.578999, 0.000000, 82.698997, - -50.575001, 15.000000, 92.773003, - -50.575001, 0.000000, 92.773003, - -45.827000, 15.000000, 94.364998, - -42.283001, 15.000000, 86.683998, - -35.817001, 15.000000, 72.501999, - -35.817001, 0.000000, 72.501999, - -35.409000, 15.000000, 71.278000, - -35.409000, 0.000000, 71.278000, - -41.581001, 15.000000, 68.727997, - -41.581001, 0.000000, 68.727997, - -42.056000, 15.000000, 69.897003, - -42.056000, 0.000000, 69.897003, - -96.862999, 31.200001, 88.888000, - -96.862999, 0.000000, 88.888000, - -92.958000, 31.200001, 92.818001, - -83.989998, 31.200001, 77.556000, - -87.688004, 31.200001, 75.719002, - -96.113998, 31.200001, 71.544998, - -88.417000, 31.200001, 54.914001, - -116.616997, 31.200001, 45.908001, - -116.616997, 0.000000, 45.908001, - -127.810997, 31.200001, 57.686001, - -127.810997, 0.000000, 57.686001, - -62.771999, 10.000000, 181.447998, - -62.771999, 0.000000, 181.447998, - -53.717999, 10.000000, 168.067001, - -53.717999, 0.000000, 168.067001, - -68.141998, 10.000000, 153.317993, - -68.141998, 0.000000, 153.317993, - -77.570999, 10.000000, 170.817001, - -77.570999, 0.000000, 170.817001, - -86.751999, 10.000000, 164.283005, - -86.751999, 0.000000, 164.283005, - -20.704000, 10.000000, 211.235001, - -20.704000, 0.000000, 211.235001, - -12.318000, 10.000000, 202.919998, - -12.318000, 0.000000, 202.919998, - -37.327999, 10.000000, 177.339996, - -37.327999, 0.000000, 177.339996, - -40.717999, 10.000000, 180.490005, - -40.717999, 0.000000, 180.490005, - -51.077000, 10.000000, 170.593994, - -51.077000, 0.000000, 170.593994, - -139.606995, 10.000000, 142.007996, - -139.606995, 0.000000, 142.007996, - -143.578995, 10.000000, 139.225998, - -143.578995, 0.000000, 139.225998, - -146.052994, 10.000000, 137.511002, - -146.052994, 0.000000, 137.511002, - -159.574997, 10.000000, 156.490997, - -159.574997, 0.000000, 156.490997, - -152.485992, 10.000000, 161.600006, - -152.485992, 0.000000, 161.600006, - -147.464005, 10.000000, 154.431000, - -147.464005, 0.000000, 154.431000, - -146.675003, 10.000000, 153.328995, - -146.675003, 0.000000, 153.328995, - -146.261002, 10.000000, 152.684006, - -146.261002, 0.000000, 152.684006, - -142.401993, 10.000000, 146.350006, - -142.401993, 0.000000, 146.350006, - -145.485001, 10.000000, 136.720993, - -145.485001, 0.000000, 136.720993, - -156.156998, 10.000000, 129.039993, - -156.156998, 0.000000, 129.039993, - -156.177002, 10.000000, 129.029007, - -156.177002, 0.000000, 129.029007, - -156.725998, 10.000000, 129.807999, - -156.725998, 0.000000, 129.807999, - -158.136993, 10.000000, 128.783997, - -158.136993, 0.000000, 128.783997, - -158.270996, 10.000000, 128.973007, - -158.270996, 0.000000, 128.973007, - -158.798996, 10.000000, 128.639008, - -164.195007, 10.000000, 135.417999, - -167.011002, 10.000000, 139.380997, - -172.761002, 10.000000, 147.139999, - 134.363007, 15.000000, -18.679001, - 134.363007, 0.000000, -18.679001, - 110.115997, 15.000000, 10.275000, - 110.115997, 0.000000, 10.275000, - 106.638000, 15.000000, 7.180000, - 106.638000, 0.000000, 7.180000, - 91.064003, 15.000000, 25.593000, - 91.064003, 0.000000, 25.593000, - 89.412003, 15.000000, 27.452000, - 89.412003, 0.000000, 27.452000, - 93.859001, 15.000000, 31.504000, - 93.859001, 0.000000, 31.504000, - 93.504997, 15.000000, 31.915001, - 93.504997, 0.000000, 31.915001, - 105.908997, 15.000000, 42.668999, - 105.908997, 0.000000, 42.668999, - 118.147003, 15.000000, 55.827000, - 118.147003, 0.000000, 55.827000, - 128.552002, 15.000000, 56.138000, - 128.552002, 0.000000, 56.138000, - 148.184998, 15.000000, 38.404999, - 148.184998, 0.000000, 38.404999, - 150.123993, 15.000000, 38.493999, - 150.123993, 0.000000, 38.493999, - 154.630997, 15.000000, 34.353001, - 154.630997, 0.000000, 34.353001, - 154.852005, 15.000000, 32.382999, - 154.852005, 0.000000, 32.382999, - 165.216995, 15.000000, 23.021000, - 165.216995, 0.000000, 23.021000, - 165.423996, 15.000000, 13.581000, - 165.423996, 0.000000, 13.581000, - 157.600006, 15.000000, 5.010000, - 157.600006, 0.000000, 5.010000, - 158.054993, 15.000000, 4.498000, - 158.054993, 0.000000, 4.498000, - 64.135002, 15.000000, -42.825001, - 64.135002, 0.000000, -42.825001, - 79.280998, 15.000000, -37.325001, - 79.280998, 0.000000, -37.325001, - 79.474998, 15.000000, -38.027000, - 79.474998, 0.000000, -38.027000, - 84.818001, 15.000000, -36.680000, - 84.818001, 0.000000, -36.680000, - 84.564003, 15.000000, -35.455002, - 84.564003, 0.000000, -35.455002, - 90.100998, 15.000000, -32.750000, - 90.100998, 0.000000, -32.750000, - 97.643997, 15.000000, -44.784000, - 97.643997, 0.000000, -44.784000, - 66.809998, 15.000000, -52.365002, - 66.809998, 0.000000, -52.365002, - 63.419998, 15.000000, -43.159000, - 63.419998, 0.000000, -43.159000, - 111.907997, 15.000000, -41.744999, - 111.907997, 0.000000, -41.744999, - 88.602997, 15.000000, -28.798000, - 88.602997, 0.000000, -28.798000, - 95.203003, 15.000000, -25.158001, - 95.203003, 0.000000, -25.158001, - 98.694000, 15.000000, -30.134001, - 98.694000, 0.000000, -30.134001, - 101.469002, 15.000000, -28.396999, - 101.469002, 0.000000, -28.396999, - 102.078003, 15.000000, -20.527000, - 102.078003, 0.000000, -20.527000, - 102.892998, 15.000000, -21.962999, - 102.892998, 0.000000, -21.962999, - 104.191002, 15.000000, -21.173000, - 104.191002, 0.000000, -21.173000, - 116.970001, 15.000000, -37.236000, - 116.970001, 0.000000, -37.236000, - 117.237000, 15.000000, -37.536999, - 117.237000, 0.000000, -37.536999, - 112.175003, 15.000000, -41.966999, - 112.175003, 0.000000, -41.966999, - 62.375999, 15.000000, -38.951000, - 62.375999, 0.000000, -38.951000, - 60.175999, 15.000000, -34.097000, - 60.175999, 0.000000, -34.097000, - 59.748001, 15.000000, -33.151001, - 59.748001, 0.000000, -33.151001, - 57.133999, 15.000000, -30.011999, - 57.133999, 0.000000, -30.011999, - 57.930000, 15.000000, -29.143000, - 57.930000, 0.000000, -29.143000, - 56.023998, 15.000000, -24.947001, - 56.023998, 0.000000, -24.947001, - 51.102001, 15.000000, -14.082000, - 51.102001, 0.000000, -14.082000, - 46.220001, 15.000000, -3.306000, - 46.220001, 0.000000, -3.306000, - 42.181000, 15.000000, 5.611000, - 42.181000, 0.000000, 5.611000, - 39.881001, 15.000000, 10.676000, - 39.881001, 0.000000, 10.676000, - 35.902000, 15.000000, 19.459000, - 35.902000, 0.000000, 19.459000, - 33.808998, 15.000000, 22.476000, - 33.808998, 0.000000, 22.476000, - 29.329000, 15.000000, 28.931999, - 29.329000, 0.000000, 28.931999, - 30.150999, 15.000000, 29.288000, - 30.150999, 0.000000, 29.288000, - 52.486000, 15.000000, 39.018002, - 52.486000, 0.000000, 39.018002, - 66.716003, 15.000000, 45.207001, - 66.716003, 0.000000, 45.207001, - 68.702003, 15.000000, 43.035999, - 68.702003, 0.000000, 43.035999, - 69.056999, 15.000000, 43.403999, - 69.056999, 0.000000, 43.403999, - 70.581001, 15.000000, 41.723000, - 70.581001, 0.000000, 41.723000, - 72.085999, 15.000000, 40.063999, - 72.085999, 0.000000, 40.063999, - 71.718002, 15.000000, 39.730000, - 71.718002, 0.000000, 39.730000, - 73.737999, 15.000000, 37.526001, - 73.737999, 0.000000, 37.526001, - 74.580002, 15.000000, 38.339001, - 74.580002, 0.000000, 38.339001, - 80.865997, 15.000000, 31.103001, - 80.865997, 0.000000, 31.103001, - 83.125999, 15.000000, 28.497999, - 83.125999, 0.000000, 28.497999, - 87.874001, 15.000000, 23.021000, - 87.874001, 0.000000, 23.021000, - 120.546997, 15.000000, -33.417999, - 120.546997, 0.000000, -33.417999, - -52.132999, 15.000000, 24.691000, - -52.132999, 0.000000, 24.691000, - -50.448002, 15.000000, 23.054001, - -50.448002, 0.000000, 23.054001, - -48.636002, 15.000000, 17.934000, - -48.636002, 0.000000, 17.934000, - -44.389999, 15.000000, 19.625999, - -44.389999, 0.000000, 19.625999, - -41.220001, 15.000000, 11.911000, - -41.220001, 0.000000, 11.911000, - -54.955002, 15.000000, 5.566000, - -54.955002, 0.000000, 5.566000, - -60.605999, 15.000000, 19.358999, - -60.605999, 0.000000, 19.358999, - -60.833000, 15.000000, 19.926001, - -60.833000, 0.000000, 19.926001, - -56.172001, 15.000000, 21.663000, - -56.172001, 0.000000, 21.663000, - -56.786999, 15.000000, 23.021000, - -56.786999, 0.000000, 23.021000, - -62.859001, 15.000000, -4.542000, - -62.859001, 0.000000, -4.542000, - -67.674004, 15.000000, -0.712000, - -67.674004, 0.000000, -0.712000, - -63.421001, 15.000000, 5.522000, - -63.421001, 0.000000, 5.522000, - -67.875000, 15.000000, 9.307000, - -67.875000, 0.000000, 9.307000, - -66.263000, 15.000000, 11.533000, - -66.263000, 0.000000, 11.533000, - -67.594002, 15.000000, 15.095000, - -67.594002, 0.000000, 15.095000, - -68.055000, 15.000000, 16.174999, - -68.055000, 0.000000, 16.174999, - -64.498001, 15.000000, 17.688999, - -64.498001, 0.000000, 17.688999, - -62.557999, 15.000000, 18.524000, - -62.557999, 0.000000, 18.524000, - -73.719002, 23.200001, 14.372000, - -73.719002, 0.000000, 14.372000, - -78.292999, 23.200001, 7.871000, - -78.292999, 0.000000, 7.871000, - -96.703003, 23.200001, 22.743000, - -96.703003, 0.000000, 22.743000, - -91.981003, 23.200001, 28.921000, - -91.981003, 0.000000, 28.921000, - -91.365997, 23.200001, 28.497999, - -91.365997, 0.000000, 28.497999, - -16.691999, 15.000000, 23.099001, - -16.691999, 0.000000, 23.099001, - -25.865999, 15.000000, 18.646000, - -25.865999, 0.000000, 18.646000, - -28.936001, 15.000000, 25.580999, - -28.936001, 0.000000, 25.580999, - -19.975000, 15.000000, 30.334999, - -19.975000, 0.000000, 30.334999, - -1.639000, 20.000000, 2.271000, - -1.639000, 0.000000, 2.271000, - 22.434000, 20.000000, 12.501000, - 22.434000, 0.000000, 12.501000, - 26.280001, 20.000000, 4.119000, - 1.350000, 20.000000, -5.187000, - -66.872002, 7.500000, 27.863001, - -62.557999, 7.500000, 18.524000, - -64.498001, 7.500000, 17.688999, - -69.038002, 7.500000, 27.106001, - -14.692000, 15.000000, 32.939999, - -14.692000, 0.000000, 32.939999, - -11.329000, 15.000000, 25.604000, - -11.329000, 0.000000, 25.604000, - -2.856000, 20.000000, 1.748000, - -2.856000, 0.000000, 1.748000, - -7.738000, 20.000000, 14.026000, - -7.738000, 0.000000, 14.026000, - 16.597000, 20.000000, 25.225000, - 16.597000, 0.000000, 25.225000, - -50.441002, 15.000000, 34.786999, - -50.441002, 0.000000, 34.786999, - -44.750999, 15.000000, 37.103001, - -44.750999, 0.000000, 37.103001, - -41.286999, 15.000000, 28.409000, - -41.286999, 0.000000, 28.409000, - -29.558001, 15.000000, 26.983999, - -29.558001, 0.000000, 26.983999, - -48.816002, 15.000000, 30.413000, - -48.816002, 0.000000, 30.413000, - -15.187000, 15.000000, 34.141998, - -15.187000, 0.000000, 34.141998, - -2.328000, 15.000000, 39.652000, - -2.328000, 0.000000, 39.652000, - -7.203000, 15.000000, 50.316002, - -7.203000, 0.000000, 50.316002, - 2.701000, 15.000000, 54.636002, - 2.701000, 0.000000, 54.636002, - 8.111000, 15.000000, 43.070000, - 8.111000, 0.000000, 43.070000, - 8.552000, 15.000000, 43.280998, - 8.552000, 0.000000, 43.280998, - 8.759000, 15.000000, 42.835999, - 8.759000, 0.000000, 42.835999, - 8.318000, 15.000000, 42.624001, - 8.318000, 0.000000, 42.624001, - 9.334000, 15.000000, 40.442001, - 9.334000, 0.000000, 40.442001, - 9.783000, 15.000000, 40.653999, - 9.783000, 0.000000, 40.653999, - 10.010000, 15.000000, 40.209000, - 10.010000, 0.000000, 40.209000, - 9.548000, 15.000000, 39.986000, - 9.548000, 0.000000, 39.986000, - 14.363000, 15.000000, 29.656000, - 14.363000, 0.000000, 29.656000, - -8.373000, 15.000000, 19.146999, - -8.373000, 0.000000, 19.146999, - -8.527000, 15.000000, 19.481001, - -8.527000, 0.000000, 19.481001, - -55.249001, 15.000000, 47.744999, - -55.249001, 0.000000, 47.744999, - -54.561001, 15.000000, 28.231001, - -54.561001, 0.000000, 28.231001, - -60.030998, 15.000000, 42.580002, - -60.030998, 0.000000, 42.580002, - -61.160999, 15.000000, 45.841000, - -61.160999, 0.000000, 45.841000, - -62.751999, 15.000000, 24.691000, - -62.751999, 0.000000, 24.691000, - -63.259998, 15.000000, 24.568001, - -63.259998, 0.000000, 24.568001, - -78.252998, 15.000000, 20.761000, - -78.252998, 0.000000, 20.761000, - -72.442001, 15.000000, 16.264000, - -72.442001, 0.000000, 16.264000, - -73.719002, 15.000000, 14.372000, - -91.365997, 15.000000, 28.497999, - -85.569000, 15.000000, 35.265999, - -85.569000, 0.000000, 35.265999, - -82.351997, 15.000000, 38.126999, - -82.351997, 0.000000, 38.126999, - -24.101000, 15.000000, 44.827999, - -31.417000, 15.000000, 41.834000, - -31.417000, 0.000000, 41.834000, - -32.199001, 15.000000, 43.726002, - -32.199001, 0.000000, 43.726002, - -35.542999, 15.000000, 42.390999, - -35.542999, 0.000000, 42.390999, - -39.882000, 15.000000, 53.277000, - -39.882000, 0.000000, 53.277000, - -29.209999, 15.000000, 57.217999, - -34.933998, 15.000000, 41.043999, - -34.933998, 0.000000, 41.043999, - 6.332000, 15.000000, 132.835999, - 6.332000, 0.000000, 132.835999, - 6.599000, 15.000000, 128.472000, - 6.599000, 0.000000, 128.472000, - 1.557000, 15.000000, 126.691002, - 1.557000, 0.000000, 126.691002, - 13.694000, 15.000000, 95.878998, - 13.694000, 0.000000, 95.878998, - 8.271000, 15.000000, 92.338997, - 8.271000, 0.000000, 92.338997, - 2.179000, 15.000000, 88.487000, - 2.179000, 0.000000, 88.487000, - 0.655000, 15.000000, 88.253998, - 0.655000, 0.000000, 88.253998, - -0.348000, 15.000000, 88.598999, - -0.348000, 0.000000, 88.598999, - -1.158000, 15.000000, 89.544998, - -1.158000, 0.000000, 89.544998, - -8.353000, 15.000000, 109.214996, - -8.353000, 0.000000, 109.214996, - -9.744000, 15.000000, 112.297997, - -9.744000, 0.000000, 112.297997, - -10.827000, 15.000000, 116.606003, - -10.827000, 0.000000, 116.606003, - -11.482000, 15.000000, 116.516998, - -11.482000, 0.000000, 116.516998, - -14.465000, 15.000000, 126.803001, - -14.465000, 0.000000, 126.803001, - -12.753000, 15.000000, 130.153000, - -12.753000, 0.000000, 130.153000, - 11.742000, 7.500000, 165.173004, - 11.742000, 0.000000, 165.173004, - -9.222000, 7.500000, 143.399994, - -9.222000, 0.000000, 143.399994, - -16.049999, 7.500000, 143.544998, - 8.064000, 7.500000, 168.858002, - 16.583000, 7.500000, 177.462006, - 16.583000, 0.000000, 177.462006, - 18.436001, 7.500000, 172.419998, - 18.436001, 0.000000, 172.419998, - 11.642000, 15.000000, 194.104004, - 11.642000, 0.000000, 194.104004, - 14.831000, 15.000000, 185.210007, - 14.831000, 0.000000, 185.210007, - 13.628000, 15.000000, 184.820007, - 13.628000, 0.000000, 184.820007, - 16.583000, 15.000000, 177.462006, - 11.334000, 15.000000, 133.537003, - 11.334000, 0.000000, 133.537003, - 11.956000, 15.000000, 133.626007, - 11.956000, 0.000000, 133.626007, - 26.527000, 15.000000, 146.639008, - 26.527000, 0.000000, 146.639008, - 47.130001, 15.000000, 123.663002, - 47.130001, 0.000000, 123.663002, - 23.912001, 15.000000, 102.546997, - 23.912001, 0.000000, 102.546997, - 12.812000, 15.000000, 116.717003, - 12.812000, 0.000000, 116.717003, - 7.201000, 15.000000, 132.957993, - 7.201000, 0.000000, 132.957993, - 58.257000, 15.000000, 156.179001, - 58.257000, 0.000000, 156.179001, - 49.530998, 15.000000, 149.610992, - 49.530998, 0.000000, 149.610992, - 48.541000, 15.000000, 150.947006, - 48.541000, 0.000000, 150.947006, - 47.557999, 15.000000, 150.246002, - 47.557999, 0.000000, 150.246002, - 46.969002, 15.000000, 150.802002, - 46.969002, 0.000000, 150.802002, - 46.000000, 15.000000, 149.990005, - 46.000000, 0.000000, 149.990005, - 38.952000, 15.000000, 157.725998, - 38.952000, 0.000000, 157.725998, - 39.901001, 15.000000, 158.572006, - 39.901001, 0.000000, 158.572006, - 37.333000, 15.000000, 161.834000, - 37.333000, 0.000000, 161.834000, - 37.681000, 15.000000, 162.100998, - 37.681000, 0.000000, 162.100998, - 48.046001, 15.000000, 169.792999, - 48.046001, 0.000000, 169.792999, - 33.889000, 15.000000, 170.326996, - 33.889000, 0.000000, 170.326996, - 44.081001, 15.000000, 175.970993, - 44.081001, 0.000000, 175.970993, - 32.618999, 15.000000, 169.636993, - 32.618999, 0.000000, 169.636993, - 7.603000, 15.000000, 197.955994, - 7.603000, 0.000000, 197.955994, - 14.925000, 15.000000, 205.324997, - 14.925000, 0.000000, 205.324997, - 18.937000, 15.000000, 201.529007, - 18.937000, 0.000000, 201.529007, - 21.739000, 15.000000, 204.735001, - 21.739000, 0.000000, 204.735001, - 29.629999, 15.000000, 197.399002, - 29.629999, 0.000000, 197.399002, - 35.514000, 15.000000, 190.408005, - 35.514000, 0.000000, 190.408005, - 44.474998, 15.000000, 176.182007, - 44.474998, 0.000000, 176.182007, - 33.327999, 15.000000, 171.128998, - 33.327999, 0.000000, 171.128998, - 26.667000, 15.000000, 168.901993, - 26.667000, 0.000000, 168.901993, - 19.392000, 15.000000, 186.869003, - 19.392000, 0.000000, 186.869003, - 68.542000, 15.000000, 142.475998, - 68.542000, 0.000000, 142.475998, - 59.834999, 15.000000, 134.828995, - 59.834999, 0.000000, 134.828995, - 51.470001, 15.000000, 144.001007, - 51.470001, 0.000000, 144.001007, - 51.890999, 15.000000, 144.367996, - 51.890999, 0.000000, 144.367996, - 52.813999, 15.000000, 145.169998, - 52.813999, 0.000000, 145.169998, - 54.752998, 15.000000, 130.365005, - 54.752998, 0.000000, 130.365005, - 34.036999, 15.000000, 153.339996, - 34.036999, 0.000000, 153.339996, - 44.287998, 15.000000, 148.520004, - 44.287998, 0.000000, 148.520004, - 49.376999, 15.000000, 142.699005, - 49.376999, 0.000000, 142.699005, - 51.269001, 15.000000, 144.223999, - 51.269001, 0.000000, 144.223999, - -110.424004, 10.000000, 160.018997, - -110.424004, 0.000000, 160.018997, - -119.773003, 10.000000, 172.520004, - -119.773003, 0.000000, 172.520004, - -114.236000, 10.000000, 176.973007, - -114.236000, 0.000000, 176.973007, - -111.889000, 10.000000, 173.912003, - -111.889000, 0.000000, 173.912003, - -106.773003, 10.000000, 177.539993, - -106.773003, 0.000000, 177.539993, - -99.110001, 10.000000, 168.468002, - -99.110001, 0.000000, 168.468002, - -90.136002, 10.000000, 175.169006, - -90.136002, 0.000000, 175.169006, - -97.838997, 10.000000, 184.664993, - -97.838997, 0.000000, 184.664993, - -98.848999, 10.000000, 185.910995, - -98.848999, 0.000000, 185.910995, - -96.188004, 10.000000, 188.048996, - -96.188004, 0.000000, 188.048996, - -97.598999, 10.000000, 189.908005, - -97.598999, 0.000000, 189.908005, - -93.365997, 10.000000, 193.246994, - -93.365997, 0.000000, 193.246994, - -83.369003, 10.000000, 180.223007, - -83.369003, 0.000000, 180.223007, - -111.842003, 10.000000, 182.938995, - -111.842003, 0.000000, 182.938995, - -116.035004, 10.000000, 179.166000, - -116.035004, 0.000000, 179.166000, - -127.764000, 10.000000, 181.524994, - -127.764000, 0.000000, 181.524994, - -67.626999, 10.000000, 191.376999, - -67.626999, 0.000000, 191.376999, - -67.713997, 10.000000, 191.498993, - -67.713997, 0.000000, 191.498993, - -68.209000, 10.000000, 191.164993, - -68.209000, 0.000000, 191.164993, - -68.542999, 10.000000, 191.643997, - -68.542999, 0.000000, 191.643997, - -71.016998, 10.000000, 189.873993, - -71.016998, 0.000000, 189.873993, - -70.737000, 10.000000, 189.462006, - -70.737000, 0.000000, 189.462006, - -71.980003, 10.000000, 188.593994, - -71.980003, 0.000000, 188.593994, - -72.267998, 10.000000, 189.005997, - -72.267998, 0.000000, 189.005997, - -74.795998, 10.000000, 187.235992, - -74.795998, 0.000000, 187.235992, - -74.514999, 10.000000, 186.824005, - -74.514999, 0.000000, 186.824005, - -75.764999, 10.000000, 185.955994, - -75.764999, 0.000000, 185.955994, - -76.053001, 10.000000, 186.367996, - -76.053001, 0.000000, 186.367996, - -78.573997, 10.000000, 184.664993, - -78.573997, 0.000000, 184.664993, - -78.233002, 10.000000, 184.175003, - -78.233002, 0.000000, 184.175003, - -78.727997, 10.000000, 183.830002, - -78.727997, 0.000000, 183.830002, - -78.634003, 10.000000, 183.695999, - -78.634003, 0.000000, 183.695999, - -83.382004, 10.000000, 180.279007, - -83.382004, 0.000000, 180.279007, - -83.455002, 10.000000, 180.378998, - -83.455002, 0.000000, 180.378998, - -92.871002, 10.000000, 192.690002, - -92.871002, 0.000000, 192.690002, - -93.057999, 10.000000, 192.934998, - -93.057999, 0.000000, 192.934998, - -95.332001, 10.000000, 195.906998, - -95.332001, 0.000000, 195.906998, - -95.151001, 10.000000, 196.052002, - -95.151001, 0.000000, 196.052002, - -99.110001, 10.000000, 201.216995, - -99.110001, 0.000000, 201.216995, - -99.530998, 10.000000, 201.639999, - -99.530998, 0.000000, 201.639999, - -107.127998, 10.000000, 209.210007, - -107.127998, 0.000000, 209.210007, - -107.355003, 10.000000, 209.432007, - -107.355003, 0.000000, 209.432007, - -101.931999, 10.000000, 216.199997, - -101.931999, 0.000000, 216.199997, - -101.551003, 10.000000, 215.865997, - -101.551003, 0.000000, 215.865997, - -99.652000, 10.000000, 218.237000, - -99.652000, 0.000000, 218.237000, - -100.039001, 10.000000, 218.570999, - -100.039001, 0.000000, 218.570999, - -98.749001, 10.000000, 220.162994, - -98.749001, 0.000000, 220.162994, - -98.367996, 10.000000, 219.839996, - -98.367996, 0.000000, 219.839996, - -96.461998, 10.000000, 222.210999, - -96.461998, 0.000000, 222.210999, - -96.862999, 10.000000, 222.533997, - -96.862999, 0.000000, 222.533997, - -94.682999, 10.000000, 225.250000, - -94.682999, 0.000000, 225.250000, - -94.000999, 10.000000, 224.692993, - -94.000999, 0.000000, 224.692993, - -91.848000, 10.000000, 227.354004, - -91.848000, 0.000000, 227.354004, - -92.416000, 10.000000, 227.843994, - -92.416000, 0.000000, 227.843994, - -91.152000, 10.000000, 229.423996, - -91.152000, 0.000000, 229.423996, - -90.570999, 10.000000, 228.945999, - -90.570999, 0.000000, 228.945999, - -88.436996, 10.000000, 231.628006, - -88.436996, 0.000000, 231.628006, - -89.133003, 10.000000, 232.184998, - -89.133003, 0.000000, 232.184998, - -87.627998, 10.000000, 234.033005, - -87.627998, 0.000000, 234.033005, - -86.873001, 10.000000, 233.442993, - -86.873001, 0.000000, 233.442993, - -85.668999, 10.000000, 234.945007, - -85.668999, 0.000000, 234.945007, - -77.403999, 10.000000, 225.962006, - -77.403999, 0.000000, 225.962006, - -80.171997, 10.000000, 222.612000, - -80.171997, 0.000000, 222.612000, - -78.306000, 10.000000, 219.962997, - -78.306000, 0.000000, 219.962997, - -78.198997, 10.000000, 219.796005, - -78.198997, 0.000000, 219.796005, - -78.112000, 10.000000, 219.617004, - -78.112000, 0.000000, 219.617004, - -78.045998, 10.000000, 219.417007, - -78.045998, 0.000000, 219.417007, - -78.012001, 10.000000, 219.216995, - -78.012001, 0.000000, 219.216995, - -77.985001, 10.000000, 218.893997, - -77.985001, 0.000000, 218.893997, - -73.919998, 10.000000, 221.798996, - -73.919998, 0.000000, 221.798996, - -73.485001, 10.000000, 221.253998, - -73.485001, 0.000000, 221.253998, - -71.680000, 10.000000, 219.016006, - -71.680000, 0.000000, 219.016006, - -71.572998, 10.000000, 219.104996, - -71.572998, 0.000000, 219.104996, - -69.386002, 10.000000, 216.746002, - -69.386002, 0.000000, 216.746002, - -74.007004, 10.000000, 213.617996, - -74.007004, 0.000000, 213.617996, - -74.053001, 10.000000, 213.584000, - -74.053001, 0.000000, 213.584000, - -75.217003, 10.000000, 212.804993, - -75.217003, 0.000000, 212.804993, - -74.046997, 10.000000, 211.067993, - -74.046997, 0.000000, 211.067993, - -73.987000, 10.000000, 211.113007, - -73.987000, 0.000000, 211.113007, - -72.415001, 10.000000, 208.820007, - -72.415001, 0.000000, 208.820007, - -62.826000, 10.000000, 194.794006, - -62.826000, 0.000000, 194.794006, - -62.778999, 10.000000, 194.716003, - -62.778999, 0.000000, 194.716003, - -64.290001, 10.000000, 193.669998, - -64.290001, 0.000000, 193.669998, - 85.139000, 15.000000, 179.565994, - 85.139000, 0.000000, 179.565994, - 95.705002, 15.000000, 167.210007, - 95.705002, 0.000000, 167.210007, - 83.018997, 15.000000, 154.710007, - 83.018997, 0.000000, 154.710007, - 61.186001, 15.000000, 183.785004, - 61.186001, 0.000000, 183.785004, - 72.507004, 15.000000, 191.988998, - 72.507004, 0.000000, 191.988998, - 76.232002, 15.000000, 186.279007, - 76.232002, 0.000000, 186.279007, - 76.834000, 15.000000, 186.723999, - 76.834000, 0.000000, 186.723999, - 79.943001, 15.000000, 182.171005, - 79.943001, 0.000000, 182.171005, - 78.827003, 15.000000, 181.335999, - 78.827003, 0.000000, 181.335999, - 82.283997, 15.000000, 176.628006, - 82.283997, 0.000000, 176.628006, - 99.677002, 7.300000, 171.440002, - 99.677002, 0.000000, 171.440002, - 88.167999, 7.300000, 187.358002, - 88.167999, 0.000000, 187.358002, - 92.962997, 7.300000, 192.089005, - 92.962997, 0.000000, 192.089005, - 103.943001, 7.300000, 175.981995, - 103.943001, 0.000000, 175.981995, - 103.943001, 15.000000, 175.981995, - 92.962997, 15.000000, 192.089005, - 99.456001, 15.000000, 198.667999, - 99.456001, 0.000000, 198.667999, - 101.549004, 15.000000, 195.873993, - 101.549004, 0.000000, 195.873993, - 110.704002, 15.000000, 183.195007, - 110.704002, 0.000000, 183.195007, - 56.532001, 7.500000, 189.205994, - 56.532001, 0.000000, 189.205994, - 72.600998, 7.500000, 199.492004, - 72.600998, 0.000000, 199.492004, - 75.430000, 7.500000, 194.070999, - 75.430000, 0.000000, 194.070999, - 72.507004, 7.500000, 191.988998, - 61.186001, 7.500000, 183.785004, - 60.598000, 7.500000, 183.350998, - 60.598000, 0.000000, 183.350998, - 84.142998, 15.000000, 219.093994, - 84.142998, 0.000000, 219.093994, - 83.547997, 15.000000, 219.873001, - 83.547997, 0.000000, 219.873001, - 112.135002, 15.000000, 232.608002, - 112.135002, 0.000000, 232.608002, - 114.695999, 15.000000, 234.289001, - 114.695999, 0.000000, 234.289001, - 135.968002, 15.000000, 208.585999, - 135.968002, 0.000000, 208.585999, - 139.009995, 5.000000, 78.278999, - 139.009995, 0.000000, 78.278999, - 149.115005, 5.000000, 87.330002, - 149.115005, 0.000000, 87.330002, - 148.973999, 5.000000, 92.361000, - 148.973999, 0.000000, 92.361000, - 139.345001, 5.000000, 103.893997, - 139.345001, 0.000000, 103.893997, - 181.024994, 5.000000, 138.289993, - 181.024994, 0.000000, 138.289993, - 186.703003, 5.000000, 142.988007, - 186.703003, 0.000000, 142.988007, - 188.962997, 5.000000, 144.847000, - 188.962997, 0.000000, 144.847000, - 201.326996, 5.000000, 130.408997, - 201.326996, 0.000000, 130.408997, - 209.987000, 5.000000, 120.212997, - 209.987000, 0.000000, 120.212997, - 197.542007, 5.000000, 109.638000, - 197.542007, 0.000000, 109.638000, - 219.723007, 5.000000, 83.300003, - 219.723007, 0.000000, 83.300003, - 231.485992, 5.000000, 45.185001, - 231.485992, 0.000000, 45.185001, - 185.459000, 5.000000, 30.000999, - 185.459000, 0.000000, 30.000999, - 162.957001, 5.000000, 50.472000, - 162.957001, 0.000000, 50.472000, - 143.738007, 5.000000, 67.959999, - 143.738007, 0.000000, 67.959999, - 179.259995, 25.700001, 125.945000, - 179.259995, 0.000000, 125.945000, - 174.639008, 25.700001, 131.143997, - 174.639008, 0.000000, 131.143997, - 177.916000, 25.700001, 134.059998, - 177.916000, 0.000000, 134.059998, - 182.537003, 25.700001, 128.873001, - 182.537003, 0.000000, 128.873001, - 149.455994, 25.700001, 65.634003, - 149.455994, 0.000000, 65.634003, - 151.602005, 25.700001, 67.971001, - 151.602005, 0.000000, 67.971001, - 157.514008, 25.700001, 62.584000, - 157.514008, 0.000000, 62.584000, - 160.563004, 25.700001, 65.922997, - 160.563004, 0.000000, 65.922997, - 170.386002, 25.700001, 56.962002, - 170.386002, 0.000000, 56.962002, - 167.110001, 25.700001, 53.377998, - 167.110001, 0.000000, 53.377998, - 158.610001, 25.700001, 61.125000, - 158.610001, 0.000000, 61.125000, - 156.690994, 25.700001, 59.033001, - 156.690994, 0.000000, 59.033001, - 149.783005, 25.700001, 109.503998, - 149.783005, 0.000000, 109.503998, - 157.487000, 25.700001, 116.027000, - 157.487000, 0.000000, 116.027000, - 159.699997, 25.700001, 113.411003, - 159.699997, 0.000000, 113.411003, - 152.003006, 25.700001, 106.888000, - 152.003006, 0.000000, 106.888000, - 134.770996, 25.700001, 91.047997, - 134.770996, 0.000000, 91.047997, - 134.436005, 25.700001, 92.750999, - 134.436005, 0.000000, 92.750999, - 135.057999, 25.700001, 92.940002, - 135.057999, 0.000000, 92.940002, - 135.393005, 25.700001, 95.010002, - 135.393005, 0.000000, 95.010002, - 138.669006, 25.700001, 96.580002, - 138.669006, 0.000000, 96.580002, - 142.988998, 25.700001, 92.584000, - 142.988998, 0.000000, 92.584000, - 142.761993, 25.700001, 90.179001, - 142.761993, 0.000000, 90.179001, - 143.190002, 25.700001, 89.901001, - 143.190002, 0.000000, 89.901001, - 142.794998, 25.700001, 86.706001, - 142.794998, 0.000000, 86.706001, - 139.632004, 25.700001, 85.526001, - 139.632004, 0.000000, 85.526001, - 137.339005, 25.700001, 87.061996, - 137.339005, 0.000000, 87.061996, - 137.445999, 25.700001, 87.462997, - 137.445999, 0.000000, 87.462997, - 135.787003, 25.700001, 88.844002, - 135.787003, 0.000000, 88.844002, - 134.436005, 25.700001, 88.276001, - 134.436005, 0.000000, 88.276001, - 132.095993, 25.700001, 87.274002, - 132.095993, 0.000000, 87.274002, - 131.145996, 25.700001, 89.511002, - 131.145996, 0.000000, 89.511002, - 133.447006, 25.700001, 90.490997, - 133.447006, 0.000000, 90.490997, - 219.423004, 31.700001, 109.102997, - 219.423004, 5.000000, 109.102997, - 194.766998, 31.700001, 88.164001, - 194.766998, 5.000000, 88.164001, - 176.671997, 31.700001, 109.459000, - 176.671997, 5.000000, 109.459000, - 201.326996, 31.700001, 130.408997, - 209.987000, 31.700001, 120.212997, - 203.688004, 7.500000, 157.003006, - 203.688004, 0.000000, 157.003006, - 206.791000, 7.500000, 152.951004, - 206.791000, 0.000000, 152.951004, - 210.983002, 7.500000, 147.462997, - 210.983002, 0.000000, 147.462997, - 216.820999, 7.500000, 139.837997, - 216.820999, 0.000000, 139.837997, - 217.350006, 7.500000, 139.147995, - 217.350006, 0.000000, 139.147995, - 230.529999, 7.500000, 121.916000, - 230.529999, 0.000000, 121.916000, - 232.602997, 7.500000, 119.154999, - 232.602997, 0.000000, 119.154999, - 223.789001, 7.500000, 111.418999, - 223.789001, 0.000000, 111.418999, - 234.589005, 7.500000, 99.107002, - 234.589005, 0.000000, 99.107002, - 239.289993, 7.500000, 93.752998, - 239.289993, 0.000000, 93.752998, - 249.274002, 7.500000, 85.927002, - 249.274002, 0.000000, 85.927002, - 245.863007, 7.500000, 81.573997, - 245.863007, 0.000000, 81.573997, - 238.360001, 7.500000, 78.668999, - 238.360001, 0.000000, 78.668999, - 240.927994, 7.500000, 71.845001, - 240.927994, 0.000000, 71.845001, - 248.089996, 7.500000, 52.787998, - 248.089996, 0.000000, 52.787998, - 248.819000, 7.500000, 50.905998, - 248.819000, 0.000000, 50.905998, - 239.511002, 7.500000, 47.834000, - 239.511002, 0.000000, 47.834000, - 231.485992, 7.500000, 45.185001, - 219.723007, 7.500000, 83.300003, - 206.928619, 7.500000, 98.492203, - 206.928619, 0.000000, 98.492203, - 219.423004, 7.500000, 109.102997, - 219.423004, 0.000000, 109.102997, - 209.987000, 7.500000, 120.212997, - 201.326996, 7.500000, 130.408997, - 188.962997, 7.500000, 144.847000, - 197.007004, 7.500000, 151.492996, - 197.007004, 0.000000, 151.492996, - 198.966995, 7.500000, 153.106995, - 198.966995, 0.000000, 153.106995, - 139.345001, 7.500000, 103.893997, - 148.973999, 7.500000, 92.361000, - 149.115005, 7.500000, 87.330002, - 139.009995, 7.500000, 78.278999, - 135.332001, 7.500000, 86.317001, - 135.332001, 0.000000, 86.317001, - 134.436005, 7.500000, 88.276001, - 135.787003, 7.500000, 88.844002, - 137.445999, 7.500000, 87.462997, - 137.339005, 7.500000, 87.061996, - 139.632004, 7.500000, 85.526001, - 142.794998, 7.500000, 86.706001, - 143.190002, 7.500000, 89.901001, - 142.761993, 7.500000, 90.179001, - 142.988998, 7.500000, 92.584000, - 138.669006, 7.500000, 96.580002, - 135.393005, 7.500000, 95.010002, - 135.057999, 7.500000, 92.940002, - 134.436005, 7.500000, 92.750999, - 134.770996, 7.500000, 91.047997, - 133.447006, 7.500000, 90.490997, - 130.658005, 7.500000, 96.747002, - 130.658005, 0.000000, 96.747002, - 133.514008, 7.500000, 99.096001, - 133.514008, 0.000000, 99.096001, - 135.298996, 7.500000, 100.554001, - 135.298996, 0.000000, 100.554001, - 114.421997, 21.299999, 118.820999, - 114.421997, 0.000000, 118.820999, - 120.058998, 21.299999, 124.231003, - 120.058998, 0.000000, 124.231003, - 121.616997, 21.299999, 125.790001, - 121.616997, 0.000000, 125.790001, - 124.378998, 21.299999, 128.572998, - 124.378998, 0.000000, 128.572998, - 125.275002, 21.299999, 127.625999, - 125.275002, 0.000000, 127.625999, - 132.089005, 21.299999, 120.490997, - 132.089005, 0.000000, 120.490997, - 127.615997, 21.299999, 116.349998, - 127.615997, 0.000000, 116.349998, - 126.332001, 21.299999, 115.158997, - 126.332001, 0.000000, 115.158997, - 124.686996, 21.299999, 113.634003, - 124.686996, 0.000000, 113.634003, - 121.917999, 21.299999, 111.061996, - 121.917999, 0.000000, 111.061996, - 156.423996, 20.000000, 174.044998, - 156.423996, 0.000000, 174.044998, - 134.229004, 20.000000, 156.914001, - 134.229004, 0.000000, 156.914001, - 121.042000, 20.000000, 172.419998, - 121.042000, 0.000000, 172.419998, - 136.294998, 20.000000, 187.970993, - 136.294998, 0.000000, 187.970993, - 141.979004, 20.000000, 193.770004, - 141.979004, 0.000000, 193.770004, - 125.275002, 20.000000, 127.625999, - 133.968002, 20.000000, 135.774994, - 133.968002, 0.000000, 135.774994, - 135.893997, 20.000000, 137.578003, - 135.893997, 0.000000, 137.578003, - 144.205994, 20.000000, 145.192001, - 144.205994, 0.000000, 145.192001, - 150.753006, 20.000000, 137.556000, - 150.753006, 0.000000, 137.556000, - 142.654999, 20.000000, 130.153000, - 142.654999, 0.000000, 130.153000, - 132.089005, 20.000000, 120.490997, - 161.526001, 20.000000, 167.076996, - 161.526001, 0.000000, 167.076996, - 171.362000, 20.000000, 153.507004, - 171.362000, 0.000000, 153.507004, - 164.962997, 20.000000, 148.554001, - 164.962997, 0.000000, 148.554001, - 141.992996, 20.000000, 147.796997, - 141.992996, 0.000000, 147.796997, - 136.195007, 20.000000, 154.598007, - 136.195007, 0.000000, 154.598007, - 147.910995, 20.000000, 198.824005, - 147.910995, 0.000000, 198.824005, - 153.233994, 20.000000, 203.509995, - 153.233994, 0.000000, 203.509995, - 164.408005, 20.000000, 187.136002, - 164.408005, 0.000000, 187.136002, - 164.802002, 20.000000, 186.567993, - 164.802002, 0.000000, 186.567993, - 180.591003, 20.000000, 160.843002, - 180.591003, 0.000000, 160.843002, - 175.388000, 20.000000, 156.712997, - 175.388000, 0.000000, 156.712997, - 166.695007, 20.000000, 170.561005, - 166.695007, 0.000000, 170.561005, - 158.970993, 20.000000, 182.895004, - 158.970993, 0.000000, 182.895004, - 173.207993, 20.000000, 154.977005, - 173.207993, 0.000000, 154.977005, - 115.852997, 7.500000, 141.328995, - 115.852997, 0.000000, 141.328995, - 119.150002, 7.500000, 138.167999, - 119.150002, 0.000000, 138.167999, - 118.126999, 7.500000, 137.009995, - 118.126999, 0.000000, 137.009995, - 122.907997, 7.500000, 132.412994, - 122.907997, 0.000000, 132.412994, - 122.166000, 7.500000, 131.432999, - 122.166000, 0.000000, 131.432999, - 124.378998, 7.500000, 128.572998, - 121.616997, 7.500000, 125.790001, - 120.058998, 7.500000, 124.231003, - 116.555000, 7.500000, 128.317001, - 116.555000, 0.000000, 128.317001, - 117.344002, 7.500000, 129.018005, - 117.344002, 0.000000, 129.018005, - 113.887001, 7.500000, 131.712006, - 113.887001, 0.000000, 131.712006, - 108.102997, 7.500000, 136.542999, - 108.102997, 0.000000, 136.542999, - 98.513000, 7.500000, 146.037994, - 98.513000, 0.000000, 146.037994, - 98.774002, 7.500000, 146.261002, - 98.774002, 0.000000, 146.261002, - 97.824997, 7.500000, 147.541000, - 97.824997, 0.000000, 147.541000, - 103.334999, 7.500000, 153.496002, - 103.334999, 0.000000, 153.496002, - 111.459999, 21.299999, 129.317993, - 111.459999, 0.000000, 129.317993, - 107.781998, 21.299999, 125.689003, - 107.781998, 0.000000, 125.689003, - 91.967003, 21.299999, 141.819000, - 91.967003, 0.000000, 141.819000, - 97.824997, 21.299999, 147.541000, - 98.774002, 21.299999, 146.261002, - 98.513000, 21.299999, 146.037994, - 108.102997, 21.299999, 136.542999, - 113.887001, 21.299999, 131.712006, - 175.007004, 10.000000, -8.582000, - 175.007004, 0.000000, -8.582000, - 172.371994, 10.000000, -10.542000, - 172.371994, 0.000000, -10.542000, - 174.438995, 10.000000, -13.325000, - 174.438995, 0.000000, -13.325000, - 176.906006, 10.000000, -11.488000, - 176.906006, 0.000000, -11.488000, - 183.145004, 10.000000, -21.073000, - 183.145004, 0.000000, -21.073000, - 179.179993, 10.000000, -22.097000, - 179.179993, 0.000000, -22.097000, - 177.274002, 10.000000, -22.587000, - 177.274002, 0.000000, -22.587000, - 164.990005, 10.000000, -3.863000, - 164.990005, 0.000000, -3.863000, - 167.016006, 10.000000, -2.159000, - 167.016006, 0.000000, -2.159000, - 169.477005, 10.000000, -0.089000, - 169.477005, 0.000000, -0.089000, - 174.171005, 10.000000, -23.377001, - 174.171005, 0.000000, -23.377001, - 169.537003, 10.000000, -16.464001, - 169.537003, 0.000000, -16.464001, - 167.817993, 10.000000, -13.503000, - 167.817993, 0.000000, -13.503000, - 162.268005, 10.000000, -6.156000, - 162.268005, 0.000000, -6.156000, - 171.589996, 10.000000, 1.681000, - 171.589996, 0.000000, 1.681000, - 173.917007, 10.000000, 3.652000, - 173.917007, 0.000000, 3.652000, - 187.686005, 10.000000, -19.903999, - 187.686005, 0.000000, -19.903999, - 184.817001, 10.000000, -20.650000, - 184.817001, 0.000000, -20.650000, - 178.884995, 10.000000, -10.019000, - 178.884995, 0.000000, -10.019000, - 176.819000, 10.000000, -7.236000, - 176.819000, 0.000000, -7.236000, - 176.524994, 10.000000, 5.833000, - 176.524994, 0.000000, 5.833000, - 179.199997, 10.000000, 8.093000, - 179.199997, 0.000000, 8.093000, - 184.242004, 10.000000, -2.115000, - 184.242004, 0.000000, -2.115000, - 181.813995, 10.000000, -3.740000, - 181.813995, 0.000000, -3.740000, - 185.091003, 10.000000, -9.006000, - 185.091003, 0.000000, -9.006000, - 187.057007, 10.000000, -7.826000, - 187.057007, 0.000000, -7.826000, - 192.427002, 10.000000, -18.690001, - 192.427002, 0.000000, -18.690001, - 189.431000, 10.000000, -19.458000, - 189.431000, 0.000000, -19.458000, - 158.776993, 10.000000, -62.071999, - 158.776993, 0.000000, -62.071999, - 152.684998, 10.000000, -42.445999, - 152.684998, 0.000000, -42.445999, - 159.132004, 10.000000, -46.242001, - 159.132004, 0.000000, -46.242001, - 164.100006, 10.000000, -45.084000, - 164.100006, 0.000000, -45.084000, - 155.548004, 10.000000, -36.958000, - 155.548004, 0.000000, -36.958000, - 164.554993, 10.000000, -34.442001, - 164.554993, 0.000000, -34.442001, - 172.065002, 10.000000, -42.825001, - 172.065002, 0.000000, -42.825001, - 191.584000, 10.000000, -37.192001, - 191.584000, 0.000000, -37.192001, - 183.371994, 10.000000, -29.021000, - 183.371994, 0.000000, -29.021000, - 188.654999, 10.000000, -27.596001, - 188.654999, 0.000000, -27.596001, - 192.253006, 10.000000, -26.627001, - 192.253006, 0.000000, -26.627001, - 199.796005, 10.000000, -34.609001, - 199.796005, 0.000000, -34.609001, - 206.710007, 10.000000, -32.672001, - 206.710007, 0.000000, -32.672001, - 215.470001, 10.000000, -19.903999, - 215.470001, 0.000000, -19.903999, - 218.587006, 10.000000, -18.846001, - 218.587006, 0.000000, -18.846001, - 220.854004, 10.000000, -25.903999, - 220.854004, 0.000000, -25.903999, - 226.182999, 10.000000, -41.789001, - 226.182999, 0.000000, -41.789001, - 215.470001, 4.000000, -19.903999, - 206.710007, 4.000000, -32.672001, - 199.796005, 4.000000, -34.609001, - 192.253006, 4.000000, -26.627001, - 183.371994, 4.000000, -29.021000, - 191.584000, 4.000000, -37.192001, - 172.065002, 4.000000, -42.825001, - 164.554993, 4.000000, -34.442001, - 155.548004, 4.000000, -36.958000, - 164.100006, 4.000000, -45.084000, - 159.132004, 4.000000, -46.242001, - 152.684998, 4.000000, -42.445999, - 151.522003, 4.000000, -38.227001, - 151.522003, 0.000000, -38.227001, - 153.701996, 4.000000, -37.536999, - 153.701996, 0.000000, -37.536999, - 187.117004, 10.000000, 4.019000, - 187.117004, 0.000000, 4.019000, - 185.766006, 10.000000, 3.329000, - 185.766006, 0.000000, 3.329000, - 187.759003, 10.000000, -0.567000, - 187.759003, 0.000000, -0.567000, - 189.076996, 10.000000, 0.112000, - 189.076996, 0.000000, 0.112000, - 190.681000, 10.000000, -3.306000, - 190.681000, 0.000000, -3.306000, - 189.684998, 10.000000, -3.751000, - 189.684998, 0.000000, -3.751000, - 191.404007, 10.000000, -7.569000, - 191.404007, 0.000000, -7.569000, - 192.487000, 10.000000, -7.080000, - 192.487000, 0.000000, -7.080000, - 197.481995, 10.000000, -17.388000, - 197.481995, 0.000000, -17.388000, - 195.035004, 10.000000, -18.011000, - 195.035004, 0.000000, -18.011000, - 181.828003, 10.000000, 9.874000, - 181.828003, 0.000000, 9.874000, - 183.660004, 10.000000, 11.121000, - 183.660004, 0.000000, 11.121000, - 188.587997, 10.000000, 1.069000, - 188.587997, 0.000000, 1.069000, - 189.557999, 10.000000, 1.559000, - 189.557999, 0.000000, 1.559000, - 188.052994, 10.000000, 4.498000, - 188.052994, 0.000000, 4.498000, - 187.270996, 10.000000, 13.570000, - 187.270996, 0.000000, 13.570000, - 188.173996, 10.000000, 11.733000, - 188.173996, 0.000000, 11.733000, - 191.464005, 10.000000, 12.980000, - 191.464005, 0.000000, 12.980000, - 196.707001, 10.000000, 14.962000, - 196.707001, 0.000000, 14.962000, - 208.227997, 10.000000, -13.592000, - 208.227997, 0.000000, -13.592000, - 203.440002, 10.000000, -15.284000, - 203.440002, 0.000000, -15.284000, - 193.757996, 10.000000, -6.512000, - 193.757996, 0.000000, -6.512000, - 192.500000, 10.000000, -3.718000, - 192.500000, 0.000000, -3.718000, - 191.143005, 10.000000, -4.330000, - 191.143005, 0.000000, -4.330000, - 84.931999, 23.600000, -60.869999, - 84.931999, 0.000000, -60.869999, - 89.839996, 23.600000, -81.052002, - 89.839996, 0.000000, -81.052002, - 74.834000, 23.600000, -83.579002, - 74.834000, 0.000000, -83.579002, - 70.380997, 23.600000, -64.431999, - 70.380997, 0.000000, -64.431999, - 144.580994, 10.000000, -50.627998, - 144.580994, 0.000000, -50.627998, - 148.966995, 10.000000, -65.055000, - 148.966995, 0.000000, -65.055000, - 135.653000, 10.000000, -69.107002, - 135.653000, 0.000000, -69.107002, - 131.574005, 10.000000, -54.390999, - 131.574005, 0.000000, -54.390999, - 142.541000, 10.000000, -51.217999, - 142.541000, 0.000000, -51.217999, - 122.373001, 23.600000, -73.137001, - 122.373001, 0.000000, -73.137001, - 117.323997, 23.600000, -52.387001, - 117.323997, 0.000000, -52.387001, - 129.701996, 23.600000, -47.344002, - 129.701996, 0.000000, -47.344002, - 131.574005, 23.600000, -54.390999, - 135.653000, 23.600000, -69.107002, - 84.792000, 23.600000, -60.313000, - 84.792000, 0.000000, -60.313000, - 157.473007, 10.000000, -27.930000, - 157.473007, 0.000000, -27.930000, - 149.776993, 10.000000, -30.134001, - 149.776993, 0.000000, -30.134001, - 146.947998, 10.000000, -30.947001, - 146.947998, 0.000000, -30.947001, - 145.302994, 10.000000, -28.141001, - 145.302994, 0.000000, -28.141001, - 141.865997, 10.000000, -24.312000, - 141.865997, 0.000000, -24.312000, - 141.505005, 10.000000, -41.321999, - 141.505005, 0.000000, -41.321999, - 143.798004, 10.000000, -40.609001, - 143.798004, 0.000000, -40.609001, - 151.522003, 10.000000, -38.227001, - 156.998993, 10.000000, -62.605999, - 156.998993, 0.000000, -62.605999, - -76.514000, 7.500000, -137.537003, - -76.514000, 0.000000, -137.537003, - -86.498001, 7.500000, -143.248001, - -86.498001, 0.000000, -143.248001, - -94.502998, 7.500000, -130.656998, - -94.502998, 0.000000, -130.656998, - -87.040001, 7.500000, -125.759003, - -87.040001, 0.000000, -125.759003, - -89.902000, 7.500000, -120.816002, - -89.902000, 0.000000, -120.816002, - -84.685997, 7.500000, -116.998001, - -84.685997, 0.000000, -116.998001, - -70.917000, 7.500000, -110.362999, - -70.917000, 0.000000, -110.362999, - -70.014000, 7.500000, -109.929001, - -70.014000, 0.000000, -109.929001, - -64.851997, 7.500000, -121.750999, - -64.851997, 0.000000, -121.750999, - -79.268997, 7.500000, -127.561996, - -79.268997, 0.000000, -127.561996, - -78.921997, 7.500000, -128.285995, - -78.921997, 0.000000, -128.285995, - -81.369003, 7.500000, -129.856003, - -81.369003, 0.000000, -129.856003, - -111.099998, 7.500000, -167.884003, - -111.099998, 0.000000, -167.884003, - -124.320000, 7.500000, -178.826996, - -124.320000, 0.000000, -178.826996, - -135.279999, 7.500000, -164.899994, - -135.279999, 0.000000, -164.899994, - -121.196999, 7.500000, -154.001999, - -121.196999, 0.000000, -154.001999, - -75.277000, 7.500000, -165.656998, - -75.277000, 0.000000, -165.656998, - -99.657997, 7.500000, -179.406006, - -99.657997, 0.000000, -179.406006, - -108.491997, 7.500000, -165.957993, - -108.491997, 0.000000, -165.957993, - -82.620003, 7.500000, -151.718994, - -82.620003, 0.000000, -151.718994, - -51.898998, 7.500000, -152.488007, - -51.898998, 0.000000, -152.488007, - -58.411999, 7.500000, -141.087997, - -58.411999, 0.000000, -141.087997, - -48.862999, 7.500000, -135.733994, - -48.862999, 0.000000, -135.733994, - -40.931999, 7.500000, -130.869003, - -34.405998, 7.500000, -142.623993, - -115.634003, 7.500000, -189.826004, - -115.634003, 0.000000, -189.826004, - -91.721001, 7.500000, -116.775002, - -91.721001, 0.000000, -116.775002, - -92.836998, 7.500000, -112.623001, - -92.836998, 0.000000, -112.623001, - -82.264999, 7.500000, -151.552994, - -82.264999, 0.000000, -151.552994, - -86.939003, 7.500000, -143.537003, - -86.939003, 0.000000, -143.537003, - -70.703003, 7.500000, -147.434006, - -70.703003, 0.000000, -147.434006, - -115.580002, 7.500000, -113.580002, - -115.580002, 0.000000, -113.580002, - -115.527000, 7.500000, -110.852997, - -115.527000, 0.000000, -110.852997, - -115.259003, 7.500000, -96.625999, - -115.259003, 0.000000, -96.625999, - -105.830002, 7.500000, -96.804001, - -105.830002, 0.000000, -96.804001, - -106.105003, 7.500000, -111.053001, - -106.105003, 0.000000, -111.053001, - -106.151001, 7.500000, -113.758003, - -106.151001, 0.000000, -113.758003, - -123.711998, 7.500000, -110.685997, - -123.711998, 0.000000, -110.685997, - -123.444000, 7.500000, -96.470001, - -123.444000, 0.000000, -96.470001, - -123.764999, 7.500000, -113.425003, - -123.764999, 0.000000, -113.425003, - -137.520996, 7.500000, -110.407997, - -137.520996, 0.000000, -110.407997, - -148.889008, 7.500000, -104.819000, - -148.889008, 0.000000, -104.819000, - -145.839005, 7.500000, -96.213997, - -145.839005, 0.000000, -96.213997, - -135.548004, 7.500000, -113.525002, - -135.548004, 0.000000, -113.525002, - -134.692001, 7.500000, -111.865997, - -134.692001, 0.000000, -111.865997, - -144.248001, 7.500000, -130.311996, - -144.248001, 0.000000, -130.311996, - -146.667999, 7.500000, -128.431000, - -146.667999, 0.000000, -128.431000, - -151.582993, 7.500000, -125.191002, - -151.582993, 0.000000, -125.191002, - -158.423996, 7.500000, -120.682999, - -158.423996, 0.000000, -120.682999, - -156.591995, 7.500000, -117.109001, - -156.591995, 0.000000, -117.109001, - -155.561996, 7.500000, -117.487999, - -155.561996, 0.000000, -117.487999, - -129.182007, 7.500000, -149.348007, - -129.182007, 0.000000, -149.348007, - -139.380005, 7.500000, -158.744003, - -139.380005, 0.000000, -158.744003, - -150.580002, 7.500000, -146.598999, - -150.580002, 0.000000, -146.598999, - -140.522995, 7.500000, -137.337006, - -140.522995, 0.000000, -137.337006, - -138.156006, 7.500000, -135.154999, - -138.156006, 0.000000, -135.154999, - -126.961998, 7.500000, -147.300003, - -126.961998, 0.000000, -147.300003, - -159.781998, 7.500000, -136.735001, - -159.781998, 0.000000, -136.735001, - -163.065002, 7.500000, -134.320007, - -163.065002, 0.000000, -134.320007, - -162.503006, 7.500000, -133.440002, - -162.503006, 0.000000, -133.440002, - -160.309998, 7.500000, -130.011993, - -160.309998, 0.000000, -130.011993, - -163.378998, 7.500000, -127.417999, - -163.378998, 0.000000, -127.417999, - -180.345001, 5.000000, -152.910995, - -170.567993, 5.000000, -141.744995, - -170.567993, 0.000000, -141.744995, - -160.363998, 5.000000, -150.039001, - -160.363998, 0.000000, -150.039001, - -154.332001, 5.000000, -156.216995, - -154.332001, 0.000000, -156.216995, - -176.138000, 5.000000, -186.352005, - -176.138000, 0.000000, -186.352005, - -181.514999, 5.000000, -190.983002, - -181.514999, 0.000000, -190.983002, - -189.613007, 5.000000, -180.485001, - -189.613007, 0.000000, -180.485001, - -197.209000, 5.000000, -187.955002, - -197.209000, 0.000000, -187.955002, - -206.317001, 5.000000, -177.257004, - -206.317001, 0.000000, -177.257004, - -194.735001, 5.000000, -167.727997, - 117.344002, 21.299999, 129.018005, - 116.555000, 21.299999, 128.317001, - -79.209000, 15.000000, 76.053001, - -69.198997, 15.000000, 79.771004, - -67.894997, 15.000000, 75.830002, - -67.894997, 0.000000, 75.830002, - -63.555000, 15.000000, 62.738998, - -63.555000, 0.000000, 62.738998, - -173.785004, 7.500000, -123.577003, - -173.785004, 0.000000, -123.577003, - -191.197998, 7.500000, -114.670998, - -191.197998, 0.000000, -114.670998, - -186.462997, 7.500000, -106.667000, - -186.462997, 0.000000, -106.667000, - -184.322998, 7.500000, -108.304001, - -184.322998, 0.000000, -108.304001, - -212.408997, 24.000000, -166.313995, - -212.408997, 0.000000, -166.313995, - -229.421005, 24.000000, -146.087006, - -229.421005, 0.000000, -146.087006, - -222.453003, 24.000000, -138.917007, - -222.453003, 0.000000, -138.917007, - -223.067993, 24.000000, -138.326996, - -223.067993, 0.000000, -138.326996, - -216.649002, 24.000000, -132.104004, - -216.649002, 0.000000, -132.104004, - -217.384003, 24.000000, -131.503006, - -217.384003, 0.000000, -131.503006, - -207.942001, 24.000000, -121.763000, - -207.942001, 0.000000, -121.763000, - -208.464005, 24.000000, -121.238998, - -208.464005, 0.000000, -121.238998, - -206.169998, 24.000000, -118.412003, - -206.169998, 0.000000, -118.412003, - -197.095993, 24.000000, -124.178001, - -197.095993, 0.000000, -124.178001, - -196.119003, 24.000000, -122.931000, - -196.119003, 0.000000, -122.931000, - -185.820999, 24.000000, -128.563995, - -185.820999, 0.000000, -128.563995, - -180.798996, 24.000000, -133.229004, - -180.798996, 0.000000, -133.229004, - -309.058014, 7.500000, -228.121002, - -309.058014, 0.000000, -228.121002, - -317.830994, 7.500000, -213.748993, - -317.830994, 0.000000, -213.748993, - -316.066010, 7.500000, -212.591003, - -316.066010, 0.000000, -212.591003, - -316.975006, 7.500000, -211.255005, - -316.975006, 0.000000, -211.255005, - -317.276001, 7.500000, -211.455994, - -317.276001, 0.000000, -211.455994, - -320.212006, 7.500000, -206.423996, - -320.212006, 0.000000, -206.423996, - -315.898010, 7.500000, -203.695999, - -315.898010, 0.000000, -203.695999, - -316.787994, 7.500000, -202.093002, - -316.787994, 0.000000, -202.093002, - -316.467010, 7.500000, -200.156006, - -316.467010, 0.000000, -200.156006, - -314.200012, 7.500000, -198.776001, - -314.200012, 0.000000, -198.776001, - -312.354004, 7.500000, -199.320999, - -312.354004, 0.000000, -199.320999, - -310.601990, 7.500000, -198.218994, - -310.601990, 0.000000, -198.218994, - -309.645996, 7.500000, -199.977997, - -309.645996, 0.000000, -199.977997, - -289.638000, 7.500000, -188.000000, - -289.638000, 0.000000, -188.000000, - -294.058014, 7.500000, -180.473999, - -294.058014, 0.000000, -180.473999, - -284.261993, 7.500000, -174.985992, - -284.261993, 0.000000, -174.985992, - -283.485992, 7.500000, -174.751999, - -283.485992, 0.000000, -174.751999, - -282.596985, 7.500000, -174.929993, - -282.596985, 0.000000, -174.929993, - -281.881012, 7.500000, -175.498001, - -281.881012, 0.000000, -175.498001, - -281.440002, 7.500000, -176.289001, - -281.440002, 0.000000, -176.289001, - -281.406006, 7.500000, -177.190002, - -281.406006, 0.000000, -177.190002, - -281.634003, 7.500000, -177.936005, - -281.634003, 0.000000, -177.936005, - -282.209015, 7.500000, -178.470001, - -282.209015, 0.000000, -178.470001, - -279.380005, 7.500000, -183.268997, - -279.380005, 0.000000, -183.268997, - -271.135010, 7.500000, -178.660004, - -271.135010, 0.000000, -178.660004, - -274.036987, 7.500000, -173.393997, - -274.036987, 0.000000, -173.393997, - -274.867004, 7.500000, -173.550003, - -274.867004, 0.000000, -173.550003, - -275.716003, 7.500000, -173.350006, - -275.716003, 0.000000, -173.350006, - -276.324005, 7.500000, -172.714996, - -276.324005, 0.000000, -172.714996, - -276.605011, 7.500000, -171.979996, - -276.605011, 0.000000, -171.979996, - -276.592010, 7.500000, -170.990005, - -276.592010, 0.000000, -170.990005, - -276.230988, 7.500000, -170.455002, - -276.230988, 0.000000, -170.455002, - -275.835999, 7.500000, -170.121002, - -275.835999, 0.000000, -170.121002, - -265.778992, 7.500000, -164.031998, - -265.778992, 0.000000, -164.031998, - -256.216003, 7.500000, -180.774994, - -256.216003, 0.000000, -180.774994, - -234.229004, 7.500000, -163.830994, - -234.229004, 0.000000, -163.830994, - -260.615997, 7.500000, -132.460999, - -260.615997, 0.000000, -132.460999, - -262.066986, 7.500000, -133.695999, - -262.066986, 0.000000, -133.695999, - -273.315002, 7.500000, -120.515999, - -273.315002, 0.000000, -120.515999, - -257.205994, 7.500000, -106.766998, - -257.205994, 0.000000, -106.766998, - -245.964996, 7.500000, -119.947998, - -245.964996, 0.000000, -119.947998, - -249.134995, 7.500000, -122.653000, - -249.134995, 0.000000, -122.653000, - -229.421005, 7.500000, -146.087006, - -212.408997, 7.500000, -166.313995, - -223.970993, 7.500000, -176.033005, - -223.970993, 0.000000, -176.033005, - -248.365997, 7.500000, -194.089005, - -248.365997, 0.000000, -194.089005, - -276.089996, 7.500000, -209.975006, - -276.089996, 0.000000, -209.975006, - -308.108002, 7.500000, -228.231995, - -308.108002, 0.000000, -228.231995, - -308.596008, 7.500000, -228.332993, - -308.596008, 0.000000, -228.332993, - 101.602997, 5.000000, 115.482002, - 101.602997, 4.700000, 115.482002, - 96.160004, 5.000000, 110.405998, - 96.160004, 4.700000, 110.405998, - 93.318001, 4.700000, 113.432999, - 98.767998, 4.700000, 118.510002, - 101.602997, 0.000000, 115.482002, - 114.750000, 5.000000, 101.400002, - 114.750000, 0.000000, 101.400002, - 109.306000, 5.000000, 96.313004, - 109.306000, 0.000000, 96.313004, - 96.160004, 0.000000, 110.405998, - -71.324997, 15.000000, 17.767000, - -71.324997, 0.000000, 17.767000, - -78.292999, 15.000000, 7.871000, - -62.993000, 15.000000, 122.361000, - -62.993000, 0.000000, 122.361000, - -53.563999, 15.000000, 113.055000, - -54.146000, 15.000000, 112.498001, - -58.779999, 15.000000, 108.045998, - -58.779999, 0.000000, 108.045998, - -51.537998, 7.500000, 96.469002, - -51.537998, 0.000000, 96.469002, - -50.575001, 7.500000, 92.773003, - -47.578999, 7.500000, 82.698997, - -50.067001, 7.500000, 81.852997, - -50.067001, 0.000000, 81.852997, - -58.779999, 7.500000, 108.045998, - -65.554001, 15.000000, 76.598999, - -65.554001, 0.000000, 76.598999, - -50.067001, 15.000000, 81.852997, - -65.554001, 7.500000, 76.598999, - -67.894997, 7.500000, 75.830002, - -73.905998, 7.500000, 93.508003, - -28.722000, 22.000000, 92.338997, - -22.235001, 22.000000, 78.068001, - -29.025999, 22.000000, 75.285004, - -29.025999, 0.000000, 75.285004, - -35.817001, 22.000000, 72.501999, - -42.283001, 22.000000, 86.683998, - -35.502499, 22.000000, 89.511497, - -35.502499, 0.000000, 89.511497, - -28.722000, 22.002426, 92.338997, - -22.235001, 22.004669, 78.068001, - -29.025999, 26.700001, 75.285004, - -35.817001, 22.008108, 72.501999, - -35.502499, 26.700001, 89.511497, - 130.973007, 21.299999, 150.524002, - 130.973007, 0.000000, 150.524002, - 128.572006, 21.299999, 153.307007, - 128.572006, 0.000000, 153.307007, - 123.696999, 21.299999, 149.311005, - 123.696999, 0.000000, 149.311005, - 115.852997, 21.299999, 141.328995, - 103.334999, 21.299999, 153.496002, - 109.947998, 21.299999, 160.074997, - 109.947998, 0.000000, 160.074997, - 111.105003, 21.299999, 161.222000, - 111.105003, 0.000000, 161.222000, - 121.042000, 21.299999, 172.419998, - 134.229004, 21.299999, 156.914001, - 136.195007, 21.299999, 154.598007, - 124.378998, 20.000000, 128.572998, - 122.166000, 20.000000, 131.432999, - 122.907997, 20.000000, 132.412994, - 118.126999, 20.000000, 137.009995, - 119.150002, 20.000000, 138.167999, - 115.852997, 20.000000, 141.328995, - 123.696999, 20.000000, 149.311005, - 128.572006, 20.000000, 153.307007, - 130.973007, 20.000000, 150.524002, - 99.677002, 6.500000, 171.440002, - 95.705002, 6.500000, 167.210007, - 85.139000, 6.500000, 179.565994, - 83.167000, 6.500000, 182.416000, - 83.167000, 0.000000, 182.416000, - 88.167999, 6.500000, 187.358002, - 188.983002, 20.000000, 201.628998, - 188.983002, 0.000000, 201.628998, - 204.871002, 20.000000, 175.414001, - 204.871002, 0.000000, 175.414001, - 195.770004, 20.000000, 169.537003, - 195.770004, 0.000000, 169.537003, - 195.048004, 20.000000, 170.783997, - 195.048004, 0.000000, 170.783997, - 176.852997, 20.000000, 221.643005, - 176.852997, 0.000000, 221.643005, - 204.871002, 7.500000, 175.414001, - 188.983002, 7.500000, 201.628998, - 176.852997, 7.500000, 221.643005, - 189.216995, 7.500000, 231.716995, - 189.216995, 0.000000, 231.716995, - 188.869003, 7.500000, 231.884003, - 188.869003, 0.000000, 231.884003, - 191.651001, 7.500000, 233.977005, - 191.651001, 0.000000, 233.977005, - 192.173004, 7.500000, 233.276001, - 192.173004, 0.000000, 233.276001, - 214.889008, 7.500000, 253.167007, - 214.889008, 0.000000, 253.167007, - 216.533997, 7.500000, 254.615005, - 216.533997, 0.000000, 254.615005, - 218.399002, 7.500000, 256.239990, - 218.399002, 0.000000, 256.239990, - 220.164993, 7.500000, 257.786987, - 220.164993, 0.000000, 257.786987, - 234.802994, 7.500000, 270.609985, - 234.802994, 0.000000, 270.609985, - 248.076996, 7.500000, 282.243011, - 248.076996, 0.000000, 282.243011, - 258.287994, 7.500000, 268.628998, - 258.287994, 0.000000, 268.628998, - 280.950012, 7.500000, 230.949005, - 280.950012, 0.000000, 230.949005, - 275.941986, 7.500000, 227.153000, - 275.941986, 0.000000, 227.153000, - 232.375000, 7.500000, 194.149002, - 232.375000, 0.000000, 194.149002, - 220.886993, 7.500000, 186.345001, - 220.886993, 0.000000, 186.345001, - 173.656006, 24.000000, -177.580002, - 173.656006, 0.000000, -177.580002, - 181.820999, 24.000000, -183.869995, - 181.820999, 0.000000, -183.869995, - 182.582993, 24.000000, -184.460007, - 182.582993, 0.000000, -184.460007, - 182.121994, 24.000000, -185.050003, - 182.121994, 0.000000, -185.050003, - 173.214996, 24.000000, -196.615997, - 173.214996, 0.000000, -196.615997, - 170.699997, 24.000000, -199.878006, - 170.699997, 0.000000, -199.878006, - 169.878006, 24.000000, -200.947006, - 169.878006, 0.000000, -200.947006, - 160.951004, 24.000000, -194.078003, - 160.951004, 0.000000, -194.078003, - 161.705994, 24.000000, -193.098007, - 161.705994, 0.000000, -193.098007, - 164.013000, 24.000000, -190.104004, - 164.013000, 0.000000, -190.104004, - 173.214996, 7.000000, -196.615997, - 182.121994, 7.000000, -185.050003, - 184.182007, 7.000000, -186.630997, - 184.182007, 0.000000, -186.630997, - 182.917999, 7.000000, -188.278000, - 182.917999, 0.000000, -188.278000, - 175.274002, 7.000000, -198.197006, - 175.274002, 0.000000, -198.197006, - 181.820999, 7.000000, -183.869995, - 173.656006, 7.000000, -177.580002, - 164.013000, 7.000000, -190.104004, - 159.184998, 7.000000, -184.393005, - 159.184998, 0.000000, -184.393005, - 166.100006, 7.000000, -175.376007, - 166.100006, 0.000000, -175.376007, - 167.697998, 7.000000, -174.429001, - 167.697998, 0.000000, -174.429001, - 169.537003, 7.000000, -173.828003, - 169.537003, 0.000000, -173.828003, - 171.416000, 7.000000, -173.794998, - 171.416000, 0.000000, -173.794998, - 173.569000, 7.000000, -174.317993, - 173.569000, 0.000000, -174.317993, - 183.826996, 7.000000, -179.317001, - 183.826996, 0.000000, -179.317001, - -152.479996, 10.000000, 161.610992, - -152.479996, 0.000000, 161.610992, - -146.641998, 10.000000, 165.563004, - -146.641998, 0.000000, 165.563004, - -139.098999, 10.000000, 155.389008, - -139.098999, 0.000000, 155.389008, - -138.009003, 10.000000, 156.223007, - -138.009003, 0.000000, 156.223007, - -137.727997, 10.000000, 155.822998, - -137.727997, 0.000000, 155.822998, - -132.190994, 10.000000, 147.496002, - -132.190994, 0.000000, 147.496002, - -132.190994, 10.000000, 147.485001, - -132.190994, 0.000000, 147.485001, - -131.949997, 10.000000, 147.128998, - -131.949997, 0.000000, 147.128998, - -139.600006, 10.000000, 142.042007, - -139.600006, 0.000000, 142.042007, - -142.375000, 10.000000, 146.371994, - -142.375000, 0.000000, 146.371994, - -146.199997, 10.000000, 152.705994, - -146.199997, 0.000000, 152.705994, - -146.621994, 10.000000, 153.328995, - -146.621994, 0.000000, 153.328995, - -147.423996, 10.000000, 154.464996, - -147.423996, 0.000000, 154.464996, - -124.220001, 7.500000, 152.238007, - -124.220001, 0.000000, 152.238007, - -130.779999, 7.500000, 147.863998, - -130.779999, 0.000000, 147.863998, - -130.906998, 7.500000, 148.063995, - -130.906998, 0.000000, 148.063995, - -130.867004, 7.500000, 148.085999, - -130.867004, 0.000000, 148.085999, - -136.832001, 7.500000, 157.125000, - -136.832001, 0.000000, 157.125000, - -138.009003, 7.500000, 156.223007, - -139.098999, 7.500000, 155.389008, - -146.641998, 7.500000, 165.563004, - -146.514999, 7.500000, 165.641006, - -146.514999, 0.000000, 165.641006, - -146.602005, 7.500000, 165.774002, - -146.602005, 0.000000, 165.774002, - -138.992004, 7.500000, 171.384995, - -138.992004, 0.000000, 171.384995, - -132.477997, 7.500000, 176.182007, - -132.477997, 0.000000, 176.182007, - -118.456001, 7.500000, 158.104996, - -118.456001, 0.000000, 158.104996, - -118.803001, 7.500000, 155.845001, - -118.803001, 0.000000, 155.845001, - 101.963997, 7.500000, -119.926003, - 101.963997, 0.000000, -119.926003, - 102.191002, 7.500000, -120.492996, - 102.191002, 0.000000, -120.492996, - 105.032997, 7.500000, -127.628998, - 105.032997, 0.000000, -127.628998, - 105.266998, 7.500000, -128.218994, - 105.266998, 0.000000, -128.218994, - 104.029999, 7.500000, -128.709000, - 104.029999, 0.000000, -128.709000, - 103.569000, 7.500000, -128.897995, - 103.569000, 0.000000, -128.897995, - 102.833000, 7.500000, -129.188004, - 102.833000, 0.000000, -129.188004, - 102.098000, 7.500000, -129.488007, - 102.098000, 0.000000, -129.488007, - 101.917000, 7.500000, -129.565994, - 101.917000, 0.000000, -129.565994, - 100.927002, 7.500000, -129.955994, - 100.927002, 0.000000, -129.955994, - 98.788002, 7.500000, -130.824005, - 98.788002, 0.000000, -130.824005, - 95.484001, 7.500000, -122.530998, - 95.484001, 0.000000, -122.530998, - 97.624001, 7.500000, -121.674004, - 97.624001, 0.000000, -121.674004, - 98.747002, 7.500000, -121.217003, - 98.747002, 0.000000, -121.217003, - 99.175003, 7.500000, -121.050003, - 99.175003, 0.000000, -121.050003, - 99.683998, 7.500000, -120.849998, - 99.683998, 0.000000, -120.849998, - 100.165001, 7.500000, -120.649002, - 100.165001, 0.000000, -120.649002, - 100.626999, 7.500000, -120.471001, - 100.626999, 0.000000, -120.471001, - 103.086998, 7.500000, -120.137001, - 103.086998, 0.000000, -120.137001, - 111.633003, 7.500000, -116.709000, - 111.633003, 0.000000, -116.709000, - 114.482002, 7.500000, -123.833000, - 114.482002, 0.000000, -123.833000, - 112.462997, 7.500000, -124.646004, - 112.462997, 0.000000, -124.646004, - 112.008003, 7.500000, -124.823997, - 112.008003, 0.000000, -124.823997, - 111.546997, 7.500000, -125.013000, - 111.546997, 0.000000, -125.013000, - 111.084999, 7.500000, -125.202003, - 111.084999, 0.000000, -125.202003, - 110.624001, 7.500000, -125.380997, - 110.624001, 0.000000, -125.380997, - 105.948997, 7.500000, -127.262001, - 105.948997, 0.000000, -127.262001, - 179.126007, 14.000000, 157.804001, - 179.126007, 13.700000, 157.804001, - 183.856995, 14.000000, 152.026993, - 183.856995, 13.700000, 152.026993, - 188.587997, 14.000000, 146.250000, - 188.587997, 13.700000, 146.250000, - 134.356003, 14.000000, 101.801003, - 134.356003, 13.700000, 101.801003, - 129.625000, 14.000000, 107.578499, - 129.625000, 13.700000, 107.578499, - 129.160004, 14.000000, 108.135002, - 129.160004, 13.700000, 108.135002, - 124.893997, 14.000000, 113.356003, - 124.893997, 13.700000, 113.356003, - 179.126007, 14.000311, 157.804001, - 183.856995, 20.000000, 152.026993, - 188.587997, 14.000311, 146.250000, - 129.625000, 20.000000, 107.578499, - 129.160004, 19.417305, 108.135002, - 124.893997, 14.000001, 113.356003, - 135.298996, 14.000000, 100.554001, - 135.298996, 13.700000, 100.554001, - 124.686996, 14.000000, 113.634003, - 124.686996, 13.700000, 113.634003, - 126.332001, 14.000000, 115.158997, - 126.332001, 13.700000, 115.158997, - 127.615997, 14.000000, 116.349998, - 127.615997, 13.700000, 116.349998, - 132.089005, 14.000000, 120.490997, - 132.089005, 13.700000, 120.490997, - 142.654999, 14.000000, 130.153000, - 142.654999, 13.700000, 130.153000, - 150.753006, 14.000000, 137.556000, - 150.753006, 13.700000, 137.556000, - 164.962997, 14.000000, 148.554001, - 164.962997, 13.700000, 148.554001, - 171.362000, 14.000000, 153.507004, - 171.362000, 13.700000, 153.507004, - 173.207993, 14.000000, 154.977005, - 173.207993, 13.700000, 154.977005, - 175.388000, 14.000000, 156.712997, - 175.388000, 13.700000, 156.712997, - 180.591003, 14.000000, 160.843002, - 180.591003, 13.700000, 160.843002, - 195.048004, 14.000000, 170.783997, - 195.048004, 13.700000, 170.783997, - 195.770004, 14.000000, 169.537003, - 195.770004, 13.700000, 169.537003, - 204.871002, 14.000000, 175.414001, - 204.871002, 13.700000, 175.414001, - 220.886993, 14.000000, 186.345001, - 220.886993, 13.700000, 186.345001, - 232.375000, 14.000000, 194.149002, - 232.375000, 13.700000, 194.149002, - 275.941986, 14.000000, 227.153000, - 275.941986, 13.700000, 227.153000, - 278.114990, 14.000000, 224.492996, - 278.114990, 13.700000, 224.492996, - 280.562988, 14.000000, 221.498993, - 280.562988, 13.700000, 221.498993, - 255.371994, 14.000000, 201.662003, - 255.371994, 13.700000, 201.662003, - 268.231995, 14.000000, 185.354996, - 268.231995, 13.700000, 185.354996, - 284.955994, 14.000000, 165.507004, - 284.955994, 13.700000, 165.507004, - 280.963989, 14.000000, 162.311996, - 280.963989, 13.700000, 162.311996, - 277.259003, 14.000000, 159.339996, - 277.259003, 13.700000, 159.339996, - 271.575012, 14.000000, 166.932007, - 271.575012, 13.700000, 166.932007, - 270.404999, 14.000000, 166.119003, - 270.404999, 13.700000, 166.119003, - 269.643005, 14.000000, 167.166000, - 269.643005, 13.700000, 167.166000, - 261.283997, 14.000000, 178.498001, - 261.283997, 13.700000, 178.498001, - 252.985001, 14.000000, 189.751999, - 252.985001, 13.700000, 189.751999, - 247.067001, 14.000000, 189.595993, - 247.067001, 13.700000, 189.595993, - 240.962006, 14.000000, 184.720001, - 240.962006, 13.700000, 184.720001, - 239.149002, 14.000000, 183.440002, - 239.149002, 13.700000, 183.440002, - 237.444000, 14.000000, 182.238007, - 237.444000, 13.700000, 182.238007, - 226.899002, 14.000000, 174.356995, - 226.899002, 13.700000, 174.356995, - 221.367996, 14.000000, 170.227005, - 221.367996, 13.700000, 170.227005, - 217.089005, 14.000000, 167.020996, - 217.089005, 13.700000, 167.020996, - 213.697998, 14.000000, 164.483002, - 213.697998, 13.700000, 164.483002, - 209.772995, 14.000000, 161.554993, - 209.772995, 13.700000, 161.554993, - 207.112000, 14.000000, 159.563004, - 207.112000, 13.700000, 159.563004, - 203.688004, 14.000000, 157.003006, - 203.688004, 13.700000, 157.003006, - 198.966995, 14.000000, 153.106995, - 198.966995, 13.700000, 153.106995, - 197.007004, 14.000000, 151.492996, - 197.007004, 13.700000, 151.492996, - 188.962997, 14.000000, 144.847000, - 188.962997, 13.700000, 144.847000, - 186.703003, 14.000000, 142.988007, - 186.703003, 13.700000, 142.988007, - 181.024994, 14.000000, 138.289993, - 181.024994, 13.700000, 138.289993, - 139.345001, 14.000000, 103.893997, - 139.345001, 13.700000, 103.893997, - -162.566879, 0.000000, -42.736065, - -161.684143, 0.000000, -42.266209, - -162.613861, 0.000000, -42.647793, - -161.731125, 0.000000, -42.177933, - -162.613861, 2.000000, -42.647793, - -161.731125, 2.000000, -42.177933, - -162.566879, 2.000000, -42.736065, - -161.684143, 2.000000, -42.266209, - 186.349350, 0.000000, 142.631027, - 187.120331, 0.000000, 143.267883, - 186.285660, 0.000000, 142.708130, - 187.056656, 0.000000, 143.344971, - 186.285660, 2.000000, 142.708130, - 187.056656, 2.000000, 143.344971, - 186.349350, 2.000000, 142.631027, - 187.120331, 2.000000, 143.267883, - 134.014008, 0.000000, 99.146004, - 133.014008, 0.000000, 99.146004, - 134.014008, 0.000000, 99.045998, - 133.014008, 0.000000, 99.045998, - 134.014008, 2.000000, 99.045998, - 133.014008, 2.000000, 99.045998, - 134.014008, 2.000000, 99.146004, - 133.014008, 2.000000, 99.146004, - 135.832001, 0.000000, 86.366997, - 134.832001, 0.000000, 86.366997, - 135.832001, 0.000000, 86.266998, - 134.832001, 0.000000, 86.266998, - 135.832001, 2.000000, 86.266998, - 134.832001, 2.000000, 86.266998, - 135.832001, 2.000000, 86.366997, - 134.832001, 2.000000, 86.366997, - 163.360489, 0.000000, 50.172497, - 162.620819, 0.000000, 50.845470, - 163.293182, 0.000000, 50.098530, - 162.553513, 0.000000, 50.771503, - 163.293182, 2.000000, 50.098530, - 162.553513, 2.000000, 50.771503, - 163.360489, 2.000000, 50.172497, - 162.620819, 2.000000, 50.845470, - 239.528732, 0.000000, 183.769104, - 238.711624, 0.000000, 183.192612, - 239.586380, 0.000000, 183.687393, - 238.769272, 0.000000, 183.110901, - 239.586380, 2.000000, 183.687393, - 238.769272, 2.000000, 183.110901, - 239.528732, 2.000000, 183.769104, - 238.711624, 2.000000, 183.192612, - 207.482422, 0.000000, 159.902542, - 206.681671, 0.000000, 159.303528, - 207.542328, 0.000000, 159.822464, - 206.741577, 0.000000, 159.223465, - 207.542328, 2.000000, 159.822464, - 206.741577, 2.000000, 159.223465, - 207.482422, 2.000000, 159.902542, - 206.681671, 2.000000, 159.303528, - 261.621033, 0.000000, 178.125290, - 261.027466, 0.000000, 178.930069, - 261.540527, 0.000000, 178.065933, - 260.946991, 0.000000, 178.870712, - 261.540527, 2.000000, 178.065933, - 260.946991, 2.000000, 178.870712, - 261.621033, 2.000000, 178.125290, - 261.027466, 2.000000, 178.930069, - 227.269623, 0.000000, 174.696320, - 226.468521, 0.000000, 174.097794, - 227.329483, 0.000000, 174.616211, - 226.528381, 0.000000, 174.017685, - 227.329483, 2.000000, 174.616211, - 226.528381, 2.000000, 174.017685, - 227.269623, 2.000000, 174.696320, - 226.468521, 2.000000, 174.097794, - 221.738480, 0.000000, 170.566483, - 220.937637, 0.000000, 169.967606, - 221.798370, 0.000000, 170.486389, - 220.997528, 0.000000, 169.887527, - 221.798370, 2.000000, 170.486389, - 220.997528, 2.000000, 169.887527, - 221.738480, 2.000000, 170.566483, - 220.937637, 2.000000, 169.967606, - 217.459244, 0.000000, 167.360733, - 216.658813, 0.000000, 166.761307, - 217.519180, 0.000000, 167.280701, - 216.718765, 0.000000, 166.681259, - 217.519180, 2.000000, 167.280701, - 216.718765, 2.000000, 166.681259, - 217.459244, 2.000000, 167.360733, - 216.658813, 2.000000, 166.761307, - 214.068619, 0.000000, 164.822311, - 213.267517, 0.000000, 164.223785, - 214.128479, 0.000000, 164.742203, - 213.327377, 0.000000, 164.143677, - 214.128479, 2.000000, 164.742203, - 213.327377, 2.000000, 164.143677, - 214.068619, 2.000000, 164.822311, - 213.267517, 2.000000, 164.223785 - ], - "parts": [ - { - "id": "shape1_part1", - "type": "TRIANGLES", - "indices": [ - 0, 1, 2, 1, 3, 2, 2, 3, 4, 3, 5, 4, - 4, 5, 6, 5, 7, 6, 6, 7, 8, 7, 9, 8, - 8, 9, 10, 9, 11, 10, 10, 11, 12, 11, 13, 12, - 12, 13, 14, 13, 15, 14, 14, 15, 16, 15, 17, 16, - 16, 17, 18, 17, 19, 18, 18, 19, 20, 19, 21, 20, - 20, 21, 22, 21, 23, 22, 22, 23, 24, 23, 25, 24, - 24, 25, 26, 25, 27, 26, 26, 27, 28, 27, 29, 28, - 28, 29, 30, 29, 31, 30, 30, 31, 32, 31, 33, 32, - 32, 33, 34, 33, 35, 34, 34, 35, 36, 35, 37, 36, - 36, 37, 38, 37, 39, 38, 38, 39, 40, 39, 41, 40, - 40, 41, 42, 41, 43, 42, 42, 43, 44, 43, 45, 44, - 44, 45, 46, 45, 47, 46, 46, 47, 48, 47, 49, 48, - 48, 49, 50, 49, 51, 50, 50, 51, 52, 51, 53, 52, - 52, 53, 54, 53, 55, 54, 54, 55, 56, 55, 57, 56, - 56, 57, 58, 57, 59, 58, 58, 59, 60, 59, 61, 60, - 60, 61, 62, 61, 63, 62, 62, 63, 64, 63, 65, 64, - 64, 65, 66, 65, 67, 66, 66, 67, 68, 67, 69, 68, - 68, 69, 70, 69, 71, 70, 70, 71, 72, 71, 73, 72, - 72, 73, 74, 73, 75, 74, 74, 75, 76, 75, 77, 76, - 76, 77, 78, 77, 79, 78, 78, 79, 80, 79, 81, 80, - 80, 81, 82, 81, 83, 82, 82, 83, 84, 83, 85, 84, - 84, 85, 86, 85, 87, 86, 86, 87, 88, 87, 89, 88, - 88, 89, 90, 89, 91, 90, 90, 91, 0, 91, 1, 0, - 0, 0, 2, 0, 2, 2, 2, 2, 4, 2, 4, 4, - 4, 4, 6, 4, 6, 6, 6, 6, 8, 6, 8, 8, - 8, 8, 10, 8, 10, 10, 10, 10, 12, 10, 12, 12, - 12, 12, 14, 12, 14, 14, 14, 14, 16, 14, 16, 16, - 16, 16, 18, 16, 18, 18, 18, 18, 20, 18, 20, 20, - 20, 20, 22, 20, 22, 22, 22, 22, 24, 22, 24, 24, - 24, 24, 26, 24, 26, 26, 26, 26, 28, 26, 28, 28, - 28, 28, 30, 28, 30, 30, 30, 30, 32, 30, 32, 32, - 32, 32, 34, 32, 34, 34, 34, 34, 36, 34, 36, 36, - 36, 36, 38, 36, 38, 38, 38, 38, 40, 38, 40, 40, - 40, 40, 42, 40, 42, 42, 42, 42, 44, 42, 44, 44, - 44, 44, 46, 44, 46, 46, 46, 46, 48, 46, 48, 48, - 48, 48, 50, 48, 50, 50, 50, 50, 52, 50, 52, 52, - 52, 52, 54, 52, 54, 54, 54, 54, 56, 54, 56, 56, - 56, 56, 58, 56, 58, 58, 58, 58, 60, 58, 60, 60, - 60, 60, 62, 60, 62, 62, 62, 62, 64, 62, 64, 64, - 64, 64, 66, 64, 66, 66, 66, 66, 68, 66, 68, 68, - 68, 68, 70, 68, 70, 70, 70, 70, 72, 70, 72, 72, - 72, 72, 74, 72, 74, 74, 74, 74, 76, 74, 76, 76, - 76, 76, 78, 76, 78, 78, 78, 78, 80, 78, 80, 80, - 80, 80, 82, 80, 82, 82, 82, 82, 84, 82, 84, 84, - 84, 84, 86, 84, 86, 86, 86, 86, 88, 86, 88, 88, - 88, 88, 90, 88, 90, 90, 90, 90, 0, 90, 0, 0, - 92, 93, 94, 93, 95, 94, 94, 95, 96, 95, 97, 96, - 96, 97, 98, 97, 99, 98, 98, 99, 100, 99, 101, 100, - 100, 101, 102, 101, 103, 102, 102, 103, 104, 103, 105, 104, - 104, 105, 106, 105, 107, 106, 106, 107, 108, 107, 109, 108, - 108, 109, 92, 109, 93, 92, 92, 92, 94, 92, 94, 94, - 94, 94, 96, 94, 96, 96, 96, 96, 98, 96, 98, 98, - 98, 98, 100, 98, 100, 100, 100, 100, 102, 100, 102, 102, - 102, 102, 104, 102, 104, 104, 104, 104, 106, 104, 106, 106, - 106, 106, 108, 106, 108, 108, 108, 108, 92, 108, 92, 92, - 110, 111, 112, 111, 113, 112, 112, 113, 114, 113, 115, 114, - 114, 115, 116, 115, 117, 116, 116, 117, 118, 117, 119, 118, - 118, 119, 120, 119, 121, 120, 120, 121, 110, 121, 111, 110, - 110, 110, 112, 110, 112, 112, 112, 112, 114, 112, 114, 114, - 114, 114, 116, 114, 116, 116, 116, 116, 118, 116, 118, 118, - 118, 118, 120, 118, 120, 120, 120, 120, 110, 120, 110, 110, - 142, 143, 144, 143, 145, 144, 144, 145, 146, 145, 147, 146, - 146, 147, 148, 147, 149, 148, 148, 149, 150, 149, 151, 150, - 150, 151, 152, 151, 153, 152, 152, 153, 154, 153, 155, 154, - 154, 155, 156, 155, 157, 156, 156, 157, 158, 157, 159, 158, - 158, 159, 142, 159, 143, 142, 142, 142, 144, 142, 144, 144, - 144, 144, 146, 144, 146, 146, 146, 146, 148, 146, 148, 148, - 148, 148, 150, 148, 150, 150, 150, 150, 152, 150, 152, 152, - 152, 152, 154, 152, 154, 154, 154, 154, 156, 154, 156, 156, - 156, 156, 158, 156, 158, 158, 158, 158, 142, 158, 142, 142, - 160, 161, 162, 161, 163, 162, 162, 163, 164, 163, 165, 164, - 164, 165, 166, 165, 167, 166, 166, 167, 168, 167, 169, 168, - 168, 169, 170, 169, 171, 170, 170, 171, 172, 171, 173, 172, - 172, 173, 174, 173, 175, 174, 174, 175, 176, 175, 177, 176, - 176, 177, 178, 177, 179, 178, 178, 179, 180, 179, 181, 180, - 180, 181, 182, 181, 183, 182, 182, 183, 184, 183, 185, 184, - 184, 185, 186, 185, 187, 186, 186, 187, 188, 187, 189, 188, - 188, 189, 190, 189, 191, 190, 190, 191, 192, 191, 193, 192, - 192, 193, 194, 193, 195, 194, 194, 195, 196, 195, 197, 196, - 196, 197, 198, 197, 199, 198, 198, 199, 160, 199, 161, 160, - 160, 160, 162, 160, 162, 162, 162, 162, 164, 162, 164, 164, - 164, 164, 166, 164, 166, 166, 166, 166, 168, 166, 168, 168, - 168, 168, 170, 168, 170, 170, 170, 170, 172, 170, 172, 172, - 172, 172, 174, 172, 174, 174, 174, 174, 176, 174, 176, 176, - 176, 176, 178, 176, 178, 178, 178, 178, 180, 178, 180, 180, - 180, 180, 182, 180, 182, 182, 182, 182, 184, 182, 184, 184, - 184, 184, 186, 184, 186, 186, 186, 186, 188, 186, 188, 188, - 188, 188, 190, 188, 190, 190, 190, 190, 192, 190, 192, 192, - 192, 192, 194, 192, 194, 194, 194, 194, 196, 194, 196, 196, - 196, 196, 198, 196, 198, 198, 198, 198, 160, 198, 160, 160, - 200, 143, 201, 143, 159, 201, 201, 159, 202, 159, 157, 202, - 202, 157, 203, 157, 155, 203, 203, 155, 204, 155, 153, 204, - 204, 153, 205, 153, 151, 205, 205, 151, 206, 151, 149, 206, - 206, 149, 207, 149, 147, 207, 207, 147, 208, 147, 145, 208, - 208, 145, 200, 145, 143, 200, 200, 200, 201, 200, 201, 201, - 201, 201, 202, 201, 202, 202, 202, 202, 203, 202, 203, 203, - 203, 203, 204, 203, 204, 204, 204, 204, 205, 204, 205, 205, - 205, 205, 206, 205, 206, 206, 206, 206, 207, 206, 207, 207, - 207, 207, 208, 207, 208, 208, 208, 208, 200, 208, 200, 200, - 209, 210, 211, 210, 212, 211, 211, 212, 213, 212, 214, 213, - 213, 214, 215, 214, 216, 215, 215, 216, 217, 216, 218, 217, - 217, 218, 219, 218, 220, 219, 219, 220, 221, 220, 222, 221, - 221, 222, 223, 222, 224, 223, 223, 224, 225, 224, 226, 225, - 225, 226, 227, 226, 228, 227, 227, 228, 229, 228, 230, 229, - 229, 230, 209, 230, 210, 209, 209, 209, 211, 209, 211, 211, - 211, 211, 213, 211, 213, 213, 213, 213, 215, 213, 215, 215, - 215, 215, 217, 215, 217, 217, 217, 217, 219, 217, 219, 219, - 219, 219, 221, 219, 221, 221, 221, 221, 223, 221, 223, 223, - 223, 223, 225, 223, 225, 225, 225, 225, 227, 225, 227, 227, - 227, 227, 229, 227, 229, 229, 229, 229, 209, 229, 209, 209, - 231, 232, 32, 232, 33, 32, 32, 33, 30, 33, 31, 30, - 30, 31, 28, 31, 29, 28, 28, 29, 26, 29, 27, 26, - 26, 27, 233, 27, 234, 233, 233, 234, 235, 234, 236, 235, - 235, 236, 237, 236, 238, 237, 237, 238, 239, 238, 240, 239, - 239, 240, 241, 240, 242, 241, 241, 242, 243, 242, 244, 243, - 243, 244, 245, 244, 246, 245, 245, 246, 247, 246, 248, 247, - 247, 248, 249, 248, 250, 249, 249, 250, 251, 250, 252, 251, - 251, 252, 253, 252, 254, 253, 253, 254, 255, 254, 256, 255, - 255, 256, 231, 256, 232, 231, 231, 231, 32, 231, 32, 32, - 32, 32, 30, 32, 30, 30, 30, 30, 28, 30, 28, 28, - 28, 28, 26, 28, 26, 26, 26, 26, 233, 26, 233, 233, - 233, 233, 235, 233, 235, 235, 235, 235, 237, 235, 237, 237, - 237, 237, 239, 237, 239, 239, 239, 239, 241, 239, 241, 241, - 241, 241, 243, 241, 243, 243, 243, 243, 245, 243, 245, 245, - 245, 245, 247, 245, 247, 247, 247, 247, 249, 247, 249, 249, - 249, 249, 251, 249, 251, 251, 251, 251, 253, 251, 253, 253, - 253, 253, 255, 253, 255, 255, 255, 255, 231, 255, 231, 231, - 257, 258, 259, 258, 260, 259, 259, 260, 261, 260, 262, 261, - 261, 262, 263, 262, 264, 263, 263, 264, 265, 264, 266, 265, - 265, 266, 267, 266, 268, 267, 267, 268, 269, 268, 270, 269, - 269, 270, 271, 270, 272, 271, 271, 272, 257, 272, 258, 257, - 257, 257, 259, 257, 259, 259, 259, 259, 261, 259, 261, 261, - 261, 261, 263, 261, 263, 263, 263, 263, 265, 263, 265, 265, - 265, 265, 267, 265, 267, 267, 267, 267, 269, 267, 269, 269, - 269, 269, 271, 269, 271, 271, 271, 271, 257, 271, 257, 257, - 273, 274, 275, 274, 276, 275, 275, 276, 277, 276, 278, 277, - 277, 278, 279, 278, 280, 279, 279, 280, 273, 280, 274, 273, - 273, 273, 275, 273, 275, 275, 275, 275, 277, 275, 277, 277, - 277, 277, 279, 277, 279, 279, 279, 279, 273, 279, 273, 273, - 281, 282, 283, 282, 284, 283, 283, 284, 285, 284, 286, 285, - 285, 286, 287, 286, 288, 287, 287, 288, 289, 288, 290, 289, - 289, 290, 281, 290, 282, 281, 281, 281, 283, 281, 283, 283, - 283, 283, 285, 283, 285, 285, 285, 285, 287, 285, 287, 287, - 287, 287, 289, 287, 289, 289, 289, 289, 281, 289, 281, 281, - 291, 292, 293, 292, 294, 293, 293, 294, 295, 294, 296, 295, - 295, 296, 297, 296, 298, 297, 297, 298, 299, 298, 300, 299, - 299, 300, 301, 300, 302, 301, 301, 302, 303, 302, 304, 303, - 303, 304, 291, 304, 292, 291, 291, 291, 293, 291, 293, 293, - 293, 293, 295, 293, 295, 295, 295, 295, 297, 295, 297, 297, - 297, 297, 299, 297, 299, 299, 299, 299, 301, 299, 301, 301, - 301, 301, 303, 301, 303, 303, 303, 303, 291, 303, 291, 291, - 305, 306, 307, 306, 308, 307, 307, 308, 309, 308, 284, 309, - 309, 284, 310, 284, 282, 310, 310, 282, 305, 282, 306, 305, - 305, 305, 307, 305, 307, 307, 307, 307, 309, 307, 309, 309, - 309, 309, 310, 309, 310, 310, 310, 310, 305, 310, 305, 305, - 311, 312, 313, 312, 314, 313, 313, 314, 315, 314, 316, 315, - 315, 316, 317, 316, 318, 317, 317, 318, 311, 318, 312, 311, - 311, 311, 313, 311, 313, 313, 313, 313, 315, 313, 315, 315, - 315, 315, 317, 315, 317, 317, 317, 317, 311, 317, 311, 311, - 345, 346, 347, 346, 348, 347, 347, 348, 349, 348, 350, 349, - 349, 350, 351, 350, 352, 351, 351, 352, 353, 352, 354, 353, - 353, 354, 355, 354, 356, 355, 355, 356, 357, 356, 358, 357, - 357, 358, 359, 358, 360, 359, 359, 360, 361, 360, 362, 361, - 361, 362, 363, 362, 364, 363, 363, 364, 365, 364, 366, 365, - 365, 366, 367, 366, 368, 367, 367, 368, 345, 368, 346, 345, - 345, 345, 347, 345, 347, 347, 347, 347, 349, 347, 349, 349, - 349, 349, 351, 349, 351, 351, 351, 351, 353, 351, 353, 353, - 353, 353, 355, 353, 355, 355, 355, 355, 357, 355, 357, 357, - 357, 357, 359, 357, 359, 359, 359, 359, 361, 359, 361, 361, - 361, 361, 363, 361, 363, 363, 363, 363, 365, 363, 365, 365, - 365, 365, 367, 365, 367, 367, 367, 367, 345, 367, 345, 345, - 369, 360, 370, 360, 358, 370, 370, 358, 371, 358, 356, 371, - 371, 356, 372, 356, 354, 372, 372, 354, 373, 354, 352, 373, - 373, 352, 374, 352, 350, 374, 374, 350, 375, 350, 376, 375, - 375, 376, 377, 376, 378, 377, 377, 378, 379, 378, 380, 379, - 379, 380, 381, 380, 382, 381, 381, 382, 383, 382, 384, 383, - 383, 384, 385, 384, 386, 385, 385, 386, 387, 386, 388, 387, - 387, 388, 369, 388, 360, 369, 369, 369, 370, 369, 370, 370, - 370, 370, 371, 370, 371, 371, 371, 371, 372, 371, 372, 372, - 372, 372, 373, 372, 373, 373, 373, 373, 374, 373, 374, 374, - 374, 374, 375, 374, 375, 375, 375, 375, 377, 375, 377, 377, - 377, 377, 379, 377, 379, 379, 379, 379, 381, 379, 381, 381, - 381, 381, 383, 381, 383, 383, 383, 383, 385, 383, 385, 385, - 385, 385, 387, 385, 387, 387, 387, 387, 369, 387, 369, 369, - 389, 390, 391, 390, 392, 391, 391, 392, 393, 392, 394, 393, - 393, 394, 395, 394, 396, 395, 395, 396, 397, 396, 398, 397, - 397, 398, 399, 398, 400, 399, 399, 400, 389, 400, 390, 389, - 389, 389, 391, 389, 391, 391, 391, 391, 393, 391, 393, 393, - 393, 393, 395, 393, 395, 395, 395, 395, 397, 395, 397, 397, - 397, 397, 399, 397, 399, 399, 399, 399, 389, 399, 389, 389, - 401, 402, 403, 402, 404, 403, 403, 404, 405, 404, 406, 405, - 405, 406, 407, 406, 408, 407, 407, 408, 409, 408, 410, 409, - 409, 410, 411, 410, 412, 411, 411, 412, 413, 412, 414, 413, - 413, 414, 415, 414, 416, 415, 415, 416, 401, 416, 402, 401, - 401, 401, 403, 401, 403, 403, 403, 403, 405, 403, 405, 405, - 405, 405, 407, 405, 407, 407, 407, 407, 409, 407, 409, 409, - 409, 409, 411, 409, 411, 411, 411, 411, 413, 411, 413, 413, - 413, 413, 415, 413, 415, 415, 415, 415, 401, 415, 401, 401, - 417, 418, 419, 418, 420, 419, 419, 420, 421, 420, 422, 421, - 421, 422, 423, 422, 424, 423, 423, 424, 425, 424, 426, 425, - 425, 426, 427, 426, 428, 427, 427, 428, 429, 428, 430, 429, - 429, 430, 431, 430, 432, 431, 431, 432, 433, 432, 434, 433, - 433, 434, 417, 434, 418, 417, 417, 417, 419, 417, 419, 419, - 419, 419, 421, 419, 421, 421, 421, 421, 423, 421, 423, 423, - 423, 423, 425, 423, 425, 425, 425, 425, 427, 425, 427, 427, - 427, 427, 429, 427, 429, 429, 429, 429, 431, 429, 431, 431, - 431, 431, 433, 431, 433, 433, 433, 433, 417, 433, 417, 417, - 435, 430, 436, 430, 437, 436, 436, 437, 438, 437, 439, 438, - 438, 439, 440, 439, 441, 440, 440, 441, 442, 441, 443, 442, - 442, 443, 444, 443, 445, 444, 444, 445, 446, 445, 447, 446, - 446, 447, 448, 447, 418, 448, 448, 418, 449, 418, 434, 449, - 449, 434, 450, 434, 432, 450, 450, 432, 435, 432, 430, 435, - 435, 435, 436, 435, 436, 436, 436, 436, 438, 436, 438, 438, - 438, 438, 440, 438, 440, 440, 440, 440, 442, 440, 442, 442, - 442, 442, 444, 442, 444, 444, 444, 444, 446, 444, 446, 446, - 446, 446, 448, 446, 448, 448, 448, 448, 449, 448, 449, 449, - 449, 449, 450, 449, 450, 450, 450, 450, 435, 450, 435, 435, - 451, 420, 452, 420, 453, 452, 452, 453, 454, 453, 455, 454, - 454, 455, 456, 455, 457, 456, 456, 457, 458, 457, 459, 458, - 458, 459, 460, 459, 461, 460, 460, 461, 462, 461, 463, 462, - 462, 463, 464, 463, 465, 464, 464, 465, 466, 465, 467, 466, - 466, 467, 468, 467, 469, 468, 468, 469, 470, 469, 471, 470, - 470, 471, 472, 471, 473, 472, 472, 473, 474, 473, 439, 474, - 474, 439, 475, 439, 437, 475, 475, 437, 476, 437, 430, 476, - 476, 430, 477, 430, 428, 477, 477, 428, 478, 428, 426, 478, - 478, 426, 479, 426, 424, 479, 479, 424, 480, 424, 422, 480, - 480, 422, 451, 422, 420, 451, 451, 451, 452, 451, 452, 452, - 452, 452, 454, 452, 454, 454, 454, 454, 456, 454, 456, 456, - 456, 456, 458, 456, 458, 458, 458, 458, 460, 458, 460, 460, - 460, 460, 462, 460, 462, 462, 462, 462, 464, 462, 464, 464, - 464, 464, 466, 464, 466, 466, 466, 466, 468, 466, 468, 468, - 468, 468, 470, 468, 470, 470, 470, 470, 472, 470, 472, 472, - 472, 472, 474, 472, 474, 474, 474, 474, 475, 474, 475, 475, - 475, 475, 476, 475, 476, 476, 476, 476, 477, 476, 477, 477, - 477, 477, 478, 477, 478, 478, 478, 478, 479, 478, 479, 479, - 479, 479, 480, 479, 480, 480, 480, 480, 451, 480, 451, 451, - 295, 296, 293, 296, 294, 293, 293, 294, 481, 294, 482, 481, - 481, 482, 483, 482, 484, 483, 483, 484, 295, 484, 296, 295, - 295, 295, 293, 295, 293, 293, 293, 293, 481, 293, 481, 481, - 481, 481, 483, 481, 483, 483, 483, 483, 295, 483, 295, 295, - 485, 486, 487, 486, 488, 487, 487, 488, 303, 488, 304, 303, - 303, 304, 301, 304, 302, 301, 301, 302, 299, 302, 300, 299, - 299, 300, 297, 300, 298, 297, 297, 298, 485, 298, 486, 485, - 485, 485, 487, 485, 487, 487, 487, 487, 303, 487, 303, 303, - 303, 303, 301, 303, 301, 301, 301, 301, 299, 301, 299, 299, - 299, 299, 297, 299, 297, 297, 297, 297, 485, 297, 485, 485, - 489, 490, 491, 490, 492, 491, 491, 492, 493, 492, 494, 493, - 493, 494, 495, 494, 496, 495, 495, 496, 489, 496, 490, 489, - 489, 489, 491, 489, 491, 491, 491, 491, 493, 491, 493, 493, - 493, 493, 495, 493, 495, 495, 495, 495, 489, 495, 489, 489, - 495, 496, 493, 496, 494, 493, 493, 494, 497, 494, 498, 497, - 497, 498, 499, 498, 500, 499, 499, 500, 501, 500, 502, 501, - 501, 502, 495, 502, 496, 495, 495, 495, 493, 495, 493, 493, - 493, 493, 497, 493, 497, 497, 497, 497, 499, 497, 499, 499, - 499, 499, 501, 499, 501, 501, 501, 501, 495, 501, 495, 495, - 503, 504, 499, 504, 500, 499, 499, 500, 497, 500, 498, 497, - 497, 498, 505, 498, 506, 505, 505, 506, 507, 506, 508, 507, - 507, 508, 503, 508, 504, 503, 503, 503, 499, 503, 499, 499, - 499, 499, 497, 499, 497, 497, 497, 497, 505, 497, 505, 505, - 505, 505, 507, 505, 507, 507, 507, 507, 503, 507, 503, 503, - 509, 510, 511, 510, 512, 511, 511, 512, 513, 512, 514, 513, - 513, 514, 515, 514, 516, 515, 515, 516, 517, 516, 518, 517, - 517, 518, 519, 518, 520, 519, 519, 520, 521, 520, 522, 521, - 521, 522, 509, 522, 510, 509, 509, 509, 511, 509, 511, 511, - 511, 511, 513, 511, 513, 513, 513, 513, 515, 513, 515, 515, - 515, 515, 517, 515, 517, 517, 517, 517, 519, 517, 519, 519, - 519, 519, 521, 519, 521, 521, 521, 521, 509, 521, 509, 509, - 523, 524, 525, 524, 526, 525, 525, 526, 527, 526, 528, 527, - 527, 528, 529, 528, 530, 529, 529, 530, 531, 530, 532, 531, - 531, 532, 533, 532, 534, 533, 533, 534, 535, 534, 536, 535, - 535, 536, 537, 536, 538, 537, 537, 538, 539, 538, 540, 539, - 539, 540, 541, 540, 542, 541, 541, 542, 543, 542, 544, 543, - 543, 544, 545, 544, 546, 545, 545, 546, 547, 546, 548, 547, - 547, 548, 523, 548, 524, 523, 523, 523, 525, 523, 525, 525, - 525, 525, 527, 525, 527, 527, 527, 527, 529, 527, 529, 529, - 529, 529, 531, 529, 531, 531, 531, 531, 533, 531, 533, 533, - 533, 533, 535, 533, 535, 535, 535, 535, 537, 535, 537, 537, - 537, 537, 539, 537, 539, 539, 539, 539, 541, 539, 541, 541, - 541, 541, 543, 541, 543, 543, 543, 543, 545, 543, 545, 545, - 545, 545, 547, 545, 547, 547, 547, 547, 523, 547, 523, 523, - 549, 550, 551, 550, 552, 551, 551, 552, 553, 552, 554, 553, - 553, 554, 555, 554, 556, 555, 555, 556, 114, 556, 115, 114, - 114, 115, 112, 115, 113, 112, 112, 113, 110, 113, 111, 110, - 110, 111, 557, 111, 558, 557, 557, 558, 559, 558, 560, 559, - 559, 560, 561, 560, 562, 561, 561, 562, 563, 562, 564, 563, - 563, 564, 565, 564, 566, 565, 565, 566, 567, 566, 568, 567, - 567, 568, 569, 568, 570, 569, 569, 570, 571, 570, 572, 571, - 571, 572, 573, 572, 574, 573, 573, 574, 549, 574, 550, 549, - 549, 549, 551, 549, 551, 551, 551, 551, 553, 551, 553, 553, - 553, 553, 555, 553, 555, 555, 555, 555, 114, 555, 114, 114, - 114, 114, 112, 114, 112, 112, 112, 112, 110, 112, 110, 110, - 110, 110, 557, 110, 557, 557, 557, 557, 559, 557, 559, 559, - 559, 559, 561, 559, 561, 561, 561, 561, 563, 561, 563, 563, - 563, 563, 565, 563, 565, 565, 565, 565, 567, 565, 567, 567, - 567, 567, 569, 567, 569, 569, 569, 569, 571, 569, 571, 571, - 571, 571, 573, 571, 573, 573, 573, 573, 549, 573, 549, 549, - 575, 576, 577, 576, 578, 577, 577, 578, 579, 578, 580, 579, - 579, 580, 581, 580, 582, 581, 581, 582, 583, 582, 584, 583, - 583, 584, 585, 584, 586, 585, 585, 586, 587, 586, 588, 587, - 587, 588, 589, 588, 590, 589, 589, 590, 591, 590, 592, 591, - 591, 592, 593, 592, 594, 593, 593, 594, 595, 594, 596, 595, - 595, 596, 597, 596, 598, 597, 597, 598, 599, 598, 600, 599, - 599, 600, 601, 600, 602, 601, 601, 602, 603, 602, 604, 603, - 603, 604, 605, 604, 532, 605, 605, 532, 606, 532, 530, 606, - 606, 530, 575, 530, 576, 575, 575, 575, 577, 575, 577, 577, - 577, 577, 579, 577, 579, 579, 579, 579, 581, 579, 581, 581, - 581, 581, 583, 581, 583, 583, 583, 583, 585, 583, 585, 585, - 585, 585, 587, 585, 587, 587, 587, 587, 589, 587, 589, 589, - 589, 589, 591, 589, 591, 591, 591, 591, 593, 591, 593, 593, - 593, 593, 595, 593, 595, 595, 595, 595, 597, 595, 597, 597, - 597, 597, 599, 597, 599, 599, 599, 599, 601, 599, 601, 601, - 601, 601, 603, 601, 603, 603, 603, 603, 605, 603, 605, 605, - 605, 605, 606, 605, 606, 606, 606, 606, 575, 606, 575, 575, - 607, 608, 609, 608, 610, 609, 609, 610, 611, 610, 612, 611, - 611, 612, 613, 612, 614, 613, 613, 614, 581, 614, 582, 581, - 581, 582, 579, 582, 580, 579, 579, 580, 607, 580, 608, 607, - 607, 607, 609, 607, 609, 609, 609, 609, 611, 609, 611, 611, - 611, 611, 613, 611, 613, 613, 613, 613, 581, 613, 581, 581, - 581, 581, 579, 581, 579, 579, 579, 579, 607, 579, 607, 607, - 615, 616, 617, 616, 618, 617, 617, 618, 619, 618, 510, 619, - 619, 510, 620, 510, 522, 620, 620, 522, 621, 522, 520, 621, - 621, 520, 615, 520, 616, 615, 615, 615, 617, 615, 617, 617, - 617, 617, 619, 617, 619, 619, 619, 619, 620, 619, 620, 620, - 620, 620, 621, 620, 621, 621, 621, 621, 615, 621, 615, 615, - 622, 623, 624, 623, 534, 624, 624, 534, 605, 534, 532, 605, - 605, 532, 603, 532, 604, 603, 603, 604, 622, 604, 623, 622, - 622, 622, 624, 622, 624, 624, 624, 624, 605, 624, 605, 605, - 605, 605, 603, 605, 603, 603, 603, 603, 622, 603, 622, 622, - 625, 626, 627, 626, 628, 627, 627, 628, 629, 628, 630, 629, - 629, 630, 631, 630, 632, 631, 631, 632, 625, 632, 626, 625, - 625, 625, 627, 625, 627, 627, 627, 627, 629, 627, 629, 629, - 629, 629, 631, 629, 631, 631, 631, 631, 625, 631, 625, 625, - 633, 634, 635, 634, 538, 635, 635, 538, 636, 538, 536, 636, - 636, 536, 624, 536, 534, 624, 624, 534, 622, 534, 623, 622, - 622, 623, 637, 623, 638, 637, 637, 638, 639, 638, 640, 639, - 639, 640, 633, 640, 634, 633, 633, 633, 635, 633, 635, 635, - 635, 635, 636, 635, 636, 636, 636, 636, 624, 636, 624, 624, - 624, 624, 622, 624, 622, 622, 622, 622, 637, 622, 637, 637, - 637, 637, 639, 637, 639, 639, 639, 639, 633, 639, 633, 633, - 641, 642, 643, 642, 644, 643, 643, 644, 645, 644, 646, 645, - 645, 646, 647, 646, 542, 647, 647, 542, 648, 542, 540, 648, - 648, 540, 649, 540, 650, 649, 649, 650, 651, 650, 652, 651, - 651, 652, 653, 652, 654, 653, 653, 654, 655, 654, 656, 655, - 655, 656, 641, 656, 642, 641, 641, 641, 643, 641, 643, 643, - 643, 643, 645, 643, 645, 645, 645, 645, 647, 645, 647, 647, - 647, 647, 648, 647, 648, 648, 648, 648, 649, 648, 649, 649, - 649, 649, 651, 649, 651, 651, 651, 651, 653, 651, 653, 653, - 653, 653, 655, 653, 655, 655, 655, 655, 641, 655, 641, 641, - 668, 669, 670, 669, 671, 670, 670, 671, 672, 671, 673, 672, - 672, 673, 674, 673, 675, 674, 674, 675, 668, 675, 669, 668, - 668, 668, 670, 668, 670, 670, 670, 670, 672, 670, 672, 672, - 672, 672, 674, 672, 674, 674, 674, 674, 668, 674, 668, 668, - 120, 121, 118, 121, 119, 118, 118, 119, 676, 119, 677, 676, - 676, 677, 674, 677, 675, 674, 674, 675, 672, 675, 673, 672, - 672, 673, 120, 673, 121, 120, 120, 120, 118, 120, 118, 118, - 118, 118, 676, 118, 676, 676, 676, 676, 674, 676, 674, 674, - 674, 674, 672, 674, 672, 672, 672, 672, 120, 672, 120, 120, - 670, 671, 668, 671, 669, 668, 668, 669, 678, 669, 679, 678, - 678, 679, 680, 679, 681, 680, 680, 681, 682, 681, 683, 682, - 682, 683, 684, 683, 685, 684, 684, 685, 686, 685, 687, 686, - 686, 687, 670, 687, 671, 670, 670, 670, 668, 670, 668, 668, - 668, 668, 678, 668, 678, 678, 678, 678, 680, 678, 680, 680, - 680, 680, 682, 680, 682, 682, 682, 682, 684, 682, 684, 684, - 684, 684, 686, 684, 686, 686, 686, 686, 670, 686, 670, 670, - 688, 689, 690, 689, 691, 690, 690, 691, 692, 691, 693, 692, - 692, 693, 694, 693, 695, 694, 694, 695, 696, 695, 697, 696, - 696, 697, 698, 697, 699, 698, 698, 699, 700, 699, 701, 700, - 700, 701, 702, 701, 703, 702, 702, 703, 704, 703, 705, 704, - 704, 705, 688, 705, 689, 688, 688, 688, 690, 688, 690, 690, - 690, 690, 692, 690, 692, 692, 692, 692, 694, 692, 694, 694, - 694, 694, 696, 694, 696, 696, 696, 696, 698, 696, 698, 698, - 698, 698, 700, 698, 700, 700, 700, 700, 702, 700, 702, 702, - 702, 702, 704, 702, 704, 704, 704, 704, 688, 704, 688, 688, - 692, 693, 706, 693, 707, 706, 706, 707, 708, 707, 709, 708, - 708, 709, 710, 709, 711, 710, 710, 711, 712, 711, 713, 712, - 712, 713, 714, 713, 715, 714, 714, 715, 716, 715, 717, 716, - 716, 717, 718, 717, 93, 718, 718, 93, 719, 93, 109, 719, - 719, 109, 720, 109, 103, 720, 720, 103, 721, 103, 101, 721, - 721, 101, 694, 101, 695, 694, 694, 695, 692, 695, 693, 692, - 692, 692, 706, 692, 706, 706, 706, 706, 708, 706, 708, 708, - 708, 708, 710, 708, 710, 710, 710, 710, 712, 710, 712, 712, - 712, 712, 714, 712, 714, 714, 714, 714, 716, 714, 716, 716, - 716, 716, 718, 716, 718, 718, 718, 718, 719, 718, 719, 719, - 719, 719, 720, 719, 720, 720, 720, 720, 721, 720, 721, 721, - 721, 721, 694, 721, 694, 694, 694, 694, 692, 694, 692, 692, - 722, 723, 724, 723, 725, 724, 724, 725, 726, 725, 727, 726, - 726, 727, 728, 727, 729, 728, 728, 729, 730, 729, 731, 730, - 730, 731, 732, 731, 733, 732, 732, 733, 734, 733, 735, 734, - 734, 735, 736, 735, 737, 736, 736, 737, 738, 737, 739, 738, - 738, 739, 740, 739, 741, 740, 740, 741, 742, 741, 743, 742, - 742, 743, 744, 743, 745, 744, 744, 745, 746, 745, 747, 746, - 746, 747, 748, 747, 749, 748, 748, 749, 750, 749, 751, 750, - 750, 751, 752, 751, 753, 752, 752, 753, 754, 753, 755, 754, - 754, 755, 756, 755, 757, 756, 756, 757, 722, 757, 723, 722, - 722, 722, 724, 722, 724, 724, 724, 724, 726, 724, 726, 726, - 726, 726, 728, 726, 728, 728, 728, 728, 730, 728, 730, 730, - 730, 730, 732, 730, 732, 732, 732, 732, 734, 732, 734, 734, - 734, 734, 736, 734, 736, 736, 736, 736, 738, 736, 738, 738, - 738, 738, 740, 738, 740, 740, 740, 740, 742, 740, 742, 742, - 742, 742, 744, 742, 744, 744, 744, 744, 746, 744, 746, 746, - 746, 746, 748, 746, 748, 748, 748, 748, 750, 748, 750, 750, - 750, 750, 752, 750, 752, 752, 752, 752, 754, 752, 754, 754, - 754, 754, 756, 754, 756, 756, 756, 756, 722, 756, 722, 722, - 758, 759, 760, 759, 761, 760, 760, 761, 762, 761, 763, 762, - 762, 763, 764, 763, 765, 764, 764, 765, 766, 765, 767, 766, - 766, 767, 768, 767, 769, 768, 768, 769, 770, 769, 771, 770, - 770, 771, 772, 771, 773, 772, 772, 773, 774, 773, 775, 774, - 774, 775, 758, 775, 759, 758, 758, 758, 760, 758, 760, 760, - 760, 760, 762, 760, 762, 762, 762, 762, 764, 762, 764, 764, - 764, 764, 766, 764, 766, 766, 766, 766, 768, 766, 768, 768, - 768, 768, 770, 768, 770, 770, 770, 770, 772, 770, 772, 772, - 772, 772, 774, 772, 774, 774, 774, 774, 758, 774, 758, 758, - 776, 777, 770, 777, 771, 770, 770, 771, 768, 771, 769, 768, - 768, 769, 778, 769, 779, 778, 778, 779, 780, 779, 781, 780, - 780, 781, 782, 781, 783, 782, 782, 783, 784, 783, 785, 784, - 784, 785, 776, 785, 777, 776, 776, 776, 770, 776, 770, 770, - 770, 770, 768, 770, 768, 768, 768, 768, 778, 768, 778, 778, - 778, 778, 780, 778, 780, 780, 780, 780, 782, 780, 782, 782, - 782, 782, 784, 782, 784, 784, 784, 784, 776, 784, 776, 776, - 776, 777, 784, 777, 785, 784, 784, 785, 782, 785, 783, 782, - 782, 783, 780, 783, 781, 780, 780, 781, 786, 781, 787, 786, - 786, 787, 788, 787, 789, 788, 788, 789, 790, 789, 791, 790, - 790, 791, 792, 791, 793, 792, 792, 793, 794, 793, 795, 794, - 794, 795, 796, 795, 797, 796, 796, 797, 776, 797, 777, 776, - 776, 776, 784, 776, 784, 784, 784, 784, 782, 784, 782, 782, - 782, 782, 780, 782, 780, 780, 780, 780, 786, 780, 786, 786, - 786, 786, 788, 786, 788, 788, 788, 788, 790, 788, 790, 790, - 790, 790, 792, 790, 792, 792, 792, 792, 794, 792, 794, 794, - 794, 794, 796, 794, 796, 796, 796, 796, 776, 796, 776, 776, - 792, 793, 790, 793, 791, 790, 790, 791, 788, 791, 789, 788, - 788, 789, 786, 789, 787, 786, 786, 787, 780, 787, 781, 780, - 780, 781, 778, 781, 779, 778, 778, 779, 768, 779, 769, 768, - 768, 769, 766, 769, 767, 766, 766, 767, 764, 767, 765, 764, - 764, 765, 762, 765, 763, 762, 762, 763, 760, 763, 761, 760, - 760, 761, 758, 761, 759, 758, 758, 759, 798, 759, 799, 798, - 798, 799, 800, 799, 801, 800, 800, 801, 802, 801, 803, 802, - 802, 803, 804, 803, 805, 804, 804, 805, 806, 805, 807, 806, - 806, 807, 808, 807, 809, 808, 808, 809, 810, 809, 811, 810, - 810, 811, 812, 811, 813, 812, 812, 813, 814, 813, 815, 814, - 814, 815, 816, 815, 817, 816, 816, 817, 818, 817, 819, 818, - 818, 819, 820, 819, 821, 820, 820, 821, 822, 821, 823, 822, - 822, 823, 824, 823, 825, 824, 824, 825, 826, 825, 827, 826, - 826, 827, 828, 827, 829, 828, 828, 829, 830, 829, 831, 830, - 830, 831, 832, 831, 833, 832, 832, 833, 834, 833, 835, 834, - 834, 835, 836, 835, 837, 836, 836, 837, 838, 837, 839, 838, - 838, 839, 840, 839, 841, 840, 840, 841, 842, 841, 843, 842, - 842, 843, 844, 843, 845, 844, 844, 845, 846, 845, 847, 846, - 846, 847, 848, 847, 849, 848, 848, 849, 728, 849, 729, 728, - 728, 729, 726, 729, 727, 726, 726, 727, 724, 727, 725, 724, - 724, 725, 722, 725, 723, 722, 722, 723, 850, 723, 851, 850, - 850, 851, 792, 851, 793, 792, 792, 792, 790, 792, 790, 790, - 790, 790, 788, 790, 788, 788, 788, 788, 786, 788, 786, 786, - 786, 786, 780, 786, 780, 780, 780, 780, 778, 780, 778, 778, - 778, 778, 768, 778, 768, 768, 768, 768, 766, 768, 766, 766, - 766, 766, 764, 766, 764, 764, 764, 764, 762, 764, 762, 762, - 762, 762, 760, 762, 760, 760, 760, 760, 758, 760, 758, 758, - 758, 758, 798, 758, 798, 798, 798, 798, 800, 798, 800, 800, - 800, 800, 802, 800, 802, 802, 802, 802, 804, 802, 804, 804, - 804, 804, 806, 804, 806, 806, 806, 806, 808, 806, 808, 808, - 808, 808, 810, 808, 810, 810, 810, 810, 812, 810, 812, 812, - 812, 812, 814, 812, 814, 814, 814, 814, 816, 814, 816, 816, - 816, 816, 818, 816, 818, 818, 818, 818, 820, 818, 820, 820, - 820, 820, 822, 820, 822, 822, 822, 822, 824, 822, 824, 824, - 824, 824, 826, 824, 826, 826, 826, 826, 828, 826, 828, 828, - 828, 828, 830, 828, 830, 830, 830, 830, 832, 830, 832, 832, - 832, 832, 834, 832, 834, 834, 834, 834, 836, 834, 836, 836, - 836, 836, 838, 836, 838, 838, 838, 838, 840, 838, 840, 840, - 840, 840, 842, 840, 842, 842, 842, 842, 844, 842, 844, 844, - 844, 844, 846, 844, 846, 846, 846, 846, 848, 846, 848, 848, - 848, 848, 728, 848, 728, 728, 728, 728, 726, 728, 726, 726, - 726, 726, 724, 726, 724, 724, 724, 724, 722, 724, 722, 722, - 722, 722, 850, 722, 850, 850, 850, 850, 792, 850, 792, 792, - 852, 853, 854, 853, 855, 854, 854, 855, 856, 855, 857, 856, - 856, 857, 858, 857, 859, 858, 858, 859, 860, 859, 861, 860, - 860, 861, 862, 861, 863, 862, 862, 863, 864, 863, 865, 864, - 864, 865, 866, 865, 867, 866, 866, 867, 868, 867, 869, 868, - 868, 869, 870, 869, 871, 870, 870, 871, 852, 871, 853, 852, - 852, 852, 854, 852, 854, 854, 854, 854, 856, 854, 856, 856, - 856, 856, 858, 856, 858, 858, 858, 858, 860, 858, 860, 860, - 860, 860, 862, 860, 862, 862, 862, 862, 864, 862, 864, 864, - 864, 864, 866, 864, 866, 866, 866, 866, 868, 866, 868, 868, - 868, 868, 870, 868, 870, 870, 870, 870, 852, 870, 852, 852, - 864, 865, 862, 865, 863, 862, 862, 863, 872, 863, 873, 872, - 872, 873, 874, 873, 875, 874, 874, 875, 876, 875, 877, 876, - 876, 877, 878, 877, 879, 878, 878, 879, 880, 879, 881, 880, - 880, 881, 882, 881, 883, 882, 882, 883, 884, 883, 885, 884, - 884, 885, 886, 885, 887, 886, 886, 887, 888, 887, 889, 888, - 888, 889, 864, 889, 865, 864, 864, 864, 862, 864, 862, 862, - 862, 862, 872, 862, 872, 872, 872, 872, 874, 872, 874, 874, - 874, 874, 876, 874, 876, 876, 876, 876, 878, 876, 878, 878, - 878, 878, 880, 878, 880, 880, 880, 880, 882, 880, 882, 882, - 882, 882, 884, 882, 884, 884, 884, 884, 886, 884, 886, 886, - 886, 886, 888, 886, 888, 888, 888, 888, 864, 888, 864, 864, - 890, 891, 892, 891, 893, 892, 892, 893, 894, 893, 895, 894, - 894, 895, 896, 895, 897, 896, 896, 897, 898, 897, 899, 898, - 898, 899, 890, 899, 891, 890, 890, 890, 892, 890, 892, 892, - 892, 892, 894, 892, 894, 894, 894, 894, 896, 894, 896, 896, - 896, 896, 898, 896, 898, 898, 898, 898, 890, 898, 890, 890, - 900, 901, 902, 901, 903, 902, 902, 903, 904, 903, 905, 904, - 904, 905, 906, 905, 907, 906, 906, 907, 900, 907, 901, 900, - 900, 900, 902, 900, 902, 902, 902, 902, 904, 902, 904, 904, - 904, 904, 906, 904, 906, 906, 906, 906, 900, 906, 900, 900, - 908, 909, 910, 909, 911, 910, 910, 911, 912, 911, 163, 912, - 912, 163, 913, 163, 161, 913, 913, 161, 908, 161, 909, 908, - 908, 908, 910, 908, 910, 910, 910, 910, 912, 910, 912, 912, - 912, 912, 913, 912, 913, 913, 913, 913, 908, 913, 908, 908, - 914, 394, 915, 394, 889, 915, 915, 889, 916, 889, 887, 916, - 916, 887, 917, 887, 396, 917, 917, 396, 914, 396, 394, 914, - 914, 914, 915, 914, 915, 915, 915, 915, 916, 915, 916, 916, - 916, 916, 917, 916, 917, 917, 917, 917, 914, 917, 914, 914, - 918, 919, 920, 919, 921, 920, 920, 921, 900, 921, 901, 900, - 900, 901, 906, 901, 907, 906, 906, 907, 918, 907, 919, 918, - 918, 918, 920, 918, 920, 920, 920, 920, 900, 920, 900, 900, - 900, 900, 906, 900, 906, 906, 906, 906, 918, 906, 918, 918, - 910, 911, 908, 911, 909, 908, 908, 909, 922, 909, 923, 922, - 922, 923, 924, 923, 925, 924, 924, 925, 926, 925, 927, 926, - 926, 927, 910, 927, 911, 910, 910, 910, 908, 910, 908, 908, - 908, 908, 922, 908, 922, 922, 922, 922, 924, 922, 924, 924, - 924, 924, 926, 924, 926, 926, 926, 926, 910, 926, 910, 910, - 928, 929, 930, 929, 931, 930, 930, 931, 932, 931, 933, 932, - 932, 933, 934, 933, 935, 934, 934, 935, 904, 935, 905, 904, - 904, 905, 902, 905, 903, 902, 902, 903, 860, 903, 861, 860, - 860, 861, 858, 861, 859, 858, 858, 859, 936, 859, 937, 936, - 936, 937, 928, 937, 929, 928, 928, 928, 930, 928, 930, 930, - 930, 930, 932, 930, 932, 932, 932, 932, 934, 932, 934, 934, - 934, 934, 904, 934, 904, 904, 904, 904, 902, 904, 902, 902, - 902, 902, 860, 902, 860, 860, 860, 860, 858, 860, 858, 858, - 858, 858, 936, 858, 936, 936, 936, 936, 928, 936, 928, 928, - 918, 919, 938, 919, 939, 938, 938, 939, 940, 939, 941, 940, - 940, 941, 942, 941, 943, 942, 942, 943, 944, 943, 945, 944, - 944, 945, 946, 945, 947, 946, 946, 947, 948, 947, 949, 948, - 948, 949, 950, 949, 951, 950, 950, 951, 952, 951, 953, 952, - 952, 953, 954, 953, 955, 954, 954, 955, 956, 955, 957, 956, - 956, 957, 958, 957, 959, 958, 958, 959, 960, 959, 961, 960, - 960, 961, 962, 961, 963, 962, 962, 963, 964, 963, 965, 964, - 964, 965, 966, 965, 967, 966, 966, 967, 920, 967, 921, 920, - 920, 921, 918, 921, 919, 918, 918, 918, 938, 918, 938, 938, - 938, 938, 940, 938, 940, 940, 940, 940, 942, 940, 942, 942, - 942, 942, 944, 942, 944, 944, 944, 944, 946, 944, 946, 946, - 946, 946, 948, 946, 948, 948, 948, 948, 950, 948, 950, 950, - 950, 950, 952, 950, 952, 952, 952, 952, 954, 952, 954, 954, - 954, 954, 956, 954, 956, 956, 956, 956, 958, 956, 958, 958, - 958, 958, 960, 958, 960, 960, 960, 960, 962, 960, 962, 962, - 962, 962, 964, 962, 964, 964, 964, 964, 966, 964, 966, 966, - 966, 966, 920, 966, 920, 920, 920, 920, 918, 920, 918, 918, - 968, 969, 928, 969, 929, 928, 928, 929, 936, 929, 937, 936, - 936, 937, 970, 937, 971, 970, 970, 971, 972, 971, 973, 972, - 972, 973, 974, 973, 975, 974, 974, 975, 968, 975, 969, 968, - 968, 968, 928, 968, 928, 928, 928, 928, 936, 928, 936, 936, - 936, 936, 970, 936, 970, 970, 970, 970, 972, 970, 972, 972, - 972, 972, 974, 972, 974, 974, 974, 974, 968, 974, 968, 968, - 974, 975, 972, 975, 973, 972, 972, 973, 970, 973, 971, 970, - 970, 971, 852, 971, 853, 852, 852, 853, 870, 853, 871, 870, - 870, 871, 868, 871, 869, 868, 868, 869, 866, 869, 867, 866, - 866, 867, 976, 867, 977, 976, 976, 977, 978, 977, 979, 978, - 978, 979, 391, 979, 392, 391, 391, 392, 389, 392, 390, 389, - 389, 390, 974, 390, 975, 974, 974, 974, 972, 974, 972, 972, - 972, 972, 970, 972, 970, 970, 970, 970, 852, 970, 852, 852, - 852, 852, 870, 852, 870, 870, 870, 870, 868, 870, 868, 868, - 868, 868, 866, 868, 866, 866, 866, 866, 976, 866, 976, 976, - 976, 976, 978, 976, 978, 978, 978, 978, 391, 978, 391, 391, - 391, 391, 389, 391, 389, 389, 389, 389, 974, 389, 974, 974, - 399, 400, 397, 400, 398, 397, 397, 398, 980, 398, 981, 980, - 980, 981, 982, 981, 983, 982, 982, 983, 984, 983, 891, 984, - 984, 891, 985, 891, 899, 985, 985, 899, 986, 899, 987, 986, - 986, 987, 988, 987, 989, 988, 988, 989, 399, 989, 400, 399, - 399, 399, 397, 399, 397, 397, 397, 397, 980, 397, 980, 980, - 980, 980, 982, 980, 982, 982, 982, 982, 984, 982, 984, 984, - 984, 984, 985, 984, 985, 985, 985, 985, 986, 985, 986, 986, - 986, 986, 988, 986, 988, 988, 988, 988, 399, 988, 399, 399, - 990, 330, 991, 330, 992, 991, 991, 992, 993, 992, 994, 993, - 993, 994, 995, 994, 996, 995, 995, 996, 997, 996, 998, 997, - 997, 998, 999, 998, 332, 999, 999, 332, 990, 332, 330, 990, - 990, 990, 991, 990, 991, 991, 991, 991, 993, 991, 993, 993, - 993, 993, 995, 993, 995, 995, 995, 995, 997, 995, 997, 997, - 997, 997, 999, 997, 999, 999, 999, 999, 990, 999, 990, 990, - 997, 998, 995, 998, 996, 995, 995, 996, 1000, 996, 1001, 1000, - 1000, 1001, 930, 1001, 931, 930, 930, 931, 928, 931, 929, 928, - 928, 929, 968, 929, 969, 968, 968, 969, 997, 969, 998, 997, - 997, 997, 995, 997, 995, 995, 995, 995, 1000, 995, 1000, 1000, - 1000, 1000, 930, 1000, 930, 930, 930, 930, 928, 930, 928, 928, - 928, 928, 968, 928, 968, 968, 968, 968, 997, 968, 997, 997, - 1002, 1003, 1004, 1003, 1005, 1004, 1004, 1005, 1006, 1005, 1007, 1006, - 1006, 1007, 1008, 1007, 1009, 1008, 1008, 1009, 1010, 1009, 1011, 1010, - 1010, 1011, 1012, 1011, 1013, 1012, 1012, 1013, 1014, 1013, 1015, 1014, - 1014, 1015, 1016, 1015, 1017, 1016, 1016, 1017, 1018, 1017, 1019, 1018, - 1018, 1019, 1020, 1019, 1021, 1020, 1020, 1021, 1022, 1021, 1023, 1022, - 1022, 1023, 1024, 1023, 1025, 1024, 1024, 1025, 1026, 1025, 1027, 1026, - 1026, 1027, 1028, 1027, 1029, 1028, 1028, 1029, 1030, 1029, 1031, 1030, - 1030, 1031, 1002, 1031, 1003, 1002, 1002, 1002, 1004, 1002, 1004, 1004, - 1004, 1004, 1006, 1004, 1006, 1006, 1006, 1006, 1008, 1006, 1008, 1008, - 1008, 1008, 1010, 1008, 1010, 1010, 1010, 1010, 1012, 1010, 1012, 1012, - 1012, 1012, 1014, 1012, 1014, 1014, 1014, 1014, 1016, 1014, 1016, 1016, - 1016, 1016, 1018, 1016, 1018, 1018, 1018, 1018, 1020, 1018, 1020, 1020, - 1020, 1020, 1022, 1020, 1022, 1022, 1022, 1022, 1024, 1022, 1024, 1024, - 1024, 1024, 1026, 1024, 1026, 1026, 1026, 1026, 1028, 1026, 1028, 1028, - 1028, 1028, 1030, 1028, 1030, 1030, 1030, 1030, 1002, 1030, 1002, 1002, - 1032, 1033, 1034, 1033, 1035, 1034, 1034, 1035, 1036, 1035, 612, 1036, - 1036, 612, 1037, 612, 610, 1037, 1037, 610, 1032, 610, 1033, 1032, - 1032, 1032, 1034, 1032, 1034, 1034, 1034, 1034, 1036, 1034, 1036, 1036, - 1036, 1036, 1037, 1036, 1037, 1037, 1037, 1037, 1032, 1037, 1032, 1032, - 1037, 610, 1038, 610, 1039, 1038, 1038, 1039, 1040, 1039, 1041, 1040, - 1040, 1041, 1032, 1041, 1033, 1032, 1032, 1033, 1037, 1033, 610, 1037, - 1037, 1037, 1038, 1037, 1038, 1038, 1038, 1038, 1040, 1038, 1040, 1040, - 1040, 1040, 1032, 1040, 1032, 1032, 1032, 1032, 1037, 1032, 1037, 1037, - 609, 610, 607, 610, 608, 607, 607, 608, 1042, 608, 1043, 1042, - 1042, 1043, 1044, 1043, 1045, 1044, 1044, 1045, 1046, 1045, 1047, 1046, - 1046, 1047, 1048, 1047, 1039, 1048, 1048, 1039, 609, 1039, 610, 609, - 609, 609, 607, 609, 607, 607, 607, 607, 1042, 607, 1042, 1042, - 1042, 1042, 1044, 1042, 1044, 1044, 1044, 1044, 1046, 1044, 1046, 1046, - 1046, 1046, 1048, 1046, 1048, 1048, 1048, 1048, 609, 1048, 609, 609, - 1049, 1050, 1051, 1050, 1052, 1051, 1051, 1052, 1053, 1052, 1054, 1053, - 1053, 1054, 1055, 1054, 1056, 1055, 1055, 1056, 1057, 1056, 1058, 1057, - 1057, 1058, 1059, 1058, 1060, 1059, 1059, 1060, 1049, 1060, 1050, 1049, - 1049, 1049, 1051, 1049, 1051, 1051, 1051, 1051, 1053, 1051, 1053, 1053, - 1053, 1053, 1055, 1053, 1055, 1055, 1055, 1055, 1057, 1055, 1057, 1057, - 1057, 1057, 1059, 1057, 1059, 1059, 1059, 1059, 1049, 1059, 1049, 1049, - 1049, 1050, 1059, 1050, 1060, 1059, 1059, 1060, 1057, 1060, 1058, 1057, - 1057, 1058, 1008, 1058, 1009, 1008, 1008, 1009, 1006, 1009, 1007, 1006, - 1006, 1007, 1004, 1007, 1005, 1004, 1004, 1005, 1002, 1005, 1003, 1002, - 1002, 1003, 1061, 1003, 1062, 1061, 1061, 1062, 1049, 1062, 1050, 1049, - 1049, 1049, 1059, 1049, 1059, 1059, 1059, 1059, 1057, 1059, 1057, 1057, - 1057, 1057, 1008, 1057, 1008, 1008, 1008, 1008, 1006, 1008, 1006, 1006, - 1006, 1006, 1004, 1006, 1004, 1004, 1004, 1004, 1002, 1004, 1002, 1002, - 1002, 1002, 1061, 1002, 1061, 1061, 1061, 1061, 1049, 1061, 1049, 1049, - 1063, 1064, 1065, 1064, 1066, 1065, 1065, 1066, 1067, 1066, 1068, 1067, - 1067, 1068, 1069, 1068, 1070, 1069, 1069, 1070, 1071, 1070, 1072, 1071, - 1071, 1072, 1073, 1072, 1074, 1073, 1073, 1074, 1075, 1074, 1076, 1075, - 1075, 1076, 1077, 1076, 1078, 1077, 1077, 1078, 1079, 1078, 1080, 1079, - 1079, 1080, 1081, 1080, 1082, 1081, 1081, 1082, 1083, 1082, 1084, 1083, - 1083, 1084, 1063, 1084, 1064, 1063, 1063, 1063, 1065, 1063, 1065, 1065, - 1065, 1065, 1067, 1065, 1067, 1067, 1067, 1067, 1069, 1067, 1069, 1069, - 1069, 1069, 1071, 1069, 1071, 1071, 1071, 1071, 1073, 1071, 1073, 1073, - 1073, 1073, 1075, 1073, 1075, 1075, 1075, 1075, 1077, 1075, 1077, 1077, - 1077, 1077, 1079, 1077, 1079, 1079, 1079, 1079, 1081, 1079, 1081, 1081, - 1081, 1081, 1083, 1081, 1083, 1083, 1083, 1083, 1063, 1083, 1063, 1063, - 1085, 1086, 1087, 1086, 1088, 1087, 1087, 1088, 1083, 1088, 1084, 1083, - 1083, 1084, 1081, 1084, 1082, 1081, 1081, 1082, 1089, 1082, 1090, 1089, - 1089, 1090, 1085, 1090, 1086, 1085, 1085, 1085, 1087, 1085, 1087, 1087, - 1087, 1087, 1083, 1087, 1083, 1083, 1083, 1083, 1081, 1083, 1081, 1081, - 1081, 1081, 1089, 1081, 1089, 1089, 1089, 1089, 1085, 1089, 1085, 1085, - 1044, 1045, 1042, 1045, 1043, 1042, 1042, 1043, 1091, 1043, 1092, 1091, - 1091, 1092, 1093, 1092, 1094, 1093, 1093, 1094, 1095, 1094, 1096, 1095, - 1095, 1096, 1097, 1096, 1098, 1097, 1097, 1098, 1099, 1098, 1100, 1099, - 1099, 1100, 1101, 1100, 1102, 1101, 1101, 1102, 1103, 1102, 1104, 1103, - 1103, 1104, 1087, 1104, 1088, 1087, 1087, 1088, 1085, 1088, 1086, 1085, - 1085, 1086, 1105, 1086, 1106, 1105, 1105, 1106, 1107, 1106, 1108, 1107, - 1107, 1108, 1109, 1108, 1110, 1109, 1109, 1110, 1044, 1110, 1045, 1044, - 1044, 1044, 1042, 1044, 1042, 1042, 1042, 1042, 1091, 1042, 1091, 1091, - 1091, 1091, 1093, 1091, 1093, 1093, 1093, 1093, 1095, 1093, 1095, 1095, - 1095, 1095, 1097, 1095, 1097, 1097, 1097, 1097, 1099, 1097, 1099, 1099, - 1099, 1099, 1101, 1099, 1101, 1101, 1101, 1101, 1103, 1101, 1103, 1103, - 1103, 1103, 1087, 1103, 1087, 1087, 1087, 1087, 1085, 1087, 1085, 1085, - 1085, 1085, 1105, 1085, 1105, 1105, 1105, 1105, 1107, 1105, 1107, 1107, - 1107, 1107, 1109, 1107, 1109, 1109, 1109, 1109, 1044, 1109, 1044, 1044, - 1065, 1066, 1063, 1066, 1064, 1063, 1063, 1064, 1111, 1064, 1112, 1111, - 1111, 1112, 1113, 1112, 1114, 1113, 1113, 1114, 1115, 1114, 1116, 1115, - 1115, 1116, 1117, 1116, 1118, 1117, 1117, 1118, 1119, 1118, 1120, 1119, - 1119, 1120, 1065, 1120, 1066, 1065, 1065, 1065, 1063, 1065, 1063, 1063, - 1063, 1063, 1111, 1063, 1111, 1111, 1111, 1111, 1113, 1111, 1113, 1113, - 1113, 1113, 1115, 1113, 1115, 1115, 1115, 1115, 1117, 1115, 1117, 1117, - 1117, 1117, 1119, 1117, 1119, 1119, 1119, 1119, 1065, 1119, 1065, 1065, - 1121, 1122, 1123, 1122, 1124, 1123, 1123, 1124, 1075, 1124, 1076, 1075, - 1075, 1076, 1073, 1076, 1074, 1073, 1073, 1074, 1125, 1074, 1126, 1125, - 1125, 1126, 1127, 1126, 1128, 1127, 1127, 1128, 1129, 1128, 1130, 1129, - 1129, 1130, 1115, 1130, 1116, 1115, 1115, 1116, 1113, 1116, 1114, 1113, - 1113, 1114, 1121, 1114, 1122, 1121, 1121, 1121, 1123, 1121, 1123, 1123, - 1123, 1123, 1075, 1123, 1075, 1075, 1075, 1075, 1073, 1075, 1073, 1073, - 1073, 1073, 1125, 1073, 1125, 1125, 1125, 1125, 1127, 1125, 1127, 1127, - 1127, 1127, 1129, 1127, 1129, 1129, 1129, 1129, 1115, 1129, 1115, 1115, - 1115, 1115, 1113, 1115, 1113, 1113, 1113, 1113, 1121, 1113, 1121, 1121, - 1123, 1124, 1121, 1124, 1122, 1121, 1121, 1122, 1055, 1122, 1056, 1055, - 1055, 1056, 1053, 1056, 1054, 1053, 1053, 1054, 1123, 1054, 1124, 1123, - 1123, 1123, 1121, 1123, 1121, 1121, 1121, 1121, 1055, 1121, 1055, 1055, - 1055, 1055, 1053, 1055, 1053, 1053, 1053, 1053, 1123, 1053, 1123, 1123, - 1131, 1132, 1133, 1132, 1134, 1133, 1133, 1134, 1135, 1134, 1136, 1135, - 1135, 1136, 1137, 1136, 1138, 1137, 1137, 1138, 1139, 1138, 1140, 1139, - 1139, 1140, 1141, 1140, 1142, 1141, 1141, 1142, 1131, 1142, 1132, 1131, - 1131, 1131, 1133, 1131, 1133, 1133, 1133, 1133, 1135, 1133, 1135, 1135, - 1135, 1135, 1137, 1135, 1137, 1137, 1137, 1137, 1139, 1137, 1139, 1139, - 1139, 1139, 1141, 1139, 1141, 1141, 1141, 1141, 1131, 1141, 1131, 1131, - 1143, 1144, 1141, 1144, 1142, 1141, 1141, 1142, 1139, 1142, 1140, 1139, - 1139, 1140, 1145, 1140, 1146, 1145, 1145, 1146, 1147, 1146, 1148, 1147, - 1147, 1148, 1149, 1148, 1150, 1149, 1149, 1150, 1151, 1150, 1152, 1151, - 1151, 1152, 1153, 1152, 1154, 1153, 1153, 1154, 1155, 1154, 1156, 1155, - 1155, 1156, 1143, 1156, 1144, 1143, 1143, 1143, 1141, 1143, 1141, 1141, - 1141, 1141, 1139, 1141, 1139, 1139, 1139, 1139, 1145, 1139, 1145, 1145, - 1145, 1145, 1147, 1145, 1147, 1147, 1147, 1147, 1149, 1147, 1149, 1149, - 1149, 1149, 1151, 1149, 1151, 1151, 1151, 1151, 1153, 1151, 1153, 1153, - 1153, 1153, 1155, 1153, 1155, 1155, 1155, 1155, 1143, 1155, 1143, 1143, - 409, 410, 407, 410, 408, 407, 407, 408, 1157, 408, 1158, 1157, - 1157, 1158, 1159, 1158, 1160, 1159, 1159, 1160, 1135, 1160, 1136, 1135, - 1135, 1136, 1133, 1136, 1134, 1133, 1133, 1134, 1161, 1134, 1162, 1161, - 1161, 1162, 409, 1162, 410, 409, 409, 409, 407, 409, 407, 407, - 407, 407, 1157, 407, 1157, 1157, 1157, 1157, 1159, 1157, 1159, 1159, - 1159, 1159, 1135, 1159, 1135, 1135, 1135, 1135, 1133, 1135, 1133, 1133, - 1133, 1133, 1161, 1133, 1161, 1161, 1161, 1161, 409, 1161, 409, 409, - 1163, 1164, 1165, 1164, 1166, 1165, 1165, 1166, 1167, 1166, 1168, 1167, - 1167, 1168, 1169, 1168, 1170, 1169, 1169, 1170, 1171, 1170, 1172, 1171, - 1171, 1172, 1173, 1172, 1174, 1173, 1173, 1174, 1175, 1174, 1176, 1175, - 1175, 1176, 1177, 1176, 1178, 1177, 1177, 1178, 1179, 1178, 1180, 1179, - 1179, 1180, 1181, 1180, 1182, 1181, 1181, 1182, 1183, 1182, 1184, 1183, - 1183, 1184, 1185, 1184, 1186, 1185, 1185, 1186, 1187, 1186, 1188, 1187, - 1187, 1188, 1189, 1188, 1190, 1189, 1189, 1190, 1191, 1190, 1192, 1191, - 1191, 1192, 1193, 1192, 1194, 1193, 1193, 1194, 1195, 1194, 1196, 1195, - 1195, 1196, 1197, 1196, 1198, 1197, 1197, 1198, 1199, 1198, 1200, 1199, - 1199, 1200, 1201, 1200, 1202, 1201, 1201, 1202, 1203, 1202, 1204, 1203, - 1203, 1204, 1205, 1204, 1206, 1205, 1205, 1206, 1207, 1206, 1208, 1207, - 1207, 1208, 1209, 1208, 1210, 1209, 1209, 1210, 1211, 1210, 1212, 1211, - 1211, 1212, 1213, 1212, 1214, 1213, 1213, 1214, 1215, 1214, 1216, 1215, - 1215, 1216, 1217, 1216, 1218, 1217, 1217, 1218, 1219, 1218, 1220, 1219, - 1219, 1220, 1221, 1220, 1222, 1221, 1221, 1222, 1223, 1222, 1224, 1223, - 1223, 1224, 1225, 1224, 1226, 1225, 1225, 1226, 1227, 1226, 1228, 1227, - 1227, 1228, 1229, 1228, 1230, 1229, 1229, 1230, 1231, 1230, 1232, 1231, - 1231, 1232, 1233, 1232, 1234, 1233, 1233, 1234, 1235, 1234, 1236, 1235, - 1235, 1236, 1237, 1236, 1238, 1237, 1237, 1238, 1239, 1238, 1240, 1239, - 1239, 1240, 1241, 1240, 1242, 1241, 1241, 1242, 1243, 1242, 1244, 1243, - 1243, 1244, 1245, 1244, 1246, 1245, 1245, 1246, 1247, 1246, 1248, 1247, - 1247, 1248, 1249, 1248, 1250, 1249, 1249, 1250, 1251, 1250, 1252, 1251, - 1251, 1252, 1253, 1252, 1254, 1253, 1253, 1254, 1255, 1254, 1256, 1255, - 1255, 1256, 1257, 1256, 1258, 1257, 1257, 1258, 1259, 1258, 1260, 1259, - 1259, 1260, 1261, 1260, 1262, 1261, 1261, 1262, 1263, 1262, 1264, 1263, - 1263, 1264, 1265, 1264, 1266, 1265, 1265, 1266, 1267, 1266, 1268, 1267, - 1267, 1268, 1269, 1268, 1270, 1269, 1269, 1270, 1271, 1270, 1272, 1271, - 1271, 1272, 1273, 1272, 1274, 1273, 1273, 1274, 1275, 1274, 1276, 1275, - 1275, 1276, 1277, 1276, 1278, 1277, 1277, 1278, 1279, 1278, 1280, 1279, - 1279, 1280, 1281, 1280, 1282, 1281, 1281, 1282, 1283, 1282, 1284, 1283, - 1283, 1284, 1285, 1284, 1286, 1285, 1285, 1286, 1287, 1286, 1288, 1287, - 1287, 1288, 1289, 1288, 1290, 1289, 1289, 1290, 1291, 1290, 1292, 1291, - 1291, 1292, 1293, 1292, 1294, 1293, 1293, 1294, 1295, 1294, 1296, 1295, - 1295, 1296, 1163, 1296, 1164, 1163, 1163, 1163, 1165, 1163, 1165, 1165, - 1165, 1165, 1167, 1165, 1167, 1167, 1167, 1167, 1169, 1167, 1169, 1169, - 1169, 1169, 1171, 1169, 1171, 1171, 1171, 1171, 1173, 1171, 1173, 1173, - 1173, 1173, 1175, 1173, 1175, 1175, 1175, 1175, 1177, 1175, 1177, 1177, - 1177, 1177, 1179, 1177, 1179, 1179, 1179, 1179, 1181, 1179, 1181, 1181, - 1181, 1181, 1183, 1181, 1183, 1183, 1183, 1183, 1185, 1183, 1185, 1185, - 1185, 1185, 1187, 1185, 1187, 1187, 1187, 1187, 1189, 1187, 1189, 1189, - 1189, 1189, 1191, 1189, 1191, 1191, 1191, 1191, 1193, 1191, 1193, 1193, - 1193, 1193, 1195, 1193, 1195, 1195, 1195, 1195, 1197, 1195, 1197, 1197, - 1197, 1197, 1199, 1197, 1199, 1199, 1199, 1199, 1201, 1199, 1201, 1201, - 1201, 1201, 1203, 1201, 1203, 1203, 1203, 1203, 1205, 1203, 1205, 1205, - 1205, 1205, 1207, 1205, 1207, 1207, 1207, 1207, 1209, 1207, 1209, 1209, - 1209, 1209, 1211, 1209, 1211, 1211, 1211, 1211, 1213, 1211, 1213, 1213, - 1213, 1213, 1215, 1213, 1215, 1215, 1215, 1215, 1217, 1215, 1217, 1217, - 1217, 1217, 1219, 1217, 1219, 1219, 1219, 1219, 1221, 1219, 1221, 1221, - 1221, 1221, 1223, 1221, 1223, 1223, 1223, 1223, 1225, 1223, 1225, 1225, - 1225, 1225, 1227, 1225, 1227, 1227, 1227, 1227, 1229, 1227, 1229, 1229, - 1229, 1229, 1231, 1229, 1231, 1231, 1231, 1231, 1233, 1231, 1233, 1233, - 1233, 1233, 1235, 1233, 1235, 1235, 1235, 1235, 1237, 1235, 1237, 1237, - 1237, 1237, 1239, 1237, 1239, 1239, 1239, 1239, 1241, 1239, 1241, 1241, - 1241, 1241, 1243, 1241, 1243, 1243, 1243, 1243, 1245, 1243, 1245, 1245, - 1245, 1245, 1247, 1245, 1247, 1247, 1247, 1247, 1249, 1247, 1249, 1249, - 1249, 1249, 1251, 1249, 1251, 1251, 1251, 1251, 1253, 1251, 1253, 1253, - 1253, 1253, 1255, 1253, 1255, 1255, 1255, 1255, 1257, 1255, 1257, 1257, - 1257, 1257, 1259, 1257, 1259, 1259, 1259, 1259, 1261, 1259, 1261, 1261, - 1261, 1261, 1263, 1261, 1263, 1263, 1263, 1263, 1265, 1263, 1265, 1265, - 1265, 1265, 1267, 1265, 1267, 1267, 1267, 1267, 1269, 1267, 1269, 1269, - 1269, 1269, 1271, 1269, 1271, 1271, 1271, 1271, 1273, 1271, 1273, 1273, - 1273, 1273, 1275, 1273, 1275, 1275, 1275, 1275, 1277, 1275, 1277, 1277, - 1277, 1277, 1279, 1277, 1279, 1279, 1279, 1279, 1281, 1279, 1281, 1281, - 1281, 1281, 1283, 1281, 1283, 1283, 1283, 1283, 1285, 1283, 1285, 1285, - 1285, 1285, 1287, 1285, 1287, 1287, 1287, 1287, 1289, 1287, 1289, 1289, - 1289, 1289, 1291, 1289, 1291, 1291, 1291, 1291, 1293, 1291, 1293, 1293, - 1293, 1293, 1295, 1293, 1295, 1295, 1295, 1295, 1163, 1295, 1163, 1163, - 1297, 1298, 1299, 1298, 1300, 1299, 1299, 1300, 1301, 1300, 1302, 1301, - 1301, 1302, 1303, 1302, 1304, 1303, 1303, 1304, 1305, 1304, 1306, 1305, - 1305, 1306, 1307, 1306, 1308, 1307, 1307, 1308, 1309, 1308, 1310, 1309, - 1309, 1310, 1311, 1310, 1312, 1311, 1311, 1312, 1313, 1312, 1314, 1313, - 1313, 1314, 1315, 1314, 1316, 1315, 1315, 1316, 1297, 1316, 1298, 1297, - 1297, 1297, 1299, 1297, 1299, 1299, 1299, 1299, 1301, 1299, 1301, 1301, - 1301, 1301, 1303, 1301, 1303, 1303, 1303, 1303, 1305, 1303, 1305, 1305, - 1305, 1305, 1307, 1305, 1307, 1307, 1307, 1307, 1309, 1307, 1309, 1309, - 1309, 1309, 1311, 1309, 1311, 1311, 1311, 1311, 1313, 1311, 1313, 1313, - 1313, 1313, 1315, 1313, 1315, 1315, 1315, 1315, 1297, 1315, 1297, 1297, - 1317, 1318, 1319, 1318, 1320, 1319, 1319, 1320, 1321, 1320, 1322, 1321, - 1321, 1322, 1323, 1322, 1324, 1323, 1323, 1324, 1317, 1324, 1318, 1317, - 1317, 1317, 1319, 1317, 1319, 1319, 1319, 1319, 1321, 1319, 1321, 1321, - 1321, 1321, 1323, 1321, 1323, 1323, 1323, 1323, 1317, 1323, 1317, 1317, - 1325, 1324, 1326, 1324, 1322, 1326, 1326, 1322, 1327, 1322, 1328, 1327, - 1327, 1328, 1329, 1328, 1330, 1329, 1329, 1330, 1331, 1330, 1332, 1331, - 1331, 1332, 1325, 1332, 1324, 1325, 1325, 1325, 1326, 1325, 1326, 1326, - 1326, 1326, 1327, 1326, 1327, 1327, 1327, 1327, 1329, 1327, 1329, 1329, - 1329, 1329, 1331, 1329, 1331, 1331, 1331, 1331, 1325, 1331, 1325, 1325, - 1333, 1334, 1335, 1334, 1336, 1335, 1335, 1336, 1337, 1336, 1338, 1337, - 1337, 1338, 1339, 1338, 1306, 1339, 1339, 1306, 1340, 1306, 1304, 1340, - 1340, 1304, 1341, 1304, 1342, 1341, 1341, 1342, 1333, 1342, 1334, 1333, - 1333, 1333, 1335, 1333, 1335, 1335, 1335, 1335, 1337, 1335, 1337, 1337, - 1337, 1337, 1339, 1337, 1339, 1339, 1339, 1339, 1340, 1339, 1340, 1340, - 1340, 1340, 1341, 1340, 1341, 1341, 1341, 1341, 1333, 1341, 1333, 1333, - 1331, 1332, 1329, 1332, 1330, 1329, 1329, 1330, 1327, 1330, 1328, 1327, - 1327, 1328, 1343, 1328, 1344, 1343, 1343, 1344, 1345, 1344, 1346, 1345, - 1345, 1346, 1347, 1346, 1348, 1347, 1347, 1348, 1349, 1348, 1350, 1349, - 1349, 1350, 1351, 1350, 1352, 1351, 1351, 1352, 1331, 1352, 1332, 1331, - 1331, 1331, 1329, 1331, 1329, 1329, 1329, 1329, 1327, 1329, 1327, 1327, - 1327, 1327, 1343, 1327, 1343, 1343, 1343, 1343, 1345, 1343, 1345, 1345, - 1345, 1345, 1347, 1345, 1347, 1347, 1347, 1347, 1349, 1347, 1349, 1349, - 1349, 1349, 1351, 1349, 1351, 1351, 1351, 1351, 1331, 1351, 1331, 1331, - 1531, 1532, 1533, 1532, 1534, 1533, 1533, 1534, 1535, 1534, 1536, 1535, - 1535, 1536, 1537, 1536, 1538, 1537, 1537, 1538, 1539, 1538, 1540, 1539, - 1539, 1540, 1541, 1540, 1542, 1541, 1541, 1542, 1543, 1542, 1544, 1543, - 1543, 1544, 1545, 1544, 1546, 1545, 1545, 1546, 1547, 1546, 1548, 1547, - 1547, 1548, 1549, 1548, 1550, 1549, 1549, 1550, 1531, 1550, 1532, 1531, - 1531, 1531, 1533, 1531, 1533, 1533, 1533, 1533, 1535, 1533, 1535, 1535, - 1535, 1535, 1537, 1535, 1537, 1537, 1537, 1537, 1539, 1537, 1539, 1539, - 1539, 1539, 1541, 1539, 1541, 1541, 1541, 1541, 1543, 1541, 1543, 1543, - 1543, 1543, 1545, 1543, 1545, 1545, 1545, 1545, 1547, 1545, 1547, 1547, - 1547, 1547, 1549, 1547, 1549, 1549, 1549, 1549, 1531, 1549, 1531, 1531, - 1551, 1552, 1553, 1552, 1554, 1553, 1553, 1554, 1555, 1554, 1556, 1555, - 1555, 1556, 1557, 1556, 1558, 1557, 1557, 1558, 1559, 1558, 1560, 1559, - 1559, 1560, 1551, 1560, 1552, 1551, 1551, 1551, 1553, 1551, 1553, 1553, - 1553, 1553, 1555, 1553, 1555, 1555, 1555, 1555, 1557, 1555, 1557, 1557, - 1557, 1557, 1559, 1557, 1559, 1559, 1559, 1559, 1551, 1559, 1551, 1551, - 1561, 1540, 1562, 1540, 1563, 1562, 1562, 1563, 1564, 1563, 1565, 1564, - 1564, 1565, 1566, 1565, 1567, 1566, 1566, 1567, 1568, 1567, 1569, 1568, - 1568, 1569, 1570, 1569, 1571, 1570, 1570, 1571, 1572, 1571, 1542, 1572, - 1572, 1542, 1561, 1542, 1540, 1561, 1561, 1561, 1562, 1561, 1562, 1562, - 1562, 1562, 1564, 1562, 1564, 1564, 1564, 1564, 1566, 1564, 1566, 1566, - 1566, 1566, 1568, 1566, 1568, 1568, 1568, 1568, 1570, 1568, 1570, 1570, - 1570, 1570, 1572, 1570, 1572, 1572, 1572, 1572, 1561, 1572, 1561, 1561, - 1553, 1554, 1551, 1554, 1552, 1551, 1551, 1552, 1573, 1552, 1574, 1573, - 1573, 1574, 1575, 1574, 1576, 1575, 1575, 1576, 1577, 1576, 1578, 1577, - 1577, 1578, 1568, 1578, 1569, 1568, 1568, 1569, 1566, 1569, 1567, 1566, - 1566, 1567, 1579, 1567, 1580, 1579, 1579, 1580, 1581, 1580, 1582, 1581, - 1581, 1582, 1553, 1582, 1554, 1553, 1553, 1553, 1551, 1553, 1551, 1551, - 1551, 1551, 1573, 1551, 1573, 1573, 1573, 1573, 1575, 1573, 1575, 1575, - 1575, 1575, 1577, 1575, 1577, 1577, 1577, 1577, 1568, 1577, 1568, 1568, - 1568, 1568, 1566, 1568, 1566, 1566, 1566, 1566, 1579, 1566, 1579, 1579, - 1579, 1579, 1581, 1579, 1581, 1581, 1581, 1581, 1553, 1581, 1553, 1553, - 1583, 1584, 1585, 1584, 1586, 1585, 1585, 1586, 1587, 1586, 1588, 1587, - 1587, 1588, 1589, 1588, 1590, 1589, 1589, 1590, 1591, 1590, 1592, 1591, - 1591, 1592, 1593, 1592, 1594, 1593, 1593, 1594, 1595, 1594, 1596, 1595, - 1595, 1596, 1597, 1596, 1598, 1597, 1597, 1598, 1583, 1598, 1584, 1583, - 1583, 1583, 1585, 1583, 1585, 1585, 1585, 1585, 1587, 1585, 1587, 1587, - 1587, 1587, 1589, 1587, 1589, 1589, 1589, 1589, 1591, 1589, 1591, 1591, - 1591, 1591, 1593, 1591, 1593, 1593, 1593, 1593, 1595, 1593, 1595, 1595, - 1595, 1595, 1597, 1595, 1597, 1597, 1597, 1597, 1583, 1597, 1583, 1583, - 1559, 1560, 1583, 1560, 1584, 1583, 1583, 1584, 1597, 1584, 1598, 1597, - 1597, 1598, 1595, 1598, 1596, 1595, 1595, 1596, 1593, 1596, 1594, 1593, - 1593, 1594, 1599, 1594, 1600, 1599, 1599, 1600, 1575, 1600, 1576, 1575, - 1575, 1576, 1573, 1576, 1574, 1573, 1573, 1574, 1551, 1574, 1552, 1551, - 1551, 1552, 1559, 1552, 1560, 1559, 1559, 1559, 1583, 1559, 1583, 1583, - 1583, 1583, 1597, 1583, 1597, 1597, 1597, 1597, 1595, 1597, 1595, 1595, - 1595, 1595, 1593, 1595, 1593, 1593, 1593, 1593, 1599, 1593, 1599, 1599, - 1599, 1599, 1575, 1599, 1575, 1575, 1575, 1575, 1573, 1575, 1573, 1573, - 1573, 1573, 1551, 1573, 1551, 1551, 1551, 1551, 1559, 1551, 1559, 1559, - 1601, 1602, 1603, 1602, 1604, 1603, 1603, 1604, 1605, 1604, 1606, 1605, - 1605, 1606, 1607, 1606, 1608, 1607, 1607, 1608, 1609, 1608, 1610, 1609, - 1609, 1610, 1611, 1610, 1538, 1611, 1611, 1538, 1612, 1538, 1536, 1612, - 1612, 1536, 1613, 1536, 1534, 1613, 1613, 1534, 1614, 1534, 1615, 1614, - 1614, 1615, 1616, 1615, 1617, 1616, 1616, 1617, 1618, 1617, 1619, 1618, - 1618, 1619, 1620, 1619, 1621, 1620, 1620, 1621, 1622, 1621, 1623, 1622, - 1622, 1623, 1624, 1623, 1625, 1624, 1624, 1625, 1626, 1625, 1627, 1626, - 1626, 1627, 1628, 1627, 1629, 1628, 1628, 1629, 1601, 1629, 1602, 1601, - 1601, 1601, 1603, 1601, 1603, 1603, 1603, 1603, 1605, 1603, 1605, 1605, - 1605, 1605, 1607, 1605, 1607, 1607, 1607, 1607, 1609, 1607, 1609, 1609, - 1609, 1609, 1611, 1609, 1611, 1611, 1611, 1611, 1612, 1611, 1612, 1612, - 1612, 1612, 1613, 1612, 1613, 1613, 1613, 1613, 1614, 1613, 1614, 1614, - 1614, 1614, 1616, 1614, 1616, 1616, 1616, 1616, 1618, 1616, 1618, 1618, - 1618, 1618, 1620, 1618, 1620, 1620, 1620, 1620, 1622, 1620, 1622, 1622, - 1622, 1622, 1624, 1622, 1624, 1624, 1624, 1624, 1626, 1624, 1626, 1626, - 1626, 1626, 1628, 1626, 1628, 1628, 1628, 1628, 1601, 1628, 1601, 1601, - 1630, 1631, 1632, 1631, 1633, 1632, 1632, 1633, 1634, 1633, 1635, 1634, - 1634, 1635, 1636, 1635, 1627, 1636, 1636, 1627, 1637, 1627, 1625, 1637, - 1637, 1625, 1638, 1625, 1623, 1638, 1638, 1623, 1639, 1623, 1621, 1639, - 1639, 1621, 1640, 1621, 1619, 1640, 1640, 1619, 1630, 1619, 1631, 1630, - 1630, 1630, 1632, 1630, 1632, 1632, 1632, 1632, 1634, 1632, 1634, 1634, - 1634, 1634, 1636, 1634, 1636, 1636, 1636, 1636, 1637, 1636, 1637, 1637, - 1637, 1637, 1638, 1637, 1638, 1638, 1638, 1638, 1639, 1638, 1639, 1639, - 1639, 1639, 1640, 1639, 1640, 1640, 1640, 1640, 1630, 1640, 1630, 1630, - 1641, 1642, 1643, 1642, 1644, 1643, 1643, 1644, 1645, 1644, 1646, 1645, - 1645, 1646, 1647, 1646, 1648, 1647, 1647, 1648, 1649, 1648, 1650, 1649, - 1649, 1650, 1651, 1650, 1652, 1651, 1651, 1652, 1653, 1652, 1654, 1653, - 1653, 1654, 1655, 1654, 1656, 1655, 1655, 1656, 1657, 1656, 1658, 1657, - 1657, 1658, 1659, 1658, 1660, 1659, 1659, 1660, 1641, 1660, 1642, 1641, - 1641, 1641, 1643, 1641, 1643, 1643, 1643, 1643, 1645, 1643, 1645, 1645, - 1645, 1645, 1647, 1645, 1647, 1647, 1647, 1647, 1649, 1647, 1649, 1649, - 1649, 1649, 1651, 1649, 1651, 1651, 1651, 1651, 1653, 1651, 1653, 1653, - 1653, 1653, 1655, 1653, 1655, 1655, 1655, 1655, 1657, 1655, 1657, 1657, - 1657, 1657, 1659, 1657, 1659, 1659, 1659, 1659, 1641, 1659, 1641, 1641, - 1653, 1654, 1661, 1654, 1662, 1661, 1661, 1662, 221, 1662, 222, 221, - 221, 222, 219, 222, 220, 219, 219, 220, 1663, 220, 1664, 1663, - 1663, 1664, 1665, 1664, 1666, 1665, 1665, 1666, 211, 1666, 212, 211, - 211, 212, 209, 212, 210, 209, 209, 210, 1667, 210, 1668, 1667, - 1667, 1668, 1655, 1668, 1656, 1655, 1655, 1656, 1653, 1656, 1654, 1653, - 1653, 1653, 1661, 1653, 1661, 1661, 1661, 1661, 221, 1661, 221, 221, - 221, 221, 219, 221, 219, 219, 219, 219, 1663, 219, 1663, 1663, - 1663, 1663, 1665, 1663, 1665, 1665, 1665, 1665, 211, 1665, 211, 211, - 211, 211, 209, 211, 209, 209, 209, 209, 1667, 209, 1667, 1667, - 1667, 1667, 1655, 1667, 1655, 1655, 1655, 1655, 1653, 1655, 1653, 1653, - 1641, 1642, 1659, 1642, 1660, 1659, 1659, 1660, 1669, 1660, 1670, 1669, - 1669, 1670, 1671, 1670, 1672, 1671, 1671, 1672, 1673, 1672, 1674, 1673, - 1673, 1674, 1675, 1674, 1676, 1675, 1675, 1676, 1649, 1676, 1650, 1649, - 1649, 1650, 1647, 1650, 1648, 1647, 1647, 1648, 1677, 1648, 1678, 1677, - 1677, 1678, 1679, 1678, 1680, 1679, 1679, 1680, 1641, 1680, 1642, 1641, - 1641, 1641, 1659, 1641, 1659, 1659, 1659, 1659, 1669, 1659, 1669, 1669, - 1669, 1669, 1671, 1669, 1671, 1671, 1671, 1671, 1673, 1671, 1673, 1673, - 1673, 1673, 1675, 1673, 1675, 1675, 1675, 1675, 1649, 1675, 1649, 1649, - 1649, 1649, 1647, 1649, 1647, 1647, 1647, 1647, 1677, 1647, 1677, 1677, - 1677, 1677, 1679, 1677, 1679, 1679, 1679, 1679, 1641, 1679, 1641, 1641, - 1673, 1674, 1671, 1674, 1672, 1671, 1671, 1672, 1681, 1672, 1682, 1681, - 1681, 1682, 1683, 1682, 1684, 1683, 1683, 1684, 1685, 1684, 1686, 1685, - 1685, 1686, 1687, 1686, 1688, 1687, 1687, 1688, 1689, 1688, 1690, 1689, - 1689, 1690, 1691, 1690, 1692, 1691, 1691, 1692, 1693, 1692, 1694, 1693, - 1693, 1694, 1695, 1694, 1696, 1695, 1695, 1696, 1673, 1696, 1674, 1673, - 1673, 1673, 1671, 1673, 1671, 1671, 1671, 1671, 1681, 1671, 1681, 1681, - 1681, 1681, 1683, 1681, 1683, 1683, 1683, 1683, 1685, 1683, 1685, 1685, - 1685, 1685, 1687, 1685, 1687, 1687, 1687, 1687, 1689, 1687, 1689, 1689, - 1689, 1689, 1691, 1689, 1691, 1691, 1691, 1691, 1693, 1691, 1693, 1693, - 1693, 1693, 1695, 1693, 1695, 1695, 1695, 1695, 1673, 1695, 1673, 1673, - 1697, 1698, 1699, 1698, 1700, 1699, 1699, 1700, 1701, 1700, 1702, 1701, - 1701, 1702, 1703, 1702, 1704, 1703, 1703, 1704, 1705, 1704, 1706, 1705, - 1705, 1706, 1707, 1706, 1708, 1707, 1707, 1708, 1709, 1708, 1710, 1709, - 1709, 1710, 1711, 1710, 1712, 1711, 1711, 1712, 1713, 1712, 1714, 1713, - 1713, 1714, 1715, 1714, 1716, 1715, 1715, 1716, 1717, 1716, 1718, 1717, - 1717, 1718, 1719, 1718, 1720, 1719, 1719, 1720, 1721, 1720, 1722, 1721, - 1721, 1722, 1723, 1722, 1724, 1723, 1723, 1724, 1725, 1724, 1726, 1725, - 1725, 1726, 1727, 1726, 1728, 1727, 1727, 1728, 1729, 1728, 1730, 1729, - 1729, 1730, 1697, 1730, 1698, 1697, 1697, 1697, 1699, 1697, 1699, 1699, - 1699, 1699, 1701, 1699, 1701, 1701, 1701, 1701, 1703, 1701, 1703, 1703, - 1703, 1703, 1705, 1703, 1705, 1705, 1705, 1705, 1707, 1705, 1707, 1707, - 1707, 1707, 1709, 1707, 1709, 1709, 1709, 1709, 1711, 1709, 1711, 1711, - 1711, 1711, 1713, 1711, 1713, 1713, 1713, 1713, 1715, 1713, 1715, 1715, - 1715, 1715, 1717, 1715, 1717, 1717, 1717, 1717, 1719, 1717, 1719, 1719, - 1719, 1719, 1721, 1719, 1721, 1721, 1721, 1721, 1723, 1721, 1723, 1723, - 1723, 1723, 1725, 1723, 1725, 1725, 1725, 1725, 1727, 1725, 1727, 1727, - 1727, 1727, 1729, 1727, 1729, 1729, 1729, 1729, 1697, 1729, 1697, 1697, - 1731, 1724, 1732, 1724, 1722, 1732, 1732, 1722, 1733, 1722, 1720, 1733, - 1733, 1720, 1734, 1720, 1718, 1734, 1734, 1718, 1731, 1718, 1724, 1731, - 1731, 1731, 1732, 1731, 1732, 1732, 1732, 1732, 1733, 1732, 1733, 1733, - 1733, 1733, 1734, 1733, 1734, 1734, 1734, 1734, 1731, 1734, 1731, 1731, - 1735, 1714, 1736, 1714, 1712, 1736, 1736, 1712, 1737, 1712, 1710, 1737, - 1737, 1710, 1738, 1710, 1708, 1738, 1738, 1708, 1735, 1708, 1714, 1735, - 1735, 1735, 1736, 1735, 1736, 1736, 1736, 1736, 1737, 1736, 1737, 1737, - 1737, 1737, 1738, 1737, 1738, 1738, 1738, 1738, 1735, 1738, 1735, 1735, - 1739, 1706, 1740, 1706, 1704, 1740, 1740, 1704, 1741, 1704, 1702, 1741, - 1741, 1702, 1742, 1702, 1700, 1742, 1742, 1700, 1743, 1700, 1744, 1743, - 1743, 1744, 1745, 1744, 1746, 1745, 1745, 1746, 1739, 1746, 1706, 1739, - 1739, 1739, 1740, 1739, 1740, 1740, 1740, 1740, 1741, 1740, 1741, 1741, - 1741, 1741, 1742, 1741, 1742, 1742, 1742, 1742, 1743, 1742, 1743, 1743, - 1743, 1743, 1745, 1743, 1745, 1745, 1745, 1745, 1739, 1745, 1739, 1739, - 1747, 1748, 1749, 1748, 1750, 1749, 1749, 1750, 1751, 1750, 1752, 1751, - 1751, 1752, 1753, 1752, 1754, 1753, 1753, 1754, 1755, 1754, 1756, 1755, - 1755, 1756, 1757, 1756, 1758, 1757, 1757, 1758, 1759, 1758, 1760, 1759, - 1759, 1760, 1761, 1760, 1762, 1761, 1761, 1762, 1763, 1762, 1764, 1763, - 1763, 1764, 1765, 1764, 1766, 1765, 1765, 1766, 1693, 1766, 1694, 1693, - 1693, 1694, 1691, 1694, 1692, 1691, 1691, 1692, 1685, 1692, 1686, 1685, - 1685, 1686, 1683, 1686, 1684, 1683, 1683, 1684, 1767, 1684, 1768, 1767, - 1767, 1768, 1769, 1768, 1770, 1769, 1769, 1770, 1747, 1770, 1748, 1747, - 1747, 1747, 1749, 1747, 1749, 1749, 1749, 1749, 1751, 1749, 1751, 1751, - 1751, 1751, 1753, 1751, 1753, 1753, 1753, 1753, 1755, 1753, 1755, 1755, - 1755, 1755, 1757, 1755, 1757, 1757, 1757, 1757, 1759, 1757, 1759, 1759, - 1759, 1759, 1761, 1759, 1761, 1761, 1761, 1761, 1763, 1761, 1763, 1763, - 1763, 1763, 1765, 1763, 1765, 1765, 1765, 1765, 1693, 1765, 1693, 1693, - 1693, 1693, 1691, 1693, 1691, 1691, 1691, 1691, 1685, 1691, 1685, 1685, - 1685, 1685, 1683, 1685, 1683, 1683, 1683, 1683, 1767, 1683, 1767, 1767, - 1767, 1767, 1769, 1767, 1769, 1769, 1769, 1769, 1747, 1769, 1747, 1747, - 1753, 1754, 1771, 1754, 1772, 1771, 1771, 1772, 1773, 1772, 1774, 1773, - 1773, 1774, 1775, 1774, 1776, 1775, 1775, 1776, 1747, 1776, 1748, 1747, - 1747, 1748, 1769, 1748, 1770, 1769, 1769, 1770, 1777, 1770, 1778, 1777, - 1777, 1778, 1779, 1778, 1780, 1779, 1779, 1780, 1781, 1780, 1782, 1781, - 1781, 1782, 1783, 1782, 1784, 1783, 1783, 1784, 1785, 1784, 1786, 1785, - 1785, 1786, 1787, 1786, 1788, 1787, 1787, 1788, 1763, 1788, 1764, 1763, - 1763, 1764, 1761, 1764, 1762, 1761, 1761, 1762, 1789, 1762, 1790, 1789, - 1789, 1790, 1791, 1790, 1792, 1791, 1791, 1792, 1793, 1792, 1794, 1793, - 1793, 1794, 1755, 1794, 1756, 1755, 1755, 1756, 1753, 1756, 1754, 1753, - 1753, 1753, 1771, 1753, 1771, 1771, 1771, 1771, 1773, 1771, 1773, 1773, - 1773, 1773, 1775, 1773, 1775, 1775, 1775, 1775, 1747, 1775, 1747, 1747, - 1747, 1747, 1769, 1747, 1769, 1769, 1769, 1769, 1777, 1769, 1777, 1777, - 1777, 1777, 1779, 1777, 1779, 1779, 1779, 1779, 1781, 1779, 1781, 1781, - 1781, 1781, 1783, 1781, 1783, 1783, 1783, 1783, 1785, 1783, 1785, 1785, - 1785, 1785, 1787, 1785, 1787, 1787, 1787, 1787, 1763, 1787, 1763, 1763, - 1763, 1763, 1761, 1763, 1761, 1761, 1761, 1761, 1789, 1761, 1789, 1789, - 1789, 1789, 1791, 1789, 1791, 1791, 1791, 1791, 1793, 1791, 1793, 1793, - 1793, 1793, 1755, 1793, 1755, 1755, 1755, 1755, 1753, 1755, 1753, 1753, - 1795, 1796, 1797, 1796, 1798, 1797, 1797, 1798, 1799, 1798, 1800, 1799, - 1799, 1800, 1801, 1800, 1802, 1801, 1801, 1802, 1795, 1802, 1796, 1795, - 1795, 1795, 1797, 1795, 1797, 1797, 1797, 1797, 1799, 1797, 1799, 1799, - 1799, 1799, 1801, 1799, 1801, 1801, 1801, 1801, 1795, 1801, 1795, 1795, - 1803, 1804, 1805, 1804, 1806, 1805, 1805, 1806, 1807, 1806, 1808, 1807, - 1807, 1808, 1809, 1808, 1810, 1809, 1809, 1810, 1811, 1810, 1812, 1811, - 1811, 1812, 1803, 1812, 1804, 1803, 1803, 1803, 1805, 1803, 1805, 1805, - 1805, 1805, 1807, 1805, 1807, 1807, 1807, 1807, 1809, 1807, 1809, 1809, - 1809, 1809, 1811, 1809, 1811, 1811, 1811, 1811, 1803, 1811, 1803, 1803, - 1813, 1814, 1815, 1814, 1816, 1815, 1815, 1816, 1817, 1816, 1818, 1817, - 1817, 1818, 1819, 1818, 1810, 1819, 1819, 1810, 1820, 1810, 1808, 1820, - 1820, 1808, 1813, 1808, 1814, 1813, 1813, 1813, 1815, 1813, 1815, 1815, - 1815, 1815, 1817, 1815, 1817, 1817, 1817, 1817, 1819, 1817, 1819, 1819, - 1819, 1819, 1820, 1819, 1820, 1820, 1820, 1820, 1813, 1820, 1813, 1813, - 1815, 1816, 1813, 1816, 1814, 1813, 1813, 1814, 1797, 1814, 1798, 1797, - 1797, 1798, 1795, 1798, 1796, 1795, 1795, 1796, 1821, 1796, 1822, 1821, - 1821, 1822, 1815, 1822, 1816, 1815, 1815, 1815, 1813, 1815, 1813, 1813, - 1813, 1813, 1797, 1813, 1797, 1797, 1797, 1797, 1795, 1797, 1795, 1795, - 1795, 1795, 1821, 1795, 1821, 1821, 1821, 1821, 1815, 1821, 1815, 1815, - 225, 226, 1823, 226, 1824, 1823, 1823, 1824, 1825, 1824, 1826, 1825, - 1825, 1826, 1827, 1826, 1828, 1827, 1827, 1828, 1829, 1828, 1830, 1829, - 1829, 1830, 1831, 1830, 1832, 1831, 1831, 1832, 227, 1832, 228, 227, - 227, 228, 225, 228, 226, 225, 225, 225, 1823, 225, 1823, 1823, - 1823, 1823, 1825, 1823, 1825, 1825, 1825, 1825, 1827, 1825, 1827, 1827, - 1827, 1827, 1829, 1827, 1829, 1829, 1829, 1829, 1831, 1829, 1831, 1831, - 1831, 1831, 227, 1831, 227, 227, 227, 227, 225, 227, 225, 225, - 1803, 1804, 1833, 1804, 1834, 1833, 1833, 1834, 1835, 1834, 1836, 1835, - 1835, 1836, 1837, 1836, 1744, 1837, 1837, 1744, 1699, 1744, 1700, 1699, - 1699, 1700, 1697, 1700, 1698, 1697, 1697, 1698, 1838, 1698, 1839, 1838, - 1838, 1839, 1805, 1839, 1806, 1805, 1805, 1806, 1803, 1806, 1804, 1803, - 1803, 1803, 1833, 1803, 1833, 1833, 1833, 1833, 1835, 1833, 1835, 1835, - 1835, 1835, 1837, 1835, 1837, 1837, 1837, 1837, 1699, 1837, 1699, 1699, - 1699, 1699, 1697, 1699, 1697, 1697, 1697, 1697, 1838, 1697, 1838, 1838, - 1838, 1838, 1805, 1838, 1805, 1805, 1805, 1805, 1803, 1805, 1803, 1803, - 1840, 1841, 1842, 1841, 1843, 1842, 1842, 1843, 1844, 1843, 1845, 1844, - 1844, 1845, 1846, 1845, 1847, 1846, 1846, 1847, 1848, 1847, 1849, 1848, - 1848, 1849, 1850, 1849, 1851, 1850, 1850, 1851, 1852, 1851, 1853, 1852, - 1852, 1853, 1854, 1853, 1855, 1854, 1854, 1855, 1856, 1855, 1857, 1856, - 1856, 1857, 1858, 1857, 1859, 1858, 1858, 1859, 1860, 1859, 1861, 1860, - 1860, 1861, 1862, 1861, 1863, 1862, 1862, 1863, 1840, 1863, 1841, 1840, - 1840, 1840, 1842, 1840, 1842, 1842, 1842, 1842, 1844, 1842, 1844, 1844, - 1844, 1844, 1846, 1844, 1846, 1846, 1846, 1846, 1848, 1846, 1848, 1848, - 1848, 1848, 1850, 1848, 1850, 1850, 1850, 1850, 1852, 1850, 1852, 1852, - 1852, 1852, 1854, 1852, 1854, 1854, 1854, 1854, 1856, 1854, 1856, 1856, - 1856, 1856, 1858, 1856, 1858, 1858, 1858, 1858, 1860, 1858, 1860, 1860, - 1860, 1860, 1862, 1860, 1862, 1862, 1862, 1862, 1840, 1862, 1840, 1840, - 1864, 1865, 1866, 1865, 1867, 1866, 1866, 1867, 1868, 1867, 1869, 1868, - 1868, 1869, 1870, 1869, 1871, 1870, 1870, 1871, 1864, 1871, 1865, 1864, - 1864, 1864, 1866, 1864, 1866, 1866, 1866, 1866, 1868, 1866, 1868, 1868, - 1868, 1868, 1870, 1868, 1870, 1870, 1870, 1870, 1864, 1870, 1864, 1864, - 1872, 1873, 1874, 1873, 1875, 1874, 1874, 1875, 1876, 1875, 1877, 1876, - 1876, 1877, 1878, 1877, 1879, 1878, 1878, 1879, 1872, 1879, 1873, 1872, - 1872, 1872, 1874, 1872, 1874, 1874, 1874, 1874, 1876, 1874, 1876, 1876, - 1876, 1876, 1878, 1876, 1878, 1878, 1878, 1878, 1872, 1878, 1872, 1872, - 1880, 1881, 1882, 1881, 1883, 1882, 1882, 1883, 1884, 1883, 1885, 1884, - 1884, 1885, 1886, 1885, 348, 1886, 1886, 348, 1887, 348, 346, 1887, - 1887, 346, 1880, 346, 1881, 1880, 1880, 1880, 1882, 1880, 1882, 1882, - 1882, 1882, 1884, 1882, 1884, 1884, 1884, 1884, 1886, 1884, 1886, 1886, - 1886, 1886, 1887, 1886, 1887, 1887, 1887, 1887, 1880, 1887, 1880, 1880, - 1864, 1865, 1876, 1865, 1877, 1876, 1876, 1877, 1874, 1877, 1875, 1874, - 1874, 1875, 1888, 1875, 1889, 1888, 1888, 1889, 1866, 1889, 1867, 1866, - 1866, 1867, 1864, 1867, 1865, 1864, 1864, 1864, 1876, 1864, 1876, 1876, - 1876, 1876, 1874, 1876, 1874, 1874, 1874, 1874, 1888, 1874, 1888, 1888, - 1888, 1888, 1866, 1888, 1866, 1866, 1866, 1866, 1864, 1866, 1864, 1864, - 1848, 1849, 1890, 1849, 1891, 1890, 1890, 1891, 1892, 1891, 1893, 1892, - 1892, 1893, 267, 1893, 268, 267, 267, 268, 265, 268, 266, 265, - 265, 266, 1852, 266, 1853, 1852, 1852, 1853, 1850, 1853, 1851, 1850, - 1850, 1851, 1848, 1851, 1849, 1848, 1848, 1848, 1890, 1848, 1890, 1890, - 1890, 1890, 1892, 1890, 1892, 1892, 1892, 1892, 267, 1892, 267, 267, - 267, 267, 265, 267, 265, 265, 265, 265, 1852, 265, 1852, 1852, - 1852, 1852, 1850, 1852, 1850, 1850, 1850, 1850, 1848, 1850, 1848, 1848, - 1880, 1881, 1872, 1881, 1873, 1872, 1872, 1873, 1878, 1873, 1879, 1878, - 1878, 1879, 1894, 1879, 1895, 1894, 1894, 1895, 1896, 1895, 1897, 1896, - 1896, 1897, 1842, 1897, 1843, 1842, 1842, 1843, 1840, 1843, 1841, 1840, - 1840, 1841, 1898, 1841, 1899, 1898, 1898, 1899, 1882, 1899, 1883, 1882, - 1882, 1883, 1880, 1883, 1881, 1880, 1880, 1880, 1872, 1880, 1872, 1872, - 1872, 1872, 1878, 1872, 1878, 1878, 1878, 1878, 1894, 1878, 1894, 1894, - 1894, 1894, 1896, 1894, 1896, 1896, 1896, 1896, 1842, 1896, 1842, 1842, - 1842, 1842, 1840, 1842, 1840, 1840, 1840, 1840, 1898, 1840, 1898, 1898, - 1898, 1898, 1882, 1898, 1882, 1882, 1882, 1882, 1880, 1882, 1880, 1880, - 1900, 1901, 1902, 1901, 1903, 1902, 1902, 1903, 1904, 1903, 1905, 1904, - 1904, 1905, 1906, 1905, 1907, 1906, 1906, 1907, 1908, 1907, 1909, 1908, - 1908, 1909, 1910, 1909, 1911, 1910, 1910, 1911, 1900, 1911, 1901, 1900, - 1900, 1900, 1902, 1900, 1902, 1902, 1902, 1902, 1904, 1902, 1904, 1904, - 1904, 1904, 1906, 1904, 1906, 1906, 1906, 1906, 1908, 1906, 1908, 1908, - 1908, 1908, 1910, 1908, 1910, 1910, 1910, 1910, 1900, 1910, 1900, 1900, - 1912, 1913, 1914, 1913, 1915, 1914, 1914, 1915, 1904, 1915, 1905, 1904, - 1904, 1905, 1902, 1905, 1903, 1902, 1902, 1903, 1900, 1903, 1901, 1900, - 1900, 1901, 1916, 1901, 1917, 1916, 1916, 1917, 1912, 1917, 1913, 1912, - 1912, 1912, 1914, 1912, 1914, 1914, 1914, 1914, 1904, 1914, 1904, 1904, - 1904, 1904, 1902, 1904, 1902, 1902, 1902, 1902, 1900, 1902, 1900, 1900, - 1900, 1900, 1916, 1900, 1916, 1916, 1916, 1916, 1912, 1916, 1912, 1912, - 1918, 1919, 1920, 1919, 1921, 1920, 1920, 1921, 1922, 1921, 1923, 1922, - 1922, 1923, 1914, 1923, 1915, 1914, 1914, 1915, 1912, 1915, 1913, 1912, - 1912, 1913, 1916, 1913, 1917, 1916, 1916, 1917, 1924, 1917, 1925, 1924, - 1924, 1925, 1926, 1925, 1927, 1926, 1926, 1927, 1918, 1927, 1919, 1918, - 1918, 1918, 1920, 1918, 1920, 1920, 1920, 1920, 1922, 1920, 1922, 1922, - 1922, 1922, 1914, 1922, 1914, 1914, 1914, 1914, 1912, 1914, 1912, 1912, - 1912, 1912, 1916, 1912, 1916, 1916, 1916, 1916, 1924, 1916, 1924, 1924, - 1924, 1924, 1926, 1924, 1926, 1926, 1926, 1926, 1918, 1926, 1918, 1918, - 1920, 1921, 1918, 1921, 1919, 1918, 1918, 1919, 1926, 1919, 1927, 1926, - 1926, 1927, 1924, 1927, 1925, 1924, 1924, 1925, 1928, 1925, 1929, 1928, - 1928, 1929, 1930, 1929, 1931, 1930, 1930, 1931, 1932, 1931, 1933, 1932, - 1932, 1933, 1934, 1933, 1935, 1934, 1934, 1935, 1936, 1935, 1937, 1936, - 1936, 1937, 1938, 1937, 1939, 1938, 1938, 1939, 1920, 1939, 1921, 1920, - 1920, 1920, 1918, 1920, 1918, 1918, 1918, 1918, 1926, 1918, 1926, 1926, - 1926, 1926, 1924, 1926, 1924, 1924, 1924, 1924, 1928, 1924, 1928, 1928, - 1928, 1928, 1930, 1928, 1930, 1930, 1930, 1930, 1932, 1930, 1932, 1932, - 1932, 1932, 1934, 1932, 1934, 1934, 1934, 1934, 1936, 1934, 1936, 1936, - 1936, 1936, 1938, 1936, 1938, 1938, 1938, 1938, 1920, 1938, 1920, 1920, - 1940, 1941, 1942, 1941, 1943, 1942, 1942, 1943, 1944, 1943, 1945, 1944, - 1944, 1945, 1946, 1945, 1947, 1946, 1946, 1947, 1948, 1947, 1949, 1948, - 1948, 1949, 1950, 1949, 1951, 1950, 1950, 1951, 1940, 1951, 1941, 1940, - 1940, 1940, 1942, 1940, 1942, 1942, 1942, 1942, 1944, 1942, 1944, 1944, - 1944, 1944, 1946, 1944, 1946, 1946, 1946, 1946, 1948, 1946, 1948, 1948, - 1948, 1948, 1950, 1948, 1950, 1950, 1950, 1950, 1940, 1950, 1940, 1940, - 1948, 1949, 1946, 1949, 1947, 1946, 1946, 1947, 1944, 1947, 1945, 1944, - 1944, 1945, 1952, 1945, 1953, 1952, 1952, 1953, 1954, 1953, 1955, 1954, - 1954, 1955, 1956, 1955, 1957, 1956, 1956, 1957, 1958, 1957, 1959, 1958, - 1958, 1959, 1960, 1959, 1961, 1960, 1960, 1961, 1934, 1961, 1935, 1934, - 1934, 1935, 1932, 1935, 1933, 1932, 1932, 1933, 1930, 1933, 1931, 1930, - 1930, 1931, 1928, 1931, 1929, 1928, 1928, 1929, 1948, 1929, 1949, 1948, - 1948, 1948, 1946, 1948, 1946, 1946, 1946, 1946, 1944, 1946, 1944, 1944, - 1944, 1944, 1952, 1944, 1952, 1952, 1952, 1952, 1954, 1952, 1954, 1954, - 1954, 1954, 1956, 1954, 1956, 1956, 1956, 1956, 1958, 1956, 1958, 1958, - 1958, 1958, 1960, 1958, 1960, 1960, 1960, 1960, 1934, 1960, 1934, 1934, - 1934, 1934, 1932, 1934, 1932, 1932, 1932, 1932, 1930, 1932, 1930, 1930, - 1930, 1930, 1928, 1930, 1928, 1928, 1928, 1928, 1948, 1928, 1948, 1948, - 283, 284, 1962, 284, 308, 1962, 1962, 308, 1963, 308, 1964, 1963, - 1963, 1964, 1965, 1964, 1966, 1965, 1965, 1966, 1967, 1966, 1968, 1967, - 1967, 1968, 285, 1968, 286, 285, 285, 286, 283, 286, 284, 283, - 283, 283, 1962, 283, 1962, 1962, 1962, 1962, 1963, 1962, 1963, 1963, - 1963, 1963, 1965, 1963, 1965, 1965, 1965, 1965, 1967, 1965, 1967, 1967, - 1967, 1967, 285, 1967, 285, 285, 285, 285, 283, 285, 283, 283, - 289, 290, 1969, 290, 1970, 1969, 1969, 1970, 1971, 1970, 1972, 1971, - 1971, 1972, 1973, 1972, 1974, 1973, 1973, 1974, 1975, 1974, 1976, 1975, - 1975, 1976, 1977, 1976, 1978, 1977, 1977, 1978, 1979, 1978, 306, 1979, - 1979, 306, 281, 306, 282, 281, 281, 282, 289, 282, 290, 289, - 289, 289, 1969, 289, 1969, 1969, 1969, 1969, 1971, 1969, 1971, 1971, - 1971, 1971, 1973, 1971, 1973, 1973, 1973, 1973, 1975, 1973, 1975, 1975, - 1975, 1975, 1977, 1975, 1977, 1977, 1977, 1977, 1979, 1977, 1979, 1979, - 1979, 1979, 281, 1979, 281, 281, 281, 281, 289, 281, 289, 289, - 1533, 1534, 1531, 1534, 1532, 1531, 1531, 1532, 1632, 1532, 1633, 1632, - 1632, 1633, 1630, 1633, 1631, 1630, 1630, 1631, 1640, 1631, 1619, 1640, - 1640, 1619, 1980, 1619, 1617, 1980, 1980, 1617, 1981, 1617, 1615, 1981, - 1981, 1615, 1533, 1615, 1534, 1533, 1533, 1533, 1531, 1533, 1531, 1531, - 1531, 1531, 1632, 1531, 1632, 1632, 1632, 1632, 1630, 1632, 1630, 1630, - 1630, 1630, 1640, 1630, 1640, 1640, 1640, 1640, 1980, 1640, 1980, 1980, - 1980, 1980, 1981, 1980, 1981, 1981, 1981, 1981, 1533, 1981, 1533, 1533, - 511, 512, 509, 512, 510, 509, 509, 510, 1982, 510, 618, 1982, - 1982, 618, 1983, 618, 616, 1983, 1983, 616, 1984, 616, 1985, 1984, - 1984, 1985, 1986, 1985, 1987, 1986, 1986, 1987, 625, 1987, 626, 625, - 625, 626, 631, 626, 632, 631, 631, 632, 511, 632, 512, 511, - 511, 511, 509, 511, 509, 509, 509, 509, 1982, 509, 1982, 1982, - 1982, 1982, 1983, 1982, 1983, 1983, 1983, 1983, 1984, 1983, 1984, 1984, - 1984, 1984, 1986, 1984, 1986, 1986, 1986, 1986, 625, 1986, 625, 625, - 625, 625, 631, 625, 631, 631, 631, 631, 511, 631, 511, 511, - 491, 492, 489, 492, 490, 489, 489, 490, 1988, 490, 1989, 1988, - 1988, 1989, 1990, 1989, 1991, 1990, 1990, 1991, 1992, 1991, 1993, 1992, - 1992, 1993, 1994, 1993, 1995, 1994, 1994, 1995, 491, 1995, 492, 491, - 491, 491, 489, 491, 489, 489, 489, 489, 1988, 489, 1988, 1988, - 1988, 1988, 1990, 1988, 1990, 1990, 1990, 1990, 1992, 1990, 1992, 1992, - 1992, 1992, 1994, 1992, 1994, 1994, 1994, 1994, 491, 1994, 491, 491, - 1996, 1997, 1998, 1997, 1999, 1998, 1998, 1999, 2000, 1999, 2001, 2000, - 2000, 2001, 2002, 2001, 2003, 2002, 2002, 2003, 2004, 2003, 2005, 2004, - 2004, 2005, 2006, 2005, 2007, 2006, 2006, 2007, 2008, 2007, 2009, 2008, - 2008, 2009, 2010, 2009, 2011, 2010, 2010, 2011, 2012, 2011, 2013, 2012, - 2012, 2013, 2014, 2013, 2015, 2014, 2014, 2015, 2016, 2015, 2017, 2016, - 2016, 2017, 2018, 2017, 2019, 2018, 2018, 2019, 2020, 2019, 2021, 2020, - 2020, 2021, 1996, 2021, 1997, 1996, 1996, 1996, 1998, 1996, 1998, 1998, - 1998, 1998, 2000, 1998, 2000, 2000, 2000, 2000, 2002, 2000, 2002, 2002, - 2002, 2002, 2004, 2002, 2004, 2004, 2004, 2004, 2006, 2004, 2006, 2006, - 2006, 2006, 2008, 2006, 2008, 2008, 2008, 2008, 2010, 2008, 2010, 2010, - 2010, 2010, 2012, 2010, 2012, 2012, 2012, 2012, 2014, 2012, 2014, 2014, - 2014, 2014, 2016, 2014, 2016, 2016, 2016, 2016, 2018, 2016, 2018, 2018, - 2018, 2018, 2020, 2018, 2020, 2020, 2020, 2020, 1996, 2020, 1996, 1996, - 2022, 2023, 2024, 2023, 2025, 2024, 2024, 2025, 2026, 2025, 2027, 2026, - 2026, 2027, 2028, 2027, 2029, 2028, 2028, 2029, 2030, 2029, 2031, 2030, - 2030, 2031, 2032, 2031, 2033, 2032, 2032, 2033, 2034, 2033, 2035, 2034, - 2034, 2035, 2036, 2035, 2037, 2036, 2036, 2037, 2038, 2037, 2039, 2038, - 2038, 2039, 2040, 2039, 2041, 2040, 2040, 2041, 2042, 2041, 2043, 2042, - 2042, 2043, 2044, 2043, 2045, 2044, 2044, 2045, 2046, 2045, 2047, 2046, - 2046, 2047, 2048, 2047, 2049, 2048, 2048, 2049, 2050, 2049, 2051, 2050, - 2050, 2051, 2052, 2051, 2053, 2052, 2052, 2053, 2054, 2053, 2055, 2054, - 2054, 2055, 2056, 2055, 2057, 2056, 2056, 2057, 2058, 2057, 2059, 2058, - 2058, 2059, 2060, 2059, 2061, 2060, 2060, 2061, 2062, 2061, 2063, 2062, - 2062, 2063, 2064, 2063, 2065, 2064, 2064, 2065, 2066, 2065, 2067, 2066, - 2066, 2067, 2068, 2067, 2069, 2068, 2068, 2069, 2070, 2069, 2071, 2070, - 2070, 2071, 2072, 2071, 2073, 2072, 2072, 2073, 2074, 2073, 2075, 2074, - 2074, 2075, 2076, 2075, 2077, 2076, 2076, 2077, 2078, 2077, 2079, 2078, - 2078, 2079, 2080, 2079, 2081, 2080, 2080, 2081, 2082, 2081, 2083, 2082, - 2082, 2083, 2084, 2083, 2085, 2084, 2084, 2085, 2086, 2085, 2087, 2086, - 2086, 2087, 2088, 2087, 2089, 2088, 2088, 2089, 2090, 2089, 2091, 2090, - 2090, 2091, 2092, 2091, 2093, 2092, 2092, 2093, 2094, 2093, 2095, 2094, - 2094, 2095, 2096, 2095, 2097, 2096, 2096, 2097, 2098, 2097, 2099, 2098, - 2098, 2099, 2100, 2099, 2101, 2100, 2100, 2101, 2102, 2101, 2103, 2102, - 2102, 2103, 2104, 2103, 2105, 2104, 2104, 2105, 2106, 2105, 1999, 2106, - 2106, 1999, 2107, 1999, 1997, 2107, 2107, 1997, 2108, 1997, 2109, 2108, - 2108, 2109, 2110, 2109, 2111, 2110, 2110, 2111, 2112, 2111, 2113, 2112, - 2112, 2113, 2114, 2113, 2115, 2114, 2114, 2115, 2116, 2115, 2117, 2116, - 2116, 2117, 2022, 2117, 2023, 2022, 2022, 2022, 2024, 2022, 2024, 2024, - 2024, 2024, 2026, 2024, 2026, 2026, 2026, 2026, 2028, 2026, 2028, 2028, - 2028, 2028, 2030, 2028, 2030, 2030, 2030, 2030, 2032, 2030, 2032, 2032, - 2032, 2032, 2034, 2032, 2034, 2034, 2034, 2034, 2036, 2034, 2036, 2036, - 2036, 2036, 2038, 2036, 2038, 2038, 2038, 2038, 2040, 2038, 2040, 2040, - 2040, 2040, 2042, 2040, 2042, 2042, 2042, 2042, 2044, 2042, 2044, 2044, - 2044, 2044, 2046, 2044, 2046, 2046, 2046, 2046, 2048, 2046, 2048, 2048, - 2048, 2048, 2050, 2048, 2050, 2050, 2050, 2050, 2052, 2050, 2052, 2052, - 2052, 2052, 2054, 2052, 2054, 2054, 2054, 2054, 2056, 2054, 2056, 2056, - 2056, 2056, 2058, 2056, 2058, 2058, 2058, 2058, 2060, 2058, 2060, 2060, - 2060, 2060, 2062, 2060, 2062, 2062, 2062, 2062, 2064, 2062, 2064, 2064, - 2064, 2064, 2066, 2064, 2066, 2066, 2066, 2066, 2068, 2066, 2068, 2068, - 2068, 2068, 2070, 2068, 2070, 2070, 2070, 2070, 2072, 2070, 2072, 2072, - 2072, 2072, 2074, 2072, 2074, 2074, 2074, 2074, 2076, 2074, 2076, 2076, - 2076, 2076, 2078, 2076, 2078, 2078, 2078, 2078, 2080, 2078, 2080, 2080, - 2080, 2080, 2082, 2080, 2082, 2082, 2082, 2082, 2084, 2082, 2084, 2084, - 2084, 2084, 2086, 2084, 2086, 2086, 2086, 2086, 2088, 2086, 2088, 2088, - 2088, 2088, 2090, 2088, 2090, 2090, 2090, 2090, 2092, 2090, 2092, 2092, - 2092, 2092, 2094, 2092, 2094, 2094, 2094, 2094, 2096, 2094, 2096, 2096, - 2096, 2096, 2098, 2096, 2098, 2098, 2098, 2098, 2100, 2098, 2100, 2100, - 2100, 2100, 2102, 2100, 2102, 2102, 2102, 2102, 2104, 2102, 2104, 2104, - 2104, 2104, 2106, 2104, 2106, 2106, 2106, 2106, 2107, 2106, 2107, 2107, - 2107, 2107, 2108, 2107, 2108, 2108, 2108, 2108, 2110, 2108, 2110, 2110, - 2110, 2110, 2112, 2110, 2112, 2112, 2112, 2112, 2114, 2112, 2114, 2114, - 2114, 2114, 2116, 2114, 2116, 2116, 2116, 2116, 2022, 2116, 2022, 2022, - 2118, 2119, 2120, 2119, 2121, 2120, 2120, 2121, 311, 2121, 2122, 311, - 311, 2122, 317, 2122, 2123, 317, 317, 2123, 2118, 2123, 2119, 2118, - 2118, 2118, 2120, 2118, 2120, 2120, 2120, 2120, 311, 2120, 311, 311, - 311, 311, 317, 311, 317, 317, 317, 317, 2118, 317, 2118, 2118, - 2122, 2121, 2119, 2123, 2122, 2119, 2118, 2124, 2125, 2124, 2126, 2125, - 2125, 2126, 2127, 2126, 2128, 2127, 2127, 2128, 2120, 2128, 2129, 2120, - 2120, 2129, 2118, 2129, 2124, 2118, 2118, 2118, 2125, 2118, 2125, 2125, - 2125, 2125, 2127, 2125, 2127, 2127, 2127, 2127, 2120, 2127, 2120, 2120, - 2120, 2120, 2118, 2120, 2118, 2118, 984, 891, 982, 891, 983, 982, - 982, 983, 2130, 983, 2131, 2130, 2130, 2131, 882, 2131, 883, 882, - 882, 883, 880, 883, 881, 880, 880, 881, 878, 881, 879, 878, - 878, 879, 876, 879, 877, 876, 876, 877, 874, 877, 875, 874, - 874, 875, 2132, 875, 893, 2132, 2132, 893, 984, 893, 891, 984, - 984, 984, 982, 984, 982, 982, 982, 982, 2130, 982, 2130, 2130, - 2130, 2130, 882, 2130, 882, 882, 882, 882, 880, 882, 880, 880, - 880, 880, 878, 880, 878, 878, 878, 878, 876, 878, 876, 876, - 876, 876, 874, 876, 874, 874, 874, 874, 2132, 874, 2132, 2132, - 2132, 2132, 984, 2132, 984, 984, 2133, 2134, 2135, 2134, 524, 2135, - 2135, 524, 2136, 524, 548, 2136, 2136, 548, 2137, 548, 2138, 2137, - 2137, 2138, 517, 2138, 518, 517, 517, 518, 515, 518, 516, 515, - 515, 516, 2133, 516, 2134, 2133, 2133, 2133, 2135, 2133, 2135, 2135, - 2135, 2135, 2136, 2135, 2136, 2136, 2136, 2136, 2137, 2136, 2137, 2137, - 2137, 2137, 517, 2137, 517, 517, 517, 517, 515, 517, 515, 515, - 515, 515, 2133, 515, 2133, 2133, 543, 544, 2139, 544, 2140, 2139, - 2139, 2140, 2141, 2140, 646, 2141, 2141, 646, 2142, 646, 644, 2142, - 2142, 644, 2143, 644, 2144, 2143, 2143, 2144, 2145, 2144, 2138, 2145, - 2145, 2138, 547, 2138, 548, 547, 547, 548, 545, 548, 546, 545, - 545, 546, 543, 546, 544, 543, 543, 543, 2139, 543, 2139, 2139, - 2139, 2139, 2141, 2139, 2141, 2141, 2141, 2141, 2142, 2141, 2142, 2142, - 2142, 2142, 2143, 2142, 2143, 2143, 2143, 2143, 2145, 2143, 2145, 2145, - 2145, 2145, 547, 2145, 547, 547, 547, 547, 545, 547, 545, 545, - 545, 545, 543, 545, 543, 543, 1986, 1987, 1984, 1987, 1985, 1984, - 1984, 1985, 2146, 1985, 2147, 2146, 2146, 2147, 2148, 2147, 2144, 2148, - 2148, 2144, 643, 2144, 644, 643, 643, 644, 641, 644, 642, 641, - 641, 642, 1986, 642, 1987, 1986, 1986, 1986, 1984, 1986, 1984, 1984, - 1984, 1984, 2146, 1984, 2146, 2146, 2146, 2146, 2148, 2146, 2148, 2148, - 2148, 2148, 643, 2148, 643, 643, 643, 643, 641, 643, 641, 641, - 641, 641, 1986, 641, 1986, 1986, 2143, 2144, 2149, 2144, 2147, 2149, - 2149, 2147, 2150, 2147, 1985, 2150, 2150, 1985, 615, 1985, 616, 615, - 615, 616, 621, 616, 520, 621, 621, 520, 2151, 520, 518, 2151, - 2151, 518, 2145, 518, 2138, 2145, 2145, 2138, 2143, 2138, 2144, 2143, - 2143, 2143, 2149, 2143, 2149, 2149, 2149, 2149, 2150, 2149, 2150, 2150, - 2150, 2150, 615, 2150, 615, 615, 615, 615, 621, 615, 621, 621, - 621, 621, 2151, 621, 2151, 2151, 2151, 2151, 2145, 2151, 2145, 2145, - 2145, 2145, 2143, 2145, 2143, 2143, 2152, 538, 2153, 538, 634, 2153, - 2153, 634, 2154, 634, 2155, 2154, 2154, 2155, 2156, 2155, 650, 2156, - 2156, 650, 2157, 650, 540, 2157, 2157, 540, 2158, 540, 2159, 2158, - 2158, 2159, 2152, 2159, 538, 2152, 2160, 2152, 2161, 2152, 2153, 2161, - 2161, 2153, 2162, 2153, 2154, 2162, 2162, 2154, 2163, 2154, 2156, 2163, - 2163, 2156, 2157, 2156, 2157, 2157, 2157, 2157, 2164, 2157, 2158, 2164, - 2164, 2158, 2160, 2158, 2152, 2160, 2165, 2166, 2167, 2166, 2168, 2167, - 2167, 2168, 2169, 2168, 2170, 2169, 2169, 2170, 2171, 2170, 1602, 2171, - 2171, 1602, 2172, 1602, 1629, 2172, 2172, 1629, 2173, 1629, 2174, 2173, - 2173, 2174, 2175, 2174, 2176, 2175, 2175, 2176, 2177, 2176, 1556, 2177, - 2177, 1556, 2178, 1556, 1554, 2178, 2178, 1554, 2179, 1554, 1582, 2179, - 2179, 1582, 2165, 1582, 2166, 2165, 2165, 2165, 2167, 2165, 2167, 2167, - 2167, 2167, 2169, 2167, 2169, 2169, 2169, 2169, 2171, 2169, 2171, 2171, - 2171, 2171, 2172, 2171, 2172, 2172, 2172, 2172, 2173, 2172, 2173, 2173, - 2173, 2173, 2175, 2173, 2175, 2175, 2175, 2175, 2177, 2175, 2177, 2177, - 2177, 2177, 2178, 2177, 2178, 2178, 2178, 2178, 2179, 2178, 2179, 2179, - 2179, 2179, 2165, 2179, 2165, 2165, 1561, 1540, 2180, 1540, 1538, 2180, - 2180, 1538, 2181, 1538, 1610, 2181, 2181, 1610, 2182, 1610, 1608, 2182, - 2182, 1608, 2183, 1608, 1606, 2183, 2183, 1606, 2184, 1606, 1604, 2184, - 2184, 1604, 2185, 1604, 1602, 2185, 2185, 1602, 2186, 1602, 2170, 2186, - 2186, 2170, 2187, 2170, 2168, 2187, 2187, 2168, 2188, 2168, 2166, 2188, - 2188, 2166, 1581, 2166, 1582, 1581, 1581, 1582, 1579, 1582, 1580, 1579, - 1579, 1580, 1566, 1580, 1567, 1566, 1566, 1567, 1564, 1567, 1565, 1564, - 1564, 1565, 1562, 1565, 1563, 1562, 1562, 1563, 1561, 1563, 1540, 1561, - 1561, 1561, 2180, 1561, 2180, 2180, 2180, 2180, 2181, 2180, 2181, 2181, - 2181, 2181, 2182, 2181, 2182, 2182, 2182, 2182, 2183, 2182, 2183, 2183, - 2183, 2183, 2184, 2183, 2184, 2184, 2184, 2184, 2185, 2184, 2185, 2185, - 2185, 2185, 2186, 2185, 2186, 2186, 2186, 2186, 2187, 2186, 2187, 2187, - 2187, 2187, 2188, 2187, 2188, 2188, 2188, 2188, 1581, 2188, 1581, 1581, - 1581, 1581, 1579, 1581, 1579, 1579, 1579, 1579, 1566, 1579, 1566, 1566, - 1566, 1566, 1564, 1566, 1564, 1564, 1564, 1564, 1562, 1564, 1562, 1562, - 1562, 1562, 1561, 1562, 1561, 1561, 2189, 1318, 2190, 1318, 1300, 2190, - 2190, 1300, 2191, 1300, 1298, 2191, 2191, 1298, 2192, 1298, 2193, 2192, - 2192, 2193, 2194, 2193, 1320, 2194, 2194, 1320, 2189, 1320, 1318, 2189, - 2189, 2189, 2190, 2189, 2190, 2190, 2190, 2190, 2191, 2190, 2191, 2191, - 2191, 2191, 2192, 2191, 2192, 2192, 2192, 2192, 2194, 2192, 2194, 2194, - 2194, 2194, 2189, 2194, 2189, 2189, 2205, 2198, 2206, 2198, 2196, 2206, - 2206, 2196, 2207, 2196, 2204, 2207, 2207, 2204, 2208, 2204, 2209, 2208, - 2208, 2209, 2210, 2209, 2211, 2210, 2210, 2211, 2212, 2211, 2213, 2212, - 2212, 2213, 2214, 2213, 2215, 2214, 2214, 2215, 2216, 2215, 2217, 2216, - 2216, 2217, 2218, 2217, 2219, 2218, 2218, 2219, 2220, 2219, 2221, 2220, - 2220, 2221, 2222, 2221, 2223, 2222, 2222, 2223, 2224, 2223, 2225, 2224, - 2224, 2225, 2226, 2225, 2227, 2226, 2226, 2227, 2228, 2227, 2229, 2228, - 2228, 2229, 2230, 2229, 2231, 2230, 2230, 2231, 2232, 2231, 2233, 2232, - 2232, 2233, 2234, 2233, 2235, 2234, 2234, 2235, 2236, 2235, 2237, 2236, - 2236, 2237, 2205, 2237, 2198, 2205, 2205, 2205, 2206, 2205, 2206, 2206, - 2206, 2206, 2207, 2206, 2207, 2207, 2207, 2207, 2208, 2207, 2208, 2208, - 2208, 2208, 2210, 2208, 2210, 2210, 2210, 2210, 2212, 2210, 2212, 2212, - 2212, 2212, 2214, 2212, 2214, 2214, 2214, 2214, 2216, 2214, 2216, 2216, - 2216, 2216, 2218, 2216, 2218, 2218, 2218, 2218, 2220, 2218, 2220, 2220, - 2220, 2220, 2222, 2220, 2222, 2222, 2222, 2222, 2224, 2222, 2224, 2224, - 2224, 2224, 2226, 2224, 2226, 2226, 2226, 2226, 2228, 2226, 2228, 2228, - 2228, 2228, 2230, 2228, 2230, 2230, 2230, 2230, 2232, 2230, 2232, 2232, - 2232, 2232, 2234, 2232, 2234, 2234, 2234, 2234, 2236, 2234, 2236, 2236, - 2236, 2236, 2205, 2236, 2205, 2205, 2238, 2239, 2240, 2239, 2241, 2240, - 2240, 2241, 2242, 2241, 2243, 2242, 2242, 2243, 2244, 2243, 2245, 2244, - 2244, 2245, 2246, 2245, 2247, 2246, 2246, 2247, 2248, 2247, 2249, 2248, - 2248, 2249, 2250, 2249, 2251, 2250, 2250, 2251, 2252, 2251, 2253, 2252, - 2252, 2253, 2254, 2253, 2255, 2254, 2254, 2255, 2256, 2255, 2257, 2256, - 2256, 2257, 2238, 2257, 2239, 2238, 2238, 2238, 2240, 2238, 2240, 2240, - 2240, 2240, 2242, 2240, 2242, 2242, 2242, 2242, 2244, 2242, 2244, 2244, - 2244, 2244, 2246, 2244, 2246, 2246, 2246, 2246, 2248, 2246, 2248, 2248, - 2248, 2248, 2250, 2248, 2250, 2250, 2250, 2250, 2252, 2250, 2252, 2252, - 2252, 2252, 2254, 2252, 2254, 2254, 2254, 2254, 2256, 2254, 2256, 2256, - 2256, 2256, 2238, 2256, 2238, 2238, 2258, 2247, 2259, 2247, 2245, 2259, - 2259, 2245, 2260, 2245, 2261, 2260, 2260, 2261, 2262, 2261, 2263, 2262, - 2262, 2263, 2264, 2263, 2265, 2264, 2264, 2265, 2258, 2265, 2247, 2258, - 2258, 2258, 2259, 2258, 2259, 2259, 2259, 2259, 2260, 2259, 2260, 2260, - 2260, 2260, 2262, 2260, 2262, 2262, 2262, 2262, 2264, 2262, 2264, 2264, - 2264, 2264, 2258, 2264, 2258, 2258, 2266, 2241, 2267, 2241, 2239, 2267, - 2267, 2239, 2268, 2239, 2257, 2268, 2268, 2257, 2269, 2257, 2270, 2269, - 2269, 2270, 2271, 2270, 2272, 2271, 2271, 2272, 2273, 2272, 2274, 2273, - 2273, 2274, 2275, 2274, 2276, 2275, 2275, 2276, 2277, 2276, 2278, 2277, - 2277, 2278, 2279, 2278, 2280, 2279, 2279, 2280, 2281, 2280, 2282, 2281, - 2281, 2282, 2266, 2282, 2241, 2266, 2266, 2266, 2267, 2266, 2267, 2267, - 2267, 2267, 2268, 2267, 2268, 2268, 2268, 2268, 2269, 2268, 2269, 2269, - 2269, 2269, 2271, 2269, 2271, 2271, 2271, 2271, 2273, 2271, 2273, 2273, - 2273, 2273, 2275, 2273, 2275, 2275, 2275, 2275, 2277, 2275, 2277, 2277, - 2277, 2277, 2279, 2277, 2279, 2279, 2279, 2279, 2281, 2279, 2281, 2281, - 2281, 2281, 2266, 2281, 2266, 2266, 2283, 2284, 2285, 2284, 2286, 2285, - 2285, 2286, 2287, 2286, 2288, 2287, 2287, 2288, 2289, 2288, 2290, 2289, - 2289, 2290, 2291, 2290, 2292, 2291, 2291, 2292, 2293, 2292, 2294, 2293, - 2293, 2294, 2295, 2294, 2296, 2295, 2295, 2296, 2297, 2296, 2298, 2297, - 2297, 2298, 2299, 2298, 2300, 2299, 2299, 2300, 2301, 2300, 2302, 2301, - 2301, 2302, 2303, 2302, 2304, 2303, 2303, 2304, 2305, 2304, 2306, 2305, - 2305, 2306, 2307, 2306, 2308, 2307, 2307, 2308, 2283, 2308, 2284, 2283, - 2283, 2283, 2285, 2283, 2285, 2285, 2285, 2285, 2287, 2285, 2287, 2287, - 2287, 2287, 2289, 2287, 2289, 2289, 2289, 2289, 2291, 2289, 2291, 2291, - 2291, 2291, 2293, 2291, 2293, 2293, 2293, 2293, 2295, 2293, 2295, 2295, - 2295, 2295, 2297, 2295, 2297, 2297, 2297, 2297, 2299, 2297, 2299, 2299, - 2299, 2299, 2301, 2299, 2301, 2301, 2301, 2301, 2303, 2301, 2303, 2303, - 2303, 2303, 2305, 2303, 2305, 2305, 2305, 2305, 2307, 2305, 2307, 2307, - 2307, 2307, 2283, 2307, 2283, 2283, 2309, 2310, 2311, 2310, 2312, 2311, - 2311, 2312, 2313, 2312, 2314, 2313, 2313, 2314, 2315, 2314, 2316, 2315, - 2315, 2316, 2317, 2316, 2318, 2317, 2317, 2318, 2319, 2318, 2290, 2319, - 2319, 2290, 2320, 2290, 2288, 2320, 2320, 2288, 2321, 2288, 2286, 2321, - 2321, 2286, 2322, 2286, 2323, 2322, 2322, 2323, 2324, 2323, 2325, 2324, - 2324, 2325, 2326, 2325, 2327, 2326, 2326, 2327, 2328, 2327, 2329, 2328, - 2328, 2329, 2330, 2329, 2331, 2330, 2330, 2331, 2332, 2331, 2333, 2332, - 2332, 2333, 2309, 2333, 2310, 2309, 2309, 2309, 2311, 2309, 2311, 2311, - 2311, 2311, 2313, 2311, 2313, 2313, 2313, 2313, 2315, 2313, 2315, 2315, - 2315, 2315, 2317, 2315, 2317, 2317, 2317, 2317, 2319, 2317, 2319, 2319, - 2319, 2319, 2320, 2319, 2320, 2320, 2320, 2320, 2321, 2320, 2321, 2321, - 2321, 2321, 2322, 2321, 2322, 2322, 2322, 2322, 2324, 2322, 2324, 2324, - 2324, 2324, 2326, 2324, 2326, 2326, 2326, 2326, 2328, 2326, 2328, 2328, - 2328, 2328, 2330, 2328, 2330, 2330, 2330, 2330, 2332, 2330, 2332, 2332, - 2332, 2332, 2309, 2332, 2309, 2309, 2334, 2335, 2336, 2335, 2337, 2336, - 2336, 2337, 2338, 2337, 2339, 2338, 2338, 2339, 2340, 2339, 2341, 2340, - 2340, 2341, 2342, 2341, 2343, 2342, 2342, 2343, 2344, 2343, 2345, 2344, - 2344, 2345, 2346, 2345, 2347, 2346, 2346, 2347, 2348, 2347, 2349, 2348, - 2348, 2349, 2350, 2349, 2351, 2350, 2350, 2351, 2352, 2351, 2353, 2352, - 2352, 2353, 2354, 2353, 2355, 2354, 2354, 2355, 2356, 2355, 2357, 2356, - 2356, 2357, 2358, 2357, 2359, 2358, 2358, 2359, 2360, 2359, 2361, 2360, - 2360, 2361, 2362, 2361, 2363, 2362, 2362, 2363, 2364, 2363, 2365, 2364, - 2364, 2365, 2366, 2365, 2367, 2366, 2366, 2367, 2368, 2367, 2369, 2368, - 2368, 2369, 2334, 2369, 2335, 2334, 2334, 2334, 2336, 2334, 2336, 2336, - 2336, 2336, 2338, 2336, 2338, 2338, 2338, 2338, 2340, 2338, 2340, 2340, - 2340, 2340, 2342, 2340, 2342, 2342, 2342, 2342, 2344, 2342, 2344, 2344, - 2344, 2344, 2346, 2344, 2346, 2346, 2346, 2346, 2348, 2346, 2348, 2348, - 2348, 2348, 2350, 2348, 2350, 2350, 2350, 2350, 2352, 2350, 2352, 2352, - 2352, 2352, 2354, 2352, 2354, 2354, 2354, 2354, 2356, 2354, 2356, 2356, - 2356, 2356, 2358, 2356, 2358, 2358, 2358, 2358, 2360, 2358, 2360, 2360, - 2360, 2360, 2362, 2360, 2362, 2362, 2362, 2362, 2364, 2362, 2364, 2364, - 2364, 2364, 2366, 2364, 2366, 2366, 2366, 2366, 2368, 2366, 2368, 2368, - 2368, 2368, 2334, 2368, 2334, 2334, 2338, 2339, 2336, 2339, 2337, 2336, - 2336, 2337, 2370, 2337, 2371, 2370, 2370, 2371, 2372, 2371, 2373, 2372, - 2372, 2373, 2374, 2373, 2375, 2374, 2374, 2375, 2376, 2375, 2377, 2376, - 2376, 2377, 2378, 2377, 2379, 2378, 2378, 2379, 2380, 2379, 2381, 2380, - 2380, 2381, 2382, 2381, 2383, 2382, 2382, 2383, 2384, 2383, 2385, 2384, - 2384, 2385, 2386, 2385, 2387, 2386, 2386, 2387, 2338, 2387, 2339, 2338, - 2338, 2338, 2336, 2338, 2336, 2336, 2336, 2336, 2370, 2336, 2370, 2370, - 2370, 2370, 2372, 2370, 2372, 2372, 2372, 2372, 2374, 2372, 2374, 2374, - 2374, 2374, 2376, 2374, 2376, 2376, 2376, 2376, 2378, 2376, 2378, 2378, - 2378, 2378, 2380, 2378, 2380, 2380, 2380, 2380, 2382, 2380, 2382, 2382, - 2382, 2382, 2384, 2382, 2384, 2384, 2384, 2384, 2386, 2384, 2386, 2386, - 2386, 2386, 2338, 2386, 2338, 2338 - ] - }, - { - "id": "shape1_part2", - "type": "TRIANGLES", - "indices": [ - 40, 42, 44, 70, 72, 74, 76, 70, 74, 80, 82, 84, - 38, 32, 34, 38, 34, 36, 44, 46, 48, 40, 44, 48, - 28, 32, 38, 54, 56, 58, 54, 50, 52, 54, 48, 50, - 48, 54, 58, 60, 48, 58, 48, 60, 66, 62, 66, 60, - 66, 40, 48, 62, 64, 66, 30, 32, 28, 88, 90, 0, - 40, 26, 28, 4, 6, 8, 40, 70, 26, 40, 28, 38, - 24, 26, 76, 66, 68, 70, 66, 70, 40, 4, 10, 16, - 10, 4, 8, 14, 10, 12, 14, 16, 10, 24, 78, 22, - 70, 76, 26, 80, 86, 78, 86, 80, 84, 20, 86, 88, - 2, 20, 88, 2, 88, 0, 20, 78, 86, 78, 24, 76, - 20, 22, 78, 20, 16, 18, 2, 16, 20, 4, 16, 2, - 104, 100, 102, 98, 100, 104, 106, 96, 98, 106, 98, 104, - 106, 108, 92, 96, 106, 92, 96, 92, 94, 116, 118, 120, - 112, 114, 116, 110, 112, 116, 110, 116, 120, 148, 152, 146, - 152, 156, 158, 146, 142, 144, 150, 152, 148, 146, 158, 142, - 146, 152, 158, 154, 156, 152, 194, 190, 192, 208, 194, 196, - 208, 196, 198, 207, 198, 160, 208, 198, 207, 194, 188, 190, - 200, 194, 208, 200, 188, 194, 164, 206, 160, 164, 160, 162, - 206, 164, 166, 207, 160, 206, 200, 184, 188, 184, 186, 188, - 200, 201, 184, 184, 201, 202, 182, 184, 202, 174, 203, 204, - 176, 202, 203, 176, 203, 174, 178, 202, 176, 180, 182, 202, - 178, 180, 202, 172, 174, 204, 166, 205, 206, 170, 166, 168, - 170, 205, 166, 204, 205, 170, 172, 204, 170, 229, 209, 211, - 215, 229, 211, 215, 211, 213, 223, 219, 221, 217, 219, 223, - 225, 217, 223, 215, 217, 225, 227, 229, 215, 225, 227, 215, - 231, 32, 30, 251, 253, 255, 30, 28, 26, 233, 30, 26, - 235, 30, 233, 245, 247, 251, 249, 251, 247, 255, 245, 251, - 235, 243, 245, 255, 231, 30, 255, 235, 245, 235, 255, 30, - 235, 241, 243, 237, 239, 235, 239, 241, 235, 263, 257, 259, - 263, 259, 261, 265, 271, 257, 263, 265, 257, 267, 271, 265, - 269, 271, 267, 275, 277, 279, 273, 275, 279, 281, 283, 285, - 289, 281, 285, 289, 285, 287, 299, 303, 293, 291, 293, 303, - 293, 295, 299, 301, 303, 299, 297, 299, 295, 305, 307, 309, - 310, 305, 309, 311, 315, 317, 313, 315, 311, 347, 349, 351, - 365, 351, 353, 367, 347, 351, 363, 365, 353, 363, 353, 355, - 359, 355, 357, 361, 355, 359, 363, 355, 361, 365, 367, 351, - 345, 347, 367, 381, 383, 385, 387, 370, 385, 381, 385, 370, - 369, 370, 387, 371, 381, 370, 372, 379, 381, 371, 372, 381, - 373, 379, 372, 374, 377, 379, 373, 374, 379, 375, 377, 374, - 389, 395, 399, 391, 393, 389, 393, 395, 389, 397, 399, 395, - 409, 411, 413, 405, 409, 413, 405, 413, 415, 405, 415, 401, - 403, 405, 401, 407, 409, 405, 427, 429, 431, 423, 427, 431, - 425, 427, 423, 423, 431, 433, 421, 423, 433, 421, 433, 417, - 419, 421, 417, 436, 438, 440, 442, 436, 440, 435, 436, 442, - 450, 435, 442, 450, 442, 444, 449, 450, 444, 449, 444, 446, - 448, 449, 446, 472, 474, 475, 468, 470, 472, 477, 472, 475, - 477, 475, 476, 466, 468, 472, 466, 472, 477, 464, 466, 477, - 464, 477, 478, 480, 478, 479, 452, 480, 451, 452, 478, 480, - 462, 464, 478, 478, 454, 462, 452, 454, 478, 460, 462, 454, - 458, 460, 454, 456, 458, 454, 295, 481, 483, 293, 481, 295, - 487, 303, 301, 301, 299, 297, 485, 487, 301, 485, 301, 297, - 495, 491, 493, 489, 491, 495, 493, 499, 501, 497, 499, 493, - 495, 493, 501, 497, 503, 499, 507, 503, 497, 505, 507, 497, - 513, 515, 517, 521, 513, 517, 521, 517, 519, 511, 513, 521, - 511, 521, 509, 545, 523, 525, 545, 525, 527, 547, 523, 545, - 543, 545, 527, 527, 529, 531, 535, 531, 533, 531, 543, 527, - 535, 543, 531, 535, 541, 543, 539, 541, 535, 539, 535, 537, - 555, 114, 112, 557, 112, 110, 559, 555, 112, 559, 112, 557, - 553, 555, 559, 559, 551, 553, 561, 551, 559, 561, 549, 551, - 563, 549, 561, 571, 573, 549, 563, 571, 549, 565, 571, 563, - 569, 571, 565, 567, 569, 565, 583, 579, 581, 589, 579, 583, - 587, 589, 583, 587, 583, 585, 591, 579, 589, 595, 597, 599, - 601, 595, 599, 575, 591, 606, 579, 575, 577, 591, 575, 579, - 606, 591, 593, 606, 593, 595, 605, 606, 595, 605, 595, 601, - 605, 601, 603, 611, 579, 607, 611, 607, 609, 581, 579, 611, - 613, 581, 611, 620, 621, 615, 619, 620, 615, 617, 619, 615, - 622, 624, 605, 622, 605, 603, 627, 629, 631, 625, 627, 631, - 635, 624, 622, 636, 624, 635, 639, 633, 635, 622, 637, 639, - 639, 635, 622, 648, 643, 645, 648, 645, 647, 643, 648, 649, - 655, 643, 649, 655, 649, 651, 641, 643, 655, 653, 655, 651, - 674, 668, 670, 672, 674, 670, 676, 674, 672, 120, 676, 672, - 118, 676, 120, 684, 668, 678, 684, 678, 680, 682, 684, 680, - 686, 668, 684, 670, 668, 686, 694, 696, 698, 704, 692, 702, - 690, 704, 688, 690, 692, 704, 694, 700, 702, 694, 698, 700, - 702, 692, 694, 720, 721, 694, 720, 694, 692, 719, 720, 692, - 712, 719, 692, 708, 712, 692, 706, 708, 692, 710, 712, 708, - 716, 719, 712, 714, 716, 712, 718, 719, 716, 732, 734, 736, - 728, 730, 732, 742, 724, 736, 732, 736, 724, 728, 732, 724, - 736, 738, 740, 740, 742, 736, 726, 728, 724, 754, 748, 750, - 754, 750, 752, 722, 724, 754, 742, 744, 746, 742, 748, 724, - 746, 748, 742, 754, 724, 748, 722, 754, 756, 764, 766, 768, - 758, 760, 762, 764, 768, 770, 772, 758, 762, 774, 758, 772, - 770, 772, 762, 770, 762, 764, 768, 778, 780, 768, 780, 782, - 770, 768, 782, 782, 784, 776, 770, 782, 776, 780, 786, 788, - 784, 780, 788, 782, 780, 784, 790, 784, 788, 796, 776, 792, - 790, 792, 784, 776, 784, 792, 794, 796, 792, 830, 832, 834, - 838, 834, 836, 840, 842, 844, 820, 824, 826, 822, 824, 820, - 818, 820, 826, 816, 818, 826, 840, 814, 816, 814, 844, 812, - 826, 828, 830, 838, 826, 830, 838, 830, 834, 826, 838, 840, - 826, 840, 816, 810, 812, 848, 840, 844, 814, 846, 812, 844, - 848, 812, 846, 726, 724, 722, 726, 848, 728, 790, 786, 726, - 726, 780, 848, 780, 810, 848, 722, 790, 726, 788, 786, 790, - 810, 778, 808, 780, 726, 786, 780, 778, 810, 806, 808, 778, - 766, 802, 806, 804, 806, 802, 850, 790, 722, 802, 760, 800, - 806, 778, 766, 766, 778, 768, 792, 790, 850, 766, 760, 802, - 760, 766, 764, 762, 760, 764, 798, 800, 760, 758, 798, 760, - 868, 870, 852, 864, 866, 868, 864, 868, 856, 854, 868, 852, - 856, 868, 854, 862, 864, 856, 856, 858, 860, 862, 856, 860, - 882, 884, 886, 880, 882, 886, 888, 864, 862, 888, 880, 886, - 862, 880, 888, 862, 876, 880, 878, 880, 876, 872, 876, 862, - 874, 876, 872, 894, 896, 898, 892, 898, 890, 894, 898, 892, - 904, 906, 900, 902, 904, 900, 913, 908, 910, 913, 910, 912, - 916, 914, 915, 917, 914, 916, 906, 918, 920, 900, 906, 920, - 908, 924, 926, 910, 908, 926, 922, 924, 908, 936, 928, 930, - 936, 930, 932, 858, 936, 932, 932, 904, 858, 904, 932, 934, - 860, 904, 902, 860, 858, 904, 946, 948, 950, 952, 946, 950, - 960, 954, 956, 960, 956, 958, 940, 942, 944, 940, 944, 946, - 918, 938, 940, 920, 918, 940, 966, 920, 940, 940, 946, 952, - 940, 952, 954, 964, 966, 962, 940, 960, 966, 954, 960, 940, - 962, 966, 960, 972, 974, 968, 972, 968, 928, 970, 972, 928, - 970, 928, 936, 389, 974, 972, 391, 389, 972, 391, 972, 970, - 976, 391, 970, 978, 391, 976, 870, 976, 970, 870, 970, 852, - 866, 976, 870, 866, 870, 868, 988, 399, 397, 986, 988, 397, - 980, 985, 986, 397, 980, 986, 984, 980, 982, 985, 980, 984, - 993, 997, 999, 993, 999, 990, 995, 997, 993, 991, 993, 990, - 930, 968, 997, 930, 997, 995, 930, 995, 1000, 928, 968, 930, - 1006, 1030, 1002, 1004, 1006, 1002, 1006, 1028, 1030, 1024, 1028, 1006, - 1026, 1028, 1024, 1022, 1024, 1006, 1020, 1022, 1006, 1020, 1006, 1008, - 1010, 1020, 1008, 1018, 1020, 1010, 1018, 1014, 1016, 1010, 1012, 1018, - 1012, 1014, 1018, 1034, 1036, 1037, 1032, 1034, 1037, 1037, 1038, 1040, - 1032, 1037, 1040, 1046, 1042, 1044, 607, 1042, 1046, 609, 607, 1046, - 609, 1046, 1048, 1055, 1059, 1051, 1055, 1051, 1053, 1049, 1051, 1059, - 1057, 1059, 1055, 1004, 1002, 1061, 1004, 1061, 1049, 1059, 1004, 1049, - 1008, 1059, 1057, 1006, 1004, 1059, 1008, 1006, 1059, 1077, 1081, 1083, - 1079, 1081, 1077, 1067, 1077, 1083, 1063, 1067, 1083, 1071, 1077, 1067, - 1069, 1071, 1067, 1073, 1077, 1071, 1075, 1077, 1073, 1065, 1067, 1063, - 1083, 1081, 1085, 1083, 1085, 1087, 1089, 1085, 1081, 1095, 1097, 1099, - 1042, 1091, 1093, 1042, 1093, 1095, 1109, 1095, 1099, 1109, 1099, 1101, - 1042, 1095, 1109, 1044, 1042, 1109, 1087, 1101, 1103, 1105, 1109, 1101, - 1105, 1101, 1087, 1085, 1105, 1087, 1107, 1109, 1105, 1119, 1065, 1063, - 1119, 1063, 1111, 1113, 1119, 1111, 1117, 1119, 1113, 1115, 1117, 1113, - 1125, 1075, 1073, 1123, 1075, 1125, 1113, 1127, 1115, 1127, 1129, 1115, - 1113, 1121, 1127, 1123, 1125, 1127, 1121, 1123, 1127, 1055, 1123, 1121, - 1053, 1123, 1055, 1133, 1135, 1137, 1141, 1131, 1137, 1141, 1137, 1139, - 1133, 1137, 1131, 1149, 1151, 1153, 1145, 1147, 1149, 1149, 1153, 1155, - 1145, 1149, 1155, 1143, 1145, 1155, 1141, 1139, 1145, 1141, 1145, 1143, - 1159, 1161, 409, 407, 1159, 409, 1159, 407, 1157, 1133, 1161, 1159, - 1133, 1159, 1135, 1243, 1245, 1247, 1243, 1247, 1249, 1237, 1239, 1241, - 1235, 1237, 1241, 1249, 1251, 1253, 1253, 1243, 1249, 1255, 1243, 1253, - 1241, 1243, 1255, 1227, 1229, 1231, 1233, 1227, 1231, 1221, 1223, 1225, - 1219, 1221, 1225, 1267, 1273, 1279, 1271, 1267, 1269, 1273, 1267, 1271, - 1273, 1275, 1277, 1279, 1273, 1277, 1281, 1267, 1279, 1283, 1267, 1281, - 1213, 1215, 1217, 1211, 1213, 1217, 1285, 1287, 1289, 1207, 1209, 1219, - 1217, 1219, 1209, 1211, 1217, 1209, 1235, 1241, 1255, 1225, 1207, 1219, - 1225, 1227, 1255, 1255, 1207, 1225, 1207, 1283, 1205, 1233, 1235, 1255, - 1255, 1227, 1233, 1257, 1207, 1255, 1257, 1261, 1207, 1259, 1261, 1257, - 1261, 1265, 1207, 1263, 1265, 1261, 1267, 1207, 1265, 1283, 1207, 1267, - 1295, 1289, 1291, 1295, 1291, 1293, 1205, 1289, 1201, 1285, 1205, 1283, - 1289, 1205, 1285, 1199, 1201, 1289, 1203, 1205, 1201, 1289, 1179, 1199, - 1295, 1169, 1289, 1165, 1169, 1295, 1163, 1165, 1295, 1167, 1169, 1165, - 1169, 1171, 1289, 1171, 1177, 1289, 1177, 1171, 1173, 1175, 1177, 1173, - 1177, 1179, 1289, 1185, 1199, 1179, 1185, 1179, 1181, 1183, 1185, 1181, - 1187, 1199, 1185, 1187, 1197, 1199, 1191, 1187, 1189, 1191, 1197, 1187, - 1197, 1191, 1193, 1195, 1197, 1193, 1303, 1305, 1307, 1307, 1309, 1311, - 1313, 1307, 1311, 1315, 1297, 1299, 1301, 1315, 1299, 1303, 1313, 1315, - 1303, 1307, 1313, 1315, 1301, 1303, 1319, 1321, 1323, 1317, 1319, 1323, - 1326, 1327, 1329, 1331, 1326, 1329, 1325, 1326, 1331, 1339, 1335, 1337, - 1339, 1333, 1335, 1340, 1333, 1339, 1341, 1333, 1340, 1343, 1345, 1347, - 1327, 1343, 1347, 1351, 1329, 1327, 1347, 1349, 1351, 1351, 1327, 1347, - 1331, 1329, 1351, 1535, 1537, 1539, 1543, 1539, 1541, 1535, 1539, 1543, - 1533, 1535, 1543, 1533, 1547, 1531, 1543, 1545, 1533, 1545, 1547, 1533, - 1549, 1531, 1547, 1557, 1559, 1551, 1553, 1555, 1557, 1553, 1557, 1551, - 1564, 1566, 1568, 1570, 1564, 1568, 1562, 1564, 1570, 1572, 1561, 1562, - 1572, 1562, 1570, 1581, 1553, 1551, 1573, 1581, 1551, 1577, 1573, 1575, - 1579, 1581, 1573, 1577, 1579, 1573, 1566, 1579, 1577, 1568, 1566, 1577, - 1583, 1585, 1587, 1597, 1583, 1587, 1597, 1587, 1589, 1591, 1595, 1589, - 1597, 1589, 1595, 1593, 1595, 1591, 1559, 1583, 1597, 1551, 1559, 1597, - 1551, 1597, 1595, 1573, 1551, 1595, 1599, 1573, 1595, 1593, 1599, 1595, - 1575, 1573, 1599, 1624, 1626, 1628, 1620, 1624, 1628, 1605, 1601, 1603, - 1601, 1620, 1628, 1620, 1601, 1605, 1622, 1624, 1620, 1618, 1620, 1605, - 1605, 1616, 1618, 1607, 1609, 1605, 1609, 1616, 1605, 1612, 1616, 1609, - 1612, 1609, 1611, 1613, 1616, 1612, 1614, 1616, 1613, 1638, 1636, 1637, - 1634, 1636, 1638, 1630, 1639, 1640, 1639, 1634, 1638, 1632, 1639, 1630, - 1632, 1634, 1639, 1657, 1659, 1641, 1643, 1657, 1641, 1655, 1657, 1643, - 1651, 1645, 1647, 1649, 1651, 1647, 1653, 1645, 1651, 1643, 1645, 1653, - 1655, 1643, 1653, 1653, 1665, 1655, 1667, 1655, 1665, 209, 1667, 1665, - 211, 209, 1665, 1653, 1663, 1665, 1661, 1663, 1653, 221, 1663, 1661, - 219, 1663, 221, 1671, 1677, 1679, 1669, 1671, 1679, 1659, 1669, 1679, - 1641, 1659, 1679, 1671, 1673, 1677, 1675, 1677, 1673, 1649, 1647, 1677, - 1675, 1649, 1677, 1681, 1683, 1685, 1687, 1681, 1685, 1671, 1681, 1687, - 1695, 1689, 1691, 1693, 1695, 1691, 1673, 1689, 1695, 1687, 1689, 1673, - 1671, 1687, 1673, 1723, 1725, 1727, 1721, 1723, 1727, 1711, 1715, 1717, - 1711, 1717, 1719, 1713, 1715, 1711, 1721, 1727, 1729, 1703, 1705, 1707, - 1703, 1707, 1709, 1697, 1699, 1701, 1697, 1701, 1703, 1697, 1703, 1709, - 1697, 1709, 1711, 1729, 1697, 1711, 1719, 1729, 1711, 1729, 1719, 1721, - 1732, 1734, 1731, 1733, 1734, 1732, 1737, 1738, 1735, 1737, 1735, 1736, - 1742, 1743, 1745, 1741, 1739, 1740, 1742, 1745, 1739, 1741, 1742, 1739, - 1767, 1769, 1747, 1749, 1767, 1747, 1683, 1767, 1749, 1685, 1683, 1749, - 1685, 1749, 1751, 1757, 1751, 1753, 1755, 1757, 1753, 1757, 1691, 1685, - 1757, 1685, 1751, 1691, 1757, 1759, 1765, 1761, 1763, 1759, 1761, 1765, - 1693, 1759, 1765, 1691, 1759, 1693, 1769, 1777, 1779, 1775, 1769, 1779, - 1747, 1769, 1775, 1781, 1775, 1779, 1773, 1775, 1781, 1753, 1771, 1773, - 1773, 1791, 1753, 1755, 1753, 1791, 1783, 1773, 1781, 1783, 1791, 1773, - 1793, 1755, 1791, 1785, 1789, 1791, 1785, 1791, 1783, 1787, 1789, 1785, - 1763, 1789, 1787, 1761, 1789, 1763, 1799, 1801, 1795, 1797, 1799, 1795, - 1807, 1809, 1811, 1811, 1803, 1805, 1807, 1811, 1805, 1815, 1817, 1819, - 1813, 1815, 1819, 1813, 1819, 1820, 1795, 1821, 1815, 1795, 1815, 1813, - 1797, 1795, 1813, 227, 1829, 1831, 225, 1823, 227, 1823, 1829, 227, - 1825, 1829, 1823, 1827, 1829, 1825, 1835, 1837, 1699, 1803, 1835, 1699, - 1833, 1835, 1803, 1838, 1803, 1699, 1697, 1838, 1699, 1805, 1803, 1838, - 1852, 1854, 1856, 1846, 1848, 1850, 1858, 1850, 1852, 1858, 1852, 1856, - 1846, 1850, 1858, 1862, 1846, 1858, 1862, 1858, 1860, 1862, 1844, 1846, - 1842, 1862, 1840, 1842, 1844, 1862, 1868, 1870, 1864, 1866, 1868, 1864, - 1874, 1876, 1878, 1872, 1874, 1878, 1884, 1886, 1887, 1880, 1882, 1884, - 1880, 1884, 1887, 1864, 1876, 1874, 1888, 1866, 1864, 1888, 1864, 1874, - 1850, 267, 265, 1850, 1892, 267, 1850, 1890, 1892, 1850, 265, 1852, - 1848, 1890, 1850, 1894, 1842, 1840, 1894, 1840, 1898, 1896, 1842, 1894, - 1872, 1894, 1898, 1898, 1882, 1880, 1878, 1894, 1872, 1872, 1898, 1880, - 1902, 1904, 1906, 1908, 1902, 1906, 1900, 1902, 1908, 1910, 1900, 1908, - 1912, 1914, 1904, 1902, 1912, 1904, 1916, 1912, 1902, 1900, 1916, 1902, - 1918, 1922, 1914, 1920, 1922, 1918, 1914, 1926, 1918, 1912, 1926, 1914, - 1916, 1926, 1912, 1924, 1926, 1916, 1924, 1918, 1926, 1934, 1936, 1938, - 1918, 1932, 1938, 1918, 1938, 1920, 1932, 1918, 1924, 1934, 1938, 1932, - 1930, 1932, 1924, 1928, 1930, 1924, 1940, 1946, 1948, 1950, 1940, 1948, - 1942, 1946, 1940, 1944, 1946, 1942, 1958, 1960, 1934, 1958, 1934, 1932, - 1930, 1952, 1958, 1956, 1958, 1952, 1954, 1956, 1952, 1946, 1928, 1948, - 1932, 1930, 1958, 1928, 1952, 1930, 1944, 1928, 1946, 1928, 1944, 1952, - 283, 1962, 1963, 283, 1963, 1965, 283, 1965, 1967, 285, 283, 1967, - 1973, 1979, 281, 1977, 1979, 1973, 1975, 1977, 1973, 289, 1973, 281, - 1971, 289, 1969, 1971, 1973, 289, 1981, 1640, 1980, 1630, 1640, 1981, - 1531, 1630, 1981, 1531, 1981, 1533, 1632, 1630, 1531, 1982, 1983, 1984, - 1982, 511, 509, 625, 1982, 1984, 625, 1984, 1986, 1982, 631, 511, - 625, 631, 1982, 1990, 1992, 1994, 1988, 491, 489, 1990, 1994, 491, - 1988, 1990, 491, 2008, 2010, 2012, 2008, 2012, 2014, 2004, 2006, 2008, - 2000, 2002, 2004, 2004, 2018, 1996, 2014, 2004, 2008, 2000, 2004, 1996, - 1998, 2000, 1996, 2014, 2016, 2018, 2018, 2004, 2014, 1996, 2018, 2020, - 2104, 2098, 2100, 2102, 2104, 2100, 2094, 2098, 2104, 2096, 2098, 2094, - 2094, 2104, 2106, 2106, 2092, 2094, 2092, 2106, 2107, 2084, 2080, 2082, - 2086, 2078, 2080, 2086, 2072, 2078, 2086, 2080, 2084, 2078, 2074, 2076, - 2088, 2072, 2086, 2072, 2074, 2078, 2108, 2092, 2107, 2058, 2062, 2066, - 2062, 2058, 2060, 2058, 2052, 2056, 2064, 2066, 2062, 2070, 2072, 2088, - 2070, 2088, 2090, 2066, 2048, 2050, 2052, 2054, 2056, 2066, 2052, 2058, - 2066, 2050, 2052, 2108, 2110, 2090, 2108, 2090, 2092, 2042, 2044, 2046, - 2040, 2036, 2038, 2042, 2034, 2036, 2112, 2068, 2070, 2110, 2112, 2070, - 2110, 2070, 2090, 2028, 2032, 2034, 2042, 2036, 2040, 2034, 2042, 2046, - 2026, 2028, 2034, 2030, 2032, 2028, 2046, 2026, 2034, 2026, 2046, 2114, - 2022, 2026, 2114, 2024, 2026, 2022, 2048, 2066, 2068, 2048, 2068, 2112, - 2112, 2046, 2048, 2112, 2114, 2046, 2116, 2022, 2114, 2120, 311, 317, - 2120, 317, 2118, 2125, 2120, 2118, 2127, 2120, 2125, 882, 982, 2130, - 878, 882, 880, 882, 984, 982, 878, 984, 882, 2132, 984, 878, - 874, 878, 876, 2132, 878, 874, 2136, 2133, 2135, 2137, 2133, 2136, - 515, 2133, 2137, 517, 515, 2137, 2145, 547, 545, 2139, 545, 543, - 2145, 545, 2139, 2143, 2141, 2142, 2145, 2139, 2141, 2143, 2145, 2141, - 1986, 2146, 2148, 1984, 2146, 1986, 641, 1986, 2148, 641, 2148, 643, - 621, 2151, 2145, 621, 2145, 2143, 615, 621, 2143, 2149, 615, 2143, - 2150, 615, 2149, 2162, 2164, 2160, 2162, 2160, 2161, 2163, 2157, 2164, - 2163, 2164, 2162, 2167, 2175, 2177, 2178, 2167, 2177, 2165, 2167, 2178, - 2165, 2178, 2179, 2169, 2175, 2167, 2169, 2173, 2175, 2171, 2173, 2169, - 2172, 2173, 2171, 2184, 2185, 2186, 2186, 2187, 2188, 1579, 1564, 2188, - 1579, 2188, 1581, 1564, 1579, 1566, 1562, 2188, 1564, 1562, 2182, 2184, - 2183, 2184, 2182, 2186, 2188, 1562, 1562, 2184, 2186, 2180, 2182, 1562, - 2181, 2182, 2180, 1561, 2180, 1562, 2191, 2192, 2194, 2191, 2194, 2189, - 2190, 2191, 2189, 2224, 2226, 2228, 2208, 2210, 2212, 2214, 2208, 2212, - 2232, 2228, 2230, 2206, 2207, 2208, 2220, 2222, 2232, 2228, 2222, 2224, - 2232, 2222, 2228, 2232, 2218, 2220, 2234, 2218, 2232, 2216, 2218, 2234, - 2214, 2216, 2234, 2234, 2206, 2214, 2214, 2206, 2208, 2206, 2234, 2236, - 2205, 2206, 2236, 2244, 2240, 2242, 2244, 2256, 2238, 2244, 2238, 2240, - 2246, 2256, 2244, 2248, 2256, 2246, 2254, 2256, 2248, 2250, 2254, 2248, - 2252, 2254, 2250, 2262, 2259, 2260, 2258, 2259, 2262, 2264, 2258, 2262, - 2281, 2267, 2279, 2266, 2267, 2281, 2268, 2269, 2271, 2267, 2268, 2271, - 2273, 2277, 2271, 2275, 2277, 2273, 2277, 2267, 2271, 2279, 2267, 2277, - 2287, 2289, 2291, 2307, 2283, 2285, 2307, 2285, 2287, 2305, 2307, 2287, - 2303, 2305, 2287, 2287, 2291, 2293, 2301, 2303, 2287, 2293, 2299, 2301, - 2287, 2293, 2301, 2295, 2299, 2293, 2299, 2295, 2297, 2322, 2324, 2326, - 2317, 2326, 2328, 2317, 2328, 2330, 2322, 2326, 2317, 2319, 2322, 2317, - 2330, 2309, 2317, 2320, 2322, 2319, 2321, 2322, 2320, 2332, 2309, 2330, - 2315, 2317, 2309, 2311, 2315, 2309, 2313, 2315, 2311, 2368, 2334, 2336, - 2364, 2366, 2336, 2342, 2338, 2340, 2342, 2344, 2338, 2344, 2346, 2338, - 2336, 2338, 2364, 2336, 2366, 2368, 2338, 2346, 2364, 2346, 2362, 2364, - 2348, 2362, 2346, 2360, 2362, 2348, 2350, 2358, 2360, 2348, 2350, 2360, - 2352, 2358, 2350, 2356, 2358, 2352, 2354, 2356, 2352, 2372, 2384, 2370, - 2374, 2376, 2372, 2376, 2378, 2372, 2378, 2380, 2372, 2380, 2382, 2372, - 2382, 2384, 2372, 2386, 2370, 2384, 2338, 2370, 2386, 2336, 2370, 2338 - ] - }, - { - "id": "shape1_part3", - "type": "TRIANGLES", - "indices": [ - 122, 123, 124, 123, 125, 124, 124, 125, 126, 125, 127, 126, - 126, 127, 128, 127, 129, 128, 128, 129, 130, 129, 131, 130, - 130, 131, 132, 131, 133, 132, 132, 133, 134, 133, 135, 134, - 134, 135, 136, 135, 137, 136, 136, 137, 138, 137, 139, 138, - 138, 139, 140, 139, 141, 140, 140, 141, 122, 141, 123, 122, - 122, 122, 124, 122, 124, 124, 124, 124, 126, 124, 126, 126, - 126, 126, 128, 126, 128, 128, 128, 128, 130, 128, 130, 130, - 130, 130, 132, 130, 132, 132, 132, 132, 134, 132, 134, 134, - 134, 134, 136, 134, 136, 136, 136, 136, 138, 136, 138, 138, - 138, 138, 140, 138, 140, 140, 140, 140, 122, 140, 122, 122, - 325, 319, 321, 323, 325, 321, 329, 331, 333, 329, 333, 335, - 337, 329, 335, 327, 329, 337, 343, 339, 340, 343, 340, 341, - 657, 658, 659, 658, 514, 659, 659, 514, 660, 514, 512, 660, - 660, 512, 661, 512, 632, 661, 661, 632, 662, 632, 630, 662, - 662, 630, 663, 630, 628, 663, 663, 628, 664, 628, 665, 664, - 664, 665, 666, 665, 667, 666, 666, 667, 657, 667, 658, 657, - 657, 657, 659, 657, 659, 659, 659, 659, 660, 659, 660, 660, - 660, 660, 661, 660, 661, 661, 661, 661, 662, 661, 662, 662, - 662, 662, 663, 662, 663, 663, 663, 663, 664, 663, 664, 664, - 664, 664, 666, 664, 666, 666, 666, 666, 657, 666, 657, 657, - 657, 659, 660, 661, 657, 660, 662, 657, 661, 666, 657, 662, - 664, 666, 662, 664, 662, 663, 1367, 1363, 1365, 1371, 1367, 1369, - 1367, 1361, 1363, 1371, 1361, 1367, 1357, 1359, 1361, 1371, 1357, 1361, - 1355, 1357, 1371, 1381, 1353, 1355, 1379, 1355, 1371, 1379, 1371, 1373, - 1381, 1355, 1379, 1377, 1379, 1373, 1375, 1377, 1373, 1389, 1385, 1387, - 1383, 1385, 1389, 1403, 1395, 1397, 1395, 1391, 1393, 1405, 1395, 1403, - 1405, 1391, 1395, 1403, 1397, 1399, 1401, 1403, 1399, 1413, 1407, 1409, - 1411, 1413, 1409, 1415, 1417, 1419, 1421, 1423, 1419, 1419, 1423, 1425, - 1427, 1439, 1425, 1439, 1419, 1425, 1415, 1419, 1439, 1441, 1447, 1415, - 1441, 1415, 1439, 1437, 1439, 1427, 1443, 1445, 1447, 1443, 1447, 1441, - 1431, 1427, 1429, 1433, 1437, 1427, 1431, 1433, 1427, 1435, 1437, 1433, - 1453, 1455, 1456, 1451, 1453, 1456, 1451, 1456, 1449, 1502, 1457, 1459, - 1500, 1459, 1461, 1459, 1500, 1502, 1498, 1461, 1463, 1498, 1500, 1461, - 1499, 1500, 1498, 1465, 1497, 1498, 1465, 1498, 1463, 1497, 1465, 1467, - 1471, 1497, 1467, 1471, 1467, 1469, 1495, 1497, 1471, 1473, 1492, 1495, - 1473, 1495, 1471, 1492, 1473, 1475, 1493, 1495, 1492, 1479, 1475, 1477, - 1481, 1492, 1475, 1481, 1475, 1479, 1481, 1483, 1492, 1489, 1483, 1485, - 1489, 1485, 1487, 1483, 1491, 1492, 1489, 1491, 1483, 1519, 1529, 1504, - 1520, 1529, 1519, 1527, 1529, 1520, 1525, 1527, 1520, 1520, 1522, 1525, - 1521, 1522, 1520, 1505, 1518, 1504, 1519, 1504, 1518, 1524, 1525, 1522, - 1524, 1522, 1523, 1516, 1518, 1505, 1517, 1518, 1516, 1516, 1505, 1506, - 1513, 1511, 1512, 1515, 1516, 1506, 1508, 1510, 1511, 1508, 1511, 1513, - 1514, 1508, 1513, 1507, 1508, 1514, 1507, 1514, 1515, 1507, 1515, 1506 - ] - }, - { - "id": "shape1_part4", - "type": "TRIANGLES", - "indices": [ - 128, 130, 132, 136, 128, 132, 136, 132, 134, 126, 128, 136, - 138, 140, 124, 126, 138, 124, 122, 124, 140, 136, 138, 126 - ] - }, - { - "id": "shape1_part5", - "type": "TRIANGLES", - "indices": [ - 319, 320, 321, 320, 322, 321, 321, 322, 323, 322, 324, 323, - 323, 324, 325, 324, 326, 325, 325, 326, 319, 326, 320, 319, - 319, 319, 321, 319, 321, 321, 321, 321, 323, 321, 323, 323, - 323, 323, 325, 323, 325, 325, 325, 325, 319, 325, 319, 319, - 324, 322, 320, 326, 324, 320, 327, 328, 329, 328, 330, 329, - 329, 330, 331, 330, 332, 331, 331, 332, 333, 332, 334, 333, - 333, 334, 335, 334, 336, 335, 335, 336, 337, 336, 338, 337, - 337, 338, 327, 338, 328, 327, 327, 327, 329, 327, 329, 329, - 329, 329, 331, 329, 331, 331, 331, 331, 333, 331, 333, 333, - 333, 333, 335, 333, 335, 335, 335, 335, 337, 335, 337, 337, - 337, 337, 327, 337, 327, 327, 339, 328, 340, 328, 338, 340, - 340, 338, 341, 338, 342, 341, 341, 342, 343, 342, 344, 343, - 343, 344, 339, 344, 328, 339, 339, 339, 340, 339, 340, 340, - 340, 340, 341, 340, 341, 341, 341, 341, 343, 341, 343, 343, - 343, 343, 339, 343, 339, 339, 1353, 1354, 1355, 1354, 1356, 1355, - 1355, 1356, 1357, 1356, 1358, 1357, 1357, 1358, 1359, 1358, 1360, 1359, - 1359, 1360, 1361, 1360, 1362, 1361, 1361, 1362, 1363, 1362, 1364, 1363, - 1363, 1364, 1365, 1364, 1366, 1365, 1365, 1366, 1367, 1366, 1368, 1367, - 1367, 1368, 1369, 1368, 1370, 1369, 1369, 1370, 1371, 1370, 1372, 1371, - 1371, 1372, 1373, 1372, 1374, 1373, 1373, 1374, 1375, 1374, 1376, 1375, - 1375, 1376, 1377, 1376, 1378, 1377, 1377, 1378, 1379, 1378, 1380, 1379, - 1379, 1380, 1381, 1380, 1382, 1381, 1381, 1382, 1353, 1382, 1354, 1353, - 1353, 1353, 1355, 1353, 1355, 1355, 1355, 1355, 1357, 1355, 1357, 1357, - 1357, 1357, 1359, 1357, 1359, 1359, 1359, 1359, 1361, 1359, 1361, 1361, - 1361, 1361, 1363, 1361, 1363, 1363, 1363, 1363, 1365, 1363, 1365, 1365, - 1365, 1365, 1367, 1365, 1367, 1367, 1367, 1367, 1369, 1367, 1369, 1369, - 1369, 1369, 1371, 1369, 1371, 1371, 1371, 1371, 1373, 1371, 1373, 1373, - 1373, 1373, 1375, 1373, 1375, 1375, 1375, 1375, 1377, 1375, 1377, 1377, - 1377, 1377, 1379, 1377, 1379, 1379, 1379, 1379, 1381, 1379, 1381, 1381, - 1381, 1381, 1353, 1381, 1353, 1353, 1383, 1384, 1385, 1384, 1386, 1385, - 1385, 1386, 1387, 1386, 1388, 1387, 1387, 1388, 1389, 1388, 1390, 1389, - 1389, 1390, 1383, 1390, 1384, 1383, 1383, 1383, 1385, 1383, 1385, 1385, - 1385, 1385, 1387, 1385, 1387, 1387, 1387, 1387, 1389, 1387, 1389, 1389, - 1389, 1389, 1383, 1389, 1383, 1383, 1391, 1392, 1393, 1392, 1394, 1393, - 1393, 1394, 1395, 1394, 1396, 1395, 1395, 1396, 1397, 1396, 1398, 1397, - 1397, 1398, 1399, 1398, 1400, 1399, 1399, 1400, 1401, 1400, 1402, 1401, - 1401, 1402, 1403, 1402, 1404, 1403, 1403, 1404, 1405, 1404, 1406, 1405, - 1405, 1406, 1391, 1406, 1392, 1391, 1391, 1391, 1393, 1391, 1393, 1393, - 1393, 1393, 1395, 1393, 1395, 1395, 1395, 1395, 1397, 1395, 1397, 1397, - 1397, 1397, 1399, 1397, 1399, 1399, 1399, 1399, 1401, 1399, 1401, 1401, - 1401, 1401, 1403, 1401, 1403, 1403, 1403, 1403, 1405, 1403, 1405, 1405, - 1405, 1405, 1391, 1405, 1391, 1391, 1407, 1408, 1409, 1408, 1410, 1409, - 1409, 1410, 1411, 1410, 1412, 1411, 1411, 1412, 1413, 1412, 1414, 1413, - 1413, 1414, 1407, 1414, 1408, 1407, 1407, 1407, 1409, 1407, 1409, 1409, - 1409, 1409, 1411, 1409, 1411, 1411, 1411, 1411, 1413, 1411, 1413, 1413, - 1413, 1413, 1407, 1413, 1407, 1407, 1415, 1416, 1417, 1416, 1418, 1417, - 1417, 1418, 1419, 1418, 1420, 1419, 1419, 1420, 1421, 1420, 1422, 1421, - 1421, 1422, 1423, 1422, 1424, 1423, 1423, 1424, 1425, 1424, 1426, 1425, - 1425, 1426, 1427, 1426, 1428, 1427, 1427, 1428, 1429, 1428, 1430, 1429, - 1429, 1430, 1431, 1430, 1432, 1431, 1431, 1432, 1433, 1432, 1434, 1433, - 1433, 1434, 1435, 1434, 1436, 1435, 1435, 1436, 1437, 1436, 1438, 1437, - 1437, 1438, 1439, 1438, 1440, 1439, 1439, 1440, 1441, 1440, 1442, 1441, - 1441, 1442, 1443, 1442, 1444, 1443, 1443, 1444, 1445, 1444, 1446, 1445, - 1445, 1446, 1447, 1446, 1448, 1447, 1447, 1448, 1415, 1448, 1416, 1415, - 1415, 1415, 1417, 1415, 1417, 1417, 1417, 1417, 1419, 1417, 1419, 1419, - 1419, 1419, 1421, 1419, 1421, 1421, 1421, 1421, 1423, 1421, 1423, 1423, - 1423, 1423, 1425, 1423, 1425, 1425, 1425, 1425, 1427, 1425, 1427, 1427, - 1427, 1427, 1429, 1427, 1429, 1429, 1429, 1429, 1431, 1429, 1431, 1431, - 1431, 1431, 1433, 1431, 1433, 1433, 1433, 1433, 1435, 1433, 1435, 1435, - 1435, 1435, 1437, 1435, 1437, 1437, 1437, 1437, 1439, 1437, 1439, 1439, - 1439, 1439, 1441, 1439, 1441, 1441, 1441, 1441, 1443, 1441, 1443, 1443, - 1443, 1443, 1445, 1443, 1445, 1445, 1445, 1445, 1447, 1445, 1447, 1447, - 1447, 1447, 1415, 1447, 1415, 1415, 1449, 1450, 1451, 1450, 1452, 1451, - 1451, 1452, 1453, 1452, 1454, 1453, 1453, 1454, 1455, 1454, 1367, 1455, - 1455, 1367, 1456, 1367, 1369, 1456, 1456, 1369, 1449, 1369, 1450, 1449, - 1449, 1449, 1451, 1449, 1451, 1451, 1451, 1451, 1453, 1451, 1453, 1453, - 1453, 1453, 1455, 1453, 1455, 1455, 1455, 1455, 1456, 1455, 1456, 1456, - 1456, 1456, 1449, 1456, 1449, 1449, 1450, 1369, 1367, 1450, 1367, 1454, - 1450, 1454, 1452, 1457, 1458, 1459, 1458, 1460, 1459, 1459, 1460, 1461, - 1460, 1462, 1461, 1461, 1462, 1463, 1462, 1464, 1463, 1463, 1464, 1465, - 1464, 1466, 1465, 1465, 1466, 1467, 1466, 1468, 1467, 1467, 1468, 1469, - 1468, 1470, 1469, 1469, 1470, 1471, 1470, 1472, 1471, 1471, 1472, 1473, - 1472, 1474, 1473, 1473, 1474, 1475, 1474, 1476, 1475, 1475, 1476, 1477, - 1476, 1478, 1477, 1477, 1478, 1479, 1478, 1480, 1479, 1479, 1480, 1481, - 1480, 1482, 1481, 1481, 1482, 1483, 1482, 1484, 1483, 1483, 1484, 1485, - 1484, 1486, 1485, 1485, 1486, 1487, 1486, 1488, 1487, 1487, 1488, 1489, - 1488, 1490, 1489, 1489, 1490, 1491, 1490, 1376, 1491, 1491, 1376, 1492, - 1376, 1374, 1492, 1492, 1374, 1493, 1374, 1494, 1493, 1493, 1494, 1495, - 1494, 1496, 1495, 1495, 1496, 1497, 1496, 1370, 1497, 1497, 1370, 1498, - 1370, 1368, 1498, 1498, 1368, 1499, 1368, 1366, 1499, 1499, 1366, 1500, - 1366, 1501, 1500, 1500, 1501, 1502, 1501, 1503, 1502, 1502, 1503, 1457, - 1503, 1458, 1457, 1457, 1457, 1459, 1457, 1459, 1459, 1459, 1459, 1461, - 1459, 1461, 1461, 1461, 1461, 1463, 1461, 1463, 1463, 1463, 1463, 1465, - 1463, 1465, 1465, 1465, 1465, 1467, 1465, 1467, 1467, 1467, 1467, 1469, - 1467, 1469, 1469, 1469, 1469, 1471, 1469, 1471, 1471, 1471, 1471, 1473, - 1471, 1473, 1473, 1473, 1473, 1475, 1473, 1475, 1475, 1475, 1475, 1477, - 1475, 1477, 1477, 1477, 1477, 1479, 1477, 1479, 1479, 1479, 1479, 1481, - 1479, 1481, 1481, 1481, 1481, 1483, 1481, 1483, 1483, 1483, 1483, 1485, - 1483, 1485, 1485, 1485, 1485, 1487, 1485, 1487, 1487, 1487, 1487, 1489, - 1487, 1489, 1489, 1489, 1489, 1491, 1489, 1491, 1491, 1491, 1491, 1492, - 1491, 1492, 1492, 1492, 1492, 1493, 1492, 1493, 1493, 1493, 1493, 1495, - 1493, 1495, 1495, 1495, 1495, 1497, 1495, 1497, 1497, 1497, 1497, 1498, - 1497, 1498, 1498, 1498, 1498, 1499, 1498, 1499, 1499, 1499, 1499, 1500, - 1499, 1500, 1500, 1500, 1500, 1502, 1500, 1502, 1502, 1502, 1502, 1457, - 1502, 1457, 1457, 1504, 1360, 1505, 1360, 1358, 1505, 1505, 1358, 1506, - 1358, 1356, 1506, 1506, 1356, 1507, 1356, 1354, 1507, 1507, 1354, 1508, - 1354, 1509, 1508, 1508, 1509, 1510, 1509, 1442, 1510, 1510, 1442, 1511, - 1442, 1440, 1511, 1511, 1440, 1512, 1440, 1438, 1512, 1512, 1438, 1513, - 1438, 1436, 1513, 1513, 1436, 1514, 1436, 1434, 1514, 1514, 1434, 1515, - 1434, 1432, 1515, 1515, 1432, 1516, 1432, 1430, 1516, 1516, 1430, 1517, - 1430, 1428, 1517, 1517, 1428, 1518, 1428, 1426, 1518, 1518, 1426, 1519, - 1426, 1424, 1519, 1519, 1424, 1520, 1424, 1422, 1520, 1520, 1422, 1521, - 1422, 1420, 1521, 1521, 1420, 1522, 1420, 1418, 1522, 1522, 1418, 1523, - 1418, 1416, 1523, 1523, 1416, 1524, 1416, 1448, 1524, 1524, 1448, 1525, - 1448, 1526, 1525, 1525, 1526, 1527, 1526, 1528, 1527, 1527, 1528, 1529, - 1528, 1530, 1529, 1529, 1530, 1504, 1530, 1360, 1504, 1504, 1504, 1505, - 1504, 1505, 1505, 1505, 1505, 1506, 1505, 1506, 1506, 1506, 1506, 1507, - 1506, 1507, 1507, 1507, 1507, 1508, 1507, 1508, 1508, 1508, 1508, 1510, - 1508, 1510, 1510, 1510, 1510, 1511, 1510, 1511, 1511, 1511, 1511, 1512, - 1511, 1512, 1512, 1512, 1512, 1513, 1512, 1513, 1513, 1513, 1513, 1514, - 1513, 1514, 1514, 1514, 1514, 1515, 1514, 1515, 1515, 1515, 1515, 1516, - 1515, 1516, 1516, 1516, 1516, 1517, 1516, 1517, 1517, 1517, 1517, 1518, - 1517, 1518, 1518, 1518, 1518, 1519, 1518, 1519, 1519, 1519, 1519, 1520, - 1519, 1520, 1520, 1520, 1520, 1521, 1520, 1521, 1521, 1521, 1521, 1522, - 1521, 1522, 1522, 1522, 1522, 1523, 1522, 1523, 1523, 1523, 1523, 1524, - 1523, 1524, 1524, 1524, 1524, 1525, 1524, 1525, 1525, 1525, 1525, 1527, - 1525, 1527, 1527, 1527, 1527, 1529, 1527, 1529, 1529, 1529, 1529, 1504, - 1529, 1504, 1504 - ] - }, - { - "id": "shape1_part6", - "type": "TRIANGLES", - "indices": [ - 2195, 2196, 2197, 2196, 2198, 2197, 2197, 2198, 2199, 2198, 2200, 2199, - 2199, 2200, 2201, 2200, 2202, 2201, 2201, 2202, 1591, 2202, 1592, 1591, - 1591, 1592, 1589, 1592, 1590, 1589, 1589, 1590, 1587, 1590, 1588, 1587, - 1587, 1588, 1585, 1588, 1586, 1585, 1585, 1586, 2203, 1586, 2204, 2203, - 2203, 2204, 2195, 2204, 2196, 2195, 2195, 2195, 2197, 2195, 2197, 2197, - 2197, 2197, 2199, 2197, 2199, 2199, 2199, 2199, 2201, 2199, 2201, 2201, - 2201, 2201, 1591, 2201, 1591, 1591, 1591, 1591, 1589, 1591, 1589, 1589, - 1589, 1589, 1587, 1589, 1587, 1587, 1587, 1587, 1585, 1587, 1585, 1585, - 1585, 1585, 2203, 1585, 2203, 2203, 2203, 2203, 2195, 2203, 2195, 2195 - ] - }, - { - "id": "shape1_part7", - "type": "TRIANGLES", - "indices": [ - 1585, 2203, 2195, 1587, 1585, 2195, 1589, 1587, 2195, 2201, 1589, 2195, - 2197, 2201, 2195, 2199, 2201, 2197, 1591, 1589, 2201 - ] - }, - { - "id": "shape1_part8", - "type": "TRIANGLES", - "indices": [ - 2388, 2389, 2390, 2389, 2391, 2390, 2390, 2391, 2392, 2391, 2393, 2392, - 2392, 2393, 2394, 2393, 2395, 2394, 2394, 2395, 2396, 2395, 2397, 2396, - 2396, 2397, 2398, 2397, 2399, 2398, 2398, 2399, 2400, 2399, 2401, 2400, - 2400, 2401, 2388, 2401, 2389, 2388, 2402, 2388, 2403, 2388, 2390, 2403, - 2403, 2390, 2404, 2390, 2392, 2404, 2404, 2392, 2394, 2392, 2394, 2394, - 2394, 2394, 2405, 2394, 2396, 2405, 2405, 2396, 2406, 2396, 2398, 2406, - 2406, 2398, 2407, 2398, 2400, 2407, 2407, 2400, 2402, 2400, 2388, 2402, - 2395, 2393, 2389, 2399, 2395, 2389, 2401, 2399, 2389, 2408, 2409, 2394, - 2409, 2395, 2394, 2394, 2395, 2392, 2395, 2393, 2392, 2392, 2393, 2388, - 2393, 2389, 2388, 2388, 2389, 2400, 2389, 2401, 2400, 2400, 2401, 2410, - 2401, 2411, 2410, 2410, 2411, 2412, 2411, 2413, 2412, 2412, 2413, 2414, - 2413, 2415, 2414, 2414, 2415, 2416, 2415, 2417, 2416, 2416, 2417, 2418, - 2417, 2419, 2418, 2418, 2419, 2420, 2419, 2421, 2420, 2420, 2421, 2422, - 2421, 2423, 2422, 2422, 2423, 2424, 2423, 2425, 2424, 2424, 2425, 2426, - 2425, 2427, 2426, 2426, 2427, 2428, 2427, 2429, 2428, 2428, 2429, 2430, - 2429, 2431, 2430, 2430, 2431, 2432, 2431, 2433, 2432, 2432, 2433, 2434, - 2433, 2435, 2434, 2434, 2435, 2436, 2435, 2437, 2436, 2436, 2437, 2438, - 2437, 2439, 2438, 2438, 2439, 2440, 2439, 2441, 2440, 2440, 2441, 2442, - 2441, 2443, 2442, 2442, 2443, 2444, 2443, 2445, 2444, 2444, 2445, 2446, - 2445, 2447, 2446, 2446, 2447, 2448, 2447, 2449, 2448, 2448, 2449, 2450, - 2449, 2451, 2450, 2450, 2451, 2452, 2451, 2453, 2452, 2452, 2453, 2454, - 2453, 2455, 2454, 2454, 2455, 2456, 2455, 2457, 2456, 2456, 2457, 2458, - 2457, 2459, 2458, 2458, 2459, 2460, 2459, 2461, 2460, 2460, 2461, 2462, - 2461, 2463, 2462, 2462, 2463, 2464, 2463, 2465, 2464, 2464, 2465, 2466, - 2465, 2467, 2466, 2466, 2467, 2468, 2467, 2469, 2468, 2468, 2469, 2470, - 2469, 2471, 2470, 2470, 2471, 2472, 2471, 2473, 2472, 2472, 2473, 2474, - 2473, 2475, 2474, 2474, 2475, 2476, 2475, 2477, 2476, 2476, 2477, 2478, - 2477, 2479, 2478, 2478, 2479, 2480, 2479, 2481, 2480, 2480, 2481, 2482, - 2481, 2483, 2482, 2482, 2483, 2484, 2483, 2485, 2484, 2484, 2485, 2486, - 2485, 2487, 2486, 2486, 2487, 2488, 2487, 2489, 2488, 2488, 2489, 2490, - 2489, 2491, 2490, 2490, 2491, 2492, 2491, 2493, 2492, 2492, 2493, 2494, - 2493, 2495, 2494, 2494, 2495, 2496, 2495, 2497, 2496, 2496, 2497, 2498, - 2497, 2499, 2498, 2498, 2499, 2500, 2499, 2501, 2500, 2500, 2501, 2408, - 2501, 2409, 2408, 2408, 2408, 2394, 2408, 2394, 2394, 2394, 2394, 2392, - 2394, 2392, 2392, 2392, 2392, 2388, 2392, 2388, 2388, 2388, 2388, 2400, - 2388, 2400, 2400, 2400, 2400, 2410, 2400, 2410, 2410, 2410, 2410, 2412, - 2410, 2412, 2412, 2412, 2412, 2414, 2412, 2414, 2414, 2414, 2414, 2416, - 2414, 2416, 2416, 2416, 2416, 2418, 2416, 2418, 2418, 2418, 2418, 2420, - 2418, 2420, 2420, 2420, 2420, 2422, 2420, 2422, 2422, 2422, 2422, 2424, - 2422, 2424, 2424, 2424, 2424, 2426, 2424, 2426, 2426, 2426, 2426, 2428, - 2426, 2428, 2428, 2428, 2428, 2430, 2428, 2430, 2430, 2430, 2430, 2432, - 2430, 2432, 2432, 2432, 2432, 2434, 2432, 2434, 2434, 2434, 2434, 2436, - 2434, 2436, 2436, 2436, 2436, 2438, 2436, 2438, 2438, 2438, 2438, 2440, - 2438, 2440, 2440, 2440, 2440, 2442, 2440, 2442, 2442, 2442, 2442, 2444, - 2442, 2444, 2444, 2444, 2444, 2446, 2444, 2446, 2446, 2446, 2446, 2448, - 2446, 2448, 2448, 2448, 2448, 2450, 2448, 2450, 2450, 2450, 2450, 2452, - 2450, 2452, 2452, 2452, 2452, 2454, 2452, 2454, 2454, 2454, 2454, 2456, - 2454, 2456, 2456, 2456, 2456, 2458, 2456, 2458, 2458, 2458, 2458, 2460, - 2458, 2460, 2460, 2460, 2460, 2462, 2460, 2462, 2462, 2462, 2462, 2464, - 2462, 2464, 2464, 2464, 2464, 2466, 2464, 2466, 2466, 2466, 2466, 2468, - 2466, 2468, 2468, 2468, 2468, 2470, 2468, 2470, 2470, 2470, 2470, 2472, - 2470, 2472, 2472, 2472, 2472, 2474, 2472, 2474, 2474, 2474, 2474, 2476, - 2474, 2476, 2476, 2476, 2476, 2478, 2476, 2478, 2478, 2478, 2478, 2480, - 2478, 2480, 2480, 2480, 2480, 2482, 2480, 2482, 2482, 2482, 2482, 2484, - 2482, 2484, 2484, 2484, 2484, 2486, 2484, 2486, 2486, 2486, 2486, 2488, - 2486, 2488, 2488, 2488, 2488, 2490, 2488, 2490, 2490, 2490, 2490, 2492, - 2490, 2492, 2492, 2492, 2492, 2494, 2492, 2494, 2494, 2494, 2494, 2496, - 2494, 2496, 2496, 2496, 2496, 2498, 2496, 2498, 2498, 2498, 2498, 2500, - 2498, 2500, 2500, 2500, 2500, 2408, 2500, 2408, 2408, 2501, 2499, 2497, - 2497, 2495, 2493, 2493, 2491, 2489, 2489, 2487, 2485, 2485, 2483, 2481, - 2485, 2481, 2479, 2479, 2477, 2475, 2475, 2473, 2471, 2475, 2471, 2469, - 2479, 2475, 2469, 2485, 2479, 2469, 2489, 2485, 2469, 2467, 2465, 2463, - 2463, 2461, 2459, 2467, 2463, 2459, 2459, 2457, 2455, 2467, 2459, 2455, - 2467, 2455, 2453, 2467, 2453, 2451, 2467, 2451, 2449, 2469, 2467, 2449, - 2489, 2469, 2449, 2493, 2489, 2449, 2497, 2493, 2449, 2501, 2497, 2449, - 2409, 2501, 2449, 2449, 2447, 2445, 2449, 2445, 2443, 2449, 2443, 2441, - 2449, 2441, 2439, 2449, 2439, 2437, 2449, 2437, 2435, 2435, 2433, 2431, - 2449, 2435, 2431, 2449, 2431, 2429, 2449, 2429, 2427, 2449, 2427, 2425, - 2423, 2421, 2419, 2425, 2423, 2419, 2425, 2419, 2417, 2425, 2417, 2415, - 2425, 2415, 2413, 2425, 2413, 2411, 2425, 2411, 2401, 2425, 2401, 2389, - 2449, 2425, 2389, 2449, 2389, 2393, 2409, 2449, 2393, 2409, 2393, 2395 - ] - }, - { - "id": "shape1_part9", - "type": "TRIANGLES", - "indices": [ - 2406, 2407, 2402, 2403, 2406, 2402, 2405, 2406, 2403, 2405, 2403, 2404, - 2394, 2405, 2404, 2448, 2442, 2444, 2448, 2444, 2446, 2448, 2440, 2442, - 2448, 2468, 2440, 2466, 2468, 2448, 2466, 2448, 2450, 2470, 2440, 2468, - 2472, 2440, 2470, 2474, 2438, 2440, 2472, 2474, 2440, 2464, 2466, 2450, - 2476, 2438, 2474, 2478, 2436, 2438, 2476, 2478, 2438, 2458, 2462, 2450, - 2464, 2450, 2462, 2480, 2436, 2478, 2450, 2452, 2458, 2460, 2462, 2458, - 2482, 2436, 2480, 2454, 2458, 2452, 2484, 2436, 2482, 2434, 2436, 2484, - 2430, 2432, 2434, 2486, 2434, 2484, 2456, 2458, 2454, 2488, 2434, 2486, - 2388, 2428, 2430, 2490, 2434, 2488, 2492, 2430, 2434, 2490, 2492, 2434, - 2392, 2388, 2430, 2492, 2392, 2430, 2494, 2392, 2492, 2496, 2392, 2494, - 2388, 2426, 2428, 2424, 2426, 2388, 2424, 2388, 2422, 2422, 2388, 2420, - 2400, 2410, 2412, 2400, 2412, 2414, 2400, 2414, 2416, 2498, 2394, 2392, - 2400, 2416, 2418, 2400, 2418, 2388, 2388, 2418, 2420, 2498, 2392, 2496, - 2500, 2394, 2498, 2408, 2394, 2500 - ] - }, - { - "id": "shape2_part1", - "type": "TRIANGLES", - "indices": [ - 2502, 2503, 2504, 2503, 2505, 2504, 2504, 2505, 2506, 2505, 2507, 2506, - 2506, 2507, 2508, 2507, 2509, 2508, 2507, 2505, 2509, 2505, 2503, 2509, - 2509, 2503, 2508, 2503, 2502, 2508, 2508, 2502, 2506, 2502, 2504, 2506, - 2510, 2511, 2512, 2511, 2513, 2512, 2512, 2513, 2514, 2513, 2515, 2514, - 2514, 2515, 2516, 2515, 2517, 2516, 2515, 2513, 2517, 2513, 2511, 2517, - 2517, 2511, 2516, 2511, 2510, 2516, 2516, 2510, 2514, 2510, 2512, 2514, - 2518, 2519, 2520, 2519, 2521, 2520, 2520, 2521, 2522, 2521, 2523, 2522, - 2522, 2523, 2524, 2523, 2525, 2524, 2523, 2521, 2525, 2521, 2519, 2525, - 2525, 2519, 2524, 2519, 2518, 2524, 2524, 2518, 2522, 2518, 2520, 2522, - 2526, 2527, 2528, 2527, 2529, 2528, 2528, 2529, 2530, 2529, 2531, 2530, - 2530, 2531, 2532, 2531, 2533, 2532, 2531, 2529, 2533, 2529, 2527, 2533, - 2533, 2527, 2532, 2527, 2526, 2532, 2532, 2526, 2530, 2526, 2528, 2530, - 2534, 2535, 2536, 2535, 2537, 2536, 2536, 2537, 2538, 2537, 2539, 2538, - 2538, 2539, 2540, 2539, 2541, 2540, 2539, 2537, 2541, 2537, 2535, 2541, - 2541, 2535, 2540, 2535, 2534, 2540, 2540, 2534, 2538, 2534, 2536, 2538, - 2542, 2543, 2544, 2543, 2545, 2544, 2544, 2545, 2546, 2545, 2547, 2546, - 2546, 2547, 2548, 2547, 2549, 2548, 2547, 2545, 2549, 2545, 2543, 2549, - 2549, 2543, 2548, 2543, 2542, 2548, 2548, 2542, 2546, 2542, 2544, 2546, - 2550, 2551, 2552, 2551, 2553, 2552, 2552, 2553, 2554, 2553, 2555, 2554, - 2554, 2555, 2556, 2555, 2557, 2556, 2555, 2553, 2557, 2553, 2551, 2557, - 2557, 2551, 2556, 2551, 2550, 2556, 2556, 2550, 2554, 2550, 2552, 2554, - 2558, 2559, 2560, 2559, 2561, 2560, 2560, 2561, 2562, 2561, 2563, 2562, - 2562, 2563, 2564, 2563, 2565, 2564, 2563, 2561, 2565, 2561, 2559, 2565, - 2565, 2559, 2564, 2559, 2558, 2564, 2564, 2558, 2562, 2558, 2560, 2562, - 2566, 2567, 2568, 2567, 2569, 2568, 2568, 2569, 2570, 2569, 2571, 2570, - 2570, 2571, 2572, 2571, 2573, 2572, 2571, 2569, 2573, 2569, 2567, 2573, - 2573, 2567, 2572, 2567, 2566, 2572, 2572, 2566, 2570, 2566, 2568, 2570, - 2574, 2575, 2576, 2575, 2577, 2576, 2576, 2577, 2578, 2577, 2579, 2578, - 2578, 2579, 2580, 2579, 2581, 2580, 2579, 2577, 2581, 2577, 2575, 2581, - 2581, 2575, 2580, 2575, 2574, 2580, 2580, 2574, 2578, 2574, 2576, 2578, - 2582, 2583, 2584, 2583, 2585, 2584, 2584, 2585, 2586, 2585, 2587, 2586, - 2586, 2587, 2588, 2587, 2589, 2588, 2587, 2585, 2589, 2585, 2583, 2589, - 2589, 2583, 2588, 2583, 2582, 2588, 2588, 2582, 2586, 2582, 2584, 2586, - 2590, 2591, 2592, 2591, 2593, 2592, 2592, 2593, 2594, 2593, 2595, 2594, - 2594, 2595, 2596, 2595, 2597, 2596, 2595, 2593, 2597, 2593, 2591, 2597, - 2597, 2591, 2596, 2591, 2590, 2596, 2596, 2590, 2594, 2590, 2592, 2594 - ] - } - ] - } - ], - "materials": [ - { - "id": "ENTRANCE_DEFAULT_0", - "ambient": [ 0.101961, 0.000000, 0.000000], - "diffuse": [ 0.101961, 0.000000, 0.000000], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "BUILDING_DEFAULT_0", - "ambient": [ 0.501961, 0.450980, 0.274510], - "diffuse": [ 0.501961, 0.450980, 0.274510], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "ROOF_DEFAULT_0", - "ambient": [ 0.400000, 0.000000, 0.000000], - "diffuse": [ 0.400000, 0.000000, 0.000000], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "MAT_0_0", - "ambient": [ 0.196078, 0.196078, 0.196078], - "diffuse": [ 0.196078, 0.196078, 0.196078], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "MAT_1_0", - "ambient": [ 0.235294, 0.215686, 0.215686], - "diffuse": [ 0.235294, 0.215686, 0.215686], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "MAT_2_0", - "ambient": [ 0.470588, 0.470588, 0.470588], - "diffuse": [ 0.470588, 0.470588, 0.470588], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "MAT_3_0", - "ambient": [ 0.333333, 0.254902, 0.156863], - "diffuse": [ 0.333333, 0.254902, 0.156863], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "MAT_4_0", - "ambient": [ 0.149020, 0.149020, 0.149020], - "diffuse": [ 0.149020, 0.149020, 0.149020], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "GLASS_0", - "ambient": [ 0.450980, 0.450980, 0.450980], - "diffuse": [ 0.450980, 0.450980, 0.450980], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - }, - { - "id": "GLASS_ROOF_0", - "ambient": [ 0.450980, 0.450980, 0.450980], - "diffuse": [ 0.450980, 0.450980, 0.450980], - "specular": [ 0.200000, 0.200000, 0.200000], - "shininess": 20.000000 - } - ], - "nodes": [ - { - "id": "test_root", - "children": [ - { - "id": "Building", - "parts": [ - { - "meshpartid": "shape1_part1", - "materialid": "BUILDING_DEFAULT_0" - }, - { - "meshpartid": "shape1_part2", - "materialid": "ROOF_DEFAULT_0" - }, - { - "meshpartid": "shape1_part3", - "materialid": "MAT_0_0" - }, - { - "meshpartid": "shape1_part4", - "materialid": "MAT_1_0" - }, - { - "meshpartid": "shape1_part5", - "materialid": "MAT_2_0" - }, - { - "meshpartid": "shape1_part6", - "materialid": "MAT_3_0" - }, - { - "meshpartid": "shape1_part7", - "materialid": "MAT_4_0" - }, - { - "meshpartid": "shape1_part8", - "materialid": "GLASS_0" - }, - { - "meshpartid": "shape1_part9", - "materialid": "GLASS_ROOF_0" - } - ] - }, - { - "id": "BuildingEntrance", - "parts": [ - { - "meshpartid": "shape2_part1", - "materialid": "ENTRANCE_DEFAULT_0" - } - ] - } - ] - } - ], - "animations": [] -} \ No newline at end of file diff --git a/vtm-playground/data/g3d/tree.png b/vtm-playground/data/g3d/tree.png deleted file mode 100644 index 12950b11..00000000 Binary files a/vtm-playground/data/g3d/tree.png and /dev/null differ diff --git a/vtm-playground/data/g3d/treeA.g3dj b/vtm-playground/data/g3d/treeA.g3dj deleted file mode 100644 index 19efbbc5..00000000 --- a/vtm-playground/data/g3d/treeA.g3dj +++ /dev/null @@ -1,177 +0,0 @@ -{ - "version": [ 0, 1], - "id": "", - "meshes": [ - { - "attributes": ["POSITION", "NORMAL", "TEXCOORD0"], - "vertices": [ - -0.003717, -0.043092, 0.000001, 0.000000, -1.000000, 0.000000, 0.000000, 0.000000, - -0.003717, -0.043092, -0.019798, 0.000000, -0.609973, -0.792383, 0.000000, 0.000000, - 0.013430, -0.043092, -0.009898, 0.686239, -0.609973, -0.396191, 0.000000, 0.000000, - -0.003717, 0.527242, 0.000001, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, - 0.013430, 0.527242, -0.009898, 0.686239, 0.609973, -0.396191, 0.000000, 0.000000, - -0.003717, 0.527242, -0.019798, 0.000000, 0.609973, -0.792383, 0.000000, 0.000000, - 0.013430, -0.043092, 0.009901, 0.686239, -0.609973, 0.396191, 0.000000, 0.000000, - 0.013430, 0.527242, 0.009901, 0.686239, 0.609973, 0.396191, 0.000000, 0.000000, - -0.003717, -0.043092, 0.019801, 0.000000, -0.609973, 0.792383, 0.000000, 0.000000, - -0.003717, 0.527242, 0.019801, 0.000000, 0.609973, 0.792383, 0.000000, 0.000000, - -0.020865, -0.043092, 0.009901, -0.686239, -0.609973, 0.396191, 0.000000, 0.000000, - -0.020865, 0.527242, 0.009901, -0.686239, 0.609973, 0.396191, 0.000000, 0.000000, - -0.020865, -0.043092, -0.009898, -0.686239, -0.609973, -0.396191, 0.000000, 0.000000, - -0.020865, 0.527242, -0.009898, -0.686239, 0.609973, -0.396191, 0.000000, 0.000000, - -0.000052, 1.708732, 0.000001, 0.000000, 1.000000, 0.000000, 0.627643, 0.963260, - -0.056858, 1.692897, -0.056805, -0.359325, 0.861232, -0.359325, 0.811107, 0.943917, - -0.080388, 1.692897, 0.000001, -0.508194, 0.861232, 0.000000, 0.930977, 0.971962, - -0.112293, 1.619116, -0.112239, -0.584552, 0.562639, -0.584552, 0.871491, 0.884983, - -0.158784, 1.619116, 0.000001, -0.826655, 0.562639, 0.000000, 1.012361, 0.910828, - -0.176420, 1.422079, -0.176367, -0.675863, 0.293832, -0.675863, 0.903795, 0.728324, - -0.249474, 1.422079, 0.000001, -0.955840, 0.293832, 0.000000, 1.035246, 0.751852, - -0.210746, 1.159339, -0.210693, -0.704306, 0.088870, -0.704306, 0.922129, 0.451029, - -0.298019, 1.159339, 0.000001, -0.996033, 0.088870, 0.000000, 1.045340, 0.473093, - -0.210605, 0.903175, -0.210552, -0.705252, -0.072024, -0.705252, 0.936767, 0.254108, - -0.297820, 0.903175, 0.000001, -0.997375, -0.072024, 0.000000, 1.052424, 0.274946, - -0.180964, 0.617981, -0.180911, -0.685263, -0.246529, -0.685263, 0.956801, 0.142573, - -0.255900, 0.617981, 0.000001, -0.969115, -0.246529, 0.000000, 1.061122, 0.161660, - -0.116291, 0.378825, -0.116238, -0.610279, -0.505051, -0.610279, 0.991689, 0.079506, - -0.164439, 0.378825, 0.000001, -0.863063, -0.505051, 0.000000, 1.074527, 0.095355, - -0.059153, 0.290116, -0.059100, -0.407514, -0.817194, -0.407544, 1.038003, 0.052079, - -0.083634, 0.290116, 0.000001, -0.576312, -0.817194, 0.000000, 1.090933, 0.063214, - -0.083634, 0.290116, 0.000001, -0.576312, -0.817194, 0.000000, 0.090933, 0.063214, - -0.059153, 0.290116, -0.059100, -0.407514, -0.817194, -0.407544, 0.038003, 0.052079, - -0.000125, 0.265210, -0.000071, -0.000244, -0.999969, -0.000244, 0.127500, 0.036749, - -0.000051, 0.290116, -0.083580, 0.000000, -0.817194, -0.576312, 0.994047, 0.033372, - -0.000125, 0.265210, -0.000071, -0.000244, -0.999969, -0.000244, 1.127500, 0.036749, - -0.000051, 0.378825, -0.164386, 0.000000, -0.505051, -0.863063, 0.893772, 0.053663, - -0.000052, 0.617981, -0.255847, 0.000000, -0.246529, -0.969115, 0.836458, 0.114704, - -0.000052, 0.903175, -0.297766, 0.000000, -0.072024, -0.997375, 0.812221, 0.226047, - -0.000052, 1.159339, -0.297966, 0.000000, 0.088870, -0.996033, 0.797565, 0.423137, - -0.000052, 1.422079, -0.249421, 0.000000, 0.293832, -0.955840, 0.781975, 0.700922, - -0.000052, 1.619116, -0.158731, 0.000000, 0.562639, -0.826655, 0.759783, 0.858997, - -0.000052, 1.692897, -0.080335, 0.000000, 0.861232, -0.508194, 0.728165, 0.921879, - 0.056754, 1.692897, -0.056805, 0.359325, 0.861232, -0.359325, 0.652361, 0.910987, - 0.112189, 1.619116, -0.112239, 0.584552, 0.562639, -0.584552, 0.659906, 0.845090, - 0.176316, 1.422079, -0.176367, 0.675863, 0.293832, -0.675863, 0.665734, 0.684958, - 0.210643, 1.159339, -0.210693, 0.704306, 0.088870, -0.704306, 0.670277, 0.405750, - 0.210502, 0.903175, -0.210552, 0.705252, -0.072024, -0.705252, 0.675032, 0.207335, - 0.180860, 0.617981, -0.180910, 0.685263, -0.246529, -0.685263, 0.684415, 0.093825, - 0.116188, 0.378825, -0.116237, 0.610279, -0.505051, -0.610279, 0.723612, 0.027920, - 0.059050, 0.290116, -0.059099, 0.407483, -0.817255, -0.407422, 1.018456, 0.011649, - 0.059050, 0.290116, -0.059099, 0.407483, -0.817255, -0.407422, 0.018456, 0.011649, - 0.083530, 0.290116, 0.000002, 0.576159, -0.817316, 0.000000, 0.267608, 0.018648, - 0.164335, 0.378825, 0.000002, 0.863063, -0.505051, 0.000000, 0.457225, 0.035136, - 0.255796, 0.617981, 0.000002, 0.969115, -0.246529, 0.000000, 0.515690, 0.098717, - 0.297716, 0.903175, 0.000002, 0.997375, -0.072024, 0.000000, 0.532803, 0.211513, - 0.297915, 1.159339, 0.000002, 0.996033, 0.088870, 0.000000, 0.541872, 0.409545, - 0.249370, 1.422079, 0.000002, 0.955840, 0.293832, 0.000000, 0.550746, 0.688375, - 0.158680, 1.619116, 0.000002, 0.826655, 0.562639, 0.000000, 0.562378, 0.848006, - 0.080284, 1.692897, 0.000001, 0.508194, 0.861232, 0.000000, 0.577714, 0.913236, - 0.056754, 1.692897, 0.056808, 0.359325, 0.861232, 0.359325, 0.500528, 0.928224, - 0.112188, 1.619116, 0.112242, 0.584552, 0.562670, 0.584552, 0.459880, 0.866817, - 0.176316, 1.422079, 0.176370, 0.675863, 0.293832, 0.675863, 0.433163, 0.709519, - 0.210642, 1.159339, 0.210696, 0.704306, 0.088870, 0.704306, 0.415507, 0.432148, - 0.210501, 0.903175, 0.210555, 0.705252, -0.072024, 0.705252, 0.399773, 0.235351, - 0.180860, 0.617981, 0.180914, 0.685263, -0.246529, 0.685263, 0.375517, 0.124299, - 0.116187, 0.378825, 0.116241, 0.610279, -0.505051, 0.610279, 0.325269, 0.063109, - 0.059049, 0.290116, 0.059103, 0.407361, -0.817347, 0.407392, 0.248452, 0.040330, - -0.000053, 0.290116, 0.083583, 0.000000, -0.817316, 0.576159, 0.199939, 0.056802, - -0.000053, 0.378825, 0.164389, 0.000000, -0.505051, 0.863063, 0.234895, 0.086200, - -0.000053, 0.617981, 0.255850, 0.000000, -0.246529, 0.969115, 0.262269, 0.150492, - -0.000052, 0.903175, 0.297769, 0.000000, -0.072024, 0.997375, 0.278892, 0.262611, - -0.000052, 1.159339, 0.297968, 0.000000, 0.088870, 0.996033, 0.291619, 0.459894, - -0.000052, 1.422079, 0.249424, 0.000000, 0.293832, 0.955840, 0.308400, 0.737559, - -0.000052, 1.619116, 0.158734, 0.000000, 0.562670, 0.826655, 0.340691, 0.894603, - -0.000052, 1.692897, 0.080338, 0.000000, 0.861232, 0.508194, 0.411564, 0.953109, - -0.056858, 1.692897, 0.056808, -0.359325, 0.861232, 0.359325, 0.247502, 0.980115, - -0.112293, 1.619116, 0.112242, -0.584552, 0.562670, 0.584552, 0.186319, 0.915857, - -0.176420, 1.422079, 0.176369, -0.675863, 0.293832, 0.675863, 0.173739, 0.755927, - -0.210747, 1.159339, 0.210696, -0.704306, 0.088870, 0.704306, 0.168491, 0.476740, - -0.210606, 0.903175, 0.210555, -0.705252, -0.072024, 0.705252, 0.164886, 0.278291, - -0.180964, 0.617981, 0.180913, -0.685263, -0.246529, 0.685263, 0.160531, 0.164632, - -0.116292, 0.378825, 0.116240, -0.610279, -0.505051, 0.610279, 0.153922, 0.097744, - -0.059154, 0.290116, 0.059102, -0.407453, -0.817255, 0.407483, 0.145909, 0.064880, - -0.164439, 0.378825, 0.000001, -0.863063, -0.505051, 0.000000, 0.074527, 0.095355, - -0.255900, 0.617981, 0.000001, -0.969115, -0.246529, 0.000000, 0.061122, 0.161660, - -0.297820, 0.903175, 0.000001, -0.997375, -0.072024, 0.000000, 0.052424, 0.274946, - -0.298019, 1.159339, 0.000001, -0.996033, 0.088870, 0.000000, 0.045340, 0.473093, - -0.249474, 1.422079, 0.000001, -0.955840, 0.293832, 0.000000, 0.035246, 0.751852, - -0.158784, 1.619116, 0.000001, -0.826655, 0.562639, 0.000000, 0.012361, 0.910828, - -0.056858, 1.692897, 0.056808, -0.359325, 0.861232, 0.359325, 1.247502, 0.980115, - -0.112293, 1.619116, 0.112242, -0.584552, 0.562670, 0.584552, 1.186319, 0.915857 - ], - "parts": [ - { - "id": "mpart1", - "type": "TRIANGLES", - "indices": [ - 0, 1, 2, 3, 4, 5, 0, 2, 6, 3, 7, 4, - 0, 6, 8, 3, 9, 7, 0, 8, 10, 3, 11, 9, - 0, 10, 12, 3, 13, 11, 12, 1, 0, 3, 5, 13, - 1, 5, 4, 1, 4, 2, 2, 4, 7, 2, 7, 6, - 6, 7, 9, 6, 9, 8, 8, 9, 11, 8, 11, 10, - 10, 11, 13, 10, 13, 12, 5, 1, 12, 5, 12, 13, - 14, 15, 16, 16, 15, 17, 16, 17, 18, 18, 17, 19, - 18, 19, 20, 20, 19, 21, 20, 21, 22, 22, 21, 23, - 22, 23, 24, 24, 23, 25, 24, 25, 26, 26, 25, 27, - 26, 27, 28, 28, 27, 29, 28, 29, 30, 31, 32, 33, - 29, 34, 35, 27, 36, 34, 27, 34, 29, 25, 37, 36, - 25, 36, 27, 23, 38, 37, 23, 37, 25, 21, 39, 38, - 21, 38, 23, 19, 40, 39, 19, 39, 21, 17, 41, 40, - 17, 40, 19, 15, 42, 41, 15, 41, 17, 15, 14, 42, - 42, 14, 43, 42, 43, 44, 42, 44, 41, 41, 44, 45, - 41, 45, 40, 40, 45, 46, 40, 46, 39, 39, 46, 47, - 39, 47, 38, 38, 47, 48, 38, 48, 37, 37, 48, 49, - 37, 49, 36, 36, 49, 50, 36, 50, 34, 34, 50, 35, - 51, 52, 33, 49, 53, 52, 49, 52, 50, 48, 54, 53, - 48, 53, 49, 47, 55, 54, 47, 54, 48, 46, 56, 55, - 46, 55, 47, 45, 57, 56, 45, 56, 46, 44, 58, 57, - 44, 57, 45, 43, 59, 58, 43, 58, 44, 43, 14, 59, - 59, 14, 60, 59, 60, 61, 59, 61, 58, 58, 61, 62, - 58, 62, 57, 57, 62, 63, 57, 63, 56, 56, 63, 64, - 56, 64, 55, 55, 64, 65, 55, 65, 54, 54, 65, 66, - 54, 66, 53, 53, 66, 67, 53, 67, 52, 52, 67, 33, - 67, 68, 33, 66, 69, 68, 66, 68, 67, 65, 70, 69, - 65, 69, 66, 64, 71, 70, 64, 70, 65, 63, 72, 71, - 63, 71, 64, 62, 73, 72, 62, 72, 63, 61, 74, 73, - 61, 73, 62, 60, 75, 74, 60, 74, 61, 60, 14, 75, - 75, 14, 76, 75, 76, 77, 75, 77, 74, 74, 77, 78, - 74, 78, 73, 73, 78, 79, 73, 79, 72, 72, 79, 80, - 72, 80, 71, 71, 80, 81, 71, 81, 70, 70, 81, 82, - 70, 82, 69, 69, 82, 83, 69, 83, 68, 68, 83, 33, - 83, 31, 33, 82, 84, 31, 82, 31, 83, 81, 85, 84, - 81, 84, 82, 80, 86, 85, 80, 85, 81, 79, 87, 86, - 79, 86, 80, 78, 88, 87, 78, 87, 79, 77, 89, 88, - 77, 88, 78, 90, 16, 18, 90, 18, 91, 90, 14, 16 - - ] - } - ] - } - ], - "materials": [ - { - "id": "_tree.png", - "diffuse": [ 0.900000, 0.900000, 0.900000], - "specular": [ 0.100000, 0.100000, 0.100000], - "textures": [ - { - "id": "_tree.png", - "filename": "tree.png", - "type": "DIFFUSE" - } - ] - } - ], - "nodes": [ - { - "id": "treeA_root", - "parts": [ - { - "meshpartid": "mpart1", - "materialid": "_tree.png", - "uvMapping": [[ 0]] - } - ] - } - ], - "animations": [] -} \ No newline at end of file diff --git a/vtm-playground/resources/assets/styles/mapzen.xml b/vtm-playground/resources/assets/styles/mapzen.xml index bd1f0ac5..18e39ec4 100644 --- a/vtm-playground/resources/assets/styles/mapzen.xml +++ b/vtm-playground/resources/assets/styles/mapzen.xml @@ -1,1176 +1,1225 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - - - - - - - - - - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + > + + + + + + + + + + + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vtm-playground/resources/assets/styles/osmarender.png b/vtm-playground/resources/assets/styles/osmarender.png deleted file mode 100644 index de48e3e5..00000000 Binary files a/vtm-playground/resources/assets/styles/osmarender.png and /dev/null differ diff --git a/vtm-playground/src/org/oscim/stuff/MapzenTest.java b/vtm-playground/src/org/oscim/stuff/MapzenTest.java index cf891508..0099d460 100644 --- a/vtm-playground/src/org/oscim/stuff/MapzenTest.java +++ b/vtm-playground/src/org/oscim/stuff/MapzenTest.java @@ -31,44 +31,44 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; public class MapzenTest extends GdxMap { - @Override - protected boolean onKeyDown(int keycode) { - if (keycode == Input.Keys.A) { - loadTheme(); - } + @Override + protected boolean onKeyDown(int keycode) { + if (keycode == Input.Keys.A) { + loadTheme(); + } - return super.onKeyDown(keycode); - } + return super.onKeyDown(keycode); + } - @Override - public void createLayers() { - UrlTileSource tileSource = OSciMap4TileSource.builder() - .url("https://vector.mapzen.com/osm/v0.8/all") - .apiKey("vector-tiles-xxxxxxx") // Put a proper API key - .zoomMax(18) - .httpFactory(new OkHttpEngine.OkHttpFactory()) - .build(); + @Override + public void createLayers() { + UrlTileSource tileSource = OSciMap4TileSource.builder() + .url("https://vector.mapzen.com/osm/v0.8/all") + .apiKey("vector-tiles-xxxxxxx") // Put a proper API key + .zoomMax(18) + .httpFactory(new OkHttpEngine.OkHttpFactory()) + .build(); - VectorTileLayer l = mMap.setBaseMap(tileSource); + VectorTileLayer l = mMap.setBaseMap(tileSource); - loadTheme(); + loadTheme(); - mMap.layers().add(new BuildingLayer(mMap, l)); - mMap.layers().add(new LabelLayer(mMap, l)); + mMap.layers().add(new BuildingLayer(mMap, l)); + mMap.layers().add(new LabelLayer(mMap, l)); - mMap.setMapPosition(53.08, 8.82, 1 << 17); - } + mMap.setMapPosition(53.08, 8.82, 1 << 17); + } - private void loadTheme() { - try { - mMap.setTheme(ThemeLoader.load(getClass().getResourceAsStream("/assets/styles/mapzen.xml"))); - } catch (ThemeException e) { - e.printStackTrace(); - } - } + private void loadTheme() { + try { + mMap.setTheme(ThemeLoader.load(getClass().getResourceAsStream("/assets/styles/mapzen.xml"))); + } catch (ThemeException e) { + e.printStackTrace(); + } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new MapzenTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new MapzenTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/AnimatorTest.java b/vtm-playground/src/org/oscim/test/AnimatorTest.java index bfb85fbe..dbf59832 100644 --- a/vtm-playground/src/org/oscim/test/AnimatorTest.java +++ b/vtm-playground/src/org/oscim/test/AnimatorTest.java @@ -1,5 +1,7 @@ package org.oscim.test; +import com.badlogic.gdx.Input; + import org.oscim.core.BoundingBox; import org.oscim.gdx.GdxMap; import org.oscim.gdx.GdxMapApp; @@ -7,32 +9,30 @@ import org.oscim.renderer.MapRenderer; import org.oscim.tiling.TileSource; import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; -import com.badlogic.gdx.Input; - public class AnimatorTest extends GdxMap { - @Override - public void createLayers() { - MapRenderer.setBackgroundColor(0xff000000); + @Override + public void createLayers() { + MapRenderer.setBackgroundColor(0xff000000); - TileSource ts = new OSciMap4TileSource(); - initDefaultLayers(ts, false, false, false); + TileSource ts = new OSciMap4TileSource(); + initDefaultLayers(ts, false, false, false); - mMap.setMapPosition(0, 0, 1 << 4); + mMap.setMapPosition(0, 0, 1 << 4); - } + } - @Override - protected boolean onKeyDown(int keycode) { - if (keycode == Input.Keys.NUM_1) { - mMap.animator().animateTo(new BoundingBox(53.1, 8.8, 53.2, 8.9)); - return true; - } - return false; - } + @Override + protected boolean onKeyDown(int keycode) { + if (keycode == Input.Keys.NUM_1) { + mMap.animator().animateTo(new BoundingBox(53.1, 8.8, 53.2, 8.9)); + return true; + } + return false; + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new AnimatorTest(), null, 256); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new AnimatorTest(), null, 256); + } } diff --git a/vtm-playground/src/org/oscim/test/BitmapLayerTest.java b/vtm-playground/src/org/oscim/test/BitmapLayerTest.java index f65460a7..426d0dd3 100644 --- a/vtm-playground/src/org/oscim/test/BitmapLayerTest.java +++ b/vtm-playground/src/org/oscim/test/BitmapLayerTest.java @@ -1,9 +1,6 @@ package org.oscim.test; -import static org.oscim.tiling.source.bitmap.DefaultSources.HD_HILLSHADE; -import static org.oscim.tiling.source.bitmap.DefaultSources.OPENSTREETMAP; -import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; -import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_WATERCOLOR; +import com.badlogic.gdx.Input; import org.oscim.gdx.GdxMap; import org.oscim.gdx.GdxMapApp; @@ -12,53 +9,56 @@ import org.oscim.renderer.MapRenderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.Input; +import static org.oscim.tiling.source.bitmap.DefaultSources.HD_HILLSHADE; +import static org.oscim.tiling.source.bitmap.DefaultSources.OPENSTREETMAP; +import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; +import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_WATERCOLOR; public class BitmapLayerTest extends GdxMap { - final Logger log = LoggerFactory.getLogger(BitmapTileLayer.class); + final Logger log = LoggerFactory.getLogger(BitmapTileLayer.class); - BitmapTileLayer mLayer = null; - BitmapTileLayer mShaded = null; + BitmapTileLayer mLayer = null; + BitmapTileLayer mShaded = null; - @Override - protected boolean onKeyDown(int keycode) { - if (keycode == Input.Keys.NUM_1) { - mMap.layers().remove(mLayer); - mLayer = new BitmapTileLayer(mMap, OPENSTREETMAP.build()); - mMap.layers().add(mLayer); - return true; - } else if (keycode == Input.Keys.NUM_2) { - mMap.layers().remove(mLayer); - mLayer = new BitmapTileLayer(mMap, STAMEN_WATERCOLOR.build()); - mMap.layers().add(mLayer); - return true; - } else if (keycode == Input.Keys.NUM_3) { - if (mShaded != null) { - mMap.layers().remove(mShaded); - mShaded = null; - } else { - mShaded = new BitmapTileLayer(mMap, HD_HILLSHADE.build()); - mMap.layers().add(mShaded); - } - return true; - } + @Override + protected boolean onKeyDown(int keycode) { + if (keycode == Input.Keys.NUM_1) { + mMap.layers().remove(mLayer); + mLayer = new BitmapTileLayer(mMap, OPENSTREETMAP.build()); + mMap.layers().add(mLayer); + return true; + } else if (keycode == Input.Keys.NUM_2) { + mMap.layers().remove(mLayer); + mLayer = new BitmapTileLayer(mMap, STAMEN_WATERCOLOR.build()); + mMap.layers().add(mLayer); + return true; + } else if (keycode == Input.Keys.NUM_3) { + if (mShaded != null) { + mMap.layers().remove(mShaded); + mShaded = null; + } else { + mShaded = new BitmapTileLayer(mMap, HD_HILLSHADE.build()); + mMap.layers().add(mShaded); + } + return true; + } - return false; - } + return false; + } - @Override - public void createLayers() { - MapRenderer.setBackgroundColor(0xff888888); + @Override + public void createLayers() { + MapRenderer.setBackgroundColor(0xff888888); - mLayer = new BitmapTileLayer(mMap, STAMEN_TONER.build()); - mMap.layers().add(mLayer); + mLayer = new BitmapTileLayer(mMap, STAMEN_TONER.build()); + mMap.layers().add(mLayer); - } + } - public static void main(String[] args) { + public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new BitmapLayerTest(), null, 256); - } + GdxMapApp.init(); + GdxMapApp.run(new BitmapLayerTest(), null, 256); + } } diff --git a/vtm-playground/src/org/oscim/test/ExternalRenderThemeTest.java b/vtm-playground/src/org/oscim/test/ExternalRenderThemeTest.java index 353bad38..f055d2e8 100644 --- a/vtm-playground/src/org/oscim/test/ExternalRenderThemeTest.java +++ b/vtm-playground/src/org/oscim/test/ExternalRenderThemeTest.java @@ -1,6 +1,6 @@ package org.oscim.test; -import java.io.FileNotFoundException; +import com.badlogic.gdx.Input; import org.oscim.gdx.GdxMap; import org.oscim.gdx.GdxMapApp; @@ -11,72 +11,72 @@ import org.oscim.theme.IRenderTheme; import org.oscim.theme.ThemeLoader; import org.oscim.tiling.source.mapfile.MapFileTileSource; -import com.badlogic.gdx.Input; +import java.io.FileNotFoundException; public class ExternalRenderThemeTest extends GdxMap { - VectorTileLayer mapLayer; + VectorTileLayer mapLayer; - @Override - protected boolean onKeyDown(int keycode) { - String name = null; - if (keycode == Input.Keys.NUM_1) - name = "themes/freizeitkarte/theme.xml"; - if (keycode == Input.Keys.NUM_2) - name = "themes/elevate/theme.xml"; - if (keycode == Input.Keys.NUM_3) - name = "themes/vmap/theme.xml"; + @Override + protected boolean onKeyDown(int keycode) { + String name = null; + if (keycode == Input.Keys.NUM_1) + name = "themes/freizeitkarte/theme.xml"; + if (keycode == Input.Keys.NUM_2) + name = "themes/elevate/theme.xml"; + if (keycode == Input.Keys.NUM_3) + name = "themes/vmap/theme.xml"; - if (name == null) - return false; + if (name == null) + return false; - try { - IRenderTheme theme = ThemeLoader.load(name); - mapLayer.setRenderTheme(theme); - MapRenderer.setBackgroundColor(theme.getMapBackground()); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } + try { + IRenderTheme theme = ThemeLoader.load(name); + mapLayer.setRenderTheme(theme); + MapRenderer.setBackgroundColor(theme.getMapBackground()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } - mMap.clearMap(); - mMap.updateMap(true); - return true; - } + mMap.clearMap(); + mMap.updateMap(true); + return true; + } - @Override - public void createLayers() { - mMap.setMapPosition(53.08, 8.83, 1 << 14); + @Override + public void createLayers() { + mMap.setMapPosition(53.08, 8.83, 1 << 14); - // TileSource tileSource = new OSciMap4TileSource(); + // TileSource tileSource = new OSciMap4TileSource(); - MapFileTileSource tileSource = new MapFileTileSource(); - // tileSource.setMapFile("/home/jeff/src/vtm/Freizeitkarte_DEU_NW.map"); - tileSource.setMapFile("/home/jeff/germany.map"); + MapFileTileSource tileSource = new MapFileTileSource(); + // tileSource.setMapFile("/home/jeff/src/vtm/Freizeitkarte_DEU_NW.map"); + tileSource.setMapFile("/home/jeff/germany.map"); - VectorTileLayer l = mMap.setBaseMap(tileSource); - mapLayer = l; + VectorTileLayer l = mMap.setBaseMap(tileSource); + mapLayer = l; - // mMap.getLayers().add(new BuildingLayer(mMap, l.getTileLayer())); - mMap.layers().add(new LabelLayer(mMap, l)); + // mMap.getLayers().add(new BuildingLayer(mMap, l.getTileLayer())); + mMap.layers().add(new LabelLayer(mMap, l)); - try { - IRenderTheme theme = ThemeLoader - .load("themes/freizeitkarte/theme.xml"); - // IRenderTheme theme = - // ThemeLoader.load("themes/elevate/theme.xml"); - // IRenderTheme theme = ThemeLoader.load("themes/vmap/theme.xml"); - l.setRenderTheme(theme); - MapRenderer.setBackgroundColor(theme.getMapBackground()); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } + try { + IRenderTheme theme = ThemeLoader + .load("themes/freizeitkarte/theme.xml"); + // IRenderTheme theme = + // ThemeLoader.load("themes/elevate/theme.xml"); + // IRenderTheme theme = ThemeLoader.load("themes/vmap/theme.xml"); + l.setRenderTheme(theme); + MapRenderer.setBackgroundColor(theme.getMapBackground()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } - // mMap.getLayers().add(new GenericLayer(mMap, new MeshRenderer())); - // mMap.getLayers().add(new GenericLayer(mMap, new GridRenderer())); - } + // mMap.getLayers().add(new GenericLayer(mMap, new MeshRenderer())); + // mMap.getLayers().add(new GenericLayer(mMap, new GridRenderer())); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new ExternalRenderThemeTest(), null, 256); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new ExternalRenderThemeTest(), null, 256); + } } diff --git a/vtm-playground/src/org/oscim/test/HairLineTest.java b/vtm-playground/src/org/oscim/test/HairLineTest.java index 7fca02f9..5507512c 100644 --- a/vtm-playground/src/org/oscim/test/HairLineTest.java +++ b/vtm-playground/src/org/oscim/test/HairLineTest.java @@ -18,98 +18,98 @@ import org.oscim.theme.styles.LineStyle.LineBuilder; public class HairLineTest extends GdxMap { - static GeometryBuffer createLine(float r) { - GeometryBuffer in = new GeometryBuffer(100, 2); + static GeometryBuffer createLine(float r) { + GeometryBuffer in = new GeometryBuffer(100, 2); - for (int j = 0; j <= 12; j += 3) { - in.startLine(); - for (int i = 0; i <= 120; i++) { - double rad = Math.toRadians(i * 3); - in.addPoint((float) (Math.cos(rad) * (r + j)), (float) (Math.sin(rad) * (r + j))); - } - } - return in; - } + for (int j = 0; j <= 12; j += 3) { + in.startLine(); + for (int i = 0; i <= 120; i++) { + double rad = Math.toRadians(i * 3); + in.addPoint((float) (Math.cos(rad) * (r + j)), (float) (Math.sin(rad) * (r + j))); + } + } + return in; + } - static class Renderer extends BucketRenderer { - boolean init; - LineBuilder l = LineStyle.builder() - .color(Color.WHITE) - .strokeWidth(1.5f) - .cap(Cap.ROUND); + static class Renderer extends BucketRenderer { + boolean init; + LineBuilder l = LineStyle.builder() + .color(Color.WHITE) + .strokeWidth(1.5f) + .cap(Cap.ROUND); - HairLineBucket ll = buckets.addHairLineBucket(1, l.build()); + HairLineBucket ll = buckets.addHairLineBucket(1, l.build()); - //LineLayer ll = layers.addLineLayer(1, new LineStyle(Color.fade(Color.CYAN, 0.6f), 2.5f)); - LineStyle style = new LineStyle(Color.fade(Color.MAGENTA, 0.6f), 2.5f); + //LineLayer ll = layers.addLineLayer(1, new LineStyle(Color.fade(Color.CYAN, 0.6f), 2.5f)); + LineStyle style = new LineStyle(Color.fade(Color.MAGENTA, 0.6f), 2.5f); - HairLineBucket l1 = buckets.addHairLineBucket(2, style); + HairLineBucket l1 = buckets.addHairLineBucket(2, style); - //style = new LineStyle(Color.fade(Color.LTGRAY, 0.8f), 1.5f); - LineBucket l2 = buckets.addLineBucket(3, style); + //style = new LineStyle(Color.fade(Color.LTGRAY, 0.8f), 1.5f); + LineBucket l2 = buckets.addLineBucket(3, style); - PolygonBucket pl = buckets.addPolygonBucket(4, AreaStyle.builder() - .color(Color.BLUE) - //.outline(Color.CYAN, 1) - .build()); + PolygonBucket pl = buckets.addPolygonBucket(4, AreaStyle.builder() + .color(Color.BLUE) + //.outline(Color.CYAN, 1) + .build()); - @Override - public boolean setup() { - //ll.roundCap = true; - return super.setup(); - } + @Override + public boolean setup() { + //ll.roundCap = true; + return super.setup(); + } - @Override - public void update(GLViewport v) { - if (!init) { - mMapPosition.copy(v.pos); - init = true; - GeometryBuffer g; + @Override + public void update(GLViewport v) { + if (!init) { + mMapPosition.copy(v.pos); + init = true; + GeometryBuffer g; - for (int i = 105; i < 160; i += 30) { + for (int i = 105; i < 160; i += 30) { - g = createLine(i); + g = createLine(i); - ll.addLine(g); + ll.addLine(g); - //g.translate(10, 10); - //l1.addLine(g); + //g.translate(10, 10); + //l1.addLine(g); - // int o = 0; - // for (int k = 0; k < g.index.length && g.index[k] >= 0; k++) { - // - // for (int j = 0; j < g.index[k];) - // ll.addPoint(g.points[o + j++], g.points[o + j++]); - // - // o += g.index[k]; - // } - } - g = new GeometryBuffer(4, 2); - g.clear(); - g.startPolygon(); - g.addPoint(-100, -100); - g.addPoint(100, -100); - g.addPoint(100, 100); - g.addPoint(-100, 100); - g.translate(100, 100); - l2.addLine(g); - pl.addPolygon(g); + // int o = 0; + // for (int k = 0; k < g.index.length && g.index[k] >= 0; k++) { + // + // for (int j = 0; j < g.index[k];) + // ll.addPoint(g.points[o + j++], g.points[o + j++]); + // + // o += g.index[k]; + // } + } + g = new GeometryBuffer(4, 2); + g.clear(); + g.startPolygon(); + g.addPoint(-100, -100); + g.addPoint(100, -100); + g.addPoint(100, 100); + g.addPoint(-100, 100); + g.translate(100, 100); + l2.addLine(g); + pl.addPolygon(g); - compile(); - } - } - } + compile(); + } + } + } - @Override - protected void createLayers() { - MapRenderer.setBackgroundColor(Color.BLACK); - mMap.layers().add(new GenericLayer(mMap, new Renderer())); + @Override + protected void createLayers() { + MapRenderer.setBackgroundColor(Color.BLACK); + mMap.layers().add(new GenericLayer(mMap, new Renderer())); - } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new HairLineTest(), null, 400); + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new HairLineTest(), null, 400); - } + } } diff --git a/vtm-playground/src/org/oscim/test/LineRenderTest.java b/vtm-playground/src/org/oscim/test/LineRenderTest.java index 167b6823..84b94652 100644 --- a/vtm-playground/src/org/oscim/test/LineRenderTest.java +++ b/vtm-playground/src/org/oscim/test/LineRenderTest.java @@ -16,6 +16,8 @@ */ package org.oscim.test; +import com.badlogic.gdx.Input; + import org.oscim.backend.canvas.Color; import org.oscim.backend.canvas.Paint.Cap; import org.oscim.core.GeometryBuffer; @@ -29,198 +31,196 @@ import org.oscim.renderer.bucket.LineBucket; import org.oscim.renderer.bucket.LineTexBucket; import org.oscim.theme.styles.LineStyle; -import com.badlogic.gdx.Input; - public class LineRenderTest extends GdxMap { - GeometryBuffer mGeom = new GeometryBuffer(2, 1); - GeometryBuffer mLine = new GeometryBuffer(2, 1); + GeometryBuffer mGeom = new GeometryBuffer(2, 1); + GeometryBuffer mLine = new GeometryBuffer(2, 1); - static boolean fixedLineWidth = true; - LineTest l = new LineTest(); + static boolean fixedLineWidth = true; + LineTest l = new LineTest(); - @Override - public void createLayers() { - MapRenderer.setBackgroundColor(0xff000000); + @Override + public void createLayers() { + MapRenderer.setBackgroundColor(0xff000000); - // TileSource ts = new OSciMap4TileSource(); - // ts.setOption("url", "http://opensciencemap.org/tiles/vtm"); - // initDefaultLayers(ts, false, false, false); + // TileSource ts = new OSciMap4TileSource(); + // ts.setOption("url", "http://opensciencemap.org/tiles/vtm"); + // initDefaultLayers(ts, false, false, false); - mMap.setMapPosition(0, 0, 1 << 4); + mMap.setMapPosition(0, 0, 1 << 4); - GeometryBuffer g = mLine; - g.startLine(); - g.addPoint(-100, 0); - g.addPoint(100, 0); + GeometryBuffer g = mLine; + g.startLine(); + g.addPoint(-100, 0); + g.addPoint(100, 0); - addLines(l, 0, true, false); + addLines(l, 0, true, false); - mMap.layers().add(new GenericLayer(mMap, l)); - } + mMap.layers().add(new GenericLayer(mMap, l)); + } - void addLines(LineTest l, int layer, boolean addOutline, boolean fixed) { + void addLines(LineTest l, int layer, boolean addOutline, boolean fixed) { - GeometryBuffer g = mLine; + GeometryBuffer g = mLine; - LineStyle line1, line2, line3, line4; + LineStyle line1, line2, line3, line4; - if (fixed) { - line1 = new LineStyle(Color.RED, 0.5f); - line2 = new LineStyle(Color.GREEN, 1); - line3 = new LineStyle(Color.BLUE, 2); - line4 = new LineStyle(Color.LTGRAY, 3); + if (fixed) { + line1 = new LineStyle(Color.RED, 0.5f); + line2 = new LineStyle(Color.GREEN, 1); + line3 = new LineStyle(Color.BLUE, 2); + line4 = new LineStyle(Color.LTGRAY, 3); - } else { - line1 = new LineStyle(0, null, Color.fade(Color.RED, 0.5f), 4.0f, - Cap.BUTT, false, 0, 0, 0, 0, 1f, false); + } else { + line1 = new LineStyle(0, null, Color.fade(Color.RED, 0.5f), 4.0f, + Cap.BUTT, false, 0, 0, 0, 0, 1f, false); - line2 = new LineStyle(0, null, Color.GREEN, 6.0f, Cap.BUTT, true, 0, 0, - 0, 0, 1f, false); + line2 = new LineStyle(0, null, Color.GREEN, 6.0f, Cap.BUTT, true, 0, 0, + 0, 0, 1f, false); - line3 = new LineStyle(0, null, Color.BLUE, 2.0f, Cap.ROUND, false, 4, - Color.CYAN, 1, 0, 0, false); + line3 = new LineStyle(0, null, Color.BLUE, 2.0f, Cap.ROUND, false, 4, + Color.CYAN, 1, 0, 0, false); - line4 = new LineStyle(0, null, Color.LTGRAY, 2.0f, Cap.ROUND, false, 0, - 0, 0, 0, 1f, false); - } + line4 = new LineStyle(0, null, Color.LTGRAY, 2.0f, Cap.ROUND, false, 0, + 0, 0, 0, 1f, false); + } - LineStyle outline = new LineStyle(0, null, Color.BLUE, 2.0f, Cap.ROUND, false, 0, - 0, 0, 0, 1f, true); + LineStyle outline = new LineStyle(0, null, Color.BLUE, 2.0f, Cap.ROUND, false, 0, + 0, 0, 0, 1f, true); - LineStyle outline2 = new LineStyle(0, null, Color.RED, 2.0f, Cap.ROUND, false, 0, - 0, 0, 0, 0, true); + LineStyle outline2 = new LineStyle(0, null, Color.RED, 2.0f, Cap.ROUND, false, 0, + 0, 0, 0, 0, true); - LineBucket ol = l.buckets.addLineBucket(0, outline); - LineBucket ol2 = l.buckets.addLineBucket(5, outline2); + LineBucket ol = l.buckets.addLineBucket(0, outline); + LineBucket ol2 = l.buckets.addLineBucket(5, outline2); - LineBucket ll = l.buckets.addLineBucket(10, line1); - ll.addLine(g.translate(0, -20)); - ll.addLine(g.translate(0, 10.5f)); - addCircle(-200, -200, 100, ll); + LineBucket ll = l.buckets.addLineBucket(10, line1); + ll.addLine(g.translate(0, -20)); + ll.addLine(g.translate(0, 10.5f)); + addCircle(-200, -200, 100, ll); - if (addOutline) - ol.addOutline(ll); + if (addOutline) + ol.addOutline(ll); - ll = l.buckets.addLineBucket(20, line2); - ll.addLine(g.translate(0, 10.5f)); - ll.addLine(g.translate(0, 10.5f)); - addCircle(200, -200, 100, ll); + ll = l.buckets.addLineBucket(20, line2); + ll.addLine(g.translate(0, 10.5f)); + ll.addLine(g.translate(0, 10.5f)); + addCircle(200, -200, 100, ll); - if (addOutline) - ol.addOutline(ll); + if (addOutline) + ol.addOutline(ll); - LineTexBucket lt = l.buckets.getLineTexBucket(30); - lt.line = line3; - lt.width = line3.width; - lt.addLine(g.translate(0, 10.5f)); - lt.addLine(g.translate(0, 10.5f)); - addCircle(200, 200, 100, lt); + LineTexBucket lt = l.buckets.getLineTexBucket(30); + lt.line = line3; + lt.width = line3.width; + lt.addLine(g.translate(0, 10.5f)); + lt.addLine(g.translate(0, 10.5f)); + addCircle(200, 200, 100, lt); - // if (addOutline) - // ol2.addOutline(ll); + // if (addOutline) + // ol2.addOutline(ll); - ll = l.buckets.addLineBucket(40, line4); - ll.addLine(g.translate(0, 10.5f)); - ll.addLine(g.translate(0, 10.5f)); - addCircle(-200, 200, 100, ll); + ll = l.buckets.addLineBucket(40, line4); + ll.addLine(g.translate(0, 10.5f)); + ll.addLine(g.translate(0, 10.5f)); + addCircle(-200, 200, 100, ll); - if (addOutline) - ol2.addOutline(ll); - } + if (addOutline) + ol2.addOutline(ll); + } - void addCircle(float cx, float cy, float radius, LineBucket ll) { - GeometryBuffer g = mGeom; + void addCircle(float cx, float cy, float radius, LineBucket ll) { + GeometryBuffer g = mGeom; - g.clear(); - g.startLine(); - g.addPoint(cx, cy); - g.addPoint(cx, cy); + g.clear(); + g.startLine(); + g.addPoint(cx, cy); + g.addPoint(cx, cy); - for (int i = 0; i < 60; i++) { - double d = Math.toRadians(i * 6); - g.setPoint(1, cx + (float) Math.sin(d) * radius, - cy + (float) Math.cos(d) * radius); - ll.addLine(g); - } - } + for (int i = 0; i < 60; i++) { + double d = Math.toRadians(i * 6); + g.setPoint(1, cx + (float) Math.sin(d) * radius, + cy + (float) Math.cos(d) * radius); + ll.addLine(g); + } + } - void addCircle(float cx, float cy, float radius, LineTexBucket ll) { - GeometryBuffer g = mGeom; + void addCircle(float cx, float cy, float radius, LineTexBucket ll) { + GeometryBuffer g = mGeom; - g.clear(); - g.startLine(); - g.addPoint(cx, cy); - g.addPoint(cx, cy); + g.clear(); + g.startLine(); + g.addPoint(cx, cy); + g.addPoint(cx, cy); - for (int i = 0; i < 60; i++) { - double d = Math.toRadians(i * 6); - g.setPoint(1, cx + (float) Math.sin(d) * radius, - cy + (float) Math.cos(d) * radius); - ll.addLine(g); - } - } + for (int i = 0; i < 60; i++) { + double d = Math.toRadians(i * 6); + g.setPoint(1, cx + (float) Math.sin(d) * radius, + cy + (float) Math.cos(d) * radius); + ll.addLine(g); + } + } - @Override - protected boolean onKeyDown(int keycode) { - if (keycode < Input.Keys.NUM_1 || keycode > Input.Keys.NUM_4) - return false; + @Override + protected boolean onKeyDown(int keycode) { + if (keycode < Input.Keys.NUM_1 || keycode > Input.Keys.NUM_4) + return false; - synchronized (l) { - l.clear(); + synchronized (l) { + l.clear(); - GeometryBuffer g = mLine; - g.clear(); - g.startLine(); - g.addPoint(-100, 0); - g.addPoint(100, 0); + GeometryBuffer g = mLine; + g.clear(); + g.startLine(); + g.addPoint(-100, 0); + g.addPoint(100, 0); - if (keycode == Input.Keys.NUM_1) - addLines(l, 0, true, true); - else if (keycode == Input.Keys.NUM_2) - addLines(l, 0, true, false); - else if (keycode == Input.Keys.NUM_3) - addLines(l, 0, false, true); - else if (keycode == Input.Keys.NUM_4) - addLines(l, 0, false, false); - } + if (keycode == Input.Keys.NUM_1) + addLines(l, 0, true, true); + else if (keycode == Input.Keys.NUM_2) + addLines(l, 0, true, false); + else if (keycode == Input.Keys.NUM_3) + addLines(l, 0, false, true); + else if (keycode == Input.Keys.NUM_4) + addLines(l, 0, false, false); + } - mMap.updateMap(true); + mMap.updateMap(true); - return true; - } + return true; + } - class LineTest extends BucketRenderer { + class LineTest extends BucketRenderer { - public LineTest() { - mMapPosition.scale = 0; - } + public LineTest() { + mMapPosition.scale = 0; + } - public synchronized void clear() { - buckets.clear(); - setReady(false); - } + public synchronized void clear() { + buckets.clear(); + setReady(false); + } - @Override - public synchronized void update(GLViewport v) { + @Override + public synchronized void update(GLViewport v) { - if (mMapPosition.scale == 0) - mMapPosition.copy(v.pos); + if (mMapPosition.scale == 0) + mMapPosition.copy(v.pos); - if (!isReady()) { - compile(); - } - } + if (!isReady()) { + compile(); + } + } - // @Override - // protected void setMatrix(MapPosition pos, Matrices m, boolean - // project) { - // m.useScreenCoordinates(true, 8f); - // } - } + // @Override + // protected void setMatrix(MapPosition pos, Matrices m, boolean + // project) { + // m.useScreenCoordinates(true, 8f); + // } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new LineRenderTest(), null, 256); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new LineRenderTest(), null, 256); + } } diff --git a/vtm-playground/src/org/oscim/test/LineTest.java b/vtm-playground/src/org/oscim/test/LineTest.java index f29141e2..5dcce07a 100644 --- a/vtm-playground/src/org/oscim/test/LineTest.java +++ b/vtm-playground/src/org/oscim/test/LineTest.java @@ -1,5 +1,8 @@ package org.oscim.test; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.Input; + import org.oscim.backend.canvas.Color; import org.oscim.core.GeometryBuffer; import org.oscim.gdx.GdxMap; @@ -11,100 +14,97 @@ import org.oscim.renderer.MapRenderer; import org.oscim.renderer.bucket.LineBucket; import org.oscim.theme.styles.LineStyle; -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.Input; - public class LineTest extends GdxMap { - @Override - protected boolean onKeyDown(int keycode) { - if (keycode == Input.Keys.NUM_1) { - angle++; - mMap.render(); - return true; + @Override + protected boolean onKeyDown(int keycode) { + if (keycode == Input.Keys.NUM_1) { + angle++; + mMap.render(); + return true; - } + } - if (keycode == Input.Keys.NUM_2) { - angle--; - mMap.render(); - return true; + if (keycode == Input.Keys.NUM_2) { + angle--; + mMap.render(); + return true; - } - return false; - } + } + return false; + } - float angle = 0; + float angle = 0; - @Override - protected void createLayers() { - mMap.layers().add(new GenericLayer(mMap, new BucketRenderer() { - boolean init; + @Override + protected void createLayers() { + mMap.layers().add(new GenericLayer(mMap, new BucketRenderer() { + boolean init; - LineBucket ll = buckets.addLineBucket(0, - new LineStyle(Color.fade(Color.CYAN, 0.5f), 1.5f)); + LineBucket ll = buckets.addLineBucket(0, + new LineStyle(Color.fade(Color.CYAN, 0.5f), 1.5f)); - GeometryBuffer g = new GeometryBuffer(10, 1); + GeometryBuffer g = new GeometryBuffer(10, 1); - @Override - public void update(GLViewport v) { - if (!init) { - mMapPosition.copy(v.pos); - init = true; + @Override + public void update(GLViewport v) { + if (!init) { + mMapPosition.copy(v.pos); + init = true; - // g.addPoint(0, 0); - // g.addPoint(0, 1); - // g.addPoint(0.1f, 0); - // - // g.addPoint(1, 1); - // g.addPoint(2, 0); - // - // g.addPoint(2, 1); - // g.addPoint(2, 0); - // - // g.addPoint(3, 1); - // g.addPoint(3, 0); - // g.addPoint(3, 1); - // - // for (int i = 0; i < 60; i++){ - // g.startLine(); - // g.addPoint(0, 0); - // g.addPoint(0, 1); - // } - // - // g.scale(100, 100); - // - // ll.addLine(g); - // - // compile(); - } + // g.addPoint(0, 0); + // g.addPoint(0, 1); + // g.addPoint(0.1f, 0); + // + // g.addPoint(1, 1); + // g.addPoint(2, 0); + // + // g.addPoint(2, 1); + // g.addPoint(2, 0); + // + // g.addPoint(3, 1); + // g.addPoint(3, 0); + // g.addPoint(3, 1); + // + // for (int i = 0; i < 60; i++){ + // g.startLine(); + // g.addPoint(0, 0); + // g.addPoint(0, 1); + // } + // + // g.scale(100, 100); + // + // ll.addLine(g); + // + // compile(); + } - buckets.clear(); - buckets.set(ll); - g.clear(); - //for (int i = 0; i < 60; i++) { - g.startLine(); - g.addPoint(-1, 0); - g.addPoint(0, 0); - g.addPoint((float) Math.cos(Math.toRadians(angle)), - (float) Math.sin(Math.toRadians(angle))); - //} + buckets.clear(); + buckets.set(ll); + g.clear(); + //for (int i = 0; i < 60; i++) { + g.startLine(); + g.addPoint(-1, 0); + g.addPoint(0, 0); + g.addPoint((float) Math.cos(Math.toRadians(angle)), + (float) Math.sin(Math.toRadians(angle))); + //} - g.scale(100, 100); + g.scale(100, 100); - ll.addLine(g); + ll.addLine(g); - compile(); + compile(); - angle = Gdx.input.getX() / 2f % 360; + angle = Gdx.input.getX() / 2f % 360; - MapRenderer.animate(); - } - })); - } + MapRenderer.animate(); + } + })); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new LineTest(), null, 256); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new LineTest(), null, 256); + } } diff --git a/vtm-playground/src/org/oscim/test/MapTest.java b/vtm-playground/src/org/oscim/test/MapTest.java index de502932..309e7f52 100644 --- a/vtm-playground/src/org/oscim/test/MapTest.java +++ b/vtm-playground/src/org/oscim/test/MapTest.java @@ -10,21 +10,21 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; public class MapTest extends GdxMapApp { - @Override - public void createLayers() { - Map map = getMap(); + @Override + public void createLayers() { + Map map = getMap(); - VectorTileLayer l = map.setBaseMap(new OSciMap4TileSource()); + VectorTileLayer l = map.setBaseMap(new OSciMap4TileSource()); - map.layers().add(new BuildingLayer(map, l)); - map.layers().add(new LabelLayer(map, l)); + map.layers().add(new BuildingLayer(map, l)); + map.layers().add(new LabelLayer(map, l)); - map.setTheme(VtmThemes.DEFAULT); - map.setMapPosition(53.075, 8.808, 1 << 17); - } + map.setTheme(VtmThemes.DEFAULT); + map.setMapPosition(53.075, 8.808, 1 << 17); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new MapTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new MapTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/MapsforgeTest.java b/vtm-playground/src/org/oscim/test/MapsforgeTest.java index 5efa76c6..a8086d2c 100644 --- a/vtm-playground/src/org/oscim/test/MapsforgeTest.java +++ b/vtm-playground/src/org/oscim/test/MapsforgeTest.java @@ -31,46 +31,46 @@ import java.io.File; public class MapsforgeTest extends GdxMap { - private static File mapFile; + private static File mapFile; - @Override - public void createLayers() { - MapFileTileSource tileSource = new MapFileTileSource(); - tileSource.setMapFile(mapFile.getAbsolutePath()); - tileSource.setPreferredLanguage("en"); + @Override + public void createLayers() { + MapFileTileSource tileSource = new MapFileTileSource(); + tileSource.setMapFile(mapFile.getAbsolutePath()); + tileSource.setPreferredLanguage("en"); - VectorTileLayer l = mMap.setBaseMap(tileSource); - mMap.setTheme(VtmThemes.DEFAULT); + VectorTileLayer l = mMap.setBaseMap(tileSource); + mMap.setTheme(VtmThemes.DEFAULT); - mMap.layers().add(new BuildingLayer(mMap, l)); - mMap.layers().add(new LabelLayer(mMap, l)); + mMap.layers().add(new BuildingLayer(mMap, l)); + mMap.layers().add(new LabelLayer(mMap, l)); - MapInfo info = tileSource.getMapInfo(); - MapPosition pos = new MapPosition(); - pos.setByBoundingBox(info.boundingBox, Tile.SIZE * 4, Tile.SIZE * 4); - mMap.setMapPosition(pos); - } + MapInfo info = tileSource.getMapInfo(); + MapPosition pos = new MapPosition(); + pos.setByBoundingBox(info.boundingBox, Tile.SIZE * 4, Tile.SIZE * 4); + mMap.setMapPosition(pos); + } - private static File getMapFile(String[] args) { - if (args.length == 0) { - throw new IllegalArgumentException("missing argument: "); - } + private static File getMapFile(String[] args) { + if (args.length == 0) { + throw new IllegalArgumentException("missing argument: "); + } - File file = new File(args[0]); - if (!file.exists()) { - throw new IllegalArgumentException("file does not exist: " + file); - } else if (!file.isFile()) { - throw new IllegalArgumentException("not a file: " + file); - } else if (!file.canRead()) { - throw new IllegalArgumentException("cannot read file: " + file); - } - return file; - } + File file = new File(args[0]); + if (!file.exists()) { + throw new IllegalArgumentException("file does not exist: " + file); + } else if (!file.isFile()) { + throw new IllegalArgumentException("not a file: " + file); + } else if (!file.canRead()) { + throw new IllegalArgumentException("cannot read file: " + file); + } + return file; + } - public static void main(String[] args) { - mapFile = getMapFile(args); + public static void main(String[] args) { + mapFile = getMapFile(args); - GdxMapApp.init(); - GdxMapApp.run(new MapsforgeTest(), null, 400); - } + GdxMapApp.init(); + GdxMapApp.run(new MapsforgeTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/PathLayerTest.java b/vtm-playground/src/org/oscim/test/PathLayerTest.java index 7894ff8d..a45e67b7 100644 --- a/vtm-playground/src/org/oscim/test/PathLayerTest.java +++ b/vtm-playground/src/org/oscim/test/PathLayerTest.java @@ -16,9 +16,6 @@ */ package org.oscim.test; -import java.util.ArrayList; -import java.util.List; - import org.oscim.backend.canvas.Color; import org.oscim.core.GeoPoint; import org.oscim.core.MapPosition; @@ -29,74 +26,77 @@ import org.oscim.layers.tile.bitmap.BitmapTileLayer; import org.oscim.map.Map.UpdateListener; import org.oscim.tiling.source.bitmap.DefaultSources; +import java.util.ArrayList; +import java.util.List; + public class PathLayerTest extends GdxMapApp { - @Override - public void createLayers() { - mMap.setBaseMap(new BitmapTileLayer(mMap, DefaultSources.STAMEN_TONER.build())); + @Override + public void createLayers() { + mMap.setBaseMap(new BitmapTileLayer(mMap, DefaultSources.STAMEN_TONER.build())); - createLayers(1, true); + createLayers(1, true); - mMap.setMapPosition(0, 0, 1 << 2); + mMap.setMapPosition(0, 0, 1 << 2); - mMap.events.bind(new UpdateListener() { - @Override - public void onMapEvent(Event e, MapPosition mapPosition) { - //if (e == Map.UPDATE_EVENT) { - long t = System.currentTimeMillis(); - float pos = t % 20000 / 10000f - 1f; - createLayers(pos, false); - mMap.updateMap(true); - //} - } - }); - } + mMap.events.bind(new UpdateListener() { + @Override + public void onMapEvent(Event e, MapPosition mapPosition) { + //if (e == Map.UPDATE_EVENT) { + long t = System.currentTimeMillis(); + float pos = t % 20000 / 10000f - 1f; + createLayers(pos, false); + mMap.updateMap(true); + //} + } + }); + } - ArrayList mPathLayers = new ArrayList<>(); + ArrayList mPathLayers = new ArrayList<>(); - void createLayers(float pos, boolean init) { + void createLayers(float pos, boolean init) { - int i = 0; + int i = 0; - for (double lat = -90; lat <= 90; lat += 5) { - List pts = new ArrayList<>(); + for (double lat = -90; lat <= 90; lat += 5) { + List pts = new ArrayList<>(); - for (double lon = -180; lon <= 180; lon += 2) { - //pts.add(new GeoPoint(lat, lon)); - // double longitude = lon + (pos * 180); - // if (longitude < -180) - // longitude += 360; - // if (longitude > 180) - // longitude -= 360; - double longitude = lon; + for (double lon = -180; lon <= 180; lon += 2) { + //pts.add(new GeoPoint(lat, lon)); + // double longitude = lon + (pos * 180); + // if (longitude < -180) + // longitude += 360; + // if (longitude > 180) + // longitude -= 360; + double longitude = lon; - double latitude = lat + (pos * 90); - if (latitude < -90) - latitude += 180; - if (latitude > 90) - latitude -= 180; + double latitude = lat + (pos * 90); + if (latitude < -90) + latitude += 180; + if (latitude > 90) + latitude -= 180; - latitude += Math.sin((Math.abs(pos) * (lon / Math.PI))); + latitude += Math.sin((Math.abs(pos) * (lon / Math.PI))); - pts.add(new GeoPoint(latitude, longitude)); - } - JtsPathLayer pathLayer; - if (init) { - int c = Color.fade(Color.rainbow((float) (lat + 90) / 180), 0.5f); - pathLayer = new JtsPathLayer(mMap, c, 6); - mMap.layers().add(pathLayer); - mPathLayers.add(pathLayer); - } else { - pathLayer = mPathLayers.get(i++); - } + pts.add(new GeoPoint(latitude, longitude)); + } + JtsPathLayer pathLayer; + if (init) { + int c = Color.fade(Color.rainbow((float) (lat + 90) / 180), 0.5f); + pathLayer = new JtsPathLayer(mMap, c, 6); + mMap.layers().add(pathLayer); + mPathLayers.add(pathLayer); + } else { + pathLayer = mPathLayers.get(i++); + } - pathLayer.setPoints(pts); - } + pathLayer.setPoints(pts); + } - } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new PathLayerTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new PathLayerTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/RuleVisitorTest.java b/vtm-playground/src/org/oscim/test/RuleVisitorTest.java index a935b6ca..32946d60 100644 --- a/vtm-playground/src/org/oscim/test/RuleVisitorTest.java +++ b/vtm-playground/src/org/oscim/test/RuleVisitorTest.java @@ -1,6 +1,6 @@ package org.oscim.test; -import static org.oscim.utils.ColorUtil.saturate; +import com.badlogic.gdx.Input; import org.oscim.gdx.GdxMap; import org.oscim.gdx.GdxMapApp; @@ -20,104 +20,104 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.Input; +import static org.oscim.utils.ColorUtil.saturate; public class RuleVisitorTest extends GdxMap { - final Logger log = LoggerFactory.getLogger(RuleVisitorTest.class); - RenderTheme mTheme; - double mSaturation = 1; + final Logger log = LoggerFactory.getLogger(RuleVisitorTest.class); + RenderTheme mTheme; + double mSaturation = 1; - @Override - protected boolean onKeyDown(int keycode) { - VectorTileLayer l = (VectorTileLayer) mMap.layers().get(1); - RenderTheme t = (RenderTheme) l.getTheme(); + @Override + protected boolean onKeyDown(int keycode) { + VectorTileLayer l = (VectorTileLayer) mMap.layers().get(1); + RenderTheme t = (RenderTheme) l.getTheme(); - if (keycode == Input.Keys.NUM_1) { - mSaturation += 0.1; - t.traverseRules(new SaturateLineStyles(mSaturation, true, true, true)); - t.updateStyles(); - mMap.render(); - return true; - } - if (keycode == Input.Keys.NUM_2) { - mSaturation -= 0.1; - t.traverseRules(new SaturateLineStyles(mSaturation, true, true, true)); - t.updateStyles(); - mMap.render(); - return true; - } + if (keycode == Input.Keys.NUM_1) { + mSaturation += 0.1; + t.traverseRules(new SaturateLineStyles(mSaturation, true, true, true)); + t.updateStyles(); + mMap.render(); + return true; + } + if (keycode == Input.Keys.NUM_2) { + mSaturation -= 0.1; + t.traverseRules(new SaturateLineStyles(mSaturation, true, true, true)); + t.updateStyles(); + mMap.render(); + return true; + } - return super.onKeyDown(keycode); - } + return super.onKeyDown(keycode); + } - @Override - public void createLayers() { - MapRenderer.setBackgroundColor(0xf0f0f0); + @Override + public void createLayers() { + MapRenderer.setBackgroundColor(0xf0f0f0); - TileSource ts = new OSciMap4TileSource(); - VectorTileLayer l = mMap.setBaseMap(ts); + TileSource ts = new OSciMap4TileSource(); + VectorTileLayer l = mMap.setBaseMap(ts); - mMap.setTheme(VtmThemes.DEFAULT); - RenderTheme t = (RenderTheme) l.getTheme(); - mTheme = t; - //t.traverseRules(new DesaturateAreaStyles()); - //t.traverseRules(new DesaturateLineStyles()); - t.traverseRules(new SaturateLineStyles(0.5, true, true, true)); - t.updateStyles(); + mMap.setTheme(VtmThemes.DEFAULT); + RenderTheme t = (RenderTheme) l.getTheme(); + mTheme = t; + //t.traverseRules(new DesaturateAreaStyles()); + //t.traverseRules(new DesaturateLineStyles()); + t.traverseRules(new SaturateLineStyles(0.5, true, true, true)); + t.updateStyles(); - //mMap.setMapPosition(7.707, 81.689, 1 << 16); + //mMap.setMapPosition(7.707, 81.689, 1 << 16); - mMap.setMapPosition(53.08, 8.82, 1 << 16); - } + mMap.setMapPosition(53.08, 8.82, 1 << 16); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new RuleVisitorTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new RuleVisitorTest(), null, 400); + } - static class SaturateLineStyles extends RuleVisitor { - private final LineBuilder lineBuilder = LineStyle.builder(); - private final AreaBuilder areaBuilder = AreaStyle.builder(); + static class SaturateLineStyles extends RuleVisitor { + private final LineBuilder lineBuilder = LineStyle.builder(); + private final AreaBuilder areaBuilder = AreaStyle.builder(); - private final double saturation; - private final boolean modifyArea; - private final boolean modifyLine; - private final boolean relative; + private final double saturation; + private final boolean modifyArea; + private final boolean modifyLine; + private final boolean relative; - public SaturateLineStyles(double saturation, boolean relative, boolean modArea, - boolean modLine) { - this.saturation = saturation; - this.modifyArea = modArea; - this.modifyLine = modLine; - this.relative = relative; - } + public SaturateLineStyles(double saturation, boolean relative, boolean modArea, + boolean modLine) { + this.saturation = saturation; + this.modifyArea = modArea; + this.modifyLine = modLine; + this.relative = relative; + } - @Override - public void apply(Rule r) { - for (RenderStyle style : r.styles) { + @Override + public void apply(Rule r) { + for (RenderStyle style : r.styles) { - if (modifyLine && style instanceof LineStyle) { - LineStyle s = (LineStyle) style; + if (modifyLine && style instanceof LineStyle) { + LineStyle s = (LineStyle) style; - s.set(lineBuilder.set(s) - .color(saturate(s.color, saturation, relative)) - .stippleColor(saturate(s.stippleColor, saturation, relative)) - .build()); - continue; - } + s.set(lineBuilder.set(s) + .color(saturate(s.color, saturation, relative)) + .stippleColor(saturate(s.stippleColor, saturation, relative)) + .build()); + continue; + } - if (modifyArea && style instanceof AreaStyle) { - AreaStyle s = (AreaStyle) style; + if (modifyArea && style instanceof AreaStyle) { + AreaStyle s = (AreaStyle) style; - s.set(areaBuilder.set(s) - .color(saturate(s.color, saturation, relative)) - .blendColor(saturate(s.blendColor, saturation, relative)) - .build()); - } - } + s.set(areaBuilder.set(s) + .color(saturate(s.color, saturation, relative)) + .blendColor(saturate(s.blendColor, saturation, relative)) + .build()); + } + } - super.apply(r); - } - } + super.apply(r); + } + } } diff --git a/vtm-playground/src/org/oscim/test/S3DBLayerTest.java b/vtm-playground/src/org/oscim/test/S3DBLayerTest.java index aba72547..bcb10d65 100644 --- a/vtm-playground/src/org/oscim/test/S3DBLayerTest.java +++ b/vtm-playground/src/org/oscim/test/S3DBLayerTest.java @@ -24,25 +24,25 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; public class S3DBLayerTest extends GdxMapApp { - @Override - public void createLayers() { - mMap.setBaseMap(new OSciMap4TileSource()); - mMap.setTheme(VtmThemes.DEFAULT); + @Override + public void createLayers() { + mMap.setBaseMap(new OSciMap4TileSource()); + mMap.setTheme(VtmThemes.DEFAULT); - TileSource ts = OSciMap4TileSource - .builder() - .url("http://opensciencemap.org/tiles/s3db") - .build(); + TileSource ts = OSciMap4TileSource + .builder() + .url("http://opensciencemap.org/tiles/s3db") + .build(); - S3DBLayer tl = new S3DBLayer(mMap, ts); - mMap.layers().add(tl); + S3DBLayer tl = new S3DBLayer(mMap, ts); + mMap.layers().add(tl); - mMap.setMapPosition(53.08, 8.82, 1 << 17); + mMap.setMapPosition(53.08, 8.82, 1 << 17); - } + } - public static void main(String[] args) { - init(); - run(new S3DBLayerTest(), null, 400); - } + public static void main(String[] args) { + init(); + run(new S3DBLayerTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/SpriteManager.java b/vtm-playground/src/org/oscim/test/SpriteManager.java index 34a12c13..17b2d8d6 100644 --- a/vtm-playground/src/org/oscim/test/SpriteManager.java +++ b/vtm-playground/src/org/oscim/test/SpriteManager.java @@ -26,79 +26,79 @@ import org.oscim.utils.pool.Inlist; /** * UNUSED - * */ + */ public abstract class SpriteManager { - TexturePool pool; + TexturePool pool; - public class Sprite extends Inlist { + public class Sprite extends Inlist { - public Sprite(T i, TextureAtlas a, Rect r) { - atlas = a; - rect = r; - item = i; - } + public Sprite(T i, TextureAtlas a, Rect r) { + atlas = a; + rect = r; + item = i; + } - T item; - TextureAtlas atlas; - Rect rect; - } + T item; + TextureAtlas atlas; + Rect rect; + } - TextureAtlas mAtlas; - TextureAtlas curAtlas; + TextureAtlas mAtlas; + TextureAtlas curAtlas; - Sprite items; + Sprite items; - protected final Canvas mCanvas = CanvasAdapter.newCanvas(); - protected TextureItem mTexture; + protected final Canvas mCanvas = CanvasAdapter.newCanvas(); + protected TextureItem mTexture; - public SpriteManager() { - //mTexture = pool.get(); + public SpriteManager() { + //mTexture = pool.get(); - //mTexture.ownBitmap = true; + //mTexture.ownBitmap = true; - //mAtlas = new TextureAtlas(mTexture.bitmap); + //mAtlas = new TextureAtlas(mTexture.bitmap); - //mCanvas.setBitmap(mTexture.bitmap); - } + //mCanvas.setBitmap(mTexture.bitmap); + } - public Sprite getRegion(T item) { - //return items.get(item); - for (Sprite t = items; t != null; t = t.next) - if (t.item == item) - return t; + public Sprite getRegion(T item) { + //return items.get(item); + for (Sprite t = items; t != null; t = t.next) + if (t.item == item) + return t; - return null; - } + return null; + } - public void clear() { - for (TextureItem t = mTexture; t != null; t = t.dispose()); - mAtlas.clear(); - items = null; + public void clear() { + for (TextureItem t = mTexture; t != null; t = t.dispose()) ; + mAtlas.clear(); + items = null; - //mTexture.bitmap.eraseColor(Color.TRANSPARENT); - mTexture = pool.get(); - mCanvas.setBitmap(mTexture.bitmap); - } + //mTexture.bitmap.eraseColor(Color.TRANSPARENT); + mTexture = pool.get(); + mCanvas.setBitmap(mTexture.bitmap); + } - public TextureItem getTextures() { - return mTexture; - } + public TextureItem getTextures() { + return mTexture; + } - public Sprite addItem(T item, int width, int height) { - Rect r = mAtlas.getRegion(width, height); - if (r == null) { - //create new atlas - return null; - } - Sprite sprite = new Sprite(item, mAtlas, r); + public Sprite addItem(T item, int width, int height) { + Rect r = mAtlas.getRegion(width, height); + if (r == null) { + //create new atlas + return null; + } + Sprite sprite = new Sprite(item, mAtlas, r); - items = Inlist.appendItem(items, sprite); + items = Inlist.appendItem(items, sprite); - draw(item, r); + draw(item, r); - return sprite; - } + return sprite; + } - abstract void draw(T item, Rect r); + abstract void draw(T item, Rect r); } diff --git a/vtm-playground/src/org/oscim/test/ThemeBuilder.java b/vtm-playground/src/org/oscim/test/ThemeBuilder.java index dbcf7836..602d6697 100644 --- a/vtm-playground/src/org/oscim/test/ThemeBuilder.java +++ b/vtm-playground/src/org/oscim/test/ThemeBuilder.java @@ -1,8 +1,5 @@ package org.oscim.test; -import java.util.ArrayList; -import java.util.Stack; - import org.oscim.theme.RenderTheme; import org.oscim.theme.rule.Rule; import org.oscim.theme.rule.Rule.Element; @@ -16,114 +13,119 @@ import org.oscim.theme.styles.RenderStyle; import org.oscim.theme.styles.TextStyle; import org.oscim.theme.styles.TextStyle.TextBuilder; +import java.util.ArrayList; +import java.util.Stack; + public class ThemeBuilder { - protected final ArrayList mRulesList = new ArrayList(); - protected final Stack mRuleStack = new Stack(); + protected final ArrayList mRulesList = new ArrayList(); + protected final Stack mRuleStack = new Stack(); - protected int mLevels = 0; - protected int mMapBackground = 0xffffffff; - protected float mBaseTextSize = 1; + protected int mLevels = 0; + protected int mMapBackground = 0xffffffff; + protected float mBaseTextSize = 1; - protected RuleBuilder mCurrentRule; + protected RuleBuilder mCurrentRule; - public RenderTheme build() { - int[] layer = new int[1]; + public RenderTheme build() { + int[] layer = new int[1]; - Rule[] rules = new Rule[mRulesList.size()]; - for (int i = 0, n = rules.length; i < n; i++) - rules[i] = mRulesList.get(i).onComplete(layer); + Rule[] rules = new Rule[mRulesList.size()]; + for (int i = 0, n = rules.length; i < n; i++) + rules[i] = mRulesList.get(i).onComplete(layer); - RenderTheme theme = new RenderTheme(mMapBackground, mBaseTextSize, rules, mLevels); + RenderTheme theme = new RenderTheme(mMapBackground, mBaseTextSize, rules, mLevels); - mRulesList.clear(); - mRuleStack.clear(); + mRulesList.clear(); + mRuleStack.clear(); - return theme; - } + return theme; + } - public ThemeBuilder pop() { + public ThemeBuilder pop() { - mRuleStack.pop(); - if (mRuleStack.empty()) { - mRulesList.add(mCurrentRule); - } else { - mCurrentRule = mRuleStack.peek(); - } - return this; - } + mRuleStack.pop(); + if (mRuleStack.empty()) { + mRulesList.add(mCurrentRule); + } else { + mCurrentRule = mRuleStack.peek(); + } + return this; + } - public ThemeBuilder push(RuleBuilder rule) { - if (!mRuleStack.empty()) - mCurrentRule.addSubRule(rule); + public ThemeBuilder push(RuleBuilder rule) { + if (!mRuleStack.empty()) + mCurrentRule.addSubRule(rule); - mCurrentRule = rule; - mRuleStack.push(mCurrentRule); + mCurrentRule = rule; + mRuleStack.push(mCurrentRule); - return this; - } + return this; + } - public ThemeBuilder rules(RuleBuilder... rb) { - for (RuleBuilder r : rb) { - mRulesList.add(r); - } - return this; - } + public ThemeBuilder rules(RuleBuilder... rb) { + for (RuleBuilder r : rb) { + mRulesList.add(r); + } + return this; + } - public RuleBuilder pushParse(String keys, String values) { + public RuleBuilder pushParse(String keys, String values) { - return RuleBuilder.create(keys, values) - .zoom(~0) - .element(Element.ANY); - } + return RuleBuilder.create(keys, values) + .zoom(~0) + .element(Element.ANY); + } - public ThemeBuilder addStyle(RenderStyle style) { - mCurrentRule.addStyle(style); - return this; - } + public ThemeBuilder addStyle(RenderStyle style) { + mCurrentRule.addStyle(style); + return this; + } - protected void rules() { + protected void rules() { - }; + } - public static LineBuilder line(int color, float width) { - return LineStyle.builder() - .color(color) - .strokeWidth(width); - } + ; - public static AreaBuilder area(int color) { - return AreaStyle.builder() - .color(color); - } + public static LineBuilder line(int color, float width) { + return LineStyle.builder() + .color(color) + .strokeWidth(width); + } - public static TextBuilder wayText(float size, int color) { - return TextStyle.builder() - .fontSize(size) - .color(color); - } + public static AreaBuilder area(int color) { + return AreaStyle.builder() + .color(color); + } - public static TextBuilder nodeText(float size, int color) { - return TextStyle.builder() - .fontSize(size) - .color(color) - .isCaption(true); - } + public static TextBuilder wayText(float size, int color) { + return TextStyle.builder() + .fontSize(size) + .color(color); + } - public static RuleBuilder matchKey(String key) { - return new RuleBuilder(RuleType.POSITIVE, - new String[] { key }, - new String[] {}); - } + public static TextBuilder nodeText(float size, int color) { + return TextStyle.builder() + .fontSize(size) + .color(color) + .isCaption(true); + } - public static RuleBuilder matchValue(String value) { - return new RuleBuilder(RuleType.POSITIVE, - new String[] {}, - new String[] { value }); - } + public static RuleBuilder matchKey(String key) { + return new RuleBuilder(RuleType.POSITIVE, + new String[]{key}, + new String[]{}); + } - public static RuleBuilder matchKeyValue(String key, String value) { - return new RuleBuilder(RuleType.POSITIVE, - new String[] { key }, - new String[] { value }); - } + public static RuleBuilder matchValue(String value) { + return new RuleBuilder(RuleType.POSITIVE, + new String[]{}, + new String[]{value}); + } + + public static RuleBuilder matchKeyValue(String key, String value) { + return new RuleBuilder(RuleType.POSITIVE, + new String[]{key}, + new String[]{value}); + } } diff --git a/vtm-playground/src/org/oscim/test/ThemeBuilderTest.java b/vtm-playground/src/org/oscim/test/ThemeBuilderTest.java index 99052273..212bd6e3 100644 --- a/vtm-playground/src/org/oscim/test/ThemeBuilderTest.java +++ b/vtm-playground/src/org/oscim/test/ThemeBuilderTest.java @@ -13,49 +13,49 @@ import org.slf4j.LoggerFactory; public class ThemeBuilderTest extends GdxMap { - final Logger log = LoggerFactory.getLogger(S3DBLayerTest.class); + final Logger log = LoggerFactory.getLogger(S3DBLayerTest.class); - static class MyTheme extends ThemeBuilder { - public MyTheme() { - rules( - matchKeyValue("natural", "water") - .style(area(Color.BLUE)), + static class MyTheme extends ThemeBuilder { + public MyTheme() { + rules( + matchKeyValue("natural", "water") + .style(area(Color.BLUE)), - matchKeyValue("landuse", "forest") - .style(area(Color.GREEN)), + matchKeyValue("landuse", "forest") + .style(area(Color.GREEN)), - matchKeyValue("landuse", "residential") - .style(area(Color.LTGRAY)), + matchKeyValue("landuse", "residential") + .style(area(Color.LTGRAY)), - matchKey("highway") - .rules(matchValue("residential") - .style(line(Color.DKGRAY, 1.2f), - line(Color.WHITE, 1.1f) - .cap(Cap.ROUND))) + matchKey("highway") + .rules(matchValue("residential") + .style(line(Color.DKGRAY, 1.2f), + line(Color.WHITE, 1.1f) + .cap(Cap.ROUND))) - .style(line(Color.BLACK, 1) - .blur(0.5f))); - } - } + .style(line(Color.BLACK, 1) + .blur(0.5f))); + } + } - @Override - public void createLayers() { + @Override + public void createLayers() { - VectorTileLayer l = mMap.setBaseMap(new OSciMap4TileSource()); + VectorTileLayer l = mMap.setBaseMap(new OSciMap4TileSource()); - RenderTheme t = new MyTheme().build(); + RenderTheme t = new MyTheme().build(); - mMap.setTheme(t); - //mMap.setTheme(VtmThemes.DEFAULT); + mMap.setTheme(t); + //mMap.setTheme(VtmThemes.DEFAULT); - mMap.layers().add(new LabelLayer(mMap, l)); + mMap.layers().add(new LabelLayer(mMap, l)); - mMap.setMapPosition(53.08, 8.82, 1 << 17); + mMap.setMapPosition(53.08, 8.82, 1 << 17); - } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new ThemeBuilderTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new ThemeBuilderTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/ThemeTest.java b/vtm-playground/src/org/oscim/test/ThemeTest.java index 7c0be1c5..099b20c2 100644 --- a/vtm-playground/src/org/oscim/test/ThemeTest.java +++ b/vtm-playground/src/org/oscim/test/ThemeTest.java @@ -1,9 +1,5 @@ package org.oscim.test; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; - import org.oscim.awt.AwtGraphics; import org.oscim.backend.AssetAdapter; import org.oscim.core.GeometryBuffer.GeometryType; @@ -14,35 +10,39 @@ import org.oscim.theme.ThemeLoader; import org.oscim.theme.VtmThemes; import org.oscim.theme.styles.RenderStyle; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; + public class ThemeTest { - public static void main(String[] args) { - AwtGraphics.init(); - AssetAdapter.init(new AssetAdapter() { - @Override - public InputStream openFileAsStream(String name) { - try { - return new FileInputStream("/home/jeff/src/vtm/OpenScienceMap/vtm/assets/" - + name); - } catch (FileNotFoundException e) { - e.printStackTrace(); - return null; - } - } - }); + public static void main(String[] args) { + AwtGraphics.init(); + AssetAdapter.init(new AssetAdapter() { + @Override + public InputStream openFileAsStream(String name) { + try { + return new FileInputStream("/home/jeff/src/vtm/OpenScienceMap/vtm/assets/" + + name); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } + } + }); - IRenderTheme t = ThemeLoader.load(VtmThemes.DEFAULT); + IRenderTheme t = ThemeLoader.load(VtmThemes.DEFAULT); - TagSet tags = new TagSet(); - tags.add(new Tag("highway", "trunk_link")); - tags.add(new Tag("brigde", "yes")); - tags.add(new Tag("oneway", "yes")); + TagSet tags = new TagSet(); + tags.add(new Tag("highway", "trunk_link")); + tags.add(new Tag("brigde", "yes")); + tags.add(new Tag("oneway", "yes")); - RenderStyle[] ri = t.matchElement(GeometryType.LINE, tags, 16); + RenderStyle[] ri = t.matchElement(GeometryType.LINE, tags, 16); - for (RenderStyle r : ri) { - System.out.println("class: " + r.getClass().getName()); - } - } + for (RenderStyle r : ri) { + System.out.println("class: " + r.getClass().getName()); + } + } } diff --git a/vtm-playground/src/org/oscim/test/TileRenderTest.java b/vtm-playground/src/org/oscim/test/TileRenderTest.java index a43eb28f..a093bf07 100644 --- a/vtm-playground/src/org/oscim/test/TileRenderTest.java +++ b/vtm-playground/src/org/oscim/test/TileRenderTest.java @@ -26,177 +26,177 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; public class TileRenderTest extends GdxMapApp { - static boolean loadOneTile = true; - // static int tileX = 34365 >> 2; - // static int tileY = 21333 >> 2; - // static byte tileZ = 14; + static boolean loadOneTile = true; + // static int tileX = 34365 >> 2; + // static int tileY = 21333 >> 2; + // static byte tileZ = 14; - static int tileX = 68747 >> 3; - static int tileY = 42648 >> 3; - static byte tileZ = 14; + static int tileX = 68747 >> 3; + static int tileY = 42648 >> 3; + static byte tileZ = 14; - @Override - public void createLayers() { + @Override + public void createLayers() { - mMap.layers().add(new TileGridLayer(mMap, Color.LTGRAY, 1.2f, 1)); + mMap.layers().add(new TileGridLayer(mMap, Color.LTGRAY, 1.2f, 1)); - MapTile tile = new MapTile(null, tileX, tileY, tileZ); + MapTile tile = new MapTile(null, tileX, tileY, tileZ); - double w = 1.0 / (1 << tile.zoomLevel); - double minLon = MercatorProjection.toLongitude(tile.x); - double maxLon = MercatorProjection.toLongitude(tile.x + w); - double minLat = MercatorProjection.toLatitude(tile.y + w); - double maxLat = MercatorProjection.toLatitude(tile.y); - double lat = minLat + (maxLat - minLat) / 2; - double lon = minLon + (maxLon - minLon) / 2; + double w = 1.0 / (1 << tile.zoomLevel); + double minLon = MercatorProjection.toLongitude(tile.x); + double maxLon = MercatorProjection.toLongitude(tile.x + w); + double minLat = MercatorProjection.toLatitude(tile.y + w); + double maxLat = MercatorProjection.toLatitude(tile.y); + double lat = minLat + (maxLat - minLat) / 2; + double lon = minLon + (maxLon - minLon) / 2; - MapPosition mapPosition = new MapPosition(lat, lon, 1 << tile.zoomLevel); + MapPosition mapPosition = new MapPosition(lat, lon, 1 << tile.zoomLevel); - mMap.setMapPosition(mapPosition); + mMap.setMapPosition(mapPosition); - final TileManager tileManager; + final TileManager tileManager; - if (loadOneTile) { - tile = new MapTile(new TileNode(), tileX, tileY, tileZ); - /* setup tile quad-tree, expected for locking */ - tile.node.parent = tile.node; - tile.node.parent.parent = tile.node; + if (loadOneTile) { + tile = new MapTile(new TileNode(), tileX, tileY, tileZ); + /* setup tile quad-tree, expected for locking */ + tile.node.parent = tile.node; + tile.node.parent.parent = tile.node; /* setup TileSet contatining one tile */ - final TileSet tiles = new TileSet(); - tiles.cnt = 1; - tiles.tiles[0] = tile; - tiles.lockTiles(); + final TileSet tiles = new TileSet(); + tiles.cnt = 1; + tiles.tiles[0] = tile; + tiles.lockTiles(); - tileManager = new TestTileManager(mMap, tiles); - } else { - /* create TileManager and calculate tiles for current position */ - tileManager = new TileManager(mMap, 100); - } + tileManager = new TestTileManager(mMap, tiles); + } else { + /* create TileManager and calculate tiles for current position */ + tileManager = new TileManager(mMap, 100); + } /* get the loader created by VectorTileLayer ... */ - final TestTileLoader[] tileLoader = { null }; + final TestTileLoader[] tileLoader = {null}; - TestVectorTileLayer tileLayer = new TestVectorTileLayer(mMap, tileManager); - tileLoader[0] = tileLayer.getTileLoader(); + TestVectorTileLayer tileLayer = new TestVectorTileLayer(mMap, tileManager); + tileLoader[0] = tileLayer.getTileLoader(); - TileSource tileSource = new OSciMap4TileSource(); - //TileSource tileSource = new TestTileSource(); + TileSource tileSource = new OSciMap4TileSource(); + //TileSource tileSource = new TestTileSource(); - tileLayer.setTileSource(tileSource); + tileLayer.setTileSource(tileSource); - //IRenderTheme theme = ThemeLoader.load(VtmThemes.OSMARENDER); - //tileLayer.setRenderTheme(theme); - //tileLayer.setRenderTheme(new DebugTheme()); + //IRenderTheme theme = ThemeLoader.load(VtmThemes.OSMARENDER); + //tileLayer.setRenderTheme(theme); + //tileLayer.setRenderTheme(new DebugTheme()); /* need to create the labellayer here to get the tileloaded event */ - LabelLayer labelLayer = new LabelLayer(mMap, tileLayer); + LabelLayer labelLayer = new LabelLayer(mMap, tileLayer); - //mMap.layers().add(tileLayer); - mMap.setBaseMap(tileLayer); - mMap.setTheme(VtmThemes.DEFAULT); + //mMap.layers().add(tileLayer); + mMap.setBaseMap(tileLayer); + mMap.setTheme(VtmThemes.DEFAULT); - log.debug("load tiles:"); - if (loadOneTile) { - log.debug("load {}", tile); + log.debug("load tiles:"); + if (loadOneTile) { + log.debug("load {}", tile); - tileLoader[0].loadTile(tile); - tileManager.jobCompleted(tile, QueryResult.SUCCESS); - } else { - tileManager.update(mapPosition); - MapTile t = tileManager.getTileJob(); - while (t != null) { - log.debug("load {}", t); + tileLoader[0].loadTile(tile); + tileManager.jobCompleted(tile, QueryResult.SUCCESS); + } else { + tileManager.update(mapPosition); + MapTile t = tileManager.getTileJob(); + while (t != null) { + log.debug("load {}", t); - tileLoader[0].loadTile(t); - tileManager.jobCompleted(t, QueryResult.SUCCESS); + tileLoader[0].loadTile(t); + tileManager.jobCompleted(t, QueryResult.SUCCESS); - t = tileManager.getTileJob(); - } - } + t = tileManager.getTileJob(); + } + } - mMap.layers().add(labelLayer); + mMap.layers().add(labelLayer); - MapRenderer.setBackgroundColor(0xff888888); - } + MapRenderer.setBackgroundColor(0xff888888); + } - static class TestTileLoader extends VectorTileLoader { + static class TestTileLoader extends VectorTileLoader { - public TestTileLoader(VectorTileLayer tileLayer) { - super(tileLayer); - } + public TestTileLoader(VectorTileLayer tileLayer) { + super(tileLayer); + } - @Override - public boolean loadTile(MapTile tile) { - mTile = tile; - return super.loadTile(tile); - } + @Override + public boolean loadTile(MapTile tile) { + mTile = tile; + return super.loadTile(tile); + } - @Override - public void process(MapElement element) { - /* ignore polygons for testing */ - if (element.type != GeometryType.LINE) - return; + @Override + public void process(MapElement element) { + /* ignore polygons for testing */ + if (element.type != GeometryType.LINE) + return; - if (element.tags.containsKey("name")) - super.process(element); - } - } + if (element.tags.containsKey("name")) + super.process(element); + } + } - static class TestVectorTileLayer extends VectorTileLayer { - final VectorTileLoader[] tileLoader = { null }; + static class TestVectorTileLayer extends VectorTileLayer { + final VectorTileLoader[] tileLoader = {null}; - public TestVectorTileLayer(Map map, TileManager tileManager) { - super(map, tileManager, new VectorTileRenderer()); - } + public TestVectorTileLayer(Map map, TileManager tileManager) { + super(map, tileManager, new VectorTileRenderer()); + } - TestTileLoader getTileLoader() { - return (TestTileLoader) mTileLoader[0]; - } + TestTileLoader getTileLoader() { + return (TestTileLoader) mTileLoader[0]; + } - @Override - protected int getNumLoaders() { - return 1; - } + @Override + protected int getNumLoaders() { + return 1; + } - @Override - protected void initLoader(int numLoaders) { - mTileLoader = new TileLoader[numLoaders]; - for (int i = 0; i < numLoaders; i++) { - mTileLoader[i] = new TestTileLoader(this); - } - } + @Override + protected void initLoader(int numLoaders) { + mTileLoader = new TileLoader[numLoaders]; + for (int i = 0; i < numLoaders; i++) { + mTileLoader[i] = new TestTileLoader(this); + } + } - @Override - public void onMapEvent(Event event, MapPosition mapPosition) { + @Override + public void onMapEvent(Event event, MapPosition mapPosition) { /* ignore map events */ - if (event != Map.CLEAR_EVENT) - return; + if (event != Map.CLEAR_EVENT) + return; - //super.onMapEvent(event, mapPosition); - } - } + //super.onMapEvent(event, mapPosition); + } + } - static class TestTileManager extends TileManager { - TileSet fixedTiles; + static class TestTileManager extends TileManager { + TileSet fixedTiles; - public TestTileManager(Map map, TileSet fixedTiles) { - super(map, 100); - this.fixedTiles = fixedTiles; - } + public TestTileManager(Map map, TileSet fixedTiles) { + super(map, 100); + this.fixedTiles = fixedTiles; + } - @Override - public boolean getActiveTiles(TileSet tileSet) { - if (tileSet == null) - tileSet = new TileSet(fixedTiles.cnt); + @Override + public boolean getActiveTiles(TileSet tileSet) { + if (tileSet == null) + tileSet = new TileSet(fixedTiles.cnt); - tileSet.setTiles(fixedTiles); - return true; - } - } + tileSet.setTiles(fixedTiles); + return true; + } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new TileRenderTest(), null, 512); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new TileRenderTest(), null, 512); + } } diff --git a/vtm-playground/src/org/oscim/test/VectorLayerTest.java b/vtm-playground/src/org/oscim/test/VectorLayerTest.java index 0910b2f2..8c8628cf 100644 --- a/vtm-playground/src/org/oscim/test/VectorLayerTest.java +++ b/vtm-playground/src/org/oscim/test/VectorLayerTest.java @@ -28,67 +28,67 @@ import org.oscim.utils.ColorUtil; public class VectorLayerTest extends GdxMapApp { - @Override - public void createLayers() { - mMap.setBaseMap(new OSciMap4TileSource()); - mMap.setTheme(VtmThemes.DEFAULT); + @Override + public void createLayers() { + mMap.setBaseMap(new OSciMap4TileSource()); + mMap.setTheme(VtmThemes.DEFAULT); - VectorLayer vectorLayer = new VectorLayer(mMap); + VectorLayer vectorLayer = new VectorLayer(mMap); - // vectorLayer.add(new PointDrawable(0, 180, Style.builder() - // .setBuffer(10) - // .setFillColor(Color.RED) - // .setFillAlpha(0.5) - // .build())); - // - // Geometry g = new GeomBuilder() - // .point(180, 0) - // .point() - // .buffer(6) - // .get(); - // - // vectorLayer.add(new PolygonDrawable(g, defaultStyle())); - // + // vectorLayer.add(new PointDrawable(0, 180, Style.builder() + // .setBuffer(10) + // .setFillColor(Color.RED) + // .setFillAlpha(0.5) + // .build())); + // + // Geometry g = new GeomBuilder() + // .point(180, 0) + // .point() + // .buffer(6) + // .get(); + // + // vectorLayer.add(new PolygonDrawable(g, defaultStyle())); + // - Style.Builder sb = Style.builder() - .buffer(0.4) - .fillColor(Color.RED) - .fillAlpha(0.2); + Style.Builder sb = Style.builder() + .buffer(0.4) + .fillColor(Color.RED) + .fillAlpha(0.2); - // int tileSize = 5; - // for (int x = -180; x < 200; x += tileSize) { - // for (int y = -90; y < 90; y += tileSize) { - // // Style style = sb.setFillAlpha(FastMath.clamp(FastMath.length(x, y) / 180, 0.2, 1)) - // // .build(); - // - // vectorLayer.add(new RectangleDrawable(FastMath.clamp(y, -85, 85), x, - // FastMath.clamp(y + tileSize - 0.1, -85, 85), - // x + tileSize - 0.1, style)); - // - // } - // } + // int tileSize = 5; + // for (int x = -180; x < 200; x += tileSize) { + // for (int y = -90; y < 90; y += tileSize) { + // // Style style = sb.setFillAlpha(FastMath.clamp(FastMath.length(x, y) / 180, 0.2, 1)) + // // .build(); + // + // vectorLayer.add(new RectangleDrawable(FastMath.clamp(y, -85, 85), x, + // FastMath.clamp(y + tileSize - 0.1, -85, 85), + // x + tileSize - 0.1, style)); + // + // } + // } - for (int i = 0; i < 1000; i++) { - Style style = sb.buffer(Math.random() * 1) - .fillColor(ColorUtil.setHue(Color.RED, - Math.random())) - .fillAlpha(0.5) - .build(); + for (int i = 0; i < 1000; i++) { + Style style = sb.buffer(Math.random() * 1) + .fillColor(ColorUtil.setHue(Color.RED, + Math.random())) + .fillAlpha(0.5) + .build(); - vectorLayer.add(new PointDrawable(Math.random() * 180 - 90, - Math.random() * 360 - 180, - style)); + vectorLayer.add(new PointDrawable(Math.random() * 180 - 90, + Math.random() * 360 - 180, + style)); - } + } - mMap.layers().add(vectorLayer); - mMap.layers().add(new TileGridLayer(mMap, 0xff222222, 1.2f, 1)); + mMap.layers().add(vectorLayer); + mMap.layers().add(new TileGridLayer(mMap, 0xff222222, 1.2f, 1)); - mMap.setMapPosition(0, 0, 1 << 2); - } + mMap.setMapPosition(0, 0, 1 << 2); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new VectorLayerTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new VectorLayerTest(), null, 400); + } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/Gdx3DTest.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/Gdx3DTest.java index d5d981ec..28a83320 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/Gdx3DTest.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/Gdx3DTest.java @@ -12,37 +12,37 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; public class Gdx3DTest extends GdxMap { - @Override - public void createLayers() { - MapRenderer.setBackgroundColor(0xff888888); + @Override + public void createLayers() { + MapRenderer.setBackgroundColor(0xff888888); - mMap.setMapPosition(53.1, 8.8, 1 << 15); + mMap.setMapPosition(53.1, 8.8, 1 << 15); - TileSource ts = new OSciMap4TileSource(); - // initDefaultLayers(ts, false, false, false); + TileSource ts = new OSciMap4TileSource(); + // initDefaultLayers(ts, false, false, false); - VectorTileLayer mMapLayer = mMap.setBaseMap(ts); - mMap.setTheme(VtmThemes.DEFAULT); - // mMap.setTheme(VtmThemes.TRONRENDER); + VectorTileLayer mMapLayer = mMap.setBaseMap(ts); + mMap.setTheme(VtmThemes.DEFAULT); + // mMap.setTheme(VtmThemes.TRONRENDER); - mMap.layers().add(new BuildingLayer(mMap, mMapLayer)); + mMap.layers().add(new BuildingLayer(mMap, mMapLayer)); - // mMap.getLayers().add(new GenericLayer(mMap, new GridRenderer())); + // mMap.getLayers().add(new GenericLayer(mMap, new GridRenderer())); - // ts = new OSciMap4TileSource("http://opensciencemap.org/tiles/s3db"); - // VectorTileLayer tl = new VectorTileLayer(mMap, 16, 16, 20); - // tl.setTileSource(ts); - // tl.setRenderTheme(ThemeLoader.load(VtmThemes.DEFAULT)); - // mMap.getLayers().add(tl); - // mMap.getLayers().add(new BuildingLayer(mMap, tl.getTileLayer())); + // ts = new OSciMap4TileSource("http://opensciencemap.org/tiles/s3db"); + // VectorTileLayer tl = new VectorTileLayer(mMap, 16, 16, 20); + // tl.setTileSource(ts); + // tl.setRenderTheme(ThemeLoader.load(VtmThemes.DEFAULT)); + // mMap.getLayers().add(tl); + // mMap.getLayers().add(new BuildingLayer(mMap, tl.getTileLayer())); - mMap.layers().add(new Poi3DLayer(mMap, mMapLayer)); + mMap.layers().add(new Poi3DLayer(mMap, mMapLayer)); - mMap.layers().add(new LabelLayer(mMap, mMapLayer)); - } + mMap.layers().add(new LabelLayer(mMap, mMapLayer)); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new Gdx3DTest(), null, 320); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new Gdx3DTest(), null, 320); + } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelLayer.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelLayer.java index c42d80aa..cccbbd60 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelLayer.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelLayer.java @@ -1,5 +1,9 @@ package org.oscim.test.gdx.poi3d; +import com.badlogic.gdx.assets.AssetManager; +import com.badlogic.gdx.graphics.g3d.Model; +import com.badlogic.gdx.graphics.g3d.model.Node; + import org.oscim.core.MapPosition; import org.oscim.event.Event; import org.oscim.layers.Layer; @@ -7,231 +11,227 @@ import org.oscim.map.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.assets.AssetManager; -import com.badlogic.gdx.graphics.g3d.Model; -import com.badlogic.gdx.graphics.g3d.model.Node; - public class GdxModelLayer extends Layer implements Map.UpdateListener { - static final Logger log = LoggerFactory.getLogger(GdxModelLayer.class); + static final Logger log = LoggerFactory.getLogger(GdxModelLayer.class); - GdxRenderer3D g3d; + GdxRenderer3D g3d; - //VectorTileLayer mTileLayer; + //VectorTileLayer mTileLayer; - public GdxModelLayer(Map map) { - super(map); - // tileLayer.addHook(new TileLoaderProcessHook() { - // - // @Override - // public boolean process(MapTile tile, ElementLayers layers, MapElement element) { - // - // if (!element.tags.contains(TREE_TAG)) - // return false; - // - // Poi3DTileData td = get(tile); - // PointF p = element.getPoint(0); - // SymbolItem s = SymbolItem.pool.get(); - // s.x = p.x; - // s.y = p.y; - // td.symbols.push(s); - // - // return true; - // } - // }); - //mTileLayer = tileLayer; + public GdxModelLayer(Map map) { + super(map); + // tileLayer.addHook(new TileLoaderProcessHook() { + // + // @Override + // public boolean process(MapTile tile, ElementLayers layers, MapElement element) { + // + // if (!element.tags.contains(TREE_TAG)) + // return false; + // + // Poi3DTileData td = get(tile); + // PointF p = element.getPoint(0); + // SymbolItem s = SymbolItem.pool.get(); + // s.x = p.x; + // s.y = p.y; + // td.symbols.push(s); + // + // return true; + // } + // }); + //mTileLayer = tileLayer; - mRenderer = g3d = new GdxRenderer3D(mMap); + mRenderer = g3d = new GdxRenderer3D(mMap); - // Material mat = new - // Material(ColorAttribute.createDiffuse(Color.BLUE)); - // ModelBuilder modelBuilder = new ModelBuilder(); - // long attributes = Usage.Position | Usage.Normal | - // Usage.TextureCoordinates; + // Material mat = new + // Material(ColorAttribute.createDiffuse(Color.BLUE)); + // ModelBuilder modelBuilder = new ModelBuilder(); + // long attributes = Usage.Position | Usage.Normal | + // Usage.TextureCoordinates; - // mModel = modelBuilder.createSphere(10f, 10f, 10f, 12, 12, - // mat, attributes); + // mModel = modelBuilder.createSphere(10f, 10f, 10f, 12, 12, + // mat, attributes); - assets = new AssetManager(); - assets.load("data/g3d/test.g3db", Model.class); - loading = true; - } + assets = new AssetManager(); + assets.load("data/g3d/test.g3db", Model.class); + loading = true; + } - // TileSet mTileSet = new TileSet(); - // TileSet mPrevTiles = new TileSet(); - // - // LinkedHashMap> mTileMap = - // new LinkedHashMap>(); + // TileSet mTileSet = new TileSet(); + // TileSet mPrevTiles = new TileSet(); + // + // LinkedHashMap> mTileMap = + // new LinkedHashMap>(); - boolean loading; - Model mModel; - AssetManager assets; + boolean loading; + Model mModel; + AssetManager assets; - private void doneLoading() { - Model model = assets.get("data/g3d/test.g3db", Model.class); - for (int i = 0; i < model.nodes.size; i++) { - Node node = model.nodes.get(i); - log.debug("loader node " + node.id); + private void doneLoading() { + Model model = assets.get("data/g3d/test.g3db", Model.class); + for (int i = 0; i < model.nodes.size; i++) { + Node node = model.nodes.get(i); + log.debug("loader node " + node.id); - if (node.id.equals("test_root")) { - node = node.getChild("Building", false, false); - log.debug("loader node " + node.id); + if (node.id.equals("test_root")) { + node = node.getChild("Building", false, false); + log.debug("loader node " + node.id); - node.rotation.setFromAxis(1, 0, 0, 90); - mModel = model; + node.rotation.setFromAxis(1, 0, 0, 90); + mModel = model; - break; - } + break; + } - //} - } + //} + } - loading = false; - } + loading = false; + } - @Override - public void onMapEvent(Event ev, MapPosition pos) { + @Override + public void onMapEvent(Event ev, MapPosition pos) { - // if (ev == Map.CLEAR_EVENT) { - // mTileSet = new TileSet(); - // mPrevTiles = new TileSet(); - // mTileMap = new LinkedHashMap>(); - // synchronized (g3d) { - // g3d.instances.clear(); - // } - // } - // - if (loading && assets.update()) { - doneLoading(); - // Renderable renderable = new Renderable(); - // new SharedModel(mModel).getRenderable(renderable); - // Shader shader = new DefaultShader(renderable, true, false, - // false, false, 1, 0, 0, 0); + // if (ev == Map.CLEAR_EVENT) { + // mTileSet = new TileSet(); + // mPrevTiles = new TileSet(); + // mTileMap = new LinkedHashMap>(); + // synchronized (g3d) { + // g3d.instances.clear(); + // } + // } + // + if (loading && assets.update()) { + doneLoading(); + // Renderable renderable = new Renderable(); + // new SharedModel(mModel).getRenderable(renderable); + // Shader shader = new DefaultShader(renderable, true, false, + // false, false, 1, 0, 0, 0); - g3d.instances.add(new SharedModel(mModel)); + g3d.instances.add(new SharedModel(mModel)); - } - if (loading) - return; + } + if (loading) + return; - int x = 17185 << 1; - int y = 10662 << 1; - int z = 16; - double scale = 1 / (1 << z); + int x = 17185 << 1; + int y = 10662 << 1; + int z = 16; + double scale = 1 / (1 << z); - g3d.cam.setMapPosition(x * scale - pos.x, y * scale - pos.y, scale / pos.scale); + g3d.cam.setMapPosition(x * scale - pos.x, y * scale - pos.y, scale / pos.scale); - // - // // log.debug("update"); - // - // mTileLayer.tileRenderer().getVisibleTiles(mTileSet); - // - // if (mTileSet.cnt == 0) { - // mTileSet.releaseTiles(); - // return; - // } - // - // boolean changed = false; - // - // Array added = new Array(); - // Array removed = new Array(); + // + // // log.debug("update"); + // + // mTileLayer.tileRenderer().getVisibleTiles(mTileSet); + // + // if (mTileSet.cnt == 0) { + // mTileSet.releaseTiles(); + // return; + // } + // + // boolean changed = false; + // + // Array added = new Array(); + // Array removed = new Array(); - // for (int i = 0; i < mTileSet.cnt; i++) { - // MapTile t = mTileSet.tiles[i]; - // if (mPrevTiles.contains(t)) - // continue; - // - // Array instances = new Array(); - // - // Poi3DTileData ld = (Poi3DTileData) t.getData(POI_DATA); - // if (ld == null) - // continue; - // - // for (SymbolItem it : ld.symbols) { - // - // SharedModel inst = new SharedModel(mModel); - // inst.userData = it; - // // float r = 0.5f + 0.5f * (float) Math.random(); - // // float g = 0.5f + 0.5f * (float) Math.random(); - // // float b = 0.5f + 0.5f * (float) Math.random(); - // - // // inst.transform.setTranslation(new Vector3(it.x, it.y, - // // 10)); - // // inst.materials.get(0).set(ColorAttribute.createDiffuse(r, - // // g, b, 0.8f)); - // instances.add(inst); - // added.add(inst); - // } - // - // if (instances.size == 0) - // continue; - // - // log.debug("add " + t + " " + instances.size); - // - // changed = true; - // - // mTileMap.put(t, instances); - // } - // - // for (int i = 0; i < mPrevTiles.cnt; i++) { - // MapTile t = mPrevTiles.tiles[i]; - // if (mTileSet.contains(t)) - // continue; - // - // Array instances = mTileMap.get(t); - // if (instances == null) - // continue; - // - // changed = true; - // - // removed.addAll(instances); - // mTileMap.remove(t); - // log.debug("remove " + t); - // } - // - // mPrevTiles.releaseTiles(); - // - // int zoom = mTileSet.tiles[0].zoomLevel; - // - // TileSet tmp = mPrevTiles; - // mPrevTiles = mTileSet; - // mTileSet = tmp; - // - // if (!changed) - // return; - // - // // scale aka tree height - // float scale = (float) (1f / (1 << (17 - zoom))) * 8; - // - // double tileX = (pos.x * (Tile.SIZE << zoom)); - // double tileY = (pos.y * (Tile.SIZE << zoom)); - // - // synchronized (g3d) { - // - // for (Entry> e : mTileMap.entrySet()) { - // Tile t = e.getKey(); - // - // float dx = (float) (t.tileX * Tile.SIZE - tileX); - // float dy = (float) (t.tileY * Tile.SIZE - tileY); - // - // for (SharedModel inst : e.getValue()) { - // SymbolItem it = (SymbolItem) inst.userData; - // - // // variable height - // float s = scale + (it.x * it.y) % 3; - // float r = (it.x * it.y) % 360; - // - // inst.transform.idt(); - // inst.transform.scale(s, s, s); - // inst.transform.translate((dx + it.x) / s, (dy + it.y) / s, 0); - // inst.transform.rotate(0, 0, 1, r); - // - // // inst.transform.setToTranslationAndScaling((dx + - // // it.x), (dy + it.y), - // // 0, s, s, s); - // - // } - // } + // for (int i = 0; i < mTileSet.cnt; i++) { + // MapTile t = mTileSet.tiles[i]; + // if (mPrevTiles.contains(t)) + // continue; + // + // Array instances = new Array(); + // + // Poi3DTileData ld = (Poi3DTileData) t.getData(POI_DATA); + // if (ld == null) + // continue; + // + // for (SymbolItem it : ld.symbols) { + // + // SharedModel inst = new SharedModel(mModel); + // inst.userData = it; + // // float r = 0.5f + 0.5f * (float) Math.random(); + // // float g = 0.5f + 0.5f * (float) Math.random(); + // // float b = 0.5f + 0.5f * (float) Math.random(); + // + // // inst.transform.setTranslation(new Vector3(it.x, it.y, + // // 10)); + // // inst.materials.get(0).set(ColorAttribute.createDiffuse(r, + // // g, b, 0.8f)); + // instances.add(inst); + // added.add(inst); + // } + // + // if (instances.size == 0) + // continue; + // + // log.debug("add " + t + " " + instances.size); + // + // changed = true; + // + // mTileMap.put(t, instances); + // } + // + // for (int i = 0; i < mPrevTiles.cnt; i++) { + // MapTile t = mPrevTiles.tiles[i]; + // if (mTileSet.contains(t)) + // continue; + // + // Array instances = mTileMap.get(t); + // if (instances == null) + // continue; + // + // changed = true; + // + // removed.addAll(instances); + // mTileMap.remove(t); + // log.debug("remove " + t); + // } + // + // mPrevTiles.releaseTiles(); + // + // int zoom = mTileSet.tiles[0].zoomLevel; + // + // TileSet tmp = mPrevTiles; + // mPrevTiles = mTileSet; + // mTileSet = tmp; + // + // if (!changed) + // return; + // + // // scale aka tree height + // float scale = (float) (1f / (1 << (17 - zoom))) * 8; + // + // double tileX = (pos.x * (Tile.SIZE << zoom)); + // double tileY = (pos.y * (Tile.SIZE << zoom)); + // + // synchronized (g3d) { + // + // for (Entry> e : mTileMap.entrySet()) { + // Tile t = e.getKey(); + // + // float dx = (float) (t.tileX * Tile.SIZE - tileX); + // float dy = (float) (t.tileY * Tile.SIZE - tileY); + // + // for (SharedModel inst : e.getValue()) { + // SymbolItem it = (SymbolItem) inst.userData; + // + // // variable height + // float s = scale + (it.x * it.y) % 3; + // float r = (it.x * it.y) % 360; + // + // inst.transform.idt(); + // inst.transform.scale(s, s, s); + // inst.transform.translate((dx + it.x) / s, (dy + it.y) / s, 0); + // inst.transform.rotate(0, 0, 1, r); + // + // // inst.transform.setToTranslationAndScaling((dx + + // // it.x), (dy + it.y), + // // 0, s, s, s); + // + // } + // } - } + } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelRenderer.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelRenderer.java index 4bff1252..da5edf5a 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelRenderer.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxModelRenderer.java @@ -1,17 +1,5 @@ package org.oscim.test.gdx.poi3d; -import static org.oscim.backend.GLAdapter.gl; - -import org.oscim.backend.GL; -import org.oscim.core.Tile; -import org.oscim.map.Map; -import org.oscim.map.Viewport; -import org.oscim.renderer.GLState; -import org.oscim.renderer.GLViewport; -import org.oscim.renderer.LayerRenderer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; @@ -25,162 +13,174 @@ import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; +import org.oscim.backend.GL; +import org.oscim.core.Tile; +import org.oscim.map.Map; +import org.oscim.map.Viewport; +import org.oscim.renderer.GLState; +import org.oscim.renderer.GLViewport; +import org.oscim.renderer.LayerRenderer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.oscim.backend.GLAdapter.gl; + public class GdxModelRenderer extends LayerRenderer { - static final Logger log = LoggerFactory.getLogger(GdxModelRenderer.class); + static final Logger log = LoggerFactory.getLogger(GdxModelRenderer.class); - ModelBatch modelBatch; - public MapCamera cam; - Map mMap; + ModelBatch modelBatch; + public MapCamera cam; + Map mMap; - boolean loading; + boolean loading; - public Environment lights; + public Environment lights; - public Array instances = new Array(); + public Array instances = new Array(); - public Shader shader; - public RenderContext renderContext; - public Model model; - private ModelBatch mBatch = new ModelBatch(); + public Shader shader; + public RenderContext renderContext; + public Model model; + private ModelBatch mBatch = new ModelBatch(); - public GdxModelRenderer(Map map) { - mMap = map; - } + public GdxModelRenderer(Map map) { + mMap = map; + } - @Override - public boolean setup() { + @Override + public boolean setup() { - modelBatch = new ModelBatch(new DefaultShaderProvider()); + modelBatch = new ModelBatch(new DefaultShaderProvider()); - lights = new Environment(); - lights.set(new ColorAttribute(ColorAttribute.AmbientLight, 1.0f, 1.0f, 1.0f, 1.f)); - lights.add(new DirectionalLight().set(0.3f, 0.3f, 0.3f, 0, 1, -0.2f)); + lights = new Environment(); + lights.set(new ColorAttribute(ColorAttribute.AmbientLight, 1.0f, 1.0f, 1.0f, 1.f)); + lights.add(new DirectionalLight().set(0.3f, 0.3f, 0.3f, 0, 1, -0.2f)); - cam = new MapCamera(mMap); + cam = new MapCamera(mMap); - renderContext = - new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); + renderContext = + new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); - // shader = new DefaultShader(renderable.material, - // renderable.mesh.getVertexAttributes(), true, false, 1, 0, 0, 0); - // shader.init(); + // shader = new DefaultShader(renderable.material, + // renderable.mesh.getVertexAttributes(), true, false, 1, 0, 0, 0); + // shader.init(); - return true; - } + return true; + } - @Override - public synchronized void update(GLViewport v) { - // if (loading && assets.update()) - // doneLoading(); + @Override + public synchronized void update(GLViewport v) { + // if (loading && assets.update()) + // doneLoading(); - if (!isReady()) { - cam.setPosition(v.pos); - setReady(true); - } + if (!isReady()) { + cam.setPosition(v.pos); + setReady(true); + } - // if (changed) { - // cam.update(position, matrices); - // } - } + // if (changed) { + // cam.update(position, matrices); + // } + } - Vector3 tempVector = new Vector3(); - float[] mBox = new float[8]; + Vector3 tempVector = new Vector3(); + float[] mBox = new float[8]; - Renderable r = new Renderable(); + Renderable r = new Renderable(); - @Override - public void render(GLViewport v) { - if (instances.size == 0) - return; + @Override + public void render(GLViewport v) { + if (instances.size == 0) + return; - // GLUtils.checkGlError(">" + TAG); + // GLUtils.checkGlError(">" + TAG); - gl.depthMask(true); + gl.depthMask(true); - if (v.pos.zoomLevel < 16) - gl.clear(GL.DEPTH_BUFFER_BIT); + if (v.pos.zoomLevel < 16) + gl.clear(GL.DEPTH_BUFFER_BIT); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); - // set state that is expected after modelBatch.end(); - // modelBatch keeps track of its own state - GLState.enableVertexArrays(-1, -1); - GLState.bindTex2D(-1); - GLState.useProgram(-1); - GLState.test(false, false); - GLState.blend(false); + // set state that is expected after modelBatch.end(); + // modelBatch keeps track of its own state + GLState.enableVertexArrays(-1, -1); + GLState.bindTex2D(-1); + GLState.useProgram(-1); + GLState.test(false, false); + GLState.blend(false); - cam.update(v); + cam.update(v); - Viewport p = mMap.viewport(); - p.getMapExtents(mBox, 10); - float scale = (float) (cam.mMapPosition.scale / v.pos.scale); + Viewport p = mMap.viewport(); + p.getMapExtents(mBox, 10); + float scale = (float) (cam.mMapPosition.scale / v.pos.scale); - float dx = (float) (cam.mMapPosition.x - v.pos.x) - * (Tile.SIZE << cam.mMapPosition.zoomLevel); - float dy = (float) (cam.mMapPosition.y - v.pos.y) - * (Tile.SIZE << cam.mMapPosition.zoomLevel); + float dx = (float) (cam.mMapPosition.x - v.pos.x) + * (Tile.SIZE << cam.mMapPosition.zoomLevel); + float dy = (float) (cam.mMapPosition.y - v.pos.y) + * (Tile.SIZE << cam.mMapPosition.zoomLevel); - for (int i = 0; i < 8; i += 2) { - mBox[i] *= scale; - mBox[i] -= dx; - mBox[i + 1] *= scale; - mBox[i + 1] -= dy; - } + for (int i = 0; i < 8; i += 2) { + mBox[i] *= scale; + mBox[i] -= dx; + mBox[i + 1] *= scale; + mBox[i + 1] -= dy; + } - //int w = mMap.getWidth() / 2; - //int h = mMap.getHeight() / 2; - //float sqRadius = (w * w + h * h) / scale; + //int w = mMap.getWidth() / 2; + //int h = mMap.getHeight() / 2; + //float sqRadius = (w * w + h * h) / scale; - synchronized (this) { - if (instances.size == 0) - return; + synchronized (this) { + if (instances.size == 0) + return; - //renderContext.begin(); + //renderContext.begin(); - // if (shader == null) { - // r = instances.get(0).getRenderable(r); - // DefaultShader.Config c = new DefaultShader.Config(); - // c.numBones = 0; - // c.numDirectionalLights = 1; - // r.environment = lights; - // - // shader = new DefaultShader(r, c); - // shader.init(); - // } - mBatch.begin(cam); - //shader.begin(cam, renderContext); + // if (shader == null) { + // r = instances.get(0).getRenderable(r); + // DefaultShader.Config c = new DefaultShader.Config(); + // c.numBones = 0; + // c.numDirectionalLights = 1; + // r.environment = lights; + // + // shader = new DefaultShader(r, c); + // shader.init(); + // } + mBatch.begin(cam); + //shader.begin(cam, renderContext); - for (SharedModel instance : instances) { - instance.transform.getTranslation(tempVector); - //instance.getRenderables(renderables, pool); - // if (tempVector.x * tempVector.x + tempVector.y * tempVector.y > sqRadius) - // continue; - // tempVector.scl(0.8f, 0.8f, 1); - // if (!GeometryUtils.pointInPoly(tempVector.x, tempVector.y, mBox, 8, 0)) - // continue; + for (SharedModel instance : instances) { + instance.transform.getTranslation(tempVector); + //instance.getRenderables(renderables, pool); + // if (tempVector.x * tempVector.x + tempVector.y * tempVector.y > sqRadius) + // continue; + // tempVector.scl(0.8f, 0.8f, 1); + // if (!GeometryUtils.pointInPoly(tempVector.x, tempVector.y, mBox, 8, 0)) + // continue; - mBatch.render(instance); + mBatch.render(instance); - //shader.render(r); - } - mBatch.end(); + //shader.render(r); + } + mBatch.end(); - //shader.end(); - //renderContext.end(); - } + //shader.end(); + //renderContext.end(); + } - gl.depthMask(false); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); - gl.bindBuffer(GL.ARRAY_BUFFER, 0); - } + gl.depthMask(false); + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); + gl.bindBuffer(GL.ARRAY_BUFFER, 0); + } - // @Override - // public void dispose () { - // modelBatch.dispose(); - // assets.dispose(); - // assets = null; - // axesModel.dispose(); - // axesModel = null; - // } + // @Override + // public void dispose () { + // modelBatch.dispose(); + // assets.dispose(); + // assets = null; + // axesModel.dispose(); + // axesModel = null; + // } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D.java index 12f7e59a..ec5751d1 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D.java @@ -1,18 +1,5 @@ package org.oscim.test.gdx.poi3d; -import static org.oscim.backend.GLAdapter.gl; - -import org.oscim.backend.GL; -import org.oscim.core.Tile; -import org.oscim.map.Map; -import org.oscim.map.Viewport; -import org.oscim.renderer.GLState; -import org.oscim.renderer.GLViewport; -import org.oscim.renderer.LayerRenderer; -import org.oscim.utils.geom.GeometryUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; @@ -27,174 +14,187 @@ import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; +import org.oscim.backend.GL; +import org.oscim.core.Tile; +import org.oscim.map.Map; +import org.oscim.map.Viewport; +import org.oscim.renderer.GLState; +import org.oscim.renderer.GLViewport; +import org.oscim.renderer.LayerRenderer; +import org.oscim.utils.geom.GeometryUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.oscim.backend.GLAdapter.gl; + public class GdxRenderer3D extends LayerRenderer { - static final Logger log = LoggerFactory.getLogger(GdxRenderer3D.class); + static final Logger log = LoggerFactory.getLogger(GdxRenderer3D.class); - ModelBatch modelBatch; - public MapCamera cam; - Map mMap; + ModelBatch modelBatch; + public MapCamera cam; + Map mMap; - boolean loading; + boolean loading; - public Environment lights; + public Environment lights; - public Array instances = new Array(); + public Array instances = new Array(); - public Shader shader; - public RenderContext renderContext; - public Model model; + public Shader shader; + public RenderContext renderContext; + public Model model; - public GdxRenderer3D(Map map) { - mMap = map; - } + public GdxRenderer3D(Map map) { + mMap = map; + } - @Override - public boolean setup() { + @Override + public boolean setup() { - modelBatch = new ModelBatch(new DefaultShaderProvider()); + modelBatch = new ModelBatch(new DefaultShaderProvider()); - lights = new Environment(); - lights.set(new ColorAttribute(ColorAttribute.AmbientLight, 1.0f, 1.0f, 1.0f, 1.f)); - lights.add(new DirectionalLight().set(0.3f, 0.3f, 0.3f, 0, 1, -0.2f)); + lights = new Environment(); + lights.set(new ColorAttribute(ColorAttribute.AmbientLight, 1.0f, 1.0f, 1.0f, 1.f)); + lights.add(new DirectionalLight().set(0.3f, 0.3f, 0.3f, 0, 1, -0.2f)); - cam = new MapCamera(mMap); + cam = new MapCamera(mMap); - renderContext = - new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); + renderContext = + new RenderContext(new DefaultTextureBinder(DefaultTextureBinder.WEIGHTED, 1)); - // shader = new DefaultShader(renderable.material, - // renderable.mesh.getVertexAttributes(), true, false, 1, 0, 0, 0); - // shader.init(); + // shader = new DefaultShader(renderable.material, + // renderable.mesh.getVertexAttributes(), true, false, 1, 0, 0, 0); + // shader.init(); - return true; - } + return true; + } - @Override - public synchronized void update(GLViewport v) { - // if (loading && assets.update()) - // doneLoading(); + @Override + public synchronized void update(GLViewport v) { + // if (loading && assets.update()) + // doneLoading(); - if (!isReady()) { - cam.setPosition(v.pos); - setReady(true); - } + if (!isReady()) { + cam.setPosition(v.pos); + setReady(true); + } - // if (changed) { - // cam.update(position, matrices); - // } - } + // if (changed) { + // cam.update(position, matrices); + // } + } - Vector3 tempVector = new Vector3(); - float[] mBox = new float[8]; + Vector3 tempVector = new Vector3(); + float[] mBox = new float[8]; - Renderable r = new Renderable(); + Renderable r = new Renderable(); - @Override - public void render(GLViewport v) { - if (instances.size == 0) - return; + @Override + public void render(GLViewport v) { + if (instances.size == 0) + return; - // GLUtils.checkGlError(">" + TAG); + // GLUtils.checkGlError(">" + TAG); - gl.depthMask(true); + gl.depthMask(true); - // if (position.zoomLevel < 17) - // GL.clear(GL20.DEPTH_BUFFER_BIT); + // if (position.zoomLevel < 17) + // GL.clear(GL20.DEPTH_BUFFER_BIT); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); - // set state that is expected after modelBatch.end(); - // modelBatch keeps track of its own state - GLState.enableVertexArrays(-1, -1); - GLState.bindTex2D(-1); - GLState.useProgram(-1); - GLState.test(false, false); - GLState.blend(false); + // set state that is expected after modelBatch.end(); + // modelBatch keeps track of its own state + GLState.enableVertexArrays(-1, -1); + GLState.bindTex2D(-1); + GLState.useProgram(-1); + GLState.test(false, false); + GLState.blend(false); - cam.update(v); - long time = System.currentTimeMillis(); + cam.update(v); + long time = System.currentTimeMillis(); - int cnt = 0; - int rnd = 0; + int cnt = 0; + int rnd = 0; - Viewport p = mMap.viewport(); - p.getMapExtents(mBox, 10); - float scale = (float) (cam.mMapPosition.scale / v.pos.scale); + Viewport p = mMap.viewport(); + p.getMapExtents(mBox, 10); + float scale = (float) (cam.mMapPosition.scale / v.pos.scale); - float dx = (float) (cam.mMapPosition.x - v.pos.x) - * (Tile.SIZE << cam.mMapPosition.zoomLevel); - float dy = (float) (cam.mMapPosition.y - v.pos.y) - * (Tile.SIZE << cam.mMapPosition.zoomLevel); + float dx = (float) (cam.mMapPosition.x - v.pos.x) + * (Tile.SIZE << cam.mMapPosition.zoomLevel); + float dy = (float) (cam.mMapPosition.y - v.pos.y) + * (Tile.SIZE << cam.mMapPosition.zoomLevel); - for (int i = 0; i < 8; i += 2) { - mBox[i] *= scale; - mBox[i] -= dx; - mBox[i + 1] *= scale; - mBox[i + 1] -= dy; - } + for (int i = 0; i < 8; i += 2) { + mBox[i] *= scale; + mBox[i] -= dx; + mBox[i + 1] *= scale; + mBox[i + 1] -= dy; + } - int w = mMap.getWidth() / 2; - int h = mMap.getHeight() / 2; + int w = mMap.getWidth() / 2; + int h = mMap.getHeight() / 2; - float sqRadius = (w * w + h * h) / scale; + float sqRadius = (w * w + h * h) / scale; - synchronized (this) { - if (instances.size == 0) - return; + synchronized (this) { + if (instances.size == 0) + return; - cnt = instances.size; + cnt = instances.size; - renderContext.begin(); + renderContext.begin(); - if (shader == null) { - r = instances.get(0).getRenderable(r); - DefaultShader.Config c = new DefaultShader.Config(); - c.numBones = 0; - c.numDirectionalLights = 1; - r.environment = lights; - // shader = new DefaultShader(r, true, false, false, false, 1, - // 0, 0, 0); - shader = new DefaultShader(r, c); - shader.init(); - } + if (shader == null) { + r = instances.get(0).getRenderable(r); + DefaultShader.Config c = new DefaultShader.Config(); + c.numBones = 0; + c.numDirectionalLights = 1; + r.environment = lights; + // shader = new DefaultShader(r, true, false, false, false, 1, + // 0, 0, 0); + shader = new DefaultShader(r, c); + shader.init(); + } - shader.begin(cam, renderContext); + shader.begin(cam, renderContext); - for (SharedModel instance : instances) { - instance.transform.getTranslation(tempVector); + for (SharedModel instance : instances) { + instance.transform.getTranslation(tempVector); - if (tempVector.x * tempVector.x + tempVector.y * tempVector.y > sqRadius) - continue; + if (tempVector.x * tempVector.x + tempVector.y * tempVector.y > sqRadius) + continue; - tempVector.scl(0.8f, 0.8f, 1); + tempVector.scl(0.8f, 0.8f, 1); - if (!GeometryUtils.pointInPoly(tempVector.x, tempVector.y, mBox, 8, 0)) - continue; + if (!GeometryUtils.pointInPoly(tempVector.x, tempVector.y, mBox, 8, 0)) + continue; - instance.getRenderable(r); - // r.lights = lights; - // r.environment = lights; - shader.render(r); + instance.getRenderable(r); + // r.lights = lights; + // r.environment = lights; + shader.render(r); - rnd++; - } + rnd++; + } - shader.end(); - renderContext.end(); - } - log.debug(">>> " + (System.currentTimeMillis() - time) + " " + cnt + "/" + rnd); + shader.end(); + renderContext.end(); + } + log.debug(">>> " + (System.currentTimeMillis() - time) + " " + cnt + "/" + rnd); - gl.depthMask(false); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); - gl.bindBuffer(GL.ARRAY_BUFFER, 0); - } + gl.depthMask(false); + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); + gl.bindBuffer(GL.ARRAY_BUFFER, 0); + } - // @Override - // public void dispose () { - // modelBatch.dispose(); - // assets.dispose(); - // assets = null; - // axesModel.dispose(); - // axesModel = null; - // } + // @Override + // public void dispose () { + // modelBatch.dispose(); + // assets.dispose(); + // assets = null; + // axesModel.dispose(); + // axesModel = null; + // } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D2.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D2.java index e4a96c24..ddf8b756 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D2.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/GdxRenderer3D2.java @@ -1,6 +1,11 @@ package org.oscim.test.gdx.poi3d; -import static org.oscim.backend.GLAdapter.gl; +import com.badlogic.gdx.graphics.g3d.Environment; +import com.badlogic.gdx.graphics.g3d.ModelBatch; +import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; +import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; +import com.badlogic.gdx.math.Vector3; +import com.badlogic.gdx.utils.Array; import org.oscim.backend.GL; import org.oscim.core.Tile; @@ -13,154 +18,149 @@ import org.oscim.utils.geom.GeometryUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.graphics.g3d.Environment; -import com.badlogic.gdx.graphics.g3d.ModelBatch; -import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; -import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; -import com.badlogic.gdx.math.Vector3; -import com.badlogic.gdx.utils.Array; +import static org.oscim.backend.GLAdapter.gl; public class GdxRenderer3D2 extends LayerRenderer { - static final Logger log = LoggerFactory.getLogger(GdxRenderer3D2.class); + static final Logger log = LoggerFactory.getLogger(GdxRenderer3D2.class); - ModelBatch modelBatch; - public MapCamera cam; - Map mMap; + ModelBatch modelBatch; + public MapCamera cam; + Map mMap; - boolean loading; + boolean loading; - public Environment lights; + public Environment lights; - public Array instances = new Array(); + public Array instances = new Array(); - public GdxRenderer3D2(Map map) { - mMap = map; - } + public GdxRenderer3D2(Map map) { + mMap = map; + } - @Override - public boolean setup() { + @Override + public boolean setup() { - // if (assets == null) - // assets = new AssetManager(); + // if (assets == null) + // assets = new AssetManager(); - // assets.load("data/g3d/invaders.g3dj", Model.class); - // loading = true; + // assets.load("data/g3d/invaders.g3dj", Model.class); + // loading = true; - modelBatch = new ModelBatch(new DefaultShaderProvider()); + modelBatch = new ModelBatch(new DefaultShaderProvider()); - lights = new Environment(); - // lights.ambientLight.set(1.0f, 1.0f, 1.0f, 1f); - // lights.ambientLight.set(215 / 255f, - // 240 / 255f, - // 51 / 255f, 1f); + lights = new Environment(); + // lights.ambientLight.set(1.0f, 1.0f, 1.0f, 1f); + // lights.ambientLight.set(215 / 255f, + // 240 / 255f, + // 51 / 255f, 1f); - lights.add(new DirectionalLight().set(0.9f, 0.9f, 0.9f, 0, 1, -0.2f)); + lights.add(new DirectionalLight().set(0.9f, 0.9f, 0.9f, 0, 1, -0.2f)); - cam = new MapCamera(mMap); + cam = new MapCamera(mMap); - return true; - } + return true; + } - @Override - public synchronized void update(GLViewport v) { - // if (loading && assets.update()) - // doneLoading(); + @Override + public synchronized void update(GLViewport v) { + // if (loading && assets.update()) + // doneLoading(); - if (!isReady()) { - cam.setPosition(v.pos); - setReady(true); - } + if (!isReady()) { + cam.setPosition(v.pos); + setReady(true); + } - // if (changed) { - // cam.update(position, matrices); - // } - } + // if (changed) { + // cam.update(position, matrices); + // } + } - Vector3 tempVector = new Vector3(); - float[] mBox = new float[8]; + Vector3 tempVector = new Vector3(); + float[] mBox = new float[8]; - @Override - public void render(GLViewport v) { - if (instances.size == 0) - return; + @Override + public void render(GLViewport v) { + if (instances.size == 0) + return; - // GLUtils.checkGlError(">" + TAG); + // GLUtils.checkGlError(">" + TAG); - gl.depthMask(true); + gl.depthMask(true); - if (v.pos.zoomLevel < 17) - gl.clear(GL.DEPTH_BUFFER_BIT); + if (v.pos.zoomLevel < 17) + gl.clear(GL.DEPTH_BUFFER_BIT); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); - // set state that is expected after modelBatch.end(); - // modelBatch keeps track of its own state - GLState.enableVertexArrays(-1, -1); - GLState.bindTex2D(-1); - GLState.useProgram(-1); - GLState.test(false, false); - GLState.blend(false); + // set state that is expected after modelBatch.end(); + // modelBatch keeps track of its own state + GLState.enableVertexArrays(-1, -1); + GLState.bindTex2D(-1); + GLState.useProgram(-1); + GLState.test(false, false); + GLState.blend(false); - // GL.cullFace(GL20.BACK); - // GL.frontFace(GL20.CW); + // GL.cullFace(GL20.BACK); + // GL.frontFace(GL20.CW); - cam.update(v); - long time = System.currentTimeMillis(); + cam.update(v); + long time = System.currentTimeMillis(); - int cnt = 0; - int rnd = 0; + int cnt = 0; + int rnd = 0; - Viewport p = mMap.viewport(); - p.getMapExtents(mBox, 10); - float scale = (float) (cam.mMapPosition.scale / v.pos.scale); + Viewport p = mMap.viewport(); + p.getMapExtents(mBox, 10); + float scale = (float) (cam.mMapPosition.scale / v.pos.scale); - float dx = - (float) (cam.mMapPosition.x - v.pos.x) - * (Tile.SIZE << cam.mMapPosition.zoomLevel); - float dy = - (float) (cam.mMapPosition.y - v.pos.y) - * (Tile.SIZE << cam.mMapPosition.zoomLevel); + float dx = + (float) (cam.mMapPosition.x - v.pos.x) + * (Tile.SIZE << cam.mMapPosition.zoomLevel); + float dy = + (float) (cam.mMapPosition.y - v.pos.y) + * (Tile.SIZE << cam.mMapPosition.zoomLevel); - for (int i = 0; i < 8; i += 2) { - mBox[i] *= scale; - mBox[i] -= dx; - mBox[i + 1] *= scale; - mBox[i + 1] -= dy; - } + for (int i = 0; i < 8; i += 2) { + mBox[i] *= scale; + mBox[i] -= dx; + mBox[i + 1] *= scale; + mBox[i + 1] -= dy; + } - synchronized (this) { - modelBatch.begin(cam); - cnt = instances.size; + synchronized (this) { + modelBatch.begin(cam); + cnt = instances.size; - for (SharedModel instance : instances) { - instance.transform.getTranslation(tempVector); - tempVector.scl(0.9f, 0.9f, 1); - if (!GeometryUtils.pointInPoly(tempVector.x, tempVector.y, mBox, 8, 0)) - continue; + for (SharedModel instance : instances) { + instance.transform.getTranslation(tempVector); + tempVector.scl(0.9f, 0.9f, 1); + if (!GeometryUtils.pointInPoly(tempVector.x, tempVector.y, mBox, 8, 0)) + continue; - modelBatch.render(instance); - rnd++; - } - modelBatch.end(); - } - log.debug(">>> " + (System.currentTimeMillis() - time) + " " + cnt + "/" + rnd); + modelBatch.render(instance); + rnd++; + } + modelBatch.end(); + } + log.debug(">>> " + (System.currentTimeMillis() - time) + " " + cnt + "/" + rnd); - // GLUtils.checkGlError("<" + TAG); + // GLUtils.checkGlError("<" + TAG); - gl.depthMask(false); - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); - gl.bindBuffer(GL.ARRAY_BUFFER, 0); + gl.depthMask(false); + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, 0); + gl.bindBuffer(GL.ARRAY_BUFFER, 0); - // GLState.bindTex2D(-1); - // GLState.useProgram(-1); - } + // GLState.bindTex2D(-1); + // GLState.useProgram(-1); + } - // @Override - // public void dispose () { - // modelBatch.dispose(); - // assets.dispose(); - // assets = null; - // axesModel.dispose(); - // axesModel = null; - // } + // @Override + // public void dispose () { + // modelBatch.dispose(); + // assets.dispose(); + // assets = null; + // axesModel.dispose(); + // axesModel = null; + // } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/MapCamera.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/MapCamera.java index d935a0a7..12367823 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/MapCamera.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/MapCamera.java @@ -1,70 +1,70 @@ package org.oscim.test.gdx.poi3d; +import com.badlogic.gdx.graphics.Camera; +import com.badlogic.gdx.math.Matrix4; + import org.oscim.core.MapPosition; import org.oscim.core.Tile; import org.oscim.map.Map; import org.oscim.renderer.GLViewport; -import com.badlogic.gdx.graphics.Camera; -import com.badlogic.gdx.math.Matrix4; - public class MapCamera extends Camera { - private final Map mMap; + private final Map mMap; - public MapCamera(Map map) { - mMap = map; + public MapCamera(Map map) { + mMap = map; - this.near = 1; - this.far = 8; - } + this.near = 1; + this.far = 8; + } - MapPosition mMapPosition = new MapPosition(); + MapPosition mMapPosition = new MapPosition(); - public void setPosition(MapPosition pos) { - mMapPosition.copy(pos); + public void setPosition(MapPosition pos) { + mMapPosition.copy(pos); - this.viewportWidth = mMap.getWidth(); - this.viewportHeight = mMap.getHeight(); - } + this.viewportWidth = mMap.getWidth(); + this.viewportHeight = mMap.getHeight(); + } - public void setMapPosition(double x, double y, double scale) { - mMapPosition.setScale(scale); - mMapPosition.x = x; - mMapPosition.y = y; - } + public void setMapPosition(double x, double y, double scale) { + mMapPosition.setScale(scale); + mMapPosition.x = x; + mMapPosition.y = y; + } - public void update(GLViewport v) { - double scale = (v.pos.scale * Tile.SIZE); + public void update(GLViewport v) { + double scale = (v.pos.scale * Tile.SIZE); - float x = (float) ((mMapPosition.x - v.pos.x) * scale); - float y = (float) ((mMapPosition.y - v.pos.y) * scale); - float z = (float) (v.pos.scale / mMapPosition.scale); + float x = (float) ((mMapPosition.x - v.pos.x) * scale); + float y = (float) ((mMapPosition.y - v.pos.y) * scale); + float z = (float) (v.pos.scale / mMapPosition.scale); - v.proj.get(projection.getValues()); - v.mvp.setTransScale(x, y, z); - v.mvp.setValue(10, z); - v.mvp.multiplyLhs(v.view); - v.mvp.get(view.getValues()); + v.proj.get(projection.getValues()); + v.mvp.setTransScale(x, y, z); + v.mvp.setValue(10, z); + v.mvp.multiplyLhs(v.view); + v.mvp.get(view.getValues()); - combined.set(projection); + combined.set(projection); - Matrix4.mul(combined.val, view.val); + Matrix4.mul(combined.val, view.val); - //if (updateFrustum) { - invProjectionView.set(combined); - Matrix4.inv(invProjectionView.val); - frustum.update(invProjectionView); - //} - } + //if (updateFrustum) { + invProjectionView.set(combined); + Matrix4.inv(invProjectionView.val); + frustum.update(invProjectionView); + //} + } - @Override - public void update() { - } + @Override + public void update() { + } - @Override - public void update(boolean updateFrustum) { + @Override + public void update(boolean updateFrustum) { - } + } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/Poi3DLayer.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/Poi3DLayer.java index 9f021f48..3434f5ae 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/Poi3DLayer.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/Poi3DLayer.java @@ -1,7 +1,9 @@ package org.oscim.test.gdx.poi3d; -import java.util.LinkedHashMap; -import java.util.Map.Entry; +import com.badlogic.gdx.assets.AssetManager; +import com.badlogic.gdx.graphics.g3d.Model; +import com.badlogic.gdx.graphics.g3d.model.Node; +import com.badlogic.gdx.utils.Array; import org.oscim.core.MapElement; import org.oscim.core.MapPosition; @@ -21,242 +23,240 @@ import org.oscim.renderer.bucket.SymbolItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.assets.AssetManager; -import com.badlogic.gdx.graphics.g3d.Model; -import com.badlogic.gdx.graphics.g3d.model.Node; -import com.badlogic.gdx.utils.Array; +import java.util.LinkedHashMap; +import java.util.Map.Entry; public class Poi3DLayer extends Layer implements Map.UpdateListener { - static final Logger log = LoggerFactory.getLogger(Poi3DLayer.class); + static final Logger log = LoggerFactory.getLogger(Poi3DLayer.class); - static class Poi3DTileData extends TileData { - public final List symbols = new List(); + static class Poi3DTileData extends TileData { + public final List symbols = new List(); - @Override - protected void dispose() { - SymbolItem.pool.releaseAll(symbols.clear()); - } - } + @Override + protected void dispose() { + SymbolItem.pool.releaseAll(symbols.clear()); + } + } - final static String POI_DATA = Poi3DLayer.class.getSimpleName(); - final static Tag TREE_TAG = new Tag("natural", "tree"); + final static String POI_DATA = Poi3DLayer.class.getSimpleName(); + final static Tag TREE_TAG = new Tag("natural", "tree"); - private Poi3DTileData get(MapTile tile) { - Poi3DTileData ld = (Poi3DTileData) tile.getData(POI_DATA); - if (ld == null) { - ld = new Poi3DTileData(); - tile.addData(POI_DATA, ld); - } - return ld; - } + private Poi3DTileData get(MapTile tile) { + Poi3DTileData ld = (Poi3DTileData) tile.getData(POI_DATA); + if (ld == null) { + ld = new Poi3DTileData(); + tile.addData(POI_DATA, ld); + } + return ld; + } - GdxRenderer3D g3d; - VectorTileLayer mTileLayer; + GdxRenderer3D g3d; + VectorTileLayer mTileLayer; - public Poi3DLayer(Map map, VectorTileLayer tileLayer) { - super(map); - tileLayer.addHook(new TileLoaderProcessHook() { + public Poi3DLayer(Map map, VectorTileLayer tileLayer) { + super(map); + tileLayer.addHook(new TileLoaderProcessHook() { - @Override - public boolean process(MapTile tile, RenderBuckets buckets, MapElement element) { + @Override + public boolean process(MapTile tile, RenderBuckets buckets, MapElement element) { - if (!element.tags.contains(TREE_TAG)) - return false; + if (!element.tags.contains(TREE_TAG)) + return false; - Poi3DTileData td = get(tile); - PointF p = element.getPoint(0); - SymbolItem s = SymbolItem.pool.get(); - s.x = p.x; - s.y = p.y; - td.symbols.push(s); + Poi3DTileData td = get(tile); + PointF p = element.getPoint(0); + SymbolItem s = SymbolItem.pool.get(); + s.x = p.x; + s.y = p.y; + td.symbols.push(s); - return true; - } + return true; + } - @Override - public void complete(MapTile tile, boolean success) { - } - }); - mTileLayer = tileLayer; + @Override + public void complete(MapTile tile, boolean success) { + } + }); + mTileLayer = tileLayer; - mRenderer = g3d = new GdxRenderer3D(mMap); + mRenderer = g3d = new GdxRenderer3D(mMap); - // Material mat = new - // Material(ColorAttribute.createDiffuse(Color.BLUE)); - // ModelBuilder modelBuilder = new ModelBuilder(); - // long attributes = Usage.Position | Usage.Normal | - // Usage.TextureCoordinates; + // Material mat = new + // Material(ColorAttribute.createDiffuse(Color.BLUE)); + // ModelBuilder modelBuilder = new ModelBuilder(); + // long attributes = Usage.Position | Usage.Normal | + // Usage.TextureCoordinates; - // mModel = modelBuilder.createSphere(10f, 10f, 10f, 12, 12, - // mat, attributes); + // mModel = modelBuilder.createSphere(10f, 10f, 10f, 12, 12, + // mat, attributes); - assets = new AssetManager(); - assets.load("data/g3d/treeA.g3dj", Model.class); - loading = true; - } + assets = new AssetManager(); + assets.load("data/g3d/treeA.g3dj", Model.class); + loading = true; + } - TileSet mTileSet = new TileSet(); - TileSet mPrevTiles = new TileSet(); + TileSet mTileSet = new TileSet(); + TileSet mPrevTiles = new TileSet(); - LinkedHashMap> mTileMap = - new LinkedHashMap>(); + LinkedHashMap> mTileMap = + new LinkedHashMap>(); - boolean loading; - Model mModel; - AssetManager assets; + boolean loading; + Model mModel; + AssetManager assets; - private void doneLoading() { - Model model = assets.get("data/g3d/treeA.g3dj", Model.class); - for (int i = 0; i < model.nodes.size; i++) { - Node node = model.nodes.get(i); + private void doneLoading() { + Model model = assets.get("data/g3d/treeA.g3dj", Model.class); + for (int i = 0; i < model.nodes.size; i++) { + Node node = model.nodes.get(i); - if (node.id.equals("treeA_root")) { - node.rotation.setFromAxis(1, 0, 0, 90); - mModel = model; + if (node.id.equals("treeA_root")) { + node.rotation.setFromAxis(1, 0, 0, 90); + mModel = model; - } - } + } + } - loading = false; - } + loading = false; + } - @Override - public void onMapEvent(Event ev, MapPosition pos) { + @Override + public void onMapEvent(Event ev, MapPosition pos) { - if (ev == Map.CLEAR_EVENT) { - mTileSet = new TileSet(); - mPrevTiles = new TileSet(); - mTileMap = new LinkedHashMap>(); - synchronized (g3d) { - g3d.instances.clear(); - } - } + if (ev == Map.CLEAR_EVENT) { + mTileSet = new TileSet(); + mPrevTiles = new TileSet(); + mTileMap = new LinkedHashMap>(); + synchronized (g3d) { + g3d.instances.clear(); + } + } - if (loading && assets.update()) { - doneLoading(); - // Renderable renderable = new Renderable(); - // new SharedModel(mModel).getRenderable(renderable); - // Shader shader = new DefaultShader(renderable, true, false, - // false, false, 1, 0, 0, 0); - } - if (loading) - return; + if (loading && assets.update()) { + doneLoading(); + // Renderable renderable = new Renderable(); + // new SharedModel(mModel).getRenderable(renderable); + // Shader shader = new DefaultShader(renderable, true, false, + // false, false, 1, 0, 0, 0); + } + if (loading) + return; - // log.debug("update"); + // log.debug("update"); - mTileLayer.tileRenderer().getVisibleTiles(mTileSet); + mTileLayer.tileRenderer().getVisibleTiles(mTileSet); - if (mTileSet.cnt == 0) { - mTileSet.releaseTiles(); - return; - } + if (mTileSet.cnt == 0) { + mTileSet.releaseTiles(); + return; + } - boolean changed = false; + boolean changed = false; - Array added = new Array(); - Array removed = new Array(); + Array added = new Array(); + Array removed = new Array(); - for (int i = 0; i < mTileSet.cnt; i++) { - MapTile t = mTileSet.tiles[i]; - if (mPrevTiles.contains(t)) - continue; + for (int i = 0; i < mTileSet.cnt; i++) { + MapTile t = mTileSet.tiles[i]; + if (mPrevTiles.contains(t)) + continue; - Array instances = new Array(); + Array instances = new Array(); - Poi3DTileData ld = (Poi3DTileData) t.getData(POI_DATA); - if (ld == null) - continue; + Poi3DTileData ld = (Poi3DTileData) t.getData(POI_DATA); + if (ld == null) + continue; - for (SymbolItem it : ld.symbols) { + for (SymbolItem it : ld.symbols) { - SharedModel inst = new SharedModel(mModel); - inst.userData = it; - // float r = 0.5f + 0.5f * (float) Math.random(); - // float g = 0.5f + 0.5f * (float) Math.random(); - // float b = 0.5f + 0.5f * (float) Math.random(); + SharedModel inst = new SharedModel(mModel); + inst.userData = it; + // float r = 0.5f + 0.5f * (float) Math.random(); + // float g = 0.5f + 0.5f * (float) Math.random(); + // float b = 0.5f + 0.5f * (float) Math.random(); - // inst.transform.setTranslation(new Vector3(it.x, it.y, - // 10)); - // inst.materials.get(0).set(ColorAttribute.createDiffuse(r, - // g, b, 0.8f)); - instances.add(inst); - added.add(inst); - } + // inst.transform.setTranslation(new Vector3(it.x, it.y, + // 10)); + // inst.materials.get(0).set(ColorAttribute.createDiffuse(r, + // g, b, 0.8f)); + instances.add(inst); + added.add(inst); + } - if (instances.size == 0) - continue; + if (instances.size == 0) + continue; - log.debug("add " + t + " " + instances.size); + log.debug("add " + t + " " + instances.size); - changed = true; + changed = true; - mTileMap.put(t, instances); - } + mTileMap.put(t, instances); + } - for (int i = 0; i < mPrevTiles.cnt; i++) { - MapTile t = mPrevTiles.tiles[i]; - if (mTileSet.contains(t)) - continue; + for (int i = 0; i < mPrevTiles.cnt; i++) { + MapTile t = mPrevTiles.tiles[i]; + if (mTileSet.contains(t)) + continue; - Array instances = mTileMap.get(t); - if (instances == null) - continue; + Array instances = mTileMap.get(t); + if (instances == null) + continue; - changed = true; + changed = true; - removed.addAll(instances); - mTileMap.remove(t); - log.debug("remove " + t); - } + removed.addAll(instances); + mTileMap.remove(t); + log.debug("remove " + t); + } - mPrevTiles.releaseTiles(); + mPrevTiles.releaseTiles(); - int zoom = mTileSet.tiles[0].zoomLevel; + int zoom = mTileSet.tiles[0].zoomLevel; - TileSet tmp = mPrevTiles; - mPrevTiles = mTileSet; - mTileSet = tmp; + TileSet tmp = mPrevTiles; + mPrevTiles = mTileSet; + mTileSet = tmp; - if (!changed) - return; + if (!changed) + return; - // scale aka tree height - float scale = (float) (1f / (1 << (17 - zoom))) * 8; + // scale aka tree height + float scale = (float) (1f / (1 << (17 - zoom))) * 8; - double tileX = (pos.x * (Tile.SIZE << zoom)); - double tileY = (pos.y * (Tile.SIZE << zoom)); + double tileX = (pos.x * (Tile.SIZE << zoom)); + double tileY = (pos.y * (Tile.SIZE << zoom)); - synchronized (g3d) { + synchronized (g3d) { - for (Entry> e : mTileMap.entrySet()) { - Tile t = e.getKey(); + for (Entry> e : mTileMap.entrySet()) { + Tile t = e.getKey(); - float dx = (float) (t.tileX * Tile.SIZE - tileX); - float dy = (float) (t.tileY * Tile.SIZE - tileY); + float dx = (float) (t.tileX * Tile.SIZE - tileX); + float dy = (float) (t.tileY * Tile.SIZE - tileY); - for (SharedModel inst : e.getValue()) { - SymbolItem it = (SymbolItem) inst.userData; + for (SharedModel inst : e.getValue()) { + SymbolItem it = (SymbolItem) inst.userData; - // variable height - float s = scale + (it.x * it.y) % 3; - float r = (it.x * it.y) % 360; + // variable height + float s = scale + (it.x * it.y) % 3; + float r = (it.x * it.y) % 360; - inst.transform.idt(); - inst.transform.scale(s, s, s); - inst.transform.translate((dx + it.x) / s, (dy + it.y) / s, 0); - inst.transform.rotate(0, 0, 1, r); + inst.transform.idt(); + inst.transform.scale(s, s, s); + inst.transform.translate((dx + it.x) / s, (dy + it.y) / s, 0); + inst.transform.rotate(0, 0, 1, r); - // inst.transform.setToTranslationAndScaling((dx + - // it.x), (dy + it.y), - // 0, s, s, s); + // inst.transform.setToTranslationAndScaling((dx + + // it.x), (dy + it.y), + // 0, s, s, s); - } - } + } + } - g3d.instances.removeAll(removed, true); - g3d.instances.addAll(added); - g3d.cam.setMapPosition(pos.x, pos.y, 1 << zoom); - } - } + g3d.instances.removeAll(removed, true); + g3d.instances.addAll(added); + g3d.cam.setMapPosition(pos.x, pos.y, 1 << zoom); + } + } } diff --git a/vtm-playground/src/org/oscim/test/gdx/poi3d/SharedModel.java b/vtm-playground/src/org/oscim/test/gdx/poi3d/SharedModel.java index 4f1babb2..74752646 100644 --- a/vtm-playground/src/org/oscim/test/gdx/poi3d/SharedModel.java +++ b/vtm-playground/src/org/oscim/test/gdx/poi3d/SharedModel.java @@ -20,420 +20,488 @@ import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Pool; -/** An instance of a {@link Model}, allows to specify global transform and modify the materials, as it - * has a copy of the model's materials. Multiple instances can be created from the same Model, - * all sharing the meshes and textures of the Model. The Model owns the meshes and textures, to +/** + * An instance of a {@link Model}, allows to specify global transform and modify the materials, as it + * has a copy of the model's materials. Multiple instances can be created from the same Model, + * all sharing the meshes and textures of the Model. The Model owns the meshes and textures, to * dispose of these, the Model has to be disposed. Therefor, the Model must outlive all its ModelInstances

- * + *

* The ModelInstance creates a full copy of all materials, nodes and animations. - * @author badlogic, xoppa */ + * + * @author badlogic, xoppa + */ public class SharedModel implements RenderableProvider { - /** the materials of the model, used by nodes that have a graphical representation FIXME not sure if superfluous, allows modification of materials without having to traverse the nodes **/ - public final Array materials = new Array(); - /** root nodes of the model **/ - public final Array nodes = new Array(); - /** animations of the model, modifying node transformations **/ - public final Array animations = new Array(); - /** the {@link Model} this instances derives from **/ - public final Model model; - /** the world transform **/ - public Matrix4 transform; - /** user definable value, which is passed to the shader. */ - public Object userData; - - /** Constructs a new ModelInstance with all nodes and materials of the given model. - * @param model The {@link Model} to create an instance of. */ - public SharedModel(final Model model) { - this(model, (String[])null); - } - - /** @param model The source {@link Model} - * @param nodeId The ID of the root {@link Node} of the {@link Model} for the instance to contain - * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. */ - public SharedModel(final Model model, final String nodeId, boolean mergeTransform) { - this(model, null, nodeId, false, false, mergeTransform); - } - - /** @param model The source {@link Model} - * @param transform The {@link Matrix4} instance for this ModelInstance to reference or null to create a new matrix. - * @param nodeId The ID of the root {@link Node} of the {@link Model} for the instance to contain - * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. */ - public SharedModel(final Model model, final Matrix4 transform, final String nodeId, boolean mergeTransform) { - this(model, transform, nodeId, false, false, mergeTransform); - } + /** + * the materials of the model, used by nodes that have a graphical representation FIXME not sure if superfluous, allows modification of materials without having to traverse the nodes + **/ + public final Array materials = new Array(); + /** + * root nodes of the model + **/ + public final Array nodes = new Array(); + /** + * animations of the model, modifying node transformations + **/ + public final Array animations = new Array(); + /** + * the {@link Model} this instances derives from + **/ + public final Model model; + /** + * the world transform + **/ + public Matrix4 transform; + /** + * user definable value, which is passed to the shader. + */ + public Object userData; - /** Recursively searches the mode for the specified node. - * @param model The source {@link Model} - * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain - * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). - * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. */ - public SharedModel(final Model model, final String nodeId, boolean parentTransform, boolean mergeTransform) { - this(model, null, nodeId, true, parentTransform, mergeTransform); - } - - /** Recursively searches the mode for the specified node. - * @param model The source {@link Model} - * @param transform The {@link Matrix4} instance for this ModelInstance to reference or null to create a new matrix. - * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain - * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). - * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. */ - public SharedModel(final Model model, final Matrix4 transform, final String nodeId, boolean parentTransform, boolean mergeTransform) { - this(model, transform, nodeId, true, parentTransform, mergeTransform); - } - - /** @param model The source {@link Model} - * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain - * @param recursive True to recursively search the Model's node tree, false to only search for a root node - * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). - * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. */ - public SharedModel(final Model model, final String nodeId, boolean recursive, boolean parentTransform, boolean mergeTransform) { - this(model, null, nodeId, recursive, parentTransform, mergeTransform); - } - - /** @param model The source {@link Model} - * @param transform The {@link Matrix4} instance for this ModelInstance to reference or null to create a new matrix. - * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain - * @param recursive True to recursively search the Model's node tree, false to only search for a root node - * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). - * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. */ - public SharedModel(final Model model, final Matrix4 transform, final String nodeId, boolean recursive, boolean parentTransform, boolean mergeTransform) { - this.model = model; - this.transform = transform == null ? new Matrix4() : transform; - nodePartBones.clear(); - Node copy, node = model.getNode(nodeId, recursive); - this.nodes.add(copy = copyNode(node)); - if (mergeTransform) { - this.transform.mul(parentTransform ? node.globalTransform : node.localTransform); - copy.translation.set(0,0,0); - copy.rotation.idt(); - copy.scale.set(1,1,1); - } else if (parentTransform && copy.hasParent()) - this.transform.mul(node.getParent().globalTransform); - setBones(); - copyAnimations(model.animations); - calculateTransforms(); - } - - /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ - public SharedModel(final Model model, final String... rootNodeIds) { - this(model, null, rootNodeIds); - } - - /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ - public SharedModel(final Model model, final Matrix4 transform, final String... rootNodeIds) { - this.model = model; - this.transform = transform == null ? new Matrix4() : transform; - if (rootNodeIds == null) - copyNodes(model.nodes); - else - copyNodes(model.nodes, rootNodeIds); - copyAnimations(model.animations); - calculateTransforms(); - } - - /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ - public SharedModel(final Model model, final Array rootNodeIds) { - this(model, null, rootNodeIds); - } - - /** Constructs a new ModelInstance with only the specified nodes and materials of the given model. */ - public SharedModel(final Model model, final Matrix4 transform, final Array rootNodeIds) { - this.model = model; - this.transform = transform == null ? new Matrix4() : transform; - copyNodes(model.nodes, rootNodeIds); - copyAnimations(model.animations); - calculateTransforms(); - } - - /** Constructs a new ModelInstance at the specified position. */ - public SharedModel(final Model model, Vector3 position) { - this(model); - this.transform.setToTranslation(position); - } - - /** Constructs a new ModelInstance at the specified position. */ - public SharedModel(final Model model, float x, float y, float z) { - this(model); - this.transform.setToTranslation(x, y, z); - } - - /** Constructs a new ModelInstance with the specified transform. */ - public SharedModel(final Model model, Matrix4 transform) { - this(model, transform, (String[])null); - } - - /** Constructs a new ModelInstance which is an copy of the specified ModelInstance. */ - public SharedModel(SharedModel copyFrom) { - this(copyFrom, copyFrom.transform.cpy()); - } - - /** Constructs a new ModelInstance which is an copy of the specified ModelInstance. */ - public SharedModel(SharedModel copyFrom, final Matrix4 transform) { - this.model = copyFrom.model; - this.transform = transform == null ? new Matrix4() : transform; - copyNodes(copyFrom.nodes); - copyAnimations(copyFrom.animations); - calculateTransforms(); - } - - /** @return A newly created ModelInstance which is a copy of this ModelInstance */ - public SharedModel copy() { - return new SharedModel(this); - } + /** + * Constructs a new ModelInstance with all nodes and materials of the given model. + * + * @param model The {@link Model} to create an instance of. + */ + public SharedModel(final Model model) { + this(model, (String[]) null); + } + + /** + * @param model The source {@link Model} + * @param nodeId The ID of the root {@link Node} of the {@link Model} for the instance to contain + * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. + */ + public SharedModel(final Model model, final String nodeId, boolean mergeTransform) { + this(model, null, nodeId, false, false, mergeTransform); + } + + /** + * @param model The source {@link Model} + * @param transform The {@link Matrix4} instance for this ModelInstance to reference or null to create a new matrix. + * @param nodeId The ID of the root {@link Node} of the {@link Model} for the instance to contain + * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. + */ + public SharedModel(final Model model, final Matrix4 transform, final String nodeId, boolean mergeTransform) { + this(model, transform, nodeId, false, false, mergeTransform); + } + + /** + * Recursively searches the mode for the specified node. + * + * @param model The source {@link Model} + * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain + * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). + * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. + */ + public SharedModel(final Model model, final String nodeId, boolean parentTransform, boolean mergeTransform) { + this(model, null, nodeId, true, parentTransform, mergeTransform); + } + + /** + * Recursively searches the mode for the specified node. + * + * @param model The source {@link Model} + * @param transform The {@link Matrix4} instance for this ModelInstance to reference or null to create a new matrix. + * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain + * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). + * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. + */ + public SharedModel(final Model model, final Matrix4 transform, final String nodeId, boolean parentTransform, boolean mergeTransform) { + this(model, transform, nodeId, true, parentTransform, mergeTransform); + } + + /** + * @param model The source {@link Model} + * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain + * @param recursive True to recursively search the Model's node tree, false to only search for a root node + * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). + * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. + */ + public SharedModel(final Model model, final String nodeId, boolean recursive, boolean parentTransform, boolean mergeTransform) { + this(model, null, nodeId, recursive, parentTransform, mergeTransform); + } + + /** + * @param model The source {@link Model} + * @param transform The {@link Matrix4} instance for this ModelInstance to reference or null to create a new matrix. + * @param nodeId The ID of the {@link Node} within the {@link Model} for the instance to contain + * @param recursive True to recursively search the Model's node tree, false to only search for a root node + * @param parentTransform True to apply the parent's node transform to the instance (only applicable if recursive is true). + * @param mergeTransform True to apply the source node transform to the instance transform, resetting the node transform. + */ + public SharedModel(final Model model, final Matrix4 transform, final String nodeId, boolean recursive, boolean parentTransform, boolean mergeTransform) { + this.model = model; + this.transform = transform == null ? new Matrix4() : transform; + nodePartBones.clear(); + Node copy, node = model.getNode(nodeId, recursive); + this.nodes.add(copy = copyNode(node)); + if (mergeTransform) { + this.transform.mul(parentTransform ? node.globalTransform : node.localTransform); + copy.translation.set(0, 0, 0); + copy.rotation.idt(); + copy.scale.set(1, 1, 1); + } else if (parentTransform && copy.hasParent()) + this.transform.mul(node.getParent().globalTransform); + setBones(); + copyAnimations(model.animations); + calculateTransforms(); + } + + /** + * Constructs a new ModelInstance with only the specified nodes and materials of the given model. + */ + public SharedModel(final Model model, final String... rootNodeIds) { + this(model, null, rootNodeIds); + } + + /** + * Constructs a new ModelInstance with only the specified nodes and materials of the given model. + */ + public SharedModel(final Model model, final Matrix4 transform, final String... rootNodeIds) { + this.model = model; + this.transform = transform == null ? new Matrix4() : transform; + if (rootNodeIds == null) + copyNodes(model.nodes); + else + copyNodes(model.nodes, rootNodeIds); + copyAnimations(model.animations); + calculateTransforms(); + } + + /** + * Constructs a new ModelInstance with only the specified nodes and materials of the given model. + */ + public SharedModel(final Model model, final Array rootNodeIds) { + this(model, null, rootNodeIds); + } + + /** + * Constructs a new ModelInstance with only the specified nodes and materials of the given model. + */ + public SharedModel(final Model model, final Matrix4 transform, final Array rootNodeIds) { + this.model = model; + this.transform = transform == null ? new Matrix4() : transform; + copyNodes(model.nodes, rootNodeIds); + copyAnimations(model.animations); + calculateTransforms(); + } + + /** + * Constructs a new ModelInstance at the specified position. + */ + public SharedModel(final Model model, Vector3 position) { + this(model); + this.transform.setToTranslation(position); + } + + /** + * Constructs a new ModelInstance at the specified position. + */ + public SharedModel(final Model model, float x, float y, float z) { + this(model); + this.transform.setToTranslation(x, y, z); + } + + /** + * Constructs a new ModelInstance with the specified transform. + */ + public SharedModel(final Model model, Matrix4 transform) { + this(model, transform, (String[]) null); + } + + /** + * Constructs a new ModelInstance which is an copy of the specified ModelInstance. + */ + public SharedModel(SharedModel copyFrom) { + this(copyFrom, copyFrom.transform.cpy()); + } + + /** + * Constructs a new ModelInstance which is an copy of the specified ModelInstance. + */ + public SharedModel(SharedModel copyFrom, final Matrix4 transform) { + this.model = copyFrom.model; + this.transform = transform == null ? new Matrix4() : transform; + copyNodes(copyFrom.nodes); + copyAnimations(copyFrom.animations); + calculateTransforms(); + } + + /** + * @return A newly created ModelInstance which is a copy of this ModelInstance + */ + public SharedModel copy() { + return new SharedModel(this); + } + + private ObjectMap> nodePartBones = new ObjectMap>(); + + private void copyNodes(Array nodes) { + nodePartBones.clear(); + for (int i = 0, n = nodes.size; i < n; ++i) { + final Node node = nodes.get(i); + this.nodes.add(copyNode(node)); + } + setBones(); + } + + private void copyNodes(Array nodes, final String... nodeIds) { + nodePartBones.clear(); + for (int i = 0, n = nodes.size; i < n; ++i) { + final Node node = nodes.get(i); + for (final String nodeId : nodeIds) { + if (nodeId.equals(node.id)) { + this.nodes.add(copyNode(node)); + break; + } + } + } + setBones(); + } + + private void copyNodes(Array nodes, final Array nodeIds) { + nodePartBones.clear(); + for (int i = 0, n = nodes.size; i < n; ++i) { + final Node node = nodes.get(i); + for (final String nodeId : nodeIds) { + if (nodeId.equals(node.id)) { + this.nodes.add(copyNode(node)); + break; + } + } + } + setBones(); + } + + private void setBones() { + for (ObjectMap.Entry> e : nodePartBones.entries()) { + if (e.key.invBoneBindTransforms == null) + e.key.invBoneBindTransforms = new ArrayMap(true, e.value.size, Node.class, Matrix4.class); + e.key.invBoneBindTransforms.clear(); + + for (final ObjectMap.Entry b : e.value.entries()) + e.key.invBoneBindTransforms.put(getNode(b.key.id), b.value); // Share the inv bind matrix with the model + + e.key.bones = new Matrix4[e.value.size]; + for (int i = 0; i < e.key.bones.length; i++) + e.key.bones[i] = new Matrix4(); + } + } + + private Node copyNode(Node node) { + Node copy = new Node(); + copy.id = node.id; + copy.inheritTransform = node.inheritTransform; + copy.translation.set(node.translation); + copy.rotation.set(node.rotation); + copy.scale.set(node.scale); + copy.localTransform.set(node.localTransform); + copy.globalTransform.set(node.globalTransform); + for (NodePart nodePart : node.parts) { + copy.parts.add(copyNodePart(nodePart)); + } + for (Node child : node.getChildren()) { + copy.addChild(copyNode(child)); + } + return copy; + } + + private NodePart copyNodePart(NodePart nodePart) { + NodePart copy = new NodePart(); + copy.meshPart = new MeshPart(); + copy.meshPart.id = nodePart.meshPart.id; + copy.meshPart.offset = nodePart.meshPart.offset; + copy.meshPart.size = nodePart.meshPart.size; + copy.meshPart.primitiveType = nodePart.meshPart.primitiveType; + copy.meshPart.mesh = nodePart.meshPart.mesh; + + if (nodePart.invBoneBindTransforms != null) + nodePartBones.put(copy, nodePart.invBoneBindTransforms); - private ObjectMap> nodePartBones = new ObjectMap>(); - private void copyNodes (Array nodes) { - nodePartBones.clear(); - for(int i = 0, n = nodes.size; i nodes, final String... nodeIds) { - nodePartBones.clear(); - for(int i = 0, n = nodes.size; i nodes, final Array nodeIds) { - nodePartBones.clear(); - for(int i = 0, n = nodes.size; i> e : nodePartBones.entries()) { - if (e.key.invBoneBindTransforms == null) - e.key.invBoneBindTransforms = new ArrayMap(true, e.value.size, Node.class, Matrix4.class); - e.key.invBoneBindTransforms.clear(); - - for (final ObjectMap.Entry b : e.value.entries()) - e.key.invBoneBindTransforms.put(getNode(b.key.id), b.value); // Share the inv bind matrix with the model - - e.key.bones = new Matrix4[e.value.size]; - for (int i = 0; i < e.key.bones.length; i++) - e.key.bones[i] = new Matrix4(); - } - } - - private Node copyNode(Node node) { - Node copy = new Node(); - copy.id = node.id; - copy.inheritTransform = node.inheritTransform; - copy.translation.set(node.translation); - copy.rotation.set(node.rotation); - copy.scale.set(node.scale); - copy.localTransform.set(node.localTransform); - copy.globalTransform.set(node.globalTransform); - for(NodePart nodePart: node.parts) { - copy.parts.add(copyNodePart(nodePart)); - } - for(Node child: node.getChildren()) { - copy.addChild(copyNode(child)); - } - return copy; - } - - private NodePart copyNodePart (NodePart nodePart) { - NodePart copy = new NodePart(); - copy.meshPart = new MeshPart(); - copy.meshPart.id = nodePart.meshPart.id; - copy.meshPart.offset = nodePart.meshPart.offset; - copy.meshPart.size = nodePart.meshPart.size; - copy.meshPart.primitiveType = nodePart.meshPart.primitiveType; - copy.meshPart.mesh = nodePart.meshPart.mesh; - - if (nodePart.invBoneBindTransforms != null) - nodePartBones.put(copy, nodePart.invBoneBindTransforms); - // final int index = materials.indexOf(nodePart.material, false); // if (index < 0) // materials.add(copy.material = nodePart.material.copy()); // else // copy.material = materials.get(index); // - copy.material = nodePart.material; - - return copy; - } - - private void copyAnimations (final Iterable source) { - for (final Animation anim : source) { - Animation animation = new Animation(); - animation.id = anim.id; - for (final NodeAnimation nanim : anim.nodeAnimations) { - final Node node = getNode(nanim.node.id); - if (node == null) - continue; - NodeAnimation nodeAnim = new NodeAnimation(); - nodeAnim.node = node; - if (nanim.rotation != null) { - nodeAnim.rotation = new Array>(); - nodeAnim.rotation.ensureCapacity(nanim.rotation.size); - for (final NodeKeyframe kf : nanim.rotation) { - if (kf.keytime > animation.duration) - animation.duration = kf.keytime; - nodeAnim.rotation.add(new NodeKeyframe(kf.keytime, new Quaternion(kf.value == null ? node.rotation : kf.value))); - } - } - if (nanim.scaling != null) { - nodeAnim.scaling = new Array>(); - nodeAnim.scaling.ensureCapacity(nanim.scaling.size); - for (final NodeKeyframe kf : nanim.scaling) { - if (kf.keytime > animation.duration) - animation.duration = kf.keytime; - nodeAnim.scaling.add(new NodeKeyframe(kf.keytime, new Vector3(kf.value == null ? node.scale : kf.value))); - } - } - if (nanim.translation != null) { - nodeAnim.translation = new Array>(); - nodeAnim.translation.ensureCapacity(nanim.translation.size); - for (final NodeKeyframe kf : nanim.translation) { - if (kf.keytime > animation.duration) - animation.duration = kf.keytime; - nodeAnim.translation.add(new NodeKeyframe(kf.keytime, new Vector3(kf.value == null ? node.translation : kf.value))); - } - } - if ((nodeAnim.rotation != null && nodeAnim.rotation.size > 0) - || (nodeAnim.scaling != null && nodeAnim.scaling.size > 0) - || (nodeAnim.translation != null && nodeAnim.translation.size > 0)) - animation.nodeAnimations.add(nodeAnim); - } - if (animation.nodeAnimations.size > 0) - animations.add(animation); - } - } - - - /** - * Traverses the Node hierarchy and collects {@link Renderable} instances for every - * node with a graphical representation. Renderables are obtained from the provided - * pool. The resulting array can be rendered via a {@link ModelBatch}. - * - * @param renderables the output array - * @param pool the pool to obtain Renderables from - */ - public void getRenderables(Array renderables, Pool pool) { - for(Node node: nodes) { - getRenderables(node, renderables, pool); - } - } + copy.material = nodePart.material; - /** @return The renderable of the first node's first part. */ - public Renderable getRenderable(final Renderable out) { - return getRenderable(out, nodes.get(0)); - } - - /** @return The renderable of the node's first part. */ - public Renderable getRenderable(final Renderable out, final Node node) { - return getRenderable(out, node, node.parts.get(0)); - } - - public Renderable getRenderable(final Renderable out, final Node node, final NodePart nodePart) { - nodePart.setRenderable(out); - if (nodePart.bones == null && transform != null) - out.worldTransform.set(transform).mul(node.globalTransform); - else if (transform != null) - out.worldTransform.set(transform); - else - out.worldTransform.idt(); - out.userData = userData; - return out; - } - - protected void getRenderables(Node node, Array renderables, Pool pool) { - if(node.parts.size > 0) { - for(NodePart nodePart: node.parts) { - renderables.add(getRenderable(pool.obtain(), node, nodePart)); - } - } - - for(Node child: node.getChildren()) { - getRenderables(child, renderables, pool); - } - } - - /** Calculates the local and world transform of all {@link Node} instances in this model, recursively. - * First each {@link Node#localTransform} transform is calculated based on the translation, rotation and - * scale of each Node. Then each {@link Node#calculateWorldTransform()} - * is calculated, based on the parent's world transform and the local transform of each Node. - * Finally, the animation bone matrices are updated accordingly.

- * - * This method can be used to recalculate all transforms if any of the Node's local properties (translation, rotation, scale) - * was modified. - */ - public void calculateTransforms() { - final int n = nodes.size; - for(int i = 0; i < n; i++) { - nodes.get(i).calculateTransforms(true); - } - for(int i = 0; i < n; i++) { - nodes.get(i).calculateBoneTransforms(true); - } - } - - /** Calculate the bounding box of this model instance. - * This is a potential slow operation, it is advised to cache the result. - * @param out the {@link BoundingBox} that will be set with the bounds. - * @return the out parameter for chaining */ - public BoundingBox calculateBoundingBox(final BoundingBox out) { - out.inf(); - return extendBoundingBox(out); - } - - /** Extends the bounding box with the bounds of this model instance. - * This is a potential slow operation, it is advised to cache the result. - * @param out the {@link BoundingBox} that will be extended with the bounds. - * @return the out parameter for chaining */ - public BoundingBox extendBoundingBox(final BoundingBox out) { - final int n = nodes.size; - for(int i = 0; i < n; i++) - nodes.get(i).extendBoundingBox(out); - return out; - } + return copy; + } + + private void copyAnimations(final Iterable source) { + for (final Animation anim : source) { + Animation animation = new Animation(); + animation.id = anim.id; + for (final NodeAnimation nanim : anim.nodeAnimations) { + final Node node = getNode(nanim.node.id); + if (node == null) + continue; + NodeAnimation nodeAnim = new NodeAnimation(); + nodeAnim.node = node; + if (nanim.rotation != null) { + nodeAnim.rotation = new Array>(); + nodeAnim.rotation.ensureCapacity(nanim.rotation.size); + for (final NodeKeyframe kf : nanim.rotation) { + if (kf.keytime > animation.duration) + animation.duration = kf.keytime; + nodeAnim.rotation.add(new NodeKeyframe(kf.keytime, new Quaternion(kf.value == null ? node.rotation : kf.value))); + } + } + if (nanim.scaling != null) { + nodeAnim.scaling = new Array>(); + nodeAnim.scaling.ensureCapacity(nanim.scaling.size); + for (final NodeKeyframe kf : nanim.scaling) { + if (kf.keytime > animation.duration) + animation.duration = kf.keytime; + nodeAnim.scaling.add(new NodeKeyframe(kf.keytime, new Vector3(kf.value == null ? node.scale : kf.value))); + } + } + if (nanim.translation != null) { + nodeAnim.translation = new Array>(); + nodeAnim.translation.ensureCapacity(nanim.translation.size); + for (final NodeKeyframe kf : nanim.translation) { + if (kf.keytime > animation.duration) + animation.duration = kf.keytime; + nodeAnim.translation.add(new NodeKeyframe(kf.keytime, new Vector3(kf.value == null ? node.translation : kf.value))); + } + } + if ((nodeAnim.rotation != null && nodeAnim.rotation.size > 0) + || (nodeAnim.scaling != null && nodeAnim.scaling.size > 0) + || (nodeAnim.translation != null && nodeAnim.translation.size > 0)) + animation.nodeAnimations.add(nodeAnim); + } + if (animation.nodeAnimations.size > 0) + animations.add(animation); + } + } + + + /** + * Traverses the Node hierarchy and collects {@link Renderable} instances for every + * node with a graphical representation. Renderables are obtained from the provided + * pool. The resulting array can be rendered via a {@link ModelBatch}. + * + * @param renderables the output array + * @param pool the pool to obtain Renderables from + */ + public void getRenderables(Array renderables, Pool pool) { + for (Node node : nodes) { + getRenderables(node, renderables, pool); + } + } + + /** + * @return The renderable of the first node's first part. + */ + public Renderable getRenderable(final Renderable out) { + return getRenderable(out, nodes.get(0)); + } + + /** + * @return The renderable of the node's first part. + */ + public Renderable getRenderable(final Renderable out, final Node node) { + return getRenderable(out, node, node.parts.get(0)); + } + + public Renderable getRenderable(final Renderable out, final Node node, final NodePart nodePart) { + nodePart.setRenderable(out); + if (nodePart.bones == null && transform != null) + out.worldTransform.set(transform).mul(node.globalTransform); + else if (transform != null) + out.worldTransform.set(transform); + else + out.worldTransform.idt(); + out.userData = userData; + return out; + } + + protected void getRenderables(Node node, Array renderables, Pool pool) { + if (node.parts.size > 0) { + for (NodePart nodePart : node.parts) { + renderables.add(getRenderable(pool.obtain(), node, nodePart)); + } + } + + for (Node child : node.getChildren()) { + getRenderables(child, renderables, pool); + } + } + + /** + * Calculates the local and world transform of all {@link Node} instances in this model, recursively. + * First each {@link Node#localTransform} transform is calculated based on the translation, rotation and + * scale of each Node. Then each {@link Node#calculateWorldTransform()} + * is calculated, based on the parent's world transform and the local transform of each Node. + * Finally, the animation bone matrices are updated accordingly.

+ *

+ * This method can be used to recalculate all transforms if any of the Node's local properties (translation, rotation, scale) + * was modified. + */ + public void calculateTransforms() { + final int n = nodes.size; + for (int i = 0; i < n; i++) { + nodes.get(i).calculateTransforms(true); + } + for (int i = 0; i < n; i++) { + nodes.get(i).calculateBoneTransforms(true); + } + } + + /** + * Calculate the bounding box of this model instance. + * This is a potential slow operation, it is advised to cache the result. + * + * @param out the {@link BoundingBox} that will be set with the bounds. + * @return the out parameter for chaining + */ + public BoundingBox calculateBoundingBox(final BoundingBox out) { + out.inf(); + return extendBoundingBox(out); + } + + /** + * Extends the bounding box with the bounds of this model instance. + * This is a potential slow operation, it is advised to cache the result. + * + * @param out the {@link BoundingBox} that will be extended with the bounds. + * @return the out parameter for chaining + */ + public BoundingBox extendBoundingBox(final BoundingBox out) { + final int n = nodes.size; + for (int i = 0; i < n; i++) + nodes.get(i).extendBoundingBox(out); + return out; + } + + /** + * @param id The ID of the animation to fetch (case sensitive). + * @return The {@link Animation} with the specified id, or null if not available. + */ + public Animation getAnimation(final String id) { + return getAnimation(id, true); + } + + /** + * @param id The ID of the animation to fetch. + * @param ignoreCase whether to use case sensitivity when comparing the animation id. + * @return The {@link Animation} with the specified id, or null if not available. + */ + public Animation getAnimation(final String id, boolean ignoreCase) { + final int n = animations.size; + Animation animation; + if (ignoreCase) { + for (int i = 0; i < n; i++) + if ((animation = animations.get(i)).id.equalsIgnoreCase(id)) + return animation; + } else { + for (int i = 0; i < n; i++) + if ((animation = animations.get(i)).id.equals(id)) + return animation; + } + return null; + } - /** @param id The ID of the animation to fetch (case sensitive). - * @return The {@link Animation} with the specified id, or null if not available. */ - public Animation getAnimation(final String id) { - return getAnimation(id, true); - } - - /** @param id The ID of the animation to fetch. - * @param ignoreCase whether to use case sensitivity when comparing the animation id. - * @return The {@link Animation} with the specified id, or null if not available. */ - public Animation getAnimation(final String id, boolean ignoreCase) { - final int n = animations.size; - Animation animation; - if (ignoreCase) { - for (int i = 0; i < n; i++) - if ((animation = animations.get(i)).id.equalsIgnoreCase(id)) - return animation; - } else { - for (int i = 0; i < n; i++) - if ((animation = animations.get(i)).id.equals(id)) - return animation; - } - return null; - } - // /** @param id The ID of the material to fetch. // * @return The {@link Material} with the specified id, or null if not available. */ // public Material getMaterial(final String id) { @@ -457,25 +525,31 @@ public class SharedModel implements RenderableProvider { // } // return null; // } - - /** @param id The ID of the node to fetch. - * @return The {@link Node} with the specified id, or null if not found. */ - public Node getNode(final String id) { - return getNode(id, true); - } - - /** @param id The ID of the node to fetch. - * @param recursive false to fetch a root node only, true to search the entire node tree for the specified node. - * @return The {@link Node} with the specified id, or null if not found. */ - public Node getNode(final String id, boolean recursive) { - return getNode(id, recursive, false); - } - - /** @param id The ID of the node to fetch. - * @param recursive false to fetch a root node only, true to search the entire node tree for the specified node. - * @param ignoreCase whether to use case sensitivity when comparing the node id. - * @return The {@link Node} with the specified id, or null if not found. */ - public Node getNode(final String id, boolean recursive, boolean ignoreCase) { - return Node.getNode(nodes, id, recursive, ignoreCase); - } + + /** + * @param id The ID of the node to fetch. + * @return The {@link Node} with the specified id, or null if not found. + */ + public Node getNode(final String id) { + return getNode(id, true); + } + + /** + * @param id The ID of the node to fetch. + * @param recursive false to fetch a root node only, true to search the entire node tree for the specified node. + * @return The {@link Node} with the specified id, or null if not found. + */ + public Node getNode(final String id, boolean recursive) { + return getNode(id, recursive, false); + } + + /** + * @param id The ID of the node to fetch. + * @param recursive false to fetch a root node only, true to search the entire node tree for the specified node. + * @param ignoreCase whether to use case sensitivity when comparing the node id. + * @return The {@link Node} with the specified id, or null if not found. + */ + public Node getNode(final String id, boolean recursive, boolean ignoreCase) { + return Node.getNode(nodes, id, recursive, ignoreCase); + } } diff --git a/vtm-playground/src/org/oscim/test/jeo/LayerTest.java b/vtm-playground/src/org/oscim/test/jeo/LayerTest.java index 079d0b96..01fefbb7 100644 --- a/vtm-playground/src/org/oscim/test/jeo/LayerTest.java +++ b/vtm-playground/src/org/oscim/test/jeo/LayerTest.java @@ -16,15 +16,8 @@ */ package org.oscim.test.jeo; -import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; - -import org.jeo.vector.VectorDataset; import org.jeo.map.Style; +import org.jeo.vector.VectorDataset; import org.oscim.gdx.GdxMap; import org.oscim.gdx.GdxMapApp; import org.oscim.layers.JeoVectorLayer; @@ -33,54 +26,61 @@ import org.oscim.layers.TileGridLayer; import org.oscim.layers.tile.bitmap.BitmapTileLayer; import org.oscim.test.JeoTest; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; + +import static org.oscim.tiling.source.bitmap.DefaultSources.STAMEN_TONER; + public class LayerTest extends GdxMap { - String PATH = "https://gist.github.com/anonymous/8960337/raw/overpass.geojson"; + String PATH = "https://gist.github.com/anonymous/8960337/raw/overpass.geojson"; - OSMIndoorLayer mIndoorLayer; + OSMIndoorLayer mIndoorLayer; - @Override - public void createLayers() { - mMap.setBaseMap(new BitmapTileLayer(mMap, STAMEN_TONER.build())); - mMap.layers().add(new TileGridLayer(mMap)); + @Override + public void createLayers() { + mMap.setBaseMap(new BitmapTileLayer(mMap, STAMEN_TONER.build())); + mMap.layers().add(new TileGridLayer(mMap)); - mMap.addTask(new Runnable() { - @Override - public void run() { - try { - URL url = new URL(PATH); - URLConnection conn = url.openConnection(); - InputStream is = conn.getInputStream(); + mMap.addTask(new Runnable() { + @Override + public void run() { + try { + URL url = new URL(PATH); + URLConnection conn = url.openConnection(); + InputStream is = conn.getInputStream(); - VectorDataset data = JeoTest.readGeoJson(is); - Style style = JeoTest.getStyle(); - mIndoorLayer = new OSMIndoorLayer(mMap, data, style); - mIndoorLayer.activeLevels[0] = true; - mIndoorLayer.activeLevels[1] = true; - mIndoorLayer.activeLevels[2] = true; - mIndoorLayer.activeLevels[3] = true; + VectorDataset data = JeoTest.readGeoJson(is); + Style style = JeoTest.getStyle(); + mIndoorLayer = new OSMIndoorLayer(mMap, data, style); + mIndoorLayer.activeLevels[0] = true; + mIndoorLayer.activeLevels[1] = true; + mIndoorLayer.activeLevels[2] = true; + mIndoorLayer.activeLevels[3] = true; - mMap.layers().add(new JeoVectorLayer(mMap, data, style)); - mMap.layers().add(mIndoorLayer); + mMap.layers().add(new JeoVectorLayer(mMap, data, style)); + mMap.layers().add(mIndoorLayer); - mMap.updateMap(true); + mMap.updateMap(true); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); - mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); + mMap.setMapPosition(53.5620092, 9.9866457, 1 << 16); - //VectorDataset data = (VectorDataset) JeoTest.getJsonData("states.json", true); - //Style style = JeoTest.getStyle(); - //mMap.layers().add(new JeoVectorLayer(mMap, data, style)); + //VectorDataset data = (VectorDataset) JeoTest.getJsonData("states.json", true); + //Style style = JeoTest.getStyle(); + //mMap.layers().add(new JeoVectorLayer(mMap, data, style)); - } + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new LayerTest(), null, 256); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new LayerTest(), null, 256); + } } diff --git a/vtm-playground/src/org/oscim/test/jeo/ThemeTest.java b/vtm-playground/src/org/oscim/test/jeo/ThemeTest.java index 35d45fdc..3d65b2d5 100644 --- a/vtm-playground/src/org/oscim/test/jeo/ThemeTest.java +++ b/vtm-playground/src/org/oscim/test/jeo/ThemeTest.java @@ -10,25 +10,25 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; public class ThemeTest extends GdxMapApp { - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new ThemeTest(), null, 256); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new ThemeTest(), null, 256); + } - @Override - public void createLayers() { - UrlTileSource ts = new OSciMap4TileSource(); + @Override + public void createLayers() { + UrlTileSource ts = new OSciMap4TileSource(); - VectorTileLayer l = mMap.setBaseMap(ts); + VectorTileLayer l = mMap.setBaseMap(ts); - l.setRenderTheme(new RenderTheme()); + l.setRenderTheme(new RenderTheme()); - MapRenderer.setBackgroundColor(0xffcccccc); + MapRenderer.setBackgroundColor(0xffcccccc); - // mMap.getLayers().add(new LabelLayer(mMap, - // mMapLayer.getTileLayer())); - // mMap.getLayers().add(new JeoMapLayer(mMap)); + // mMap.getLayers().add(new LabelLayer(mMap, + // mMapLayer.getTileLayer())); + // mMap.getLayers().add(new JeoMapLayer(mMap)); - mMap.layers().add(new TileGridLayer(mMap)); - } + mMap.layers().add(new TileGridLayer(mMap)); + } } diff --git a/vtm-playground/src/org/oscim/test/renderer/AtlasTest.java b/vtm-playground/src/org/oscim/test/renderer/AtlasTest.java index 81707453..b37261a6 100644 --- a/vtm-playground/src/org/oscim/test/renderer/AtlasTest.java +++ b/vtm-playground/src/org/oscim/test/renderer/AtlasTest.java @@ -1,7 +1,5 @@ package org.oscim.test.renderer; -import java.util.Arrays; - import org.oscim.backend.canvas.Color; import org.oscim.backend.canvas.Paint.Cap; import org.oscim.gdx.GdxMap; @@ -20,123 +18,125 @@ import org.oscim.theme.styles.TextStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Arrays; + public class AtlasTest extends GdxMap { - @Override - protected void createLayers() { - mMap.setMapPosition(0, 0, 1 << 4); - mMap.layers().add(new GenericLayer(mMap, new AtlasRenderLayer())); - } + @Override + protected void createLayers() { + mMap.setMapPosition(0, 0, 1 << 4); + mMap.layers().add(new GenericLayer(mMap, new AtlasRenderLayer())); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new AtlasTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new AtlasTest(), null, 400); + } - static class AtlasRenderLayer extends BucketRenderer { + static class AtlasRenderLayer extends BucketRenderer { - Logger log = LoggerFactory.getLogger(AtlasRenderLayer.class); + Logger log = LoggerFactory.getLogger(AtlasRenderLayer.class); - public AtlasRenderLayer() { + public AtlasRenderLayer() { - TextureAtlas mAtlas = TextureAtlas.create(2048, 2048, 1); + TextureAtlas mAtlas = TextureAtlas.create(2048, 2048, 1); - TextBucket tl = new TextBucket(); - TextStyle t = TextStyle.builder().fontSize(20).color(Color.BLACK).build(); - buckets.set(tl); + TextBucket tl = new TextBucket(); + TextStyle t = TextStyle.builder().fontSize(20).color(Color.BLACK).build(); + buckets.set(tl); - LineBucket ll = buckets.getLineBucket(0); - ll.line = new LineStyle(Color.BLUE, 3, Cap.BUTT); - ll.scale = 1f; + LineBucket ll = buckets.getLineBucket(0); + ll.line = new LineStyle(Color.BLUE, 3, Cap.BUTT); + ll.scale = 1f; - LineBucket ll2 = buckets.getLineBucket(1); - ll2.line = new LineStyle(Color.RED, 3, Cap.BUTT); - ll2.scale = 1f; + LineBucket ll2 = buckets.getLineBucket(1); + ll2.line = new LineStyle(Color.RED, 3, Cap.BUTT); + ll2.scale = 1f; - LineBucket ll3 = buckets.getLineBucket(2); - ll3.line = new LineStyle(Color.GREEN, 3, Cap.BUTT); - ll3.scale = 1f; + LineBucket ll3 = buckets.getLineBucket(2); + ll3.line = new LineStyle(Color.GREEN, 3, Cap.BUTT); + ll3.scale = 1f; - float[] points = new float[10]; + float[] points = new float[10]; - for (int i = 0; i < 400; i++) { - int w = (int) (20 + Math.random() * 256); - int h = (int) (20 + Math.random() * 56); - Rect r = mAtlas.getRegion(w, h); - if (r == null) { - log.debug("no space left"); - continue; - } - r.x += 1; - r.y += 1; + for (int i = 0; i < 400; i++) { + int w = (int) (20 + Math.random() * 256); + int h = (int) (20 + Math.random() * 56); + Rect r = mAtlas.getRegion(w, h); + if (r == null) { + log.debug("no space left"); + continue; + } + r.x += 1; + r.y += 1; - points[0] = r.x; - points[1] = r.y; - points[2] = r.x + (r.w - 2); - points[3] = r.y; - points[4] = r.x + (r.w - 2); - points[5] = r.y + (r.h - 2); - points[6] = r.x; - points[7] = r.y + (r.h - 2); - points[8] = r.x; - points[9] = r.y; - ll.addLine(points, 10, false); + points[0] = r.x; + points[1] = r.y; + points[2] = r.x + (r.w - 2); + points[3] = r.y; + points[4] = r.x + (r.w - 2); + points[5] = r.y + (r.h - 2); + points[6] = r.x; + points[7] = r.y + (r.h - 2); + points[8] = r.x; + points[9] = r.y; + ll.addLine(points, 10, false); - r.x += 1; - r.y += 1; - points[0] = r.x; - points[1] = r.y; - points[2] = r.x + (w - 4); - points[3] = r.y; - points[4] = r.x + (w - 4); - points[5] = r.y + (h - 4); - points[6] = r.x; - points[7] = r.y + (h - 4); - points[8] = r.x; - points[9] = r.y; + r.x += 1; + r.y += 1; + points[0] = r.x; + points[1] = r.y; + points[2] = r.x + (w - 4); + points[3] = r.y; + points[4] = r.x + (w - 4); + points[5] = r.y + (h - 4); + points[6] = r.x; + points[7] = r.y + (h - 4); + points[8] = r.x; + points[9] = r.y; - log.debug("add region: " + Arrays.toString(points)); - ll2.addLine(points, 10, false); + log.debug("add region: " + Arrays.toString(points)); + ll2.addLine(points, 10, false); - TextItem ti = TextItem.pool.get(); - ti.set(r.x + r.w / 2, r.y + r.h / 2, "" + i, t); - ti.x1 = 0; - ti.y1 = 1; // (short) (size / 2); - ti.x2 = 1; // (short) size; - ti.y2 = 1; - tl.addText(ti); - } + TextItem ti = TextItem.pool.get(); + ti.set(r.x + r.w / 2, r.y + r.h / 2, "" + i, t); + ti.x1 = 0; + ti.y1 = 1; // (short) (size / 2); + ti.x2 = 1; // (short) size; + ti.y2 = 1; + tl.addText(ti); + } - for (Slot s = mAtlas.mSlots; s != null; s = s.next) { - points[0] = s.x; - points[1] = s.y; - points[2] = s.x + s.w; - points[3] = s.y; - points[4] = s.x + s.w; - points[5] = 2048; - points[6] = s.x; - points[7] = 2048; - points[8] = s.x; - points[9] = s.y; + for (Slot s = mAtlas.mSlots; s != null; s = s.next) { + points[0] = s.x; + points[1] = s.y; + points[2] = s.x + s.w; + points[3] = s.y; + points[4] = s.x + s.w; + points[5] = 2048; + points[6] = s.x; + points[7] = 2048; + points[8] = s.x; + points[9] = s.y; - ll3.addLine(points, 10, false); - } + ll3.addLine(points, 10, false); + } - tl.prepare(); - //tl.labels = TextItem.pool.releaseAll(tl.labels); - } + tl.prepare(); + //tl.labels = TextItem.pool.releaseAll(tl.labels); + } - boolean initial = true; + boolean initial = true; - @Override - public void update(GLViewport v) { + @Override + public void update(GLViewport v) { - if (initial) { - mMapPosition.copy(v.pos); - initial = false; + if (initial) { + mMapPosition.copy(v.pos); + initial = false; - compile(); - } - } - } + compile(); + } + } + } } diff --git a/vtm-playground/src/org/oscim/test/renderer/BezierTest.java b/vtm-playground/src/org/oscim/test/renderer/BezierTest.java index 0039d10f..663888b9 100644 --- a/vtm-playground/src/org/oscim/test/renderer/BezierTest.java +++ b/vtm-playground/src/org/oscim/test/renderer/BezierTest.java @@ -1,7 +1,5 @@ package org.oscim.test.renderer; -import java.util.List; - import org.oscim.backend.canvas.Color; import org.oscim.core.GeometryBuffer; import org.oscim.core.Point; @@ -14,75 +12,77 @@ import org.oscim.renderer.bucket.LineBucket; import org.oscim.theme.styles.LineStyle; import org.oscim.utils.geom.BezierPath; +import java.util.List; + public class BezierTest extends GdxMap { - @Override - protected void createLayers() { - mMap.layers().add(new GenericLayer(mMap, new BezierPathLayer())); - } + @Override + protected void createLayers() { + mMap.layers().add(new GenericLayer(mMap, new BezierPathLayer())); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new BezierTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new BezierTest(), null, 400); + } - static class BezierPathLayer extends BucketRenderer { + static class BezierPathLayer extends BucketRenderer { - public BezierPathLayer() { - mMapPosition.scale = 0; + public BezierPathLayer() { + mMapPosition.scale = 0; - GeometryBuffer g = new GeometryBuffer(100, 1); - g.startLine(); + GeometryBuffer g = new GeometryBuffer(100, 1); + g.startLine(); - Point[] pts = new Point[10]; - for (int i = 0; i < 10; i++) { - pts[i] = new Point(i * 3, (i * i) % 3 * 4); - pts[i].x *= 10; - pts[i].y *= 10; - // System.out.println(pts[i]); - g.addPoint(pts[i]); - } - LineBucket ll = buckets.addLineBucket(0, new LineStyle(Color.BLUE, 2f)); - ll.addLine(g); + Point[] pts = new Point[10]; + for (int i = 0; i < 10; i++) { + pts[i] = new Point(i * 3, (i * i) % 3 * 4); + pts[i].x *= 10; + pts[i].y *= 10; + // System.out.println(pts[i]); + g.addPoint(pts[i]); + } + LineBucket ll = buckets.addLineBucket(0, new LineStyle(Color.BLUE, 2f)); + ll.addLine(g); - List ctrl = BezierPath.cubicSplineControlPoints(pts, 0.1f); + List ctrl = BezierPath.cubicSplineControlPoints(pts, 0.1f); - g.clear(); - g.startLine(); - Point p0 = pts[0]; + g.clear(); + g.startLine(); + Point p0 = pts[0]; - for (int j = 1, k = 0; j < pts.length; j++) { - Point p1 = ctrl.get(k++); - Point p2 = ctrl.get(k++); - Point p3 = pts[j]; - System.out.println(">>> " + p1 + " " + p2); - for (int i = 0; i < 10; i++) { - double mu = (i / 10f); - Point p = BezierPath.cubicBezier(p0, p1, p2, p3, mu); - g.addPoint(p); - System.out.println(mu + " " + p); - } - p0 = p3; - } - ll = buckets.addLineBucket(1, new LineStyle(Color.CYAN, 2f)); - ll.addLine(g); + for (int j = 1, k = 0; j < pts.length; j++) { + Point p1 = ctrl.get(k++); + Point p2 = ctrl.get(k++); + Point p3 = pts[j]; + System.out.println(">>> " + p1 + " " + p2); + for (int i = 0; i < 10; i++) { + double mu = (i / 10f); + Point p = BezierPath.cubicBezier(p0, p1, p2, p3, mu); + g.addPoint(p); + System.out.println(mu + " " + p); + } + p0 = p3; + } + ll = buckets.addLineBucket(1, new LineStyle(Color.CYAN, 2f)); + ll.addLine(g); - } + } - public synchronized void clear() { - buckets.clear(); - setReady(false); - } + public synchronized void clear() { + buckets.clear(); + setReady(false); + } - @Override - public synchronized void update(GLViewport v) { + @Override + public synchronized void update(GLViewport v) { - if (mMapPosition.scale == 0) - mMapPosition.copy(v.pos); + if (mMapPosition.scale == 0) + mMapPosition.copy(v.pos); - if (!isReady()) { - compile(); - } - } - } + if (!isReady()) { + compile(); + } + } + } } diff --git a/vtm-playground/src/org/oscim/test/renderer/CustomRenderer.java b/vtm-playground/src/org/oscim/test/renderer/CustomRenderer.java index e932f700..a1b2f18b 100644 --- a/vtm-playground/src/org/oscim/test/renderer/CustomRenderer.java +++ b/vtm-playground/src/org/oscim/test/renderer/CustomRenderer.java @@ -16,12 +16,6 @@ */ package org.oscim.test.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; - import org.oscim.backend.GL; import org.oscim.core.MapPosition; import org.oscim.map.Map; @@ -31,6 +25,12 @@ import org.oscim.renderer.GLUtils; import org.oscim.renderer.GLViewport; import org.oscim.renderer.LayerRenderer; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import static org.oscim.backend.GLAdapter.gl; + /* * This is an example how to integrate custom OpenGL drawing routines as map overlay * @@ -40,127 +40,127 @@ import org.oscim.renderer.LayerRenderer; public class CustomRenderer extends LayerRenderer { - private final Map mMap; - private final MapPosition mMapPosition; + private final Map mMap; + private final MapPosition mMapPosition; - private int mProgramObject; - private int hVertexPosition; - private int hMatrixPosition; + private int mProgramObject; + private int hVertexPosition; + private int hMatrixPosition; - private FloatBuffer mVertices; - private final float[] mVerticesData = { - -200, -200, 1.0f, - 200, 200, 0, - -200, 200, 0.5f, - 200, -200, 0.5f, - }; - private boolean mInitialized; + private FloatBuffer mVertices; + private final float[] mVerticesData = { + -200, -200, 1.0f, + 200, 200, 0, + -200, 200, 0.5f, + 200, -200, 0.5f, + }; + private boolean mInitialized; - public CustomRenderer(Map map) { - mMap = map; - mMapPosition = new MapPosition(); - } + public CustomRenderer(Map map) { + mMap = map; + mMapPosition = new MapPosition(); + } - // ---------- everything below runs in GLRender Thread ---------- - @Override - public void update(GLViewport v) { - if (!mInitialized) { - if (!init()) - return; + // ---------- everything below runs in GLRender Thread ---------- + @Override + public void update(GLViewport v) { + if (!mInitialized) { + if (!init()) + return; - mInitialized = true; + mInitialized = true; - // fix current MapPosition - mMapPosition.copy(v.pos); + // fix current MapPosition + mMapPosition.copy(v.pos); - compile(); - } - } + compile(); + } + } - protected void compile() { - // modify mVerticesData and put in FloatBuffer + protected void compile() { + // modify mVerticesData and put in FloatBuffer - mVertices.clear(); - mVertices.put(mVerticesData); - mVertices.flip(); + mVertices.clear(); + mVertices.put(mVerticesData); + mVertices.flip(); - setReady(true); - } + setReady(true); + } - @Override - public void render(GLViewport v) { + @Override + public void render(GLViewport v) { - // Use the program object - GLState.useProgram(mProgramObject); + // Use the program object + GLState.useProgram(mProgramObject); - GLState.blend(true); - GLState.test(false, false); + GLState.blend(true); + GLState.test(false, false); - // unbind previously bound VBOs - gl.bindBuffer(GL.ARRAY_BUFFER, 0); + // unbind previously bound VBOs + gl.bindBuffer(GL.ARRAY_BUFFER, 0); - // Load the vertex data - //mVertices.position(0); - gl.vertexAttribPointer(hVertexPosition, 3, GL.FLOAT, false, 0, mVertices); - //mVertices.position(2); - //GL.vertexAttribPointer(hVertexPosition, 2, GL20.FLOAT, false, 4, mVertices); + // Load the vertex data + //mVertices.position(0); + gl.vertexAttribPointer(hVertexPosition, 3, GL.FLOAT, false, 0, mVertices); + //mVertices.position(2); + //GL.vertexAttribPointer(hVertexPosition, 2, GL20.FLOAT, false, 4, mVertices); - GLState.enableVertexArrays(hVertexPosition, -1); + GLState.enableVertexArrays(hVertexPosition, -1); /* apply view and projection matrices */ - // set mvp (tmp) matrix relative to mMapPosition - // i.e. fixed on the map + // set mvp (tmp) matrix relative to mMapPosition + // i.e. fixed on the map - float ratio = 1f / mMap.getWidth(); + float ratio = 1f / mMap.getWidth(); - v.mvp.setScale(ratio, ratio, 1); - v.mvp.multiplyLhs(v.proj); - v.mvp.setAsUniform(hMatrixPosition); + v.mvp.setScale(ratio, ratio, 1); + v.mvp.multiplyLhs(v.proj); + v.mvp.setAsUniform(hMatrixPosition); - // Draw the triangle - gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); + // Draw the triangle + gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); - GLUtils.checkGlError("..."); - } + GLUtils.checkGlError("..."); + } - private boolean init() { - // Load the vertex/fragment shaders - int programObject = GLShader.createProgram(vShaderStr, fShaderStr); + private boolean init() { + // Load the vertex/fragment shaders + int programObject = GLShader.createProgram(vShaderStr, fShaderStr); - if (programObject == 0) - return false; + if (programObject == 0) + return false; - // Handle for vertex position in shader - hVertexPosition = gl.getAttribLocation(programObject, "a_pos"); + // Handle for vertex position in shader + hVertexPosition = gl.getAttribLocation(programObject, "a_pos"); - hMatrixPosition = gl.getUniformLocation(programObject, "u_mvp"); + hMatrixPosition = gl.getUniformLocation(programObject, "u_mvp"); - // Store the program object - mProgramObject = programObject; + // Store the program object + mProgramObject = programObject; - mVertices = ByteBuffer.allocateDirect(mVerticesData.length * 4) - .order(ByteOrder.nativeOrder()).asFloatBuffer(); + mVertices = ByteBuffer.allocateDirect(mVerticesData.length * 4) + .order(ByteOrder.nativeOrder()).asFloatBuffer(); - return true; - } + return true; + } - private final static String vShaderStr = "" + - "precision mediump float;" - + "uniform mat4 u_mvp;" - + "attribute vec4 a_pos;" - + "varying float alpha;" - + "void main()" - + "{" - + " gl_Position = u_mvp * vec4(a_pos.xy, 0.0, 1.0);" - + " alpha = a_pos.z;" - + "}"; + private final static String vShaderStr = "" + + "precision mediump float;" + + "uniform mat4 u_mvp;" + + "attribute vec4 a_pos;" + + "varying float alpha;" + + "void main()" + + "{" + + " gl_Position = u_mvp * vec4(a_pos.xy, 0.0, 1.0);" + + " alpha = a_pos.z;" + + "}"; - private final static String fShaderStr = "" + - "precision mediump float;" - + "varying float alpha;" - + "void main()" - + "{" - + " gl_FragColor = vec4 (alpha, 1.0-alpha, 0.0, 0.7 );" - + "}"; + private final static String fShaderStr = "" + + "precision mediump float;" + + "varying float alpha;" + + "void main()" + + "{" + + " gl_FragColor = vec4 (alpha, 1.0-alpha, 0.0, 0.7 );" + + "}"; } diff --git a/vtm-playground/src/org/oscim/test/renderer/HexagonRenderTest.java b/vtm-playground/src/org/oscim/test/renderer/HexagonRenderTest.java index 3f92f3d0..a9c99d6f 100644 --- a/vtm-playground/src/org/oscim/test/renderer/HexagonRenderTest.java +++ b/vtm-playground/src/org/oscim/test/renderer/HexagonRenderTest.java @@ -1,9 +1,5 @@ package org.oscim.test.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.FloatBuffer; - import org.oscim.backend.GL; import org.oscim.backend.canvas.Color; import org.oscim.gdx.GdxMap; @@ -18,195 +14,199 @@ import org.oscim.renderer.GLViewport; import org.oscim.renderer.MapRenderer; import org.oscim.utils.FastMath; +import java.nio.FloatBuffer; + +import static org.oscim.backend.GLAdapter.gl; + public class HexagonRenderTest extends GdxMap { - @Override - protected void createLayers() { - mMap.setMapPosition(0, 0, 1 << 4); - mMap.layers().add(new GenericLayer(mMap, new HexagonRenderer())); - } + @Override + protected void createLayers() { + mMap.setMapPosition(0, 0, 1 << 4); + mMap.layers().add(new GenericLayer(mMap, new HexagonRenderer())); + } - public static void main(String[] args) { - GdxMapApp.init(); - GdxMapApp.run(new HexagonRenderTest(), null, 400); - } + public static void main(String[] args) { + GdxMapApp.init(); + GdxMapApp.run(new HexagonRenderTest(), null, 400); + } /* This is an example how to integrate custom OpenGL drawing routines as map - * overlay + * overlay * * based on chapter 2 from: * https://github.com/dalinaum/opengl-es-book-samples/tree/master/Android */ - static class HexagonRenderer extends BucketRenderer { + static class HexagonRenderer extends BucketRenderer { - private int mProgramObject; - private int hVertexPosition; - private int hMatrixPosition; - private int hColorPosition; - private int hCenterPosition; + private int mProgramObject; + private int hVertexPosition; + private int hMatrixPosition; + private int hColorPosition; + private int hCenterPosition; - //private FloatBuffer mVertices; - private boolean mInitialized; - private BufferObject mVBO; + //private FloatBuffer mVertices; + private boolean mInitialized; + private BufferObject mVBO; - int mZoom = -1; - float mCellScale = 60 * MapRenderer.COORD_SCALE; + int mZoom = -1; + float mCellScale = 60 * MapRenderer.COORD_SCALE; - @Override - public void update(GLViewport v) { - if (!mInitialized) { - if (!init()) { - return; - } - mInitialized = true; + @Override + public void update(GLViewport v) { + if (!mInitialized) { + if (!init()) { + return; + } + mInitialized = true; - compile(); - mMapPosition.copy(v.pos); - } + compile(); + mMapPosition.copy(v.pos); + } - //if (mZoom != v.pos.zoomLevel) { - // mMapPosition.copy(v.pos); - // mZoom = v.pos.zoomLevel; - //} - } + //if (mZoom != v.pos.zoomLevel) { + // mMapPosition.copy(v.pos); + // mZoom = v.pos.zoomLevel; + //} + } - @Override - protected void compile() { + @Override + protected void compile() { - float[] vertices = new float[12]; + float[] vertices = new float[12]; - for (int i = 0; i < 6; i++) { - vertices[i * 2 + 0] = (float) Math.cos(Math.PI * 2 * i / 6) * mCellScale; - vertices[i * 2 + 1] = (float) Math.sin(Math.PI * 2 * i / 6) * mCellScale; - } - FloatBuffer buf = MapRenderer.getFloatBuffer(12); - buf.put(vertices); + for (int i = 0; i < 6; i++) { + vertices[i * 2 + 0] = (float) Math.cos(Math.PI * 2 * i / 6) * mCellScale; + vertices[i * 2 + 1] = (float) Math.sin(Math.PI * 2 * i / 6) * mCellScale; + } + FloatBuffer buf = MapRenderer.getFloatBuffer(12); + buf.put(vertices); - mVBO = BufferObject.get(GL.ARRAY_BUFFER, 0); - mVBO.loadBufferData(buf.flip(), 12 * 4); + mVBO = BufferObject.get(GL.ARRAY_BUFFER, 0); + mVBO.loadBufferData(buf.flip(), 12 * 4); - setReady(true); - } + setReady(true); + } - @Override - public void render(GLViewport v) { + @Override + public void render(GLViewport v) { - // Use the program object - GLState.useProgram(mProgramObject); + // Use the program object + GLState.useProgram(mProgramObject); - GLState.blend(true); - GLState.test(false, false); + GLState.blend(true); + GLState.test(false, false); - // bind VBO data - mVBO.bind(); + // bind VBO data + mVBO.bind(); - // set VBO vertex layout - gl.vertexAttribPointer(hVertexPosition, 2, GL.FLOAT, false, 0, 0); + // set VBO vertex layout + gl.vertexAttribPointer(hVertexPosition, 2, GL.FLOAT, false, 0, 0); - GLState.enableVertexArrays(hVertexPosition, -1); + GLState.enableVertexArrays(hVertexPosition, -1); /* apply view and projection matrices */ - // set mvp (tmp) matrix relative to mMapPosition - // i.e. fixed on the map - setMatrix(v); - v.mvp.setAsUniform(hMatrixPosition); + // set mvp (tmp) matrix relative to mMapPosition + // i.e. fixed on the map + setMatrix(v); + v.mvp.setAsUniform(hMatrixPosition); - final int offset_x = 4; - final int offset_y = 16; + final int offset_x = 4; + final int offset_y = 16; - float h = (float) (Math.sqrt(3) / 2); - for (int y = -offset_y; y < offset_y; y++) { - for (int x = -offset_x; x < offset_x; x++) { - float xx = x * 2 + (y % 2 == 0 ? 1 : 0); - float yy = y * h + h / 2; + float h = (float) (Math.sqrt(3) / 2); + for (int y = -offset_y; y < offset_y; y++) { + for (int x = -offset_x; x < offset_x; x++) { + float xx = x * 2 + (y % 2 == 0 ? 1 : 0); + float yy = y * h + h / 2; - gl.uniform2f(hCenterPosition, xx * (mCellScale * 1.5f), yy * mCellScale); + gl.uniform2f(hCenterPosition, xx * (mCellScale * 1.5f), yy * mCellScale); - //float alpha = 1 + (float) Math.log10(FastMath.clamp( - // (float) Math.sqrt(xx * xx + yy * yy) / offset_y, 0.0f, 1.0f)) * 2; + //float alpha = 1 + (float) Math.log10(FastMath.clamp( + // (float) Math.sqrt(xx * xx + yy * yy) / offset_y, 0.0f, 1.0f)) * 2; - float alpha = (float) Math.sqrt(xx * xx + yy * yy) / offset_y; + float alpha = (float) Math.sqrt(xx * xx + yy * yy) / offset_y; - float fy = (float) (y + offset_y) / (offset_y * 2); - float fx = (float) (x + offset_x) / (offset_x * 2); - float fz = FastMath.clamp( - (float) (x < 0 || y < 0 ? 1 - Math.sqrt(fx * fx + fy - * fy) - : 0), - 0, - 1); + float fy = (float) (y + offset_y) / (offset_y * 2); + float fx = (float) (x + offset_x) / (offset_x * 2); + float fz = FastMath.clamp( + (float) (x < 0 || y < 0 ? 1 - Math.sqrt(fx * fx + fy + * fy) + : 0), + 0, + 1); - int c = 0xff << 24 - | (int) (0xff * fy) << 16 - | (int) (0xff * fx) << 8 - | (int) (0xff * fz); + int c = 0xff << 24 + | (int) (0xff * fy) << 16 + | (int) (0xff * fx) << 8 + | (int) (0xff * fz); - GLUtils.setColor(hColorPosition, c, alpha); + GLUtils.setColor(hColorPosition, c, alpha); - gl.drawArrays(GL.TRIANGLE_FAN, 0, 6); - } - } + gl.drawArrays(GL.TRIANGLE_FAN, 0, 6); + } + } - GLUtils.setColor(hColorPosition, Color.DKGRAY, 0.3f); + GLUtils.setColor(hColorPosition, Color.DKGRAY, 0.3f); - for (int y = -offset_y; y < offset_y; y++) { - for (int x = -offset_x; x < offset_x; x++) { - float xx = x * 2 + (y % 2 == 0 ? 1 : 0); - float yy = y * h + h / 2; + for (int y = -offset_y; y < offset_y; y++) { + for (int x = -offset_x; x < offset_x; x++) { + float xx = x * 2 + (y % 2 == 0 ? 1 : 0); + float yy = y * h + h / 2; - gl.uniform2f(hCenterPosition, xx * (mCellScale * 1.5f), yy * mCellScale); - gl.drawArrays(GL.LINE_LOOP, 0, 6); - } - } + gl.uniform2f(hCenterPosition, xx * (mCellScale * 1.5f), yy * mCellScale); + gl.drawArrays(GL.LINE_LOOP, 0, 6); + } + } - GLUtils.checkGlError("..."); - } + GLUtils.checkGlError("..."); + } - private boolean init() { - // Load the vertex/fragment shaders - int programObject = GLShader.createProgram(vShaderStr, fShaderStr); + private boolean init() { + // Load the vertex/fragment shaders + int programObject = GLShader.createProgram(vShaderStr, fShaderStr); - if (programObject == 0) - return false; + if (programObject == 0) + return false; - // Handle for vertex position in shader - hVertexPosition = gl.getAttribLocation(programObject, "a_pos"); + // Handle for vertex position in shader + hVertexPosition = gl.getAttribLocation(programObject, "a_pos"); - hMatrixPosition = gl.getUniformLocation(programObject, "u_mvp"); + hMatrixPosition = gl.getUniformLocation(programObject, "u_mvp"); - hColorPosition = gl.getUniformLocation(programObject, "u_color"); + hColorPosition = gl.getUniformLocation(programObject, "u_color"); - hCenterPosition = gl.getUniformLocation(programObject, "u_center"); + hCenterPosition = gl.getUniformLocation(programObject, "u_center"); - // Store the program object - mProgramObject = programObject; + // Store the program object + mProgramObject = programObject; - return true; - } + return true; + } - private final static String vShaderStr = "" - + "#ifdef GLES\n" - + "precision mediump float;\n" - + "#endif\n" - + "uniform mat4 u_mvp;" - + "uniform vec2 u_center;" - + "attribute vec2 a_pos;" - + "void main()" - + "{" - + " gl_Position = u_mvp * vec4(u_center + a_pos, 0.0, 1.0);" - + "}"; + private final static String vShaderStr = "" + + "#ifdef GLES\n" + + "precision mediump float;\n" + + "#endif\n" + + "uniform mat4 u_mvp;" + + "uniform vec2 u_center;" + + "attribute vec2 a_pos;" + + "void main()" + + "{" + + " gl_Position = u_mvp * vec4(u_center + a_pos, 0.0, 1.0);" + + "}"; - private final static String fShaderStr = "" - + "#ifdef GLES\n" - + "precision mediump float;\n" - + "#endif\n" - + "varying float alpha;" - + "uniform vec4 u_color;" - + "void main()" - + "{" - + " gl_FragColor = u_color;" - + "}"; + private final static String fShaderStr = "" + + "#ifdef GLES\n" + + "precision mediump float;\n" + + "#endif\n" + + "varying float alpha;" + + "uniform vec4 u_color;" + + "void main()" + + "{" + + " gl_FragColor = u_color;" + + "}"; - } + } } diff --git a/vtm-playground/src/org/oscim/test/renderer/SymbolRenderLayer.java b/vtm-playground/src/org/oscim/test/renderer/SymbolRenderLayer.java index 1730a5cc..fd1711b7 100644 --- a/vtm-playground/src/org/oscim/test/renderer/SymbolRenderLayer.java +++ b/vtm-playground/src/org/oscim/test/renderer/SymbolRenderLayer.java @@ -23,30 +23,30 @@ import org.oscim.renderer.bucket.SymbolBucket; import org.oscim.renderer.bucket.SymbolItem; public class SymbolRenderLayer extends BucketRenderer { - boolean initialize = true; + boolean initialize = true; - public SymbolRenderLayer() { - SymbolBucket l = new SymbolBucket(); - buckets.set(l); + public SymbolRenderLayer() { + SymbolBucket l = new SymbolBucket(); + buckets.set(l); - SymbolItem it = SymbolItem.pool.get(); - it.billboard = false; + SymbolItem it = SymbolItem.pool.get(); + it.billboard = false; - try { - it.bitmap = CanvasAdapter.getBitmapAsset("jar:symbols/cafe.png"); - } catch (Exception e) { - e.printStackTrace(); + try { + it.bitmap = CanvasAdapter.getBitmapAsset("jar:symbols/cafe.png"); + } catch (Exception e) { + e.printStackTrace(); - } - l.addSymbol(it); - } + } + l.addSymbol(it); + } - @Override - public void update(GLViewport v) { - if (initialize) { - initialize = false; - mMapPosition.copy(v.pos); - compile(); - } - } + @Override + public void update(GLViewport v) { + if (initialize) { + initialize = false; + mMapPosition.copy(v.pos); + compile(); + } + } } diff --git a/vtm-tests/test/org/oscim/layers/MapEventLayerTest.java b/vtm-tests/test/org/oscim/layers/MapEventLayerTest.java index 98aae198..19015758 100644 --- a/vtm-tests/test/org/oscim/layers/MapEventLayerTest.java +++ b/vtm-tests/test/org/oscim/layers/MapEventLayerTest.java @@ -17,127 +17,127 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class MapEventLayerTest { - private MapEventLayer layer; - private Map mockMap; - private ViewController mockViewport; - private Animator mockAnimator; - private ArgumentCaptor argumentCaptor; + private MapEventLayer layer; + private Map mockMap; + private ViewController mockViewport; + private Animator mockAnimator; + private ArgumentCaptor argumentCaptor; - @Before - public void setUp() throws Exception { - mockMap = Mockito.mock(Map.class); - mockViewport = Mockito.mock(ViewController.class); - mockAnimator = Mockito.mock(Animator.class); - layer = new MapEventLayer(mockMap); - when(mockMap.viewport()).thenReturn(mockViewport); - when(mockMap.animator()).thenReturn(mockAnimator); - when(mockMap.getHeight()).thenReturn(6); - argumentCaptor = ArgumentCaptor.forClass(float.class); - } + @Before + public void setUp() throws Exception { + mockMap = Mockito.mock(Map.class); + mockViewport = Mockito.mock(ViewController.class); + mockAnimator = Mockito.mock(Animator.class); + layer = new MapEventLayer(mockMap); + when(mockMap.viewport()).thenReturn(mockViewport); + when(mockMap.animator()).thenReturn(mockAnimator); + when(mockMap.getHeight()).thenReturn(6); + argumentCaptor = ArgumentCaptor.forClass(float.class); + } - @Test - public void shouldNotBeNull() throws Exception { - assertThat(layer).isNotNull(); - } + @Test + public void shouldNotBeNull() throws Exception { + assertThat(layer).isNotNull(); + } - @Test - public void doubleTap_shouldAnimateZoom() throws Exception { - simulateDoubleTap(); - verify(mockAnimator).animateZoom(300, 2, 1.0f, -2.0f); - } + @Test + public void doubleTap_shouldAnimateZoom() throws Exception { + simulateDoubleTap(); + verify(mockAnimator).animateZoom(300, 2, 1.0f, -2.0f); + } - @Test - public void doubleTap_shouldAnimateZoomAfterDoubleTouchDrag() throws Exception { - simulateDoubleTouchDragUp(); - simulateDoubleTap(); - verify(mockAnimator).animateZoom(300, 2, 1.0f, -2.0f); - } + @Test + public void doubleTap_shouldAnimateZoomAfterDoubleTouchDrag() throws Exception { + simulateDoubleTouchDragUp(); + simulateDoubleTap(); + verify(mockAnimator).animateZoom(300, 2, 1.0f, -2.0f); + } - @Test - public void doubleTouchDrag_shouldNotAnimateZoom() throws Exception { - simulateDoubleTouchDragUp(); - verify(mockAnimator, never()).animateZoom(any(long.class), any(double.class), - any(float.class), any(float.class)); - } + @Test + public void doubleTouchDrag_shouldNotAnimateZoom() throws Exception { + simulateDoubleTouchDragUp(); + verify(mockAnimator, never()).animateZoom(any(long.class), any(double.class), + any(float.class), any(float.class)); + } - @Test - public void doubleTouchDragUp_shouldDecreaseContentScale() throws Exception { - simulateDoubleTouchDragUp(); - verify(mockViewport).scaleMap(argumentCaptor.capture(), any(float.class), any(float.class)); - assertThat(argumentCaptor.getValue()).isLessThan(1); - } + @Test + public void doubleTouchDragUp_shouldDecreaseContentScale() throws Exception { + simulateDoubleTouchDragUp(); + verify(mockViewport).scaleMap(argumentCaptor.capture(), any(float.class), any(float.class)); + assertThat(argumentCaptor.getValue()).isLessThan(1); + } - @Test - public void doubleTouchDragDown_shouldIncreaseContentScale() throws Exception { - simulateDoubleTouchDragDown(); - verify(mockViewport).scaleMap(argumentCaptor.capture(), any(float.class), any(float.class)); - assertThat(argumentCaptor.getValue()).isGreaterThan(1); - } + @Test + public void doubleTouchDragDown_shouldIncreaseContentScale() throws Exception { + simulateDoubleTouchDragDown(); + verify(mockViewport).scaleMap(argumentCaptor.capture(), any(float.class), any(float.class)); + assertThat(argumentCaptor.getValue()).isGreaterThan(1); + } - private void simulateDoubleTap() { - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1)); - layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_UP, 1, 1)); - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 1)); - } + private void simulateDoubleTap() { + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1)); + layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_UP, 1, 1)); + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 1)); + } - private void simulateDoubleTouchDragUp() { - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1)); - layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_MOVE, 1, 0)); - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_MOVE, -100, 0)); - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 0)); - } + private void simulateDoubleTouchDragUp() { + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1)); + layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_MOVE, 1, 0)); + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_MOVE, -100, 0)); + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 0)); + } - private void simulateDoubleTouchDragDown() { - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1)); - layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_MOVE, 1, 2)); - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_MOVE, 100, 2)); - layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 2)); - } + private void simulateDoubleTouchDragDown() { + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_DOWN, 1, 1)); + layer.onGesture(Gesture.DOUBLE_TAP, new TestMotionEvent(MotionEvent.ACTION_MOVE, 1, 2)); + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_MOVE, 100, 2)); + layer.onTouchEvent(new TestMotionEvent(MotionEvent.ACTION_UP, 1, 2)); + } - class TestMotionEvent extends MotionEvent { - final int action; - final float x; - final float y; + class TestMotionEvent extends MotionEvent { + final int action; + final float x; + final float y; - public TestMotionEvent(int action, float x, float y) { - this.action = action; - this.x = x; - this.y = y; - } + public TestMotionEvent(int action, float x, float y) { + this.action = action; + this.x = x; + this.y = y; + } - @Override - public long getTime() { - return 0; - } + @Override + public long getTime() { + return 0; + } - @Override - public int getAction() { - return action; - } + @Override + public int getAction() { + return action; + } - @Override - public float getX() { - return x; - } + @Override + public float getX() { + return x; + } - @Override - public float getY() { - return y; - } + @Override + public float getY() { + return y; + } - @Override - public float getX(int idx) { - return x; - } + @Override + public float getX(int idx) { + return x; + } - @Override - public float getY(int idx) { - return y; - } + @Override + public float getY(int idx) { + return y; + } - @Override - public int getPointerCount() { - return 0; - } - } + @Override + public int getPointerCount() { + return 0; + } + } } diff --git a/vtm-tests/test/org/oscim/layers/tile/TileRendererTest.java b/vtm-tests/test/org/oscim/layers/tile/TileRendererTest.java index fda2b66c..10f3ee78 100644 --- a/vtm-tests/test/org/oscim/layers/tile/TileRendererTest.java +++ b/vtm-tests/test/org/oscim/layers/tile/TileRendererTest.java @@ -1,168 +1,168 @@ package org.oscim.layers.tile; -import static org.fest.assertions.api.Assertions.assertThat; - import org.junit.Test; import org.oscim.layers.tile.MapTile.TileNode; import org.oscim.renderer.MapRenderer; +import static org.fest.assertions.api.Assertions.assertThat; + public class TileRendererTest { - static { - /* makes default minFadeTime == 1000 */ - MapRenderer.frametime = 1050; - } + static { + /* makes default minFadeTime == 1000 */ + MapRenderer.frametime = 1050; + } - static TileNode makeNode(int fadeTime, TileNode parent) { - TileNode n = new TileNode(); - n.item = new MapTile(n, 0, 0, 0); - n.item.fadeTime = fadeTime; + static TileNode makeNode(int fadeTime, TileNode parent) { + TileNode n = new TileNode(); + n.item = new MapTile(n, 0, 0, 0); + n.item.fadeTime = fadeTime; - if (parent == null) { - // root node is its own parent - n.parent = n; - } else { - parent.child00 = n; - n.parent = parent; - } + if (parent == null) { + // root node is its own parent + n.parent = n; + } else { + parent.child00 = n; + n.parent = parent; + } - return n; - } + return n; + } - @Test - public void shouldGetMinFadeTimeOf1000() { + @Test + public void shouldGetMinFadeTimeOf1000() { - TileNode r = makeNode(0, null); - TileNode n = makeNode(0, r); + TileNode r = makeNode(0, null); + TileNode n = makeNode(0, r); - long fadeTime = TileRenderer.getMinFade(n.item, 0); + long fadeTime = TileRenderer.getMinFade(n.item, 0); - assertThat(fadeTime).isEqualTo(1000); - } + assertThat(fadeTime).isEqualTo(1000); + } - @Test - public void shouldGetMinFadeTimeFromParent() { + @Test + public void shouldGetMinFadeTimeFromParent() { - TileNode r = makeNode(100, null); - TileNode n = makeNode(0, r); + TileNode r = makeNode(100, null); + TileNode n = makeNode(0, r); - long fadeTime = TileRenderer.getMinFade(n.item, 0); + long fadeTime = TileRenderer.getMinFade(n.item, 0); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldGetMinFadeTimeFromGrandparent() { + @Test + public void shouldGetMinFadeTimeFromGrandparent() { - TileNode r = makeNode(100, null); - TileNode p = makeNode(200, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(100, null); + TileNode p = makeNode(200, r); + TileNode n = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(n.item, 0); + long fadeTime = TileRenderer.getMinFade(n.item, 0); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldGetMinFadeTimeFromParentWhenParentsTimeIsLessThanGrandpasTime() { + @Test + public void shouldGetMinFadeTimeFromParentWhenParentsTimeIsLessThanGrandpasTime() { - TileNode r = makeNode(200, null); - TileNode p = makeNode(100, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(200, null); + TileNode p = makeNode(100, r); + TileNode n = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(n.item, 0); + long fadeTime = TileRenderer.getMinFade(n.item, 0); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldGetMinFadeTimeFromParentForParentProxy() { + @Test + public void shouldGetMinFadeTimeFromParentForParentProxy() { - TileNode r = makeNode(200, null); - TileNode p = makeNode(100, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(200, null); + TileNode p = makeNode(100, r); + TileNode n = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(n.item, -1); + long fadeTime = TileRenderer.getMinFade(n.item, -1); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldNotGetMinFadeTimeFromGradparentForParentProxy() { - /* (as the grandparent will not be locked) */ + @Test + public void shouldNotGetMinFadeTimeFromGradparentForParentProxy() { + /* (as the grandparent will not be locked) */ - TileNode r = makeNode(100, null); - TileNode p = makeNode(200, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(100, null); + TileNode p = makeNode(200, r); + TileNode n = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(n.item, -1); + long fadeTime = TileRenderer.getMinFade(n.item, -1); - assertThat(fadeTime).isNotEqualTo(100); - assertThat(fadeTime).isEqualTo(200); - } + assertThat(fadeTime).isNotEqualTo(100); + assertThat(fadeTime).isEqualTo(200); + } - @Test - public void shouldGetMinFadeTimeFromParentForChildProxy() { + @Test + public void shouldGetMinFadeTimeFromParentForChildProxy() { - TileNode r = makeNode(200, null); - TileNode p = makeNode(100, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(200, null); + TileNode p = makeNode(100, r); + TileNode n = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(n.item, 1); + long fadeTime = TileRenderer.getMinFade(n.item, 1); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldGetMinFadeTimeFromGrandparentForChildProxy() { + @Test + public void shouldGetMinFadeTimeFromGrandparentForChildProxy() { - TileNode r = makeNode(100, null); - TileNode p = makeNode(200, r); - TileNode c = makeNode(0, p); + TileNode r = makeNode(100, null); + TileNode p = makeNode(200, r); + TileNode c = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(c.item, 1); + long fadeTime = TileRenderer.getMinFade(c.item, 1); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldGetMinFadeTimeFromGrandgrandparentForChildProxy() { + @Test + public void shouldGetMinFadeTimeFromGrandgrandparentForChildProxy() { - TileNode r = makeNode(100, null); - TileNode gp = makeNode(200, r); - TileNode p = makeNode(200, gp); - TileNode c = makeNode(0, p); + TileNode r = makeNode(100, null); + TileNode gp = makeNode(200, r); + TileNode p = makeNode(200, gp); + TileNode c = makeNode(0, p); - long fadeTime = TileRenderer.getMinFade(c.item, 1); + long fadeTime = TileRenderer.getMinFade(c.item, 1); - assertThat(fadeTime).isEqualTo(100); - } + assertThat(fadeTime).isEqualTo(100); + } - @Test - public void shouldGetMinFadeTimeFromChild() { + @Test + public void shouldGetMinFadeTimeFromChild() { - TileNode r = makeNode(100, null); - TileNode p = makeNode(200, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(100, null); + TileNode p = makeNode(200, r); + TileNode n = makeNode(0, p); - n.child00 = makeNode(50, n); + n.child00 = makeNode(50, n); - long fadeTime = TileRenderer.getMinFade(n.item, 0); + long fadeTime = TileRenderer.getMinFade(n.item, 0); - assertThat(fadeTime).isEqualTo(50); - } + assertThat(fadeTime).isEqualTo(50); + } - @Test - public void shouldGetMinFadeTimeForParentFromChild() { + @Test + public void shouldGetMinFadeTimeForParentFromChild() { - TileNode r = makeNode(100, null); - TileNode p = makeNode(200, r); - TileNode n = makeNode(0, p); + TileNode r = makeNode(100, null); + TileNode p = makeNode(200, r); + TileNode n = makeNode(0, p); - n.child00 = makeNode(50, n); + n.child00 = makeNode(50, n); - long fadeTime = TileRenderer.getMinFade(p.item, -1); + long fadeTime = TileRenderer.getMinFade(p.item, -1); - assertThat(fadeTime).isEqualTo(50); - } + assertThat(fadeTime).isEqualTo(50); + } } diff --git a/vtm-tests/test/org/oscim/tiling/source/OkHttpEngineTest.java b/vtm-tests/test/org/oscim/tiling/source/OkHttpEngineTest.java index 0581d8f4..90a66a07 100644 --- a/vtm-tests/test/org/oscim/tiling/source/OkHttpEngineTest.java +++ b/vtm-tests/test/org/oscim/tiling/source/OkHttpEngineTest.java @@ -1,11 +1,9 @@ package org.oscim.tiling.source; -import static org.fest.assertions.api.Assertions.assertThat; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; +import com.squareup.okhttp.HttpResponseCache; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; @@ -13,92 +11,94 @@ import org.junit.Test; import org.oscim.core.Tile; import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; -import com.squareup.okhttp.HttpResponseCache; -import com.squareup.okhttp.mockwebserver.MockResponse; -import com.squareup.okhttp.mockwebserver.MockWebServer; -import com.squareup.okhttp.mockwebserver.RecordedRequest; +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; + +import static org.fest.assertions.api.Assertions.assertThat; public class OkHttpEngineTest { - private OkHttpEngine engine; - private MockWebServer server; - private MockResponse mockResponse; - private HttpResponseCache cache; + private OkHttpEngine engine; + private MockWebServer server; + private MockResponse mockResponse; + private HttpResponseCache cache; - @Before - public void setUp() throws Exception { - mockResponse = new MockResponse(); - mockResponse.setBody("TEST RESPONSE".getBytes()); - server = new MockWebServer(); - server.enqueue(mockResponse); - server.play(); - engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory() - .create(new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString())); - } + @Before + public void setUp() throws Exception { + mockResponse = new MockResponse(); + mockResponse.setBody("TEST RESPONSE".getBytes()); + server = new MockWebServer(); + server.enqueue(mockResponse); + server.play(); + engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory() + .create(new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString())); + } - @After - public void tearDown() throws Exception { - server.shutdown(); - } + @After + public void tearDown() throws Exception { + server.shutdown(); + } - @Test - public void shouldNotBeNull() throws Exception { - assertThat(engine).isNotNull(); - } + @Test + public void shouldNotBeNull() throws Exception { + assertThat(engine).isNotNull(); + } - @Test(expected = IllegalArgumentException.class) - public void sendRequest_shouldRejectNullTile() throws Exception { - engine.sendRequest(null); - } + @Test(expected = IllegalArgumentException.class) + public void sendRequest_shouldRejectNullTile() throws Exception { + engine.sendRequest(null); + } - @Test - public void sendRequest_shouldAppendXYZToPath() throws Exception { - engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); + @Test + public void sendRequest_shouldAppendXYZToPath() throws Exception { + engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); - RecordedRequest request = server.takeRequest(); - assertThat(request.getPath()).isEqualTo("/tiles/vtm/3/1/2.vtm"); - } + RecordedRequest request = server.takeRequest(); + assertThat(request.getPath()).isEqualTo("/tiles/vtm/3/1/2.vtm"); + } - @Test - public void read_shouldReturnResponseStream() throws Exception { - engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); + @Test + public void read_shouldReturnResponseStream() throws Exception { + engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); - InputStream responseStream = engine.read(); - String response = new BufferedReader(new InputStreamReader(responseStream)).readLine(); - assertThat(response).isEqualTo("TEST RESPONSE"); - } + InputStream responseStream = engine.read(); + String response = new BufferedReader(new InputStreamReader(responseStream)).readLine(); + assertThat(response).isEqualTo("TEST RESPONSE"); + } - // @Test(expected = IOException.class) - // public void close_shouldCloseInputStream() throws Exception { - // engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); - // engine.close(); - // // Calling read after the stream is closed should throw an exception. - // InputStream responseStream = engine.read(); - // responseStream.read(); - // } - // - // @Test(expected = IOException.class) - // public void requestCompleted_shouldCloseInputStream() throws Exception { - // engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); - // engine.requestCompleted(true); - // // Calling read after the stream is closed should throw an exception. - // InputStream responseStream = engine.read(); - // responseStream.read(); - // } + // @Test(expected = IOException.class) + // public void close_shouldCloseInputStream() throws Exception { + // engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); + // engine.close(); + // // Calling read after the stream is closed should throw an exception. + // InputStream responseStream = engine.read(); + // responseStream.read(); + // } + // + // @Test(expected = IOException.class) + // public void requestCompleted_shouldCloseInputStream() throws Exception { + // engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); + // engine.requestCompleted(true); + // // Calling read after the stream is closed should throw an exception. + // InputStream responseStream = engine.read(); + // responseStream.read(); + // } - @Test - public void requestCompleted_shouldReturnValueGiven() throws Exception { - assertThat(engine.requestCompleted(true)).isTrue(); - assertThat(engine.requestCompleted(false)).isFalse(); - } + @Test + public void requestCompleted_shouldReturnValueGiven() throws Exception { + assertThat(engine.requestCompleted(true)).isTrue(); + assertThat(engine.requestCompleted(false)).isFalse(); + } - @Test - public void create_shouldUseTileSourceCache() throws Exception { - cache = new HttpResponseCache(new File("tmp"), 1024); - OSciMap4TileSource tileSource = - new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString()); - engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory(cache).create(tileSource); - engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); - engine.requestCompleted(true); - assertThat(cache.getRequestCount()).isEqualTo(1); - } + @Test + public void create_shouldUseTileSourceCache() throws Exception { + cache = new HttpResponseCache(new File("tmp"), 1024); + OSciMap4TileSource tileSource = + new OSciMap4TileSource(server.getUrl("/tiles/vtm").toString()); + engine = (OkHttpEngine) new OkHttpEngine.OkHttpFactory(cache).create(tileSource); + engine.sendRequest(new Tile(1, 2, new Integer(3).byteValue())); + engine.requestCompleted(true); + assertThat(cache.getRequestCount()).isEqualTo(1); + } } diff --git a/vtm-tests/test/org/oscim/tiling/source/UrlTileSourceTest.java b/vtm-tests/test/org/oscim/tiling/source/UrlTileSourceTest.java index f9441420..1e92293b 100644 --- a/vtm-tests/test/org/oscim/tiling/source/UrlTileSourceTest.java +++ b/vtm-tests/test/org/oscim/tiling/source/UrlTileSourceTest.java @@ -16,64 +16,64 @@ */ package org.oscim.tiling.source; -import static org.fest.assertions.api.Assertions.assertThat; - import org.junit.Before; import org.junit.Test; import org.oscim.core.Tile; import org.oscim.tiling.ITileDataSource; +import static org.fest.assertions.api.Assertions.assertThat; + public class UrlTileSourceTest { - private UrlTileSource tileSource; + private UrlTileSource tileSource; - @Before - public void setUp() throws Exception { - tileSource = new TestTileSource("http://example.org/tiles/vtm", "/{Z}/{X}/{Z}.vtm"); - } + @Before + public void setUp() throws Exception { + tileSource = new TestTileSource("http://example.org/tiles/vtm", "/{Z}/{X}/{Z}.vtm"); + } - @Test - public void setApiKey_shouldAppendApiKey() throws Exception { - tileSource.setApiKey("testkey"); - assertThat(tileSource.getTileUrl(new Tile(0, 0, (byte) 0))).endsWith("?api_key=testkey"); - } + @Test + public void setApiKey_shouldAppendApiKey() throws Exception { + tileSource.setApiKey("testkey"); + assertThat(tileSource.getTileUrl(new Tile(0, 0, (byte) 0))).endsWith("?api_key=testkey"); + } - @Test - public void shouldNotBeNull() throws Exception { - assertThat(tileSource).isNotNull(); - } + @Test + public void shouldNotBeNull() throws Exception { + assertThat(tileSource).isNotNull(); + } - @Test - public void shouldUseDefaultHttpEngine() throws Exception { - TestTileDataSource dataSource = (TestTileDataSource) tileSource.getDataSource(); - assertThat(dataSource.getConnection()).isInstanceOf(LwHttp.class); - } + @Test + public void shouldUseDefaultHttpEngine() throws Exception { + TestTileDataSource dataSource = (TestTileDataSource) tileSource.getDataSource(); + assertThat(dataSource.getConnection()).isInstanceOf(LwHttp.class); + } - @Test - public void shouldUseCustomHttpEngine() throws Exception { - tileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory()); - TestTileDataSource dataSource = (TestTileDataSource) tileSource.getDataSource(); - assertThat(dataSource.getConnection()).isInstanceOf(OkHttpEngine.class); - } + @Test + public void shouldUseCustomHttpEngine() throws Exception { + tileSource.setHttpEngine(new OkHttpEngine.OkHttpFactory()); + TestTileDataSource dataSource = (TestTileDataSource) tileSource.getDataSource(); + assertThat(dataSource.getConnection()).isInstanceOf(OkHttpEngine.class); + } - class TestTileSource extends UrlTileSource { - public TestTileSource(String urlString, String tilePath) { - super(urlString, tilePath); - } + class TestTileSource extends UrlTileSource { + public TestTileSource(String urlString, String tilePath) { + super(urlString, tilePath); + } - @Override - public ITileDataSource getDataSource() { - return new TestTileDataSource(this, null, getHttpEngine()); - } - } + @Override + public ITileDataSource getDataSource() { + return new TestTileDataSource(this, null, getHttpEngine()); + } + } - class TestTileDataSource extends UrlTileDataSource { - public TestTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, - HttpEngine conn) { - super(tileSource, tileDecoder, conn); - } + class TestTileDataSource extends UrlTileDataSource { + public TestTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, + HttpEngine conn) { + super(tileSource, tileDecoder, conn); + } - public HttpEngine getConnection() { - return mConn; - } - } + public HttpEngine getConnection() { + return mConn; + } + } } diff --git a/vtm-tests/test/org/oscim/tiling/source/bitmap/BitmapTileSourceTest.java b/vtm-tests/test/org/oscim/tiling/source/bitmap/BitmapTileSourceTest.java index 5d15be66..80bfb068 100644 --- a/vtm-tests/test/org/oscim/tiling/source/bitmap/BitmapTileSourceTest.java +++ b/vtm-tests/test/org/oscim/tiling/source/bitmap/BitmapTileSourceTest.java @@ -1,7 +1,5 @@ package org.oscim.tiling.source.bitmap; -import static org.fest.assertions.api.Assertions.assertThat; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -13,66 +11,68 @@ import org.oscim.tiling.source.OkHttpEngine; import org.oscim.tiling.source.UrlTileDataSource; import org.oscim.tiling.source.UrlTileSource; +import static org.fest.assertions.api.Assertions.assertThat; + public class BitmapTileSourceTest { - private BitmapTileSource tileSource; + private BitmapTileSource tileSource; - @Before - public void setUp() throws Exception { - tileSource = new BitmapTileSource("http://tile.openstreetmap.org", 0, 18); - } + @Before + public void setUp() throws Exception { + tileSource = new BitmapTileSource("http://tile.openstreetmap.org", 0, 18); + } - @Test - public void shouldNotBeNull() throws Exception { - assertThat(tileSource).isNotNull(); - } + @Test + public void shouldNotBeNull() throws Exception { + assertThat(tileSource).isNotNull(); + } - @Test - public void shouldUseLwHttp() throws Exception { - LwHttp lwHttp = Mockito.mock(LwHttp.class); - tileSource.setHttpEngine(new TestHttpFactory(lwHttp)); - ITileDataSource dataSource = tileSource.getDataSource(); - dataSource.dispose(); - Mockito.verify(lwHttp).close(); - } + @Test + public void shouldUseLwHttp() throws Exception { + LwHttp lwHttp = Mockito.mock(LwHttp.class); + tileSource.setHttpEngine(new TestHttpFactory(lwHttp)); + ITileDataSource dataSource = tileSource.getDataSource(); + dataSource.dispose(); + Mockito.verify(lwHttp).close(); + } - @Test - public void shouldUseOkHttp() throws Exception { - OkHttpEngine okHttp = Mockito.mock(OkHttpEngine.class); - tileSource.setHttpEngine(new TestHttpFactory(okHttp)); - UrlTileDataSource dataSource = (UrlTileDataSource) tileSource.getDataSource(); - dataSource.dispose(); - Mockito.verify(okHttp).close(); - } + @Test + public void shouldUseOkHttp() throws Exception { + OkHttpEngine okHttp = Mockito.mock(OkHttpEngine.class); + tileSource.setHttpEngine(new TestHttpFactory(okHttp)); + UrlTileDataSource dataSource = (UrlTileDataSource) tileSource.getDataSource(); + dataSource.dispose(); + Mockito.verify(okHttp).close(); + } - @Test - public void shouldUseBuilderConfig() { - BitmapTileSource ts = BitmapTileSource.builder() - .url("http://example.com") - .zoomMax(42) - .zoomMin(23) - .fadeSteps(new FadeStep[] { new FadeStep(0, 10, 0.5f, 1.0f) }) - .build(); + @Test + public void shouldUseBuilderConfig() { + BitmapTileSource ts = BitmapTileSource.builder() + .url("http://example.com") + .zoomMax(42) + .zoomMin(23) + .fadeSteps(new FadeStep[]{new FadeStep(0, 10, 0.5f, 1.0f)}) + .build(); - assertThat(ts.getUrl().getHost()).isEqualTo("example.com"); - assertThat(ts.getZoomLevelMin()).isEqualTo(23); - assertThat(ts.getZoomLevelMax()).isEqualTo(42); - assertThat(ts.getFadeSteps()).isNotNull(); - } + assertThat(ts.getUrl().getHost()).isEqualTo("example.com"); + assertThat(ts.getZoomLevelMin()).isEqualTo(23); + assertThat(ts.getZoomLevelMax()).isEqualTo(42); + assertThat(ts.getFadeSteps()).isNotNull(); + } - /** - * Test factory that allows the specific {@link HttpEngine} instance to be - * set. - */ - class TestHttpFactory implements HttpEngine.Factory { - final HttpEngine engine; + /** + * Test factory that allows the specific {@link HttpEngine} instance to be + * set. + */ + class TestHttpFactory implements HttpEngine.Factory { + final HttpEngine engine; - public TestHttpFactory(HttpEngine engine) { - this.engine = engine; - } + public TestHttpFactory(HttpEngine engine) { + this.engine = engine; + } - @Override - public HttpEngine create(UrlTileSource tileSource) { - return engine; - } - } + @Override + public HttpEngine create(UrlTileSource tileSource) { + return engine; + } + } } diff --git a/vtm-tests/test/org/oscim/tiling/source/oscimap4/OSciMap4TileSourceTest.java b/vtm-tests/test/org/oscim/tiling/source/oscimap4/OSciMap4TileSourceTest.java index 34ad024f..ba78c78f 100644 --- a/vtm-tests/test/org/oscim/tiling/source/oscimap4/OSciMap4TileSourceTest.java +++ b/vtm-tests/test/org/oscim/tiling/source/oscimap4/OSciMap4TileSourceTest.java @@ -1,7 +1,5 @@ package org.oscim.tiling.source.oscimap4; -import static org.fest.assertions.api.Assertions.assertThat; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -11,51 +9,53 @@ import org.oscim.tiling.source.LwHttp; import org.oscim.tiling.source.OkHttpEngine; import org.oscim.tiling.source.UrlTileSource; +import static org.fest.assertions.api.Assertions.assertThat; + public class OSciMap4TileSourceTest { - private OSciMap4TileSource tileSource; + private OSciMap4TileSource tileSource; - @Before - public void setUp() throws Exception { - tileSource = new OSciMap4TileSource("http://www.example.org/tiles/vtm"); - } + @Before + public void setUp() throws Exception { + tileSource = new OSciMap4TileSource("http://www.example.org/tiles/vtm"); + } - @Test - public void shouldNotBeNull() throws Exception { - assertThat(tileSource).isNotNull(); - } + @Test + public void shouldNotBeNull() throws Exception { + assertThat(tileSource).isNotNull(); + } - @Test - public void shouldUseLwHttp() throws Exception { - LwHttp lwHttp = Mockito.mock(LwHttp.class); - tileSource.setHttpEngine(new TestHttpFactory(lwHttp)); - ITileDataSource dataSource = tileSource.getDataSource(); - dataSource.dispose(); - Mockito.verify(lwHttp).close(); - } + @Test + public void shouldUseLwHttp() throws Exception { + LwHttp lwHttp = Mockito.mock(LwHttp.class); + tileSource.setHttpEngine(new TestHttpFactory(lwHttp)); + ITileDataSource dataSource = tileSource.getDataSource(); + dataSource.dispose(); + Mockito.verify(lwHttp).close(); + } - @Test - public void shouldUseOkHttp() throws Exception { - OkHttpEngine okHttp = Mockito.mock(OkHttpEngine.class); - tileSource.setHttpEngine(new TestHttpFactory(okHttp)); - ITileDataSource dataSource = tileSource.getDataSource(); - dataSource.dispose(); - Mockito.verify(okHttp).close(); - } + @Test + public void shouldUseOkHttp() throws Exception { + OkHttpEngine okHttp = Mockito.mock(OkHttpEngine.class); + tileSource.setHttpEngine(new TestHttpFactory(okHttp)); + ITileDataSource dataSource = tileSource.getDataSource(); + dataSource.dispose(); + Mockito.verify(okHttp).close(); + } - /** - * Test factory that allows the specific {@link HttpEngine} instance to be - * set. - */ - class TestHttpFactory implements HttpEngine.Factory { - final HttpEngine engine; + /** + * Test factory that allows the specific {@link HttpEngine} instance to be + * set. + */ + class TestHttpFactory implements HttpEngine.Factory { + final HttpEngine engine; - public TestHttpFactory(HttpEngine engine) { - this.engine = engine; - } + public TestHttpFactory(HttpEngine engine) { + this.engine = engine; + } - @Override - public HttpEngine create(UrlTileSource tileSource) { - return engine; - } - } + @Override + public HttpEngine create(UrlTileSource tileSource) { + return engine; + } + } } diff --git a/vtm-tests/test/org/oscim/utils/KeyMapTest.java b/vtm-tests/test/org/oscim/utils/KeyMapTest.java index 103f1302..efbaa365 100644 --- a/vtm-tests/test/org/oscim/utils/KeyMapTest.java +++ b/vtm-tests/test/org/oscim/utils/KeyMapTest.java @@ -1,70 +1,70 @@ package org.oscim.utils; -import java.util.ArrayList; - import org.junit.Assert; import org.junit.Test; import org.oscim.utils.KeyMap.HashItem; +import java.util.ArrayList; + public class KeyMapTest { - static class Item extends HashItem { - int key; + static class Item extends HashItem { + int key; - public Item(int i) { - key = i; - } + public Item(int i) { + key = i; + } - @Override - public boolean equals(Object obj) { - Item it = (Item) obj; + @Override + public boolean equals(Object obj) { + Item it = (Item) obj; - return it.key == key; - } + return it.key == key; + } - @Override - public int hashCode() { - return key; - } - } + @Override + public int hashCode() { + return key; + } + } - @Test - public void shouldWork1() { - KeyMap map = new KeyMap(512); - KeyMap map2 = new KeyMap(512); + @Test + public void shouldWork1() { + KeyMap map = new KeyMap(512); + KeyMap map2 = new KeyMap(512); - ArrayList items = new ArrayList(1024); + ArrayList items = new ArrayList(1024); - for (int i = 0; i < 10000; i++) { - Item it = new Item(i); - items.add(it); - Assert.assertNull(map.put(it)); - } + for (int i = 0; i < 10000; i++) { + Item it = new Item(i); + items.add(it); + Assert.assertNull(map.put(it)); + } - for (Item it : items) { - Item it2 = map.remove(it); - Assert.assertTrue(it == it2); - map2.put(it2); - } + for (Item it : items) { + Item it2 = map.remove(it); + Assert.assertTrue(it == it2); + map2.put(it2); + } - for (Item it : items) { - Item it2 = map2.get(it); - Assert.assertTrue(it == it2); - } + for (Item it : items) { + Item it2 = map2.get(it); + Assert.assertTrue(it == it2); + } /* replace the items with itself */ - for (Item it : items) { - Item it2 = map2.put(it); - Assert.assertTrue(it == it2); - } - } + for (Item it : items) { + Item it2 = map2.put(it); + Assert.assertTrue(it == it2); + } + } - @Test - public void shouldWork2() { - for (int i = 0; i < 100; i++) { - long start = System.currentTimeMillis(); - shouldWork1(); - System.out.println("time: " + ((System.currentTimeMillis() - start))); + @Test + public void shouldWork2() { + for (int i = 0; i < 100; i++) { + long start = System.currentTimeMillis(); + shouldWork1(); + System.out.println("time: " + ((System.currentTimeMillis() - start))); - } - } + } + } } diff --git a/vtm-tests/test/org/oscim/utils/QuadTreeTest.java b/vtm-tests/test/org/oscim/utils/QuadTreeTest.java index e538fc3e..04a18ead 100644 --- a/vtm-tests/test/org/oscim/utils/QuadTreeTest.java +++ b/vtm-tests/test/org/oscim/utils/QuadTreeTest.java @@ -1,234 +1,235 @@ package org.oscim.utils; -import static java.lang.System.currentTimeMillis; -import static java.lang.System.out; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - import org.junit.Assert; import org.junit.Test; import org.oscim.core.Box; import org.oscim.utils.SpatialIndex.SearchCb; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static java.lang.System.currentTimeMillis; +import static java.lang.System.out; + public class QuadTreeTest { - final static Random rand = new Random((long) (Math.PI * 10000000)); + final static Random rand = new Random((long) (Math.PI * 10000000)); - public class Item { - final int val; - final Box bbox;; + public class Item { + final int val; + final Box bbox; + ; - Item(Box bbox, int val) { - this.val = val; - this.bbox = new Box(bbox); - } + Item(Box bbox, int val) { + this.val = val; + this.bbox = new Box(bbox); + } - @Override - public String toString() { - return String.valueOf(val) + ' ' + bbox; - } - } + @Override + public String toString() { + return String.valueOf(val) + ' ' + bbox; + } + } - ArrayList fillRandomTree(SpatialIndex q, int numItems) { - Box box = new Box(); - ArrayList items = new ArrayList(numItems + 16); + ArrayList fillRandomTree(SpatialIndex q, int numItems) { + Box box = new Box(); + ArrayList items = new ArrayList(numItems + 16); - for (int i = 0; i < numItems; i++) { - box.xmin = (int) (rand.nextDouble() * 10000 - 5000); - box.ymin = (int) (rand.nextDouble() * 10000 - 5000); - box.xmax = (int) (box.xmin + rand.nextDouble() * 500); - box.ymax = (int) (box.ymin + rand.nextDouble() * 500); + for (int i = 0; i < numItems; i++) { + box.xmin = (int) (rand.nextDouble() * 10000 - 5000); + box.ymin = (int) (rand.nextDouble() * 10000 - 5000); + box.xmax = (int) (box.xmin + rand.nextDouble() * 500); + box.ymax = (int) (box.ymin + rand.nextDouble() * 500); - Item it = new Item(box, i); - q.insert(box, it); + Item it = new Item(box, i); + q.insert(box, it); - items.add(it); + items.add(it); - } - return items; - } + } + return items; + } - @Test - public void shouldWork0() { + @Test + public void shouldWork0() { - SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 16); - //SpatialIndex q = new RTree(); + SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 16); + //SpatialIndex q = new RTree(); - int numItems = 10000; + int numItems = 10000; - List items = fillRandomTree(q, numItems); + List items = fillRandomTree(q, numItems); - final int[] found = { 0 }; - final int[] matched = { 0 }; + final int[] found = {0}; + final int[] matched = {0}; - for (Item it : items) { - int f = matched[0]; - q.search(it.bbox, new SearchCb() { - @Override - public boolean call(Item item, Object context) { - found[0]++; - if (context == item) { - matched[0]++; - return false; - } - return true; - } - }, it); + for (Item it : items) { + int f = matched[0]; + q.search(it.bbox, new SearchCb() { + @Override + public boolean call(Item item, Object context) { + found[0]++; + if (context == item) { + matched[0]++; + return false; + } + return true; + } + }, it); - if (f == matched[0]) - out.println((it.bbox.xmax - it.bbox.xmin) - + " x " + (it.bbox.ymax - it.bbox.ymin) - + " ==> " + it); - } + if (f == matched[0]) + out.println((it.bbox.xmax - it.bbox.xmin) + + " x " + (it.bbox.ymax - it.bbox.ymin) + + " ==> " + it); + } - //out.println("m:" + matched[0] + " f:" + found[0]); - Assert.assertEquals(numItems, matched[0]); - Assert.assertEquals(numItems, q.size()); - } + //out.println("m:" + matched[0] + " f:" + found[0]); + Assert.assertEquals(numItems, matched[0]); + Assert.assertEquals(numItems, q.size()); + } - @Test - public void shouldWork1() { - long time = currentTimeMillis(); + @Test + public void shouldWork1() { + long time = currentTimeMillis(); - for (int i = 0; i < 10; i++) { - shouldWork0(); - } + for (int i = 0; i < 10; i++) { + shouldWork0(); + } - long now = currentTimeMillis(); - out.println("==>" + (now - time) / 10.0f + "ms"); - } + long now = currentTimeMillis(); + out.println("==>" + (now - time) / 10.0f + "ms"); + } - @Test - public void shouldWork6() { - SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 16); + @Test + public void shouldWork6() { + SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 16); - Box box = new Box(-4184.653317773969, - 3183.6174297948446, - -4088.3197324911957, - 3222.7770427421046); + Box box = new Box(-4184.653317773969, + 3183.6174297948446, + -4088.3197324911957, + 3222.7770427421046); - Item it = new Item(box, 1); - q.insert(box, it); + Item it = new Item(box, 1); + q.insert(box, it); - q.search(it.bbox, new SearchCb() { - @Override - public boolean call(Item item, Object context) { - out.println("==> " + item + " " + (context == item)); - return true; - } - }, it); - Assert.assertEquals(1, q.size()); - } + q.search(it.bbox, new SearchCb() { + @Override + public boolean call(Item item, Object context) { + out.println("==> " + item + " " + (context == item)); + return true; + } + }, it); + Assert.assertEquals(1, q.size()); + } - @Test - public void shouldWork7() { - SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 14); - //SpatialIndex q = new RTree(); + @Test + public void shouldWork7() { + SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 14); + //SpatialIndex q = new RTree(); - int numItems = 10000; + int numItems = 10000; - List items = fillRandomTree(q, numItems); + List items = fillRandomTree(q, numItems); - Assert.assertEquals(numItems, q.size()); + Assert.assertEquals(numItems, q.size()); - int cnt = numItems; - for (Item it : items) { - if (!q.remove(it.bbox, it)) { - out.println((it.bbox.xmax - it.bbox.xmin) - + " x " + (it.bbox.ymax - it.bbox.ymin) - + " ==> " + it); + int cnt = numItems; + for (Item it : items) { + if (!q.remove(it.bbox, it)) { + out.println((it.bbox.xmax - it.bbox.xmin) + + " x " + (it.bbox.ymax - it.bbox.ymin) + + " ==> " + it); - q.search(it.bbox, new SearchCb() { - @Override - public boolean call(Item item, Object context) { - if (context == item) { - out.println("found..."); - return false; - } - return true; - } - }, it); - } - Assert.assertEquals(--cnt, q.size()); - } + q.search(it.bbox, new SearchCb() { + @Override + public boolean call(Item item, Object context) { + if (context == item) { + out.println("found..."); + return false; + } + return true; + } + }, it); + } + Assert.assertEquals(--cnt, q.size()); + } - items = fillRandomTree(q, numItems); + items = fillRandomTree(q, numItems); - Assert.assertEquals(numItems, q.size()); + Assert.assertEquals(numItems, q.size()); - cnt = numItems; - for (Item it : items) { - if (!q.remove(it.bbox, it)) - out.println((it.bbox.xmax - it.bbox.xmin) - + " x " + (it.bbox.ymax - it.bbox.ymin) - + " => " + it); + cnt = numItems; + for (Item it : items) { + if (!q.remove(it.bbox, it)) + out.println((it.bbox.xmax - it.bbox.xmin) + + " x " + (it.bbox.ymax - it.bbox.ymin) + + " => " + it); - Assert.assertEquals(--cnt, q.size()); - } - Assert.assertEquals(0, q.size()); - out.println(""); - } + Assert.assertEquals(--cnt, q.size()); + } + Assert.assertEquals(0, q.size()); + out.println(""); + } - @Test - public void shouldWork8() { + @Test + public void shouldWork8() { - SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 16); - //SpatialIndex q = new RTree(); + SpatialIndex q = new QuadTree(Short.MAX_VALUE + 1, 16); + //SpatialIndex q = new RTree(); - int numItems = 10000; + int numItems = 10000; - List items = fillRandomTree(q, numItems); + List items = fillRandomTree(q, numItems); - final int[] found = { 0 }; - final int[] matched = { 0 }; + final int[] found = {0}; + final int[] matched = {0}; - for (Item it : items) { - int f = matched[0]; - int cnt = 0; - for (Item it2 : items) { - if (it2.bbox.overlap(it.bbox)) - cnt++; - } - found[0] = 0; - q.search(it.bbox, new SearchCb() { - @Override - public boolean call(Item item, Object context) { - found[0]++; - if (context == item) { - matched[0]++; - //return false; - } - return true; - } - }, it); + for (Item it : items) { + int f = matched[0]; + int cnt = 0; + for (Item it2 : items) { + if (it2.bbox.overlap(it.bbox)) + cnt++; + } + found[0] = 0; + q.search(it.bbox, new SearchCb() { + @Override + public boolean call(Item item, Object context) { + found[0]++; + if (context == item) { + matched[0]++; + //return false; + } + return true; + } + }, it); - if (found[0] != cnt) { - out.println("not found " + (found[0] - cnt)); - } - //Assert.assertEquals(cnt, found[0]); - if (f == matched[0]) - out.println((it.bbox.xmax - it.bbox.xmin) - + " x " + (it.bbox.ymax - it.bbox.ymin) - + " ==> " + it); - } + if (found[0] != cnt) { + out.println("not found " + (found[0] - cnt)); + } + //Assert.assertEquals(cnt, found[0]); + if (f == matched[0]) + out.println((it.bbox.xmax - it.bbox.xmin) + + " x " + (it.bbox.ymax - it.bbox.ymin) + + " ==> " + it); + } - //out.println("m:" + matched[0] + " f:" + found[0]); - Assert.assertEquals(numItems, matched[0]); - Assert.assertEquals(numItems, q.size()); - } + //out.println("m:" + matched[0] + " f:" + found[0]); + Assert.assertEquals(numItems, matched[0]); + Assert.assertEquals(numItems, q.size()); + } - public static void main(String[] args) { - QuadTreeTest qt = new QuadTreeTest(); + public static void main(String[] args) { + QuadTreeTest qt = new QuadTreeTest(); - long time = currentTimeMillis(); + long time = currentTimeMillis(); - for (int i = 0; i < 100; i++) { - qt.shouldWork0(); - long now = currentTimeMillis(); + for (int i = 0; i < 100; i++) { + qt.shouldWork0(); + long now = currentTimeMillis(); - out.println("==>" + (now - time)); - time = now; - } - } + out.println("==>" + (now - time)); + time = now; + } + } } diff --git a/vtm-tests/test/org/oscim/utils/RTreeTest.java b/vtm-tests/test/org/oscim/utils/RTreeTest.java index a0fb1c02..334f2b9d 100644 --- a/vtm-tests/test/org/oscim/utils/RTreeTest.java +++ b/vtm-tests/test/org/oscim/utils/RTreeTest.java @@ -16,212 +16,212 @@ */ package org.oscim.utils; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Random; - import org.junit.Assert; import org.junit.Test; import org.oscim.core.Box; import org.oscim.utils.SpatialIndex.SearchCb; +import java.util.ArrayList; +import java.util.Random; + +import static org.junit.Assert.assertEquals; + public class RTreeTest { - public class Item { - final int val; - final double[] min; - final double[] max; + public class Item { + final int val; + final double[] min; + final double[] max; - Item(final double[] min, final double[] max, int val) { - this.val = val; - this.min = min.clone(); - this.max = max.clone(); - } + Item(final double[] min, final double[] max, int val) { + this.val = val; + this.min = min.clone(); + this.max = max.clone(); + } - @Override - public String toString() { - // return val + "/" - // + Arrays.toString(min) + "/" - // + Arrays.toString(max); - return String.valueOf(val); - } - } + @Override + public String toString() { + // return val + "/" + // + Arrays.toString(min) + "/" + // + Arrays.toString(max); + return String.valueOf(val); + } + } - @Test - public void shouldRemove() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 1, 1 }; - Item it = new Item(min, max, 1); - t.insert(min, max, it); - Assert.assertEquals(1, t.size()); - t.remove(min, max, it); - Assert.assertEquals(0, t.size()); - } + @Test + public void shouldRemove() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {1, 1}; + Item it = new Item(min, max, 1); + t.insert(min, max, it); + Assert.assertEquals(1, t.size()); + t.remove(min, max, it); + Assert.assertEquals(0, t.size()); + } - @Test - public void shouldWork() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 1, 1 }; - for (int i = 0; i < 1000; i++) { + @Test + public void shouldWork() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {1, 1}; + for (int i = 0; i < 1000; i++) { - Item it = new Item(min, max, i); - //out.println("insert: " + it.val); - t.insert(min, max, it); + Item it = new Item(min, max, i); + //out.println("insert: " + it.val); + t.insert(min, max, it); - min[0]++; - min[1]++; + min[0]++; + min[1]++; - max[0]++; - max[1]++; + max[0]++; + max[1]++; - } - Assert.assertEquals(1000, t.size()); + } + Assert.assertEquals(1000, t.size()); - min[0] = 0; - min[1] = 0; - // max[0] = 4; - // max[1] = 4; + min[0] = 0; + min[1] = 0; + // max[0] = 4; + // max[1] = 4; - final ArrayList results = new ArrayList(); + final ArrayList results = new ArrayList(); - t.search(min, max, new SearchCb() { - @Override - public boolean call(Item item, Object context) { - //out.println("found: " + item); - results.add(item); - return true; - } - }, - null); + t.search(min, max, new SearchCb() { + @Override + public boolean call(Item item, Object context) { + //out.println("found: " + item); + results.add(item); + return true; + } + }, + null); - for (int i = 999; i >= 0; i--) { - Item it = results.remove(i); - //boolean removed = - t.remove(it.min, it.max, it); - //out.println("REMOVED: " + it + " " + removed); + for (int i = 999; i >= 0; i--) { + Item it = results.remove(i); + //boolean removed = + t.remove(it.min, it.max, it); + //out.println("REMOVED: " + it + " " + removed); - Assert.assertEquals(i, t.size()); - } - Assert.assertEquals(0, t.size()); - } + Assert.assertEquals(i, t.size()); + } + Assert.assertEquals(0, t.size()); + } - @Test - public void shouldStack1() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 1, 1 }; + @Test + public void shouldStack1() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {1, 1}; - int numItems = 10000; - for (int i = 0; i < numItems; i++) { + int numItems = 10000; + for (int i = 0; i < numItems; i++) { - Item it = new Item(min, max, i); - //out.println("insert: " + it.val); - t.insert(min, max, it); + Item it = new Item(min, max, i); + //out.println("insert: " + it.val); + t.insert(min, max, it); - min[0]++; - min[1]++; + min[0]++; + min[1]++; - max[0]++; - max[1]++; + max[0]++; + max[1]++; - } - assertEquals(numItems, t.size()); + } + assertEquals(numItems, t.size()); - min[0] = 0; - min[1] = 0; + min[0] = 0; + min[1] = 0; - final ArrayList results = new ArrayList(); + final ArrayList results = new ArrayList(); - t.search(min, max, new SearchCb() { - @Override - public boolean call(Item item, Object context) { - //out.println("found: " + item); - results.add(item); - return true; - } - }, null); + t.search(min, max, new SearchCb() { + @Override + public boolean call(Item item, Object context) { + //out.println("found: " + item); + results.add(item); + return true; + } + }, null); - assertEquals(results.size(), numItems); + assertEquals(results.size(), numItems); - // for (int i = 999; i >= 0; i--) { - // Item it = results.remove(i); - // boolean removed = t.remove(it.min, it.max, it); - // //out.println("REMOVED: " + it + " " + removed); - // - // Assert.assertEquals(i, t.count()); - // } - // Assert.assertEquals(0, t.count()); - } + // for (int i = 999; i >= 0; i--) { + // Item it = results.remove(i); + // boolean removed = t.remove(it.min, it.max, it); + // //out.println("REMOVED: " + it + " " + removed); + // + // Assert.assertEquals(i, t.count()); + // } + // Assert.assertEquals(0, t.count()); + } - @Test - public void shouldStack2() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 1, 1 }; + @Test + public void shouldStack2() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {1, 1}; - int numItems = 10000; - for (int i = 0; i < numItems; i++) { + int numItems = 10000; + for (int i = 0; i < numItems; i++) { - Item it = new Item(min, max, i); - //out.println("insert: " + it.val); - t.insert(min, max, it); + Item it = new Item(min, max, i); + //out.println("insert: " + it.val); + t.insert(min, max, it); - min[0]++; - min[1]++; + min[0]++; + min[1]++; - max[0]++; - max[1]++; + max[0]++; + max[1]++; - } - assertEquals(numItems, t.size()); + } + assertEquals(numItems, t.size()); - min[0] = 0; - min[1] = 0; + min[0] = 0; + min[1] = 0; - final ArrayList results = new ArrayList(); + final ArrayList results = new ArrayList(); - Box bbox = new Box(min[0], min[1], max[0], max[1]); + Box bbox = new Box(min[0], min[1], max[0], max[1]); - t.search(bbox, results); + t.search(bbox, results); - assertEquals(numItems, results.size()); + assertEquals(numItems, results.size()); - // for (int i = 999; i >= 0; i--) { - // Item it = results.remove(i); - // boolean removed = t.remove(it.min, it.max, it); - // //out.println("REMOVED: " + it + " " + removed); - // - // Assert.assertEquals(i, t.count()); - // } - // Assert.assertEquals(0, t.count()); - } + // for (int i = 999; i >= 0; i--) { + // Item it = results.remove(i); + // boolean removed = t.remove(it.min, it.max, it); + // //out.println("REMOVED: " + it + " " + removed); + // + // Assert.assertEquals(i, t.count()); + // } + // Assert.assertEquals(0, t.count()); + } - @Test - public void shouldWork0() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 0, 0 }; - Random r = new Random((long) (Math.PI * 10000000)); - ArrayList items = new ArrayList(); + @Test + public void shouldWork0() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {0, 0}; + Random r = new Random((long) (Math.PI * 10000000)); + ArrayList items = new ArrayList(); - for (int i = 0; i < 10000; i++) { - min[0] = r.nextDouble() * 10000 - 5000; - min[1] = Math.random() * 10000 - 5000; - max[0] = min[0] + Math.random() * 100; - max[1] = min[1] + Math.random() * 100; + for (int i = 0; i < 10000; i++) { + min[0] = r.nextDouble() * 10000 - 5000; + min[1] = Math.random() * 10000 - 5000; + max[0] = min[0] + Math.random() * 100; + max[1] = min[1] + Math.random() * 100; - Item it = new Item(min, max, i); - t.insert(min, max, it); - items.add(it); - } + Item it = new Item(min, max, i); + t.insert(min, max, it); + items.add(it); + } - Assert.assertEquals(10000, t.size()); + Assert.assertEquals(10000, t.size()); /*SearchCb cb = new SearchCb() { - @Override + @Override public boolean call(Item item, Object context) { //out.println("found: " + item); //results.add(item); @@ -236,98 +236,98 @@ public class RTreeTest { } System.out.println("found: " + counter);*/ - } + } - @Test - public void shouldWork1() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 0, 0 }; + @Test + public void shouldWork1() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {0, 0}; - ArrayList items = new ArrayList(); + ArrayList items = new ArrayList(); - for (int i = 0; i < 10000; i++) { - min[0] = Math.random() * 10000 - 5000; - min[1] = Math.random() * 10000 - 5000; - max[0] = min[0] + Math.random() * 1000; - max[1] = min[1] + Math.random() * 1000; + for (int i = 0; i < 10000; i++) { + min[0] = Math.random() * 10000 - 5000; + min[1] = Math.random() * 10000 - 5000; + max[0] = min[0] + Math.random() * 1000; + max[1] = min[1] + Math.random() * 1000; - Item it = new Item(min, max, i); - t.insert(min, max, it); - items.add(it); - } + Item it = new Item(min, max, i); + t.insert(min, max, it); + items.add(it); + } - Assert.assertEquals(10000, t.size()); + Assert.assertEquals(10000, t.size()); - for (Item it : items) - t.remove(it.min, it.max, it); + for (Item it : items) + t.remove(it.min, it.max, it); - Assert.assertEquals(0, t.size()); - } + Assert.assertEquals(0, t.size()); + } - @Test - public void shouldWork2() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 0, 0 }; + @Test + public void shouldWork2() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {0, 0}; - ArrayList items = new ArrayList(); + ArrayList items = new ArrayList(); - int numItems = 10000; - for (int i = 0; i < numItems; i++) { - min[0] = Math.random() * 10000 - 5000; - min[1] = Math.random() * 10000 - 5000; - max[0] = min[0] + Math.random() * 1000; - max[1] = min[1] + Math.random() * 1000; + int numItems = 10000; + for (int i = 0; i < numItems; i++) { + min[0] = Math.random() * 10000 - 5000; + min[1] = Math.random() * 10000 - 5000; + max[0] = min[0] + Math.random() * 1000; + max[1] = min[1] + Math.random() * 1000; - Item it = new Item(min, max, i); - t.insert(min, max, it); - items.add(it); - } + Item it = new Item(min, max, i); + t.insert(min, max, it); + items.add(it); + } - Assert.assertEquals(numItems, t.size()); + Assert.assertEquals(numItems, t.size()); - for (Item it : items) - t.remove(it.min, it.max, it); + for (Item it : items) + t.remove(it.min, it.max, it); - Assert.assertEquals(0, t.size()); - } + Assert.assertEquals(0, t.size()); + } - @Test - public void shouldWork3() { - RTree t = new RTree(); - double[] min = { 0, 0 }; - double[] max = { 0, 0 }; + @Test + public void shouldWork3() { + RTree t = new RTree(); + double[] min = {0, 0}; + double[] max = {0, 0}; - ArrayList items = new ArrayList(); + ArrayList items = new ArrayList(); - for (int i = 0; i < 1000; i++) { - min[0] = Math.random() * 10000 - 5000; - min[1] = Math.random() * 10000 - 5000; - max[0] = min[0] + Math.random() * 1000; - max[1] = min[1] + Math.random() * 1000; + for (int i = 0; i < 1000; i++) { + min[0] = Math.random() * 10000 - 5000; + min[1] = Math.random() * 10000 - 5000; + max[0] = min[0] + Math.random() * 1000; + max[1] = min[1] + Math.random() * 1000; - Item it = new Item(min, max, i); - t.insert(min, max, it); - items.add(it); - } + Item it = new Item(min, max, i); + t.insert(min, max, it); + items.add(it); + } - int cnt = 0; + int cnt = 0; - for (@SuppressWarnings("unused") - Item it : t) { - //System.out.println(it.val); - cnt++; - } + for (@SuppressWarnings("unused") + Item it : t) { + //System.out.println(it.val); + cnt++; + } - Assert.assertEquals(1000, cnt); + Assert.assertEquals(1000, cnt); - Assert.assertEquals(1000, t.size()); + Assert.assertEquals(1000, t.size()); - } + } - public static void main(String[] args) { - RTreeTest t = new RTreeTest(); - t.shouldWork2(); - } + public static void main(String[] args) { + RTreeTest t = new RTreeTest(); + t.shouldWork2(); + } } diff --git a/vtm-tests/test/org/oscim/utils/pool/InlistTest.java b/vtm-tests/test/org/oscim/utils/pool/InlistTest.java index 4634635a..603017aa 100644 --- a/vtm-tests/test/org/oscim/utils/pool/InlistTest.java +++ b/vtm-tests/test/org/oscim/utils/pool/InlistTest.java @@ -1,154 +1,156 @@ package org.oscim.utils.pool; -import static java.lang.System.out; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import org.junit.Assert; import org.junit.Test; import org.oscim.utils.pool.Inlist.List; +import static java.lang.System.out; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + public class InlistTest { - @Test - public void shouldWork() { - List list = new List(); + @Test + public void shouldWork() { + List list = new List(); - list.reverse(); - assertNull(list.pop()); + list.reverse(); + assertNull(list.pop()); - list.push(new Thing(1)); - list.push(new Thing(2)); - list.push(new Thing(3)); - list.push(new Thing(4)); - list.push(new Thing(5)); + list.push(new Thing(1)); + list.push(new Thing(2)); + list.push(new Thing(3)); + list.push(new Thing(4)); + list.push(new Thing(5)); /* iterate items */ - int i = 5; - for (Thing it : list) - assertEquals(it.value, i--); + int i = 5; + for (Thing it : list) + assertEquals(it.value, i--); - assertEquals(i, 0); + assertEquals(i, 0); /* iterate with insertion order */ - list.reverse(); - i = 1; - for (Thing it : list) - assertEquals(it.value, i++); + list.reverse(); + i = 1; + for (Thing it : list) + assertEquals(it.value, i++); - assertEquals(i, 6); + assertEquals(i, 6); - list.reverse(); + list.reverse(); - List list2 = new List(); + List list2 = new List(); /* pop list and append to list2 */ - for (int j = 5; j > 0; j--) { - Thing t = list.pop(); - assertEquals(t.value, j); - Assert.assertNull(t.next); + for (int j = 5; j > 0; j--) { + Thing t = list.pop(); + assertEquals(t.value, j); + Assert.assertNull(t.next); - list2.append(t); - } + list2.append(t); + } /* check nothing to iterate */ - for (Thing t : list) - assert (t == null && t != null); + for (Thing t : list) + assert (t == null && t != null); - assertNull(list.pop()); - assertNull(list.head()); + assertNull(list.pop()); + assertNull(list.head()); - list.push(new Thing(6)); + list.push(new Thing(6)); /* move items from list2 to list */ - list.appendList(list2.clear()); + list.appendList(list2.clear()); - assertNull(list2.head()); - assertNull(list2.pop()); + assertNull(list2.head()); + assertNull(list2.pop()); - list.reverse(); + list.reverse(); - list.push(new Thing(0)); - i = 0; - for (Thing t : list) - assertEquals(t.value, i++); + list.push(new Thing(0)); + i = 0; + for (Thing t : list) + assertEquals(t.value, i++); - assertEquals(i, 7); - } + assertEquals(i, 7); + } - @Test - public void shouldRemoveFirstInIterator() { - List list = new List(); - list.push(new Thing(1)); - list.push(new Thing(2)); - list.push(new Thing(3)); - list.push(new Thing(4)); - list.push(new Thing(5)); + @Test + public void shouldRemoveFirstInIterator() { + List list = new List(); + list.push(new Thing(1)); + list.push(new Thing(2)); + list.push(new Thing(3)); + list.push(new Thing(4)); + list.push(new Thing(5)); - out.println("\n shouldRemoveFirstInIterator"); + out.println("\n shouldRemoveFirstInIterator"); - int cnt = 5; - for (Thing t : list) { - list.remove(); - cnt--; - assertEquals(cnt, list.size()); - } - } + int cnt = 5; + for (Thing t : list) { + list.remove(); + cnt--; + assertEquals(cnt, list.size()); + } + } - @Test - public void shouldRemoveSomeInIterator() { - List list = new List(); - list.push(new Thing(1)); - list.push(new Thing(2)); - list.push(new Thing(3)); - list.push(new Thing(4)); - list.push(new Thing(5)); - list.push(new Thing(6)); - out.println("\n shouldRemoveSomeInIterator"); + @Test + public void shouldRemoveSomeInIterator() { + List list = new List(); + list.push(new Thing(1)); + list.push(new Thing(2)); + list.push(new Thing(3)); + list.push(new Thing(4)); + list.push(new Thing(5)); + list.push(new Thing(6)); + out.println("\n shouldRemoveSomeInIterator"); - int pos = 0; - for (Thing t : list) { - if (pos++ % 2 == 0) { - out.println(pos + " val:" + t.value); - list.remove(); - } - } + int pos = 0; + for (Thing t : list) { + if (pos++ % 2 == 0) { + out.println(pos + " val:" + t.value); + list.remove(); + } + } - assertEquals(3, list.size()); + assertEquals(3, list.size()); - for (Thing t : list) { - out.println(t.value); - } - } + for (Thing t : list) { + out.println(t.value); + } + } - @Test - public void shouldRemoveLastInIterator() { - List list = new List(); - list.append(new Thing(1)); - list.append(new Thing(2)); - out.println("\n shouldRemoveLastInIterator"); + @Test + public void shouldRemoveLastInIterator() { + List list = new List(); + list.append(new Thing(1)); + list.append(new Thing(2)); + out.println("\n shouldRemoveLastInIterator"); - int pos = 0; - for (Thing t : list) { - if (pos++ == 1) { - out.println(pos + " val:" + t.value); - list.remove(); - } - } + int pos = 0; + for (Thing t : list) { + if (pos++ == 1) { + out.println(pos + " val:" + t.value); + list.remove(); + } + } - assertEquals(1, list.size()); + assertEquals(1, list.size()); - for (Thing t : list) { - out.println(t.value); - } - } + for (Thing t : list) { + out.println(t.value); + } + } - static class Thing extends Inlist { - final int value; + static class Thing extends Inlist { + final int value; - public Thing(int val) { - value = val; - } - }; + public Thing(int val) { + value = val; + } + } + + ; } diff --git a/vtm-themes/icons/maki/atlas.xml b/vtm-themes/icons/maki/atlas.xml index 8558ae1d..ee786868 100644 --- a/vtm-themes/icons/maki/atlas.xml +++ b/vtm-themes/icons/maki/atlas.xml @@ -92,4 +92,4 @@ - \ No newline at end of file + diff --git a/vtm-themes/icons/osm/osm.xml b/vtm-themes/icons/osm/osm.xml index 89a8bc69..c8d7de76 100644 --- a/vtm-themes/icons/osm/osm.xml +++ b/vtm-themes/icons/osm/osm.xml @@ -1,43 +1,42 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vtm-themes/resources/assets/styles/default.xml b/vtm-themes/resources/assets/styles/default.xml index 4c584413..8eb3681d 100644 --- a/vtm-themes/resources/assets/styles/default.xml +++ b/vtm-themes/resources/assets/styles/default.xml @@ -1,1258 +1,1283 @@ - + - - + + - + - + - + - + - + - - - + + + - + - - + + - - + + - - + + - + - + - - + + - - - + + + - - + + - - + + - - + + - - - - - + + + + + - - - - - - - - - - - - + + + + + + + + + + + + - - - - - + + + + + - - + + - - - - + + + + - - + + - - - + + + - - - + + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - + + - - - - - - - - - - - + - - - - + - - - - - - + + + + + + + + + + + + + - - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + - - + + + + + + + - - - - - - - - - + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + diff --git a/vtm-themes/resources/assets/styles/newtron.xml b/vtm-themes/resources/assets/styles/newtron.xml index 42873680..e259881f 100644 --- a/vtm-themes/resources/assets/styles/newtron.xml +++ b/vtm-themes/resources/assets/styles/newtron.xml @@ -1,1357 +1,1367 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - + + - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + highway + + - - - + historic + + house numbers + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + place + + + - + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + railway + + + + - + + + + + + + + + + + --> - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - \ No newline at end of file + diff --git a/vtm-themes/resources/assets/styles/osmarender.xml b/vtm-themes/resources/assets/styles/osmarender.xml index 2f5b22a8..b2c57ecc 100644 --- a/vtm-themes/resources/assets/styles/osmarender.xml +++ b/vtm-themes/resources/assets/styles/osmarender.xml @@ -1,1340 +1,1393 @@ - + - - - - - + + + + + - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - + + - - - - - - + + - - - - - - + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vtm-themes/resources/assets/styles/tronrender.xml b/vtm-themes/resources/assets/styles/tronrender.xml index 11edfff9..ffab2733 100644 --- a/vtm-themes/resources/assets/styles/tronrender.xml +++ b/vtm-themes/resources/assets/styles/tronrender.xml @@ -1,1347 +1,1360 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - + + - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + highway + + - - - + historic + + house numbers + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + place + + + - + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + railway + + + + + + + + + + - - - + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - \ No newline at end of file + diff --git a/vtm-themes/src/org/oscim/theme/VtmThemes.java b/vtm-themes/src/org/oscim/theme/VtmThemes.java index ff04a389..bea032c2 100644 --- a/vtm-themes/src/org/oscim/theme/VtmThemes.java +++ b/vtm-themes/src/org/oscim/theme/VtmThemes.java @@ -17,28 +17,28 @@ */ package org.oscim.theme; -import java.io.InputStream; - import org.oscim.backend.AssetAdapter; +import java.io.InputStream; + /** * Enumeration of all internal rendering themes. */ public enum VtmThemes implements ThemeFile { - DEFAULT("styles/default.xml"), - TRONRENDER("styles/tronrender.xml"), - NEWTRON("styles/newtron.xml"), - OSMARENDER("styles/osmarender.xml"); + DEFAULT("styles/default.xml"), + TRONRENDER("styles/tronrender.xml"), + NEWTRON("styles/newtron.xml"), + OSMARENDER("styles/osmarender.xml"); - private final String mPath; + private final String mPath; - private VtmThemes(String path) { - mPath = path; - } + private VtmThemes(String path) { + mPath = path; + } - @Override - public InputStream getRenderThemeAsStream() { - return AssetAdapter.readFileAsStream(mPath); - } + @Override + public InputStream getRenderThemeAsStream() { + return AssetAdapter.readFileAsStream(mPath); + } } diff --git a/vtm-web-app/src/main/webapp/WEB-INF/web.xml b/vtm-web-app/src/main/webapp/WEB-INF/web.xml index a0e8eb7f..954f87ca 100644 --- a/vtm-web-app/src/main/webapp/WEB-INF/web.xml +++ b/vtm-web-app/src/main/webapp/WEB-INF/web.xml @@ -1,10 +1,8 @@ - - - + + + diff --git a/vtm-web-app/src/org/oscim/web/VtmWebApp.gwt.xml b/vtm-web-app/src/org/oscim/web/VtmWebApp.gwt.xml index 9b776abf..5b6c922d 100644 --- a/vtm-web-app/src/org/oscim/web/VtmWebApp.gwt.xml +++ b/vtm-web-app/src/org/oscim/web/VtmWebApp.gwt.xml @@ -1,26 +1,26 @@ - - - - - - - - - - - - - - - - - + + - + + + + + + + + + + + + + + + + diff --git a/vtm-web-app/src/org/oscim/web/client/GwtLauncher.java b/vtm-web-app/src/org/oscim/web/client/GwtLauncher.java index dbe20666..903b0dde 100644 --- a/vtm-web-app/src/org/oscim/web/client/GwtLauncher.java +++ b/vtm-web-app/src/org/oscim/web/client/GwtLauncher.java @@ -16,59 +16,59 @@ */ package org.oscim.web.client; -import org.oscim.core.Tile; -import org.oscim.gdx.client.MapConfig; - import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.badlogic.gdx.backends.gwt.preloader.Preloader.PreloaderCallback; import com.badlogic.gdx.backends.gwt.preloader.Preloader.PreloaderState; +import org.oscim.core.Tile; +import org.oscim.gdx.client.MapConfig; + public class GwtLauncher extends GwtApplication { - @Override - public GwtApplicationConfiguration getConfig() { + @Override + public GwtApplicationConfiguration getConfig() { - GwtApplicationConfiguration cfg = - new GwtApplicationConfiguration(getWindowWidth(), - getWindowHeight()); + GwtApplicationConfiguration cfg = + new GwtApplicationConfiguration(getWindowWidth(), + getWindowHeight()); - cfg.canvasId = "map-canvas"; - cfg.stencil = true; - cfg.fps = 120; + cfg.canvasId = "map-canvas"; + cfg.stencil = true; + cfg.fps = 120; - return cfg; - } + return cfg; + } - @Override - public ApplicationListener getApplicationListener() { - Tile.SIZE = MapConfig.get().getTileSize(); + @Override + public ApplicationListener getApplicationListener() { + Tile.SIZE = MapConfig.get().getTileSize(); - return new GwtMap(); - } + return new GwtMap(); + } - @Override - public PreloaderCallback getPreloaderCallback() { - return new PreloaderCallback() { + @Override + public PreloaderCallback getPreloaderCallback() { + return new PreloaderCallback() { - @Override - public void update(PreloaderState state) { - } + @Override + public void update(PreloaderState state) { + } - @Override - public void error(String file) { - //log.debug("error loading " + file); - } - }; - } + @Override + public void error(String file) { + //log.debug("error loading " + file); + } + }; + } - private static native int getWindowWidth() /*-{ - return $wnd.innerWidth; + private static native int getWindowWidth() /*-{ + return $wnd.innerWidth; }-*/; - private static native int getWindowHeight() /*-{ - return $wnd.innerHeight; + private static native int getWindowHeight() /*-{ + return $wnd.innerHeight; }-*/; } diff --git a/vtm-web-app/src/org/oscim/web/client/GwtMap.java b/vtm-web-app/src/org/oscim/web/client/GwtMap.java index 7978e016..0c52c878 100644 --- a/vtm-web-app/src/org/oscim/web/client/GwtMap.java +++ b/vtm-web-app/src/org/oscim/web/client/GwtMap.java @@ -16,6 +16,9 @@ */ package org.oscim.web.client; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.backends.gwt.GwtApplication; + import org.oscim.backend.CanvasAdapter; import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; @@ -39,112 +42,109 @@ import org.oscim.tiling.source.oscimap4.OSciMap4TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.backends.gwt.GwtApplication; - class GwtMap extends GdxMap { - static final Logger log = LoggerFactory.getLogger(GwtMap.class); + static final Logger log = LoggerFactory.getLogger(GwtMap.class); - SearchBox mSearchBox; + SearchBox mSearchBox; - @Override - public void create() { - MapConfig c = MapConfig.get(); + @Override + public void create() { + MapConfig c = MapConfig.get(); - // stroke text takes about 70% cpu time in firefox: - // https://bug568526.bugzilla.mozilla.org/attachment.cgi?id=447932 - // <- circle/stroke test 800ms firefox, 80ms chromium.. - // TODO use texture atlas to avoid drawing text-textures - if (GwtApplication.agentInfo().isLinux() && - GwtApplication.agentInfo().isFirefox()) - GwtGdxGraphics.NO_STROKE_TEXT = true; + // stroke text takes about 70% cpu time in firefox: + // https://bug568526.bugzilla.mozilla.org/attachment.cgi?id=447932 + // <- circle/stroke test 800ms firefox, 80ms chromium.. + // TODO use texture atlas to avoid drawing text-textures + if (GwtApplication.agentInfo().isLinux() && + GwtApplication.agentInfo().isFirefox()) + GwtGdxGraphics.NO_STROKE_TEXT = true; - GwtGdxGraphics.init(); - GdxAssets.init(""); - CanvasAdapter.textScale = 0.7f; + GwtGdxGraphics.init(); + GdxAssets.init(""); + CanvasAdapter.textScale = 0.7f; - GLAdapter.init((GL) Gdx.graphics.getGL20()); - GLAdapter.GDX_WEBGL_QUIRKS = true; - MapRenderer.setBackgroundColor(0xffffff); - //Gdx.app.setLogLevel(Application.LOG_DEBUG); + GLAdapter.init((GL) Gdx.graphics.getGL20()); + GLAdapter.GDX_WEBGL_QUIRKS = true; + MapRenderer.setBackgroundColor(0xffffff); + //Gdx.app.setLogLevel(Application.LOG_DEBUG); - super.create(); + super.create(); - MapPosition p = new MapPosition(); - p.setZoomLevel(c.getZoom()); - p.setPosition(c.getLatitude(), c.getLongitude()); + MapPosition p = new MapPosition(); + p.setZoomLevel(c.getZoom()); + p.setPosition(c.getLatitude(), c.getLongitude()); - MapUrl mapUrl = new MapUrl(mMap); - mapUrl.parseUrl(p); - mapUrl.scheduleRepeating(5000); + MapUrl mapUrl = new MapUrl(mMap); + mapUrl.parseUrl(p); + mapUrl.scheduleRepeating(5000); - mMap.setMapPosition(p); + mMap.setMapPosition(p); - String mapName = mapUrl.getParam("map"); - String themeName = mapUrl.getParam("theme"); + String mapName = mapUrl.getParam("map"); + String themeName = mapUrl.getParam("theme"); - VectorTileLayer l = null; + VectorTileLayer l = null; - if (mapName != null) { - BitmapTileSource ts; + if (mapName != null) { + BitmapTileSource ts; - if ("toner".equals(mapName)) - ts = DefaultSources.STAMEN_TONER.build(); - else if ("osm".equals(mapName)) - ts = DefaultSources.OPENSTREETMAP.build(); - else if ("watercolor".equals(mapName)) - ts = DefaultSources.STAMEN_WATERCOLOR.build(); - else if ("arcgis-shaded".equals(mapName)) - ts = DefaultSources.ARCGIS_RELIEF.build(); - else if ("imagico".equals(mapName)) - ts = DefaultSources.IMAGICO_LANDCOVER.build(); - else - ts = DefaultSources.STAMEN_TONER.build(); + if ("toner".equals(mapName)) + ts = DefaultSources.STAMEN_TONER.build(); + else if ("osm".equals(mapName)) + ts = DefaultSources.OPENSTREETMAP.build(); + else if ("watercolor".equals(mapName)) + ts = DefaultSources.STAMEN_WATERCOLOR.build(); + else if ("arcgis-shaded".equals(mapName)) + ts = DefaultSources.ARCGIS_RELIEF.build(); + else if ("imagico".equals(mapName)) + ts = DefaultSources.IMAGICO_LANDCOVER.build(); + else + ts = DefaultSources.STAMEN_TONER.build(); - mMap.setBaseMap(new BitmapTileLayer(mMap, ts)); - } else { - TileSource ts = new OSciMap4TileSource(); - l = mMap.setBaseMap(ts); + mMap.setBaseMap(new BitmapTileLayer(mMap, ts)); + } else { + TileSource ts = new OSciMap4TileSource(); + l = mMap.setBaseMap(ts); - if (themeName == null) { - mMap.setTheme(VtmThemes.DEFAULT); - } else { - if ("osmarender".equals(themeName)) - mMap.setTheme(VtmThemes.OSMARENDER); - else if ("tron".equals(themeName)) - mMap.setTheme(VtmThemes.TRONRENDER); - else if ("newtron".equals(themeName)) - mMap.setTheme(VtmThemes.NEWTRON); - else - mMap.setTheme(VtmThemes.DEFAULT); - } - } + if (themeName == null) { + mMap.setTheme(VtmThemes.DEFAULT); + } else { + if ("osmarender".equals(themeName)) + mMap.setTheme(VtmThemes.OSMARENDER); + else if ("tron".equals(themeName)) + mMap.setTheme(VtmThemes.TRONRENDER); + else if ("newtron".equals(themeName)) + mMap.setTheme(VtmThemes.NEWTRON); + else + mMap.setTheme(VtmThemes.DEFAULT); + } + } - boolean s3db = mapUrl.params.containsKey("s3db"); - if (s3db) { - TileSource ts = OSciMap4TileSource.builder() - .url("http://opensciencemap.org/tiles/s3db") - .zoomMin(16) - .zoomMax(16) - .build(); - mMap.layers().add(new S3DBLayer(mMap, ts)); - } - if (l != null) { - boolean nolabels = mapUrl.params.containsKey("nolabels"); - boolean nobuildings = mapUrl.params.containsKey("nobuildings"); + boolean s3db = mapUrl.params.containsKey("s3db"); + if (s3db) { + TileSource ts = OSciMap4TileSource.builder() + .url("http://opensciencemap.org/tiles/s3db") + .zoomMin(16) + .zoomMax(16) + .build(); + mMap.layers().add(new S3DBLayer(mMap, ts)); + } + if (l != null) { + boolean nolabels = mapUrl.params.containsKey("nolabels"); + boolean nobuildings = mapUrl.params.containsKey("nobuildings"); - if (!nobuildings && !s3db) - mMap.layers().add(new BuildingLayer(mMap, l)); + if (!nobuildings && !s3db) + mMap.layers().add(new BuildingLayer(mMap, l)); - if (!nolabels) - mMap.layers().add(new LabelLayer(mMap, l)); - } + if (!nolabels) + mMap.layers().add(new LabelLayer(mMap, l)); + } - mSearchBox = new SearchBox(mMap); + mSearchBox = new SearchBox(mMap); - } + } - @Override - protected void createLayers() { - } + @Override + protected void createLayers() { + } } diff --git a/vtm-web-app/src/org/oscim/web/client/SearchBox.java b/vtm-web-app/src/org/oscim/web/client/SearchBox.java index 40044c54..7b348e7a 100644 --- a/vtm-web-app/src/org/oscim/web/client/SearchBox.java +++ b/vtm-web-app/src/org/oscim/web/client/SearchBox.java @@ -16,17 +16,6 @@ */ package org.oscim.web.client; -import java.util.ArrayList; -import java.util.List; - -import org.oscim.core.BoundingBox; -import org.oscim.core.GeometryBuffer; -import org.oscim.core.MapPosition; -import org.oscim.layers.PathLayer; -import org.oscim.map.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; @@ -52,315 +41,326 @@ import com.google.gwt.view.client.ProvidesKey; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; +import org.oscim.core.BoundingBox; +import org.oscim.core.GeometryBuffer; +import org.oscim.core.MapPosition; +import org.oscim.layers.PathLayer; +import org.oscim.map.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + /** * Entry point classes define onModuleLoad(). */ public class SearchBox { - protected static final Logger log = LoggerFactory.getLogger(SearchBox.class); + protected static final Logger log = LoggerFactory.getLogger(SearchBox.class); - private static final String NOMINATIM_GLOBAL = "http://nominatim.openstreetmap.org/search?polygon_text=1&addressdetails=0&format=json&limit=25&q="; + private static final String NOMINATIM_GLOBAL = "http://nominatim.openstreetmap.org/search?polygon_text=1&addressdetails=0&format=json&limit=25&q="; - interface PoiData { - public static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { - @Override - public Object getKey(PoiData item) { - return item == null ? null : item.getId(); - } - }; + interface PoiData { + public static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(PoiData item) { + return item == null ? null : item.getId(); + } + }; - String getId(); + String getId(); - String getName(); + String getName(); - double getLatitude(); + double getLatitude(); - double getLongitude(); + double getLongitude(); - String getIcon(); + String getIcon(); - BoundingBox getBoundingBox(); - } + BoundingBox getBoundingBox(); + } - final static class NominatimData extends JavaScriptObject implements - PoiData { + final static class NominatimData extends JavaScriptObject implements + PoiData { - protected NominatimData() { - } + protected NominatimData() { + } - final static class BBox extends JsArrayNumber { - protected BBox() { - } - } + final static class BBox extends JsArrayNumber { + protected BBox() { + } + } - final static class Polygon extends JsArray { - protected Polygon() { - } + final static class Polygon extends JsArray { + protected Polygon() { + } - } + } - @Override - public final native String getId() - /*-{ - return this.osm_id; + @Override + public final native String getId() + /*-{ + return this.osm_id; }-*/; - public final native String name() /*-{ + public final native String name() /*-{ return this.display_name; }-*/; - public final native BBox getBBox() /*-{ + public final native BBox getBBox() /*-{ return this.boundingbox }-*/; - public final native String getWkt() /*-{ + public final native String getWkt() /*-{ return this.geotext; }-*/; - private final native String latitude() /*-{ + private final native String latitude() /*-{ return this.lat; }-*/; - private final native String longitude() /*-{ + private final native String longitude() /*-{ return this.lon; }-*/; - public final native String getIcon() /*-{ + public final native String getIcon() /*-{ return this.icon; }-*/; - @Override - public double getLatitude() { - try { - return Double.parseDouble(latitude()); - } catch (Exception e) { + @Override + public double getLatitude() { + try { + return Double.parseDouble(latitude()); + } catch (Exception e) { - } - return 0; - } + } + return 0; + } - @Override - public double getLongitude() { - try { - return Double.parseDouble(longitude()); - } catch (Exception e) { - } - return 0; - } + @Override + public double getLongitude() { + try { + return Double.parseDouble(longitude()); + } catch (Exception e) { + } + return 0; + } - @Override - public BoundingBox getBoundingBox() { - if (getBBox() != null) { - BBox b = getBBox(); - return new BoundingBox(b.get(0), b.get(2), b.get(1), b.get(3)); - } - return null; - } + @Override + public BoundingBox getBoundingBox() { + if (getBBox() != null) { + BBox b = getBBox(); + return new BoundingBox(b.get(0), b.get(2), b.get(1), b.get(3)); + } + return null; + } - @Override - public String getName() { - String[] n = name().split(", "); - if (n != null && n.length > 2) - return n[0] + ", " + n[1] + " " + n[2]; - else if (n != null && n.length > 1) - return n[0] + ", " + n[1]; + @Override + public String getName() { + String[] n = name().split(", "); + if (n != null && n.length > 2) + return n[0] + ", " + n[1] + " " + n[2]; + else if (n != null && n.length > 1) + return n[0] + ", " + n[1]; - return name(); - } - } + return name(); + } + } - class PoiCell extends AbstractCell { + class PoiCell extends AbstractCell { - @Override - public void render(com.google.gwt.cell.client.Cell.Context context, - PoiData value, SafeHtmlBuilder sb) { + @Override + public void render(com.google.gwt.cell.client.Cell.Context context, + PoiData value, SafeHtmlBuilder sb) { - // Value can be null, so do a null check.. - if (value == null) { - return; - } + // Value can be null, so do a null check.. + if (value == null) { + return; + } - sb.appendHtmlConstant(""); + sb.appendHtmlConstant("
"); - if (value.getIcon() != null) { - // Add the contact image. - sb.appendHtmlConstant(""); - } + if (value.getIcon() != null) { + // Add the contact image. + sb.appendHtmlConstant(""); + } - // Add the name and address. - sb.appendHtmlConstant(""); - //sb.appendEscaped(""); - sb.appendHtmlConstant("
"); - sb.appendHtmlConstant(""); - sb.appendHtmlConstant("
"); + sb.appendHtmlConstant(""); + sb.appendHtmlConstant(""); - sb.appendEscaped(value.getName()); - sb.appendHtmlConstant("
" + value.getId()+ "
"); - sb.appendHtmlConstant(""); - } - } + // Add the name and address. + sb.appendHtmlConstant(""); + sb.appendEscaped(value.getName()); + sb.appendHtmlConstant(""); + //sb.appendEscaped("" + value.getId()+ ""); + sb.appendHtmlConstant(""); + sb.appendHtmlConstant(""); + } + } - public SearchBox(final Map map) { - final Button searchButton = new Button("Search"); - final TextBox searchField = new TextBox(); - //searchField.setText("Bremen"); - final PathLayer mOverlay = new PathLayer(map, 0xCC0000FF); - map.layers().add(mOverlay); + public SearchBox(final Map map) { + final Button searchButton = new Button("Search"); + final TextBox searchField = new TextBox(); + //searchField.setText("Bremen"); + final PathLayer mOverlay = new PathLayer(map, 0xCC0000FF); + map.layers().add(mOverlay); - // We can add style names to widgets - searchButton.addStyleName("sendButton"); + // We can add style names to widgets + searchButton.addStyleName("sendButton"); - RootPanel.get("nameFieldContainer").add(searchField); - RootPanel.get("sendButtonContainer").add(searchButton); + RootPanel.get("nameFieldContainer").add(searchField); + RootPanel.get("sendButtonContainer").add(searchButton); - // Focus the cursor on the name field when the app loads - searchField.setFocus(true); - searchField.selectAll(); + // Focus the cursor on the name field when the app loads + searchField.setFocus(true); + searchField.selectAll(); - // Create a cell to render each value in the list. - PoiCell poiCell = new PoiCell(); + // Create a cell to render each value in the list. + PoiCell poiCell = new PoiCell(); - // Create a CellList that uses the cell. - final CellList cellList = new CellList(poiCell, - PoiData.KEY_PROVIDER); + // Create a CellList that uses the cell. + final CellList cellList = new CellList(poiCell, + PoiData.KEY_PROVIDER); - final SingleSelectionModel selectionModel = new SingleSelectionModel( - PoiData.KEY_PROVIDER); - cellList.setSelectionModel(selectionModel); + final SingleSelectionModel selectionModel = new SingleSelectionModel( + PoiData.KEY_PROVIDER); + cellList.setSelectionModel(selectionModel); - final ScrollPanel scroller = new ScrollPanel(cellList); - RootPanel.get("listContainer").add(scroller); + final ScrollPanel scroller = new ScrollPanel(cellList); + RootPanel.get("listContainer").add(scroller); - scroller.setSize("350px", "300px"); + scroller.setSize("350px", "300px"); - RootPanel.get("search").getElement().getStyle().setVisibility(Visibility.VISIBLE); - scroller.setVisible(false); + RootPanel.get("search").getElement().getStyle().setVisibility(Visibility.VISIBLE); + scroller.setVisible(false); - searchField.addFocusHandler(new FocusHandler() { - @Override - public void onFocus(FocusEvent event) { - scroller.setVisible(true); - } - }); - selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { - public void onSelectionChange(SelectionChangeEvent event) { - final PoiData d = selectionModel.getSelectedObject(); + searchField.addFocusHandler(new FocusHandler() { + @Override + public void onFocus(FocusEvent event) { + scroller.setVisible(true); + } + }); + selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { + public void onSelectionChange(SelectionChangeEvent event) { + final PoiData d = selectionModel.getSelectedObject(); - mOverlay.clearPath(); + mOverlay.clearPath(); - //log.debug("selected " + d.getName() + " " + d.getLatitude() + " " - // + d.getLongitude()); + //log.debug("selected " + d.getName() + " " + d.getLatitude() + " " + // + d.getLongitude()); - BoundingBox b = d.getBoundingBox(); - if (b != null) { - if (b.maxLatitudeE6 - b.minLatitudeE6 < 100 && - b.maxLongitudeE6 - b.minLongitudeE6 < 100) - // for small bbox use zoom=16 to get an overview - map.animator().animateTo(500, b.getCenterPoint(), 1 << 16, false); - else - map.animator().animateTo(b); - if (d instanceof NominatimData && ((NominatimData) d).getWkt() != null) { - String wkt = ((NominatimData) d).getWkt(); + BoundingBox b = d.getBoundingBox(); + if (b != null) { + if (b.maxLatitudeE6 - b.minLatitudeE6 < 100 && + b.maxLongitudeE6 - b.minLongitudeE6 < 100) + // for small bbox use zoom=16 to get an overview + map.animator().animateTo(500, b.getCenterPoint(), 1 << 16, false); + else + map.animator().animateTo(b); + if (d instanceof NominatimData && ((NominatimData) d).getWkt() != null) { + String wkt = ((NominatimData) d).getWkt(); - WKTReader r = new WKTReader(); - GeometryBuffer g = new GeometryBuffer(1024, 10); - try { - r.parse(wkt, g); - } catch (Exception e) { - log.debug(wkt); - } - //FIXME mOverlay.setGeom(g); + WKTReader r = new WKTReader(); + GeometryBuffer g = new GeometryBuffer(1024, 10); + try { + r.parse(wkt, g); + } catch (Exception e) { + log.debug(wkt); + } + //FIXME mOverlay.setGeom(g); - //log.debug("add polygon " + p.length()); - } else { - mOverlay.addPoint(b.maxLatitudeE6, b.minLongitudeE6); - mOverlay.addPoint(b.maxLatitudeE6, b.maxLongitudeE6); - mOverlay.addPoint(b.minLatitudeE6, b.maxLongitudeE6); - mOverlay.addPoint(b.minLatitudeE6, b.minLongitudeE6); - mOverlay.addPoint(b.maxLatitudeE6, b.minLongitudeE6); - } - // hide overlay after 5 seconds - map.postDelayed(new Runnable() { - @Override - public void run() { - mOverlay.clearPath(); - } - }, 5000); - } else { - MapPosition pos = new MapPosition(); + //log.debug("add polygon " + p.length()); + } else { + mOverlay.addPoint(b.maxLatitudeE6, b.minLongitudeE6); + mOverlay.addPoint(b.maxLatitudeE6, b.maxLongitudeE6); + mOverlay.addPoint(b.minLatitudeE6, b.maxLongitudeE6); + mOverlay.addPoint(b.minLatitudeE6, b.minLongitudeE6); + mOverlay.addPoint(b.maxLatitudeE6, b.minLongitudeE6); + } + // hide overlay after 5 seconds + map.postDelayed(new Runnable() { + @Override + public void run() { + mOverlay.clearPath(); + } + }, 5000); + } else { + MapPosition pos = new MapPosition(); - map.viewport().setTilt(0); - map.viewport().setRotation(0); + map.viewport().setTilt(0); + map.viewport().setRotation(0); - pos.setZoomLevel(13); - pos.setPosition(d.getLatitude(), d.getLongitude()); - map.setMapPosition(pos); - } + pos.setZoomLevel(13); + pos.setPosition(d.getLatitude(), d.getLongitude()); + map.setMapPosition(pos); + } - scroller.setVisible(false); - } + scroller.setVisible(false); + } - }); + }); - // Create a handler for the sendButton and nameField - class MyHandler implements ClickHandler, KeyUpHandler { + // Create a handler for the sendButton and nameField + class MyHandler implements ClickHandler, KeyUpHandler { - /** - * Fired when the user clicks on the sendButton. - */ - public void onClick(ClickEvent event) { - sendRequest(); - } + /** + * Fired when the user clicks on the sendButton. + */ + public void onClick(ClickEvent event) { + sendRequest(); + } - /** - * Fired when the user types in the nameField. - */ - public void onKeyUp(KeyUpEvent event) { - if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { - sendRequest(); - } - } + /** + * Fired when the user types in the nameField. + */ + public void onKeyUp(KeyUpEvent event) { + if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { + sendRequest(); + } + } - /** - * Send the name from the nameField to the server and wait for a - * response. - */ - private void sendRequest() { - String textToServer = searchField.getText(); - searchButton.setEnabled(false); + /** + * Send the name from the nameField to the server and wait for a + * response. + */ + private void sendRequest() { + String textToServer = searchField.getText(); + searchButton.setEnabled(false); - String url = URL - .encode(NOMINATIM_GLOBAL - + textToServer); + String url = URL + .encode(NOMINATIM_GLOBAL + + textToServer); - JsonpRequestBuilder builder = new JsonpRequestBuilder(); - builder.setCallbackParam("json_callback"); - builder.requestObject(url, new AsyncCallback>() { - public void onFailure(Throwable caught) { - log.debug("request failed"); - searchButton.setEnabled(true); - } + JsonpRequestBuilder builder = new JsonpRequestBuilder(); + builder.setCallbackParam("json_callback"); + builder.requestObject(url, new AsyncCallback>() { + public void onFailure(Throwable caught) { + log.debug("request failed"); + searchButton.setEnabled(true); + } - public void onSuccess(JsArray data) { - List items = new ArrayList(); - for (int i = 0, n = data.length(); i < n; i++) { - NominatimData d = data.get(i); - items.add(d); - } + public void onSuccess(JsArray data) { + List items = new ArrayList(); + for (int i = 0, n = data.length(); i < n; i++) { + NominatimData d = data.get(i); + items.add(d); + } - cellList.setRowCount(items.size(), true); - cellList.setRowData(0, items); - scroller.setVisible(true); - searchButton.setEnabled(true); - } - }); - } - } + cellList.setRowCount(items.size(), true); + cellList.setRowData(0, items); + scroller.setVisible(true); + searchButton.setEnabled(true); + } + }); + } + } - // Add a handler to send the name to the server - MyHandler handler = new MyHandler(); - searchButton.addClickHandler(handler); - searchField.addKeyUpHandler(handler); + // Add a handler to send the name to the server + MyHandler handler = new MyHandler(); + searchButton.addClickHandler(handler); + searchField.addKeyUpHandler(handler); - } + } } diff --git a/vtm-web-app/src/org/oscim/web/client/WKTReader.java b/vtm-web-app/src/org/oscim/web/client/WKTReader.java index a7bd01de..11189852 100644 --- a/vtm-web-app/src/org/oscim/web/client/WKTReader.java +++ b/vtm-web-app/src/org/oscim/web/client/WKTReader.java @@ -19,222 +19,222 @@ package org.oscim.web.client; import org.oscim.core.GeometryBuffer; public class WKTReader { - private final static String POINT = "POINT"; - private final static String LINE = "LINESTRING"; - private final static String POLY = "POLYGON"; - private final static String MULTI = "MULTI"; + private final static String POINT = "POINT"; + private final static String LINE = "LINESTRING"; + private final static String POLY = "POLYGON"; + private final static String MULTI = "MULTI"; - private final static int SKIP_POINT = POINT.length(); - private final static int SKIP_LINE = LINE.length(); - private final static int SKIP_POLY = POLY.length(); - private final static int SKIP_MULTI = MULTI.length(); + private final static int SKIP_POINT = POINT.length(); + private final static int SKIP_LINE = LINE.length(); + private final static int SKIP_POLY = POLY.length(); + private final static int SKIP_MULTI = MULTI.length(); - public void parse(String wkt, GeometryBuffer geom) throws Exception { - // return position. - int[] pos = new int[] { 0 }; + public void parse(String wkt, GeometryBuffer geom) throws Exception { + // return position. + int[] pos = new int[]{0}; - int len = wkt.length(); + int len = wkt.length(); - if (wkt.startsWith(POINT, pos[0])) { - pos[0] += SKIP_POINT; - geom.startPoints(); - ensure(wkt, pos, '('); - parsePoint(geom, wkt, len, pos); - ensure(wkt, pos, ')'); - } else if (wkt.startsWith(LINE, pos[0])) { - pos[0] += SKIP_LINE; - geom.startLine(); + if (wkt.startsWith(POINT, pos[0])) { + pos[0] += SKIP_POINT; + geom.startPoints(); + ensure(wkt, pos, '('); + parsePoint(geom, wkt, len, pos); + ensure(wkt, pos, ')'); + } else if (wkt.startsWith(LINE, pos[0])) { + pos[0] += SKIP_LINE; + geom.startLine(); - parseLine(geom, wkt, len, pos); + parseLine(geom, wkt, len, pos); - } else if (wkt.startsWith(POLY, pos[0])) { - pos[0] += SKIP_POLY; - geom.startPolygon(); + } else if (wkt.startsWith(POLY, pos[0])) { + pos[0] += SKIP_POLY; + geom.startPolygon(); - parsePoly(geom, wkt, len, pos); + parsePoly(geom, wkt, len, pos); - } else if (wkt.startsWith(MULTI, pos[0])) { - pos[0] += SKIP_MULTI; + } else if (wkt.startsWith(MULTI, pos[0])) { + pos[0] += SKIP_MULTI; - if (wkt.startsWith(POINT, pos[0])) { - pos[0] += SKIP_POINT; - geom.startPoints(); - ensure(wkt, pos, '('); - parsePoint(geom, wkt, len, pos); - while (wkt.charAt(pos[0]) == ',') { - pos[0]++; - parsePoint(geom, wkt, len, pos); - } - ensure(wkt, pos, ')'); + if (wkt.startsWith(POINT, pos[0])) { + pos[0] += SKIP_POINT; + geom.startPoints(); + ensure(wkt, pos, '('); + parsePoint(geom, wkt, len, pos); + while (wkt.charAt(pos[0]) == ',') { + pos[0]++; + parsePoint(geom, wkt, len, pos); + } + ensure(wkt, pos, ')'); - } else if (wkt.startsWith(LINE, pos[0])) { - pos[0] += SKIP_LINE; - geom.startLine(); - ensure(wkt, pos, '('); - parseLine(geom, wkt, len, pos); - while (wkt.charAt(pos[0]) == ',') { - pos[0]++; - geom.startLine(); - parseLine(geom, wkt, len, pos); - } - ensure(wkt, pos, ')'); + } else if (wkt.startsWith(LINE, pos[0])) { + pos[0] += SKIP_LINE; + geom.startLine(); + ensure(wkt, pos, '('); + parseLine(geom, wkt, len, pos); + while (wkt.charAt(pos[0]) == ',') { + pos[0]++; + geom.startLine(); + parseLine(geom, wkt, len, pos); + } + ensure(wkt, pos, ')'); - } else if (wkt.startsWith(POLY, pos[0])) { - pos[0] += SKIP_POLY; - geom.startPolygon(); - ensure(wkt, pos, '('); - parsePoly(geom, wkt, len, pos); - while (wkt.charAt(pos[0]) == ',') { - pos[0]++; - geom.startPolygon(); - parsePoly(geom, wkt, len, pos); - } - ensure(wkt, pos, ')'); - } else - throw new Exception("usupported geometry "); - } else - throw new Exception("usupported geometry "); - } + } else if (wkt.startsWith(POLY, pos[0])) { + pos[0] += SKIP_POLY; + geom.startPolygon(); + ensure(wkt, pos, '('); + parsePoly(geom, wkt, len, pos); + while (wkt.charAt(pos[0]) == ',') { + pos[0]++; + geom.startPolygon(); + parsePoly(geom, wkt, len, pos); + } + ensure(wkt, pos, ')'); + } else + throw new Exception("usupported geometry "); + } else + throw new Exception("usupported geometry "); + } - private static void ensure(String wkt, int[] pos, char c) throws Exception { - if (wkt.charAt(pos[0]) != c) - throw new Exception(); + private static void ensure(String wkt, int[] pos, char c) throws Exception { + if (wkt.charAt(pos[0]) != c) + throw new Exception(); - pos[0]++; - } + pos[0]++; + } - private static void parsePoly(GeometryBuffer geom, String wkt, int len, int[] adv) - throws Exception { - // outer ring - ensure(wkt, adv, '('); - parseLine(geom, wkt, len, adv); + private static void parsePoly(GeometryBuffer geom, String wkt, int len, int[] adv) + throws Exception { + // outer ring + ensure(wkt, adv, '('); + parseLine(geom, wkt, len, adv); - while (wkt.charAt(adv[0]) == ',') { - adv[0]++; - geom.startHole(); - parseLine(geom, wkt, len, adv); - } - ensure(wkt, adv, ')'); - } + while (wkt.charAt(adv[0]) == ',') { + adv[0]++; + geom.startHole(); + parseLine(geom, wkt, len, adv); + } + ensure(wkt, adv, ')'); + } - private static void parseLine(GeometryBuffer geom, String wkt, int len, int[] adv) - throws Exception { - ensure(wkt, adv, '('); + private static void parseLine(GeometryBuffer geom, String wkt, int len, int[] adv) + throws Exception { + ensure(wkt, adv, '('); - parsePoint(geom, wkt, len, adv); - while (wkt.charAt(adv[0]) == ',') { - adv[0]++; - parsePoint(geom, wkt, len, adv); - } - ensure(wkt, adv, ')'); - } + parsePoint(geom, wkt, len, adv); + while (wkt.charAt(adv[0]) == ',') { + adv[0]++; + parsePoint(geom, wkt, len, adv); + } + ensure(wkt, adv, ')'); + } - private static void parsePoint(GeometryBuffer geom, String wkt, int len, int[] adv) { - float x = parseNumber(wkt, len, adv); + private static void parsePoint(GeometryBuffer geom, String wkt, int len, int[] adv) { + float x = parseNumber(wkt, len, adv); - // skip ' ' - adv[0]++; + // skip ' ' + adv[0]++; - float y = parseNumber(wkt, len, adv); + float y = parseNumber(wkt, len, adv); - geom.addPoint(x, y); - } + geom.addPoint(x, y); + } - static float parseNumber(String wkt, int len, int[] adv) { - int pos = adv[0]; + static float parseNumber(String wkt, int len, int[] adv) { + int pos = adv[0]; - boolean neg = false; - if (wkt.charAt(pos) == '-') { - neg = true; - pos++; - } + boolean neg = false; + if (wkt.charAt(pos) == '-') { + neg = true; + pos++; + } - float val = 0; - int pre = 0; - char c = 0; + float val = 0; + int pre = 0; + char c = 0; - for (; pos < len; pos++, pre++) { - c = wkt.charAt(pos); - if (c < '0' || c > '9') { - if (pre == 0) - throw new NumberFormatException("s " + c); + for (; pos < len; pos++, pre++) { + c = wkt.charAt(pos); + if (c < '0' || c > '9') { + if (pre == 0) + throw new NumberFormatException("s " + c); - break; - } - val = val * 10 + (int) (c - '0'); - } + break; + } + val = val * 10 + (int) (c - '0'); + } - if (pre == 0) - throw new NumberFormatException(); + if (pre == 0) + throw new NumberFormatException(); - if (c == '.') { - float div = 10; - for (pos++; pos < len; pos++) { - c = wkt.charAt(pos); - if (c < '0' || c > '9') - break; - val = val + ((int) (c - '0')) / div; - div *= 10; - } - } + if (c == '.') { + float div = 10; + for (pos++; pos < len; pos++) { + c = wkt.charAt(pos); + if (c < '0' || c > '9') + break; + val = val + ((int) (c - '0')) / div; + div *= 10; + } + } - if (c == 'e' || c == 'E') { - // advance 'e' - pos++; + if (c == 'e' || c == 'E') { + // advance 'e' + pos++; - // check direction - int dir = 1; - if (wkt.charAt(pos) == '-') { - dir = -1; - pos++; - } - // skip leading zeros - for (; pos < len; pos++) - if (wkt.charAt(pos) != '0') - break; + // check direction + int dir = 1; + if (wkt.charAt(pos) == '-') { + dir = -1; + pos++; + } + // skip leading zeros + for (; pos < len; pos++) + if (wkt.charAt(pos) != '0') + break; - int shift = 0; - for (pre = 0; pos < len; pos++, pre++) { - c = wkt.charAt(pos); - if (c < '0' || c > '9') { - // nothing after 'e' - if (pre == 0) - throw new NumberFormatException("e " + c); - break; - } - shift = shift * 10 + (int) (c - '0'); - } + int shift = 0; + for (pre = 0; pos < len; pos++, pre++) { + c = wkt.charAt(pos); + if (c < '0' || c > '9') { + // nothing after 'e' + if (pre == 0) + throw new NumberFormatException("e " + c); + break; + } + shift = shift * 10 + (int) (c - '0'); + } - // guess it's ok for sane values of E - if (dir > 0) { - while (shift-- > 0) - val *= 10; - } else { - while (shift-- > 0) - val /= 10; - } - } + // guess it's ok for sane values of E + if (dir > 0) { + while (shift-- > 0) + val *= 10; + } else { + while (shift-- > 0) + val /= 10; + } + } - adv[0] = pos; + adv[0] = pos; - return neg ? -val : val; - } + return neg ? -val : val; + } - // public static void main(String[] args) { - // WKTReader r = new WKTReader(); - // GeometryBuffer geom = new GeometryBuffer(10, 10); - // try { - // String wkt = "MULTIPOINT(0 0,1 0)"; - // r.parse(wkt, geom); - // for (int i = 0; i < geom.index.length; i++) { - // int len = geom.index[i]; - // if (len < 0) - // break; - // for (int p = 0; p < len; p += 2) - // System.out.println(len + ": " + geom.points[p] + "," + geom.points[p + 1]); - // } - // } catch (Exception e) { - // e.printStackTrace(); - // } - // } + // public static void main(String[] args) { + // WKTReader r = new WKTReader(); + // GeometryBuffer geom = new GeometryBuffer(10, 10); + // try { + // String wkt = "MULTIPOINT(0 0,1 0)"; + // r.parse(wkt, geom); + // for (int i = 0; i < geom.index.length; i++) { + // int len = geom.index[i]; + // if (len < 0) + // break; + // for (int p = 0; p < len; p += 2) + // System.out.println(len + ": " + geom.points[p] + "," + geom.points[p + 1]); + // } + // } catch (Exception e) { + // e.printStackTrace(); + // } + // } } diff --git a/vtm-web-app/war/index.html b/vtm-web-app/war/index.html index 074b952c..02b10b24 100644 --- a/vtm-web-app/war/index.html +++ b/vtm-web-app/war/index.html @@ -1,21 +1,21 @@ -vtm-gdx - + vtm-gdx + - - - - - - + + + + + + - + - + + -

- Source | map data © OpenStreetMap contributors | OpenScienceMap -
+
+ Source | map data © OpenStreetMap contributors | OpenScienceMap +
-
- -
+
+ +
- - - - - + + + + + + diff --git a/vtm-web-js/src/main/webapp/WEB-INF/web.xml b/vtm-web-js/src/main/webapp/WEB-INF/web.xml index a0e8eb7f..954f87ca 100644 --- a/vtm-web-js/src/main/webapp/WEB-INF/web.xml +++ b/vtm-web-js/src/main/webapp/WEB-INF/web.xml @@ -1,10 +1,8 @@ - - - + + + diff --git a/vtm-web-js/src/org/oscim/web/VtmWebJs.gwt.xml b/vtm-web-js/src/org/oscim/web/VtmWebJs.gwt.xml index a09700ba..cf963562 100644 --- a/vtm-web-js/src/org/oscim/web/VtmWebJs.gwt.xml +++ b/vtm-web-js/src/org/oscim/web/VtmWebJs.gwt.xml @@ -1,28 +1,28 @@ - + - + - - + + - - - - - + + + + + - - - - + + + + - + - - + + - + diff --git a/vtm-web-js/src/org/oscim/web/client/GwtLauncher.java b/vtm-web-js/src/org/oscim/web/client/GwtLauncher.java index 2fee4a67..3a383213 100644 --- a/vtm-web-js/src/org/oscim/web/client/GwtLauncher.java +++ b/vtm-web-js/src/org/oscim/web/client/GwtLauncher.java @@ -16,69 +16,69 @@ */ package org.oscim.web.client; -import org.oscim.core.Tile; -import org.oscim.gdx.client.MapConfig; -import org.timepedia.exporter.client.ExporterUtil; - import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.badlogic.gdx.backends.gwt.preloader.Preloader.PreloaderCallback; import com.badlogic.gdx.backends.gwt.preloader.Preloader.PreloaderState; +import org.oscim.core.Tile; +import org.oscim.gdx.client.MapConfig; +import org.timepedia.exporter.client.ExporterUtil; + public class GwtLauncher extends GwtApplication { - @Override - public void onModuleLoad() { - //GWT.create(GwtGdxMap.class); - //JsOverlays.init(); - ExporterUtil.exportAll(); + @Override + public void onModuleLoad() { + //GWT.create(GwtGdxMap.class); + //JsOverlays.init(); + ExporterUtil.exportAll(); - super.onModuleLoad(); - } + super.onModuleLoad(); + } - @Override - public GwtApplicationConfiguration getConfig() { + @Override + public GwtApplicationConfiguration getConfig() { - GwtApplicationConfiguration cfg = - new GwtApplicationConfiguration(getWindowWidth(), - getWindowHeight()); + GwtApplicationConfiguration cfg = + new GwtApplicationConfiguration(getWindowWidth(), + getWindowHeight()); - cfg.canvasId = "map-canvas"; - cfg.stencil = true; - cfg.fps = 120; + cfg.canvasId = "map-canvas"; + cfg.stencil = true; + cfg.fps = 120; - return cfg; - } + return cfg; + } - @Override - public ApplicationListener getApplicationListener() { - Tile.SIZE = MapConfig.get().getTileSize(); + @Override + public ApplicationListener getApplicationListener() { + Tile.SIZE = MapConfig.get().getTileSize(); - return new GwtMap(); - } + return new GwtMap(); + } - @Override - public PreloaderCallback getPreloaderCallback() { - return new PreloaderCallback() { + @Override + public PreloaderCallback getPreloaderCallback() { + return new PreloaderCallback() { - @Override - public void update(PreloaderState state) { - } + @Override + public void update(PreloaderState state) { + } - @Override - public void error(String file) { - //log.debug("error loading " + file); - } - }; - } + @Override + public void error(String file) { + //log.debug("error loading " + file); + } + }; + } - private static native int getWindowWidth() /*-{ - return $wnd.innerWidth; + private static native int getWindowWidth() /*-{ + return $wnd.innerWidth; }-*/; - private static native int getWindowHeight() /*-{ - return $wnd.innerHeight; + private static native int getWindowHeight() /*-{ + return $wnd.innerHeight; }-*/; } diff --git a/vtm-web-js/src/org/oscim/web/client/GwtMap.java b/vtm-web-js/src/org/oscim/web/client/GwtMap.java index f6902ce6..3b2a3c13 100644 --- a/vtm-web-js/src/org/oscim/web/client/GwtMap.java +++ b/vtm-web-js/src/org/oscim/web/client/GwtMap.java @@ -16,6 +16,9 @@ */ package org.oscim.web.client; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.backends.gwt.GwtApplication; + import org.oscim.backend.CanvasAdapter; import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; @@ -30,47 +33,44 @@ import org.oscim.web.js.JsMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.backends.gwt.GwtApplication; - public class GwtMap extends GdxMap { - static final Logger log = LoggerFactory.getLogger(GwtMap.class); + static final Logger log = LoggerFactory.getLogger(GwtMap.class); - @Override - public void create() { + @Override + public void create() { - GwtGdxGraphics.init(); - GdxAssets.init(""); - CanvasAdapter.textScale = 0.7f; - GLAdapter.init((GL) Gdx.graphics.getGL20()); - GLAdapter.GDX_WEBGL_QUIRKS = true; - MapRenderer.setBackgroundColor(0xffffff); + GwtGdxGraphics.init(); + GdxAssets.init(""); + CanvasAdapter.textScale = 0.7f; + GLAdapter.init((GL) Gdx.graphics.getGL20()); + GLAdapter.GDX_WEBGL_QUIRKS = true; + MapRenderer.setBackgroundColor(0xffffff); - JsMap.init(mMap); + JsMap.init(mMap); - if (GwtApplication.agentInfo().isLinux() && - GwtApplication.agentInfo().isFirefox()) - GwtGdxGraphics.NO_STROKE_TEXT = true; + if (GwtApplication.agentInfo().isLinux() && + GwtApplication.agentInfo().isFirefox()) + GwtGdxGraphics.NO_STROKE_TEXT = true; - MapConfig c = MapConfig.get(); - super.create(); + MapConfig c = MapConfig.get(); + super.create(); - MapPosition p = new MapPosition(); - p.setZoomLevel(c.getZoom()); - p.setPosition(c.getLatitude(), c.getLongitude()); + MapPosition p = new MapPosition(); + p.setZoomLevel(c.getZoom()); + p.setPosition(c.getLatitude(), c.getLongitude()); - MapUrl mapUrl = new MapUrl(mMap); - mapUrl.parseUrl(p); - mapUrl.scheduleRepeating(5000); - } + MapUrl mapUrl = new MapUrl(mMap); + mapUrl.parseUrl(p); + mapUrl.scheduleRepeating(5000); + } - private final native void createLayersN()/*-{ - $wnd.createLayers(); + private final native void createLayersN()/*-{ + $wnd.createLayers(); }-*/; - @Override - protected void createLayers() { - log.debug("<<< create layers >>>"); - createLayersN(); - } + @Override + protected void createLayers() { + log.debug("<<< create layers >>>"); + createLayersN(); + } } diff --git a/vtm-web-js/src/org/oscim/web/js/JsBitmapTileLayer.java b/vtm-web-js/src/org/oscim/web/js/JsBitmapTileLayer.java index bb080e37..5bc51add 100644 --- a/vtm-web-js/src/org/oscim/web/js/JsBitmapTileLayer.java +++ b/vtm-web-js/src/org/oscim/web/js/JsBitmapTileLayer.java @@ -11,12 +11,12 @@ import org.timepedia.exporter.client.ExportPackage; @Export("BitmapTileLayer") public class JsBitmapTileLayer extends BitmapTileLayer implements ExportOverlay { - public JsBitmapTileLayer(Map map, TileSource tileSource) { - super(map, tileSource); - } + public JsBitmapTileLayer(Map map, TileSource tileSource) { + super(map, tileSource); + } - // @ExportConstructor - // public static BitmapTileLayer constructor(Map map, TileSource tileSource) { - // return new JsBitmapTileLayer(map, tileSource); - // } + // @ExportConstructor + // public static BitmapTileLayer constructor(Map map, TileSource tileSource) { + // return new JsBitmapTileLayer(map, tileSource); + // } } diff --git a/vtm-web-js/src/org/oscim/web/js/JsBitmapTileSource.java b/vtm-web-js/src/org/oscim/web/js/JsBitmapTileSource.java index d8321f03..c993355b 100644 --- a/vtm-web-js/src/org/oscim/web/js/JsBitmapTileSource.java +++ b/vtm-web-js/src/org/oscim/web/js/JsBitmapTileSource.java @@ -11,17 +11,17 @@ import org.timepedia.exporter.client.ExportPackage; public class JsBitmapTileSource extends BitmapTileSource implements ExportOverlay { - public JsBitmapTileSource(String url, int zoomMin, int zoomMax) { - super(url, zoomMin, zoomMax); - } + public JsBitmapTileSource(String url, int zoomMin, int zoomMax) { + super(url, zoomMin, zoomMax); + } - @Override - public ITileDataSource getDataSource() { - return null; - } - // @ExportConstructor - // public static BitmapTileSource constructor(String url, int zoomMin, int zoomMax) { - // return new JsBitmapTileSource(url, zoomMin, zoomMax); - // } + @Override + public ITileDataSource getDataSource() { + return null; + } + // @ExportConstructor + // public static BitmapTileSource constructor(String url, int zoomMin, int zoomMax) { + // return new JsBitmapTileSource(url, zoomMin, zoomMax); + // } } diff --git a/vtm-web-js/src/org/oscim/web/js/JsMap.java b/vtm-web-js/src/org/oscim/web/js/JsMap.java index 2537b697..fed9416a 100644 --- a/vtm-web-js/src/org/oscim/web/js/JsMap.java +++ b/vtm-web-js/src/org/oscim/web/js/JsMap.java @@ -16,45 +16,45 @@ import org.timepedia.exporter.client.NoExport; @Export("map") public class JsMap implements Exportable { - static Map mMap; + static Map mMap; - @Export - public static Map map() { - return mMap; - } + @Export + public static Map map() { + return mMap; + } - @Export - public static Layers layers() { - return mMap.layers(); - } + @Export + public static Layers layers() { + return mMap.layers(); + } - @Export - public static boolean addLayer(Layer l) { - return mMap.layers().add(l); - } + @Export + public static boolean addLayer(Layer l) { + return mMap.layers().add(l); + } - @Export - public static boolean getPosition(MapPosition pos) { - return mMap.getMapPosition(pos); - } + @Export + public static boolean getPosition(MapPosition pos) { + return mMap.getMapPosition(pos); + } - @Export - public static void setPosition(MapPosition pos) { - mMap.setMapPosition(pos); - } + @Export + public static void setPosition(MapPosition pos) { + mMap.setMapPosition(pos); + } - @Export - public static IRenderTheme loadTheme(String theme) { - return ThemeLoader.load(VtmThemes.valueOf(theme)); - } + @Export + public static IRenderTheme loadTheme(String theme) { + return ThemeLoader.load(VtmThemes.valueOf(theme)); + } - @NoExport - public static void init(Map map) { - mMap = map; - } + @NoExport + public static void init(Map map) { + mMap = map; + } - // @ExportInstanceMethod("foo") - // public static String instanceMethod(Map instance, String surname) { - // return instance.getName() + "-" + surname; - // } + // @ExportInstanceMethod("foo") + // public static String instanceMethod(Map instance, String surname) { + // return instance.getName() + "-" + surname; + // } } diff --git a/vtm-web-js/src/org/oscim/web/js/JsOsmLanduseJsonTileSource.java b/vtm-web-js/src/org/oscim/web/js/JsOsmLanduseJsonTileSource.java index 871463e9..5792c6da 100644 --- a/vtm-web-js/src/org/oscim/web/js/JsOsmLanduseJsonTileSource.java +++ b/vtm-web-js/src/org/oscim/web/js/JsOsmLanduseJsonTileSource.java @@ -6,6 +6,6 @@ import org.timepedia.exporter.client.ExportPackage; @ExportPackage("vtm") public class JsOsmLanduseJsonTileSource implements ExportOverlay { - public JsOsmLanduseJsonTileSource() { - } + public JsOsmLanduseJsonTileSource() { + } } diff --git a/vtm-web-js/src/org/oscim/web/js/JsOverlays.java b/vtm-web-js/src/org/oscim/web/js/JsOverlays.java index f3704c64..c6b145b0 100644 --- a/vtm-web-js/src/org/oscim/web/js/JsOverlays.java +++ b/vtm-web-js/src/org/oscim/web/js/JsOverlays.java @@ -22,104 +22,108 @@ import org.timepedia.exporter.client.Exportable; @ExportPackage("") public class JsOverlays implements Exportable { - @ExportPackage("vtm") - @Export("Layers") - public interface XLayers extends ExportOverlay { - void add(Layer layer); - } + @ExportPackage("vtm") + @Export("Layers") + public interface XLayers extends ExportOverlay { + void add(Layer layer); + } - @ExportPackage("vtm") - @Export("Map") - public interface XMap extends ExportOverlay { - public abstract Layers layers(); + @ExportPackage("vtm") + @Export("Map") + public interface XMap extends ExportOverlay { + public abstract Layers layers(); - public abstract void setMapPosition(MapPosition pos); + public abstract void setMapPosition(MapPosition pos); - public abstract MapPosition getMapPosition(); + public abstract MapPosition getMapPosition(); - } + } - @ExportPackage("vtm") - @Export("MapPosition") - public static class XMapPosition implements ExportOverlay { - public XMapPosition(double latitude, double longitude, double scale) { - }; + @ExportPackage("vtm") + @Export("MapPosition") + public static class XMapPosition implements ExportOverlay { + public XMapPosition(double latitude, double longitude, double scale) { + } - public XMapPosition() { - }; + ; - public void setPosition(double latitude, double longitude) { - } + public XMapPosition() { + } - public void setScale(double scale) { - } - } + ; - @ExportPackage("vtm") - @Export("GenericLayer") - public abstract class XGenericLayer implements ExportOverlay { - public XGenericLayer(Map map, LayerRenderer renderer) { - } - } + public void setPosition(double latitude, double longitude) { + } - @ExportPackage("vtm") - @Export("TileGridLayer") - public static class XTileGridLayer implements ExportOverlay { - public XTileGridLayer(Map map) { - } - } + public void setScale(double scale) { + } + } - @ExportPackage("vtm") - @Export("OsmTileLayer") - public static class XOsmTileLayer implements ExportOverlay { - public XOsmTileLayer(Map map) { - } + @ExportPackage("vtm") + @Export("GenericLayer") + public abstract class XGenericLayer implements ExportOverlay { + public XGenericLayer(Map map, LayerRenderer renderer) { + } + } - public boolean setTileSource(TileSource tileSource) { - return false; - } + @ExportPackage("vtm") + @Export("TileGridLayer") + public static class XTileGridLayer implements ExportOverlay { + public XTileGridLayer(Map map) { + } + } - public void setRenderTheme(IRenderTheme theme) { - } - } + @ExportPackage("vtm") + @Export("OsmTileLayer") + public static class XOsmTileLayer implements ExportOverlay { + public XOsmTileLayer(Map map) { + } - @ExportPackage("vtm") - @Export("HighroadJsonTileSource") - public static class XHighroadJsonTileSource implements - ExportOverlay { - public XHighroadJsonTileSource() { - } - } + public boolean setTileSource(TileSource tileSource) { + return false; + } - @ExportPackage("vtm") - @Export("OSciMap4TileSource") - public static class XOSciMap4TileSource implements - ExportOverlay { - public XOSciMap4TileSource(String url) { - } + public void setRenderTheme(IRenderTheme theme) { + } + } - public XOSciMap4TileSource() { - } - } + @ExportPackage("vtm") + @Export("HighroadJsonTileSource") + public static class XHighroadJsonTileSource implements + ExportOverlay { + public XHighroadJsonTileSource() { + } + } - @ExportPackage("vtm") - @Export("LabelLayer") - public static class XLabelLayer implements - ExportOverlay { - public XLabelLayer(Map map, VectorTileLayer l) { - } - } + @ExportPackage("vtm") + @Export("OSciMap4TileSource") + public static class XOSciMap4TileSource implements + ExportOverlay { + public XOSciMap4TileSource(String url) { + } - @ExportPackage("vtm") - @Export("BuildingLayer") - public static class XBuildingLayer implements - ExportOverlay { - public XBuildingLayer(Map map, VectorTileLayer l) { - } - } + public XOSciMap4TileSource() { + } + } - // @ExportPackage("vtm") - // @Export("Viewport") - // public interface XViewport extends ExportOverlay - // + @ExportPackage("vtm") + @Export("LabelLayer") + public static class XLabelLayer implements + ExportOverlay { + public XLabelLayer(Map map, VectorTileLayer l) { + } + } + + @ExportPackage("vtm") + @Export("BuildingLayer") + public static class XBuildingLayer implements + ExportOverlay { + public XBuildingLayer(Map map, VectorTileLayer l) { + } + } + + // @ExportPackage("vtm") + // @Export("Viewport") + // public interface XViewport extends ExportOverlay + // } diff --git a/vtm-web-js/src/org/oscim/web/js/JsVectorTileLayer.java b/vtm-web-js/src/org/oscim/web/js/JsVectorTileLayer.java index 7b569d7b..83865e41 100644 --- a/vtm-web-js/src/org/oscim/web/js/JsVectorTileLayer.java +++ b/vtm-web-js/src/org/oscim/web/js/JsVectorTileLayer.java @@ -9,13 +9,13 @@ import org.timepedia.exporter.client.ExportPackage; @ExportPackage("vtm") public class JsVectorTileLayer implements ExportOverlay { - public JsVectorTileLayer(Map map, TileSource tileSource) { - } + public JsVectorTileLayer(Map map, TileSource tileSource) { + } - public boolean setTileSource(TileSource tileSource) { - return false; - } + public boolean setTileSource(TileSource tileSource) { + return false; + } - public void setRenderTheme(IRenderTheme theme) { - } + public void setRenderTheme(IRenderTheme theme) { + } } diff --git a/vtm-web-js/war/index.html b/vtm-web-js/war/index.html index 6d90d342..d1c00125 100644 --- a/vtm-web-js/war/index.html +++ b/vtm-web-js/war/index.html @@ -1,33 +1,33 @@ -vtm-web-js - + vtm-web-js + - + - + -
- - Your browser does not support the HTML5 canvas tag. - -
+
+ + Your browser does not support the HTML5 canvas tag. + +
- + - - - + + + -
- Source | map data © OpenStreetMap contributors | OpenScienceMap -
+
+ Source | map data © OpenStreetMap contributors | OpenScienceMap +
diff --git a/vtm-web/src/com/badlogic/gdx/backends/Gdx.gwt.xml b/vtm-web/src/com/badlogic/gdx/backends/Gdx.gwt.xml index 54c3b707..1cba7763 100644 --- a/vtm-web/src/com/badlogic/gdx/backends/Gdx.gwt.xml +++ b/vtm-web/src/com/badlogic/gdx/backends/Gdx.gwt.xml @@ -1,33 +1,34 @@ - - + - - - - - - - - + + + + - - - - - + + + + + + + + + - - - + + + - - - - - - - - - + + + + + + + + + diff --git a/vtm-web/src/org/oscim/gdx/VtmWeb.gwt.xml b/vtm-web/src/org/oscim/gdx/VtmWeb.gwt.xml index 7d700825..9cbbbbb9 100644 --- a/vtm-web/src/org/oscim/gdx/VtmWeb.gwt.xml +++ b/vtm-web/src/org/oscim/gdx/VtmWeb.gwt.xml @@ -1,75 +1,75 @@ - + - - + + - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - + + - + + - + - - - - - + + + + + + + diff --git a/vtm-web/src/org/oscim/gdx/client/GdxGL.java b/vtm-web/src/org/oscim/gdx/client/GdxGL.java index 13a29c96..066ca1cd 100644 --- a/vtm-web/src/org/oscim/gdx/client/GdxGL.java +++ b/vtm-web/src/org/oscim/gdx/client/GdxGL.java @@ -2,13 +2,13 @@ package org.oscim.gdx.client; /******************************************************************************* * Copyright 2011 See AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,704 +16,704 @@ package org.oscim.gdx.client; * limitations under the License. ******************************************************************************/ -import java.nio.Buffer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; - -import org.oscim.backend.GL; - import com.badlogic.gdx.backends.gwt.GwtGL20; import com.badlogic.gdx.graphics.Pixmap; import com.google.gwt.typedarrays.client.Uint8ArrayNative; import com.google.gwt.webgl.client.WebGLRenderingContext; +import org.oscim.backend.GL; + +import java.nio.Buffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + public class GdxGL extends GwtGL20 implements GL { - protected final WebGLRenderingContext gl; - - public GdxGL(WebGLRenderingContext gl) { - super(gl); - gl.pixelStorei(WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); - this.gl = gl; - } - - // @Override - // public void glGetShaderSource(int shader, int bufsize, Buffer length, String source) { - // - // } - - @Override - public void glTexImage2D(int target, int level, int internalformat, int width, int height, - int border, int format, int type, Buffer pixels) { - - if (pixels == null) { - gl.texImage2D(target, level, internalformat, - width, height, border, format, - type, null); - return; - } - - Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer) pixels).get(0)); - if (pixmap != null) { - gl.texImage2D(target, level, internalformat, format, type, pixmap.getCanvasElement()); - } else if (format == GL.ALPHA) { - int tmp[] = new int[(width * height) >> 2]; - ((IntBuffer) pixels).get(tmp); - - Uint8ArrayNative v = com.google.gwt.typedarrays.client.Uint8ArrayNative.create(width - * height); - - for (int i = 0, n = (width * height) >> 2; i < n; i++) { - v.set(i * 4 + 3, (tmp[i] >> 24) & 0xff); - v.set(i * 4 + 2, (tmp[i] >> 16) & 0xff); - v.set(i * 4 + 1, (tmp[i] >> 8) & 0xff); - v.set(i * 4 + 0, (tmp[i]) & 0xff); - } - gl.texImage2D(target, level, internalformat, width, height, 0, format, type, v); - } - } - - public void activeTexture(int texture) { - glActiveTexture(texture); - } - - public void bindTexture(int target, int texture) { - glBindTexture(target, texture); - } - - public void blendFunc(int sfactor, int dfactor) { - glBlendFunc(sfactor, dfactor); - } - - public void clear(int mask) { - glClear(mask); - } - - public void clearColor(float red, float green, float blue, float alpha) { - glClearColor(red, green, blue, alpha); - } - - public void clearDepthf(float depth) { - glClearDepthf(depth); - } - - public void clearStencil(int s) { - glClearStencil(s); - } - - public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - glColorMask(red, green, blue, alpha); - } - - public void compressedTexImage2D(int target, int level, int internalformat, int width, - int height, int border, - int imageSize, Buffer data) { - glCompressedTexImage2D( - target, - level, - internalformat, - width, - height, - border, - imageSize, - data); - } - - public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, - int width, int height, int format, - int imageSize, Buffer data) { - glCompressedTexSubImage2D(target, - level, - xoffset, - yoffset, - width, - height, - format, - imageSize, - data); - } - - public void copyTexImage2D(int target, int level, int internalformat, int x, int y, - int width, int height, int border) { - glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); - } - - public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, - int width, int height) { - glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); - } - - public void cullFace(int mode) { - glCullFace(mode); - } - - public void deleteTextures(int n, IntBuffer textures) { - glDeleteTextures(n, textures); - } - - public void depthFunc(int func) { - glDepthFunc(func); - } - - public void depthMask(boolean flag) { - glDepthMask(flag); - } - - public void depthRangef(float zNear, float zFar) { - glDepthRangef(zNear, zFar); - } - - public void disable(int cap) { - glDisable(cap); - } - - public void drawArrays(int mode, int first, int count) { - glDrawArrays(mode, first, count); - } - - public void drawElements(int mode, int count, int type, Buffer indices) { - glDrawElements(mode, count, type, indices); - } - - public void enable(int cap) { - glEnable(cap); - } - - public void finish() { - glFinish(); - } - - public void flush() { - glFlush(); - } - - public void frontFace(int mode) { - glFrontFace(mode); - } - - public void genTextures(int n, IntBuffer textures) { - glGenTextures(n, textures); - } - - public int getError() { - return glGetError(); - } - - public void getIntegerv(int pname, IntBuffer params) { - glGetIntegerv(pname, params); - } - - public String getString(int name) { - return glGetString(name); - } - - public void hint(int target, int mode) { - glHint(target, mode); - } - - public void lineWidth(float width) { - glLineWidth(width); - } - - public void pixelStorei(int pname, int param) { - glPixelStorei(pname, param); - } - - public void polygonOffset(float factor, float units) { - glPolygonOffset(factor, units); - } - - public void readPixels(int x, int y, int width, int height, int format, int type, - Buffer pixels) { - glReadPixels(x, y, width, height, format, type, pixels); - } - - public void scissor(int x, int y, int width, int height) { - glScissor(x, y, width, height); - } - - public void stencilFunc(int func, int ref, int mask) { - glStencilFunc(func, ref, mask); - } - - public void stencilMask(int mask) { - glStencilMask(mask); - } - - public void stencilOp(int fail, int zfail, int zpass) { - glStencilOp(fail, zfail, zpass); - } - - public void texImage2D(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, - Buffer pixels) { - glTexImage2D(target, - level, - internalFormat, - width, - height, - border, - format, - type, - pixels); - } - - public void texParameterf(int target, int pname, float param) { - glTexParameterf(target, pname, param); - } - - public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, - int height, int format, int type, - Buffer pixels) { - glTexSubImage2D(target, - level, - xoffset, - yoffset, - width, - height, - format, - type, - pixels); - } - - public void viewport(int x, int y, int width, int height) { - glViewport(x, y, width, height); - } - - public void getFloatv(int pname, FloatBuffer params) { - glGetFloatv(pname, params); - } - - public void getTexParameterfv(int target, int pname, FloatBuffer params) { - glGetTexParameterfv(target, pname, params); - } - - public void texParameterfv(int target, int pname, FloatBuffer params) { - glTexParameterfv(target, pname, params); - } - - public void bindBuffer(int target, int buffer) { - glBindBuffer(target, buffer); - } - - public void bufferData(int target, int size, Buffer data, int usage) { - glBufferData(target, size, data, usage); - } - - public void bufferSubData(int target, int offset, int size, Buffer data) { - glBufferSubData(target, offset, size, data); - } - - public void deleteBuffers(int n, IntBuffer buffers) { - glDeleteBuffers(n, buffers); - } - - public void getBufferParameteriv(int target, int pname, IntBuffer params) { - glGetBufferParameteriv(target, pname, params); - } - - public void genBuffers(int n, IntBuffer buffers) { - glGenBuffers(n, buffers); - } - - public void getTexParameteriv(int target, int pname, IntBuffer params) { - glGetTexParameteriv(target, pname, params); - } - - public boolean isBuffer(int buffer) { - return glIsBuffer(buffer); - } - - public boolean isEnabled(int cap) { - return glIsEnabled(cap); - } - - public boolean isTexture(int texture) { - return glIsTexture(texture); - } - - public void texParameteri(int target, int pname, int param) { - glTexParameteri(target, pname, param); - } - - public void texParameteriv(int target, int pname, IntBuffer params) { - glTexParameteriv(target, pname, params); - } - - public void drawElements(int mode, int count, int type, int indices) { - glDrawElements(mode, count, type, indices); - } - - public void attachShader(int program, int shader) { - glAttachShader(program, shader); - } - - public void bindAttribLocation(int program, int index, String name) { - glBindAttribLocation(program, index, name); - } - - public void bindFramebuffer(int target, int framebuffer) { - glBindFramebuffer(target, framebuffer); - } - - public void bindRenderbuffer(int target, int renderbuffer) { - glBindRenderbuffer(target, renderbuffer); - } - - public void blendColor(float red, float green, float blue, float alpha) { - glBlendColor(red, green, blue, alpha); - } - - public void blendEquation(int mode) { - glBlendEquation(mode); - } - - public void blendEquationSeparate(int modeRGB, int modeAlpha) { - glBlendEquationSeparate(modeRGB, modeAlpha); - } - - public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { - glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); - } - - public int checkFramebufferStatus(int target) { - return glCheckFramebufferStatus(target); - } - - public void compileShader(int shader) { - glCompileShader(shader); - } - - public int createProgram() { - return glCreateProgram(); - } - - public int createShader(int type) { - return glCreateShader(type); - } - - public void deleteFramebuffers(int n, IntBuffer framebuffers) { - glDeleteFramebuffers(n, framebuffers); - } - - public void deleteProgram(int program) { - glDeleteProgram(program); - } - - public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { - glDeleteRenderbuffers(n, renderbuffers); - } - - public void deleteShader(int shader) { - glDeleteShader(shader); - } - - public void detachShader(int program, int shader) { - glDetachShader(program, shader); - } - - public void disableVertexAttribArray(int index) { - glDisableVertexAttribArray(index); - } - - public void enableVertexAttribArray(int index) { - glEnableVertexAttribArray(index); - } - - public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, - int renderbuffer) { - glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); - } - - public void framebufferTexture2D(int target, int attachment, int textarget, int texture, - int level) { - glFramebufferTexture2D(target, attachment, textarget, texture, level); - } - - public void generateMipmap(int target) { - glGenerateMipmap(target); - } - - public void genFramebuffers(int n, IntBuffer framebuffers) { - glGenFramebuffers(n, framebuffers); - } - - public void genRenderbuffers(int n, IntBuffer renderbuffers) { - glGenRenderbuffers(n, renderbuffers); - } - - public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { - return glGetActiveAttrib(program, - index, - size, - type); - } - - public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { - return glGetActiveUniform(program, - index, - size, - type); - } - - public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { - glGetAttachedShaders(program, - maxcount, - count, - shaders); - } - - public int getAttribLocation(int program, String name) { - return glGetAttribLocation(program, name); - } - - public void getBooleanv(int pname, Buffer params) { - glGetBooleanv(pname, params); - } - - public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, - IntBuffer params) { - glGetFramebufferAttachmentParameteriv(target, - attachment, - pname, - params); - } - - public void getProgramiv(int program, int pname, IntBuffer params) { - glGetProgramiv(program, pname, params); - } - - public String getProgramInfoLog(int program) { - return glGetProgramInfoLog(program); - } - - public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { - glGetRenderbufferParameteriv(target, pname, params); - } - - public void getShaderiv(int shader, int pname, IntBuffer params) { - glGetShaderiv(shader, pname, params); - } - - public String getShaderInfoLog(int shader) { - return glGetShaderInfoLog(shader); - } - - public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, - IntBuffer precision) { - glGetShaderPrecisionFormat(shadertype, - precisiontype, - range, - precision); - } - - public void getShaderSource(int shader, int bufsize, Buffer length, String source) { - throw new UnsupportedOperationException("Not implemented"); - } - - public void getUniformfv(int program, int location, FloatBuffer params) { - glGetUniformfv(program, location, params); - } - - public void getUniformiv(int program, int location, IntBuffer params) { - glGetUniformiv(program, location, params); - } - - public int getUniformLocation(int program, String name) { - return glGetUniformLocation(program, name); - } - - public void getVertexAttribfv(int index, int pname, FloatBuffer params) { - glGetVertexAttribfv(index, pname, params); - } - - public void getVertexAttribiv(int index, int pname, IntBuffer params) { - glGetVertexAttribiv(index, pname, params); - } - - public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { - glGetVertexAttribPointerv(index, pname, pointer); - } - - public boolean isFramebuffer(int framebuffer) { - return glIsFramebuffer(framebuffer); - } - - public boolean isProgram(int program) { - return glIsProgram(program); - } - - public boolean isRenderbuffer(int renderbuffer) { - return glIsRenderbuffer(renderbuffer); - } - - public boolean isShader(int shader) { - return glIsShader(shader); - } - - public void linkProgram(int program) { - glLinkProgram(program); - } - - public void releaseShaderCompiler() { - glReleaseShaderCompiler(); - } - - public void renderbufferStorage(int target, int internalformat, int width, int height) { - glRenderbufferStorage(target, internalformat, width, height); - } - - public void sampleCoverage(float value, boolean invert) { - glSampleCoverage(value, invert); - } - - public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { - glShaderBinary(n, - shaders, - binaryformat, - binary, - length); - } - - public void shaderSource(int shader, String string) { - glShaderSource(shader, string); - } - - public void stencilFuncSeparate(int face, int func, int ref, int mask) { - glStencilFuncSeparate(face, func, ref, mask); - } - - public void stencilMaskSeparate(int face, int mask) { - glStencilMaskSeparate(face, mask); - } - - public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { - glStencilOpSeparate(face, fail, zfail, zpass); - } - - public void uniform1f(int location, float x) { - glUniform1f(location, x); - } - - public void uniform1fv(int location, int count, FloatBuffer v) { - glUniform1fv(location, count, v); - } - - public void uniform1i(int location, int x) { - glUniform1i(location, x); - } - - public void uniform1iv(int location, int count, IntBuffer v) { - glUniform1iv(location, count, v); - } + protected final WebGLRenderingContext gl; + + public GdxGL(WebGLRenderingContext gl) { + super(gl); + gl.pixelStorei(WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); + this.gl = gl; + } + + // @Override + // public void glGetShaderSource(int shader, int bufsize, Buffer length, String source) { + // + // } + + @Override + public void glTexImage2D(int target, int level, int internalformat, int width, int height, + int border, int format, int type, Buffer pixels) { + + if (pixels == null) { + gl.texImage2D(target, level, internalformat, + width, height, border, format, + type, null); + return; + } + + Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer) pixels).get(0)); + if (pixmap != null) { + gl.texImage2D(target, level, internalformat, format, type, pixmap.getCanvasElement()); + } else if (format == GL.ALPHA) { + int tmp[] = new int[(width * height) >> 2]; + ((IntBuffer) pixels).get(tmp); + + Uint8ArrayNative v = com.google.gwt.typedarrays.client.Uint8ArrayNative.create(width + * height); + + for (int i = 0, n = (width * height) >> 2; i < n; i++) { + v.set(i * 4 + 3, (tmp[i] >> 24) & 0xff); + v.set(i * 4 + 2, (tmp[i] >> 16) & 0xff); + v.set(i * 4 + 1, (tmp[i] >> 8) & 0xff); + v.set(i * 4 + 0, (tmp[i]) & 0xff); + } + gl.texImage2D(target, level, internalformat, width, height, 0, format, type, v); + } + } + + public void activeTexture(int texture) { + glActiveTexture(texture); + } + + public void bindTexture(int target, int texture) { + glBindTexture(target, texture); + } + + public void blendFunc(int sfactor, int dfactor) { + glBlendFunc(sfactor, dfactor); + } + + public void clear(int mask) { + glClear(mask); + } + + public void clearColor(float red, float green, float blue, float alpha) { + glClearColor(red, green, blue, alpha); + } + + public void clearDepthf(float depth) { + glClearDepthf(depth); + } + + public void clearStencil(int s) { + glClearStencil(s); + } + + public void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + glColorMask(red, green, blue, alpha); + } + + public void compressedTexImage2D(int target, int level, int internalformat, int width, + int height, int border, + int imageSize, Buffer data) { + glCompressedTexImage2D( + target, + level, + internalformat, + width, + height, + border, + imageSize, + data); + } + + public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, + int width, int height, int format, + int imageSize, Buffer data) { + glCompressedTexSubImage2D(target, + level, + xoffset, + yoffset, + width, + height, + format, + imageSize, + data); + } + + public void copyTexImage2D(int target, int level, int internalformat, int x, int y, + int width, int height, int border) { + glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); + } + + public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, + int width, int height) { + glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); + } + + public void cullFace(int mode) { + glCullFace(mode); + } + + public void deleteTextures(int n, IntBuffer textures) { + glDeleteTextures(n, textures); + } + + public void depthFunc(int func) { + glDepthFunc(func); + } + + public void depthMask(boolean flag) { + glDepthMask(flag); + } + + public void depthRangef(float zNear, float zFar) { + glDepthRangef(zNear, zFar); + } + + public void disable(int cap) { + glDisable(cap); + } + + public void drawArrays(int mode, int first, int count) { + glDrawArrays(mode, first, count); + } + + public void drawElements(int mode, int count, int type, Buffer indices) { + glDrawElements(mode, count, type, indices); + } + + public void enable(int cap) { + glEnable(cap); + } + + public void finish() { + glFinish(); + } + + public void flush() { + glFlush(); + } + + public void frontFace(int mode) { + glFrontFace(mode); + } + + public void genTextures(int n, IntBuffer textures) { + glGenTextures(n, textures); + } + + public int getError() { + return glGetError(); + } + + public void getIntegerv(int pname, IntBuffer params) { + glGetIntegerv(pname, params); + } + + public String getString(int name) { + return glGetString(name); + } + + public void hint(int target, int mode) { + glHint(target, mode); + } + + public void lineWidth(float width) { + glLineWidth(width); + } + + public void pixelStorei(int pname, int param) { + glPixelStorei(pname, param); + } + + public void polygonOffset(float factor, float units) { + glPolygonOffset(factor, units); + } + + public void readPixels(int x, int y, int width, int height, int format, int type, + Buffer pixels) { + glReadPixels(x, y, width, height, format, type, pixels); + } + + public void scissor(int x, int y, int width, int height) { + glScissor(x, y, width, height); + } + + public void stencilFunc(int func, int ref, int mask) { + glStencilFunc(func, ref, mask); + } + + public void stencilMask(int mask) { + glStencilMask(mask); + } + + public void stencilOp(int fail, int zfail, int zpass) { + glStencilOp(fail, zfail, zpass); + } + + public void texImage2D(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, + Buffer pixels) { + glTexImage2D(target, + level, + internalFormat, + width, + height, + border, + format, + type, + pixels); + } + + public void texParameterf(int target, int pname, float param) { + glTexParameterf(target, pname, param); + } + + public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, + int height, int format, int type, + Buffer pixels) { + glTexSubImage2D(target, + level, + xoffset, + yoffset, + width, + height, + format, + type, + pixels); + } + + public void viewport(int x, int y, int width, int height) { + glViewport(x, y, width, height); + } + + public void getFloatv(int pname, FloatBuffer params) { + glGetFloatv(pname, params); + } + + public void getTexParameterfv(int target, int pname, FloatBuffer params) { + glGetTexParameterfv(target, pname, params); + } + + public void texParameterfv(int target, int pname, FloatBuffer params) { + glTexParameterfv(target, pname, params); + } + + public void bindBuffer(int target, int buffer) { + glBindBuffer(target, buffer); + } + + public void bufferData(int target, int size, Buffer data, int usage) { + glBufferData(target, size, data, usage); + } + + public void bufferSubData(int target, int offset, int size, Buffer data) { + glBufferSubData(target, offset, size, data); + } + + public void deleteBuffers(int n, IntBuffer buffers) { + glDeleteBuffers(n, buffers); + } + + public void getBufferParameteriv(int target, int pname, IntBuffer params) { + glGetBufferParameteriv(target, pname, params); + } + + public void genBuffers(int n, IntBuffer buffers) { + glGenBuffers(n, buffers); + } + + public void getTexParameteriv(int target, int pname, IntBuffer params) { + glGetTexParameteriv(target, pname, params); + } + + public boolean isBuffer(int buffer) { + return glIsBuffer(buffer); + } + + public boolean isEnabled(int cap) { + return glIsEnabled(cap); + } + + public boolean isTexture(int texture) { + return glIsTexture(texture); + } + + public void texParameteri(int target, int pname, int param) { + glTexParameteri(target, pname, param); + } + + public void texParameteriv(int target, int pname, IntBuffer params) { + glTexParameteriv(target, pname, params); + } + + public void drawElements(int mode, int count, int type, int indices) { + glDrawElements(mode, count, type, indices); + } + + public void attachShader(int program, int shader) { + glAttachShader(program, shader); + } + + public void bindAttribLocation(int program, int index, String name) { + glBindAttribLocation(program, index, name); + } + + public void bindFramebuffer(int target, int framebuffer) { + glBindFramebuffer(target, framebuffer); + } + + public void bindRenderbuffer(int target, int renderbuffer) { + glBindRenderbuffer(target, renderbuffer); + } + + public void blendColor(float red, float green, float blue, float alpha) { + glBlendColor(red, green, blue, alpha); + } + + public void blendEquation(int mode) { + glBlendEquation(mode); + } + + public void blendEquationSeparate(int modeRGB, int modeAlpha) { + glBlendEquationSeparate(modeRGB, modeAlpha); + } + + public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + + public int checkFramebufferStatus(int target) { + return glCheckFramebufferStatus(target); + } + + public void compileShader(int shader) { + glCompileShader(shader); + } + + public int createProgram() { + return glCreateProgram(); + } + + public int createShader(int type) { + return glCreateShader(type); + } + + public void deleteFramebuffers(int n, IntBuffer framebuffers) { + glDeleteFramebuffers(n, framebuffers); + } + + public void deleteProgram(int program) { + glDeleteProgram(program); + } + + public void deleteRenderbuffers(int n, IntBuffer renderbuffers) { + glDeleteRenderbuffers(n, renderbuffers); + } + + public void deleteShader(int shader) { + glDeleteShader(shader); + } + + public void detachShader(int program, int shader) { + glDetachShader(program, shader); + } + + public void disableVertexAttribArray(int index) { + glDisableVertexAttribArray(index); + } + + public void enableVertexAttribArray(int index) { + glEnableVertexAttribArray(index); + } + + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, + int renderbuffer) { + glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); + } + + public void framebufferTexture2D(int target, int attachment, int textarget, int texture, + int level) { + glFramebufferTexture2D(target, attachment, textarget, texture, level); + } + + public void generateMipmap(int target) { + glGenerateMipmap(target); + } + + public void genFramebuffers(int n, IntBuffer framebuffers) { + glGenFramebuffers(n, framebuffers); + } + + public void genRenderbuffers(int n, IntBuffer renderbuffers) { + glGenRenderbuffers(n, renderbuffers); + } + + public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type) { + return glGetActiveAttrib(program, + index, + size, + type); + } + + public String getActiveUniform(int program, int index, IntBuffer size, Buffer type) { + return glGetActiveUniform(program, + index, + size, + type); + } + + public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders) { + glGetAttachedShaders(program, + maxcount, + count, + shaders); + } + + public int getAttribLocation(int program, String name) { + return glGetAttribLocation(program, name); + } + + public void getBooleanv(int pname, Buffer params) { + glGetBooleanv(pname, params); + } + + public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, + IntBuffer params) { + glGetFramebufferAttachmentParameteriv(target, + attachment, + pname, + params); + } + + public void getProgramiv(int program, int pname, IntBuffer params) { + glGetProgramiv(program, pname, params); + } + + public String getProgramInfoLog(int program) { + return glGetProgramInfoLog(program); + } + + public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) { + glGetRenderbufferParameteriv(target, pname, params); + } + + public void getShaderiv(int shader, int pname, IntBuffer params) { + glGetShaderiv(shader, pname, params); + } + + public String getShaderInfoLog(int shader) { + return glGetShaderInfoLog(shader); + } + + public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, + IntBuffer precision) { + glGetShaderPrecisionFormat(shadertype, + precisiontype, + range, + precision); + } + + public void getShaderSource(int shader, int bufsize, Buffer length, String source) { + throw new UnsupportedOperationException("Not implemented"); + } + + public void getUniformfv(int program, int location, FloatBuffer params) { + glGetUniformfv(program, location, params); + } + + public void getUniformiv(int program, int location, IntBuffer params) { + glGetUniformiv(program, location, params); + } + + public int getUniformLocation(int program, String name) { + return glGetUniformLocation(program, name); + } + + public void getVertexAttribfv(int index, int pname, FloatBuffer params) { + glGetVertexAttribfv(index, pname, params); + } + + public void getVertexAttribiv(int index, int pname, IntBuffer params) { + glGetVertexAttribiv(index, pname, params); + } + + public void getVertexAttribPointerv(int index, int pname, Buffer pointer) { + glGetVertexAttribPointerv(index, pname, pointer); + } + + public boolean isFramebuffer(int framebuffer) { + return glIsFramebuffer(framebuffer); + } + + public boolean isProgram(int program) { + return glIsProgram(program); + } + + public boolean isRenderbuffer(int renderbuffer) { + return glIsRenderbuffer(renderbuffer); + } + + public boolean isShader(int shader) { + return glIsShader(shader); + } + + public void linkProgram(int program) { + glLinkProgram(program); + } + + public void releaseShaderCompiler() { + glReleaseShaderCompiler(); + } + + public void renderbufferStorage(int target, int internalformat, int width, int height) { + glRenderbufferStorage(target, internalformat, width, height); + } + + public void sampleCoverage(float value, boolean invert) { + glSampleCoverage(value, invert); + } + + public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) { + glShaderBinary(n, + shaders, + binaryformat, + binary, + length); + } + + public void shaderSource(int shader, String string) { + glShaderSource(shader, string); + } + + public void stencilFuncSeparate(int face, int func, int ref, int mask) { + glStencilFuncSeparate(face, func, ref, mask); + } + + public void stencilMaskSeparate(int face, int mask) { + glStencilMaskSeparate(face, mask); + } + + public void stencilOpSeparate(int face, int fail, int zfail, int zpass) { + glStencilOpSeparate(face, fail, zfail, zpass); + } + + public void uniform1f(int location, float x) { + glUniform1f(location, x); + } + + public void uniform1fv(int location, int count, FloatBuffer v) { + glUniform1fv(location, count, v); + } + + public void uniform1i(int location, int x) { + glUniform1i(location, x); + } + + public void uniform1iv(int location, int count, IntBuffer v) { + glUniform1iv(location, count, v); + } - public void uniform2f(int location, float x, float y) { - glUniform2f(location, x, y); - } - - public void uniform2fv(int location, int count, FloatBuffer v) { - glUniform2fv(location, count, v); - } - - public void uniform2i(int location, int x, int y) { - glUniform2i(location, x, y); - } - - public void uniform2iv(int location, int count, IntBuffer v) { - glUniform2iv(location, count, v); - } - - public void uniform3f(int location, float x, float y, float z) { - glUniform3f(location, x, y, z); - } - - public void uniform3fv(int location, int count, FloatBuffer v) { - glUniform3fv(location, count, v); - } - - public void uniform3i(int location, int x, int y, int z) { - glUniform3i(location, x, y, z); - } - - public void uniform3iv(int location, int count, IntBuffer v) { - glUniform3iv(location, count, v); - } - - public void uniform4f(int location, float x, float y, float z, float w) { - glUniform4f(location, x, y, z, w); - } - - public void uniform4fv(int location, int count, FloatBuffer v) { - glUniform4fv(location, count, v); - } - - public void uniform4i(int location, int x, int y, int z, int w) { - glUniform4i(location, x, y, z, w); - } - - public void uniform4iv(int location, int count, IntBuffer v) { - glUniform4iv(location, count, v); - } - - public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { - glUniformMatrix2fv(location, count, transpose, value); - } - - public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { - glUniformMatrix3fv(location, count, transpose, value); - } - - public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { - glUniformMatrix4fv(location, count, transpose, value); - } - - public void useProgram(int program) { - glUseProgram(program); - } - - public void validateProgram(int program) { - glValidateProgram(program); - } + public void uniform2f(int location, float x, float y) { + glUniform2f(location, x, y); + } + + public void uniform2fv(int location, int count, FloatBuffer v) { + glUniform2fv(location, count, v); + } + + public void uniform2i(int location, int x, int y) { + glUniform2i(location, x, y); + } + + public void uniform2iv(int location, int count, IntBuffer v) { + glUniform2iv(location, count, v); + } + + public void uniform3f(int location, float x, float y, float z) { + glUniform3f(location, x, y, z); + } + + public void uniform3fv(int location, int count, FloatBuffer v) { + glUniform3fv(location, count, v); + } + + public void uniform3i(int location, int x, int y, int z) { + glUniform3i(location, x, y, z); + } + + public void uniform3iv(int location, int count, IntBuffer v) { + glUniform3iv(location, count, v); + } + + public void uniform4f(int location, float x, float y, float z, float w) { + glUniform4f(location, x, y, z, w); + } + + public void uniform4fv(int location, int count, FloatBuffer v) { + glUniform4fv(location, count, v); + } + + public void uniform4i(int location, int x, int y, int z, int w) { + glUniform4i(location, x, y, z, w); + } + + public void uniform4iv(int location, int count, IntBuffer v) { + glUniform4iv(location, count, v); + } + + public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value) { + glUniformMatrix2fv(location, count, transpose, value); + } + + public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value) { + glUniformMatrix3fv(location, count, transpose, value); + } + + public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value) { + glUniformMatrix4fv(location, count, transpose, value); + } + + public void useProgram(int program) { + glUseProgram(program); + } + + public void validateProgram(int program) { + glValidateProgram(program); + } - public void vertexAttrib1f(int indx, float x) { - glVertexAttrib1f(indx, x); - } + public void vertexAttrib1f(int indx, float x) { + glVertexAttrib1f(indx, x); + } - public void vertexAttrib1fv(int indx, FloatBuffer values) { - glVertexAttrib1fv(indx, values); - } + public void vertexAttrib1fv(int indx, FloatBuffer values) { + glVertexAttrib1fv(indx, values); + } - public void vertexAttrib2f(int indx, float x, float y) { - glVertexAttrib2f(indx, x, y); - } + public void vertexAttrib2f(int indx, float x, float y) { + glVertexAttrib2f(indx, x, y); + } - public void vertexAttrib2fv(int indx, FloatBuffer values) { - glVertexAttrib2fv(indx, values); - } + public void vertexAttrib2fv(int indx, FloatBuffer values) { + glVertexAttrib2fv(indx, values); + } - public void vertexAttrib3f(int indx, float x, float y, float z) { - glVertexAttrib3f(indx, x, y, z); - } + public void vertexAttrib3f(int indx, float x, float y, float z) { + glVertexAttrib3f(indx, x, y, z); + } - public void vertexAttrib3fv(int indx, FloatBuffer values) { - glVertexAttrib3fv(indx, values); - } + public void vertexAttrib3fv(int indx, FloatBuffer values) { + glVertexAttrib3fv(indx, values); + } - public void vertexAttrib4f(int indx, float x, float y, float z, float w) { - glVertexAttrib4f(indx, x, y, z, w); - } + public void vertexAttrib4f(int indx, float x, float y, float z, float w) { + glVertexAttrib4f(indx, x, y, z, w); + } - public void vertexAttrib4fv(int indx, FloatBuffer values) { - glVertexAttrib4fv(indx, values); - } + public void vertexAttrib4fv(int indx, FloatBuffer values) { + glVertexAttrib4fv(indx, values); + } - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - Buffer ptr) { - glVertexAttribPointer(indx, size, type, normalized, stride, ptr); - } - - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - int ptr) { - glVertexAttribPointer(indx, size, type, normalized, stride, ptr); - } + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + Buffer ptr) { + glVertexAttribPointer(indx, size, type, normalized, stride, ptr); + } + + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + int ptr) { + glVertexAttribPointer(indx, size, type, normalized, stride, ptr); + } } diff --git a/vtm-web/src/org/oscim/gdx/client/GwtBitmap.java b/vtm-web/src/org/oscim/gdx/client/GwtBitmap.java index 65b66a0b..10a97b8b 100644 --- a/vtm-web/src/org/oscim/gdx/client/GwtBitmap.java +++ b/vtm-web/src/org/oscim/gdx/client/GwtBitmap.java @@ -16,9 +16,6 @@ */ package org.oscim.gdx.client; -import org.oscim.backend.GL; -import org.oscim.backend.canvas.Bitmap; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; @@ -26,75 +23,80 @@ import com.google.gwt.dom.client.ImageElement; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.RootPanel; +import org.oscim.backend.GL; +import org.oscim.backend.canvas.Bitmap; + public class GwtBitmap implements Bitmap { - Pixmap pixmap; - Image image; - boolean disposable; + Pixmap pixmap; + Image image; + boolean disposable; - public GwtBitmap(Image data) { - ImageElement imageElement = ImageElement.as(data.getElement()); - pixmap = new Pixmap(imageElement); - image = data; - } + public GwtBitmap(Image data) { + ImageElement imageElement = ImageElement.as(data.getElement()); + pixmap = new Pixmap(imageElement); + image = data; + } - /** always argb8888 */ - public GwtBitmap(int width, int height, int format) { - pixmap = new Pixmap(width, height, null); - } + /** + * always argb8888 + */ + public GwtBitmap(int width, int height, int format) { + pixmap = new Pixmap(width, height, null); + } - public GwtBitmap(String fileName) { - FileHandle handle = Gdx.files.internal(fileName); - pixmap = new Pixmap(handle); - disposable = true; - } + public GwtBitmap(String fileName) { + FileHandle handle = Gdx.files.internal(fileName); + pixmap = new Pixmap(handle); + disposable = true; + } - @Override - public int getWidth() { - return pixmap.getWidth(); - } + @Override + public int getWidth() { + return pixmap.getWidth(); + } - @Override - public int getHeight() { - return pixmap.getHeight(); - } + @Override + public int getHeight() { + return pixmap.getHeight(); + } - @Override - public void recycle() { - // FIXME this should be called at some point in time - pixmap.dispose(); + @Override + public void recycle() { + // FIXME this should be called at some point in time + pixmap.dispose(); - if (image != null) - RootPanel.get().remove(image); - } + if (image != null) + RootPanel.get().remove(image); + } - @Override - public int[] getPixels() { - return null; - } + @Override + public int[] getPixels() { + return null; + } - @Override - public void eraseColor(int color) { - } + @Override + public void eraseColor(int color) { + } - @Override - public void uploadToTexture(boolean replace) { + @Override + public void uploadToTexture(boolean replace) { - Gdx.gl.glTexImage2D(GL.TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), - pixmap.getHeight(), 0, - pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + Gdx.gl.glTexImage2D(GL.TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), + pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); - if (disposable || image != null) { - //log.debug("dispose pixmap " + getWidth() + "/" + getHeight()); - pixmap.dispose(); + if (disposable || image != null) { + //log.debug("dispose pixmap " + getWidth() + "/" + getHeight()); + pixmap.dispose(); - if (image != null) - RootPanel.get().remove(image); - } - } + if (image != null) + RootPanel.get().remove(image); + } + } - @Override - public boolean isValid() { - return true; - } + @Override + public boolean isValid() { + return true; + } } diff --git a/vtm-web/src/org/oscim/gdx/client/GwtCanvas.java b/vtm-web/src/org/oscim/gdx/client/GwtCanvas.java index d94bc5c3..3403d0c9 100644 --- a/vtm-web/src/org/oscim/gdx/client/GwtCanvas.java +++ b/vtm-web/src/org/oscim/gdx/client/GwtCanvas.java @@ -16,54 +16,54 @@ */ package org.oscim.gdx.client; -import org.oscim.backend.canvas.Bitmap; -import org.oscim.backend.canvas.Paint; - import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.Context2d.LineJoin; +import org.oscim.backend.canvas.Bitmap; +import org.oscim.backend.canvas.Paint; + public class GwtCanvas implements org.oscim.backend.canvas.Canvas { - GwtBitmap bitmap; + GwtBitmap bitmap; - public GwtCanvas() { - // canvas comes with gdx pixmap - } + public GwtCanvas() { + // canvas comes with gdx pixmap + } - @Override - public void setBitmap(Bitmap bitmap) { - this.bitmap = (GwtBitmap) bitmap; - Context2d ctx = this.bitmap.pixmap.getContext(); + @Override + public void setBitmap(Bitmap bitmap) { + this.bitmap = (GwtBitmap) bitmap; + Context2d ctx = this.bitmap.pixmap.getContext(); - ctx.clearRect(0, 0, this.bitmap.getWidth(), this.bitmap.getHeight()); - ctx.setLineJoin(LineJoin.BEVEL); - } + ctx.clearRect(0, 0, this.bitmap.getWidth(), this.bitmap.getHeight()); + ctx.setLineJoin(LineJoin.BEVEL); + } - @Override - public void drawText(String string, float x, float y, Paint fill, Paint stroke) { - if (bitmap == null) { - //log.debug("no bitmap set"); - return; - } + @Override + public void drawText(String string, float x, float y, Paint fill, Paint stroke) { + if (bitmap == null) { + //log.debug("no bitmap set"); + return; + } - GwtPaint p = (GwtPaint) fill; + GwtPaint p = (GwtPaint) fill; - if (p.stroke && GwtGdxGraphics.NO_STROKE_TEXT) - return; + if (p.stroke && GwtGdxGraphics.NO_STROKE_TEXT) + return; - Context2d ctx = bitmap.pixmap.getContext(); - ctx.setFont(p.font); + Context2d ctx = bitmap.pixmap.getContext(); + ctx.setFont(p.font); - if (p.stroke) { - ctx.setLineWidth(p.strokeWidth); - ctx.setStrokeStyle(p.color); - ctx.strokeText(string, (int) (x + 1), (int) (y + 1)); - } else { - ctx.setFillStyle(p.color); - ctx.fillText(string, (int) (x + 1), (int) (y + 1)); - } - } + if (p.stroke) { + ctx.setLineWidth(p.strokeWidth); + ctx.setStrokeStyle(p.color); + ctx.strokeText(string, (int) (x + 1), (int) (y + 1)); + } else { + ctx.setFillStyle(p.color); + ctx.fillText(string, (int) (x + 1), (int) (y + 1)); + } + } - @Override - public void drawBitmap(Bitmap bitmap, float x, float y) { - } + @Override + public void drawBitmap(Bitmap bitmap, float x, float y) { + } } diff --git a/vtm-web/src/org/oscim/gdx/client/GwtGdxGraphics.java b/vtm-web/src/org/oscim/gdx/client/GwtGdxGraphics.java index 36f16723..51382a96 100644 --- a/vtm-web/src/org/oscim/gdx/client/GwtGdxGraphics.java +++ b/vtm-web/src/org/oscim/gdx/client/GwtGdxGraphics.java @@ -16,62 +16,62 @@ */ package org.oscim.gdx.client; -import java.io.InputStream; +import com.google.gwt.canvas.client.Canvas; +import com.google.gwt.canvas.dom.client.Context2d; +import com.google.gwt.canvas.dom.client.TextMetrics; import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Paint; -import com.google.gwt.canvas.client.Canvas; -import com.google.gwt.canvas.dom.client.Context2d; -import com.google.gwt.canvas.dom.client.TextMetrics; +import java.io.InputStream; public class GwtGdxGraphics extends CanvasAdapter { - public static boolean NO_STROKE_TEXT = false; + public static boolean NO_STROKE_TEXT = false; - static final Context2d ctx; + static final Context2d ctx; - static { - Canvas canvas = Canvas.createIfSupported(); - canvas.setCoordinateSpaceWidth(1); - canvas.setCoordinateSpaceHeight(1); - ctx = canvas.getContext2d(); - } + static { + Canvas canvas = Canvas.createIfSupported(); + canvas.setCoordinateSpaceWidth(1); + canvas.setCoordinateSpaceHeight(1); + ctx = canvas.getContext2d(); + } - public static synchronized float getTextWidth(String text, String font) { - ctx.setFont(font); - TextMetrics tm = ctx.measureText(text); - return (float) tm.getWidth(); - } + public static synchronized float getTextWidth(String text, String font) { + ctx.setFont(font); + TextMetrics tm = ctx.measureText(text); + return (float) tm.getWidth(); + } - @Override - public Bitmap decodeBitmapImpl(InputStream in) { - //ImageData data = new ImageData(); - return null; - } + @Override + public Bitmap decodeBitmapImpl(InputStream in) { + //ImageData data = new ImageData(); + return null; + } - @Override - public Bitmap loadBitmapAssetImpl(String fileName) { - return new GwtBitmap(fileName); - } + @Override + public Bitmap loadBitmapAssetImpl(String fileName) { + return new GwtBitmap(fileName); + } - @Override - public Paint newPaintImpl() { - return new GwtPaint(); - } + @Override + public Paint newPaintImpl() { + return new GwtPaint(); + } - @Override - public Bitmap newBitmapImpl(int width, int height, int format) { - return new GwtBitmap(width, height, format); - } + @Override + public Bitmap newBitmapImpl(int width, int height, int format) { + return new GwtBitmap(width, height, format); + } - @Override - public org.oscim.backend.canvas.Canvas newCanvasImpl() { - return new GwtCanvas(); - } + @Override + public org.oscim.backend.canvas.Canvas newCanvasImpl() { + return new GwtCanvas(); + } - public static void init() { - CanvasAdapter.init(new GwtGdxGraphics()); - } + public static void init() { + CanvasAdapter.init(new GwtGdxGraphics()); + } } diff --git a/vtm-web/src/org/oscim/gdx/client/GwtPaint.java b/vtm-web/src/org/oscim/gdx/client/GwtPaint.java index 60f8f775..515c3424 100644 --- a/vtm-web/src/org/oscim/gdx/client/GwtPaint.java +++ b/vtm-web/src/org/oscim/gdx/client/GwtPaint.java @@ -16,106 +16,106 @@ */ package org.oscim.gdx.client; -import org.oscim.backend.canvas.Paint; - import com.badlogic.gdx.graphics.Pixmap; +import org.oscim.backend.canvas.Paint; + public class GwtPaint implements Paint { - String color; - boolean stroke; + String color; + boolean stroke; - float strokeWidth; - Align mAlign; + float strokeWidth; + Align mAlign; - float fontSize = 12; + float fontSize = 12; - private FontStyle fontStyle = FontStyle.NORMAL; - //private FontFamily fontFamily = FontFamily.DEFAULT; + private FontStyle fontStyle = FontStyle.NORMAL; + //private FontFamily fontFamily = FontFamily.DEFAULT; - //String font = "12px sans-serif"; - String font = "13px Helvetica"; + //String font = "12px sans-serif"; + String font = "13px Helvetica"; - //private int cap; + //private int cap; - @Override - public int getColor() { - return 0; - } + @Override + public int getColor() { + return 0; + } - @Override - public void setColor(int color) { - float a = ((color >>> 24) & 0xff) / 255f; - int r = (color >>> 16) & 0xff; - int g = (color >>> 8) & 0xff; - int b = (color & 0xff); + @Override + public void setColor(int color) { + float a = ((color >>> 24) & 0xff) / 255f; + int r = (color >>> 16) & 0xff; + int g = (color >>> 8) & 0xff; + int b = (color & 0xff); - this.color = Pixmap.make(r, g, b, a); - } + this.color = Pixmap.make(r, g, b, a); + } - @Override - public void setStrokeCap(Cap cap) { - stroke = true; - } + @Override + public void setStrokeCap(Cap cap) { + stroke = true; + } - @Override - public void setStrokeWidth(float width) { - stroke = true; - strokeWidth = width; - } + @Override + public void setStrokeWidth(float width) { + stroke = true; + strokeWidth = width; + } - @Override - public void setStyle(Style style) { - } + @Override + public void setStyle(Style style) { + } - @Override - public void setTextAlign(Align align) { - mAlign = align; - } + @Override + public void setTextAlign(Align align) { + mAlign = align; + } - @Override - public void setTextSize(float size) { - fontSize = size; - buildFont(); - } + @Override + public void setTextSize(float size) { + fontSize = size; + buildFont(); + } - @Override - public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { - this.fontStyle = fontStyle; - //this.fontFamily = fontFamily; - buildFont(); - } + @Override + public void setTypeface(FontFamily fontFamily, FontStyle fontStyle) { + this.fontStyle = fontStyle; + //this.fontFamily = fontFamily; + buildFont(); + } - @Override - public float measureText(String text) { - return GwtGdxGraphics.getTextWidth(text, font); - } + @Override + public float measureText(String text) { + return GwtGdxGraphics.getTextWidth(text, font); + } - // FIXME all estimates. no idea how to properly measure canvas text.. - @Override - public float getFontHeight() { - return 2 + fontSize + strokeWidth * 2; - } + // FIXME all estimates. no idea how to properly measure canvas text.. + @Override + public float getFontHeight() { + return 2 + fontSize + strokeWidth * 2; + } - @Override - public float getFontDescent() { - return 4 + strokeWidth; - } + @Override + public float getFontDescent() { + return 4 + strokeWidth; + } - void buildFont() { - StringBuilder sb = new StringBuilder(); + void buildFont() { + StringBuilder sb = new StringBuilder(); - if (this.fontStyle == FontStyle.BOLD) - sb.append("bold "); - else if (this.fontStyle == FontStyle.ITALIC) - sb.append("italic "); + if (this.fontStyle == FontStyle.BOLD) + sb.append("bold "); + else if (this.fontStyle == FontStyle.ITALIC) + sb.append("italic "); - sb.append(Math.round(this.fontSize)); - sb.append("px "); + sb.append(Math.round(this.fontSize)); + sb.append("px "); - sb.append("Helvetica"); + sb.append("Helvetica"); - this.font = sb.toString(); + this.font = sb.toString(); - } + } } diff --git a/vtm-web/src/org/oscim/gdx/client/MapConfig.java b/vtm-web/src/org/oscim/gdx/client/MapConfig.java index 2f006137..9dc1e010 100644 --- a/vtm-web/src/org/oscim/gdx/client/MapConfig.java +++ b/vtm-web/src/org/oscim/gdx/client/MapConfig.java @@ -19,30 +19,30 @@ package org.oscim.gdx.client; import com.google.gwt.core.client.JavaScriptObject; public class MapConfig extends JavaScriptObject { - protected MapConfig() { - } + protected MapConfig() { + } - public static native MapConfig get()/*-{ - return $wnd.mapconfig; + public static native MapConfig get()/*-{ + return $wnd.mapconfig; }-*/; - public final native double getLatitude() /*-{ - return this.latitude || 0; + public final native double getLatitude() /*-{ + return this.latitude || 0; }-*/; - public final native double getLongitude() /*-{ + public final native double getLongitude() /*-{ return this.longitude || 0; }-*/; - public final native int getZoom() /*-{ + public final native int getZoom() /*-{ return this.zoom || 2; }-*/; - public final native String getTileSource() /*-{ + public final native String getTileSource() /*-{ return this.tilesource; }-*/; - public final native int getTileSize() /*-{ + public final native int getTileSize() /*-{ return this.tileSize || 256; }-*/; diff --git a/vtm-web/src/org/oscim/gdx/client/MapUrl.java b/vtm-web/src/org/oscim/gdx/client/MapUrl.java index 97b96773..fafc2f07 100644 --- a/vtm-web/src/org/oscim/gdx/client/MapUrl.java +++ b/vtm-web/src/org/oscim/gdx/client/MapUrl.java @@ -1,120 +1,120 @@ package org.oscim.gdx.client; -import java.util.HashMap; +import com.google.gwt.user.client.Timer; +import com.google.gwt.user.client.Window; import org.oscim.core.MapPosition; import org.oscim.core.MercatorProjection; import org.oscim.map.Map; -import com.google.gwt.user.client.Timer; -import com.google.gwt.user.client.Window; +import java.util.HashMap; public class MapUrl extends Timer { - private int curLon, curLat, curZoom, curTilt, curRot; - private MapPosition pos = new MapPosition(); - private final Map mMap; - private String mParams = ""; + private int curLon, curLat, curZoom, curTilt, curRot; + private MapPosition pos = new MapPosition(); + private final Map mMap; + private String mParams = ""; - public MapUrl(Map map) { - mMap = map; - } + public MapUrl(Map map) { + mMap = map; + } - public String getParam(String name) { - return params.get(name); - } + public String getParam(String name) { + return params.get(name); + } - public final HashMap params = new HashMap(); + public final HashMap params = new HashMap(); - public void parseUrl(MapPosition pos) { + public void parseUrl(MapPosition pos) { - //String addOpts = ""; - if (Window.Location.getHash() == null) - return; + //String addOpts = ""; + if (Window.Location.getHash() == null) + return; - String hash = Window.Location.getHash(); - hash = hash.substring(1); - String[] urlParams = null; - urlParams = hash.split("&"); - if (urlParams.length == 1) - urlParams = hash.split(","); - double lat = pos.getLatitude(), lon = pos.getLongitude(); - float rotation = pos.bearing; - float tilt = pos.tilt; + String hash = Window.Location.getHash(); + hash = hash.substring(1); + String[] urlParams = null; + urlParams = hash.split("&"); + if (urlParams.length == 1) + urlParams = hash.split(","); + double lat = pos.getLatitude(), lon = pos.getLongitude(); + float rotation = pos.bearing; + float tilt = pos.tilt; - //String themeName = ""; - //String mapName = ""; + //String themeName = ""; + //String mapName = ""; - int zoom = pos.zoomLevel; + int zoom = pos.zoomLevel; - for (String p : urlParams) { - try { - if (p.startsWith("lat=")) - lat = Double.parseDouble(p.substring(4)); + for (String p : urlParams) { + try { + if (p.startsWith("lat=")) + lat = Double.parseDouble(p.substring(4)); - else if (p.startsWith("lon=")) - lon = Double.parseDouble(p.substring(4)); - else if (p.startsWith("scale=")) - zoom = Integer.parseInt(p.substring(6)); - else if (p.startsWith("rot=")) - rotation = Float.parseFloat(p.substring(4)); - else if (p.startsWith("tilt=")) - tilt = Float.parseFloat(p.substring(5)); - // else if (p.startsWith("theme=")) - // themeName = p.substring(6); - // else if (p.startsWith("map=")) - // mapName = p.substring(4); - else { - String[] opt = p.split("="); - if (opt.length > 1) - params.put(opt[0], opt[1]); - else - params.put(opt[0], null); + else if (p.startsWith("lon=")) + lon = Double.parseDouble(p.substring(4)); + else if (p.startsWith("scale=")) + zoom = Integer.parseInt(p.substring(6)); + else if (p.startsWith("rot=")) + rotation = Float.parseFloat(p.substring(4)); + else if (p.startsWith("tilt=")) + tilt = Float.parseFloat(p.substring(5)); + // else if (p.startsWith("theme=")) + // themeName = p.substring(6); + // else if (p.startsWith("map=")) + // mapName = p.substring(4); + else { + String[] opt = p.split("="); + if (opt.length > 1) + params.put(opt[0], opt[1]); + else + params.put(opt[0], null); - mParams += p + "&"; + mParams += p + "&"; - } - } catch (NumberFormatException e) { + } + } catch (NumberFormatException e) { - } - } - pos.setPosition(lat, lon); - pos.setZoomLevel(zoom); - pos.set(MercatorProjection.longitudeToX(lon), - MercatorProjection.latitudeToY(lat), - 1 << zoom, - rotation, - tilt); + } + } + pos.setPosition(lat, lon); + pos.setZoomLevel(zoom); + pos.set(MercatorProjection.longitudeToX(lon), + MercatorProjection.latitudeToY(lat), + 1 << zoom, + rotation, + tilt); - } + } - @Override - public void run() { - mMap.viewport().getMapPosition(pos); - int lat = (int) (MercatorProjection.toLatitude(pos.y) * 1000); - int lon = (int) (MercatorProjection.toLongitude(pos.x) * 1000); - int rot = (int) (pos.bearing); - rot = (int) (pos.bearing) % 360; - //rot = rot < 0 ? -rot : rot; + @Override + public void run() { + mMap.viewport().getMapPosition(pos); + int lat = (int) (MercatorProjection.toLatitude(pos.y) * 1000); + int lon = (int) (MercatorProjection.toLongitude(pos.x) * 1000); + int rot = (int) (pos.bearing); + rot = (int) (pos.bearing) % 360; + //rot = rot < 0 ? -rot : rot; - if (curZoom != pos.zoomLevel || curLat != lat || curLon != lon - || curTilt != rot || curRot != (int) (pos.bearing)) { + if (curZoom != pos.zoomLevel || curLat != lat || curLon != lon + || curTilt != rot || curRot != (int) (pos.bearing)) { - curLat = lat; - curLon = lon; - curZoom = pos.zoomLevel; - curTilt = (int) pos.tilt; - curRot = rot; + curLat = lat; + curLon = lon; + curZoom = pos.zoomLevel; + curTilt = (int) pos.tilt; + curRot = rot; - String newURL = Window.Location - .createUrlBuilder() - .setHash(mParams - + "scale=" + pos.zoomLevel - + "&rot=" + curRot - + "&tilt=" + curTilt - + "&lat=" + (curLat / 1000f) - + "&lon=" + (curLon / 1000f)) - .buildString(); - Window.Location.replace(newURL); - } - } + String newURL = Window.Location + .createUrlBuilder() + .setHash(mParams + + "scale=" + pos.zoomLevel + + "&rot=" + curRot + + "&tilt=" + curTilt + + "&lat=" + (curLat / 1000f) + + "&lon=" + (curLon / 1000f)) + .buildString(); + Window.Location.replace(newURL); + } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtApplication.java b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtApplication.java index 0749720d..87d4f6b8 100644 --- a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtApplication.java +++ b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtApplication.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2011 See libgdx AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,9 +16,6 @@ package com.badlogic.gdx.backends.gwt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Audio; @@ -44,290 +41,297 @@ import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Panel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Implementation of an {@link Application} based on GWT. Clients have to * override {@link #getConfig()} and {@link #getApplicationListener()}. Clients * can override the default loading screen via {@link #getPreloaderCallback()} * and implement any loading screen drawing via GWT widgets. - * + * * @author mzechner */ public abstract class GwtApplication implements EntryPoint, Application { - private final static Logger log = LoggerFactory.getLogger(GwtApplication.class); + private final static Logger log = LoggerFactory.getLogger(GwtApplication.class); - private ApplicationListener listener; - private GwtApplicationConfiguration config; - private GwtGraphics graphics; - private GwtInput input; - private GwtNet net; - private int logLevel = LOG_ERROR; - private Array runnables = new Array(); - private Array runnablesHelper = new Array(); - private Array lifecycleListeners = new Array(); - private int lastWidth; - private int lastHeight; - Preloader preloader; - private static AgentInfo agentInfo; - private ObjectMap prefs = new ObjectMap(); + private ApplicationListener listener; + private GwtApplicationConfiguration config; + private GwtGraphics graphics; + private GwtInput input; + private GwtNet net; + private int logLevel = LOG_ERROR; + private Array runnables = new Array(); + private Array runnablesHelper = new Array(); + private Array lifecycleListeners = new Array(); + private int lastWidth; + private int lastHeight; + Preloader preloader; + private static AgentInfo agentInfo; + private ObjectMap prefs = new ObjectMap(); - /** @return the configuration for the {@link GwtApplication}. */ - public abstract GwtApplicationConfiguration getConfig(); + /** + * @return the configuration for the {@link GwtApplication}. + */ + public abstract GwtApplicationConfiguration getConfig(); - public String getPreloaderBaseURL() { - return GWT.getHostPageBaseURL() + "assets/"; - } + public String getPreloaderBaseURL() { + return GWT.getHostPageBaseURL() + "assets/"; + } - @Override - public void onModuleLoad() { - GwtApplication.agentInfo = computeAgentInfo(); - this.listener = getApplicationListener(); - this.config = getConfig(); + @Override + public void onModuleLoad() { + GwtApplication.agentInfo = computeAgentInfo(); + this.listener = getApplicationListener(); + this.config = getConfig(); - final PreloaderCallback callback = getPreloaderCallback(); - preloader = createPreloader(); - preloader.preload("assets.txt", new PreloaderCallback() { - @Override - public void error(String file) { - callback.error(file); - } + final PreloaderCallback callback = getPreloaderCallback(); + preloader = createPreloader(); + preloader.preload("assets.txt", new PreloaderCallback() { + @Override + public void error(String file) { + callback.error(file); + } - @Override - public void update(PreloaderState state) { - callback.update(state); - if (state.hasEnded()) { - //getRootPanel().clear(); - setupLoop(); - } - } - }); - } + @Override + public void update(PreloaderState state) { + callback.update(state); + if (state.hasEnded()) { + //getRootPanel().clear(); + setupLoop(); + } + } + }); + } - void setupLoop() { - Gdx.app = this; - // setup modules - try { - graphics = new GwtGraphics(null, config); - } catch (Throwable e) { - error("GwtApplication", "exception: " + e.getMessage(), e); - //root.clear(); - //root.add(new Label("Sorry, your browser doesn't seem to support WebGL")); - return; - } - lastWidth = graphics.getWidth(); - lastHeight = graphics.getHeight(); - Gdx.app = this; - Gdx.graphics = graphics; - Gdx.gl20 = graphics.getGL20(); - Gdx.gl = Gdx.gl20; - Gdx.files = new GwtFiles(preloader); - this.input = new GwtInput(graphics.canvas); - Gdx.input = this.input; - this.net = new GwtNet(); - Gdx.net = this.net; + void setupLoop() { + Gdx.app = this; + // setup modules + try { + graphics = new GwtGraphics(null, config); + } catch (Throwable e) { + error("GwtApplication", "exception: " + e.getMessage(), e); + //root.clear(); + //root.add(new Label("Sorry, your browser doesn't seem to support WebGL")); + return; + } + lastWidth = graphics.getWidth(); + lastHeight = graphics.getHeight(); + Gdx.app = this; + Gdx.graphics = graphics; + Gdx.gl20 = graphics.getGL20(); + Gdx.gl = Gdx.gl20; + Gdx.files = new GwtFiles(preloader); + this.input = new GwtInput(graphics.canvas); + Gdx.input = this.input; + this.net = new GwtNet(); + Gdx.net = this.net; - // tell listener about app creation - try { - listener.create(); - listener.resize(graphics.getWidth(), graphics.getHeight()); - } catch (Throwable t) { - error("GwtApplication", "exception: " + t.getMessage(), t); - t.printStackTrace(); - throw new RuntimeException(t); - } + // tell listener about app creation + try { + listener.create(); + listener.resize(graphics.getWidth(), graphics.getHeight()); + } catch (Throwable t) { + error("GwtApplication", "exception: " + t.getMessage(), t); + t.printStackTrace(); + throw new RuntimeException(t); + } - Gdx.gl.glClearColor(1, 1, 1, 1); - Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); + Gdx.gl.glClearColor(1, 1, 1, 1); + Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); - final int frameTime = (int) ((1f / config.fps) * 1000); + final int frameTime = (int) ((1f / config.fps) * 1000); - // setup rendering timer - new Timer() { - @Override - public void run() { - try { - mainLoop(this, frameTime); - } catch (Throwable t) { - error("GwtApplication", "exception: " + t.getMessage(), t); - throw new RuntimeException(t); - } - } - }.schedule(1); - } + // setup rendering timer + new Timer() { + @Override + public void run() { + try { + mainLoop(this, frameTime); + } catch (Throwable t) { + error("GwtApplication", "exception: " + t.getMessage(), t); + throw new RuntimeException(t); + } + } + }.schedule(1); + } - void mainLoop(Timer timer, int frameTime) { - graphics.update(); - if (Gdx.graphics.getWidth() != lastWidth || Gdx.graphics.getHeight() != lastHeight) { - GwtApplication.this.listener.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); - lastWidth = graphics.getWidth(); - lastHeight = graphics.getHeight(); - Gdx.gl.glViewport(0, 0, lastWidth, lastHeight); - } - runnablesHelper.addAll(runnables); - runnables.clear(); - for (int i = 0; i < runnablesHelper.size; i++) { - runnablesHelper.get(i).run(); - } - runnablesHelper.clear(); - listener.render(); - input.justTouched = false; + void mainLoop(Timer timer, int frameTime) { + graphics.update(); + if (Gdx.graphics.getWidth() != lastWidth || Gdx.graphics.getHeight() != lastHeight) { + GwtApplication.this.listener.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + lastWidth = graphics.getWidth(); + lastHeight = graphics.getHeight(); + Gdx.gl.glViewport(0, 0, lastWidth, lastHeight); + } + runnablesHelper.addAll(runnables); + runnables.clear(); + for (int i = 0; i < runnablesHelper.size; i++) { + runnablesHelper.get(i).run(); + } + runnablesHelper.clear(); + listener.render(); + input.justTouched = false; - long now = System.currentTimeMillis(); - int diff = (int) (now - graphics.lastTimeStamp); - diff = frameTime - diff; - timer.schedule(diff > 5 ? diff : 5); - } + long now = System.currentTimeMillis(); + int diff = (int) (now - graphics.lastTimeStamp); + diff = frameTime - diff; + timer.schedule(diff > 5 ? diff : 5); + } - public Panel getRootPanel() { - throw new GdxRuntimeException("no panel!"); - } + public Panel getRootPanel() { + throw new GdxRuntimeException("no panel!"); + } - long loadStart = TimeUtils.nanoTime(); + long loadStart = TimeUtils.nanoTime(); - public Preloader createPreloader() { - return new Preloader(getPreloaderBaseURL()); - } + public Preloader createPreloader() { + return new Preloader(getPreloaderBaseURL()); + } - public PreloaderCallback getPreloaderCallback() { - return null; - } + public PreloaderCallback getPreloaderCallback() { + return null; + } - @Override - public Graphics getGraphics() { - return graphics; - } + @Override + public Graphics getGraphics() { + return graphics; + } - @Override - public Audio getAudio() { - return Gdx.audio; - } + @Override + public Audio getAudio() { + return Gdx.audio; + } - @Override - public Input getInput() { - return Gdx.input; - } + @Override + public Input getInput() { + return Gdx.input; + } - @Override - public Files getFiles() { - return Gdx.files; - } + @Override + public Files getFiles() { + return Gdx.files; + } - @Override - public Net getNet() { - return Gdx.net; - } + @Override + public Net getNet() { + return Gdx.net; + } - @Override - public void log(String tag, String message) { - log.info("{} : {}", tag, message); - } + @Override + public void log(String tag, String message) { + log.info("{} : {}", tag, message); + } - @Override - public void log(String tag, String message, Throwable exception) { - log.info("{} : {}\n{}", tag, exception, getStackTrace(exception)); - } + @Override + public void log(String tag, String message, Throwable exception) { + log.info("{} : {}\n{}", tag, exception, getStackTrace(exception)); + } - @Override - public void error(String tag, String message) { - log.error("{} : {}", tag, message); - } + @Override + public void error(String tag, String message) { + log.error("{} : {}", tag, message); + } - @Override - public void error(String tag, String message, Throwable exception) { - log.error("{} : {}\n{}", tag, message, getStackTrace(exception)); - } + @Override + public void error(String tag, String message, Throwable exception) { + log.error("{} : {}\n{}", tag, message, getStackTrace(exception)); + } - @Override - public void debug(String tag, String message) { - log.debug("{} : {}", tag, message); - } + @Override + public void debug(String tag, String message) { + log.debug("{} : {}", tag, message); + } - @Override - public void debug(String tag, String message, Throwable exception) { - log.debug("{} : {}\n{}", tag, message, getStackTrace(exception)); - } + @Override + public void debug(String tag, String message, Throwable exception) { + log.debug("{} : {}\n{}", tag, message, getStackTrace(exception)); + } - private String getStackTrace(Throwable e) { - StringBuffer buffer = new StringBuffer(); - for (StackTraceElement trace : e.getStackTrace()) { - buffer.append(trace.toString() + "\n"); - } - return buffer.toString(); - } + private String getStackTrace(Throwable e) { + StringBuffer buffer = new StringBuffer(); + for (StackTraceElement trace : e.getStackTrace()) { + buffer.append(trace.toString() + "\n"); + } + return buffer.toString(); + } - @Override - public void setLogLevel(int logLevel) { - } + @Override + public void setLogLevel(int logLevel) { + } - @Override - public int getLogLevel() { - return LOG_DEBUG; - } + @Override + public int getLogLevel() { + return LOG_DEBUG; + } - @Override - public ApplicationType getType() { - return ApplicationType.WebGL; - } + @Override + public ApplicationType getType() { + return ApplicationType.WebGL; + } - @Override - public int getVersion() { - return 0; - } + @Override + public int getVersion() { + return 0; + } - @Override - public long getJavaHeap() { - return 0; - } + @Override + public long getJavaHeap() { + return 0; + } - @Override - public long getNativeHeap() { - return 0; - } + @Override + public long getNativeHeap() { + return 0; + } - @Override - public Preferences getPreferences(String name) { - Preferences pref = prefs.get(name); - if (pref == null) { - pref = new GwtPreferences(name); - prefs.put(name, pref); - } - return pref; - } + @Override + public Preferences getPreferences(String name) { + Preferences pref = prefs.get(name); + if (pref == null) { + pref = new GwtPreferences(name); + prefs.put(name, pref); + } + return pref; + } - @Override - public Clipboard getClipboard() { - return new Clipboard() { - @Override - public String getContents() { - return null; - } + @Override + public Clipboard getClipboard() { + return new Clipboard() { + @Override + public String getContents() { + return null; + } - @Override - public void setContents(String content) { - } - }; - } + @Override + public void setContents(String content) { + } + }; + } - @Override - public void postRunnable(Runnable runnable) { - runnables.add(runnable); - } + @Override + public void postRunnable(Runnable runnable) { + runnables.add(runnable); + } - @Override - public void exit() { - } + @Override + public void exit() { + } - /** - * Contains precomputed information on the user-agent. Useful for dealing - * with browser and OS behavioral differences. Kindly - * borrowed from PlayN - */ - public static AgentInfo agentInfo() { - return agentInfo; - } + /** + * Contains precomputed information on the user-agent. Useful for dealing + * with browser and OS behavioral differences. Kindly + * borrowed from PlayN + */ + public static AgentInfo agentInfo() { + return agentInfo; + } - /** kindly borrowed from PlayN **/ - private static native AgentInfo computeAgentInfo() /*-{ - var userAgent = navigator.userAgent.toLowerCase(); + /** + * kindly borrowed from PlayN + **/ + private static native AgentInfo computeAgentInfo() /*-{ + var userAgent = navigator.userAgent.toLowerCase(); return { // browser type flags isFirefox : userAgent.indexOf("firefox") != -1, @@ -342,63 +346,65 @@ public abstract class GwtApplication implements EntryPoint, Application { }; }-*/; - /** Returned by {@link #agentInfo}. Kindly borrowed from PlayN. */ - public static class AgentInfo extends JavaScriptObject { - public final native boolean isFirefox() /*-{ - return this.isFirefox; + /** + * Returned by {@link #agentInfo}. Kindly borrowed from PlayN. + */ + public static class AgentInfo extends JavaScriptObject { + public final native boolean isFirefox() /*-{ + return this.isFirefox; }-*/; - public final native boolean isChrome() /*-{ + public final native boolean isChrome() /*-{ return this.isChrome; }-*/; - public final native boolean isSafari() /*-{ + public final native boolean isSafari() /*-{ return this.isSafari; }-*/; - public final native boolean isOpera() /*-{ + public final native boolean isOpera() /*-{ return this.isOpera; }-*/; - public final native boolean isIE() /*-{ + public final native boolean isIE() /*-{ return this.isIE; }-*/; - public final native boolean isMacOS() /*-{ + public final native boolean isMacOS() /*-{ return this.isMacOS; }-*/; - public final native boolean isLinux() /*-{ + public final native boolean isLinux() /*-{ return this.isLinux; }-*/; - public final native boolean isWindows() /*-{ + public final native boolean isWindows() /*-{ return this.isWindows; }-*/; - protected AgentInfo() { - } - } + protected AgentInfo() { + } + } - public String getBaseUrl() { - return preloader.baseUrl; - } + public String getBaseUrl() { + return preloader.baseUrl; + } - public Preloader getPreloader() { - return preloader; - } + public Preloader getPreloader() { + return preloader; + } - @Override - public void addLifecycleListener(LifecycleListener listener) { - synchronized (lifecycleListeners) { - lifecycleListeners.add(listener); - } - } + @Override + public void addLifecycleListener(LifecycleListener listener) { + synchronized (lifecycleListeners) { + lifecycleListeners.add(listener); + } + } - @Override - public void removeLifecycleListener(LifecycleListener listener) { - synchronized (lifecycleListeners) { - lifecycleListeners.removeValue(listener, true); - } - } + @Override + public void removeLifecycleListener(LifecycleListener listener) { + synchronized (lifecycleListeners) { + lifecycleListeners.removeValue(listener, true); + } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtGraphics.java b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtGraphics.java index 1721f083..a8199ed3 100644 --- a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtGraphics.java +++ b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtGraphics.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2011 See libgdx AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,10 +16,6 @@ package com.badlogic.gdx.backends.gwt; -import org.oscim.gdx.client.GdxGL; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics; import com.badlogic.gdx.graphics.GL20; @@ -33,154 +29,158 @@ import com.google.gwt.user.client.ui.Panel; import com.google.gwt.webgl.client.WebGLContextAttributes; import com.google.gwt.webgl.client.WebGLRenderingContext; +import org.oscim.gdx.client.GdxGL; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class GwtGraphics implements Graphics { - static final Logger log = LoggerFactory.getLogger(GwtGraphics.class); + static final Logger log = LoggerFactory.getLogger(GwtGraphics.class); - CanvasElement canvas; - WebGLRenderingContext context; - GL20 gl; - String extensions; - float fps = 0; - long lastTimeStamp = System.currentTimeMillis(); - float deltaTime = 0; - float time = 0; - int frames; - GwtApplicationConfiguration config; - boolean inFullscreenMode = false; - double pixelRatio; + CanvasElement canvas; + WebGLRenderingContext context; + GL20 gl; + String extensions; + float fps = 0; + long lastTimeStamp = System.currentTimeMillis(); + float deltaTime = 0; + float time = 0; + int frames; + GwtApplicationConfiguration config; + boolean inFullscreenMode = false; + double pixelRatio; - public GwtGraphics(Panel root, final GwtApplicationConfiguration config) { - this.pixelRatio = getDevicePixelRatioJSNI(); + public GwtGraphics(Panel root, final GwtApplicationConfiguration config) { + this.pixelRatio = getDevicePixelRatioJSNI(); - if (config.canvasId == null) { - Canvas canvasWidget = Canvas.createIfSupported(); - if (canvasWidget == null) - throw new GdxRuntimeException("Canvas not supported"); - canvas = canvasWidget.getCanvasElement(); - root.add(canvasWidget); - } else { - canvas = (CanvasElement) Document.get().getElementById(config.canvasId); + if (config.canvasId == null) { + Canvas canvasWidget = Canvas.createIfSupported(); + if (canvasWidget == null) + throw new GdxRuntimeException("Canvas not supported"); + canvas = canvasWidget.getCanvasElement(); + root.add(canvasWidget); + } else { + canvas = (CanvasElement) Document.get().getElementById(config.canvasId); - canvas.setWidth((int) (config.width * pixelRatio)); - canvas.setHeight((int) (config.height * pixelRatio)); + canvas.setWidth((int) (config.width * pixelRatio)); + canvas.setHeight((int) (config.height * pixelRatio)); - canvas.getStyle().setWidth(config.width, Unit.PX); - canvas.getStyle().setHeight(config.height, Unit.PX); - } + canvas.getStyle().setWidth(config.width, Unit.PX); + canvas.getStyle().setHeight(config.height, Unit.PX); + } - this.config = config; + this.config = config; - WebGLContextAttributes attributes = WebGLContextAttributes.create(); - attributes.setAntialias(config.antialiasing); - attributes.setStencil(config.stencil); - attributes.setAlpha(false); - attributes.setPremultipliedAlpha(false); + WebGLContextAttributes attributes = WebGLContextAttributes.create(); + attributes.setAntialias(config.antialiasing); + attributes.setStencil(config.stencil); + attributes.setAlpha(false); + attributes.setPremultipliedAlpha(false); - context = WebGLRenderingContext.getContext(canvas, attributes); - if (context == null) - throw new GdxRuntimeException("Could not create Canvas for " + attributes); + context = WebGLRenderingContext.getContext(canvas, attributes); + if (context == null) + throw new GdxRuntimeException("Could not create Canvas for " + attributes); - context.viewport(0, 0, config.width, config.height); + context.viewport(0, 0, config.width, config.height); - // this actually *enables* the option to use std derivatives in shader.. - if (context.getExtension("OES_standard_derivatives") == null) { - log.error("Missing gl extension for OES_standard_derivatives"); - } + // this actually *enables* the option to use std derivatives in shader.. + if (context.getExtension("OES_standard_derivatives") == null) { + log.error("Missing gl extension for OES_standard_derivatives"); + } - if (context.getExtension("WEBKIT_WEBGL_depth_texture") == null) { - log.error("Missing gl extension for WEBKIT_WEBGL_depth_texture"); - } + if (context.getExtension("WEBKIT_WEBGL_depth_texture") == null) { + log.error("Missing gl extension for WEBKIT_WEBGL_depth_texture"); + } - this.gl = config.useDebugGL ? new GwtGL20Debug(context) : new GdxGL(context); - } + this.gl = config.useDebugGL ? new GwtGL20Debug(context) : new GdxGL(context); + } - public static native double getDevicePixelRatioJSNI() /*-{ - return $wnd.devicePixelRatio || 1.0; + public static native double getDevicePixelRatioJSNI() /*-{ + return $wnd.devicePixelRatio || 1.0; }-*/; - public static native int getWindowWidthJSNI() /*-{ - return $wnd.innerWidth; + public static native int getWindowWidthJSNI() /*-{ + return $wnd.innerWidth; }-*/; - public static native int getWindowHeightJSNI() /*-{ + public static native int getWindowHeightJSNI() /*-{ return $wnd.innerHeight; }-*/; - public WebGLRenderingContext getContext() { - return context; - } + public WebGLRenderingContext getContext() { + return context; + } - @Override - public GL20 getGL20() { - return gl; - } + @Override + public GL20 getGL20() { + return gl; + } - @Override - public int getWidth() { - return canvas.getWidth(); - } + @Override + public int getWidth() { + return canvas.getWidth(); + } - @Override - public int getHeight() { - return canvas.getHeight(); - } + @Override + public int getHeight() { + return canvas.getHeight(); + } - @Override - public float getDeltaTime() { - return deltaTime; - } + @Override + public float getDeltaTime() { + return deltaTime; + } - @Override - public int getFramesPerSecond() { - return (int) fps; - } + @Override + public int getFramesPerSecond() { + return (int) fps; + } - @Override - public GraphicsType getType() { - return GraphicsType.WebGL; - } + @Override + public GraphicsType getType() { + return GraphicsType.WebGL; + } - @Override - public float getPpiX() { - return 96; - } + @Override + public float getPpiX() { + return 96; + } - @Override - public float getPpiY() { - return 96; - } + @Override + public float getPpiY() { + return 96; + } - @Override - public float getPpcX() { - return 96 / 2.54f; - } + @Override + public float getPpcX() { + return 96 / 2.54f; + } - @Override - public float getPpcY() { - return 96 / 2.54f; - } + @Override + public float getPpcY() { + return 96 / 2.54f; + } - @Override - public boolean supportsDisplayModeChange() { - return true; - } + @Override + public boolean supportsDisplayModeChange() { + return true; + } - @Override - public DisplayMode[] getDisplayModes() { - return new DisplayMode[] { new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, - 8) { - } }; - } + @Override + public DisplayMode[] getDisplayModes() { + return new DisplayMode[]{new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, + 8) { + }}; + } - private native int getScreenWidthJSNI() /*-{ + private native int getScreenWidthJSNI() /*-{ return $wnd.screen.width; }-*/; - private native int getScreenHeightJSNI() /*-{ + private native int getScreenHeightJSNI() /*-{ return $wnd.screen.height; }-*/; - private native boolean isFullscreenJSNI() /*-{ + private native boolean isFullscreenJSNI() /*-{ if ("webkitIsFullScreen" in $doc) { return $doc.webkitIsFullScreen; } @@ -190,14 +190,14 @@ public class GwtGraphics implements Graphics { return false }-*/; - private void fullscreenChanged() { - if (!isFullscreen()) { - canvas.setWidth(config.width); - canvas.setHeight(config.height); - } - } + private void fullscreenChanged() { + if (!isFullscreen()) { + canvas.setWidth(config.width); + canvas.setHeight(config.height); + } + } - private native boolean setFullscreenJSNI(GwtGraphics graphics, CanvasElement element) /*-{ + private native boolean setFullscreenJSNI(GwtGraphics graphics, CanvasElement element) /*-{ if (element.webkitRequestFullScreen) { element.width = $wnd.screen.width; element.height = $wnd.screen.height; @@ -225,118 +225,118 @@ public class GwtGraphics implements Graphics { return false; }-*/; - private native void exitFullscreen() /*-{ + private native void exitFullscreen() /*-{ if ($doc.webkitExitFullscreen) $doc.webkitExitFullscreen(); if ($doc.mozExitFullscreen) $doc.mozExitFullscreen(); }-*/; - @Override - public DisplayMode getDesktopDisplayMode() { - return new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, 8) { - }; - } + @Override + public DisplayMode getDesktopDisplayMode() { + return new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, 8) { + }; + } - @Override - public boolean setDisplayMode(DisplayMode displayMode) { - if (displayMode.width != getScreenWidthJSNI() - && displayMode.height != getScreenHeightJSNI()) - return false; - return setFullscreenJSNI(this, canvas); - } + @Override + public boolean setDisplayMode(DisplayMode displayMode) { + if (displayMode.width != getScreenWidthJSNI() + && displayMode.height != getScreenHeightJSNI()) + return false; + return setFullscreenJSNI(this, canvas); + } - @Override - public boolean setDisplayMode(int width, int height, boolean fullscreen) { - if (fullscreen) { - if (width != getScreenWidthJSNI() && height != getScreenHeightJSNI()) - return false; - return setFullscreenJSNI(this, canvas); - } else { - if (isFullscreenJSNI()) - exitFullscreen(); - canvas.setWidth(width); - canvas.setHeight(height); - canvas.getStyle().setWidth(width, Unit.PX); - canvas.getStyle().setHeight(height, Unit.PX); - return true; - } - } + @Override + public boolean setDisplayMode(int width, int height, boolean fullscreen) { + if (fullscreen) { + if (width != getScreenWidthJSNI() && height != getScreenHeightJSNI()) + return false; + return setFullscreenJSNI(this, canvas); + } else { + if (isFullscreenJSNI()) + exitFullscreen(); + canvas.setWidth(width); + canvas.setHeight(height); + canvas.getStyle().setWidth(width, Unit.PX); + canvas.getStyle().setHeight(height, Unit.PX); + return true; + } + } - @Override - public BufferFormat getBufferFormat() { - return new BufferFormat(8, 8, 8, 0, 16, config.stencil ? 8 : 0, 0, false); - } + @Override + public BufferFormat getBufferFormat() { + return new BufferFormat(8, 8, 8, 0, 16, config.stencil ? 8 : 0, 0, false); + } - @Override - public boolean supportsExtension(String extension) { - if (extensions == null) - extensions = Gdx.gl.glGetString(GL20.GL_EXTENSIONS); - return extensions.contains(extension); - } + @Override + public boolean supportsExtension(String extension) { + if (extensions == null) + extensions = Gdx.gl.glGetString(GL20.GL_EXTENSIONS); + return extensions.contains(extension); + } - public void update() { - long currTimeStamp = System.currentTimeMillis(); - deltaTime = (currTimeStamp - lastTimeStamp) / 1000.0f; - lastTimeStamp = currTimeStamp; - time += deltaTime; - frames++; - if (time > 1) { - this.fps = frames; - time = 0; - frames = 0; - } - } + public void update() { + long currTimeStamp = System.currentTimeMillis(); + deltaTime = (currTimeStamp - lastTimeStamp) / 1000.0f; + lastTimeStamp = currTimeStamp; + time += deltaTime; + frames++; + if (time > 1) { + this.fps = frames; + time = 0; + frames = 0; + } + } - @Override - public void setTitle(String title) { - } + @Override + public void setTitle(String title) { + } - @Override - public void setVSync(boolean vsync) { - } + @Override + public void setVSync(boolean vsync) { + } - @Override - public float getDensity() { - return 96.0f / 160; - } + @Override + public float getDensity() { + return 96.0f / 160; + } - @Override - public void setContinuousRendering(boolean isContinuous) { - } + @Override + public void setContinuousRendering(boolean isContinuous) { + } - @Override - public boolean isContinuousRendering() { - return false; - } + @Override + public boolean isContinuousRendering() { + return false; + } - @Override - public void requestRendering() { - } + @Override + public void requestRendering() { + } - @Override - public float getRawDeltaTime() { - return getDeltaTime(); - } + @Override + public float getRawDeltaTime() { + return getDeltaTime(); + } - @Override - public boolean isFullscreen() { - return isFullscreenJSNI(); - } + @Override + public boolean isFullscreen() { + return isFullscreenJSNI(); + } - @Override - public boolean isGL30Available() { - return false; - } + @Override + public boolean isGL30Available() { + return false; + } - @Override - public GL30 getGL30() { - return null; - } + @Override + public GL30 getGL30() { + return null; + } - @Override - public long getFrameId() { - // TODO Auto-generated method stub - return 0; - } + @Override + public long getFrameId() { + // TODO Auto-generated method stub + return 0; + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtInput.java b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtInput.java index 3be2b71d..b46262ea 100644 --- a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtInput.java +++ b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/backends/gwt/GwtInput.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,9 +16,6 @@ package com.badlogic.gdx.backends.gwt; -import java.util.HashSet; -import java.util.Set; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; @@ -34,243 +31,246 @@ import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.dom.client.KeyCodes; +import java.util.HashSet; +import java.util.Set; + public class GwtInput implements Input { - boolean justTouched = false; - private boolean[] touched = new boolean[20]; - private int[] touchX = new int[20]; - private int[] touchY = new int[20]; - private int[] deltaX = new int[20]; - private int[] deltaY = new int[20]; - Set pressedButtons = new HashSet(); - Set pressedKeys = new HashSet(); - InputProcessor processor; - char lastKeyCharPressed; - float keyRepeatTimer; - long currentEventTimeStamp; - final CanvasElement canvas; - boolean hasFocus = true; + boolean justTouched = false; + private boolean[] touched = new boolean[20]; + private int[] touchX = new int[20]; + private int[] touchY = new int[20]; + private int[] deltaX = new int[20]; + private int[] deltaY = new int[20]; + Set pressedButtons = new HashSet(); + Set pressedKeys = new HashSet(); + InputProcessor processor; + char lastKeyCharPressed; + float keyRepeatTimer; + long currentEventTimeStamp; + final CanvasElement canvas; + boolean hasFocus = true; - public GwtInput(CanvasElement canvas) { - this.canvas = canvas; - hookEvents(); - } + public GwtInput(CanvasElement canvas) { + this.canvas = canvas; + hookEvents(); + } - @Override - public float getAccelerometerX() { - return 0; - } + @Override + public float getAccelerometerX() { + return 0; + } - @Override - public float getAccelerometerY() { - return 0; - } + @Override + public float getAccelerometerY() { + return 0; + } - @Override - public float getAccelerometerZ() { - return 0; - } + @Override + public float getAccelerometerZ() { + return 0; + } - @Override - public int getX() { - return touchX[0]; - } + @Override + public int getX() { + return touchX[0]; + } - @Override - public int getX(int pointer) { - return touchX[pointer]; - } + @Override + public int getX(int pointer) { + return touchX[pointer]; + } - @Override - public int getDeltaX() { - return deltaX[0]; - } + @Override + public int getDeltaX() { + return deltaX[0]; + } - @Override - public int getDeltaX(int pointer) { - return deltaX[pointer]; - } + @Override + public int getDeltaX(int pointer) { + return deltaX[pointer]; + } - @Override - public int getY() { - return touchY[0]; - } + @Override + public int getY() { + return touchY[0]; + } - @Override - public int getY(int pointer) { - return touchY[pointer]; - } + @Override + public int getY(int pointer) { + return touchY[pointer]; + } - @Override - public int getDeltaY() { - return deltaY[0]; - } + @Override + public int getDeltaY() { + return deltaY[0]; + } - @Override - public int getDeltaY(int pointer) { - return deltaY[pointer]; - } + @Override + public int getDeltaY(int pointer) { + return deltaY[pointer]; + } - @Override - public boolean isTouched() { - return touched[0]; - } + @Override + public boolean isTouched() { + return touched[0]; + } - @Override - public boolean justTouched() { - return justTouched; - } + @Override + public boolean justTouched() { + return justTouched; + } - @Override - public boolean isTouched(int pointer) { - return touched[pointer]; - } + @Override + public boolean isTouched(int pointer) { + return touched[pointer]; + } - @Override - public boolean isButtonPressed(int button) { - return button == Buttons.LEFT && touched[0]; - } + @Override + public boolean isButtonPressed(int button) { + return button == Buttons.LEFT && touched[0]; + } - @Override - public boolean isKeyPressed(int key) { - if (key == Keys.ANY_KEY) - return pressedKeys.size() > 0; - return pressedKeys.contains(key); - } + @Override + public boolean isKeyPressed(int key) { + if (key == Keys.ANY_KEY) + return pressedKeys.size() > 0; + return pressedKeys.contains(key); + } - @Override - public void getTextInput(TextInputListener listener, String title, String text) { - TextInputDialogBox dialog = new TextInputDialogBox(title, text, null); - final TextInputListener capturedListener = listener; - dialog.setListener(new TextInputDialogListener() { - @Override - public void onPositive(String text) { - if (capturedListener != null) { - capturedListener.input(text); - } - } + @Override + public void getTextInput(TextInputListener listener, String title, String text) { + TextInputDialogBox dialog = new TextInputDialogBox(title, text, null); + final TextInputListener capturedListener = listener; + dialog.setListener(new TextInputDialogListener() { + @Override + public void onPositive(String text) { + if (capturedListener != null) { + capturedListener.input(text); + } + } - @Override - public void onNegative() { - if (capturedListener != null) { - capturedListener.canceled(); - } - } - }); - } + @Override + public void onNegative() { + if (capturedListener != null) { + capturedListener.canceled(); + } + } + }); + } - @Override - public void getPlaceholderTextInput(TextInputListener listener, String title, String placeholder) { - TextInputDialogBox dialog = new TextInputDialogBox(title, null, placeholder); - final TextInputListener capturedListener = listener; - dialog.setListener(new TextInputDialogListener() { - @Override - public void onPositive(String text) { - if (capturedListener != null) { - capturedListener.input(text); - } - } + @Override + public void getPlaceholderTextInput(TextInputListener listener, String title, String placeholder) { + TextInputDialogBox dialog = new TextInputDialogBox(title, null, placeholder); + final TextInputListener capturedListener = listener; + dialog.setListener(new TextInputDialogListener() { + @Override + public void onPositive(String text) { + if (capturedListener != null) { + capturedListener.input(text); + } + } - @Override - public void onNegative() { - if (capturedListener != null) { - capturedListener.canceled(); - } - } - }); - } + @Override + public void onNegative() { + if (capturedListener != null) { + capturedListener.canceled(); + } + } + }); + } - @Override - public void setOnscreenKeyboardVisible(boolean visible) { - } + @Override + public void setOnscreenKeyboardVisible(boolean visible) { + } - @Override - public void vibrate(int milliseconds) { - } + @Override + public void vibrate(int milliseconds) { + } - @Override - public void vibrate(long[] pattern, int repeat) { - } + @Override + public void vibrate(long[] pattern, int repeat) { + } - @Override - public void cancelVibrate() { - } + @Override + public void cancelVibrate() { + } - @Override - public float getAzimuth() { - return 0; - } + @Override + public float getAzimuth() { + return 0; + } - @Override - public float getPitch() { - return 0; - } + @Override + public float getPitch() { + return 0; + } - @Override - public float getRoll() { - return 0; - } + @Override + public float getRoll() { + return 0; + } - @Override - public void getRotationMatrix(float[] matrix) { - } + @Override + public void getRotationMatrix(float[] matrix) { + } - @Override - public long getCurrentEventTime() { - return currentEventTimeStamp; - } + @Override + public long getCurrentEventTime() { + return currentEventTimeStamp; + } - @Override - public void setCatchBackKey(boolean catchBack) { - } + @Override + public void setCatchBackKey(boolean catchBack) { + } - @Override - public void setCatchMenuKey(boolean catchMenu) { - } + @Override + public void setCatchMenuKey(boolean catchMenu) { + } - @Override - public void setInputProcessor(InputProcessor processor) { - this.processor = processor; - } + @Override + public void setInputProcessor(InputProcessor processor) { + this.processor = processor; + } - @Override - public InputProcessor getInputProcessor() { - return processor; - } + @Override + public InputProcessor getInputProcessor() { + return processor; + } - @Override - public boolean isPeripheralAvailable(Peripheral peripheral) { - if (peripheral == Peripheral.Accelerometer) - return false; - if (peripheral == Peripheral.Compass) - return false; - if (peripheral == Peripheral.HardwareKeyboard) - return true; - if (peripheral == Peripheral.MultitouchScreen) - return isTouchScreen(); - if (peripheral == Peripheral.OnscreenKeyboard) - return false; - if (peripheral == Peripheral.Vibrator) - return false; - return false; - } + @Override + public boolean isPeripheralAvailable(Peripheral peripheral) { + if (peripheral == Peripheral.Accelerometer) + return false; + if (peripheral == Peripheral.Compass) + return false; + if (peripheral == Peripheral.HardwareKeyboard) + return true; + if (peripheral == Peripheral.MultitouchScreen) + return isTouchScreen(); + if (peripheral == Peripheral.OnscreenKeyboard) + return false; + if (peripheral == Peripheral.Vibrator) + return false; + return false; + } - @Override - public int getRotation() { - return 0; - } + @Override + public int getRotation() { + return 0; + } - @Override - public Orientation getNativeOrientation() { - return Orientation.Landscape; - } + @Override + public Orientation getNativeOrientation() { + return Orientation.Landscape; + } - /** - * from https://github.com/toji/game-shim/blob/master/game-shim.js - * - * @return is Cursor catched - */ - private native boolean isCursorCatchedJSNI() /*-{ - if (!navigator.pointer) { + /** + * from https://github.com/toji/game-shim/blob/master/game-shim.js + * + * @return is Cursor catched + */ + private native boolean isCursorCatchedJSNI() /*-{ + if (!navigator.pointer) { navigator.pointer = navigator.webkitPointer || navigator.mozPointer; } if (navigator.pointer) { @@ -288,13 +288,13 @@ public class GwtInput implements Input { return false; }-*/; - /** - * from https://github.com/toji/game-shim/blob/master/game-shim.js - * - * @param element Canvas - */ - private native void setCursorCatchedJSNI(CanvasElement element) /*-{ - // Navigator pointer is not the right interface according to spec. + /** + * from https://github.com/toji/game-shim/blob/master/game-shim.js + * + * @param element Canvas + */ + private native void setCursorCatchedJSNI(CanvasElement element) /*-{ + // Navigator pointer is not the right interface according to spec. // Here for backwards compatibility only if (!navigator.pointer) { navigator.pointer = navigator.webkitPointer || navigator.mozPointer; @@ -313,8 +313,10 @@ public class GwtInput implements Input { element.requestPointerLock(); }-*/; - /** from https://github.com/toji/game-shim/blob/master/game-shim.js */ - private native void exitCursorCatchedJSNI() /*-{ + /** + * from https://github.com/toji/game-shim/blob/master/game-shim.js + */ + private native void exitCursorCatchedJSNI() /*-{ if (!$doc.exitPointerLock) { $doc.exitPointerLock = (function() { return $doc.webkitExitPointerLock || $doc.mozExitPointerLock @@ -328,60 +330,60 @@ public class GwtInput implements Input { } }-*/; - /** - * from https://github.com/toji/game-shim/blob/master/game-shim.js - * - * @param event JavaScript Mouse Event - * @return movement in x direction - */ - private native float getMovementXJSNI(NativeEvent event) /*-{ + /** + * from https://github.com/toji/game-shim/blob/master/game-shim.js + * + * @param event JavaScript Mouse Event + * @return movement in x direction + */ + private native float getMovementXJSNI(NativeEvent event) /*-{ return event.movementX || event.webkitMovementX || 0; }-*/; - /** - * from https://github.com/toji/game-shim/blob/master/game-shim.js - * - * @param event JavaScript Mouse Event - * @return movement in y direction - */ - private native float getMovementYJSNI(NativeEvent event) /*-{ + /** + * from https://github.com/toji/game-shim/blob/master/game-shim.js + * + * @param event JavaScript Mouse Event + * @return movement in y direction + */ + private native float getMovementYJSNI(NativeEvent event) /*-{ return event.movementY || event.webkitMovementY || 0; }-*/; - private static native boolean isTouchScreen() /*-{ + private static native boolean isTouchScreen() /*-{ return (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)); }-*/; - /** - * works only for Chrome > Version 18 with enabled Mouse Lock enable in - * about:flags or start Chrome with the - * --enable-pointer-lock flag - */ - @Override - public void setCursorCatched(boolean catched) { - if (catched) - setCursorCatchedJSNI(canvas); - else - exitCursorCatchedJSNI(); - } + /** + * works only for Chrome > Version 18 with enabled Mouse Lock enable in + * about:flags or start Chrome with the + * --enable-pointer-lock flag + */ + @Override + public void setCursorCatched(boolean catched) { + if (catched) + setCursorCatchedJSNI(canvas); + else + exitCursorCatchedJSNI(); + } - @Override - public boolean isCursorCatched() { - return isCursorCatchedJSNI(); - } + @Override + public boolean isCursorCatched() { + return isCursorCatchedJSNI(); + } - @Override - public void setCursorPosition(int x, int y) { - // FIXME?? - } + @Override + public void setCursorPosition(int x, int y) { + // FIXME?? + } - @Override - public void setCursorImage(Pixmap pixmap, int xHotspot, int yHotspot) { - } + @Override + public void setCursorImage(Pixmap pixmap, int xHotspot, int yHotspot) { + } - // kindly borrowed from our dear playn friends... - static native void addEventListener(JavaScriptObject target, String name, GwtInput handler, - boolean capture) /*-{ + // kindly borrowed from our dear playn friends... + static native void addEventListener(JavaScriptObject target, String name, GwtInput handler, + boolean capture) /*-{ target .addEventListener( name, @@ -390,7 +392,7 @@ public class GwtInput implements Input { }, capture); }-*/; - private static native float getMouseWheelVelocity(NativeEvent evt) /*-{ + private static native float getMouseWheelVelocity(NativeEvent evt) /*-{ var delta = 0.0; var agentInfo = @com.badlogic.gdx.backends.gwt.GwtApplication::agentInfo()(); @@ -421,8 +423,10 @@ public class GwtInput implements Input { return delta; }-*/; - /** Kindly borrowed from PlayN. **/ - protected static native String getMouseWheelEvent() /*-{ + /** + * Kindly borrowed from PlayN. + **/ + protected static native String getMouseWheelEvent() /*-{ if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) { return "DOMMouseScroll"; } else { @@ -430,530 +434,536 @@ public class GwtInput implements Input { } }-*/; - /** Kindly borrowed from PlayN. **/ - protected static float getRelativeX(NativeEvent e, Element target) { - return e.getClientX() - target.getAbsoluteLeft() + target.getScrollLeft() - + target.getOwnerDocument().getScrollLeft(); - } + /** + * Kindly borrowed from PlayN. + **/ + protected static float getRelativeX(NativeEvent e, Element target) { + return e.getClientX() - target.getAbsoluteLeft() + target.getScrollLeft() + + target.getOwnerDocument().getScrollLeft(); + } - /** Kindly borrowed from PlayN. **/ - protected static float getRelativeY(NativeEvent e, Element target) { - return e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() - + target.getOwnerDocument().getScrollTop(); - } + /** + * Kindly borrowed from PlayN. + **/ + protected static float getRelativeY(NativeEvent e, Element target) { + return e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() + + target.getOwnerDocument().getScrollTop(); + } - private void hookEvents() { - addEventListener(canvas, "mousedown", this, true); - // addEventListener(Document.get(), "mousedown", this, true); - addEventListener(canvas, "mouseup", this, true); - // addEventListener(Document.get(), "mouseup", this, true); - addEventListener(canvas, "mousemove", this, true); - // addEventListener(Document.get(), "mousemove", this, true); - addEventListener(canvas, getMouseWheelEvent(), this, true); - // addEventListener(Document.get(), "keydown", this, false); - // addEventListener(Document.get(), "keyup", this, false); - // addEventListener(Document.get(), "keypress", this, false); - addEventListener(canvas, "keydown", this, false); - addEventListener(canvas, "keyup", this, false); - addEventListener(canvas, "keypress", this, false); - addEventListener(canvas, "touchstart", this, true); - addEventListener(canvas, "touchmove", this, true); - addEventListener(canvas, "touchcancel", this, true); - addEventListener(canvas, "touchend", this, true); + private void hookEvents() { + addEventListener(canvas, "mousedown", this, true); + // addEventListener(Document.get(), "mousedown", this, true); + addEventListener(canvas, "mouseup", this, true); + // addEventListener(Document.get(), "mouseup", this, true); + addEventListener(canvas, "mousemove", this, true); + // addEventListener(Document.get(), "mousemove", this, true); + addEventListener(canvas, getMouseWheelEvent(), this, true); + // addEventListener(Document.get(), "keydown", this, false); + // addEventListener(Document.get(), "keyup", this, false); + // addEventListener(Document.get(), "keypress", this, false); + addEventListener(canvas, "keydown", this, false); + addEventListener(canvas, "keyup", this, false); + addEventListener(canvas, "keypress", this, false); + addEventListener(canvas, "touchstart", this, true); + addEventListener(canvas, "touchmove", this, true); + addEventListener(canvas, "touchcancel", this, true); + addEventListener(canvas, "touchend", this, true); - } + } - private int getButton(int button) { - if (button == NativeEvent.BUTTON_LEFT) - return Buttons.LEFT; - if (button == NativeEvent.BUTTON_RIGHT) - return Buttons.RIGHT; - if (button == NativeEvent.BUTTON_MIDDLE) - return Buttons.MIDDLE; - return Buttons.LEFT; - } + private int getButton(int button) { + if (button == NativeEvent.BUTTON_LEFT) + return Buttons.LEFT; + if (button == NativeEvent.BUTTON_RIGHT) + return Buttons.RIGHT; + if (button == NativeEvent.BUTTON_MIDDLE) + return Buttons.MIDDLE; + return Buttons.LEFT; + } - private void handleEvent(NativeEvent e) { - if (e.getType().equals("mousedown")) { - if (!e.getEventTarget().equals(canvas) || touched[0]) { - float mouseX = (int) getRelativeX(e, canvas); - float mouseY = (int) getRelativeY(e, canvas); - if (mouseX < 0 || mouseX > Gdx.graphics.getWidth() || mouseY < 0 - || mouseY > Gdx.graphics.getHeight()) { - hasFocus = false; - } - return; - } - hasFocus = true; - this.justTouched = true; - this.touched[0] = true; - this.pressedButtons.add(getButton(e.getButton())); - this.deltaX[0] = 0; - this.deltaY[0] = 0; - if (isCursorCatched()) { - this.touchX[0] += getMovementXJSNI(e); - this.touchY[0] += getMovementYJSNI(e); - } else { - this.touchX[0] = (int) getRelativeX(e, canvas); - this.touchY[0] = (int) getRelativeY(e, canvas); - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - if (processor != null) - processor.touchDown(touchX[0], touchY[0], 0, getButton(e.getButton())); - } + private void handleEvent(NativeEvent e) { + if (e.getType().equals("mousedown")) { + if (!e.getEventTarget().equals(canvas) || touched[0]) { + float mouseX = (int) getRelativeX(e, canvas); + float mouseY = (int) getRelativeY(e, canvas); + if (mouseX < 0 || mouseX > Gdx.graphics.getWidth() || mouseY < 0 + || mouseY > Gdx.graphics.getHeight()) { + hasFocus = false; + } + return; + } + hasFocus = true; + this.justTouched = true; + this.touched[0] = true; + this.pressedButtons.add(getButton(e.getButton())); + this.deltaX[0] = 0; + this.deltaY[0] = 0; + if (isCursorCatched()) { + this.touchX[0] += getMovementXJSNI(e); + this.touchY[0] += getMovementYJSNI(e); + } else { + this.touchX[0] = (int) getRelativeX(e, canvas); + this.touchY[0] = (int) getRelativeY(e, canvas); + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + if (processor != null) + processor.touchDown(touchX[0], touchY[0], 0, getButton(e.getButton())); + } - if (e.getType().equals("mousemove")) { - if (isCursorCatched()) { - this.deltaX[0] = (int) getMovementXJSNI(e); - this.deltaY[0] = (int) getMovementYJSNI(e); - this.touchX[0] += getMovementXJSNI(e); - this.touchY[0] += getMovementYJSNI(e); - } else { - this.deltaX[0] = (int) getRelativeX(e, canvas) - touchX[0]; - this.deltaY[0] = (int) getRelativeY(e, canvas) - touchY[0]; - this.touchX[0] = (int) getRelativeX(e, canvas); - this.touchY[0] = (int) getRelativeY(e, canvas); - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - if (processor != null) { - if (touched[0]) - processor.touchDragged(touchX[0], touchY[0], 0); - else - processor.mouseMoved(touchX[0], touchY[0]); - } - } + if (e.getType().equals("mousemove")) { + if (isCursorCatched()) { + this.deltaX[0] = (int) getMovementXJSNI(e); + this.deltaY[0] = (int) getMovementYJSNI(e); + this.touchX[0] += getMovementXJSNI(e); + this.touchY[0] += getMovementYJSNI(e); + } else { + this.deltaX[0] = (int) getRelativeX(e, canvas) - touchX[0]; + this.deltaY[0] = (int) getRelativeY(e, canvas) - touchY[0]; + this.touchX[0] = (int) getRelativeX(e, canvas); + this.touchY[0] = (int) getRelativeY(e, canvas); + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + if (processor != null) { + if (touched[0]) + processor.touchDragged(touchX[0], touchY[0], 0); + else + processor.mouseMoved(touchX[0], touchY[0]); + } + } - if (e.getType().equals("mouseup")) { - if (!touched[0]) - return; - this.pressedButtons.remove(getButton(e.getButton())); - this.touched[0] = pressedButtons.size() > 0; - if (isCursorCatched()) { - this.deltaX[0] = (int) getMovementXJSNI(e); - this.deltaY[0] = (int) getMovementYJSNI(e); - this.touchX[0] += getMovementXJSNI(e); - this.touchY[0] += getMovementYJSNI(e); - } else { - this.deltaX[0] = (int) getRelativeX(e, canvas) - touchX[0]; - this.deltaY[0] = (int) getRelativeY(e, canvas) - touchY[0]; - this.touchX[0] = (int) getRelativeX(e, canvas); - this.touchY[0] = (int) getRelativeY(e, canvas); - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - this.touched[0] = false; - if (processor != null) - processor.touchUp(touchX[0], touchY[0], 0, getButton(e.getButton())); - } - if (e.getType().equals(getMouseWheelEvent())) { - if (processor != null) { - processor.scrolled((int) getMouseWheelVelocity(e)); - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - e.preventDefault(); - } - if (e.getType().equals("keydown") && hasFocus) { - //System.out.println("keydown"); - int code = keyForCode(e.getKeyCode()); - if (code == 67) { - e.preventDefault(); - if (processor != null) { - processor.keyDown(code); - processor.keyTyped('\b'); - } - } else { - if (this.pressedKeys.add(code) && processor != null) { - processor.keyDown(code); - } - } - } + if (e.getType().equals("mouseup")) { + if (!touched[0]) + return; + this.pressedButtons.remove(getButton(e.getButton())); + this.touched[0] = pressedButtons.size() > 0; + if (isCursorCatched()) { + this.deltaX[0] = (int) getMovementXJSNI(e); + this.deltaY[0] = (int) getMovementYJSNI(e); + this.touchX[0] += getMovementXJSNI(e); + this.touchY[0] += getMovementYJSNI(e); + } else { + this.deltaX[0] = (int) getRelativeX(e, canvas) - touchX[0]; + this.deltaY[0] = (int) getRelativeY(e, canvas) - touchY[0]; + this.touchX[0] = (int) getRelativeX(e, canvas); + this.touchY[0] = (int) getRelativeY(e, canvas); + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + this.touched[0] = false; + if (processor != null) + processor.touchUp(touchX[0], touchY[0], 0, getButton(e.getButton())); + } + if (e.getType().equals(getMouseWheelEvent())) { + if (processor != null) { + processor.scrolled((int) getMouseWheelVelocity(e)); + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + e.preventDefault(); + } + if (e.getType().equals("keydown") && hasFocus) { + //System.out.println("keydown"); + int code = keyForCode(e.getKeyCode()); + if (code == 67) { + e.preventDefault(); + if (processor != null) { + processor.keyDown(code); + processor.keyTyped('\b'); + } + } else { + if (this.pressedKeys.add(code) && processor != null) { + processor.keyDown(code); + } + } + } - if (e.getType().equals("keypress") && hasFocus) { - //System.out.println("keypress"); - char c = (char) e.getCharCode(); - if (processor != null) - processor.keyTyped(c); - } + if (e.getType().equals("keypress") && hasFocus) { + //System.out.println("keypress"); + char c = (char) e.getCharCode(); + if (processor != null) + processor.keyTyped(c); + } - if (e.getType().equals("keyup") && hasFocus) { - //System.out.println("keyup"); - int code = keyForCode(e.getKeyCode()); - this.pressedKeys.remove(code); - if (processor != null) { - processor.keyUp(code); - } - } + if (e.getType().equals("keyup") && hasFocus) { + //System.out.println("keyup"); + int code = keyForCode(e.getKeyCode()); + this.pressedKeys.remove(code); + if (processor != null) { + processor.keyUp(code); + } + } - if (e.getType().equals("touchstart")) { - this.justTouched = true; - JsArray touches = e.getChangedTouches(); - for (int i = 0, j = touches.length(); i < j; i++) { - Touch touch = touches.get(i); - int touchId = touch.getIdentifier(); - touched[touchId] = true; - touchX[touchId] = touch.getRelativeX(canvas); - touchY[touchId] = touch.getRelativeY(canvas); - deltaX[touchId] = 0; - deltaY[touchId] = 0; - if (processor != null) { - processor.touchDown(touchX[touchId], touchY[touchId], touchId, Buttons.LEFT); - } - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - e.preventDefault(); - } - if (e.getType().equals("touchmove")) { - JsArray touches = e.getChangedTouches(); - for (int i = 0, j = touches.length(); i < j; i++) { - Touch touch = touches.get(i); - int touchId = touch.getIdentifier(); - deltaX[touchId] = touch.getRelativeX(canvas) - touchX[touchId]; - deltaY[touchId] = touch.getRelativeY(canvas) - touchY[touchId]; - touchX[touchId] = touch.getRelativeX(canvas); - touchY[touchId] = touch.getRelativeY(canvas); - if (processor != null) { - processor.touchDragged(touchX[touchId], touchY[touchId], touchId); - } - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - e.preventDefault(); - } - if (e.getType().equals("touchcancel")) { - JsArray touches = e.getChangedTouches(); - for (int i = 0, j = touches.length(); i < j; i++) { - Touch touch = touches.get(i); - int touchId = touch.getIdentifier(); - touched[touchId] = false; - deltaX[touchId] = touch.getRelativeX(canvas) - touchX[touchId]; - deltaY[touchId] = touch.getRelativeY(canvas) - touchY[touchId]; - touchX[touchId] = touch.getRelativeX(canvas); - touchY[touchId] = touch.getRelativeY(canvas); - if (processor != null) { - processor.touchUp(touchX[touchId], touchY[touchId], touchId, Buttons.LEFT); - } - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - e.preventDefault(); - } - if (e.getType().equals("touchend")) { - JsArray touches = e.getChangedTouches(); - for (int i = 0, j = touches.length(); i < j; i++) { - Touch touch = touches.get(i); - int touchId = touch.getIdentifier(); - touched[touchId] = false; - deltaX[touchId] = touch.getRelativeX(canvas) - touchX[touchId]; - deltaY[touchId] = touch.getRelativeY(canvas) - touchY[touchId]; - touchX[touchId] = touch.getRelativeX(canvas); - touchY[touchId] = touch.getRelativeY(canvas); - if (processor != null) { - processor.touchUp(touchX[touchId], touchY[touchId], touchId, Buttons.LEFT); - } - } - this.currentEventTimeStamp = TimeUtils.nanoTime(); - e.preventDefault(); - } - // if(hasFocus) e.preventDefault(); - } + if (e.getType().equals("touchstart")) { + this.justTouched = true; + JsArray touches = e.getChangedTouches(); + for (int i = 0, j = touches.length(); i < j; i++) { + Touch touch = touches.get(i); + int touchId = touch.getIdentifier(); + touched[touchId] = true; + touchX[touchId] = touch.getRelativeX(canvas); + touchY[touchId] = touch.getRelativeY(canvas); + deltaX[touchId] = 0; + deltaY[touchId] = 0; + if (processor != null) { + processor.touchDown(touchX[touchId], touchY[touchId], touchId, Buttons.LEFT); + } + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + e.preventDefault(); + } + if (e.getType().equals("touchmove")) { + JsArray touches = e.getChangedTouches(); + for (int i = 0, j = touches.length(); i < j; i++) { + Touch touch = touches.get(i); + int touchId = touch.getIdentifier(); + deltaX[touchId] = touch.getRelativeX(canvas) - touchX[touchId]; + deltaY[touchId] = touch.getRelativeY(canvas) - touchY[touchId]; + touchX[touchId] = touch.getRelativeX(canvas); + touchY[touchId] = touch.getRelativeY(canvas); + if (processor != null) { + processor.touchDragged(touchX[touchId], touchY[touchId], touchId); + } + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + e.preventDefault(); + } + if (e.getType().equals("touchcancel")) { + JsArray touches = e.getChangedTouches(); + for (int i = 0, j = touches.length(); i < j; i++) { + Touch touch = touches.get(i); + int touchId = touch.getIdentifier(); + touched[touchId] = false; + deltaX[touchId] = touch.getRelativeX(canvas) - touchX[touchId]; + deltaY[touchId] = touch.getRelativeY(canvas) - touchY[touchId]; + touchX[touchId] = touch.getRelativeX(canvas); + touchY[touchId] = touch.getRelativeY(canvas); + if (processor != null) { + processor.touchUp(touchX[touchId], touchY[touchId], touchId, Buttons.LEFT); + } + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + e.preventDefault(); + } + if (e.getType().equals("touchend")) { + JsArray touches = e.getChangedTouches(); + for (int i = 0, j = touches.length(); i < j; i++) { + Touch touch = touches.get(i); + int touchId = touch.getIdentifier(); + touched[touchId] = false; + deltaX[touchId] = touch.getRelativeX(canvas) - touchX[touchId]; + deltaY[touchId] = touch.getRelativeY(canvas) - touchY[touchId]; + touchX[touchId] = touch.getRelativeX(canvas); + touchY[touchId] = touch.getRelativeY(canvas); + if (processor != null) { + processor.touchUp(touchX[touchId], touchY[touchId], touchId, Buttons.LEFT); + } + } + this.currentEventTimeStamp = TimeUtils.nanoTime(); + e.preventDefault(); + } + // if(hasFocus) e.preventDefault(); + } - /** borrowed from PlayN, thanks guys **/ - private static int keyForCode(int keyCode) { - switch (keyCode) { - case KeyCodes.KEY_ALT: - return Keys.ALT_LEFT; - case KeyCodes.KEY_BACKSPACE: - return Keys.BACKSPACE; - case KeyCodes.KEY_CTRL: - return Keys.CONTROL_LEFT; - case KeyCodes.KEY_DELETE: - return Keys.DEL; - case KeyCodes.KEY_DOWN: - return Keys.DOWN; - case KeyCodes.KEY_END: - return Keys.END; - case KeyCodes.KEY_ENTER: - return Keys.ENTER; - case KeyCodes.KEY_ESCAPE: - return Keys.ESCAPE; - case KeyCodes.KEY_HOME: - return Keys.HOME; - case KeyCodes.KEY_LEFT: - return Keys.LEFT; - case KeyCodes.KEY_PAGEDOWN: - return Keys.PAGE_DOWN; - case KeyCodes.KEY_PAGEUP: - return Keys.PAGE_UP; - case KeyCodes.KEY_RIGHT: - return Keys.RIGHT; - case KeyCodes.KEY_SHIFT: - return Keys.SHIFT_LEFT; - case KeyCodes.KEY_TAB: - return Keys.TAB; - case KeyCodes.KEY_UP: - return Keys.UP; + /** + * borrowed from PlayN, thanks guys + **/ + private static int keyForCode(int keyCode) { + switch (keyCode) { + case KeyCodes.KEY_ALT: + return Keys.ALT_LEFT; + case KeyCodes.KEY_BACKSPACE: + return Keys.BACKSPACE; + case KeyCodes.KEY_CTRL: + return Keys.CONTROL_LEFT; + case KeyCodes.KEY_DELETE: + return Keys.DEL; + case KeyCodes.KEY_DOWN: + return Keys.DOWN; + case KeyCodes.KEY_END: + return Keys.END; + case KeyCodes.KEY_ENTER: + return Keys.ENTER; + case KeyCodes.KEY_ESCAPE: + return Keys.ESCAPE; + case KeyCodes.KEY_HOME: + return Keys.HOME; + case KeyCodes.KEY_LEFT: + return Keys.LEFT; + case KeyCodes.KEY_PAGEDOWN: + return Keys.PAGE_DOWN; + case KeyCodes.KEY_PAGEUP: + return Keys.PAGE_UP; + case KeyCodes.KEY_RIGHT: + return Keys.RIGHT; + case KeyCodes.KEY_SHIFT: + return Keys.SHIFT_LEFT; + case KeyCodes.KEY_TAB: + return Keys.TAB; + case KeyCodes.KEY_UP: + return Keys.UP; - case KEY_PAUSE: - return Keys.UNKNOWN; // FIXME - case KEY_CAPS_LOCK: - return Keys.UNKNOWN; // FIXME - case KEY_SPACE: - return Keys.SPACE; - case KEY_INSERT: - return Keys.INSERT; - case KEY_0: - return Keys.NUM_0; - case KEY_1: - return Keys.NUM_1; - case KEY_2: - return Keys.NUM_2; - case KEY_3: - return Keys.NUM_3; - case KEY_4: - return Keys.NUM_4; - case KEY_5: - return Keys.NUM_5; - case KEY_6: - return Keys.NUM_6; - case KEY_7: - return Keys.NUM_7; - case KEY_8: - return Keys.NUM_8; - case KEY_9: - return Keys.NUM_9; - case KEY_A: - return Keys.A; - case KEY_B: - return Keys.B; - case KEY_C: - return Keys.C; - case KEY_D: - return Keys.D; - case KEY_E: - return Keys.E; - case KEY_F: - return Keys.F; - case KEY_G: - return Keys.G; - case KEY_H: - return Keys.H; - case KEY_I: - return Keys.I; - case KEY_J: - return Keys.J; - case KEY_K: - return Keys.K; - case KEY_L: - return Keys.L; - case KEY_M: - return Keys.M; - case KEY_N: - return Keys.N; - case KEY_O: - return Keys.O; - case KEY_P: - return Keys.P; - case KEY_Q: - return Keys.Q; - case KEY_R: - return Keys.R; - case KEY_S: - return Keys.S; - case KEY_T: - return Keys.T; - case KEY_U: - return Keys.U; - case KEY_V: - return Keys.V; - case KEY_W: - return Keys.W; - case KEY_X: - return Keys.X; - case KEY_Y: - return Keys.Y; - case KEY_Z: - return Keys.Z; - case KEY_LEFT_WINDOW_KEY: - return Keys.UNKNOWN; // FIXME - case KEY_RIGHT_WINDOW_KEY: - return Keys.UNKNOWN; // FIXME - // case KEY_SELECT_KEY: return Keys.SELECT_KEY; - case KEY_NUMPAD0: - return Keys.NUMPAD_0; - case KEY_NUMPAD1: - return Keys.NUMPAD_1; - case KEY_NUMPAD2: - return Keys.NUMPAD_2; - case KEY_NUMPAD3: - return Keys.NUMPAD_3; - case KEY_NUMPAD4: - return Keys.NUMPAD_4; - case KEY_NUMPAD5: - return Keys.NUMPAD_5; - case KEY_NUMPAD6: - return Keys.NUMPAD_6; - case KEY_NUMPAD7: - return Keys.NUMPAD_7; - case KEY_NUMPAD8: - return Keys.NUMPAD_8; - case KEY_NUMPAD9: - return Keys.NUMPAD_9; - case KEY_MULTIPLY: - return Keys.UNKNOWN; // FIXME - case KEY_ADD: - return Keys.PLUS; - case KEY_SUBTRACT: - return Keys.MINUS; - case KEY_DECIMAL_POINT_KEY: - return Keys.PERIOD; - case KEY_DIVIDE: - return Keys.UNKNOWN; // FIXME - case KEY_F1: - return Keys.F1; - case KEY_F2: - return Keys.F2; - case KEY_F3: - return Keys.F3; - case KEY_F4: - return Keys.F4; - case KEY_F5: - return Keys.F5; - case KEY_F6: - return Keys.F6; - case KEY_F7: - return Keys.F7; - case KEY_F8: - return Keys.F8; - case KEY_F9: - return Keys.F9; - case KEY_F10: - return Keys.F10; - case KEY_F11: - return Keys.F11; - case KEY_F12: - return Keys.F12; - case KEY_NUM_LOCK: - return Keys.NUM; - case KEY_SCROLL_LOCK: - return Keys.UNKNOWN; // FIXME - case KEY_SEMICOLON: - return Keys.SEMICOLON; - case KEY_EQUALS: - return Keys.EQUALS; - case KEY_COMMA: - return Keys.COMMA; - case KEY_DASH: - return Keys.MINUS; - case KEY_PERIOD: - return Keys.PERIOD; - case KEY_FORWARD_SLASH: - return Keys.SLASH; - case KEY_GRAVE_ACCENT: - return Keys.UNKNOWN; // FIXME - case KEY_OPEN_BRACKET: - return Keys.LEFT_BRACKET; - case KEY_BACKSLASH: - return Keys.BACKSLASH; - case KEY_CLOSE_BRACKET: - return Keys.RIGHT_BRACKET; - case KEY_SINGLE_QUOTE: - return Keys.APOSTROPHE; - default: - return Keys.UNKNOWN; - } - } + case KEY_PAUSE: + return Keys.UNKNOWN; // FIXME + case KEY_CAPS_LOCK: + return Keys.UNKNOWN; // FIXME + case KEY_SPACE: + return Keys.SPACE; + case KEY_INSERT: + return Keys.INSERT; + case KEY_0: + return Keys.NUM_0; + case KEY_1: + return Keys.NUM_1; + case KEY_2: + return Keys.NUM_2; + case KEY_3: + return Keys.NUM_3; + case KEY_4: + return Keys.NUM_4; + case KEY_5: + return Keys.NUM_5; + case KEY_6: + return Keys.NUM_6; + case KEY_7: + return Keys.NUM_7; + case KEY_8: + return Keys.NUM_8; + case KEY_9: + return Keys.NUM_9; + case KEY_A: + return Keys.A; + case KEY_B: + return Keys.B; + case KEY_C: + return Keys.C; + case KEY_D: + return Keys.D; + case KEY_E: + return Keys.E; + case KEY_F: + return Keys.F; + case KEY_G: + return Keys.G; + case KEY_H: + return Keys.H; + case KEY_I: + return Keys.I; + case KEY_J: + return Keys.J; + case KEY_K: + return Keys.K; + case KEY_L: + return Keys.L; + case KEY_M: + return Keys.M; + case KEY_N: + return Keys.N; + case KEY_O: + return Keys.O; + case KEY_P: + return Keys.P; + case KEY_Q: + return Keys.Q; + case KEY_R: + return Keys.R; + case KEY_S: + return Keys.S; + case KEY_T: + return Keys.T; + case KEY_U: + return Keys.U; + case KEY_V: + return Keys.V; + case KEY_W: + return Keys.W; + case KEY_X: + return Keys.X; + case KEY_Y: + return Keys.Y; + case KEY_Z: + return Keys.Z; + case KEY_LEFT_WINDOW_KEY: + return Keys.UNKNOWN; // FIXME + case KEY_RIGHT_WINDOW_KEY: + return Keys.UNKNOWN; // FIXME + // case KEY_SELECT_KEY: return Keys.SELECT_KEY; + case KEY_NUMPAD0: + return Keys.NUMPAD_0; + case KEY_NUMPAD1: + return Keys.NUMPAD_1; + case KEY_NUMPAD2: + return Keys.NUMPAD_2; + case KEY_NUMPAD3: + return Keys.NUMPAD_3; + case KEY_NUMPAD4: + return Keys.NUMPAD_4; + case KEY_NUMPAD5: + return Keys.NUMPAD_5; + case KEY_NUMPAD6: + return Keys.NUMPAD_6; + case KEY_NUMPAD7: + return Keys.NUMPAD_7; + case KEY_NUMPAD8: + return Keys.NUMPAD_8; + case KEY_NUMPAD9: + return Keys.NUMPAD_9; + case KEY_MULTIPLY: + return Keys.UNKNOWN; // FIXME + case KEY_ADD: + return Keys.PLUS; + case KEY_SUBTRACT: + return Keys.MINUS; + case KEY_DECIMAL_POINT_KEY: + return Keys.PERIOD; + case KEY_DIVIDE: + return Keys.UNKNOWN; // FIXME + case KEY_F1: + return Keys.F1; + case KEY_F2: + return Keys.F2; + case KEY_F3: + return Keys.F3; + case KEY_F4: + return Keys.F4; + case KEY_F5: + return Keys.F5; + case KEY_F6: + return Keys.F6; + case KEY_F7: + return Keys.F7; + case KEY_F8: + return Keys.F8; + case KEY_F9: + return Keys.F9; + case KEY_F10: + return Keys.F10; + case KEY_F11: + return Keys.F11; + case KEY_F12: + return Keys.F12; + case KEY_NUM_LOCK: + return Keys.NUM; + case KEY_SCROLL_LOCK: + return Keys.UNKNOWN; // FIXME + case KEY_SEMICOLON: + return Keys.SEMICOLON; + case KEY_EQUALS: + return Keys.EQUALS; + case KEY_COMMA: + return Keys.COMMA; + case KEY_DASH: + return Keys.MINUS; + case KEY_PERIOD: + return Keys.PERIOD; + case KEY_FORWARD_SLASH: + return Keys.SLASH; + case KEY_GRAVE_ACCENT: + return Keys.UNKNOWN; // FIXME + case KEY_OPEN_BRACKET: + return Keys.LEFT_BRACKET; + case KEY_BACKSLASH: + return Keys.BACKSLASH; + case KEY_CLOSE_BRACKET: + return Keys.RIGHT_BRACKET; + case KEY_SINGLE_QUOTE: + return Keys.APOSTROPHE; + default: + return Keys.UNKNOWN; + } + } - // these are absent from KeyCodes; we know not why... - private static final int KEY_PAUSE = 19; - private static final int KEY_CAPS_LOCK = 20; - private static final int KEY_SPACE = 32; - private static final int KEY_INSERT = 45; - private static final int KEY_0 = 48; - private static final int KEY_1 = 49; - private static final int KEY_2 = 50; - private static final int KEY_3 = 51; - private static final int KEY_4 = 52; - private static final int KEY_5 = 53; - private static final int KEY_6 = 54; - private static final int KEY_7 = 55; - private static final int KEY_8 = 56; - private static final int KEY_9 = 57; - private static final int KEY_A = 65; - private static final int KEY_B = 66; - private static final int KEY_C = 67; - private static final int KEY_D = 68; - private static final int KEY_E = 69; - private static final int KEY_F = 70; - private static final int KEY_G = 71; - private static final int KEY_H = 72; - private static final int KEY_I = 73; - private static final int KEY_J = 74; - private static final int KEY_K = 75; - private static final int KEY_L = 76; - private static final int KEY_M = 77; - private static final int KEY_N = 78; - private static final int KEY_O = 79; - private static final int KEY_P = 80; - private static final int KEY_Q = 81; - private static final int KEY_R = 82; - private static final int KEY_S = 83; - private static final int KEY_T = 84; - private static final int KEY_U = 85; - private static final int KEY_V = 86; - private static final int KEY_W = 87; - private static final int KEY_X = 88; - private static final int KEY_Y = 89; - private static final int KEY_Z = 90; - private static final int KEY_LEFT_WINDOW_KEY = 91; - private static final int KEY_RIGHT_WINDOW_KEY = 92; - private static final int KEY_SELECT_KEY = 93; - private static final int KEY_NUMPAD0 = 96; - private static final int KEY_NUMPAD1 = 97; - private static final int KEY_NUMPAD2 = 98; - private static final int KEY_NUMPAD3 = 99; - private static final int KEY_NUMPAD4 = 100; - private static final int KEY_NUMPAD5 = 101; - private static final int KEY_NUMPAD6 = 102; - private static final int KEY_NUMPAD7 = 103; - private static final int KEY_NUMPAD8 = 104; - private static final int KEY_NUMPAD9 = 105; - private static final int KEY_MULTIPLY = 106; - private static final int KEY_ADD = 107; - private static final int KEY_SUBTRACT = 109; - private static final int KEY_DECIMAL_POINT_KEY = 110; - private static final int KEY_DIVIDE = 111; - private static final int KEY_F1 = 112; - private static final int KEY_F2 = 113; - private static final int KEY_F3 = 114; - private static final int KEY_F4 = 115; - private static final int KEY_F5 = 116; - private static final int KEY_F6 = 117; - private static final int KEY_F7 = 118; - private static final int KEY_F8 = 119; - private static final int KEY_F9 = 120; - private static final int KEY_F10 = 121; - private static final int KEY_F11 = 122; - private static final int KEY_F12 = 123; - private static final int KEY_NUM_LOCK = 144; - private static final int KEY_SCROLL_LOCK = 145; - private static final int KEY_SEMICOLON = 186; - private static final int KEY_EQUALS = 187; - private static final int KEY_COMMA = 188; - private static final int KEY_DASH = 189; - private static final int KEY_PERIOD = 190; - private static final int KEY_FORWARD_SLASH = 191; - private static final int KEY_GRAVE_ACCENT = 192; - private static final int KEY_OPEN_BRACKET = 219; - private static final int KEY_BACKSLASH = 220; - private static final int KEY_CLOSE_BRACKET = 221; - private static final int KEY_SINGLE_QUOTE = 222; + // these are absent from KeyCodes; we know not why... + private static final int KEY_PAUSE = 19; + private static final int KEY_CAPS_LOCK = 20; + private static final int KEY_SPACE = 32; + private static final int KEY_INSERT = 45; + private static final int KEY_0 = 48; + private static final int KEY_1 = 49; + private static final int KEY_2 = 50; + private static final int KEY_3 = 51; + private static final int KEY_4 = 52; + private static final int KEY_5 = 53; + private static final int KEY_6 = 54; + private static final int KEY_7 = 55; + private static final int KEY_8 = 56; + private static final int KEY_9 = 57; + private static final int KEY_A = 65; + private static final int KEY_B = 66; + private static final int KEY_C = 67; + private static final int KEY_D = 68; + private static final int KEY_E = 69; + private static final int KEY_F = 70; + private static final int KEY_G = 71; + private static final int KEY_H = 72; + private static final int KEY_I = 73; + private static final int KEY_J = 74; + private static final int KEY_K = 75; + private static final int KEY_L = 76; + private static final int KEY_M = 77; + private static final int KEY_N = 78; + private static final int KEY_O = 79; + private static final int KEY_P = 80; + private static final int KEY_Q = 81; + private static final int KEY_R = 82; + private static final int KEY_S = 83; + private static final int KEY_T = 84; + private static final int KEY_U = 85; + private static final int KEY_V = 86; + private static final int KEY_W = 87; + private static final int KEY_X = 88; + private static final int KEY_Y = 89; + private static final int KEY_Z = 90; + private static final int KEY_LEFT_WINDOW_KEY = 91; + private static final int KEY_RIGHT_WINDOW_KEY = 92; + private static final int KEY_SELECT_KEY = 93; + private static final int KEY_NUMPAD0 = 96; + private static final int KEY_NUMPAD1 = 97; + private static final int KEY_NUMPAD2 = 98; + private static final int KEY_NUMPAD3 = 99; + private static final int KEY_NUMPAD4 = 100; + private static final int KEY_NUMPAD5 = 101; + private static final int KEY_NUMPAD6 = 102; + private static final int KEY_NUMPAD7 = 103; + private static final int KEY_NUMPAD8 = 104; + private static final int KEY_NUMPAD9 = 105; + private static final int KEY_MULTIPLY = 106; + private static final int KEY_ADD = 107; + private static final int KEY_SUBTRACT = 109; + private static final int KEY_DECIMAL_POINT_KEY = 110; + private static final int KEY_DIVIDE = 111; + private static final int KEY_F1 = 112; + private static final int KEY_F2 = 113; + private static final int KEY_F3 = 114; + private static final int KEY_F4 = 115; + private static final int KEY_F5 = 116; + private static final int KEY_F6 = 117; + private static final int KEY_F7 = 118; + private static final int KEY_F8 = 119; + private static final int KEY_F9 = 120; + private static final int KEY_F10 = 121; + private static final int KEY_F11 = 122; + private static final int KEY_F12 = 123; + private static final int KEY_NUM_LOCK = 144; + private static final int KEY_SCROLL_LOCK = 145; + private static final int KEY_SEMICOLON = 186; + private static final int KEY_EQUALS = 187; + private static final int KEY_COMMA = 188; + private static final int KEY_DASH = 189; + private static final int KEY_PERIOD = 190; + private static final int KEY_FORWARD_SLASH = 191; + private static final int KEY_GRAVE_ACCENT = 192; + private static final int KEY_OPEN_BRACKET = 219; + private static final int KEY_BACKSLASH = 220; + private static final int KEY_CLOSE_BRACKET = 221; + private static final int KEY_SINGLE_QUOTE = 222; - @Override - public boolean isKeyJustPressed(int key) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isKeyJustPressed(int key) { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean isCatchBackKey() { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isCatchBackKey() { + // TODO Auto-generated method stub + return false; + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/graphics/Pixmap.java b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/graphics/Pixmap.java index b594ae74..6a6040fd 100644 --- a/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/graphics/Pixmap.java +++ b/vtm-web/src/org/oscim/gdx/emu/com/badlogic/gdx/graphics/Pixmap.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2011 See libgdx AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,11 +16,6 @@ package com.badlogic.gdx.graphics; -import java.nio.Buffer; -import java.nio.IntBuffer; -import java.util.HashMap; -import java.util.Map; - import com.badlogic.gdx.backends.gwt.GwtFileHandle; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.BufferUtils; @@ -33,185 +28,216 @@ import com.google.gwt.canvas.dom.client.Context2d.Composite; import com.google.gwt.dom.client.CanvasElement; import com.google.gwt.dom.client.ImageElement; +import java.nio.Buffer; +import java.nio.IntBuffer; +import java.util.HashMap; +import java.util.Map; + public class Pixmap implements Disposable { - public static Map pixmaps = new HashMap(); - static int nextId = 0; + public static Map pixmaps = new HashMap(); + static int nextId = 0; - /** Different pixel formats. - * - * @author mzechner */ - public enum Format { - Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888; - } + /** + * Different pixel formats. + * + * @author mzechner + */ + public enum Format { + Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888; + } - /** Blending functions to be set with {@link Pixmap#setBlending}. - * @author mzechner */ - public enum Blending { - None, SourceOver - } + /** + * Blending functions to be set with {@link Pixmap#setBlending}. + * + * @author mzechner + */ + public enum Blending { + None, SourceOver + } - /** Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. - * - * @author mzechner */ - public enum Filter { - NearestNeighbour, BiLinear - } + /** + * Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. + * + * @author mzechner + */ + public enum Filter { + NearestNeighbour, BiLinear + } - int width; - int height; - Format format; - Canvas canvas; - Context2d context; - int id; - IntBuffer buffer; - int r = 255, g = 255, b = 255; - float a; - String color = make(r, g, b, a); - static Blending blending; - CanvasPixelArray pixels; + int width; + int height; + Format format; + Canvas canvas; + Context2d context; + int id; + IntBuffer buffer; + int r = 255, g = 255, b = 255; + float a; + String color = make(r, g, b, a); + static Blending blending; + CanvasPixelArray pixels; - public Context2d getContext(){ - return context; - } + public Context2d getContext() { + return context; + } - public Pixmap (FileHandle file) { - GwtFileHandle gwtFile = (GwtFileHandle)file; - ImageElement img = gwtFile.preloader.images.get(file.path()); - if (img == null) throw new GdxRuntimeException("Couldn't load image '" + file.path() + "', file does not exist"); - create(img.getWidth(), img.getHeight(), Format.RGBA8888); - context.setGlobalCompositeOperation(Composite.COPY); - context.drawImage(img, 0, 0); - context.setGlobalCompositeOperation(getComposite()); - } + public Pixmap(FileHandle file) { + GwtFileHandle gwtFile = (GwtFileHandle) file; + ImageElement img = gwtFile.preloader.images.get(file.path()); + if (img == null) + throw new GdxRuntimeException("Couldn't load image '" + file.path() + "', file does not exist"); + create(img.getWidth(), img.getHeight(), Format.RGBA8888); + context.setGlobalCompositeOperation(Composite.COPY); + context.drawImage(img, 0, 0); + context.setGlobalCompositeOperation(getComposite()); + } - private static Composite getComposite () { - return blending == Blending.None ? Composite.COPY : Composite.SOURCE_OVER; - } + private static Composite getComposite() { + return blending == Blending.None ? Composite.COPY : Composite.SOURCE_OVER; + } - public Pixmap (ImageElement img) { - create(img.getWidth(), img.getHeight(), Format.RGBA8888); - context.drawImage(img, 0, 0); - } + public Pixmap(ImageElement img) { + create(img.getWidth(), img.getHeight(), Format.RGBA8888); + context.drawImage(img, 0, 0); + } - public Pixmap (int width, int height, Format format) { - create(width, height, format); - } + public Pixmap(int width, int height, Format format) { + create(width, height, format); + } - private void create (int width, int height, Format format2) { - this.width = width; - this.height = height; - this.format = Format.RGBA8888; - canvas = Canvas.createIfSupported(); - canvas.getCanvasElement().setWidth(width); - canvas.getCanvasElement().setHeight(height); - context = canvas.getContext2d(); - context.setGlobalCompositeOperation(getComposite()); - buffer = BufferUtils.newIntBuffer(1); - id = nextId++; - buffer.put(0, id); - pixmaps.put(id, this); - } + private void create(int width, int height, Format format2) { + this.width = width; + this.height = height; + this.format = Format.RGBA8888; + canvas = Canvas.createIfSupported(); + canvas.getCanvasElement().setWidth(width); + canvas.getCanvasElement().setHeight(height); + context = canvas.getContext2d(); + context.setGlobalCompositeOperation(getComposite()); + buffer = BufferUtils.newIntBuffer(1); + id = nextId++; + buffer.put(0, id); + pixmaps.put(id, this); + } - public static String make (int r2, int g2, int b2, float a2) { - return "rgba(" + r2 + "," + g2 + "," + b2 + "," + a2 + ")"; - } + public static String make(int r2, int g2, int b2, float a2) { + return "rgba(" + r2 + "," + g2 + "," + b2 + "," + a2 + ")"; + } - /** Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}. - * @param blending the blending type */ - public static void setBlending (Blending blending) { - Pixmap.blending = blending; - Composite composite = getComposite(); - for (Pixmap pixmap : pixmaps.values()) { - pixmap.context.setGlobalCompositeOperation(composite); - } - } + /** + * Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}. + * + * @param blending the blending type + */ + public static void setBlending(Blending blending) { + Pixmap.blending = blending; + Composite composite = getComposite(); + for (Pixmap pixmap : pixmaps.values()) { + pixmap.context.setGlobalCompositeOperation(composite); + } + } - /** @return the currently set {@link Blending} */ - public static Blending getBlending () { - return blending; - } + /** + * @return the currently set {@link Blending} + */ + public static Blending getBlending() { + return blending; + } - /** Sets the type of interpolation {@link Filter} to be used in conjunction with - * {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. - * @param filter the filter. */ - public static void setFilter (Filter filter) { - } + /** + * Sets the type of interpolation {@link Filter} to be used in conjunction with + * {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. + * + * @param filter the filter. + */ + public static void setFilter(Filter filter) { + } - public Format getFormat () { - return format; - } + public Format getFormat() { + return format; + } - public int getGLInternalFormat () { - return GL20.GL_RGBA; - } + public int getGLInternalFormat() { + return GL20.GL_RGBA; + } - public int getGLFormat () { - return GL20.GL_RGBA; - } + public int getGLFormat() { + return GL20.GL_RGBA; + } - public int getGLType () { - return GL20.GL_UNSIGNED_BYTE; - } + public int getGLType() { + return GL20.GL_UNSIGNED_BYTE; + } - public int getWidth () { - return width; - } + public int getWidth() { + return width; + } - public int getHeight () { - return height; - } + public int getHeight() { + return height; + } - public Buffer getPixels () { - return buffer; - } + public Buffer getPixels() { + return buffer; + } - @Override - public void dispose () { - pixmaps.remove(id); - } + @Override + public void dispose() { + pixmaps.remove(id); + } - public CanvasElement getCanvasElement () { - return canvas.getCanvasElement(); - } + public CanvasElement getCanvasElement() { + return canvas.getCanvasElement(); + } - /** Sets the color for the following drawing operations - * @param color the color, encoded as RGBA8888 */ - public void setColor (int color) { - r = (color >>> 24) & 0xff; - g = (color >>> 16) & 0xff; - b = (color >>> 8) & 0xff; - a = (color & 0xff) / 255f; - this.color = make(r, g, b, a); - context.setFillStyle(this.color); - context.setStrokeStyle(this.color); - } + /** + * Sets the color for the following drawing operations + * + * @param color the color, encoded as RGBA8888 + */ + public void setColor(int color) { + r = (color >>> 24) & 0xff; + g = (color >>> 16) & 0xff; + b = (color >>> 8) & 0xff; + a = (color & 0xff) / 255f; + this.color = make(r, g, b, a); + context.setFillStyle(this.color); + context.setStrokeStyle(this.color); + } - /** Sets the color for the following drawing operations. - * - * @param r The red component. - * @param g The green component. - * @param b The blue component. - * @param a The alpha component. */ - public void setColor (float r, float g, float b, float a) { - this.r = (int)(r * 255); - this.g = (int)(g * 255); - this.b = (int)(b * 255); - this.a = a; - color = make(this.r, this.g, this.b, this.a); - context.setFillStyle(color); - context.setStrokeStyle(this.color); - } + /** + * Sets the color for the following drawing operations. + * + * @param r The red component. + * @param g The green component. + * @param b The blue component. + * @param a The alpha component. + */ + public void setColor(float r, float g, float b, float a) { + this.r = (int) (r * 255); + this.g = (int) (g * 255); + this.b = (int) (b * 255); + this.a = a; + color = make(this.r, this.g, this.b, this.a); + context.setFillStyle(color); + context.setStrokeStyle(this.color); + } - /** Sets the color for the following drawing operations. - * @param color The color. */ - public void setColor (Color color) { - setColor(color.r, color.g, color.b, color.a); - } + /** + * Sets the color for the following drawing operations. + * + * @param color The color. + */ + public void setColor(Color color) { + setColor(color.r, color.g, color.b, color.a); + } - /** Fills the complete bitmap with the currently set color. */ - public void fill () { - context.fillRect(0, 0, getWidth(), getHeight()); - } + /** + * Fills the complete bitmap with the currently set color. + */ + public void fill() { + context.fillRect(0, 0, getWidth(), getHeight()); + } // /** // * Sets the width in pixels of strokes. @@ -220,158 +246,182 @@ public class Pixmap implements Disposable { // */ // public void setStrokeWidth (int width); - /** Draws a line between the given coordinates using the currently set color. - * - * @param x The x-coodinate of the first point - * @param y The y-coordinate of the first point - * @param x2 The x-coordinate of the first point - * @param y2 The y-coordinate of the first point */ - public void drawLine (int x, int y, int x2, int y2) { - context.beginPath(); - context.moveTo(x, y); - context.lineTo(x2, y2); - context.stroke(); - context.closePath(); - } + /** + * Draws a line between the given coordinates using the currently set color. + * + * @param x The x-coodinate of the first point + * @param y The y-coordinate of the first point + * @param x2 The x-coordinate of the first point + * @param y2 The y-coordinate of the first point + */ + public void drawLine(int x, int y, int x2, int y2) { + context.beginPath(); + context.moveTo(x, y); + context.lineTo(x2, y2); + context.stroke(); + context.closePath(); + } - /** Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards) - * using the current color. - * - * @param x The x coordinate - * @param y The y coordinate - * @param width The width in pixels - * @param height The height in pixels */ - public void drawRectangle (int x, int y, int width, int height) { - context.beginPath(); - context.rect(x, y, width, height); - context.stroke(); - context.closePath(); - } + /** + * Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards) + * using the current color. + * + * @param x The x coordinate + * @param y The y coordinate + * @param width The width in pixels + * @param height The height in pixels + */ + public void drawRectangle(int x, int y, int width, int height) { + context.beginPath(); + context.rect(x, y, width, height); + context.stroke(); + context.closePath(); + } - /** Draws an area form another Pixmap to this Pixmap. - * - * @param pixmap The other Pixmap - * @param x The target x-coordinate (top left corner) - * @param y The target y-coordinate (top left corner) */ - public void drawPixmap (Pixmap pixmap, int x, int y) { - context.drawImage(pixmap.getCanvasElement(), x, y); - } + /** + * Draws an area form another Pixmap to this Pixmap. + * + * @param pixmap The other Pixmap + * @param x The target x-coordinate (top left corner) + * @param y The target y-coordinate (top left corner) + */ + public void drawPixmap(Pixmap pixmap, int x, int y) { + context.drawImage(pixmap.getCanvasElement(), x, y); + } - /** Draws an area form another Pixmap to this Pixmap. - * - * @param pixmap The other Pixmap - * @param x The target x-coordinate (top left corner) - * @param y The target y-coordinate (top left corner) - * @param srcx The source x-coordinate (top left corner) - * @param srcy The source y-coordinate (top left corner); - * @param srcWidth The width of the area form the other Pixmap in pixels - * @param srcHeight The height of the area form the other Pixmap in pixles */ - public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) { - context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, x, y, srcWidth, srcHeight); - } + /** + * Draws an area form another Pixmap to this Pixmap. + * + * @param pixmap The other Pixmap + * @param x The target x-coordinate (top left corner) + * @param y The target y-coordinate (top left corner) + * @param srcx The source x-coordinate (top left corner) + * @param srcy The source y-coordinate (top left corner); + * @param srcWidth The width of the area form the other Pixmap in pixels + * @param srcHeight The height of the area form the other Pixmap in pixles + */ + public void drawPixmap(Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) { + context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, x, y, srcWidth, srcHeight); + } - /** Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the - * specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest - * neighbour or bilinear). - * - * @param pixmap The other Pixmap - * @param srcx The source x-coordinate (top left corner) - * @param srcy The source y-coordinate (top left corner); - * @param srcWidth The width of the area form the other Pixmap in pixels - * @param srcHeight The height of the area form the other Pixmap in pixles - * @param dstx The target x-coordinate (top left corner) - * @param dsty The target y-coordinate (top left corner) - * @param dstWidth The target width - * @param dstHeight the target height */ - public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth, - int dstHeight) { - context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight); - } + /** + * Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the + * specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest + * neighbour or bilinear). + * + * @param pixmap The other Pixmap + * @param srcx The source x-coordinate (top left corner) + * @param srcy The source y-coordinate (top left corner); + * @param srcWidth The width of the area form the other Pixmap in pixels + * @param srcHeight The height of the area form the other Pixmap in pixles + * @param dstx The target x-coordinate (top left corner) + * @param dsty The target y-coordinate (top left corner) + * @param dstWidth The target width + * @param dstHeight the target height + */ + public void drawPixmap(Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth, + int dstHeight) { + context.drawImage(pixmap.getCanvasElement(), srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight); + } - /** Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using - * the current color. - * - * @param x The x coordinate - * @param y The y coordinate - * @param width The width in pixels - * @param height The height in pixels */ - public void fillRectangle (int x, int y, int width, int height) { - context.fillRect(x, y, width, height); - } + /** + * Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using + * the current color. + * + * @param x The x coordinate + * @param y The y coordinate + * @param width The width in pixels + * @param height The height in pixels + */ + public void fillRectangle(int x, int y, int width, int height) { + context.fillRect(x, y, width, height); + } - /** Draws a circle outline with the center at x,y and a radius using the current color and stroke width. - * - * @param x The x-coordinate of the center - * @param y The y-coordinate of the center - * @param radius The radius in pixels */ - public void drawCircle (int x, int y, int radius) { - context.beginPath(); - context.arc(x, y, radius, 0, 2 * Math.PI, false); - context.stroke(); - context.closePath(); - } + /** + * Draws a circle outline with the center at x,y and a radius using the current color and stroke width. + * + * @param x The x-coordinate of the center + * @param y The y-coordinate of the center + * @param radius The radius in pixels + */ + public void drawCircle(int x, int y, int radius) { + context.beginPath(); + context.arc(x, y, radius, 0, 2 * Math.PI, false); + context.stroke(); + context.closePath(); + } - /** Fills a circle with the center at x,y and a radius using the current color. - * - * @param x The x-coordinate of the center - * @param y The y-coordinate of the center - * @param radius The radius in pixels */ - public void fillCircle (int x, int y, int radius) { - context.beginPath(); - context.arc(x, y, radius, 0, 2 * Math.PI, false); - context.fill(); - context.closePath(); - } + /** + * Fills a circle with the center at x,y and a radius using the current color. + * + * @param x The x-coordinate of the center + * @param y The y-coordinate of the center + * @param radius The radius in pixels + */ + public void fillCircle(int x, int y, int radius) { + context.beginPath(); + context.arc(x, y, radius, 0, 2 * Math.PI, false); + context.fill(); + context.closePath(); + } - /** Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color. - * - * @param x1 The x-coordinate of vertex 1 - * @param y1 The y-coordinate of vertex 1 - * @param x2 The x-coordinate of vertex 2 - * @param y2 The y-coordinate of vertex 2 - * @param x3 The x-coordinate of vertex 3 - * @param y3 The y-coordinate of vertex 3 */ - public void fillTriangle (int x1, int y1, int x2, int y2, int x3, int y3) { - context.beginPath(); - context.moveTo(x1,y1); - context.lineTo(x2,y2); - context.lineTo(x3,y3); - context.lineTo(x1,y1); - context.fill(); - context.closePath(); - } + /** + * Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color. + * + * @param x1 The x-coordinate of vertex 1 + * @param y1 The y-coordinate of vertex 1 + * @param x2 The x-coordinate of vertex 2 + * @param y2 The y-coordinate of vertex 2 + * @param x3 The x-coordinate of vertex 3 + * @param y3 The y-coordinate of vertex 3 + */ + public void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) { + context.beginPath(); + context.moveTo(x1, y1); + context.lineTo(x2, y2); + context.lineTo(x3, y3); + context.lineTo(x1, y1); + context.fill(); + context.closePath(); + } - /** Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one. - * - * @param x The x-coordinate - * @param y The y-coordinate - * @return The pixel color in RGBA8888 format. */ - public int getPixel (int x, int y) { - if (pixels == null) pixels = context.getImageData(0, 0, width, height).getData(); - int i = x * 4 + y * width * 4; - int r = pixels.get(i + 0) & 0xff; - int g = pixels.get(i + 1) & 0xff; - int b = pixels.get(i + 2) & 0xff; - int a = pixels.get(i + 3) & 0xff; - return (r << 24) | (g << 16) | (b << 8) | (a); - } + /** + * Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one. + * + * @param x The x-coordinate + * @param y The y-coordinate + * @return The pixel color in RGBA8888 format. + */ + public int getPixel(int x, int y) { + if (pixels == null) pixels = context.getImageData(0, 0, width, height).getData(); + int i = x * 4 + y * width * 4; + int r = pixels.get(i + 0) & 0xff; + int g = pixels.get(i + 1) & 0xff; + int b = pixels.get(i + 2) & 0xff; + int a = pixels.get(i + 3) & 0xff; + return (r << 24) | (g << 16) | (b << 8) | (a); + } - /** Draws a pixel at the given location with the current color. - * - * @param x the x-coordinate - * @param y the y-coordinate */ - public void drawPixel (int x, int y) { - context.fillRect(x, y, 1, 1); - } + /** + * Draws a pixel at the given location with the current color. + * + * @param x the x-coordinate + * @param y the y-coordinate + */ + public void drawPixel(int x, int y) { + context.fillRect(x, y, 1, 1); + } - /** Draws a pixel at the given location with the given color. - * - * @param x the x-coordinate - * @param y the y-coordinate - * @param color the color in RGBA8888 format. */ - public void drawPixel (int x, int y, int color) { - setColor(color); - drawPixel(x, y); - } + /** + * Draws a pixel at the given location with the given color. + * + * @param x the x-coordinate + * @param y the y-coordinate + * @param color the color in RGBA8888 format. + */ + public void drawPixel(int x, int y, int color) { + setColor(color); + drawPixel(x, y); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/java/net/MalformedURLException.java b/vtm-web/src/org/oscim/gdx/emu/java/net/MalformedURLException.java index 839be0aa..e2e6c2c0 100644 --- a/vtm-web/src/org/oscim/gdx/emu/java/net/MalformedURLException.java +++ b/vtm-web/src/org/oscim/gdx/emu/java/net/MalformedURLException.java @@ -2,9 +2,9 @@ package java.net; public class MalformedURLException extends Exception { - /** + /** * */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/vtm-web/src/org/oscim/gdx/emu/java/net/URL.java b/vtm-web/src/org/oscim/gdx/emu/java/net/URL.java index 2309246d..b9156b1f 100644 --- a/vtm-web/src/org/oscim/gdx/emu/java/net/URL.java +++ b/vtm-web/src/org/oscim/gdx/emu/java/net/URL.java @@ -1,22 +1,22 @@ package java.net; public class URL { - @Override - public String toString() { - return mPath; - } + @Override + public String toString() { + return mPath; + } - String mProtocol; - String mHostname; - int mPort; - String mPath; + String mProtocol; + String mHostname; + int mPort; + String mPath; - public URL(String protocol, String hostName, int port, String path) { - //mPath = "http://" +hostName +"/" + path; - mPath = path; - } + public URL(String protocol, String hostName, int port, String path) { + //mPath = "http://" +hostName +"/" + path; + mPath = path; + } - public URL(String path) throws MalformedURLException { - mPath = path; - } + public URL(String path) throws MalformedURLException { + mPath = path; + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CancellationException.java b/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CancellationException.java index e4ea12ec..86959480 100644 --- a/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CancellationException.java +++ b/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CancellationException.java @@ -2,9 +2,9 @@ package java.util.concurrent; public class CancellationException extends IllegalStateException { - /** - * - */ + /** + * + */ private static final long serialVersionUID = 1L; } diff --git a/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CopyOnWriteArrayList.java b/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CopyOnWriteArrayList.java index a5cac2f6..3b0b0636 100644 --- a/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CopyOnWriteArrayList.java +++ b/vtm-web/src/org/oscim/gdx/emu/java/util/concurrent/CopyOnWriteArrayList.java @@ -4,9 +4,9 @@ import java.util.ArrayList; public class CopyOnWriteArrayList extends ArrayList { - /** + /** * */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyAttributes.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyAttributes.java index d738dc3b..fb81e771 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyAttributes.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyAttributes.java @@ -1,75 +1,75 @@ package org.oscim.backend; -import org.xml.sax.Attributes; - import com.google.gwt.xml.client.NamedNodeMap; import com.google.gwt.xml.client.Node; +import org.xml.sax.Attributes; + public class MyAttributes implements Attributes { - private NamedNodeMap map; + private NamedNodeMap map; - public MyAttributes(Node n) { - map = n.getAttributes(); - } + public MyAttributes(Node n) { + map = n.getAttributes(); + } - public String getValue(int i) { - return map.item(i).getNodeValue(); - } + public String getValue(int i) { + return map.item(i).getNodeValue(); + } - public int getLength() { - return map.getLength(); - } + public int getLength() { + return map.getLength(); + } - public String getLocalName(int i) { - return map.item(i).getNodeName(); - } + public String getLocalName(int i) { + return map.item(i).getNodeName(); + } - public String getValue(String string) { - Node n = map.getNamedItem(string); - if (n == null) - return null; + public String getValue(String string) { + Node n = map.getNamedItem(string); + if (n == null) + return null; - return n.getNodeValue(); - } + return n.getNodeValue(); + } - @Override - public String getURI(int paramInt) { - return null; - } + @Override + public String getURI(int paramInt) { + return null; + } - @Override - public String getQName(int paramInt) { - return null; - } + @Override + public String getQName(int paramInt) { + return null; + } - @Override - public String getType(int paramInt) { - return null; - } + @Override + public String getType(int paramInt) { + return null; + } - @Override - public int getIndex(String paramString1, String paramString2) { - return 0; - } + @Override + public int getIndex(String paramString1, String paramString2) { + return 0; + } - @Override - public int getIndex(String paramString) { - return 0; - } + @Override + public int getIndex(String paramString) { + return 0; + } - @Override - public String getType(String paramString1, String paramString2) { - return null; - } + @Override + public String getType(String paramString1, String paramString2) { + return null; + } - @Override - public String getType(String paramString) { - return null; - } + @Override + public String getType(String paramString) { + return null; + } - @Override - public String getValue(String paramString1, String paramString2) { - return null; - } + @Override + public String getValue(String paramString1, String paramString2) { + return null; + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyXMLReader.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyXMLReader.java index c8db3813..ead4f755 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyXMLReader.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/MyXMLReader.java @@ -1,61 +1,61 @@ package org.oscim.backend; -import java.io.IOException; -import java.io.InputStream; - -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - import com.google.gwt.xml.client.Document; import com.google.gwt.xml.client.Node; import com.google.gwt.xml.client.NodeList; import com.google.gwt.xml.client.XMLParser; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import java.io.IOException; +import java.io.InputStream; + public class MyXMLReader { - public void parse(InputStream is) throws SAXException { - StringBuilder sb = new StringBuilder(); - byte[] buf = new byte[8192]; - int read; - try { - while ((read = is.read(buf)) >= 0) { - if (read > 0) - sb.append(new String(buf, 0, read)); - } - } catch (IOException e) { - e.printStackTrace(); - } + public void parse(InputStream is) throws SAXException { + StringBuilder sb = new StringBuilder(); + byte[] buf = new byte[8192]; + int read; + try { + while ((read = is.read(buf)) >= 0) { + if (read > 0) + sb.append(new String(buf, 0, read)); + } + } catch (IOException e) { + e.printStackTrace(); + } - Document d = XMLParser.parse(sb.toString()); - handleElement(d.getFirstChild()); - mHandler.endDocument(); - } + Document d = XMLParser.parse(sb.toString()); + handleElement(d.getFirstChild()); + mHandler.endDocument(); + } - int level = 0; + int level = 0; - void handleElement(Node n) throws SAXException { - if (n == null) { - return; - } - if (n.getNodeType() == Node.ELEMENT_NODE) { + void handleElement(Node n) throws SAXException { + if (n == null) { + return; + } + if (n.getNodeType() == Node.ELEMENT_NODE) { - String localName = n.getNodeName(); - mHandler.startElement(null, localName, null, new MyAttributes(n)); + String localName = n.getNodeName(); + mHandler.startElement(null, localName, null, new MyAttributes(n)); - if (n.hasChildNodes()) { - NodeList l = n.getChildNodes(); - for (int i = 0, len = l.getLength(); i < len; i++) { - handleElement(l.item(i)); - } - } - mHandler.endElement(null, localName, null); - } + if (n.hasChildNodes()) { + NodeList l = n.getChildNodes(); + for (int i = 0, len = l.getLength(); i < len; i++) { + handleElement(l.item(i)); + } + } + mHandler.endElement(null, localName, null); + } - } + } - private DefaultHandler mHandler; + private DefaultHandler mHandler; - public void setContentHandler(DefaultHandler handler) { - mHandler = handler; - } + public void setContentHandler(DefaultHandler handler) { + mHandler = handler; + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/XMLReaderAdapter.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/XMLReaderAdapter.java index 87470794..03c195d3 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/XMLReaderAdapter.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/backend/XMLReaderAdapter.java @@ -1,16 +1,16 @@ package org.oscim.backend; -import java.io.IOException; -import java.io.InputStream; - import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; -public class XMLReaderAdapter { - public void parse(DefaultHandler handler, InputStream is) throws IOException, SAXException { +import java.io.IOException; +import java.io.InputStream; - MyXMLReader xmlReader = new MyXMLReader(); - xmlReader.setContentHandler(handler); - xmlReader.parse(is); - } +public class XMLReaderAdapter { + public void parse(DefaultHandler handler, InputStream is) throws IOException, SAXException { + + MyXMLReader xmlReader = new MyXMLReader(); + xmlReader.setContentHandler(handler); + xmlReader.parse(is); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/LoadDelayTask.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/LoadDelayTask.java index e6df4507..a608f913 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/LoadDelayTask.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/LoadDelayTask.java @@ -1,29 +1,29 @@ package org.oscim.layers.tile; +import com.badlogic.gdx.Gdx; + import org.oscim.renderer.MapRenderer; import org.oscim.tiling.ITileDataSink; -import com.badlogic.gdx.Gdx; - public abstract class LoadDelayTask implements Runnable { - protected final MapTile tile; - protected final ITileDataSink sink; - protected final T data; + protected final MapTile tile; + protected final ITileDataSink sink; + protected final T data; - public LoadDelayTask(MapTile tile, ITileDataSink sink, T data) { - this.tile = tile; - this.sink = sink; - this.data = data; - } + public LoadDelayTask(MapTile tile, ITileDataSink sink, T data) { + this.tile = tile; + this.sink = sink; + this.data = data; + } - @Override - public void run() { - if (MapRenderer.frametime == TileLoader.lastLoadTime) { - Gdx.app.postRunnable(this); - return; - } - continueLoading(); - } + @Override + public void run() { + if (MapRenderer.frametime == TileLoader.lastLoadTime) { + Gdx.app.postRunnable(this); + return; + } + continueLoading(); + } - public abstract void continueLoading(); + public abstract void continueLoading(); } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/TileLoader.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/TileLoader.java index 9b5d184c..34e91a5a 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/TileLoader.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/layers/tile/TileLoader.java @@ -14,7 +14,8 @@ */ package org.oscim.layers.tile; -import static org.oscim.tiling.QueryResult.FAILED; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.utils.Timer; import org.oscim.backend.canvas.Bitmap; import org.oscim.core.MapElement; @@ -24,136 +25,135 @@ import org.oscim.tiling.QueryResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.utils.Timer; +import static org.oscim.tiling.QueryResult.FAILED; public abstract class TileLoader implements ITileDataSink { - final static Logger log = LoggerFactory.getLogger(TileLoader.class); + final static Logger log = LoggerFactory.getLogger(TileLoader.class); - private final TileManager mTileManager; - private Timer mTimer; + private final TileManager mTileManager; + private Timer mTimer; - public TileLoader(TileManager tileManager) { - if (mTimer == null) - mTimer = new Timer(); + public TileLoader(TileManager tileManager) { + if (mTimer == null) + mTimer = new Timer(); - mTileManager = tileManager; - } + mTileManager = tileManager; + } - public abstract void dispose(); + public abstract void dispose(); - protected abstract boolean loadTile(MapTile tile); + protected abstract boolean loadTile(MapTile tile); - boolean isInterrupted; + boolean isInterrupted; - public void finish() { - isInterrupted = true; - // cancel loading - } + public void finish() { + isInterrupted = true; + // cancel loading + } - public void cancel() { - isInterrupted = true; - // cancel loading... ? - } + public void cancel() { + isInterrupted = true; + // cancel loading... ? + } - boolean mPausing; + boolean mPausing; - public boolean isCanceled() { - return mPausing; - } + public boolean isCanceled() { + return mPausing; + } - public boolean isPausing() { - return mPausing; - } + public boolean isPausing() { + return mPausing; + } - public void pause() { - mPausing = true; - } + public void pause() { + mPausing = true; + } - public void proceed() { - mPausing = false; - // FIXME - mWorking = false; - if (mTileManager.hasTileJobs()) - go(); - } + public void proceed() { + mPausing = false; + // FIXME + mWorking = false; + if (mTileManager.hasTileJobs()) + go(); + } - public void awaitPausing() { + public void awaitPausing() { - } + } - public void start() { - mPausing = false; - } + public void start() { + mPausing = false; + } - protected boolean mWorking; - protected MapTile mTile; + protected boolean mWorking; + protected MapTile mTile; - public void go() { - if (mWorking) - return; + public void go() { + if (mWorking) + return; - mTile = mTileManager.getTileJob(); + mTile = mTileManager.getTileJob(); - if (mTile == null) - return; + if (mTile == null) + return; - try { - loadTile(mTile); - mWorking = true; - } catch (Exception e) { - e.printStackTrace(); - completed(FAILED); - } - } + try { + loadTile(mTile); + mWorking = true; + } catch (Exception e) { + e.printStackTrace(); + completed(FAILED); + } + } - public static long lastLoadTime; + public static long lastLoadTime; - /** - * Callback to be called by TileDataSource when finished - * loading or on failure. MUST BE CALLED IN ANY CASE! - */ - @Override - public void completed(QueryResult result) { - long now = MapRenderer.frametime; + /** + * Callback to be called by TileDataSource when finished + * loading or on failure. MUST BE CALLED IN ANY CASE! + */ + @Override + public void completed(QueryResult result) { + long now = MapRenderer.frametime; - //log.debug("completed {} diff time:{}", mTile, (now - lastLoadTime)); - lastLoadTime = now; + //log.debug("completed {} diff time:{}", mTile, (now - lastLoadTime)); + lastLoadTime = now; - mTileManager.jobCompleted(mTile, result); - mTile = null; + mTileManager.jobCompleted(mTile, result); + mTile = null; - mWorking = false; + mWorking = false; - if (mPausing || !mTileManager.hasTileJobs()) - return; + if (mPausing || !mTileManager.hasTileJobs()) + return; - Gdx.app.postRunnable(new Runnable() { - @Override - public void run() { - go(); - } - }); - } + Gdx.app.postRunnable(new Runnable() { + @Override + public void run() { + go(); + } + }); + } - /** - * Called by TileDataSource - */ - @Override - public void process(MapElement element) { + /** + * Called by TileDataSource + */ + @Override + public void process(MapElement element) { - } + } - /** - * Called by TileDataSource - */ - @Override - public void setTileImage(Bitmap bitmap) { + /** + * Called by TileDataSource + */ + @Override + public void setTileImage(Bitmap bitmap) { - } + } - public static void postLoadDelay(LoadDelayTask task) { - Gdx.app.postRunnable(task); - } + public static void postLoadDelay(LoadDelayTask task) { + Gdx.app.postRunnable(task); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/renderer/GLMatrix.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/renderer/GLMatrix.java index 2994db17..c40aeab7 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/renderer/GLMatrix.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/renderer/GLMatrix.java @@ -1,13 +1,13 @@ /******************************************************************************* * Copyright 2011 See libgdx AUTHORS file. * Copyright 2013 Hannes Janetzek - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,377 +17,376 @@ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; +import static org.oscim.backend.GLAdapter.gl; + public class GLMatrix { - public static final int M00 = 0;// 0; - public static final int M01 = 4;// 1; - public static final int M02 = 8;// 2; - public static final int M03 = 12;// 3; - public static final int M10 = 1;// 4; - public static final int M11 = 5;// 5; - public static final int M12 = 9;// 6; - public static final int M13 = 13;// 7; - public static final int M20 = 2;// 8; - public static final int M21 = 6;// 9; - public static final int M22 = 10;// 10; - public static final int M23 = 14;// 11; - public static final int M30 = 3;// 12; - public static final int M31 = 7;// 13; - public static final int M32 = 11;// 14; - public static final int M33 = 15;// 15; + public static final int M00 = 0;// 0; + public static final int M01 = 4;// 1; + public static final int M02 = 8;// 2; + public static final int M03 = 12;// 3; + public static final int M10 = 1;// 4; + public static final int M11 = 5;// 5; + public static final int M12 = 9;// 6; + public static final int M13 = 13;// 7; + public static final int M20 = 2;// 8; + public static final int M21 = 6;// 9; + public static final int M22 = 10;// 10; + public static final int M23 = 14;// 11; + public static final int M30 = 3;// 12; + public static final int M31 = 7;// 13; + public static final int M32 = 11;// 14; + public static final int M33 = 15;// 15; - private final FloatBuffer buffer = ByteBuffer.allocateDirect(16 * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer(); + private final FloatBuffer buffer = ByteBuffer.allocateDirect(16 * 4) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer(); - private final static String INVALID_INPUT = "Bad Array!"; + private final static String INVALID_INPUT = "Bad Array!"; - public final float tmp[] = new float[16]; - public final float val[] = new float[16]; + public final float tmp[] = new float[16]; + public final float val[] = new float[16]; - /** - * Sets the matrix to the given matrix as a float array. The float array - * must have at least 16 elements; the first 16 will be - * copied. - * - * @param values The matrix, in float form, that is to be copied. Remember - * that this matrix is in column - * major order. - * @return This matrix for the purpose of chaining methods together. - */ - public void set(float[] values) { - val[M00] = values[M00]; - val[M10] = values[M10]; - val[M20] = values[M20]; - val[M30] = values[M30]; - val[M01] = values[M01]; - val[M11] = values[M11]; - val[M21] = values[M21]; - val[M31] = values[M31]; - val[M02] = values[M02]; - val[M12] = values[M12]; - val[M22] = values[M22]; - val[M32] = values[M32]; - val[M03] = values[M03]; - val[M13] = values[M13]; - val[M23] = values[M23]; - val[M33] = values[M33]; - } + /** + * Sets the matrix to the given matrix as a float array. The float array + * must have at least 16 elements; the first 16 will be + * copied. + * + * @param values The matrix, in float form, that is to be copied. Remember + * that this matrix is in column + * major order. + * @return This matrix for the purpose of chaining methods together. + */ + public void set(float[] values) { + val[M00] = values[M00]; + val[M10] = values[M10]; + val[M20] = values[M20]; + val[M30] = values[M30]; + val[M01] = values[M01]; + val[M11] = values[M11]; + val[M21] = values[M21]; + val[M31] = values[M31]; + val[M02] = values[M02]; + val[M12] = values[M12]; + val[M22] = values[M22]; + val[M32] = values[M32]; + val[M03] = values[M03]; + val[M13] = values[M13]; + val[M23] = values[M23]; + val[M33] = values[M33]; + } - /** - * Get the Matrix as float array - * - * @param m float array to store Matrix - */ - public void get(float[] m) { + /** + * Get the Matrix as float array + * + * @param m float array to store Matrix + */ + public void get(float[] m) { - if (m == null || m.length != 16) - throw new IllegalArgumentException(INVALID_INPUT); + if (m == null || m.length != 16) + throw new IllegalArgumentException(INVALID_INPUT); - System.arraycopy(val, 0, m, 0, 16); - } + System.arraycopy(val, 0, m, 0, 16); + } - /** - * Copy values from mat - * - * @param mat Matrix to copy - */ - public void copy(GLMatrix m) { - if (m == null || m.val.length != 16) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Copy values from mat + * + * @param mat Matrix to copy + */ + public void copy(GLMatrix m) { + if (m == null || m.val.length != 16) + throw new IllegalArgumentException(INVALID_INPUT); - System.arraycopy(m.val, 0, val, 0, 16); - } + System.arraycopy(m.val, 0, val, 0, 16); + } - /** - * Project Vector with Matrix - * - * @param vec3 Vector to project - */ - public void prj(float[] vec3) { - if (vec3 == null || vec3.length < 3) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Project Vector with Matrix + * + * @param vec3 Vector to project + */ + public void prj(float[] vec3) { + if (vec3 == null || vec3.length < 3) + throw new IllegalArgumentException(INVALID_INPUT); - matrix4_proj(val, vec3); - } + matrix4_proj(val, vec3); + } - static void matrix4_proj(float[] mat, float[] vec) { - float inv_w = 1.0f / (vec[0] * mat[M30] + vec[1] * mat[M31] + vec[2] * mat[M32] + mat[M33]); - float x = (vec[0] * mat[M00] + vec[1] * mat[M01] + vec[2] * mat[M02] + mat[M03]) * inv_w; - float y = (vec[0] * mat[M10] + vec[1] * mat[M11] + vec[2] * mat[M12] + mat[M13]) * inv_w; - float z = (vec[0] * mat[M20] + vec[1] * mat[M21] + vec[2] * mat[M22] + mat[M23]) * inv_w; - vec[0] = x; - vec[1] = y; - vec[2] = z; - } + static void matrix4_proj(float[] mat, float[] vec) { + float inv_w = 1.0f / (vec[0] * mat[M30] + vec[1] * mat[M31] + vec[2] * mat[M32] + mat[M33]); + float x = (vec[0] * mat[M00] + vec[1] * mat[M01] + vec[2] * mat[M02] + mat[M03]) * inv_w; + float y = (vec[0] * mat[M10] + vec[1] * mat[M11] + vec[2] * mat[M12] + mat[M13]) * inv_w; + float z = (vec[0] * mat[M20] + vec[1] * mat[M21] + vec[2] * mat[M22] + mat[M23]) * inv_w; + vec[0] = x; + vec[1] = y; + vec[2] = z; + } - public void prj3D(float[] vec, int offset, int cnt) { - throw new RuntimeException("unimplemented"); - } + public void prj3D(float[] vec, int offset, int cnt) { + throw new RuntimeException("unimplemented"); + } - public void prj2D(float[] vec, int offset, int cnt) { - offset <<= 1; - cnt <<= 1; + public void prj2D(float[] vec, int offset, int cnt) { + offset <<= 1; + cnt <<= 1; - for (int x = offset, y = x + 1; x < cnt + offset; x += 2, y += 2) { - float inv_w = 1.0f / (vec[x] * val[M30] + vec[y] * val[M31] + val[M33]); - float ox = (vec[x] * val[M00] + vec[y] * val[M01] + val[M03]) * inv_w; - vec[y] = (vec[x] * val[M10] + vec[y] * val[M11] + val[M13]) * inv_w; - vec[x] = ox; - } - } + for (int x = offset, y = x + 1; x < cnt + offset; x += 2, y += 2) { + float inv_w = 1.0f / (vec[x] * val[M30] + vec[y] * val[M31] + val[M33]); + float ox = (vec[x] * val[M00] + vec[y] * val[M01] + val[M03]) * inv_w; + vec[y] = (vec[x] * val[M10] + vec[y] * val[M11] + val[M13]) * inv_w; + vec[x] = ox; + } + } - /** - * Project Vectors with Matrix - * - * - * @param vec2 Vector to project - */ - public void prj2D(float[] src, int src_offset, float[] dst, int dst_offset, int length) { - if (src == null || src_offset < 0 || length + src_offset * 2 > src.length) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Project Vectors with Matrix + * + * @param vec2 Vector to project + */ + public void prj2D(float[] src, int src_offset, float[] dst, int dst_offset, int length) { + if (src == null || src_offset < 0 || length + src_offset * 2 > src.length) + throw new IllegalArgumentException(INVALID_INPUT); - int x = (src_offset << 1); - int y = x + 1; + int x = (src_offset << 1); + int y = x + 1; - int end = x + (length << 1); + int end = x + (length << 1); - dst_offset <<= 1; + dst_offset <<= 1; - while (x < end) { - float inv_w = 1.0f / (src[x] * val[M30] + src[y] * val[M31] + val[M33]); + while (x < end) { + float inv_w = 1.0f / (src[x] * val[M30] + src[y] * val[M31] + val[M33]); - dst[dst_offset++] = (src[x] * val[M00] + src[y] * val[M01] + val[M03]) * inv_w; - dst[dst_offset++] = (src[x] * val[M10] + src[y] * val[M11] + val[M13]) * inv_w; - x += 2; - y += 2; - } - } + dst[dst_offset++] = (src[x] * val[M00] + src[y] * val[M01] + val[M03]) * inv_w; + dst[dst_offset++] = (src[x] * val[M10] + src[y] * val[M11] + val[M13]) * inv_w; + x += 2; + y += 2; + } + } - /** - * Multiply rhs onto Matrix. - * - * @param rhs right hand side - */ - public void multiplyRhs(GLMatrix rhs) { - matrix4_mul(val, rhs.val); - } + /** + * Multiply rhs onto Matrix. + * + * @param rhs right hand side + */ + public void multiplyRhs(GLMatrix rhs) { + matrix4_mul(val, rhs.val); + } - /** - * Use this matrix as rhs, multiply it on lhs and store result. - * - * @param lhs right hand side - */ - public void multiplyLhs(GLMatrix lhs) { - System.arraycopy(lhs.val, 0, tmp, 0, 16); - matrix4_mul(tmp, val); - System.arraycopy(tmp, 0, val, 0, 16); - } + /** + * Use this matrix as rhs, multiply it on lhs and store result. + * + * @param lhs right hand side + */ + public void multiplyLhs(GLMatrix lhs) { + System.arraycopy(lhs.val, 0, tmp, 0, 16); + matrix4_mul(tmp, val); + System.arraycopy(tmp, 0, val, 0, 16); + } - /** - * Multiply rhs onto lhs and store result in Matrix. - * - * This matrix MUST be different from lhs and rhs! - * - * As you know, when combining matrices for vector projection - * this has the same effect first as applying rhs then lhs. - * - * @param lhs left hand side - * @param rhs right hand side - */ - public void multiplyMM(GLMatrix lhs, GLMatrix rhs) { - System.arraycopy(lhs.val, 0, tmp, 0, 16); - matrix4_mul(tmp, rhs.val); - System.arraycopy(tmp, 0, val, 0, 16); - } + /** + * Multiply rhs onto lhs and store result in Matrix. + *

+ * This matrix MUST be different from lhs and rhs! + *

+ * As you know, when combining matrices for vector projection + * this has the same effect first as applying rhs then lhs. + * + * @param lhs left hand side + * @param rhs right hand side + */ + public void multiplyMM(GLMatrix lhs, GLMatrix rhs) { + System.arraycopy(lhs.val, 0, tmp, 0, 16); + matrix4_mul(tmp, rhs.val); + System.arraycopy(tmp, 0, val, 0, 16); + } - /** - * Transpose mat and store result in Matrix - * - * @param mat to transpose - */ - public void transposeM(GLMatrix mat) { - val[M00] = mat.val[M00]; - val[M01] = mat.val[M10]; - val[M02] = mat.val[M20]; - val[M03] = mat.val[M30]; - val[M10] = mat.val[M01]; - val[M11] = mat.val[M11]; - val[M12] = mat.val[M21]; - val[M13] = mat.val[M31]; - val[M20] = mat.val[M02]; - val[M21] = mat.val[M12]; - val[M22] = mat.val[M22]; - val[M23] = mat.val[M32]; - val[M30] = mat.val[M03]; - val[M31] = mat.val[M13]; - val[M32] = mat.val[M23]; - val[M33] = mat.val[M33]; - } + /** + * Transpose mat and store result in Matrix + * + * @param mat to transpose + */ + public void transposeM(GLMatrix mat) { + val[M00] = mat.val[M00]; + val[M01] = mat.val[M10]; + val[M02] = mat.val[M20]; + val[M03] = mat.val[M30]; + val[M10] = mat.val[M01]; + val[M11] = mat.val[M11]; + val[M12] = mat.val[M21]; + val[M13] = mat.val[M31]; + val[M20] = mat.val[M02]; + val[M21] = mat.val[M12]; + val[M22] = mat.val[M22]; + val[M23] = mat.val[M32]; + val[M30] = mat.val[M03]; + val[M31] = mat.val[M13]; + val[M32] = mat.val[M23]; + val[M33] = mat.val[M33]; + } - /** - * Set rotation - * - * @param a angle in degree - * @param x around x-axis - * @param y around y-axis - * @param z around z-axis - */ - public void setRotation(float a, float x, float y, float z) { - setRotateM(val, 0, a, x, y, z); - } + /** + * Set rotation + * + * @param a angle in degree + * @param x around x-axis + * @param y around y-axis + * @param z around z-axis + */ + public void setRotation(float a, float x, float y, float z) { + setRotateM(val, 0, a, x, y, z); + } - /** - * Set translation - * - * @param x along x-axis - * @param y along y-axis - * @param z along z-axis - */ - public void setTranslation(float x, float y, float z) { - setIdentity(); - val[M03] = x; - val[M13] = y; - val[M23] = z; - } + /** + * Set translation + * + * @param x along x-axis + * @param y along y-axis + * @param z along z-axis + */ + public void setTranslation(float x, float y, float z) { + setIdentity(); + val[M03] = x; + val[M13] = y; + val[M23] = z; + } - /** - * Set scale factor - * - * @param x axis - * @param y axis - * @param z axis - */ - public void setScale(float x, float y, float z) { - setIdentity(); - val[M00] = x; - val[M11] = y; - val[M22] = z; - } + /** + * Set scale factor + * + * @param x axis + * @param y axis + * @param z axis + */ + public void setScale(float x, float y, float z) { + setIdentity(); + val[M00] = x; + val[M11] = y; + val[M22] = z; + } - /** - * Set translation and x,y scale - * - * @param tx translate x - * @param ty translate y - * @param scale factor x,y - */ - public void setTransScale(float tx, float ty, float scale) { - setIdentity(); - val[M03] = tx; - val[M13] = ty; + /** + * Set translation and x,y scale + * + * @param tx translate x + * @param ty translate y + * @param scale factor x,y + */ + public void setTransScale(float tx, float ty, float scale) { + setIdentity(); + val[M03] = tx; + val[M13] = ty; - val[M00] = scale; - val[M11] = scale; - } + val[M00] = scale; + val[M11] = scale; + } - /** - * Set Matrix with glUniformMatrix - * - * @param location GL location id - */ - public void setAsUniform(int location) { - buffer.clear(); - buffer.put(val, 0, 16); - buffer.position(0); - gl.uniformMatrix4fv(location, 1, false, buffer); - } + /** + * Set Matrix with glUniformMatrix + * + * @param location GL location id + */ + public void setAsUniform(int location) { + buffer.clear(); + buffer.put(val, 0, 16); + buffer.position(0); + gl.uniformMatrix4fv(location, 1, false, buffer); + } - /** - * Set single value - * - * @param pos at position - * @param value value to set - */ - public void setValue(int pos, float value) { - val[pos] = value; - } + /** + * Set single value + * + * @param pos at position + * @param value value to set + */ + public void setValue(int pos, float value) { + val[pos] = value; + } - static float PiTimesThumb = 1.0f / (1 << 11); + static float PiTimesThumb = 1.0f / (1 << 11); - /** - * add some offset (similar to glDepthOffset) - * - * @param delta offset - */ - public void addDepthOffset(int delta) { - val[10] *= 1.0f + PiTimesThumb * delta; - } + /** + * add some offset (similar to glDepthOffset) + * + * @param delta offset + */ + public void addDepthOffset(int delta) { + val[10] *= 1.0f + PiTimesThumb * delta; + } - /** - * Set identity matrix - */ - public void setIdentity() { - val[M00] = 1; - val[M01] = 0; - val[M02] = 0; - val[M03] = 0; - val[M10] = 0; - val[M11] = 1; - val[M12] = 0; - val[M13] = 0; - val[M20] = 0; - val[M21] = 0; - val[M22] = 1; - val[M23] = 0; - val[M30] = 0; - val[M31] = 0; - val[M32] = 0; - val[M33] = 1; - } + /** + * Set identity matrix + */ + public void setIdentity() { + val[M00] = 1; + val[M01] = 0; + val[M02] = 0; + val[M03] = 0; + val[M10] = 0; + val[M11] = 1; + val[M12] = 0; + val[M13] = 0; + val[M20] = 0; + val[M21] = 0; + val[M22] = 1; + val[M23] = 0; + val[M30] = 0; + val[M31] = 0; + val[M32] = 0; + val[M33] = 1; + } - static void matrix4_mul(float[] mata, float[] matb) { - float tmp[] = new float[16]; - tmp[M00] = mata[M00] * matb[M00] + mata[M01] * matb[M10] + mata[M02] * matb[M20] - + mata[M03] * matb[M30]; - tmp[M01] = mata[M00] * matb[M01] + mata[M01] * matb[M11] + mata[M02] * matb[M21] - + mata[M03] * matb[M31]; - tmp[M02] = mata[M00] * matb[M02] + mata[M01] * matb[M12] + mata[M02] * matb[M22] - + mata[M03] * matb[M32]; - tmp[M03] = mata[M00] * matb[M03] + mata[M01] * matb[M13] + mata[M02] * matb[M23] - + mata[M03] * matb[M33]; - tmp[M10] = mata[M10] * matb[M00] + mata[M11] * matb[M10] + mata[M12] * matb[M20] - + mata[M13] * matb[M30]; - tmp[M11] = mata[M10] * matb[M01] + mata[M11] * matb[M11] + mata[M12] * matb[M21] - + mata[M13] * matb[M31]; - tmp[M12] = mata[M10] * matb[M02] + mata[M11] * matb[M12] + mata[M12] * matb[M22] - + mata[M13] * matb[M32]; - tmp[M13] = mata[M10] * matb[M03] + mata[M11] * matb[M13] + mata[M12] * matb[M23] - + mata[M13] * matb[M33]; - tmp[M20] = mata[M20] * matb[M00] + mata[M21] * matb[M10] + mata[M22] * matb[M20] - + mata[M23] * matb[M30]; - tmp[M21] = mata[M20] * matb[M01] + mata[M21] * matb[M11] + mata[M22] * matb[M21] - + mata[M23] * matb[M31]; - tmp[M22] = mata[M20] * matb[M02] + mata[M21] * matb[M12] + mata[M22] * matb[M22] - + mata[M23] * matb[M32]; - tmp[M23] = mata[M20] * matb[M03] + mata[M21] * matb[M13] + mata[M22] * matb[M23] - + mata[M23] * matb[M33]; - tmp[M30] = mata[M30] * matb[M00] + mata[M31] * matb[M10] + mata[M32] * matb[M20] - + mata[M33] * matb[M30]; - tmp[M31] = mata[M30] * matb[M01] + mata[M31] * matb[M11] + mata[M32] * matb[M21] - + mata[M33] * matb[M31]; - tmp[M32] = mata[M30] * matb[M02] + mata[M31] * matb[M12] + mata[M32] * matb[M22] - + mata[M33] * matb[M32]; - tmp[M33] = mata[M30] * matb[M03] + mata[M31] * matb[M13] + mata[M32] * matb[M23] - + mata[M33] * matb[M33]; - System.arraycopy(tmp, 0, mata, 0, 16); - } + static void matrix4_mul(float[] mata, float[] matb) { + float tmp[] = new float[16]; + tmp[M00] = mata[M00] * matb[M00] + mata[M01] * matb[M10] + mata[M02] * matb[M20] + + mata[M03] * matb[M30]; + tmp[M01] = mata[M00] * matb[M01] + mata[M01] * matb[M11] + mata[M02] * matb[M21] + + mata[M03] * matb[M31]; + tmp[M02] = mata[M00] * matb[M02] + mata[M01] * matb[M12] + mata[M02] * matb[M22] + + mata[M03] * matb[M32]; + tmp[M03] = mata[M00] * matb[M03] + mata[M01] * matb[M13] + mata[M02] * matb[M23] + + mata[M03] * matb[M33]; + tmp[M10] = mata[M10] * matb[M00] + mata[M11] * matb[M10] + mata[M12] * matb[M20] + + mata[M13] * matb[M30]; + tmp[M11] = mata[M10] * matb[M01] + mata[M11] * matb[M11] + mata[M12] * matb[M21] + + mata[M13] * matb[M31]; + tmp[M12] = mata[M10] * matb[M02] + mata[M11] * matb[M12] + mata[M12] * matb[M22] + + mata[M13] * matb[M32]; + tmp[M13] = mata[M10] * matb[M03] + mata[M11] * matb[M13] + mata[M12] * matb[M23] + + mata[M13] * matb[M33]; + tmp[M20] = mata[M20] * matb[M00] + mata[M21] * matb[M10] + mata[M22] * matb[M20] + + mata[M23] * matb[M30]; + tmp[M21] = mata[M20] * matb[M01] + mata[M21] * matb[M11] + mata[M22] * matb[M21] + + mata[M23] * matb[M31]; + tmp[M22] = mata[M20] * matb[M02] + mata[M21] * matb[M12] + mata[M22] * matb[M22] + + mata[M23] * matb[M32]; + tmp[M23] = mata[M20] * matb[M03] + mata[M21] * matb[M13] + mata[M22] * matb[M23] + + mata[M23] * matb[M33]; + tmp[M30] = mata[M30] * matb[M00] + mata[M31] * matb[M10] + mata[M32] * matb[M20] + + mata[M33] * matb[M30]; + tmp[M31] = mata[M30] * matb[M01] + mata[M31] * matb[M11] + mata[M32] * matb[M21] + + mata[M33] * matb[M31]; + tmp[M32] = mata[M30] * matb[M02] + mata[M31] * matb[M12] + mata[M32] * matb[M22] + + mata[M33] * matb[M32]; + tmp[M33] = mata[M30] * matb[M03] + mata[M31] * matb[M13] + mata[M32] * matb[M23] + + mata[M33] * matb[M33]; + System.arraycopy(tmp, 0, mata, 0, 16); + } - // @Override - // public void finalize() { - // if (pointer != 0) - // delete(pointer); - // } + // @Override + // public void finalize() { + // if (pointer != 0) + // delete(pointer); + // } /* Copyright (C) 2007 The Android Open Source Project - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -400,264 +399,255 @@ public class GLMatrix { * See the License for the specific language governing permissions and * limitations under the License. */ - /** - * Define a projection matrix in terms of six clip planes - * - * @param m the float array that holds the perspective matrix - * @param offset the offset into float array m where the perspective - * matrix data is written - */ - public static void frustumM(float[] m, int offset, - float left, float right, float bottom, float top, - float near, float far) { - if (left == right) { - throw new IllegalArgumentException("left == right"); - } - if (top == bottom) { - throw new IllegalArgumentException("top == bottom"); - } - if (near == far) { - throw new IllegalArgumentException("near == far"); - } - if (near <= 0.0f) { - throw new IllegalArgumentException("near <= 0.0f"); - } - if (far <= 0.0f) { - throw new IllegalArgumentException("far <= 0.0f"); - } - final float r_width = 1.0f / (right - left); - final float r_height = 1.0f / (top - bottom); - final float r_depth = 1.0f / (near - far); - final float x = 2.0f * (near * r_width); - final float y = 2.0f * (near * r_height); - final float A = (right + left) * r_width; - final float B = (top + bottom) * r_height; - final float C = (far + near) * r_depth; - final float D = 2.0f * (far * near * r_depth); - m[offset + 0] = x; - m[offset + 5] = y; - m[offset + 8] = A; - m[offset + 9] = B; - m[offset + 10] = C; - m[offset + 14] = D; - m[offset + 11] = -1.0f; - m[offset + 1] = 0.0f; - m[offset + 2] = 0.0f; - m[offset + 3] = 0.0f; - m[offset + 4] = 0.0f; - m[offset + 6] = 0.0f; - m[offset + 7] = 0.0f; - m[offset + 12] = 0.0f; - m[offset + 13] = 0.0f; - m[offset + 15] = 0.0f; - } + /** + * Define a projection matrix in terms of six clip planes + * + * @param m the float array that holds the perspective matrix + * @param offset the offset into float array m where the perspective + * matrix data is written + */ + public static void frustumM(float[] m, int offset, + float left, float right, float bottom, float top, + float near, float far) { + if (left == right) { + throw new IllegalArgumentException("left == right"); + } + if (top == bottom) { + throw new IllegalArgumentException("top == bottom"); + } + if (near == far) { + throw new IllegalArgumentException("near == far"); + } + if (near <= 0.0f) { + throw new IllegalArgumentException("near <= 0.0f"); + } + if (far <= 0.0f) { + throw new IllegalArgumentException("far <= 0.0f"); + } + final float r_width = 1.0f / (right - left); + final float r_height = 1.0f / (top - bottom); + final float r_depth = 1.0f / (near - far); + final float x = 2.0f * (near * r_width); + final float y = 2.0f * (near * r_height); + final float A = (right + left) * r_width; + final float B = (top + bottom) * r_height; + final float C = (far + near) * r_depth; + final float D = 2.0f * (far * near * r_depth); + m[offset + 0] = x; + m[offset + 5] = y; + m[offset + 8] = A; + m[offset + 9] = B; + m[offset + 10] = C; + m[offset + 14] = D; + m[offset + 11] = -1.0f; + m[offset + 1] = 0.0f; + m[offset + 2] = 0.0f; + m[offset + 3] = 0.0f; + m[offset + 4] = 0.0f; + m[offset + 6] = 0.0f; + m[offset + 7] = 0.0f; + m[offset + 12] = 0.0f; + m[offset + 13] = 0.0f; + m[offset + 15] = 0.0f; + } - /** - * Inverts a 4 x 4 matrix. - * - * @param mInv the array that holds the output inverted matrix - * @param mInvOffset an offset into mInv where the inverted matrix is - * stored. - * @param m the input array - * @param mOffset an offset into m where the matrix is stored. - * @return true if the matrix could be inverted, false if it could not. - */ - public static boolean invertM(float[] mInv, int mInvOffset, float[] m, - int mOffset) { - // Invert a 4 x 4 matrix using Cramer's Rule + /** + * Inverts a 4 x 4 matrix. + * + * @param mInv the array that holds the output inverted matrix + * @param mInvOffset an offset into mInv where the inverted matrix is + * stored. + * @param m the input array + * @param mOffset an offset into m where the matrix is stored. + * @return true if the matrix could be inverted, false if it could not. + */ + public static boolean invertM(float[] mInv, int mInvOffset, float[] m, + int mOffset) { + // Invert a 4 x 4 matrix using Cramer's Rule - // transpose matrix - final float src0 = m[mOffset + 0]; - final float src4 = m[mOffset + 1]; - final float src8 = m[mOffset + 2]; - final float src12 = m[mOffset + 3]; + // transpose matrix + final float src0 = m[mOffset + 0]; + final float src4 = m[mOffset + 1]; + final float src8 = m[mOffset + 2]; + final float src12 = m[mOffset + 3]; - final float src1 = m[mOffset + 4]; - final float src5 = m[mOffset + 5]; - final float src9 = m[mOffset + 6]; - final float src13 = m[mOffset + 7]; + final float src1 = m[mOffset + 4]; + final float src5 = m[mOffset + 5]; + final float src9 = m[mOffset + 6]; + final float src13 = m[mOffset + 7]; - final float src2 = m[mOffset + 8]; - final float src6 = m[mOffset + 9]; - final float src10 = m[mOffset + 10]; - final float src14 = m[mOffset + 11]; + final float src2 = m[mOffset + 8]; + final float src6 = m[mOffset + 9]; + final float src10 = m[mOffset + 10]; + final float src14 = m[mOffset + 11]; - final float src3 = m[mOffset + 12]; - final float src7 = m[mOffset + 13]; - final float src11 = m[mOffset + 14]; - final float src15 = m[mOffset + 15]; + final float src3 = m[mOffset + 12]; + final float src7 = m[mOffset + 13]; + final float src11 = m[mOffset + 14]; + final float src15 = m[mOffset + 15]; - // calculate pairs for first 8 elements (cofactors) - final float atmp0 = src10 * src15; - final float atmp1 = src11 * src14; - final float atmp2 = src9 * src15; - final float atmp3 = src11 * src13; - final float atmp4 = src9 * src14; - final float atmp5 = src10 * src13; - final float atmp6 = src8 * src15; - final float atmp7 = src11 * src12; - final float atmp8 = src8 * src14; - final float atmp9 = src10 * src12; - final float atmp10 = src8 * src13; - final float atmp11 = src9 * src12; + // calculate pairs for first 8 elements (cofactors) + final float atmp0 = src10 * src15; + final float atmp1 = src11 * src14; + final float atmp2 = src9 * src15; + final float atmp3 = src11 * src13; + final float atmp4 = src9 * src14; + final float atmp5 = src10 * src13; + final float atmp6 = src8 * src15; + final float atmp7 = src11 * src12; + final float atmp8 = src8 * src14; + final float atmp9 = src10 * src12; + final float atmp10 = src8 * src13; + final float atmp11 = src9 * src12; - // calculate first 8 elements (cofactors) - final float dst0 = (atmp0 * src5 + atmp3 * src6 + atmp4 * src7) - - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7); - final float dst1 = (atmp1 * src4 + atmp6 * src6 + atmp9 * src7) - - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7); - final float dst2 = (atmp2 * src4 + atmp7 * src5 + atmp10 * src7) - - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7); - final float dst3 = (atmp5 * src4 + atmp8 * src5 + atmp11 * src6) - - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6); - final float dst4 = (atmp1 * src1 + atmp2 * src2 + atmp5 * src3) - - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3); - final float dst5 = (atmp0 * src0 + atmp7 * src2 + atmp8 * src3) - - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3); - final float dst6 = (atmp3 * src0 + atmp6 * src1 + atmp11 * src3) - - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3); - final float dst7 = (atmp4 * src0 + atmp9 * src1 + atmp10 * src2) - - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2); + // calculate first 8 elements (cofactors) + final float dst0 = (atmp0 * src5 + atmp3 * src6 + atmp4 * src7) + - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7); + final float dst1 = (atmp1 * src4 + atmp6 * src6 + atmp9 * src7) + - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7); + final float dst2 = (atmp2 * src4 + atmp7 * src5 + atmp10 * src7) + - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7); + final float dst3 = (atmp5 * src4 + atmp8 * src5 + atmp11 * src6) + - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6); + final float dst4 = (atmp1 * src1 + atmp2 * src2 + atmp5 * src3) + - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3); + final float dst5 = (atmp0 * src0 + atmp7 * src2 + atmp8 * src3) + - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3); + final float dst6 = (atmp3 * src0 + atmp6 * src1 + atmp11 * src3) + - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3); + final float dst7 = (atmp4 * src0 + atmp9 * src1 + atmp10 * src2) + - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2); - // calculate pairs for second 8 elements (cofactors) - final float btmp0 = src2 * src7; - final float btmp1 = src3 * src6; - final float btmp2 = src1 * src7; - final float btmp3 = src3 * src5; - final float btmp4 = src1 * src6; - final float btmp5 = src2 * src5; - final float btmp6 = src0 * src7; - final float btmp7 = src3 * src4; - final float btmp8 = src0 * src6; - final float btmp9 = src2 * src4; - final float btmp10 = src0 * src5; - final float btmp11 = src1 * src4; + // calculate pairs for second 8 elements (cofactors) + final float btmp0 = src2 * src7; + final float btmp1 = src3 * src6; + final float btmp2 = src1 * src7; + final float btmp3 = src3 * src5; + final float btmp4 = src1 * src6; + final float btmp5 = src2 * src5; + final float btmp6 = src0 * src7; + final float btmp7 = src3 * src4; + final float btmp8 = src0 * src6; + final float btmp9 = src2 * src4; + final float btmp10 = src0 * src5; + final float btmp11 = src1 * src4; - // calculate second 8 elements (cofactors) - final float dst8 = (btmp0 * src13 + btmp3 * src14 + btmp4 * src15) - - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15); - final float dst9 = (btmp1 * src12 + btmp6 * src14 + btmp9 * src15) - - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15); - final float dst10 = (btmp2 * src12 + btmp7 * src13 + btmp10 * src15) - - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15); - final float dst11 = (btmp5 * src12 + btmp8 * src13 + btmp11 * src14) - - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14); - final float dst12 = (btmp2 * src10 + btmp5 * src11 + btmp1 * src9) - - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10); - final float dst13 = (btmp8 * src11 + btmp0 * src8 + btmp7 * src10) - - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8); - final float dst14 = (btmp6 * src9 + btmp11 * src11 + btmp3 * src8) - - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9); - final float dst15 = (btmp10 * src10 + btmp4 * src8 + btmp9 * src9) - - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8); + // calculate second 8 elements (cofactors) + final float dst8 = (btmp0 * src13 + btmp3 * src14 + btmp4 * src15) + - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15); + final float dst9 = (btmp1 * src12 + btmp6 * src14 + btmp9 * src15) + - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15); + final float dst10 = (btmp2 * src12 + btmp7 * src13 + btmp10 * src15) + - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15); + final float dst11 = (btmp5 * src12 + btmp8 * src13 + btmp11 * src14) + - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14); + final float dst12 = (btmp2 * src10 + btmp5 * src11 + btmp1 * src9) + - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10); + final float dst13 = (btmp8 * src11 + btmp0 * src8 + btmp7 * src10) + - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8); + final float dst14 = (btmp6 * src9 + btmp11 * src11 + btmp3 * src8) + - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9); + final float dst15 = (btmp10 * src10 + btmp4 * src8 + btmp9 * src9) + - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8); - // calculate determinant - final float det = - src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3; + // calculate determinant + final float det = + src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3; - if (det == 0.0f) { - return false; - } + if (det == 0.0f) { + return false; + } - // calculate matrix inverse - final float invdet = 1.0f / det; - mInv[mInvOffset] = dst0 * invdet; - mInv[1 + mInvOffset] = dst1 * invdet; - mInv[2 + mInvOffset] = dst2 * invdet; - mInv[3 + mInvOffset] = dst3 * invdet; + // calculate matrix inverse + final float invdet = 1.0f / det; + mInv[mInvOffset] = dst0 * invdet; + mInv[1 + mInvOffset] = dst1 * invdet; + mInv[2 + mInvOffset] = dst2 * invdet; + mInv[3 + mInvOffset] = dst3 * invdet; - mInv[4 + mInvOffset] = dst4 * invdet; - mInv[5 + mInvOffset] = dst5 * invdet; - mInv[6 + mInvOffset] = dst6 * invdet; - mInv[7 + mInvOffset] = dst7 * invdet; + mInv[4 + mInvOffset] = dst4 * invdet; + mInv[5 + mInvOffset] = dst5 * invdet; + mInv[6 + mInvOffset] = dst6 * invdet; + mInv[7 + mInvOffset] = dst7 * invdet; - mInv[8 + mInvOffset] = dst8 * invdet; - mInv[9 + mInvOffset] = dst9 * invdet; - mInv[10 + mInvOffset] = dst10 * invdet; - mInv[11 + mInvOffset] = dst11 * invdet; + mInv[8 + mInvOffset] = dst8 * invdet; + mInv[9 + mInvOffset] = dst9 * invdet; + mInv[10 + mInvOffset] = dst10 * invdet; + mInv[11 + mInvOffset] = dst11 * invdet; - mInv[12 + mInvOffset] = dst12 * invdet; - mInv[13 + mInvOffset] = dst13 * invdet; - mInv[14 + mInvOffset] = dst14 * invdet; - mInv[15 + mInvOffset] = dst15 * invdet; + mInv[12 + mInvOffset] = dst12 * invdet; + mInv[13 + mInvOffset] = dst13 * invdet; + mInv[14 + mInvOffset] = dst14 * invdet; + mInv[15 + mInvOffset] = dst15 * invdet; - return true; - } + return true; + } - void setRotateM(float[] rm, int rmOffset, float a, float x, float y, float z) - { - rm[rmOffset + 3] = 0; - rm[rmOffset + 7] = 0; - rm[rmOffset + 11] = 0; - rm[rmOffset + 12] = 0; - rm[rmOffset + 13] = 0; - rm[rmOffset + 14] = 0; - rm[rmOffset + 15] = 1; - a *= (float) (Math.PI / 180.0f); - float s = (float) Math.sin(a); - float c = (float) Math.cos(a); - if (1.0f == x && 0.0f == y && 0.0f == z) - { - rm[rmOffset + 5] = c; - rm[rmOffset + 10] = c; - rm[rmOffset + 6] = s; - rm[rmOffset + 9] = -s; - rm[rmOffset + 1] = 0; - rm[rmOffset + 2] = 0; - rm[rmOffset + 4] = 0; - rm[rmOffset + 8] = 0; - rm[rmOffset + 0] = 1; - } - else if (0.0f == x && 1.0f == y && 0.0f == z) - { - rm[rmOffset + 0] = c; - rm[rmOffset + 10] = c; - rm[rmOffset + 8] = s; - rm[rmOffset + 2] = -s; - rm[rmOffset + 1] = 0; - rm[rmOffset + 4] = 0; - rm[rmOffset + 6] = 0; - rm[rmOffset + 9] = 0; - rm[rmOffset + 5] = 1; - } - else if (0.0f == x && 0.0f == y && 1.0f == z) - { - rm[rmOffset + 0] = c; - rm[rmOffset + 5] = c; - rm[rmOffset + 1] = s; - rm[rmOffset + 4] = -s; - rm[rmOffset + 2] = 0; - rm[rmOffset + 6] = 0; - rm[rmOffset + 8] = 0; - rm[rmOffset + 9] = 0; - rm[rmOffset + 10] = 1; - } - else - { - float len = (float) Math.sqrt(x * x + y * y + z * z); - if (1.0f != len) - { - float recipLen = 1.0f / len; - x *= recipLen; - y *= recipLen; - z *= recipLen; - } - float nc = 1.0f - c; - float xy = x * y; - float yz = y * z; - float zx = z * x; - float xs = x * s; - float ys = y * s; - float zs = z * s; - rm[rmOffset + 0] = x * x * nc + c; - rm[rmOffset + 4] = xy * nc - zs; - rm[rmOffset + 8] = zx * nc + ys; - rm[rmOffset + 1] = xy * nc + zs; - rm[rmOffset + 5] = y * y * nc + c; - rm[rmOffset + 9] = yz * nc - xs; - rm[rmOffset + 2] = zx * nc - ys; - rm[rmOffset + 6] = yz * nc + xs; - rm[rmOffset + 10] = z * z * nc + c; - } - } + void setRotateM(float[] rm, int rmOffset, float a, float x, float y, float z) { + rm[rmOffset + 3] = 0; + rm[rmOffset + 7] = 0; + rm[rmOffset + 11] = 0; + rm[rmOffset + 12] = 0; + rm[rmOffset + 13] = 0; + rm[rmOffset + 14] = 0; + rm[rmOffset + 15] = 1; + a *= (float) (Math.PI / 180.0f); + float s = (float) Math.sin(a); + float c = (float) Math.cos(a); + if (1.0f == x && 0.0f == y && 0.0f == z) { + rm[rmOffset + 5] = c; + rm[rmOffset + 10] = c; + rm[rmOffset + 6] = s; + rm[rmOffset + 9] = -s; + rm[rmOffset + 1] = 0; + rm[rmOffset + 2] = 0; + rm[rmOffset + 4] = 0; + rm[rmOffset + 8] = 0; + rm[rmOffset + 0] = 1; + } else if (0.0f == x && 1.0f == y && 0.0f == z) { + rm[rmOffset + 0] = c; + rm[rmOffset + 10] = c; + rm[rmOffset + 8] = s; + rm[rmOffset + 2] = -s; + rm[rmOffset + 1] = 0; + rm[rmOffset + 4] = 0; + rm[rmOffset + 6] = 0; + rm[rmOffset + 9] = 0; + rm[rmOffset + 5] = 1; + } else if (0.0f == x && 0.0f == y && 1.0f == z) { + rm[rmOffset + 0] = c; + rm[rmOffset + 5] = c; + rm[rmOffset + 1] = s; + rm[rmOffset + 4] = -s; + rm[rmOffset + 2] = 0; + rm[rmOffset + 6] = 0; + rm[rmOffset + 8] = 0; + rm[rmOffset + 9] = 0; + rm[rmOffset + 10] = 1; + } else { + float len = (float) Math.sqrt(x * x + y * y + z * z); + if (1.0f != len) { + float recipLen = 1.0f / len; + x *= recipLen; + y *= recipLen; + z *= recipLen; + } + float nc = 1.0f - c; + float xy = x * y; + float yz = y * z; + float zx = z * x; + float xs = x * s; + float ys = y * s; + float zs = z * s; + rm[rmOffset + 0] = x * x * nc + c; + rm[rmOffset + 4] = xy * nc - zs; + rm[rmOffset + 8] = zx * nc + ys; + rm[rmOffset + 1] = xy * nc + zs; + rm[rmOffset + 5] = y * y * nc + c; + rm[rmOffset + 9] = yz * nc - xs; + rm[rmOffset + 2] = zx * nc - ys; + rm[rmOffset + 6] = yz * nc + xs; + rm[rmOffset + 10] = z * z * nc + c; + } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/LwHttp.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/LwHttp.java index b25da4b9..ed70c801 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/LwHttp.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/LwHttp.java @@ -14,116 +14,116 @@ */ package org.oscim.tiling.source; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.oscim.core.Tile; -import org.oscim.layers.tile.MapTile; - import com.google.gwt.typedarrays.client.Uint8ArrayNative; import com.google.gwt.typedarrays.shared.Uint8Array; import com.google.gwt.xhr.client.ReadyStateChangeHandler; import com.google.gwt.xhr.client.XMLHttpRequest; import com.google.gwt.xhr.client.XMLHttpRequest.ResponseType; +import org.oscim.core.Tile; +import org.oscim.layers.tile.MapTile; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + public class LwHttp implements HttpEngine { - //static final Logger log = LoggerFactory.getLogger(LwHttp.class); + //static final Logger log = LoggerFactory.getLogger(LwHttp.class); - private XMLHttpRequest mHttpRequest; + private XMLHttpRequest mHttpRequest; - private ReadyStateChangeHandler mResponseHandler; + private ReadyStateChangeHandler mResponseHandler; - public LwHttp(UrlTileSource tileSource) { - mTileSource = tileSource; - } + public LwHttp(UrlTileSource tileSource) { + mTileSource = tileSource; + } - static class Buffer extends InputStream { - Uint8Array mBuffer; - int mPos; - int mEnd; + static class Buffer extends InputStream { + Uint8Array mBuffer; + int mPos; + int mEnd; - public Buffer(Uint8Array buf) { - mBuffer = buf; - mPos = 0; - mEnd = buf.byteLength(); - } + public Buffer(Uint8Array buf) { + mBuffer = buf; + mPos = 0; + mEnd = buf.byteLength(); + } - @Override - public synchronized int read() throws IOException { - if (mPos < mEnd) - return mBuffer.get(mPos++); + @Override + public synchronized int read() throws IOException { + if (mPos < mEnd) + return mBuffer.get(mPos++); - return -1; - } - } + return -1; + } + } - public void close() { - if (mHttpRequest == null) - return; + public void close() { + if (mHttpRequest == null) + return; - mHttpRequest.abort(); - mHttpRequest = null; - } + mHttpRequest.abort(); + mHttpRequest = null; + } - private UrlTileSource mTileSource; + private UrlTileSource mTileSource; - public void sendRequest(MapTile tile, final UrlTileDataSource dataSource) { + public void sendRequest(MapTile tile, final UrlTileDataSource dataSource) { - String url = mTileSource.getTileUrl(tile); + String url = mTileSource.getTileUrl(tile); - mHttpRequest = XMLHttpRequest.create(); - mHttpRequest.open("GET", url); - mHttpRequest.setResponseType(ResponseType.ArrayBuffer); + mHttpRequest = XMLHttpRequest.create(); + mHttpRequest.open("GET", url); + mHttpRequest.setResponseType(ResponseType.ArrayBuffer); - mResponseHandler = new ReadyStateChangeHandler() { + mResponseHandler = new ReadyStateChangeHandler() { - @Override - public void onReadyStateChange(XMLHttpRequest xhr) { - int state = xhr.getReadyState(); - //log.debug(mCurrentUrl + "response " + status + "/" + state); + @Override + public void onReadyStateChange(XMLHttpRequest xhr) { + int state = xhr.getReadyState(); + //log.debug(mCurrentUrl + "response " + status + "/" + state); - if (state == XMLHttpRequest.DONE) { - if (xhr.getStatus() == 200) { - Uint8Array buf = Uint8ArrayNative.create(xhr.getResponseArrayBuffer()); - dataSource.process(new Buffer(buf)); - } else { - dataSource.process(null); - } - mHttpRequest = null; - } - } - }; + if (state == XMLHttpRequest.DONE) { + if (xhr.getStatus() == 200) { + Uint8Array buf = Uint8ArrayNative.create(xhr.getResponseArrayBuffer()); + dataSource.process(new Buffer(buf)); + } else { + dataSource.process(null); + } + mHttpRequest = null; + } + } + }; - mHttpRequest.setOnReadyStateChange(mResponseHandler); - mHttpRequest.send(); - } + mHttpRequest.setOnReadyStateChange(mResponseHandler); + mHttpRequest.send(); + } - public static class LwHttpFactory implements HttpEngine.Factory { + public static class LwHttpFactory implements HttpEngine.Factory { - @Override - public HttpEngine create(UrlTileSource tileSource) { - return new LwHttp(tileSource); - } - } + @Override + public HttpEngine create(UrlTileSource tileSource) { + return new LwHttp(tileSource); + } + } - @Override - public InputStream read() throws IOException { - return null; - } + @Override + public InputStream read() throws IOException { + return null; + } - @Override - public void setCache(OutputStream os) { - } + @Override + public void setCache(OutputStream os) { + } - @Override - public boolean requestCompleted(boolean success) { - // mHttpRequest.clearOnReadyStateChange(); - // mHttpRequest = null; - return true; - } + @Override + public boolean requestCompleted(boolean success) { + // mHttpRequest.clearOnReadyStateChange(); + // mHttpRequest = null; + return true; + } - @Override - public void sendRequest(Tile tile) throws IOException { - } + @Override + public void sendRequest(Tile tile) throws IOException { + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/UrlTileDataSource.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/UrlTileDataSource.java index e8d5b45b..05f9b6ca 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/UrlTileDataSource.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/UrlTileDataSource.java @@ -14,12 +14,6 @@ */ package org.oscim.tiling.source; -import static org.oscim.tiling.QueryResult.FAILED; -import static org.oscim.tiling.QueryResult.SUCCESS; - -import java.io.IOException; -import java.io.InputStream; - import org.oscim.layers.tile.LoadDelayTask; import org.oscim.layers.tile.MapTile; import org.oscim.layers.tile.TileLoader; @@ -28,69 +22,75 @@ import org.oscim.tiling.ITileDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; + +import static org.oscim.tiling.QueryResult.FAILED; +import static org.oscim.tiling.QueryResult.SUCCESS; + public class UrlTileDataSource implements ITileDataSource { - static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class); + static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class); - protected final LwHttp mConn; - protected final ITileDecoder mTileDecoder; - protected final UrlTileSource mTileSource; + protected final LwHttp mConn; + protected final ITileDecoder mTileDecoder; + protected final UrlTileSource mTileSource; - private ITileDataSink mSink; - private MapTile mTile; + private ITileDataSink mSink; + private MapTile mTile; - public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) { - mTileSource = tileSource; - mTileDecoder = tileDecoder; - mConn = (LwHttp) conn; - } + public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) { + mTileSource = tileSource; + mTileDecoder = tileDecoder; + mConn = (LwHttp) conn; + } - @Override - public void query(MapTile tile, ITileDataSink sink) { - mTile = tile; - mSink = sink; - mConn.sendRequest(tile, this); - } + @Override + public void query(MapTile tile, ITileDataSink sink) { + mTile = tile; + mSink = sink; + mConn.sendRequest(tile, this); + } - public void process(final InputStream is) { - if (is == null) { - log.debug("{} no inputstream", mTile); - mSink.completed(FAILED); - mTile = null; - mSink = null; - return; - } + public void process(final InputStream is) { + if (is == null) { + log.debug("{} no inputstream", mTile); + mSink.completed(FAILED); + mTile = null; + mSink = null; + return; + } - TileLoader.postLoadDelay(new LoadDelayTask(mTile, mSink, is) { - @Override - public void continueLoading() { - boolean win = false; - if (tile.state(MapTile.State.LOADING)) { - try { - win = mTileDecoder.decode(tile, sink, data); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (win) { - sink.completed(SUCCESS); - } else { - sink.completed(FAILED); - log.debug("{} decode failed", tile); - } - } - }); - mTile = null; - mSink = null; - } + TileLoader.postLoadDelay(new LoadDelayTask(mTile, mSink, is) { + @Override + public void continueLoading() { + boolean win = false; + if (tile.state(MapTile.State.LOADING)) { + try { + win = mTileDecoder.decode(tile, sink, data); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (win) { + sink.completed(SUCCESS); + } else { + sink.completed(FAILED); + log.debug("{} decode failed", tile); + } + } + }); + mTile = null; + mSink = null; + } - @Override - public void dispose() { - mConn.close(); - } + @Override + public void dispose() { + mConn.close(); + } - @Override - public void cancel() { - mConn.close(); - } + @Override + public void cancel() { + mConn.close(); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/bitmap/BitmapTileSource.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/bitmap/BitmapTileSource.java index 66fa1def..f2783467 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/bitmap/BitmapTileSource.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/bitmap/BitmapTileSource.java @@ -1,5 +1,14 @@ package org.oscim.tiling.source.bitmap; +import com.google.gwt.event.dom.client.ErrorEvent; +import com.google.gwt.event.dom.client.ErrorHandler; +import com.google.gwt.event.dom.client.LoadEvent; +import com.google.gwt.event.dom.client.LoadHandler; +import com.google.gwt.safehtml.shared.SafeUri; +import com.google.gwt.safehtml.shared.UriUtils; +import com.google.gwt.user.client.ui.Image; +import com.google.gwt.user.client.ui.RootPanel; + import org.oscim.gdx.client.GwtBitmap; import org.oscim.layers.tile.LoadDelayTask; import org.oscim.layers.tile.MapTile; @@ -12,126 +21,117 @@ import org.oscim.tiling.source.UrlTileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gwt.event.dom.client.ErrorEvent; -import com.google.gwt.event.dom.client.ErrorHandler; -import com.google.gwt.event.dom.client.LoadEvent; -import com.google.gwt.event.dom.client.LoadHandler; -import com.google.gwt.safehtml.shared.SafeUri; -import com.google.gwt.safehtml.shared.UriUtils; -import com.google.gwt.user.client.ui.Image; -import com.google.gwt.user.client.ui.RootPanel; - public class BitmapTileSource extends UrlTileSource { - static final Logger log = LoggerFactory.getLogger(LwHttp.class); + static final Logger log = LoggerFactory.getLogger(LwHttp.class); - public static class Builder> extends UrlTileSource.Builder { + public static class Builder> extends UrlTileSource.Builder { - public Builder() { - super(null, "/{Z}/{X}/{Y}.png", 0, 17); - } + public Builder() { + super(null, "/{Z}/{X}/{Y}.png", 0, 17); + } - public BitmapTileSource build() { - return new BitmapTileSource(this); - } - } + public BitmapTileSource build() { + return new BitmapTileSource(this); + } + } - protected BitmapTileSource(Builder builder) { - super(builder); - } + protected BitmapTileSource(Builder builder) { + super(builder); + } - @SuppressWarnings("rawtypes") - public static Builder builder() { - return new Builder(); - } + @SuppressWarnings("rawtypes") + public static Builder builder() { + return new Builder(); + } - /** - * Create BitmapTileSource for 'url' - * - * By default path will be formatted as: url/z/x/y.png - * Use e.g. setExtension(".jpg") to overide ending or - * implement getUrlString() for custom formatting. - */ + /** + * Create BitmapTileSource for 'url' + *

+ * By default path will be formatted as: url/z/x/y.png + * Use e.g. setExtension(".jpg") to overide ending or + * implement getUrlString() for custom formatting. + */ - public BitmapTileSource(String url, int zoomMin, int zoomMax) { - super(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax); - } + public BitmapTileSource(String url, int zoomMin, int zoomMax) { + super(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax); + } - public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) { - super(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax); - } + public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) { + super(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax); + } - public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) { - super(url, tilePath, zoomMin, zoomMax); - } + public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) { + super(url, tilePath, zoomMin, zoomMax); + } - @Override - public ITileDataSource getDataSource() { - return new BitmapTileDataSource(this); - } + @Override + public ITileDataSource getDataSource() { + return new BitmapTileDataSource(this); + } - public class BitmapTileDataSource implements ITileDataSource { + public class BitmapTileDataSource implements ITileDataSource { - protected final UrlTileSource mTileSource; + protected final UrlTileSource mTileSource; - public BitmapTileDataSource(BitmapTileSource bitmapTileSource) { - mTileSource = bitmapTileSource; - } + public BitmapTileDataSource(BitmapTileSource bitmapTileSource) { + mTileSource = bitmapTileSource; + } - @Override - public void query(final MapTile tile, final ITileDataSink sink) { + @Override + public void query(final MapTile tile, final ITileDataSink sink) { - String url = mTileSource.getTileUrl(tile); + String url = mTileSource.getTileUrl(tile); - SafeUri uri = UriUtils.fromTrustedString(url); + SafeUri uri = UriUtils.fromTrustedString(url); - final Image img = new Image(); - img.setVisible(false); + final Image img = new Image(); + img.setVisible(false); /* As if researching CORS issues doesnt result in - * enough headache... + * enough headache... * * Here are some more special Chrome/Webkit quirks: * MUST SET CORS BEFORE URL! */ - img.getElement().setAttribute("crossorigin", "anonymous"); - img.setUrl(uri); + img.getElement().setAttribute("crossorigin", "anonymous"); + img.setUrl(uri); - RootPanel.get().add(img); + RootPanel.get().add(img); - img.addLoadHandler(new LoadHandler() { - public void onLoad(LoadEvent event) { - TileLoader.postLoadDelay(new LoadDelayTask(tile, sink, img) { + img.addLoadHandler(new LoadHandler() { + public void onLoad(LoadEvent event) { + TileLoader.postLoadDelay(new LoadDelayTask(tile, sink, img) { - @Override - public void continueLoading() { - if (!tile.state(MapTile.State.LOADING)) { - sink.completed(QueryResult.FAILED); - RootPanel.get().remove(data); - } else { - sink.setTileImage(new GwtBitmap(data)); - sink.completed(QueryResult.SUCCESS); - } - } - }); - } - }); + @Override + public void continueLoading() { + if (!tile.state(MapTile.State.LOADING)) { + sink.completed(QueryResult.FAILED); + RootPanel.get().remove(data); + } else { + sink.setTileImage(new GwtBitmap(data)); + sink.completed(QueryResult.SUCCESS); + } + } + }); + } + }); - img.addErrorHandler(new ErrorHandler() { + img.addErrorHandler(new ErrorHandler() { - @Override - public void onError(ErrorEvent event) { - sink.completed(QueryResult.FAILED); - RootPanel.get().remove(img); - } - }); - } + @Override + public void onError(ErrorEvent event) { + sink.completed(QueryResult.FAILED); + RootPanel.get().remove(img); + } + }); + } - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public void cancel() { - } + @Override + public void cancel() { + } - } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/geojson/GeoJsonTileSource.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/geojson/GeoJsonTileSource.java index c0cfd4a2..42801165 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/geojson/GeoJsonTileSource.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/tiling/source/geojson/GeoJsonTileSource.java @@ -16,8 +16,6 @@ */ package org.oscim.tiling.source.geojson; -import java.util.Map; - import org.oscim.core.MapElement; import org.oscim.core.Tag; import org.oscim.tiling.ITileDataSource; @@ -26,37 +24,43 @@ import org.oscim.tiling.source.UrlTileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; + public abstract class GeoJsonTileSource extends UrlTileSource { - static final Logger log = LoggerFactory.getLogger(GeoJsonTileSource.class); + static final Logger log = LoggerFactory.getLogger(GeoJsonTileSource.class); - public GeoJsonTileSource(String url) { - super(url, "/{Z}/{X}/{Y}.json"); - } + public GeoJsonTileSource(String url) { + super(url, "/{Z}/{X}/{Y}.json"); + } - @Override - public ITileDataSource getDataSource() { - return new JsonTileDataSource(this); - } + @Override + public ITileDataSource getDataSource() { + return new JsonTileDataSource(this); + } - public Tag getFeatureTag() { - return null; - } + public Tag getFeatureTag() { + return null; + } - /** allow overriding tag handling */ - public abstract void decodeTags(MapElement mapElement, Map properties); + /** + * allow overriding tag handling + */ + public abstract void decodeTags(MapElement mapElement, Map properties); - public Tag rewriteTag(String key, Object value) { + public Tag rewriteTag(String key, Object value) { - if (value == null) - return null; + if (value == null) + return null; - String val = (value instanceof String) ? (String) value : String.valueOf(value); + String val = (value instanceof String) ? (String) value : String.valueOf(value); - return new Tag(key, val); - } + return new Tag(key, val); + } - /** modify mapElement before process() */ - public void postGeomHook(MapElement mapElement) { + /** + * modify mapElement before process() + */ + public void postGeomHook(MapElement mapElement) { - } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/IOUtils.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/IOUtils.java index 0292e51b..b360a5ae 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/IOUtils.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/IOUtils.java @@ -25,34 +25,33 @@ import java.util.logging.Level; */ public final class IOUtils { - /** - * Invokes the {@link Closeable#close()} method on the given object. If an - * {@link IOException} occurs during the - * method call, it will be caught and logged on level {@link Level#WARNING}. - * - * @param closeable - * the data source which should be closed (may be null). - */ - public static void closeQuietly(OutputStream closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (IOException e) { - //log.debug(e.getMessage() + " " + e); - } - } + /** + * Invokes the {@link Closeable#close()} method on the given object. If an + * {@link IOException} occurs during the + * method call, it will be caught and logged on level {@link Level#WARNING}. + * + * @param closeable the data source which should be closed (may be null). + */ + public static void closeQuietly(OutputStream closeable) { + try { + if (closeable != null) { + closeable.close(); + } + } catch (IOException e) { + //log.debug(e.getMessage() + " " + e); + } + } - public static void closeQuietly(InputStream closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (IOException e) { - //log.debug(e.getMessage() + " " + e); - } - } + public static void closeQuietly(InputStream closeable) { + try { + if (closeable != null) { + closeable.close(); + } + } catch (IOException e) { + //log.debug(e.getMessage() + " " + e); + } + } - private IOUtils() { - } + private IOUtils() { + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/TessJNI.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/TessJNI.java index c6a45d7a..9bf40cdf 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/TessJNI.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/TessJNI.java @@ -2,72 +2,72 @@ package org.oscim.utils; public class TessJNI { - public TessJNI() { + public TessJNI() { - } + } - public TessJNI(int size) { - throw new RuntimeException("unimplemented"); - } + public TessJNI(int size) { + throw new RuntimeException("unimplemented"); + } - public void dispose() { - throw new RuntimeException("unimplemented"); - } + public void dispose() { + throw new RuntimeException("unimplemented"); + } - public void addContour2D(float[] points) { - throw new RuntimeException("unimplemented"); - } + public void addContour2D(float[] points) { + throw new RuntimeException("unimplemented"); + } - public void addContour2D(float[] points, int offset, int length) { - throw new RuntimeException("unimplemented"); - } + public void addContour2D(float[] points, int offset, int length) { + throw new RuntimeException("unimplemented"); + } - public void addContour2D(int[] index, float[] contour) { - throw new RuntimeException("unimplemented"); - } + public void addContour2D(int[] index, float[] contour) { + throw new RuntimeException("unimplemented"); + } - public void addContour2D(int[] index, float[] contour, int idxStart, int idxEnd) { - throw new RuntimeException("unimplemented"); - } + public void addContour2D(int[] index, float[] contour, int idxStart, int idxEnd) { + throw new RuntimeException("unimplemented"); + } - public boolean tesselate() { - throw new RuntimeException("unimplemented"); - } + public boolean tesselate() { + throw new RuntimeException("unimplemented"); + } - public boolean tesselate(int windingRule, int elementType) { - throw new RuntimeException("unimplemented"); - } + public boolean tesselate(int windingRule, int elementType) { + throw new RuntimeException("unimplemented"); + } - public int getVertexCount() { - throw new RuntimeException("unimplemented"); - } + public int getVertexCount() { + throw new RuntimeException("unimplemented"); + } - public int getElementCount() { - throw new RuntimeException("unimplemented"); - } + public int getElementCount() { + throw new RuntimeException("unimplemented"); + } - public void getVertices(float[] out, int offset, int length) { - throw new RuntimeException("unimplemented"); - } + public void getVertices(float[] out, int offset, int length) { + throw new RuntimeException("unimplemented"); + } - public void getVertices(short[] out, int offset, int length, float scale) { - throw new RuntimeException("unimplemented"); - } + public void getVertices(short[] out, int offset, int length, float scale) { + throw new RuntimeException("unimplemented"); + } - public void getElements(int[] out, int offset, int length) { - throw new RuntimeException("unimplemented"); - } + public void getElements(int[] out, int offset, int length) { + throw new RuntimeException("unimplemented"); + } - public void getElements(short[] out, int offset, int length) { - throw new RuntimeException("unimplemented"); - } + public void getElements(short[] out, int offset, int length) { + throw new RuntimeException("unimplemented"); + } - public void getVertexIndices(int[] out, int offset, int length) { - throw new RuntimeException("unimplemented"); - } + public void getVertexIndices(int[] out, int offset, int length) { + throw new RuntimeException("unimplemented"); + } - public void getElementsWithInputVertexIds(short[] dst, int dstOffset, int offset, int length) { - throw new RuntimeException("unimplemented"); - } + public void getElementsWithInputVertexIds(short[] dst, int dstOffset, int offset, int length) { + throw new RuntimeException("unimplemented"); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/Tessellator.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/Tessellator.java index fac67faa..26d698da 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/Tessellator.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/Tessellator.java @@ -1,10 +1,5 @@ package org.oscim.utils; -import org.oscim.core.GeometryBuffer; -import org.oscim.renderer.bucket.VertexData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gwt.core.client.JavaScriptException; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArrayInteger; @@ -13,179 +8,184 @@ import com.google.gwt.core.client.JsArrayUtils; import com.google.gwt.typedarrays.shared.Float32Array; import com.google.gwt.typedarrays.shared.Int32Array; +import org.oscim.core.GeometryBuffer; +import org.oscim.renderer.bucket.VertexData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class Tessellator { - static final Logger log = LoggerFactory.getLogger(Tessellator.class); + static final Logger log = LoggerFactory.getLogger(Tessellator.class); - public static int tessellate(GeometryBuffer geom, float scale, - VertexData outPoints, VertexData outTris, int vertexOffset) { + public static int tessellate(GeometryBuffer geom, float scale, + VertexData outPoints, VertexData outTris, int vertexOffset) { - int numIndices = 0; - int indexPos = 0; - int pointPos = 0; - int indexEnd = geom.index.length; + int numIndices = 0; + int indexPos = 0; + int pointPos = 0; + int indexEnd = geom.index.length; - JsArrayNumber jspoints = JsArrayUtils.readOnlyJsArray(geom.points); - JsArrayInteger jsindex = JsArrayUtils.readOnlyJsArray(geom.index); + JsArrayNumber jspoints = JsArrayUtils.readOnlyJsArray(geom.points); + JsArrayInteger jsindex = JsArrayUtils.readOnlyJsArray(geom.index); - for (int idx = 0; idx < indexEnd && geom.index[idx] > 0; idx++) { - indexPos = idx; + for (int idx = 0; idx < indexEnd && geom.index[idx] > 0; idx++) { + indexPos = idx; - int numRings = 1; - int numPoints = geom.index[idx++]; + int numRings = 1; + int numPoints = geom.index[idx++]; - for (; idx < indexEnd && geom.index[idx] > 0; idx++) { - numRings++; - numPoints += geom.index[idx]; - } + for (; idx < indexEnd && geom.index[idx] > 0; idx++) { + numRings++; + numPoints += geom.index[idx]; + } - if (numPoints <= 0 && numRings == 1) { - log.debug("tessellation skip empty"); - pointPos += numPoints; - continue; - } + if (numPoints <= 0 && numRings == 1) { + log.debug("tessellation skip empty"); + pointPos += numPoints; + continue; + } - TessResult res; - try { - res = tessellate2(jspoints, pointPos, numPoints, - jsindex, indexPos, numRings); - } catch (JavaScriptException e) { - e.printStackTrace(); - return 0; - } - pointPos += numPoints; + TessResult res; + try { + res = tessellate2(jspoints, pointPos, numPoints, + jsindex, indexPos, numRings); + } catch (JavaScriptException e) { + e.printStackTrace(); + return 0; + } + pointPos += numPoints; - if (res == null) { - log.debug("tessellation failed"); - continue; - } + if (res == null) { + log.debug("tessellation failed"); + continue; + } - Int32Array io = res.getIndices(res); - int resIndices = io.length(); - numIndices += resIndices; + Int32Array io = res.getIndices(res); + int resIndices = io.length(); + numIndices += resIndices; - for (int k = 0, cnt = 0; k < resIndices; k += cnt) { - VertexData.Chunk chunk = outTris.obtainChunk(); + for (int k = 0, cnt = 0; k < resIndices; k += cnt) { + VertexData.Chunk chunk = outTris.obtainChunk(); - cnt = VertexData.SIZE - chunk.used; + cnt = VertexData.SIZE - chunk.used; - if (k + cnt > resIndices) - cnt = resIndices - k; + if (k + cnt > resIndices) + cnt = resIndices - k; - for (int i = 0; i < cnt; i++) - chunk.vertices[chunk.used + i] = - (short) (vertexOffset + io.get(k + i)); + for (int i = 0; i < cnt; i++) + chunk.vertices[chunk.used + i] = + (short) (vertexOffset + io.get(k + i)); - chunk.used += cnt; - outTris.releaseChunk(); - } + chunk.used += cnt; + outTris.releaseChunk(); + } - Float32Array po = res.getPoints(res); - int resPoints = po.length(); + Float32Array po = res.getPoints(res); + int resPoints = po.length(); - vertexOffset += (resPoints >> 1); + vertexOffset += (resPoints >> 1); - for (int k = 0, cnt = 0; k < resPoints; k += cnt) { - VertexData.Chunk chunk = outPoints.obtainChunk(); + for (int k = 0, cnt = 0; k < resPoints; k += cnt) { + VertexData.Chunk chunk = outPoints.obtainChunk(); - cnt = VertexData.SIZE - chunk.used; + cnt = VertexData.SIZE - chunk.used; - if (k + cnt > resPoints) - cnt = resPoints - k; + if (k + cnt > resPoints) + cnt = resPoints - k; - for (int i = 0; i < cnt; i++) - chunk.vertices[chunk.used + i] = - (short) (po.get(k + i) * scale); + for (int i = 0; i < cnt; i++) + chunk.vertices[chunk.used + i] = + (short) (po.get(k + i) * scale); - chunk.used += cnt; - outPoints.releaseChunk(); - } + chunk.used += cnt; + outPoints.releaseChunk(); + } - if (idx >= indexEnd || geom.index[idx] < 0) - break; - } + if (idx >= indexEnd || geom.index[idx] < 0) + break; + } - return numIndices; - } + return numIndices; + } - public static int tessellate(float[] points, int ppos, int plen, int[] index, - int ipos, int rings, int vertexOffset, VertexData outTris) { + public static int tessellate(float[] points, int ppos, int plen, int[] index, + int ipos, int rings, int vertexOffset, VertexData outTris) { - Int32Array io; - try { - io = tessellate(JsArrayUtils.readOnlyJsArray(points), ppos, plen, - JsArrayUtils.readOnlyJsArray(index), ipos, rings); - } catch (JavaScriptException e) { - e.printStackTrace(); - return 0; - } + Int32Array io; + try { + io = tessellate(JsArrayUtils.readOnlyJsArray(points), ppos, plen, + JsArrayUtils.readOnlyJsArray(index), ipos, rings); + } catch (JavaScriptException e) { + e.printStackTrace(); + return 0; + } - if (io == null) { - //log.debug("building tessellation failed"); - return 0; - } + if (io == null) { + //log.debug("building tessellation failed"); + return 0; + } - // if (vo.length() != plen) { - // // TODO handle different output points - // log.debug(" + io.length()); - // - // //for (int i = 0; i < vo.length(); i += 2) - // // log.debug(vo.get(i) + " " + vo.get(i + 1)); - // //for (int i = ppos; i < ppos + plen; i += 2) - // // log.debug( points[i]+ " " + points[i + 1]); - // - // return 0; - // } + // if (vo.length() != plen) { + // // TODO handle different output points + // log.debug(" + io.length()); + // + // //for (int i = 0; i < vo.length(); i += 2) + // // log.debug(vo.get(i) + " " + vo.get(i + 1)); + // //for (int i = ppos; i < ppos + plen; i += 2) + // // log.debug( points[i]+ " " + points[i + 1]); + // + // return 0; + // } - int numIndices = io.length(); + int numIndices = io.length(); - for (int k = 0, cnt = 0; k < numIndices; k += cnt) { - VertexData.Chunk chunk = outTris.obtainChunk(); + for (int k = 0, cnt = 0; k < numIndices; k += cnt) { + VertexData.Chunk chunk = outTris.obtainChunk(); - cnt = VertexData.SIZE - chunk.used; + cnt = VertexData.SIZE - chunk.used; - if (k + cnt > numIndices) - cnt = numIndices - k; + if (k + cnt > numIndices) + cnt = numIndices - k; - for (int i = 0; i < cnt; i++) { - int idx = (vertexOffset + io.get(k + i)); - chunk.vertices[chunk.used + i] = (short) idx; - } - chunk.used += cnt; - outTris.releaseChunk(); - } + for (int i = 0; i < cnt; i++) { + int idx = (vertexOffset + io.get(k + i)); + chunk.vertices[chunk.used + i] = (short) idx; + } + chunk.used += cnt; + outTris.releaseChunk(); + } - return numIndices; - } + return numIndices; + } - public static int tessellate(GeometryBuffer geom, GeometryBuffer out) { - return 0; - } + public static int tessellate(GeometryBuffer geom, GeometryBuffer out) { + return 0; + } - static native Int32Array tessellate(JsArrayNumber points, int pOffset, int pLength, - JsArrayInteger bounds, int bOffset, int bLength)/*-{ + static native Int32Array tessellate(JsArrayNumber points, int pOffset, int pLength, + JsArrayInteger bounds, int bOffset, int bLength)/*-{ return $wnd.tessellate(points, pOffset, pOffset + pLength, bounds, bOffset, bOffset + bLength, false); }-*/; - static native TessResult tessellate2(JsArrayNumber points, int pOffset, int pLength, - JsArrayInteger bounds, int bOffset, int bLength) - /*-{ + static native TessResult tessellate2(JsArrayNumber points, int pOffset, int pLength, + JsArrayInteger bounds, int bOffset, int bLength) + /*-{ return $wnd.tessellate(points, pOffset, pOffset + pLength, bounds, bOffset, bOffset + bLength, true); }-*/; - static final class TessResult extends JavaScriptObject { - protected TessResult() { - } + static final class TessResult extends JavaScriptObject { + protected TessResult() { + } - native Float32Array getPoints(JavaScriptObject result)/*-{ - return result.vertices; + native Float32Array getPoints(JavaScriptObject result)/*-{ + return result.vertices; }-*/; - native Int32Array getIndices(JavaScriptObject result)/*-{ + native Int32Array getIndices(JavaScriptObject result)/*-{ return result.triangles; }-*/; - } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/ThreadUtils.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/ThreadUtils.java index 56ee2076..6b6ede1d 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/ThreadUtils.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/ThreadUtils.java @@ -2,15 +2,15 @@ package org.oscim.utils; public class ThreadUtils { - public static void assertMainThread() { - } + public static void assertMainThread() { + } - public static boolean isMainThread() { - return true; - } + public static boolean isMainThread() { + return true; + } - public static void init() { + public static void init() { - } + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/async/AsyncExecutor.java b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/async/AsyncExecutor.java index cb9effaf..5de69ff8 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/async/AsyncExecutor.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/async/AsyncExecutor.java @@ -5,46 +5,45 @@ import com.badlogic.gdx.utils.Disposable; /** * GWT emulation of AsynchExecutor, will call tasks immediately :D - * + * * @author badlogic - * */ public class AsyncExecutor implements Disposable { - private final TaskQueue mainloop; + private final TaskQueue mainloop; - /** - * Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable} - * instances to run in parallel. - * - * @param maxConcurrent - */ - public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) { - this.mainloop = mainloop; - } + /** + * Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable} + * instances to run in parallel. + * + * @param maxConcurrent + */ + public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) { + this.mainloop = mainloop; + } - /** - * Submits a {@link Runnable} to be executed asynchronously. If - * maxConcurrent runnables are already running, the runnable - * will be queued. - * - * @param task the task to execute asynchronously - */ - public boolean post(Runnable task) { - if (task instanceof AsyncTask) { - ((AsyncTask) task).setTaskQueue(mainloop); - } + /** + * Submits a {@link Runnable} to be executed asynchronously. If + * maxConcurrent runnables are already running, the runnable + * will be queued. + * + * @param task the task to execute asynchronously + */ + public boolean post(Runnable task) { + if (task instanceof AsyncTask) { + ((AsyncTask) task).setTaskQueue(mainloop); + } - Gdx.app.postRunnable(task); + Gdx.app.postRunnable(task); - return true; - } + return true; + } - /** - * Waits for running {@link AsyncTask} instances to finish, - * then destroys any resources like threads. Can not be used - * after this method is called. - */ - @Override - public void dispose() { - } + /** + * Waits for running {@link AsyncTask} instances to finish, + * then destroys any resources like threads. Can not be used + * after this method is called. + */ + @Override + public void dispose() { + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/Attributes.java b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/Attributes.java index f6fc653f..ba36c62d 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/Attributes.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/Attributes.java @@ -1,27 +1,27 @@ package org.xml.sax; public abstract interface Attributes { - public abstract int getLength(); + public abstract int getLength(); - public abstract String getURI(int paramInt); + public abstract String getURI(int paramInt); - public abstract String getLocalName(int paramInt); + public abstract String getLocalName(int paramInt); - public abstract String getQName(int paramInt); + public abstract String getQName(int paramInt); - public abstract String getType(int paramInt); + public abstract String getType(int paramInt); - public abstract String getValue(int paramInt); + public abstract String getValue(int paramInt); - public abstract int getIndex(String paramString1, String paramString2); + public abstract int getIndex(String paramString1, String paramString2); - public abstract int getIndex(String paramString); + public abstract int getIndex(String paramString); - public abstract String getType(String paramString1, String paramString2); + public abstract String getType(String paramString1, String paramString2); - public abstract String getType(String paramString); + public abstract String getType(String paramString); - public abstract String getValue(String paramString1, String paramString2); + public abstract String getValue(String paramString1, String paramString2); - public abstract String getValue(String paramString); + public abstract String getValue(String paramString); } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXException.java b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXException.java index 951b588f..1af7c343 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXException.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXException.java @@ -4,17 +4,16 @@ import java.io.IOException; public class SAXException extends IOException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - public SAXException(String str) { - super(str); - } + public SAXException(String str) { + super(str); + } - public SAXException(String str, Throwable throwable) - { - super(str); - } + public SAXException(String str, Throwable throwable) { + super(str); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXParseException.java b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXParseException.java index 890139b3..f662a15d 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXParseException.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/SAXParseException.java @@ -2,18 +2,17 @@ package org.xml.sax; public class SAXParseException extends SAXException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - public SAXParseException(String str) { - super(str); - } + public SAXParseException(String str) { + super(str); + } - public SAXParseException(String str, Throwable throwable) - { - super(str); - } + public SAXParseException(String str, Throwable throwable) { + super(str); + } } diff --git a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/helpers/DefaultHandler.java b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/helpers/DefaultHandler.java index ecbaee96..8eb3b98a 100644 --- a/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/helpers/DefaultHandler.java +++ b/vtm-web/src/org/oscim/gdx/emu/org/xml/sax/helpers/DefaultHandler.java @@ -5,25 +5,25 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class DefaultHandler { - public void endDocument() { + public void endDocument() { - } + } - public void error(SAXParseException exception) { + public void error(SAXParseException exception) { - } + } - public void warning(SAXParseException exception) { + public void warning(SAXParseException exception) { - } + } - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { - } + } - public void endElement(String uri, String localName, String qName) { + public void endElement(String uri, String localName, String qName) { - } + } } diff --git a/vtm-web/src/org/oscim/tiling/source/JsonTileDataSource.java b/vtm-web/src/org/oscim/tiling/source/JsonTileDataSource.java index 8584b387..97a2a53a 100644 --- a/vtm-web/src/org/oscim/tiling/source/JsonTileDataSource.java +++ b/vtm-web/src/org/oscim/tiling/source/JsonTileDataSource.java @@ -16,10 +16,10 @@ */ package org.oscim.tiling.source; -import static org.oscim.tiling.QueryResult.FAILED; -import static org.oscim.tiling.QueryResult.SUCCESS; - -import java.io.InputStream; +import com.google.gwt.core.client.JavaScriptObject; +import com.google.gwt.jsonp.client.JsonpRequest; +import com.google.gwt.jsonp.client.JsonpRequestBuilder; +import com.google.gwt.user.client.rpc.AsyncCallback; import org.oscim.layers.tile.MapTile; import org.oscim.layers.tile.MapTile.State; @@ -30,95 +30,95 @@ import org.oscim.tiling.source.geojson.GeoJsonTileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gwt.core.client.JavaScriptObject; -import com.google.gwt.jsonp.client.JsonpRequest; -import com.google.gwt.jsonp.client.JsonpRequestBuilder; -import com.google.gwt.user.client.rpc.AsyncCallback; +import java.io.InputStream; + +import static org.oscim.tiling.QueryResult.FAILED; +import static org.oscim.tiling.QueryResult.SUCCESS; public class JsonTileDataSource implements ITileDataSource { - static final Logger log = LoggerFactory.getLogger(JsonTileDataSource.class); + static final Logger log = LoggerFactory.getLogger(JsonTileDataSource.class); - protected final GeoJsonTileDecoder mTileDecoder; - protected final UrlTileSource mTileSource; + protected final GeoJsonTileDecoder mTileDecoder; + protected final UrlTileSource mTileSource; - public JsonTileDataSource(GeoJsonTileSource tileSource) { - mTileSource = tileSource; - mTileDecoder = new GeoJsonTileDecoder(tileSource); - } + public JsonTileDataSource(GeoJsonTileSource tileSource) { + mTileSource = tileSource; + mTileDecoder = new GeoJsonTileDecoder(tileSource); + } - UrlTileSource getTileSource() { - return mTileSource; - } + UrlTileSource getTileSource() { + return mTileSource; + } - private ITileDataSink mSink; - private MapTile mTile; + private ITileDataSink mSink; + private MapTile mTile; - @Override - public void query(MapTile tile, ITileDataSink sink) { - mTile = tile; - mSink = sink; + @Override + public void query(MapTile tile, ITileDataSink sink) { + mTile = tile; + mSink = sink; - try { - doGet(mTileSource.getTileUrl(tile)); - } catch (Exception e) { - e.printStackTrace(); - sink.completed(FAILED); - } - } + try { + doGet(mTileSource.getTileUrl(tile)); + } catch (Exception e) { + e.printStackTrace(); + sink.completed(FAILED); + } + } - public void process(InputStream is) { - } + public void process(InputStream is) { + } - boolean mFinished; + boolean mFinished; - @Override - public void dispose() { - mFinished = true; - } + @Override + public void dispose() { + mFinished = true; + } - @Override - public void cancel() { - mFinished = true; - } + @Override + public void cancel() { + mFinished = true; + } - JsonpRequest mRequestHandle; + JsonpRequest mRequestHandle; - void doGet(final String url) { - JsonpRequestBuilder builder = new JsonpRequestBuilder(); - //builder.setCallbackParam("json_callback"); + void doGet(final String url) { + JsonpRequestBuilder builder = new JsonpRequestBuilder(); + //builder.setCallbackParam("json_callback"); - mRequestHandle = builder.requestObject(url, new AsyncCallback() { - public void onFailure(Throwable caught) { + mRequestHandle = builder.requestObject(url, new AsyncCallback() { + public void onFailure(Throwable caught) { - mSink.completed(FAILED); - log.debug("fail! {} {}", mRequestHandle, caught.getMessage()); - //mRequestHandle.cancel(); - } + mSink.completed(FAILED); + log.debug("fail! {} {}", mRequestHandle, caught.getMessage()); + //mRequestHandle.cancel(); + } - public void onSuccess(JavaScriptObject jso) { - if (mTile.state(State.NONE)) { - log.debug("tile cleared {}", url); - mSink.completed(FAILED); - return; - } + public void onSuccess(JavaScriptObject jso) { + if (mTile.state(State.NONE)) { + log.debug("tile cleared {}", url); + mSink.completed(FAILED); + return; + } - if (jso == null) { - log.debug("Couldn't retrieve JSON for {}", url); - mSink.completed(FAILED); - return; - } + if (jso == null) { + log.debug("Couldn't retrieve JSON for {}", url); + mSink.completed(FAILED); + return; + } - try { - if (mTileDecoder.decode(mTile, mSink, jso)) { - mSink.completed(SUCCESS); - return; - } - } catch (Exception e) { - log.debug("Couldn't retrieve JSON for {} {}" + url, e); - // FIXME need to check where it might be thrown - mSink.completed(FAILED); - } - } - }); - } + try { + if (mTileDecoder.decode(mTile, mSink, jso)) { + mSink.completed(SUCCESS); + return; + } + } catch (Exception e) { + log.debug("Couldn't retrieve JSON for {} {}" + url, e); + // FIXME need to check where it might be thrown + mSink.completed(FAILED); + } + } + }); + } } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/Feature.java b/vtm-web/src/org/oscim/tiling/source/geojson/Feature.java index 0773ce57..5b04f0f3 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/Feature.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/Feature.java @@ -21,30 +21,30 @@ import java.util.Map; public class Feature extends GeoJsonObject { - protected Feature() { + protected Feature() { - } + } - public final native Geometry getGeometry() /*-{ - return this.geometry; + public final native Geometry getGeometry() /*-{ + return this.geometry; }-*/; - public final native String getId() /*-{ - return this.id; + public final native String getId() /*-{ + return this.id; }-*/; - public final native void setId(String id) /*-{ + public final native void setId(String id) /*-{ this.id = id; }-*/; - public final Map getProperties(HashMap map) { - map.clear(); - fromJavascriptObject(map); + public final Map getProperties(HashMap map) { + map.clear(); + fromJavascriptObject(map); - return map; - } + return map; + } - public final native void fromJavascriptObject(HashMap s) /*-{ + public final native void fromJavascriptObject(HashMap s) /*-{ for(var key in this.properties) { s.@java.util.HashMap::put(Ljava/lang/Object;Ljava/lang/Object;)(key, Object(this.properties[key])); } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/FeatureCollection.java b/vtm-web/src/org/oscim/tiling/source/geojson/FeatureCollection.java index 0ef10d4e..2b901031 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/FeatureCollection.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/FeatureCollection.java @@ -16,23 +16,23 @@ */ package org.oscim.tiling.source.geojson; -import java.util.Collection; - import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; +import java.util.Collection; + public class FeatureCollection extends JavaScriptObject { - protected FeatureCollection() { + protected FeatureCollection() { - } + } - public final Collection getFeatures() { - return new JsArrayCollection(getFeaturesInternal()); - } + public final Collection getFeatures() { + return new JsArrayCollection(getFeaturesInternal()); + } - public final native JsArray getFeaturesInternal()/*-{ - return this.features; + public final native JsArray getFeaturesInternal()/*-{ + return this.features; }-*/; } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonObject.java b/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonObject.java index c8589256..3ca3fa48 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonObject.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonObject.java @@ -20,15 +20,15 @@ import com.google.gwt.core.client.JavaScriptObject; public abstract class GeoJsonObject extends JavaScriptObject { - protected GeoJsonObject() { + protected GeoJsonObject() { - } + } - public final native double[] getBbox()/*-{ - return bbox; + public final native double[] getBbox()/*-{ + return bbox; }-*/; - public final native void setBbox(double[] bbox) /*-{ - this.bbox = bbox; + public final native void setBbox(double[] bbox) /*-{ + this.bbox = bbox; }-*/; } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java b/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java index 23e6ae0a..647c1c07 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/GeoJsonTileDecoder.java @@ -16,12 +16,7 @@ */ package org.oscim.tiling.source.geojson; -import static org.oscim.core.MercatorProjection.latitudeToY; -import static org.oscim.core.MercatorProjection.longitudeToX; - -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedHashMap; +import com.google.gwt.core.client.JavaScriptObject; import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; @@ -31,109 +26,114 @@ import org.oscim.tiling.source.ITileDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gwt.core.client.JavaScriptObject; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; + +import static org.oscim.core.MercatorProjection.latitudeToY; +import static org.oscim.core.MercatorProjection.longitudeToX; public class GeoJsonTileDecoder implements ITileDecoder { - static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class); + static final Logger log = LoggerFactory.getLogger(GeoJsonTileDecoder.class); - private final MapElement mapElement; - private final GeoJsonTileSource mTileSource; + private final MapElement mapElement; + private final GeoJsonTileSource mTileSource; - private ITileDataSink mTileDataSink; + private ITileDataSink mTileDataSink; - public GeoJsonTileDecoder(GeoJsonTileSource tileSource) { - mTileSource = tileSource; - mapElement = new MapElement(); - mapElement.layer = 5; - } + public GeoJsonTileDecoder(GeoJsonTileSource tileSource) { + mTileSource = tileSource; + mapElement = new MapElement(); + mapElement.layer = 5; + } - final static LinkedHashMap mProperties = new LinkedHashMap(10); + final static LinkedHashMap mProperties = new LinkedHashMap(10); - double mTileY, mTileX, mTileScale; + double mTileY, mTileX, mTileScale; - public boolean decode(Tile tile, ITileDataSink sink, JavaScriptObject jso) { - mTileDataSink = sink; + public boolean decode(Tile tile, ITileDataSink sink, JavaScriptObject jso) { + mTileDataSink = sink; - mTileScale = 1 << tile.zoomLevel; - mTileX = tile.tileX / mTileScale; - mTileY = tile.tileY / mTileScale; - mTileScale *= Tile.SIZE; + mTileScale = 1 << tile.zoomLevel; + mTileX = tile.tileX / mTileScale; + mTileY = tile.tileY / mTileScale; + mTileScale *= Tile.SIZE; - FeatureCollection c = (FeatureCollection) jso; + FeatureCollection c = (FeatureCollection) jso; - for (Feature f : c.getFeatures()) { - mapElement.clear(); - mapElement.tags.clear(); + for (Feature f : c.getFeatures()) { + mapElement.clear(); + mapElement.tags.clear(); /* add tag information */ - mTileSource.decodeTags(mapElement, f.getProperties(mProperties)); - if (mapElement.tags.numTags == 0) - continue; + mTileSource.decodeTags(mapElement, f.getProperties(mProperties)); + if (mapElement.tags.numTags == 0) + continue; /* add geometry information */ - decodeGeometry(f.getGeometry()); + decodeGeometry(f.getGeometry()); - if (mapElement.type == GeometryType.NONE) - continue; + if (mapElement.type == GeometryType.NONE) + continue; - mTileDataSink.process(mapElement); - } + mTileDataSink.process(mapElement); + } - return true; - } + return true; + } - private void decodeGeometry(Geometry geometry) { - String type = geometry.type(); + private void decodeGeometry(Geometry geometry) { + String type = geometry.type(); - if ("Polygon".equals(type)) { - Polygon p = (Polygon) geometry.getCoordinates(); - decodePolygon(p); - } else if ("MultiPolygon".equals(type)) { - MultiPolygon mp = (MultiPolygon) geometry.getCoordinates(); - for (int k = 0, l = mp.getNumGeometries(); k < l; k++) - decodePolygon(mp.getGeometryN(k)); + if ("Polygon".equals(type)) { + Polygon p = (Polygon) geometry.getCoordinates(); + decodePolygon(p); + } else if ("MultiPolygon".equals(type)) { + MultiPolygon mp = (MultiPolygon) geometry.getCoordinates(); + for (int k = 0, l = mp.getNumGeometries(); k < l; k++) + decodePolygon(mp.getGeometryN(k)); - } else if ("LineString".equals(type)) { - LineString ls = (LineString) geometry.getCoordinates(); - decodeLineString(ls); + } else if ("LineString".equals(type)) { + LineString ls = (LineString) geometry.getCoordinates(); + decodeLineString(ls); - } else if ("MultiLineString".equals(type)) { - MultiLineString ml = (MultiLineString) geometry.getCoordinates(); - for (int k = 0, n = ml.getNumGeometries(); k < n; k++) - decodeLineString(ml.getGeometryN(k)); - } - } + } else if ("MultiLineString".equals(type)) { + MultiLineString ml = (MultiLineString) geometry.getCoordinates(); + for (int k = 0, n = ml.getNumGeometries(); k < n; k++) + decodeLineString(ml.getGeometryN(k)); + } + } - private void decodeLineString(LineString l) { - mapElement.startLine(); - for (int j = 0, m = l.length(); j < m; j++) { - decodePoint(l.get(j)); - } - } + private void decodeLineString(LineString l) { + mapElement.startLine(); + for (int j = 0, m = l.length(); j < m; j++) { + decodePoint(l.get(j)); + } + } - private void decodePolygon(Polygon p) { - for (int i = 0, n = p.getNumRings(); i < n; i++) { - if (i > 0) - mapElement.startHole(); - else - mapElement.startPolygon(); + private void decodePolygon(Polygon p) { + for (int i = 0, n = p.getNumRings(); i < n; i++) { + if (i > 0) + mapElement.startHole(); + else + mapElement.startPolygon(); - LineString ls = p.getRing(i); - for (int j = 0, m = ls.length() - 1; j < m; j++) - decodePoint(ls.get(j)); - } - } + LineString ls = p.getRing(i); + for (int j = 0, m = ls.length() - 1; j < m; j++) + decodePoint(ls.get(j)); + } + } - private void decodePoint(LngLat point) { + private void decodePoint(LngLat point) { - float x = (float) ((longitudeToX(point.getLongitude()) - mTileX) * mTileScale); - float y = (float) ((latitudeToY(point.getLatitude()) - mTileY) * mTileScale); + float x = (float) ((longitudeToX(point.getLongitude()) - mTileX) * mTileScale); + float y = (float) ((latitudeToY(point.getLatitude()) - mTileY) * mTileScale); - mapElement.addPoint(x, y); - } + mapElement.addPoint(x, y); + } - @Override - public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException { - return false; - } + @Override + public boolean decode(Tile tile, ITileDataSink sink, InputStream is) throws IOException { + return false; + } } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/Geometry.java b/vtm-web/src/org/oscim/tiling/source/geojson/Geometry.java index c9a51d78..5dea6a1b 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/Geometry.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/Geometry.java @@ -21,15 +21,15 @@ import com.google.gwt.core.client.JsArray; public abstract class Geometry extends JsArray { - protected Geometry() { + protected Geometry() { - } + } - public final native String type()/*-{ - return this.type + public final native String type()/*-{ + return this.type }-*/; - public final native JsArray getCoordinates() /*-{ - return this.coordinates; + public final native JsArray getCoordinates() /*-{ + return this.coordinates; }-*/; } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/JsArrayCollection.java b/vtm-web/src/org/oscim/tiling/source/geojson/JsArrayCollection.java index ed45484c..ae9284ca 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/JsArrayCollection.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/JsArrayCollection.java @@ -1,100 +1,101 @@ package org.oscim.tiling.source.geojson; +import com.google.gwt.core.client.JavaScriptObject; + import java.util.AbstractCollection; import java.util.Iterator; -import com.google.gwt.core.client.JavaScriptObject; - /** * a Java Friendly way of working with Js Arrays using the Java.util.Collection * API * https://groups.google.com/forum/#!topic/google-web-toolkit/_8X9WPL6qwM - * - * @author sg - * + * * @param + * @author sg */ public class JsArrayCollection extends AbstractCollection { - private JsArr _data; + private JsArr _data; - /** - * creates an empty array - */ - public JsArrayCollection() { - _data = JsArr.create().cast(); - } + /** + * creates an empty array + */ + public JsArrayCollection() { + _data = JsArr.create().cast(); + } - /** - * creates JsArrayCollection wrapping an existing js array - */ - public JsArrayCollection(JavaScriptObject data) { - this._data = data.cast(); - } + /** + * creates JsArrayCollection wrapping an existing js array + */ + public JsArrayCollection(JavaScriptObject data) { + this._data = data.cast(); + } - public static JsArrayCollection create(JavaScriptObject data) { - return new JsArrayCollection(data); - } + public static JsArrayCollection create(JavaScriptObject data) { + return new JsArrayCollection(data); + } - @Override - public Iterator iterator() { - return new JsArrayIterator(this); - } + @Override + public Iterator iterator() { + return new JsArrayIterator(this); + } - @Override - public int size() { - return _data.size(); - } + @Override + public int size() { + return _data.size(); + } - public static class JsArrayIterator implements Iterator { + public static class JsArrayIterator implements Iterator { - private JsArrayCollection arr; - int currentIndex; + private JsArrayCollection arr; + int currentIndex; - public JsArrayIterator(JsArrayCollection arr) { - this.arr = arr; - currentIndex = 0; - } + public JsArrayIterator(JsArrayCollection arr) { + this.arr = arr; + currentIndex = 0; + } - @Override - public boolean hasNext() { - // System.out.println(currentIndex+" - "+arr.size()); - return currentIndex < arr.size(); - } + @Override + public boolean hasNext() { + // System.out.println(currentIndex+" - "+arr.size()); + return currentIndex < arr.size(); + } - @Override - public T next() { - currentIndex++; - return arr._data.get(currentIndex - 1); - } + @Override + public T next() { + currentIndex++; + return arr._data.get(currentIndex - 1); + } - @Override - public void remove() { - arr._data.slice(currentIndex - 1, currentIndex); - } + @Override + public void remove() { + arr._data.slice(currentIndex - 1, currentIndex); + } - } + } - /** untyped array */ - private static class JsArr extends JavaScriptObject { - protected JsArr() { - } + /** + * untyped array + */ + private static class JsArr extends JavaScriptObject { + protected JsArr() { + } - public native final JsArr slice(int start, int end)/*-{ - return this.slice(start, end); + public native final JsArr slice(int start, int end)/*-{ + return this.slice(start, end); }-*/; - public static final native JsArr create() /*-{ - return []; + public static final native JsArr create() /*-{ + return []; }-*/; - public final native int size() /*-{ + public final native int size() /*-{ return this.length; }-*/; - public final native T get(int i) /*-{ + public final native T get(int i) /*-{ return this[i]; }-*/; - } + } } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/LineString.java b/vtm-web/src/org/oscim/tiling/source/geojson/LineString.java index 490e1cf0..0eb9bf53 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/LineString.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/LineString.java @@ -18,6 +18,6 @@ package org.oscim.tiling.source.geojson; public class LineString extends Geometry { - protected LineString() { - } + protected LineString() { + } } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/LngLat.java b/vtm-web/src/org/oscim/tiling/source/geojson/LngLat.java index 0fdf879f..b2170a22 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/LngLat.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/LngLat.java @@ -4,15 +4,15 @@ import com.google.gwt.core.client.JavaScriptObject; public class LngLat extends JavaScriptObject { - protected LngLat() { + protected LngLat() { - } + } - public final native double getLongitude() /*-{ - return this[0]; + public final native double getLongitude() /*-{ + return this[0]; }-*/; - public final native double getLatitude() /*-{ - return this[1]; + public final native double getLatitude() /*-{ + return this[1]; }-*/; } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/MultiLineString.java b/vtm-web/src/org/oscim/tiling/source/geojson/MultiLineString.java index 422a3b44..0a4ac9c0 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/MultiLineString.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/MultiLineString.java @@ -18,15 +18,15 @@ package org.oscim.tiling.source.geojson; public class MultiLineString extends Geometry { - protected MultiLineString() { - } + protected MultiLineString() { + } - public final native LineString getGeometryN(int i) /*-{ - return this[i]; + public final native LineString getGeometryN(int i) /*-{ + return this[i]; }-*/; - public final native int getNumGeometries() /*-{ - return this.length; + public final native int getNumGeometries() /*-{ + return this.length; }-*/; } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/MultiPolygon.java b/vtm-web/src/org/oscim/tiling/source/geojson/MultiPolygon.java index c52b89a5..f1ecf681 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/MultiPolygon.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/MultiPolygon.java @@ -18,15 +18,15 @@ package org.oscim.tiling.source.geojson; public class MultiPolygon extends Geometry { - protected MultiPolygon() { - } + protected MultiPolygon() { + } - public final native Polygon getGeometryN(int i) /*-{ - return this[i]; + public final native Polygon getGeometryN(int i) /*-{ + return this[i]; }-*/; - public final native int getNumGeometries() /*-{ - return this.length; + public final native int getNumGeometries() /*-{ + return this.length; }-*/; } diff --git a/vtm-web/src/org/oscim/tiling/source/geojson/Polygon.java b/vtm-web/src/org/oscim/tiling/source/geojson/Polygon.java index 3ef0bc0b..d462d0a8 100644 --- a/vtm-web/src/org/oscim/tiling/source/geojson/Polygon.java +++ b/vtm-web/src/org/oscim/tiling/source/geojson/Polygon.java @@ -18,18 +18,18 @@ package org.oscim.tiling.source.geojson; public class Polygon extends Geometry { - protected Polygon() { - } + protected Polygon() { + } - public final native LineString getExteriorRing()/*-{ - return this[0]; + public final native LineString getExteriorRing()/*-{ + return this[0]; }-*/; - public final native LineString getRing(int i) /*-{ - return this[i]; + public final native LineString getRing(int i) /*-{ + return this[i]; }-*/; - public final native int getNumRings() /*-{ + public final native int getNumRings() /*-{ return this.length; }-*/; diff --git a/vtm/src/org/oscim/backend/AssetAdapter.java b/vtm/src/org/oscim/backend/AssetAdapter.java index 8235568c..a4b35739 100644 --- a/vtm/src/org/oscim/backend/AssetAdapter.java +++ b/vtm/src/org/oscim/backend/AssetAdapter.java @@ -26,40 +26,42 @@ import java.io.InputStreamReader; */ public abstract class AssetAdapter { - /** The instance provided by backend */ - static AssetAdapter g; + /** + * The instance provided by backend + */ + static AssetAdapter g; - /** - * Open file from asset path as stream. - */ - protected abstract InputStream openFileAsStream(String file); + /** + * Open file from asset path as stream. + */ + protected abstract InputStream openFileAsStream(String file); - public static InputStream readFileAsStream(String file) { - return g.openFileAsStream(file); - } + public static InputStream readFileAsStream(String file) { + return g.openFileAsStream(file); + } - public static String readTextFile(String file) { - StringBuilder sb = new StringBuilder(); + public static String readTextFile(String file) { + StringBuilder sb = new StringBuilder(); - InputStream is = g.openFileAsStream(file); - if (is == null) - return null; + InputStream is = g.openFileAsStream(file); + if (is == null) + return null; - BufferedReader r = new BufferedReader(new InputStreamReader(is)); - String line; - try { - while ((line = r.readLine()) != null) { - sb.append(line).append('\n'); - } - } catch (IOException e) { - e.printStackTrace(); - } + BufferedReader r = new BufferedReader(new InputStreamReader(is)); + String line; + try { + while ((line = r.readLine()) != null) { + sb.append(line).append('\n'); + } + } catch (IOException e) { + e.printStackTrace(); + } - return sb.toString(); + return sb.toString(); - } + } - public static void init(AssetAdapter adapter) { - g = adapter; - } + public static void init(AssetAdapter adapter) { + g = adapter; + } } diff --git a/vtm/src/org/oscim/backend/CanvasAdapter.java b/vtm/src/org/oscim/backend/CanvasAdapter.java index 411b962e..09948606 100644 --- a/vtm/src/org/oscim/backend/CanvasAdapter.java +++ b/vtm/src/org/oscim/backend/CanvasAdapter.java @@ -16,105 +16,111 @@ */ package org.oscim.backend; -import java.io.IOException; -import java.io.InputStream; - import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Canvas; import org.oscim.backend.canvas.Paint; +import java.io.IOException; +import java.io.InputStream; + /** * The Class CanvasAdapter. */ public abstract class CanvasAdapter { - /** The instance provided by backend */ - static CanvasAdapter g; + /** + * The instance provided by backend + */ + static CanvasAdapter g; - /** The dpi. */ - public static float dpi = 240; + /** + * The dpi. + */ + public static float dpi = 240; - /** The text scale. */ - public static float textScale = 1; + /** + * The text scale. + */ + public static float textScale = 1; - /** - * Create a Canvas. - * - * @return the canvas - */ - protected abstract Canvas newCanvasImpl(); + /** + * Create a Canvas. + * + * @return the canvas + */ + protected abstract Canvas newCanvasImpl(); - public static Canvas newCanvas() { - return g.newCanvasImpl(); - } + public static Canvas newCanvas() { + return g.newCanvasImpl(); + } - /** - * Create Paint. - * - * @return the paint - */ - protected abstract Paint newPaintImpl(); + /** + * Create Paint. + * + * @return the paint + */ + protected abstract Paint newPaintImpl(); - public static Paint newPaint() { - return g.newPaintImpl(); - } + public static Paint newPaint() { + return g.newPaintImpl(); + } - /** - * Create {@link Bitmap} with given dimensions. - * - * @param width the width - * @param height the height - * @param format the format - * @return the bitmap - */ - protected abstract Bitmap newBitmapImpl(int width, int height, int format); + /** + * Create {@link Bitmap} with given dimensions. + * + * @param width the width + * @param height the height + * @param format the format + * @return the bitmap + */ + protected abstract Bitmap newBitmapImpl(int width, int height, int format); - public static Bitmap newBitmap(int width, int height, int format) { - return g.newBitmapImpl(width, height, format); - } + public static Bitmap newBitmap(int width, int height, int format) { + return g.newBitmapImpl(width, height, format); + } - /** - * Create {@link Bitmap} from InputStream. - * - * @param inputStream the input stream - * @return the bitmap - */ - protected abstract Bitmap decodeBitmapImpl(InputStream inputStream); + /** + * Create {@link Bitmap} from InputStream. + * + * @param inputStream the input stream + * @return the bitmap + */ + protected abstract Bitmap decodeBitmapImpl(InputStream inputStream); - public static Bitmap decodeBitmap(InputStream inputStream) { - return g.decodeBitmapImpl(inputStream); - } + public static Bitmap decodeBitmap(InputStream inputStream) { + return g.decodeBitmapImpl(inputStream); + } - /** - * Create {@link Bitmap} from bundled assets. - * - * @param fileName the file name - * @return the bitmap - */ - protected abstract Bitmap loadBitmapAssetImpl(String fileName); + /** + * Create {@link Bitmap} from bundled assets. + * + * @param fileName the file name + * @return the bitmap + */ + protected abstract Bitmap loadBitmapAssetImpl(String fileName); - public static Bitmap getBitmapAsset(String fileName) { - return g.loadBitmapAssetImpl(fileName); - } + public static Bitmap getBitmapAsset(String fileName) { + return g.loadBitmapAssetImpl(fileName); + } - protected static Bitmap createBitmap(String src) throws IOException { - if (src == null || src.length() == 0) { - // no image source defined - return null; - } + protected static Bitmap createBitmap(String src) throws IOException { + if (src == null || src.length() == 0) { + // no image source defined + return null; + } - InputStream inputStream = AssetAdapter.g.openFileAsStream(src); - if (inputStream == null) { - //log.error("invalid bitmap source: " + src); - return null; - } + InputStream inputStream = AssetAdapter.g.openFileAsStream(src); + if (inputStream == null) { + //log.error("invalid bitmap source: " + src); + return null; + } - Bitmap bitmap = decodeBitmap(inputStream); - inputStream.close(); - return bitmap; - } + Bitmap bitmap = decodeBitmap(inputStream); + inputStream.close(); + return bitmap; + } - protected static void init(CanvasAdapter adapter) { - g = adapter; - } + protected static void init(CanvasAdapter adapter) { + g = adapter; + } } diff --git a/vtm/src/org/oscim/backend/GL.java b/vtm/src/org/oscim/backend/GL.java index 8d1dcef5..307f3ec9 100644 --- a/vtm/src/org/oscim/backend/GL.java +++ b/vtm/src/org/oscim/backend/GL.java @@ -16,13 +16,13 @@ */ /******************************************************************************* * Copyright 2011 See libgdx AUTHORS file. - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,635 +38,635 @@ import java.nio.IntBuffer; /** * Interface wrapping all the methods of OpenGL ES 2.0 - * + * * @author mzechner */ public interface GL { - public static final int ES_VERSION_2_0 = 1; - public static final int DEPTH_BUFFER_BIT = 0x00000100; - public static final int STENCIL_BUFFER_BIT = 0x00000400; - public static final int COLOR_BUFFER_BIT = 0x00004000; - public static final int FALSE = 0; - public static final int TRUE = 1; - public static final int POINTS = 0x0000; - public static final int LINES = 0x0001; - public static final int LINE_LOOP = 0x0002; - public static final int LINE_STRIP = 0x0003; - public static final int TRIANGLES = 0x0004; - public static final int TRIANGLE_STRIP = 0x0005; - public static final int TRIANGLE_FAN = 0x0006; - public static final int ZERO = 0; - public static final int ONE = 1; - public static final int SRC_COLOR = 0x0300; - public static final int ONE_MINUS_SRC_COLOR = 0x0301; - public static final int SRC_ALPHA = 0x0302; - public static final int ONE_MINUS_SRC_ALPHA = 0x0303; - public static final int DST_ALPHA = 0x0304; - public static final int ONE_MINUS_DST_ALPHA = 0x0305; - public static final int DST_COLOR = 0x0306; - public static final int ONE_MINUS_DST_COLOR = 0x0307; - public static final int SRC_ALPHA_SATURATE = 0x0308; - public static final int FUNC_ADD = 0x8006; - public static final int BLEND_EQUATION = 0x8009; - public static final int BLEND_EQUATION_RGB = 0x8009; - public static final int BLEND_EQUATION_ALPHA = 0x883D; - public static final int FUNC_SUBTRACT = 0x800A; - public static final int FUNC_REVERSE_SUBTRACT = 0x800B; - public static final int BLEND_DST_RGB = 0x80C8; - public static final int BLEND_SRC_RGB = 0x80C9; - public static final int BLEND_DST_ALPHA = 0x80CA; - public static final int BLEND_SRC_ALPHA = 0x80CB; - public static final int CONSTANT_COLOR = 0x8001; - public static final int ONE_MINUS_CONSTANT_COLOR = 0x8002; - public static final int CONSTANT_ALPHA = 0x8003; - public static final int ONE_MINUS_CONSTANT_ALPHA = 0x8004; - public static final int BLEND_COLOR = 0x8005; - public static final int ARRAY_BUFFER = 0x8892; - public static final int ELEMENT_ARRAY_BUFFER = 0x8893; - public static final int ARRAY_BUFFER_BINDING = 0x8894; - public static final int ELEMENT_ARRAY_BUFFER_BINDING = 0x8895; - public static final int STREAM_DRAW = 0x88E0; - public static final int STATIC_DRAW = 0x88E4; - public static final int DYNAMIC_DRAW = 0x88E8; - public static final int BUFFER_SIZE = 0x8764; - public static final int BUFFER_USAGE = 0x8765; - public static final int CURRENT_VERTEX_ATTRIB = 0x8626; - public static final int FRONT = 0x0404; - public static final int BACK = 0x0405; - public static final int FRONT_AND_BACK = 0x0408; - public static final int TEXTURE_2D = 0x0DE1; - public static final int CULL_FACE = 0x0B44; - public static final int BLEND = 0x0BE2; - public static final int DITHER = 0x0BD0; - public static final int STENCIL_TEST = 0x0B90; - public static final int DEPTH_TEST = 0x0B71; - public static final int SCISSOR_TEST = 0x0C11; - public static final int POLYGON_OFFSET_FILL = 0x8037; - public static final int SAMPLE_ALPHA_TO_COVERAGE = 0x809E; - public static final int SAMPLE_COVERAGE = 0x80A0; - //public static final int NO_ERROR = 0; - public static final int INVALID_ENUM = 0x0500; - public static final int INVALID_VALUE = 0x0501; - public static final int INVALID_OPERATION = 0x0502; - public static final int OUT_OF_MEMORY = 0x0505; - public static final int CW = 0x0900; - public static final int CCW = 0x0901; - public static final int LINE_WIDTH = 0x0B21; - public static final int ALIASED_POINT_SIZE_RANGE = 0x846D; - public static final int ALIASED_LINE_WIDTH_RANGE = 0x846E; - public static final int CULL_FACE_MODE = 0x0B45; - public static final int FRONT_FACE = 0x0B46; - public static final int DEPTH_RANGE = 0x0B70; - public static final int DEPTH_WRITEMASK = 0x0B72; - public static final int DEPTH_CLEAR_VALUE = 0x0B73; - public static final int DEPTH_FUNC = 0x0B74; - public static final int STENCIL_CLEAR_VALUE = 0x0B91; - public static final int STENCIL_FUNC = 0x0B92; - public static final int STENCIL_FAIL = 0x0B94; - public static final int STENCIL_PASS_DEPTH_FAIL = 0x0B95; - public static final int STENCIL_PASS_DEPTH_PASS = 0x0B96; - public static final int STENCIL_REF = 0x0B97; - public static final int STENCIL_VALUE_MASK = 0x0B93; - public static final int STENCIL_WRITEMASK = 0x0B98; - public static final int STENCIL_BACK_FUNC = 0x8800; - public static final int STENCIL_BACK_FAIL = 0x8801; - public static final int STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802; - public static final int STENCIL_BACK_PASS_DEPTH_PASS = 0x8803; - public static final int STENCIL_BACK_REF = 0x8CA3; - public static final int STENCIL_BACK_VALUE_MASK = 0x8CA4; - public static final int STENCIL_BACK_WRITEMASK = 0x8CA5; - public static final int VIEWPORT = 0x0BA2; - public static final int SCISSOR_BOX = 0x0C10; - public static final int COLOR_CLEAR_VALUE = 0x0C22; - public static final int COLOR_WRITEMASK = 0x0C23; - public static final int UNPACK_ALIGNMENT = 0x0CF5; - public static final int PACK_ALIGNMENT = 0x0D05; - public static final int MAX_TEXTURE_SIZE = 0x0D33; - public static final int MAX_TEXTURE_UNITS = 0x84E2; - public static final int MAX_VIEWPORT_DIMS = 0x0D3A; - public static final int SUBPIXEL_BITS = 0x0D50; - public static final int RED_BITS = 0x0D52; - public static final int GREEN_BITS = 0x0D53; - public static final int BLUE_BITS = 0x0D54; - public static final int ALPHA_BITS = 0x0D55; - public static final int DEPTH_BITS = 0x0D56; - public static final int STENCIL_BITS = 0x0D57; - public static final int POLYGON_OFFSET_UNITS = 0x2A00; - public static final int POLYGON_OFFSET_FACTOR = 0x8038; - public static final int TEXTURE_BINDING_2D = 0x8069; - public static final int SAMPLE_BUFFERS = 0x80A8; - public static final int SAMPLES = 0x80A9; - public static final int SAMPLE_COVERAGE_VALUE = 0x80AA; - public static final int SAMPLE_COVERAGE_INVERT = 0x80AB; - public static final int NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2; - public static final int COMPRESSED_TEXTURE_FORMATS = 0x86A3; - public static final int DONT_CARE = 0x1100; - public static final int FASTEST = 0x1101; - public static final int NICEST = 0x1102; - public static final int GENERATE_MIPMAP_HINT = 0x8192; - public static final int BYTE = 0x1400; - public static final int UNSIGNED_BYTE = 0x1401; - public static final int SHORT = 0x1402; - public static final int UNSIGNED_SHORT = 0x1403; - public static final int INT = 0x1404; - public static final int UNSIGNED_INT = 0x1405; - public static final int FLOAT = 0x1406; - public static final int FIXED = 0x140C; - public static final int DEPTH_COMPONENT = 0x1902; - public static final int ALPHA = 0x1906; - public static final int RGB = 0x1907; - public static final int RGBA = 0x1908; - public static final int LUMINANCE = 0x1909; - public static final int LUMINANCE_ALPHA = 0x190A; - public static final int UNSIGNED_SHORT_4_4_4_4 = 0x8033; - public static final int UNSIGNED_SHORT_5_5_5_1 = 0x8034; - public static final int UNSIGNED_SHORT_5_6_5 = 0x8363; - public static final int FRAGMENT_SHADER = 0x8B30; - public static final int VERTEX_SHADER = 0x8B31; - public static final int MAX_VERTEX_ATTRIBS = 0x8869; - public static final int MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; - public static final int MAX_VARYING_VECTORS = 0x8DFC; - public static final int MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D; - public static final int MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; - public static final int MAX_TEXTURE_IMAGE_UNITS = 0x8872; - public static final int MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD; - public static final int SHADER_TYPE = 0x8B4F; - public static final int DELETE_STATUS = 0x8B80; - public static final int LINK_STATUS = 0x8B82; - public static final int VALIDATE_STATUS = 0x8B83; - public static final int ATTACHED_SHADERS = 0x8B85; - public static final int ACTIVE_UNIFORMS = 0x8B86; - public static final int ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87; - public static final int ACTIVE_ATTRIBUTES = 0x8B89; - public static final int ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A; - public static final int SHADING_LANGUAGE_VERSION = 0x8B8C; - public static final int CURRENT_PROGRAM = 0x8B8D; - public static final int NEVER = 0x0200; - public static final int LESS = 0x0201; - public static final int EQUAL = 0x0202; - public static final int LEQUAL = 0x0203; - public static final int GREATER = 0x0204; - public static final int NOTEQUAL = 0x0205; - public static final int GEQUAL = 0x0206; - public static final int ALWAYS = 0x0207; - public static final int KEEP = 0x1E00; - public static final int REPLACE = 0x1E01; - public static final int INCR = 0x1E02; - public static final int DECR = 0x1E03; - public static final int INVERT = 0x150A; - public static final int INCR_WRAP = 0x8507; - public static final int DECR_WRAP = 0x8508; - public static final int VENDOR = 0x1F00; - public static final int RENDERER = 0x1F01; - public static final int VERSION = 0x1F02; - public static final int EXTENSIONS = 0x1F03; - public static final int NEAREST = 0x2600; - public static final int LINEAR = 0x2601; - public static final int NEAREST_MIPMAP_NEAREST = 0x2700; - public static final int LINEAR_MIPMAP_NEAREST = 0x2701; - public static final int NEAREST_MIPMAP_LINEAR = 0x2702; - public static final int LINEAR_MIPMAP_LINEAR = 0x2703; - public static final int TEXTURE_MAG_FILTER = 0x2800; - public static final int TEXTURE_MIN_FILTER = 0x2801; - public static final int TEXTURE_WRAP_S = 0x2802; - public static final int TEXTURE_WRAP_T = 0x2803; - public static final int TEXTURE = 0x1702; - public static final int TEXTURE_CUBE_MAP = 0x8513; - public static final int TEXTURE_BINDING_CUBE_MAP = 0x8514; - public static final int TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515; - public static final int TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516; - public static final int TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517; - public static final int TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518; - public static final int TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519; - public static final int TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A; - public static final int MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C; - public static final int TEXTURE0 = 0x84C0; - public static final int TEXTURE1 = 0x84C1; - public static final int TEXTURE2 = 0x84C2; - public static final int TEXTURE3 = 0x84C3; - public static final int TEXTURE4 = 0x84C4; - public static final int TEXTURE5 = 0x84C5; - public static final int TEXTURE6 = 0x84C6; - public static final int TEXTURE7 = 0x84C7; - public static final int TEXTURE8 = 0x84C8; - public static final int TEXTURE9 = 0x84C9; - public static final int TEXTURE10 = 0x84CA; - public static final int TEXTURE11 = 0x84CB; - public static final int TEXTURE12 = 0x84CC; - public static final int TEXTURE13 = 0x84CD; - public static final int TEXTURE14 = 0x84CE; - public static final int TEXTURE15 = 0x84CF; - public static final int TEXTURE16 = 0x84D0; - public static final int TEXTURE17 = 0x84D1; - public static final int TEXTURE18 = 0x84D2; - public static final int TEXTURE19 = 0x84D3; - public static final int TEXTURE20 = 0x84D4; - public static final int TEXTURE21 = 0x84D5; - public static final int TEXTURE22 = 0x84D6; - public static final int TEXTURE23 = 0x84D7; - public static final int TEXTURE24 = 0x84D8; - public static final int TEXTURE25 = 0x84D9; - public static final int TEXTURE26 = 0x84DA; - public static final int TEXTURE27 = 0x84DB; - public static final int TEXTURE28 = 0x84DC; - public static final int TEXTURE29 = 0x84DD; - public static final int TEXTURE30 = 0x84DE; - public static final int TEXTURE31 = 0x84DF; - public static final int ACTIVE_TEXTURE = 0x84E0; - public static final int REPEAT = 0x2901; - public static final int CLAMP_TO_EDGE = 0x812F; - public static final int MIRRORED_REPEAT = 0x8370; - public static final int FLOAT_VEC2 = 0x8B50; - public static final int FLOAT_VEC3 = 0x8B51; - public static final int FLOAT_VEC4 = 0x8B52; - public static final int INT_VEC2 = 0x8B53; - public static final int INT_VEC3 = 0x8B54; - public static final int INT_VEC4 = 0x8B55; - public static final int BOOL = 0x8B56; - public static final int BOOL_VEC2 = 0x8B57; - public static final int BOOL_VEC3 = 0x8B58; - public static final int BOOL_VEC4 = 0x8B59; - public static final int FLOAT_MAT2 = 0x8B5A; - public static final int FLOAT_MAT3 = 0x8B5B; - public static final int FLOAT_MAT4 = 0x8B5C; - public static final int SAMPLER_2D = 0x8B5E; - public static final int SAMPLER_CUBE = 0x8B60; - public static final int VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622; - public static final int VERTEX_ATTRIB_ARRAY_SIZE = 0x8623; - public static final int VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624; - public static final int VERTEX_ATTRIB_ARRAY_TYPE = 0x8625; - public static final int VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A; - public static final int VERTEX_ATTRIB_ARRAY_POINTER = 0x8645; - public static final int VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F; - public static final int IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A; - public static final int IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B; - public static final int COMPILE_STATUS = 0x8B81; - public static final int INFO_LOG_LENGTH = 0x8B84; - public static final int SHADER_SOURCE_LENGTH = 0x8B88; - public static final int SHADER_COMPILER = 0x8DFA; - public static final int SHADER_BINARY_FORMATS = 0x8DF8; - public static final int NUM_SHADER_BINARY_FORMATS = 0x8DF9; - public static final int LOW_FLOAT = 0x8DF0; - public static final int MEDIUM_FLOAT = 0x8DF1; - public static final int HIGH_FLOAT = 0x8DF2; - public static final int LOW_INT = 0x8DF3; - public static final int MEDIUM_INT = 0x8DF4; - public static final int HIGH_INT = 0x8DF5; - public static final int FRAMEBUFFER = 0x8D40; - public static final int RENDERBUFFER = 0x8D41; - public static final int RGBA4 = 0x8056; - public static final int RGB5_A1 = 0x8057; - public static final int RGB565 = 0x8D62; - public static final int DEPTH_COMPONENT16 = 0x81A5; - public static final int STENCIL_INDEX = 0x1901; - public static final int STENCIL_INDEX8 = 0x8D48; - public static final int RENDERBUFFER_WIDTH = 0x8D42; - public static final int RENDERBUFFER_HEIGHT = 0x8D43; - public static final int RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; - public static final int RENDERBUFFER_RED_SIZE = 0x8D50; - public static final int RENDERBUFFER_GREEN_SIZE = 0x8D51; - public static final int RENDERBUFFER_BLUE_SIZE = 0x8D52; - public static final int RENDERBUFFER_ALPHA_SIZE = 0x8D53; - public static final int RENDERBUFFER_DEPTH_SIZE = 0x8D54; - public static final int RENDERBUFFER_STENCIL_SIZE = 0x8D55; - public static final int FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; - public static final int FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; - public static final int FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; - public static final int FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; - public static final int COLOR_ATTACHMENT0 = 0x8CE0; - public static final int DEPTH_ATTACHMENT = 0x8D00; - public static final int STENCIL_ATTACHMENT = 0x8D20; - public static final int NONE = 0; - public static final int FRAMEBUFFER_COMPLETE = 0x8CD5; - public static final int FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; - public static final int FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; - public static final int FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9; - public static final int FRAMEBUFFER_UNSUPPORTED = 0x8CDD; - public static final int FRAMEBUFFER_BINDING = 0x8CA6; - public static final int RENDERBUFFER_BINDING = 0x8CA7; - public static final int MAX_RENDERBUFFER_SIZE = 0x84E8; - public static final int INVALID_FRAMEBUFFER_OPERATION = 0x0506; - public static final int VERTEX_PROGRAM_POINT_SIZE = 0x8642; - - // Extensions - public static final int COVERAGE_BUFFER_BIT_NV = 0x8000; - - public void attachShader(int program, int shader); - - public void bindAttribLocation(int program, int index, String name); + public static final int ES_VERSION_2_0 = 1; + public static final int DEPTH_BUFFER_BIT = 0x00000100; + public static final int STENCIL_BUFFER_BIT = 0x00000400; + public static final int COLOR_BUFFER_BIT = 0x00004000; + public static final int FALSE = 0; + public static final int TRUE = 1; + public static final int POINTS = 0x0000; + public static final int LINES = 0x0001; + public static final int LINE_LOOP = 0x0002; + public static final int LINE_STRIP = 0x0003; + public static final int TRIANGLES = 0x0004; + public static final int TRIANGLE_STRIP = 0x0005; + public static final int TRIANGLE_FAN = 0x0006; + public static final int ZERO = 0; + public static final int ONE = 1; + public static final int SRC_COLOR = 0x0300; + public static final int ONE_MINUS_SRC_COLOR = 0x0301; + public static final int SRC_ALPHA = 0x0302; + public static final int ONE_MINUS_SRC_ALPHA = 0x0303; + public static final int DST_ALPHA = 0x0304; + public static final int ONE_MINUS_DST_ALPHA = 0x0305; + public static final int DST_COLOR = 0x0306; + public static final int ONE_MINUS_DST_COLOR = 0x0307; + public static final int SRC_ALPHA_SATURATE = 0x0308; + public static final int FUNC_ADD = 0x8006; + public static final int BLEND_EQUATION = 0x8009; + public static final int BLEND_EQUATION_RGB = 0x8009; + public static final int BLEND_EQUATION_ALPHA = 0x883D; + public static final int FUNC_SUBTRACT = 0x800A; + public static final int FUNC_REVERSE_SUBTRACT = 0x800B; + public static final int BLEND_DST_RGB = 0x80C8; + public static final int BLEND_SRC_RGB = 0x80C9; + public static final int BLEND_DST_ALPHA = 0x80CA; + public static final int BLEND_SRC_ALPHA = 0x80CB; + public static final int CONSTANT_COLOR = 0x8001; + public static final int ONE_MINUS_CONSTANT_COLOR = 0x8002; + public static final int CONSTANT_ALPHA = 0x8003; + public static final int ONE_MINUS_CONSTANT_ALPHA = 0x8004; + public static final int BLEND_COLOR = 0x8005; + public static final int ARRAY_BUFFER = 0x8892; + public static final int ELEMENT_ARRAY_BUFFER = 0x8893; + public static final int ARRAY_BUFFER_BINDING = 0x8894; + public static final int ELEMENT_ARRAY_BUFFER_BINDING = 0x8895; + public static final int STREAM_DRAW = 0x88E0; + public static final int STATIC_DRAW = 0x88E4; + public static final int DYNAMIC_DRAW = 0x88E8; + public static final int BUFFER_SIZE = 0x8764; + public static final int BUFFER_USAGE = 0x8765; + public static final int CURRENT_VERTEX_ATTRIB = 0x8626; + public static final int FRONT = 0x0404; + public static final int BACK = 0x0405; + public static final int FRONT_AND_BACK = 0x0408; + public static final int TEXTURE_2D = 0x0DE1; + public static final int CULL_FACE = 0x0B44; + public static final int BLEND = 0x0BE2; + public static final int DITHER = 0x0BD0; + public static final int STENCIL_TEST = 0x0B90; + public static final int DEPTH_TEST = 0x0B71; + public static final int SCISSOR_TEST = 0x0C11; + public static final int POLYGON_OFFSET_FILL = 0x8037; + public static final int SAMPLE_ALPHA_TO_COVERAGE = 0x809E; + public static final int SAMPLE_COVERAGE = 0x80A0; + //public static final int NO_ERROR = 0; + public static final int INVALID_ENUM = 0x0500; + public static final int INVALID_VALUE = 0x0501; + public static final int INVALID_OPERATION = 0x0502; + public static final int OUT_OF_MEMORY = 0x0505; + public static final int CW = 0x0900; + public static final int CCW = 0x0901; + public static final int LINE_WIDTH = 0x0B21; + public static final int ALIASED_POINT_SIZE_RANGE = 0x846D; + public static final int ALIASED_LINE_WIDTH_RANGE = 0x846E; + public static final int CULL_FACE_MODE = 0x0B45; + public static final int FRONT_FACE = 0x0B46; + public static final int DEPTH_RANGE = 0x0B70; + public static final int DEPTH_WRITEMASK = 0x0B72; + public static final int DEPTH_CLEAR_VALUE = 0x0B73; + public static final int DEPTH_FUNC = 0x0B74; + public static final int STENCIL_CLEAR_VALUE = 0x0B91; + public static final int STENCIL_FUNC = 0x0B92; + public static final int STENCIL_FAIL = 0x0B94; + public static final int STENCIL_PASS_DEPTH_FAIL = 0x0B95; + public static final int STENCIL_PASS_DEPTH_PASS = 0x0B96; + public static final int STENCIL_REF = 0x0B97; + public static final int STENCIL_VALUE_MASK = 0x0B93; + public static final int STENCIL_WRITEMASK = 0x0B98; + public static final int STENCIL_BACK_FUNC = 0x8800; + public static final int STENCIL_BACK_FAIL = 0x8801; + public static final int STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802; + public static final int STENCIL_BACK_PASS_DEPTH_PASS = 0x8803; + public static final int STENCIL_BACK_REF = 0x8CA3; + public static final int STENCIL_BACK_VALUE_MASK = 0x8CA4; + public static final int STENCIL_BACK_WRITEMASK = 0x8CA5; + public static final int VIEWPORT = 0x0BA2; + public static final int SCISSOR_BOX = 0x0C10; + public static final int COLOR_CLEAR_VALUE = 0x0C22; + public static final int COLOR_WRITEMASK = 0x0C23; + public static final int UNPACK_ALIGNMENT = 0x0CF5; + public static final int PACK_ALIGNMENT = 0x0D05; + public static final int MAX_TEXTURE_SIZE = 0x0D33; + public static final int MAX_TEXTURE_UNITS = 0x84E2; + public static final int MAX_VIEWPORT_DIMS = 0x0D3A; + public static final int SUBPIXEL_BITS = 0x0D50; + public static final int RED_BITS = 0x0D52; + public static final int GREEN_BITS = 0x0D53; + public static final int BLUE_BITS = 0x0D54; + public static final int ALPHA_BITS = 0x0D55; + public static final int DEPTH_BITS = 0x0D56; + public static final int STENCIL_BITS = 0x0D57; + public static final int POLYGON_OFFSET_UNITS = 0x2A00; + public static final int POLYGON_OFFSET_FACTOR = 0x8038; + public static final int TEXTURE_BINDING_2D = 0x8069; + public static final int SAMPLE_BUFFERS = 0x80A8; + public static final int SAMPLES = 0x80A9; + public static final int SAMPLE_COVERAGE_VALUE = 0x80AA; + public static final int SAMPLE_COVERAGE_INVERT = 0x80AB; + public static final int NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2; + public static final int COMPRESSED_TEXTURE_FORMATS = 0x86A3; + public static final int DONT_CARE = 0x1100; + public static final int FASTEST = 0x1101; + public static final int NICEST = 0x1102; + public static final int GENERATE_MIPMAP_HINT = 0x8192; + public static final int BYTE = 0x1400; + public static final int UNSIGNED_BYTE = 0x1401; + public static final int SHORT = 0x1402; + public static final int UNSIGNED_SHORT = 0x1403; + public static final int INT = 0x1404; + public static final int UNSIGNED_INT = 0x1405; + public static final int FLOAT = 0x1406; + public static final int FIXED = 0x140C; + public static final int DEPTH_COMPONENT = 0x1902; + public static final int ALPHA = 0x1906; + public static final int RGB = 0x1907; + public static final int RGBA = 0x1908; + public static final int LUMINANCE = 0x1909; + public static final int LUMINANCE_ALPHA = 0x190A; + public static final int UNSIGNED_SHORT_4_4_4_4 = 0x8033; + public static final int UNSIGNED_SHORT_5_5_5_1 = 0x8034; + public static final int UNSIGNED_SHORT_5_6_5 = 0x8363; + public static final int FRAGMENT_SHADER = 0x8B30; + public static final int VERTEX_SHADER = 0x8B31; + public static final int MAX_VERTEX_ATTRIBS = 0x8869; + public static final int MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; + public static final int MAX_VARYING_VECTORS = 0x8DFC; + public static final int MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D; + public static final int MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; + public static final int MAX_TEXTURE_IMAGE_UNITS = 0x8872; + public static final int MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD; + public static final int SHADER_TYPE = 0x8B4F; + public static final int DELETE_STATUS = 0x8B80; + public static final int LINK_STATUS = 0x8B82; + public static final int VALIDATE_STATUS = 0x8B83; + public static final int ATTACHED_SHADERS = 0x8B85; + public static final int ACTIVE_UNIFORMS = 0x8B86; + public static final int ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87; + public static final int ACTIVE_ATTRIBUTES = 0x8B89; + public static final int ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A; + public static final int SHADING_LANGUAGE_VERSION = 0x8B8C; + public static final int CURRENT_PROGRAM = 0x8B8D; + public static final int NEVER = 0x0200; + public static final int LESS = 0x0201; + public static final int EQUAL = 0x0202; + public static final int LEQUAL = 0x0203; + public static final int GREATER = 0x0204; + public static final int NOTEQUAL = 0x0205; + public static final int GEQUAL = 0x0206; + public static final int ALWAYS = 0x0207; + public static final int KEEP = 0x1E00; + public static final int REPLACE = 0x1E01; + public static final int INCR = 0x1E02; + public static final int DECR = 0x1E03; + public static final int INVERT = 0x150A; + public static final int INCR_WRAP = 0x8507; + public static final int DECR_WRAP = 0x8508; + public static final int VENDOR = 0x1F00; + public static final int RENDERER = 0x1F01; + public static final int VERSION = 0x1F02; + public static final int EXTENSIONS = 0x1F03; + public static final int NEAREST = 0x2600; + public static final int LINEAR = 0x2601; + public static final int NEAREST_MIPMAP_NEAREST = 0x2700; + public static final int LINEAR_MIPMAP_NEAREST = 0x2701; + public static final int NEAREST_MIPMAP_LINEAR = 0x2702; + public static final int LINEAR_MIPMAP_LINEAR = 0x2703; + public static final int TEXTURE_MAG_FILTER = 0x2800; + public static final int TEXTURE_MIN_FILTER = 0x2801; + public static final int TEXTURE_WRAP_S = 0x2802; + public static final int TEXTURE_WRAP_T = 0x2803; + public static final int TEXTURE = 0x1702; + public static final int TEXTURE_CUBE_MAP = 0x8513; + public static final int TEXTURE_BINDING_CUBE_MAP = 0x8514; + public static final int TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515; + public static final int TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516; + public static final int TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517; + public static final int TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518; + public static final int TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519; + public static final int TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A; + public static final int MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C; + public static final int TEXTURE0 = 0x84C0; + public static final int TEXTURE1 = 0x84C1; + public static final int TEXTURE2 = 0x84C2; + public static final int TEXTURE3 = 0x84C3; + public static final int TEXTURE4 = 0x84C4; + public static final int TEXTURE5 = 0x84C5; + public static final int TEXTURE6 = 0x84C6; + public static final int TEXTURE7 = 0x84C7; + public static final int TEXTURE8 = 0x84C8; + public static final int TEXTURE9 = 0x84C9; + public static final int TEXTURE10 = 0x84CA; + public static final int TEXTURE11 = 0x84CB; + public static final int TEXTURE12 = 0x84CC; + public static final int TEXTURE13 = 0x84CD; + public static final int TEXTURE14 = 0x84CE; + public static final int TEXTURE15 = 0x84CF; + public static final int TEXTURE16 = 0x84D0; + public static final int TEXTURE17 = 0x84D1; + public static final int TEXTURE18 = 0x84D2; + public static final int TEXTURE19 = 0x84D3; + public static final int TEXTURE20 = 0x84D4; + public static final int TEXTURE21 = 0x84D5; + public static final int TEXTURE22 = 0x84D6; + public static final int TEXTURE23 = 0x84D7; + public static final int TEXTURE24 = 0x84D8; + public static final int TEXTURE25 = 0x84D9; + public static final int TEXTURE26 = 0x84DA; + public static final int TEXTURE27 = 0x84DB; + public static final int TEXTURE28 = 0x84DC; + public static final int TEXTURE29 = 0x84DD; + public static final int TEXTURE30 = 0x84DE; + public static final int TEXTURE31 = 0x84DF; + public static final int ACTIVE_TEXTURE = 0x84E0; + public static final int REPEAT = 0x2901; + public static final int CLAMP_TO_EDGE = 0x812F; + public static final int MIRRORED_REPEAT = 0x8370; + public static final int FLOAT_VEC2 = 0x8B50; + public static final int FLOAT_VEC3 = 0x8B51; + public static final int FLOAT_VEC4 = 0x8B52; + public static final int INT_VEC2 = 0x8B53; + public static final int INT_VEC3 = 0x8B54; + public static final int INT_VEC4 = 0x8B55; + public static final int BOOL = 0x8B56; + public static final int BOOL_VEC2 = 0x8B57; + public static final int BOOL_VEC3 = 0x8B58; + public static final int BOOL_VEC4 = 0x8B59; + public static final int FLOAT_MAT2 = 0x8B5A; + public static final int FLOAT_MAT3 = 0x8B5B; + public static final int FLOAT_MAT4 = 0x8B5C; + public static final int SAMPLER_2D = 0x8B5E; + public static final int SAMPLER_CUBE = 0x8B60; + public static final int VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622; + public static final int VERTEX_ATTRIB_ARRAY_SIZE = 0x8623; + public static final int VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624; + public static final int VERTEX_ATTRIB_ARRAY_TYPE = 0x8625; + public static final int VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A; + public static final int VERTEX_ATTRIB_ARRAY_POINTER = 0x8645; + public static final int VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F; + public static final int IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A; + public static final int IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B; + public static final int COMPILE_STATUS = 0x8B81; + public static final int INFO_LOG_LENGTH = 0x8B84; + public static final int SHADER_SOURCE_LENGTH = 0x8B88; + public static final int SHADER_COMPILER = 0x8DFA; + public static final int SHADER_BINARY_FORMATS = 0x8DF8; + public static final int NUM_SHADER_BINARY_FORMATS = 0x8DF9; + public static final int LOW_FLOAT = 0x8DF0; + public static final int MEDIUM_FLOAT = 0x8DF1; + public static final int HIGH_FLOAT = 0x8DF2; + public static final int LOW_INT = 0x8DF3; + public static final int MEDIUM_INT = 0x8DF4; + public static final int HIGH_INT = 0x8DF5; + public static final int FRAMEBUFFER = 0x8D40; + public static final int RENDERBUFFER = 0x8D41; + public static final int RGBA4 = 0x8056; + public static final int RGB5_A1 = 0x8057; + public static final int RGB565 = 0x8D62; + public static final int DEPTH_COMPONENT16 = 0x81A5; + public static final int STENCIL_INDEX = 0x1901; + public static final int STENCIL_INDEX8 = 0x8D48; + public static final int RENDERBUFFER_WIDTH = 0x8D42; + public static final int RENDERBUFFER_HEIGHT = 0x8D43; + public static final int RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; + public static final int RENDERBUFFER_RED_SIZE = 0x8D50; + public static final int RENDERBUFFER_GREEN_SIZE = 0x8D51; + public static final int RENDERBUFFER_BLUE_SIZE = 0x8D52; + public static final int RENDERBUFFER_ALPHA_SIZE = 0x8D53; + public static final int RENDERBUFFER_DEPTH_SIZE = 0x8D54; + public static final int RENDERBUFFER_STENCIL_SIZE = 0x8D55; + public static final int FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; + public static final int FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; + public static final int FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; + public static final int FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; + public static final int COLOR_ATTACHMENT0 = 0x8CE0; + public static final int DEPTH_ATTACHMENT = 0x8D00; + public static final int STENCIL_ATTACHMENT = 0x8D20; + public static final int NONE = 0; + public static final int FRAMEBUFFER_COMPLETE = 0x8CD5; + public static final int FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; + public static final int FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; + public static final int FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9; + public static final int FRAMEBUFFER_UNSUPPORTED = 0x8CDD; + public static final int FRAMEBUFFER_BINDING = 0x8CA6; + public static final int RENDERBUFFER_BINDING = 0x8CA7; + public static final int MAX_RENDERBUFFER_SIZE = 0x84E8; + public static final int INVALID_FRAMEBUFFER_OPERATION = 0x0506; + public static final int VERTEX_PROGRAM_POINT_SIZE = 0x8642; + + // Extensions + public static final int COVERAGE_BUFFER_BIT_NV = 0x8000; + + public void attachShader(int program, int shader); + + public void bindAttribLocation(int program, int index, String name); - public void bindBuffer(int target, int buffer); + public void bindBuffer(int target, int buffer); - public void bindFramebuffer(int target, int framebuffer); + public void bindFramebuffer(int target, int framebuffer); - public void bindRenderbuffer(int target, int renderbuffer); + public void bindRenderbuffer(int target, int renderbuffer); - public void blendColor(float red, float green, float blue, float alpha); + public void blendColor(float red, float green, float blue, float alpha); - public void blendEquation(int mode); + public void blendEquation(int mode); - public void blendEquationSeparate(int modeRGB, int modeAlpha); + public void blendEquationSeparate(int modeRGB, int modeAlpha); - public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha); + public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha); - public void bufferData(int target, int size, Buffer data, int usage); + public void bufferData(int target, int size, Buffer data, int usage); - public void bufferSubData(int target, int offset, int size, Buffer data); + public void bufferSubData(int target, int offset, int size, Buffer data); - public int checkFramebufferStatus(int target); + public int checkFramebufferStatus(int target); - public void compileShader(int shader); + public void compileShader(int shader); - public int createProgram(); + public int createProgram(); - public int createShader(int type); + public int createShader(int type); - public void deleteBuffers(int n, IntBuffer buffers); + public void deleteBuffers(int n, IntBuffer buffers); - public void deleteFramebuffers(int n, IntBuffer framebuffers); + public void deleteFramebuffers(int n, IntBuffer framebuffers); - public void deleteProgram(int program); + public void deleteProgram(int program); - public void deleteRenderbuffers(int n, IntBuffer renderbuffers); + public void deleteRenderbuffers(int n, IntBuffer renderbuffers); - public void deleteShader(int shader); + public void deleteShader(int shader); - public void detachShader(int program, int shader); + public void detachShader(int program, int shader); - public void disableVertexAttribArray(int index); + public void disableVertexAttribArray(int index); - public void drawElements(int mode, int count, int type, int offset); + public void drawElements(int mode, int count, int type, int offset); - public void enableVertexAttribArray(int index); + public void enableVertexAttribArray(int index); - public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, - int renderbuffer); + public void framebufferRenderbuffer(int target, int attachment, int renderbuffertarget, + int renderbuffer); - public void framebufferTexture2D(int target, int attachment, int textarget, int texture, - int level); + public void framebufferTexture2D(int target, int attachment, int textarget, int texture, + int level); - public void genBuffers(int n, IntBuffer buffers); + public void genBuffers(int n, IntBuffer buffers); - public void generateMipmap(int target); + public void generateMipmap(int target); - public void genFramebuffers(int n, IntBuffer framebuffers); + public void genFramebuffers(int n, IntBuffer framebuffers); - public void genRenderbuffers(int n, IntBuffer renderbuffers); + public void genRenderbuffers(int n, IntBuffer renderbuffers); - // deviates - public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type); + // deviates + public String getActiveAttrib(int program, int index, IntBuffer size, Buffer type); - // deviates - public String getActiveUniform(int program, int index, IntBuffer size, Buffer type); + // deviates + public String getActiveUniform(int program, int index, IntBuffer size, Buffer type); - public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders); + public void getAttachedShaders(int program, int maxcount, Buffer count, IntBuffer shaders); - public int getAttribLocation(int program, String name); + public int getAttribLocation(int program, String name); - public void getBooleanv(int pname, Buffer params); + public void getBooleanv(int pname, Buffer params); - public void getBufferParameteriv(int target, int pname, IntBuffer params); + public void getBufferParameteriv(int target, int pname, IntBuffer params); - public void getFloatv(int pname, FloatBuffer params); + public void getFloatv(int pname, FloatBuffer params); - public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, - IntBuffer params); + public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, + IntBuffer params); - public void getProgramiv(int program, int pname, IntBuffer params); + public void getProgramiv(int program, int pname, IntBuffer params); - // deviates - public String getProgramInfoLog(int program); + // deviates + public String getProgramInfoLog(int program); - public void getRenderbufferParameteriv(int target, int pname, IntBuffer params); + public void getRenderbufferParameteriv(int target, int pname, IntBuffer params); - public void getShaderiv(int shader, int pname, IntBuffer params); + public void getShaderiv(int shader, int pname, IntBuffer params); - // deviates - public String getShaderInfoLog(int shader); + // deviates + public String getShaderInfoLog(int shader); - public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, - IntBuffer precision); + public void getShaderPrecisionFormat(int shadertype, int precisiontype, IntBuffer range, + IntBuffer precision); - public void getShaderSource(int shader, int bufsize, Buffer length, String source); + public void getShaderSource(int shader, int bufsize, Buffer length, String source); - public void getTexParameterfv(int target, int pname, FloatBuffer params); + public void getTexParameterfv(int target, int pname, FloatBuffer params); - public void getTexParameteriv(int target, int pname, IntBuffer params); + public void getTexParameteriv(int target, int pname, IntBuffer params); - public void getUniformfv(int program, int location, FloatBuffer params); + public void getUniformfv(int program, int location, FloatBuffer params); - public void getUniformiv(int program, int location, IntBuffer params); + public void getUniformiv(int program, int location, IntBuffer params); - public int getUniformLocation(int program, String name); + public int getUniformLocation(int program, String name); - public void getVertexAttribfv(int index, int pname, FloatBuffer params); + public void getVertexAttribfv(int index, int pname, FloatBuffer params); - public void getVertexAttribiv(int index, int pname, IntBuffer params); + public void getVertexAttribiv(int index, int pname, IntBuffer params); - public void getVertexAttribPointerv(int index, int pname, Buffer pointer); + public void getVertexAttribPointerv(int index, int pname, Buffer pointer); - public boolean isBuffer(int buffer); + public boolean isBuffer(int buffer); - public boolean isEnabled(int cap); + public boolean isEnabled(int cap); - public boolean isFramebuffer(int framebuffer); + public boolean isFramebuffer(int framebuffer); - public boolean isProgram(int program); + public boolean isProgram(int program); - public boolean isRenderbuffer(int renderbuffer); + public boolean isRenderbuffer(int renderbuffer); - public boolean isShader(int shader); + public boolean isShader(int shader); - public boolean isTexture(int texture); + public boolean isTexture(int texture); - public void linkProgram(int program); + public void linkProgram(int program); - public void releaseShaderCompiler(); + public void releaseShaderCompiler(); - public void renderbufferStorage(int target, int internalformat, int width, int height); + public void renderbufferStorage(int target, int internalformat, int width, int height); - public void sampleCoverage(float value, boolean invert); + public void sampleCoverage(float value, boolean invert); - public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length); + public void shaderBinary(int n, IntBuffer shaders, int binaryformat, Buffer binary, int length); - // Deviates - public void shaderSource(int shader, String string); + // Deviates + public void shaderSource(int shader, String string); - public void stencilFuncSeparate(int face, int func, int ref, int mask); + public void stencilFuncSeparate(int face, int func, int ref, int mask); - public void stencilMaskSeparate(int face, int mask); + public void stencilMaskSeparate(int face, int mask); - public void stencilOpSeparate(int face, int fail, int zfail, int zpass); + public void stencilOpSeparate(int face, int fail, int zfail, int zpass); - public void texParameterfv(int target, int pname, FloatBuffer params); + public void texParameterfv(int target, int pname, FloatBuffer params); - public void texParameteri(int target, int pname, int param); + public void texParameteri(int target, int pname, int param); - public void texParameteriv(int target, int pname, IntBuffer params); + public void texParameteriv(int target, int pname, IntBuffer params); - public void uniform1f(int location, float x); + public void uniform1f(int location, float x); - public void uniform1fv(int location, int count, FloatBuffer v); + public void uniform1fv(int location, int count, FloatBuffer v); - public void uniform1i(int location, int x); + public void uniform1i(int location, int x); - public void uniform1iv(int location, int count, IntBuffer v); + public void uniform1iv(int location, int count, IntBuffer v); - public void uniform2f(int location, float x, float y); + public void uniform2f(int location, float x, float y); - public void uniform2fv(int location, int count, FloatBuffer v); + public void uniform2fv(int location, int count, FloatBuffer v); - public void uniform2i(int location, int x, int y); + public void uniform2i(int location, int x, int y); - public void uniform2iv(int location, int count, IntBuffer v); + public void uniform2iv(int location, int count, IntBuffer v); - public void uniform3f(int location, float x, float y, float z); + public void uniform3f(int location, float x, float y, float z); - public void uniform3fv(int location, int count, FloatBuffer v); + public void uniform3fv(int location, int count, FloatBuffer v); - public void uniform3i(int location, int x, int y, int z); + public void uniform3i(int location, int x, int y, int z); - public void uniform3iv(int location, int count, IntBuffer v); + public void uniform3iv(int location, int count, IntBuffer v); - public void uniform4f(int location, float x, float y, float z, float w); + public void uniform4f(int location, float x, float y, float z, float w); - public void uniform4fv(int location, int count, FloatBuffer v); + public void uniform4fv(int location, int count, FloatBuffer v); - public void uniform4i(int location, int x, int y, int z, int w); + public void uniform4i(int location, int x, int y, int z, int w); - public void uniform4iv(int location, int count, IntBuffer v); + public void uniform4iv(int location, int count, IntBuffer v); - public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value); + public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer value); - public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value); + public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer value); - public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value); + public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value); - public void useProgram(int program); + public void useProgram(int program); - public void validateProgram(int program); + public void validateProgram(int program); - public void vertexAttrib1f(int indx, float x); + public void vertexAttrib1f(int indx, float x); - public void vertexAttrib1fv(int indx, FloatBuffer values); + public void vertexAttrib1fv(int indx, FloatBuffer values); - public void vertexAttrib2f(int indx, float x, float y); + public void vertexAttrib2f(int indx, float x, float y); - public void vertexAttrib2fv(int indx, FloatBuffer values); + public void vertexAttrib2fv(int indx, FloatBuffer values); - public void vertexAttrib3f(int indx, float x, float y, float z); + public void vertexAttrib3f(int indx, float x, float y, float z); - public void vertexAttrib3fv(int indx, FloatBuffer values); + public void vertexAttrib3fv(int indx, FloatBuffer values); - public void vertexAttrib4f(int indx, float x, float y, float z, float w); + public void vertexAttrib4f(int indx, float x, float y, float z, float w); - public void vertexAttrib4fv(int indx, FloatBuffer values); + public void vertexAttrib4fv(int indx, FloatBuffer values); - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - Buffer ptr); + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + Buffer ptr); - /** - * - */ - public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, - int offset); + /** + * + */ + public void vertexAttribPointer(int indx, int size, int type, boolean normalized, int stride, + int offset); - //------------------------ + //------------------------ - public static final int GENERATE_MIPMAP = 0x8191; - public static final int TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE; - public static final int MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF; + public static final int GENERATE_MIPMAP = 0x8191; + public static final int TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE; + public static final int MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF; - public void activeTexture(int texture); + public void activeTexture(int texture); - public void bindTexture(int target, int texture); + public void bindTexture(int target, int texture); - public void blendFunc(int sfactor, int dfactor); + public void blendFunc(int sfactor, int dfactor); - public void clear(int mask); + public void clear(int mask); - public void clearColor(float red, float green, float blue, float alpha); + public void clearColor(float red, float green, float blue, float alpha); - public void clearDepthf(float depth); + public void clearDepthf(float depth); - public void clearStencil(int s); + public void clearStencil(int s); - public void colorMask(boolean red, boolean green, boolean blue, boolean alpha); + public void colorMask(boolean red, boolean green, boolean blue, boolean alpha); - public void compressedTexImage2D(int target, int level, int internalformat, int width, - int height, int border, - int imageSize, Buffer data); + public void compressedTexImage2D(int target, int level, int internalformat, int width, + int height, int border, + int imageSize, Buffer data); - public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, - int width, int height, int format, - int imageSize, Buffer data); + public void compressedTexSubImage2D(int target, int level, int xoffset, int yoffset, + int width, int height, int format, + int imageSize, Buffer data); - public void copyTexImage2D(int target, int level, int internalformat, int x, int y, - int width, int height, int border); + public void copyTexImage2D(int target, int level, int internalformat, int x, int y, + int width, int height, int border); - public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, - int width, int height); + public void copyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, + int width, int height); - public void cullFace(int mode); + public void cullFace(int mode); - public void deleteTextures(int n, IntBuffer textures); + public void deleteTextures(int n, IntBuffer textures); - public void depthFunc(int func); + public void depthFunc(int func); - public void depthMask(boolean flag); + public void depthMask(boolean flag); - public void depthRangef(float zNear, float zFar); + public void depthRangef(float zNear, float zFar); - public void disable(int cap); + public void disable(int cap); - public void drawArrays(int mode, int first, int count); + public void drawArrays(int mode, int first, int count); - public void drawElements(int mode, int count, int type, Buffer indices); + public void drawElements(int mode, int count, int type, Buffer indices); - public void enable(int cap); + public void enable(int cap); - public void finish(); + public void finish(); - public void flush(); + public void flush(); - public void frontFace(int mode); + public void frontFace(int mode); - public void genTextures(int n, IntBuffer textures); + public void genTextures(int n, IntBuffer textures); - public int getError(); + public int getError(); - public void getIntegerv(int pname, IntBuffer params); + public void getIntegerv(int pname, IntBuffer params); - public String getString(int name); + public String getString(int name); - public void hint(int target, int mode); + public void hint(int target, int mode); - public void lineWidth(float width); + public void lineWidth(float width); - public void pixelStorei(int pname, int param); + public void pixelStorei(int pname, int param); - public void polygonOffset(float factor, float units); + public void polygonOffset(float factor, float units); - public void readPixels(int x, int y, int width, int height, int format, int type, - Buffer pixels); + public void readPixels(int x, int y, int width, int height, int format, int type, + Buffer pixels); - public void scissor(int x, int y, int width, int height); + public void scissor(int x, int y, int width, int height); - public void stencilFunc(int func, int ref, int mask); + public void stencilFunc(int func, int ref, int mask); - public void stencilMask(int mask); + public void stencilMask(int mask); - public void stencilOp(int fail, int zfail, int zpass); + public void stencilOp(int fail, int zfail, int zpass); - public void texImage2D(int target, int level, int internalformat, int width, int height, - int border, int format, int type, - Buffer pixels); + public void texImage2D(int target, int level, int internalformat, int width, int height, + int border, int format, int type, + Buffer pixels); - public void texParameterf(int target, int pname, float param); + public void texParameterf(int target, int pname, float param); - public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, - int height, int format, int type, - Buffer pixels); + public void texSubImage2D(int target, int level, int xoffset, int yoffset, int width, + int height, int format, int type, + Buffer pixels); - public void viewport(int x, int y, int width, int height); + public void viewport(int x, int y, int width, int height); } diff --git a/vtm/src/org/oscim/backend/GLAdapter.java b/vtm/src/org/oscim/backend/GLAdapter.java index 23d93d81..b6be5f99 100644 --- a/vtm/src/org/oscim/backend/GLAdapter.java +++ b/vtm/src/org/oscim/backend/GLAdapter.java @@ -18,22 +18,24 @@ package org.oscim.backend; public class GLAdapter { - public final static boolean debug = false; - public final static boolean debugView = false; + public final static boolean debug = false; + public final static boolean debugView = false; - /** The instance provided by backend */ - public static GL gl; + /** + * The instance provided by backend + */ + public static GL gl; - public static boolean GDX_DESKTOP_QUIRKS = false; - public static boolean GDX_WEBGL_QUIRKS = false; + public static boolean GDX_DESKTOP_QUIRKS = false; + public static boolean GDX_WEBGL_QUIRKS = false; - /** - * Set true as workaround for adreno driver issue: - * https://github.com/opensciencemap/vtm/issues/52 - */ - public static boolean NO_BUFFER_SUB_DATA = false; + /** + * Set true as workaround for adreno driver issue: + * https://github.com/opensciencemap/vtm/issues/52 + */ + public static boolean NO_BUFFER_SUB_DATA = false; - public static void init(GL gl20) { - gl = gl20; - } + public static void init(GL gl20) { + gl = gl20; + } } diff --git a/vtm/src/org/oscim/backend/XMLReaderAdapter.java b/vtm/src/org/oscim/backend/XMLReaderAdapter.java index fb491170..73b74021 100644 --- a/vtm/src/org/oscim/backend/XMLReaderAdapter.java +++ b/vtm/src/org/oscim/backend/XMLReaderAdapter.java @@ -16,36 +16,36 @@ */ package org.oscim.backend; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - /** * The Class XMLReaderAdapter. Used by RenderTheme. Note: GWT Backend provides * its own implementation. */ public class XMLReaderAdapter { - public void parse(DefaultHandler handler, InputStream is) throws IOException { + public void parse(DefaultHandler handler, InputStream is) throws IOException { - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setNamespaceAware(true); + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); - try { - XMLReader xmlReader = factory.newSAXParser().getXMLReader(); - xmlReader.setContentHandler(handler); - xmlReader.parse(new InputSource(is)); + try { + XMLReader xmlReader = factory.newSAXParser().getXMLReader(); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(is)); - } catch (SAXException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } - } + } catch (SAXException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } + } } diff --git a/vtm/src/org/oscim/backend/canvas/Bitmap.java b/vtm/src/org/oscim/backend/canvas/Bitmap.java index 79c49a26..8f9d9139 100644 --- a/vtm/src/org/oscim/backend/canvas/Bitmap.java +++ b/vtm/src/org/oscim/backend/canvas/Bitmap.java @@ -21,45 +21,45 @@ package org.oscim.backend.canvas; */ public interface Bitmap { - /** - * Gets the width. - * - * @return the width - */ - int getWidth(); + /** + * Gets the width. + * + * @return the width + */ + int getWidth(); - /** - * Gets the height. - * - * @return the height - */ - int getHeight(); + /** + * Gets the height. + * + * @return the height + */ + int getHeight(); - /** - * Recycle. - */ - void recycle(); + /** + * Recycle. + */ + void recycle(); - /** - * Gets the pixels as ARGB int array. - * - * @return the pixels - */ - int[] getPixels(); + /** + * Gets the pixels as ARGB int array. + * + * @return the pixels + */ + int[] getPixels(); - /** - * Erase color, clear Bitmap. - * - * @param color the color - */ - void eraseColor(int color); + /** + * Erase color, clear Bitmap. + * + * @param color the color + */ + void eraseColor(int color); - /** - * Upload Bitmap to currently bound GL texture. - * - * @param replace true, when glSubImage2D can be used for upload - */ - void uploadToTexture(boolean replace); + /** + * Upload Bitmap to currently bound GL texture. + * + * @param replace true, when glSubImage2D can be used for upload + */ + void uploadToTexture(boolean replace); - boolean isValid(); + boolean isValid(); } diff --git a/vtm/src/org/oscim/backend/canvas/Canvas.java b/vtm/src/org/oscim/backend/canvas/Canvas.java index f250511d..065315c8 100644 --- a/vtm/src/org/oscim/backend/canvas/Canvas.java +++ b/vtm/src/org/oscim/backend/canvas/Canvas.java @@ -22,31 +22,31 @@ package org.oscim.backend.canvas; */ public interface Canvas { - /** - * Sets the backing {@link Bitmap}. - * - * @param bitmap the new bitmap - */ - void setBitmap(Bitmap bitmap); + /** + * Sets the backing {@link Bitmap}. + * + * @param bitmap the new bitmap + */ + void setBitmap(Bitmap bitmap); - /** - * Draw text to Canvas. - * - * @param string the String - * @param x - * @param y - * @param stroke the stroke - * @param - */ - void drawText(String string, float x, float y, Paint fill, Paint stroke); + /** + * Draw text to Canvas. + * + * @param string the String + * @param x + * @param y + * @param stroke the stroke + * @param + */ + void drawText(String string, float x, float y, Paint fill, Paint stroke); - /** - * Draw Bitmap to Canvas. - * - * @param bitmap the Bitmap - * @param x - * @param y - */ - void drawBitmap(Bitmap bitmap, float x, float y); + /** + * Draw Bitmap to Canvas. + * + * @param bitmap the Bitmap + * @param x + * @param y + */ + void drawBitmap(Bitmap bitmap, float x, float y); } diff --git a/vtm/src/org/oscim/backend/canvas/Color.java b/vtm/src/org/oscim/backend/canvas/Color.java index 6a3e27c1..59e7af46 100644 --- a/vtm/src/org/oscim/backend/canvas/Color.java +++ b/vtm/src/org/oscim/backend/canvas/Color.java @@ -21,230 +21,230 @@ import org.oscim.utils.FastMath; public final class Color { - private static final int OPAQUE = 0xff000000; + private static final int OPAQUE = 0xff000000; - public static int fadePremul(int color, double alpha) { - alpha = FastMath.clamp(alpha, 0, 1); + public static int fadePremul(int color, double alpha) { + alpha = FastMath.clamp(alpha, 0, 1); - alpha *= (color >>> 24) & 0xff; - int c = (((int) alpha) & 0xff) << 24; + alpha *= (color >>> 24) & 0xff; + int c = (((int) alpha) & 0xff) << 24; - alpha /= 255; + alpha /= 255; - c |= ((int) (alpha * ((color >>> 16) & 0xff))) << 16; - c |= ((int) (alpha * ((color >>> 8) & 0xff))) << 8; - c |= ((int) (alpha * (color & 0xff))); + c |= ((int) (alpha * ((color >>> 16) & 0xff))) << 16; + c |= ((int) (alpha * ((color >>> 8) & 0xff))) << 8; + c |= ((int) (alpha * (color & 0xff))); - return c; - } + return c; + } - public static int fade(int color, double alpha) { - alpha = FastMath.clamp(alpha, 0, 1); + public static int fade(int color, double alpha) { + alpha = FastMath.clamp(alpha, 0, 1); - alpha *= (color >>> 24) & 0xff; - int c = (((int) alpha) & 0xff) << 24; + alpha *= (color >>> 24) & 0xff; + int c = (((int) alpha) & 0xff) << 24; - return c | (color & 0x00ffffff); - } + return c | (color & 0x00ffffff); + } - public static int rainbow(float pos) { - float i = 255 * pos; - int r = (int) Math.round(Math.sin(0.024 * i + 0) * 127 + 128); - int g = (int) Math.round(Math.sin(0.024 * i + 2) * 127 + 128); - int b = (int) Math.round(Math.sin(0.024 * i + 4) * 127 + 128); - return 0xff000000 | (r << 16) | (g << 8) | b; - } + public static int rainbow(float pos) { + float i = 255 * pos; + int r = (int) Math.round(Math.sin(0.024 * i + 0) * 127 + 128); + int g = (int) Math.round(Math.sin(0.024 * i + 2) * 127 + 128); + int b = (int) Math.round(Math.sin(0.024 * i + 4) * 127 + 128); + return 0xff000000 | (r << 16) | (g << 8) | b; + } - /** - * Pack r, g, b bytes into one int. - */ - public static int get(int r, int g, int b) { - return 0xff << 24 | r << 16 | g << 8 | b; - } + /** + * Pack r, g, b bytes into one int. + */ + public static int get(int r, int g, int b) { + return 0xff << 24 | r << 16 | g << 8 | b; + } - public static int get(double r, double g, double b) { - return 0xff << 24 - | (int) Math.round(r * 255) << 16 - | (int) Math.round(g * 255) << 8 - | (int) Math.round(b * 255); - } + public static int get(double r, double g, double b) { + return 0xff << 24 + | (int) Math.round(r * 255) << 16 + | (int) Math.round(g * 255) << 8 + | (int) Math.round(b * 255); + } - /** - * Pack premultiplied a, r, g, b bytes into one int. - */ - public static int get(int a, int r, int g, int b) { - return a << 24 | r << 16 | g << 8 | b; - } + /** + * Pack premultiplied a, r, g, b bytes into one int. + */ + public static int get(int a, int r, int g, int b) { + return a << 24 | r << 16 | g << 8 | b; + } - /** - * Pack r, g, b bytes into one int with premultiplied alpha a. - */ - public static int get(float a, int r, int g, int b) { - return fade(0xff << 24 | r << 16 | g << 8 | b, a); - } + /** + * Pack r, g, b bytes into one int with premultiplied alpha a. + */ + public static int get(float a, int r, int g, int b) { + return fade(0xff << 24 | r << 16 | g << 8 | b, a); + } - public static float rToFloat(int color) { - return ((color >>> 16) & 0xff) / 255f; - } + public static float rToFloat(int color) { + return ((color >>> 16) & 0xff) / 255f; + } - public static float gToFloat(int color) { - return ((color >>> 8) & 0xff) / 255f; - } + public static float gToFloat(int color) { + return ((color >>> 8) & 0xff) / 255f; + } - public static float bToFloat(int color) { - return ((color) & 0xff) / 255f; - } + public static float bToFloat(int color) { + return ((color) & 0xff) / 255f; + } - public static float aToFloat(int color) { - return ((color >>> 24) & 0xff) / 255f; - } + public static float aToFloat(int color) { + return ((color >>> 24) & 0xff) / 255f; + } - public static int a(int color) { - return ((color >>> 24) & 0xff); - } + public static int a(int color) { + return ((color >>> 24) & 0xff); + } - public static int r(int color) { - return ((color >>> 16) & 0xff); - } + public static int r(int color) { + return ((color >>> 16) & 0xff); + } - public static int g(int color) { - return ((color >>> 8) & 0xff); - } + public static int g(int color) { + return ((color >>> 8) & 0xff); + } - public static int b(int color) { - return ((color) & 0xff); - } + public static int b(int color) { + return ((color) & 0xff); + } - public static int parseColorComponents(String str) { - int numComponents = 4; - int cur = 5; + public static int parseColorComponents(String str) { + int numComponents = 4; + int cur = 5; - if (str.startsWith("rgb(")) { - numComponents = 3; - cur = 4; - } else if (!str.startsWith("rgba(")) - parseColorException(str); + if (str.startsWith("rgb(")) { + numComponents = 3; + cur = 4; + } else if (!str.startsWith("rgba(")) + parseColorException(str); - int end = str.length(); - int component = 0; - int a = 0, r = 0, g = 0, b = 0; + int end = str.length(); + int component = 0; + int a = 0, r = 0, g = 0, b = 0; - if (str.charAt(end - 1) != ')') - parseColorException(str); + if (str.charAt(end - 1) != ')') + parseColorException(str); - for (; cur < end; cur++) { - char c = str.charAt(cur); - if (c == ',') { - component++; - if (component >= numComponents) - parseColorException(str); - continue; - } else if (c >= '0' && c <= '9') { - if (component == 0) { - r *= 10; - r += c - '0'; - } else if (component == 1) { - g *= 10; - g += c - '0'; - } else if (component == 2) { - b *= 10; - b += c - '0'; - } else { - a *= 10; - a += c - '0'; - } + for (; cur < end; cur++) { + char c = str.charAt(cur); + if (c == ',') { + component++; + if (component >= numComponents) + parseColorException(str); + continue; + } else if (c >= '0' && c <= '9') { + if (component == 0) { + r *= 10; + r += c - '0'; + } else if (component == 1) { + g *= 10; + g += c - '0'; + } else if (component == 2) { + b *= 10; + b += c - '0'; + } else { + a *= 10; + a += c - '0'; + } - } else - parseColorException(str); - } - if (r > 255 || g > 255 || b > 255 || a > 255) - parseColorException(str); + } else + parseColorException(str); + } + if (r > 255 || g > 255 || b > 255 || a > 255) + parseColorException(str); - if (numComponents == 3) - return get(r, g, b); - else - return get(a, r, g, b); - } + if (numComponents == 3) + return get(r, g, b); + else + return get(a, r, g, b); + } - private static void parseColorException(String str) { - throw new IllegalArgumentException("Unknown color: \'" + str + '\''); - } + private static void parseColorException(String str) { + throw new IllegalArgumentException("Unknown color: \'" + str + '\''); + } - /* Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ - public static final int BLACK = 0xFF000000; - public static final int DKGRAY = 0xFF444444; - public static final int GRAY = 0xFF888888; - public static final int LTGRAY = 0xFFCCCCCC; - public static final int WHITE = 0xFFFFFFFF; - public static final int RED = 0xFFFF0000; - public static final int GREEN = 0xFF00FF00; - public static final int BLUE = 0xFF0000FF; - public static final int YELLOW = 0xFFFFFF00; - public static final int CYAN = 0xFF00FFFF; - public static final int MAGENTA = 0xFFFF00FF; - public static final int TRANSPARENT = 0; + /* Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + public static final int BLACK = 0xFF000000; + public static final int DKGRAY = 0xFF444444; + public static final int GRAY = 0xFF888888; + public static final int LTGRAY = 0xFFCCCCCC; + public static final int WHITE = 0xFFFFFFFF; + public static final int RED = 0xFFFF0000; + public static final int GREEN = 0xFF00FF00; + public static final int BLUE = 0xFF0000FF; + public static final int YELLOW = 0xFFFFFF00; + public static final int CYAN = 0xFF00FFFF; + public static final int MAGENTA = 0xFFFF00FF; + public static final int TRANSPARENT = 0; - /** - * Parse the color string, and return the corresponding color-int. - * If the string cannot be parsed, throws an IllegalArgumentException - * exception. Supported formats are: - * #RRGGBB - * #AARRGGBB - * 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', - * 'yellow', 'lightgray', 'darkgray' - * - * @param colorString the color string - * @return the int - */ - public static int parseColor(String colorString) { - if (colorString.charAt(0) == '#') { - // Use a long to avoid rollovers on #ffXXXXXX - long color = Long.parseLong(colorString.substring(1), 16); - if (colorString.length() == 7) { - // Set the alpha value - color |= 0x00000000ff000000; - } else if (colorString.length() != 9) { - parseColorException(colorString); - } - return (int) color; - } - if (colorString.charAt(0) == 'r') { - return parseColorComponents(colorString); - } - throw new IllegalArgumentException("Unknown color"); - } + /** + * Parse the color string, and return the corresponding color-int. + * If the string cannot be parsed, throws an IllegalArgumentException + * exception. Supported formats are: + * #RRGGBB + * #AARRGGBB + * 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', + * 'yellow', 'lightgray', 'darkgray' + * + * @param colorString the color string + * @return the int + */ + public static int parseColor(String colorString) { + if (colorString.charAt(0) == '#') { + // Use a long to avoid rollovers on #ffXXXXXX + long color = Long.parseLong(colorString.substring(1), 16); + if (colorString.length() == 7) { + // Set the alpha value + color |= 0x00000000ff000000; + } else if (colorString.length() != 9) { + parseColorException(colorString); + } + return (int) color; + } + if (colorString.charAt(0) == 'r') { + return parseColorComponents(colorString); + } + throw new IllegalArgumentException("Unknown color"); + } - public static int parseColor(String colorString, int fallBackColor) { - if (colorString.charAt(0) == '#') { - // Use a long to avoid rollovers on #ffXXXXXX - long color = Long.parseLong(colorString.substring(1), 16); - if (colorString.length() == 7) { - // Set the alpha value - color |= 0x00000000ff000000; - } else if (colorString.length() != 9) { - return fallBackColor; - } - return (int) color; - } - return fallBackColor; - } + public static int parseColor(String colorString, int fallBackColor) { + if (colorString.charAt(0) == '#') { + // Use a long to avoid rollovers on #ffXXXXXX + long color = Long.parseLong(colorString.substring(1), 16); + if (colorString.length() == 7) { + // Set the alpha value + color |= 0x00000000ff000000; + } else if (colorString.length() != 9) { + return fallBackColor; + } + return (int) color; + } + return fallBackColor; + } - public static boolean isOpaque(int color) { - return (color & OPAQUE) == OPAQUE; - } + public static boolean isOpaque(int color) { + return (color & OPAQUE) == OPAQUE; + } - private Color() { - } + private Color() { + } } diff --git a/vtm/src/org/oscim/backend/canvas/Paint.java b/vtm/src/org/oscim/backend/canvas/Paint.java index ba1872e2..16933723 100644 --- a/vtm/src/org/oscim/backend/canvas/Paint.java +++ b/vtm/src/org/oscim/backend/canvas/Paint.java @@ -22,45 +22,45 @@ package org.oscim.backend.canvas; */ public interface Paint { - public static enum Align { - CENTER, LEFT, RIGHT; - } + public static enum Align { + CENTER, LEFT, RIGHT; + } - public enum Cap { - BUTT, ROUND, SQUARE; - } + public enum Cap { + BUTT, ROUND, SQUARE; + } - public enum Style { - FILL, STROKE - } + public enum Style { + FILL, STROKE + } - public enum FontFamily { - DEFAULT, DEFAULT_BOLD, MONOSPACE, SANS_SERIF, SERIF; - } + public enum FontFamily { + DEFAULT, DEFAULT_BOLD, MONOSPACE, SANS_SERIF, SERIF; + } - public enum FontStyle { - BOLD, BOLD_ITALIC, ITALIC, NORMAL; - } + public enum FontStyle { + BOLD, BOLD_ITALIC, ITALIC, NORMAL; + } - int getColor(); + int getColor(); - void setColor(int color); + void setColor(int color); - void setStrokeCap(Cap cap); + void setStrokeCap(Cap cap); - void setStrokeWidth(float width); + void setStrokeWidth(float width); - void setStyle(Style style); + void setStyle(Style style); - void setTextAlign(Align align); + void setTextAlign(Align align); - void setTextSize(float textSize); + void setTextSize(float textSize); - void setTypeface(FontFamily fontFamily, FontStyle fontStyle); + void setTypeface(FontFamily fontFamily, FontStyle fontStyle); - float measureText(String text); + float measureText(String text); - float getFontHeight(); + float getFontHeight(); - float getFontDescent(); + float getFontDescent(); } diff --git a/vtm/src/org/oscim/core/BoundingBox.java b/vtm/src/org/oscim/core/BoundingBox.java index a33b8cdf..9343255b 100644 --- a/vtm/src/org/oscim/core/BoundingBox.java +++ b/vtm/src/org/oscim/core/BoundingBox.java @@ -24,183 +24,178 @@ import java.util.List; * coordinates. */ public class BoundingBox { - /** - * Conversion factor from degrees to microdegrees. - */ - private static final double CONVERSION_FACTOR = 1000000d; + /** + * Conversion factor from degrees to microdegrees. + */ + private static final double CONVERSION_FACTOR = 1000000d; - /** - * The maximum latitude value of this BoundingBox in microdegrees (degrees * - * 10^6). - */ - public final int maxLatitudeE6; + /** + * The maximum latitude value of this BoundingBox in microdegrees (degrees * + * 10^6). + */ + public final int maxLatitudeE6; - /** - * The maximum longitude value of this BoundingBox in microdegrees (degrees - * * 10^6). - */ - public final int maxLongitudeE6; + /** + * The maximum longitude value of this BoundingBox in microdegrees (degrees + * * 10^6). + */ + public final int maxLongitudeE6; - /** - * The minimum latitude value of this BoundingBox in microdegrees (degrees * - * 10^6). - */ - public final int minLatitudeE6; + /** + * The minimum latitude value of this BoundingBox in microdegrees (degrees * + * 10^6). + */ + public final int minLatitudeE6; - /** - * The minimum longitude value of this BoundingBox in microdegrees (degrees - * * 10^6). - */ - public final int minLongitudeE6; + /** + * The minimum longitude value of this BoundingBox in microdegrees (degrees + * * 10^6). + */ + public final int minLongitudeE6; - /** - * @param minLatitudeE6 - * the minimum latitude in microdegrees (degrees * 10^6). - * @param minLongitudeE6 - * the minimum longitude in microdegrees (degrees * 10^6). - * @param maxLatitudeE6 - * the maximum latitude in microdegrees (degrees * 10^6). - * @param maxLongitudeE6 - * the maximum longitude in microdegrees (degrees * 10^6). - */ - public BoundingBox(int minLatitudeE6, int minLongitudeE6, int maxLatitudeE6, int maxLongitudeE6) { - this.minLatitudeE6 = minLatitudeE6; - this.minLongitudeE6 = minLongitudeE6; - this.maxLatitudeE6 = maxLatitudeE6; - this.maxLongitudeE6 = maxLongitudeE6; - } + /** + * @param minLatitudeE6 the minimum latitude in microdegrees (degrees * 10^6). + * @param minLongitudeE6 the minimum longitude in microdegrees (degrees * 10^6). + * @param maxLatitudeE6 the maximum latitude in microdegrees (degrees * 10^6). + * @param maxLongitudeE6 the maximum longitude in microdegrees (degrees * 10^6). + */ + public BoundingBox(int minLatitudeE6, int minLongitudeE6, int maxLatitudeE6, int maxLongitudeE6) { + this.minLatitudeE6 = minLatitudeE6; + this.minLongitudeE6 = minLongitudeE6; + this.maxLatitudeE6 = maxLatitudeE6; + this.maxLongitudeE6 = maxLongitudeE6; + } - public BoundingBox(double minLatitude, double minLongitude, double maxLatitude, - double maxLongitude) { - this.minLatitudeE6 = (int) (minLatitude * 1E6); - this.minLongitudeE6 = (int) (minLongitude * 1E6); - this.maxLatitudeE6 = (int) (maxLatitude * 1E6); - this.maxLongitudeE6 = (int) (maxLongitude * 1E6); - } + public BoundingBox(double minLatitude, double minLongitude, double maxLatitude, + double maxLongitude) { + this.minLatitudeE6 = (int) (minLatitude * 1E6); + this.minLongitudeE6 = (int) (minLongitude * 1E6); + this.maxLatitudeE6 = (int) (maxLatitude * 1E6); + this.maxLongitudeE6 = (int) (maxLongitude * 1E6); + } - /** - * @param geoPoint - * the point whose coordinates should be checked. - * @return true if this BoundingBox contains the given GeoPoint, false - * otherwise. - */ - public boolean contains(GeoPoint geoPoint) { - return geoPoint.latitudeE6 <= maxLatitudeE6 - && geoPoint.latitudeE6 >= minLatitudeE6 - && geoPoint.longitudeE6 <= maxLongitudeE6 - && geoPoint.longitudeE6 >= minLongitudeE6; - } + /** + * @param geoPoint the point whose coordinates should be checked. + * @return true if this BoundingBox contains the given GeoPoint, false + * otherwise. + */ + public boolean contains(GeoPoint geoPoint) { + return geoPoint.latitudeE6 <= maxLatitudeE6 + && geoPoint.latitudeE6 >= minLatitudeE6 + && geoPoint.longitudeE6 <= maxLongitudeE6 + && geoPoint.longitudeE6 >= minLongitudeE6; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (!(obj instanceof BoundingBox)) { - return false; - } - BoundingBox other = (BoundingBox) obj; - if (maxLatitudeE6 != other.maxLatitudeE6) { - return false; - } else if (maxLongitudeE6 != other.maxLongitudeE6) { - return false; - } else if (minLatitudeE6 != other.minLatitudeE6) { - return false; - } else if (minLongitudeE6 != other.minLongitudeE6) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof BoundingBox)) { + return false; + } + BoundingBox other = (BoundingBox) obj; + if (maxLatitudeE6 != other.maxLatitudeE6) { + return false; + } else if (maxLongitudeE6 != other.maxLongitudeE6) { + return false; + } else if (minLatitudeE6 != other.minLatitudeE6) { + return false; + } else if (minLongitudeE6 != other.minLongitudeE6) { + return false; + } + return true; + } - /** - * @return the GeoPoint at the horizontal and vertical center of this - * BoundingBox. - */ - public GeoPoint getCenterPoint() { - int latitudeOffset = (maxLatitudeE6 - minLatitudeE6) / 2; - int longitudeOffset = (maxLongitudeE6 - minLongitudeE6) / 2; - return new GeoPoint(minLatitudeE6 + latitudeOffset, minLongitudeE6 - + longitudeOffset); - } + /** + * @return the GeoPoint at the horizontal and vertical center of this + * BoundingBox. + */ + public GeoPoint getCenterPoint() { + int latitudeOffset = (maxLatitudeE6 - minLatitudeE6) / 2; + int longitudeOffset = (maxLongitudeE6 - minLongitudeE6) / 2; + return new GeoPoint(minLatitudeE6 + latitudeOffset, minLongitudeE6 + + longitudeOffset); + } - /** - * @return the maximum latitude value of this BoundingBox in degrees. - */ - public double getMaxLatitude() { - return maxLatitudeE6 / CONVERSION_FACTOR; - } + /** + * @return the maximum latitude value of this BoundingBox in degrees. + */ + public double getMaxLatitude() { + return maxLatitudeE6 / CONVERSION_FACTOR; + } - /** - * @return the maximum longitude value of this BoundingBox in degrees. - */ - public double getMaxLongitude() { - return maxLongitudeE6 / CONVERSION_FACTOR; - } + /** + * @return the maximum longitude value of this BoundingBox in degrees. + */ + public double getMaxLongitude() { + return maxLongitudeE6 / CONVERSION_FACTOR; + } - /** - * @return the minimum latitude value of this BoundingBox in degrees. - */ - public double getMinLatitude() { - return minLatitudeE6 / CONVERSION_FACTOR; - } + /** + * @return the minimum latitude value of this BoundingBox in degrees. + */ + public double getMinLatitude() { + return minLatitudeE6 / CONVERSION_FACTOR; + } - /** - * @return the minimum longitude value of this BoundingBox in degrees. - */ - public double getMinLongitude() { - return minLongitudeE6 / CONVERSION_FACTOR; - } + /** + * @return the minimum longitude value of this BoundingBox in degrees. + */ + public double getMinLongitude() { + return minLongitudeE6 / CONVERSION_FACTOR; + } - @Override - public int hashCode() { - int result = 7; - result = 31 * result + maxLatitudeE6; - result = 31 * result + maxLongitudeE6; - result = 31 * result + minLatitudeE6; - result = 31 * result + minLongitudeE6; - return result; - } + @Override + public int hashCode() { + int result = 7; + result = 31 * result + maxLatitudeE6; + result = 31 * result + maxLongitudeE6; + result = 31 * result + minLatitudeE6; + result = 31 * result + minLongitudeE6; + return result; + } - @Override - public String toString() { - return new StringBuilder() - .append("BoundingBox [minLat=") - .append(minLatitudeE6) - .append(", minLon=") - .append(minLongitudeE6) - .append(", maxLat=") - .append(maxLatitudeE6) - .append(", maxLon=") - .append(maxLongitudeE6) - .append("]") - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("BoundingBox [minLat=") + .append(minLatitudeE6) + .append(", minLon=") + .append(minLongitudeE6) + .append(", maxLat=") + .append(maxLatitudeE6) + .append(", maxLon=") + .append(maxLongitudeE6) + .append("]") + .toString(); + } - public String format() { - return new StringBuilder() - .append(minLatitudeE6 / CONVERSION_FACTOR) - .append(',') - .append(minLongitudeE6 / CONVERSION_FACTOR) - .append(',') - .append(maxLatitudeE6 / CONVERSION_FACTOR) - .append(',') - .append(maxLongitudeE6 / CONVERSION_FACTOR) - .toString(); - } + public String format() { + return new StringBuilder() + .append(minLatitudeE6 / CONVERSION_FACTOR) + .append(',') + .append(minLongitudeE6 / CONVERSION_FACTOR) + .append(',') + .append(maxLatitudeE6 / CONVERSION_FACTOR) + .append(',') + .append(maxLongitudeE6 / CONVERSION_FACTOR) + .toString(); + } - /* code below is from osdmroid, @author Nicolas Gramlich */ - public static BoundingBox fromGeoPoints(final List partialPolyLine) { - int minLat = Integer.MAX_VALUE; - int minLon = Integer.MAX_VALUE; - int maxLat = Integer.MIN_VALUE; - int maxLon = Integer.MIN_VALUE; - for (final GeoPoint gp : partialPolyLine) { + /* code below is from osdmroid, @author Nicolas Gramlich */ + public static BoundingBox fromGeoPoints(final List partialPolyLine) { + int minLat = Integer.MAX_VALUE; + int minLon = Integer.MAX_VALUE; + int maxLat = Integer.MIN_VALUE; + int maxLon = Integer.MIN_VALUE; + for (final GeoPoint gp : partialPolyLine) { - minLat = Math.min(minLat, gp.latitudeE6); - minLon = Math.min(minLon, gp.longitudeE6); - maxLat = Math.max(maxLat, gp.latitudeE6); - maxLon = Math.max(maxLon, gp.longitudeE6); - } + minLat = Math.min(minLat, gp.latitudeE6); + minLon = Math.min(minLon, gp.longitudeE6); + maxLat = Math.max(maxLat, gp.latitudeE6); + maxLon = Math.max(maxLon, gp.longitudeE6); + } - return new BoundingBox(minLat, minLon, maxLat, maxLon); - } + return new BoundingBox(minLat, minLon, maxLat, maxLon); + } } diff --git a/vtm/src/org/oscim/core/Box.java b/vtm/src/org/oscim/core/Box.java index e27c9758..14346919 100644 --- a/vtm/src/org/oscim/core/Box.java +++ b/vtm/src/org/oscim/core/Box.java @@ -21,172 +21,174 @@ package org.oscim.core; */ public class Box { - public double xmin; - public double xmax; - public double ymin; - public double ymax; + public double xmin; + public double xmax; + public double ymin; + public double ymax; - /** - * Instantiates a new Box with all values being 0. - */ - public Box() { + /** + * Instantiates a new Box with all values being 0. + */ + public Box() { - } + } - /** - * Instantiates a new Box. - * - * @param xmin the min x - * @param ymin the min y - * @param xmax the max x - * @param ymax the max y - */ - public Box(double xmin, double ymin, double xmax, double ymax) { - if (xmin > xmax || ymin > ymax) - throw new IllegalArgumentException("min > max !"); - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - } + /** + * Instantiates a new Box. + * + * @param xmin the min x + * @param ymin the min y + * @param xmax the max x + * @param ymax the max y + */ + public Box(double xmin, double ymin, double xmax, double ymax) { + if (xmin > xmax || ymin > ymax) + throw new IllegalArgumentException("min > max !"); + this.xmin = xmin; + this.ymin = ymin; + this.xmax = xmax; + this.ymax = ymax; + } - public Box(Box bbox) { - this.xmin = bbox.xmin; - this.ymin = bbox.ymin; - this.xmax = bbox.xmax; - this.ymax = bbox.ymax; - } + public Box(Box bbox) { + this.xmin = bbox.xmin; + this.ymin = bbox.ymin; + this.xmax = bbox.xmax; + this.ymax = bbox.ymax; + } - /** - * Check if Box contains point defined by coordinates x and y. - * - * @param x the x ordinate - * @param y the y ordinate - * @return true, if point is inside box. - */ - public boolean contains(double x, double y) { - return (x >= xmin - && x <= xmax - && y >= ymin - && y <= ymax); - } + /** + * Check if Box contains point defined by coordinates x and y. + * + * @param x the x ordinate + * @param y the y ordinate + * @return true, if point is inside box. + */ + public boolean contains(double x, double y) { + return (x >= xmin + && x <= xmax + && y >= ymin + && y <= ymax); + } - /** - * Check if Box contains Point. - */ - public boolean contains(Point p) { - return (p.x >= xmin - && p.x <= xmax - && p.y >= ymin - && p.y <= ymax); - } + /** + * Check if Box contains Point. + */ + public boolean contains(Point p) { + return (p.x >= xmin + && p.x <= xmax + && p.y >= ymin + && p.y <= ymax); + } - /** - * Check if this Box is inside box. - */ - public boolean inside(Box box) { - return xmin >= box.xmin - && xmax <= box.xmax - && ymin >= box.ymin - && ymax <= box.ymax; - } + /** + * Check if this Box is inside box. + */ + public boolean inside(Box box) { + return xmin >= box.xmin + && xmax <= box.xmax + && ymin >= box.ymin + && ymax <= box.ymax; + } - public double getWidth() { - return xmax - xmin; - } + public double getWidth() { + return xmax - xmin; + } - public double getHeight() { - return ymax - ymin; - } + public double getHeight() { + return ymax - ymin; + } - public boolean overlap(Box other) { - return !(xmin > other.xmax - || xmax < other.xmin - || ymin > other.ymax - || ymax < other.ymin); - } + public boolean overlap(Box other) { + return !(xmin > other.xmax + || xmax < other.xmin + || ymin > other.ymax + || ymax < other.ymin); + } - @Override - public String toString() { - return "[" + xmin + ',' + ymin + ',' + xmax + ',' + ymax + ']'; - } + @Override + public String toString() { + return "[" + xmin + ',' + ymin + ',' + xmax + ',' + ymax + ']'; + } - public static Box createSafe(double x1, double y1, double x2, double y2) { - return new Box(x1 < x2 ? x1 : x2, - y1 < y2 ? y1 : y2, - x1 > x2 ? x1 : x2, - y1 > y2 ? y1 : y2); - } + public static Box createSafe(double x1, double y1, double x2, double y2) { + return new Box(x1 < x2 ? x1 : x2, + y1 < y2 ? y1 : y2, + x1 > x2 ? x1 : x2, + y1 > y2 ? y1 : y2); + } - public void setExtents(float[] points) { - float x1, y1, x2, y2; - x1 = x2 = points[0]; - y1 = y2 = points[1]; + public void setExtents(float[] points) { + float x1, y1, x2, y2; + x1 = x2 = points[0]; + y1 = y2 = points[1]; - for (int i = 2, n = points.length; i < n; i += 2) { - float x = points[i]; - if (x < x1) - x1 = x; - else if (x > x2) - x2 = x; + for (int i = 2, n = points.length; i < n; i += 2) { + float x = points[i]; + if (x < x1) + x1 = x; + else if (x > x2) + x2 = x; - float y = points[i + 1]; - if (y < y1) - y1 = y; - else if (y > y2) - y2 = y; - } - this.xmin = x1; - this.ymin = y1; - this.xmax = x2; - this.ymax = y2; - } + float y = points[i + 1]; + if (y < y1) + y1 = y; + else if (y > y2) + y2 = y; + } + this.xmin = x1; + this.ymin = y1; + this.xmax = x2; + this.ymax = y2; + } - public void add(Box bbox) { - if (bbox.xmin < xmin) - xmin = bbox.xmin; - if (bbox.ymin < ymin) - ymin = bbox.ymin; - if (bbox.xmax > xmax) - xmax = bbox.xmax; - if (bbox.ymax > ymax) - ymax = bbox.ymax; - } + public void add(Box bbox) { + if (bbox.xmin < xmin) + xmin = bbox.xmin; + if (bbox.ymin < ymin) + ymin = bbox.ymin; + if (bbox.xmax > xmax) + xmax = bbox.xmax; + if (bbox.ymax > ymax) + ymax = bbox.ymax; + } - public void add(double x, double y) { - if (x < xmin) - xmin = x; - if (y < ymin) - ymin = y; - if (x > xmax) - xmax = x; - if (y > ymax) - ymax = y; - } + public void add(double x, double y) { + if (x < xmin) + xmin = x; + if (y < ymin) + ymin = y; + if (x > xmax) + xmax = x; + if (y > ymax) + ymax = y; + } - public void translate(double dx, double dy) { - xmin += dx; - xmax += dx; - ymin += dy; - ymax += dy; - } + public void translate(double dx, double dy) { + xmin += dx; + xmax += dx; + ymin += dy; + ymax += dy; + } - public void scale(double d) { - xmin *= d; - xmax *= d; - ymin *= d; - ymax *= d; - } + public void scale(double d) { + xmin *= d; + xmax *= d; + ymin *= d; + ymax *= d; + } - /** convrt map coordinates to lat/lon. */ - public void map2mercator() { - double minLon = MercatorProjection.toLongitude(xmin); - double maxLon = MercatorProjection.toLongitude(xmax); - double minLat = MercatorProjection.toLatitude(ymax); - double maxLat = MercatorProjection.toLatitude(ymin); - xmin = minLon; - xmax = maxLon; - ymin = minLat; - ymax = maxLat; - } + /** + * convrt map coordinates to lat/lon. + */ + public void map2mercator() { + double minLon = MercatorProjection.toLongitude(xmin); + double maxLon = MercatorProjection.toLongitude(xmax); + double minLat = MercatorProjection.toLatitude(ymax); + double maxLat = MercatorProjection.toLatitude(ymin); + xmin = minLon; + xmax = maxLon; + ymin = minLat; + ymax = maxLat; + } } diff --git a/vtm/src/org/oscim/core/GeoPoint.java b/vtm/src/org/oscim/core/GeoPoint.java index c9d28f8f..25e18ac9 100644 --- a/vtm/src/org/oscim/core/GeoPoint.java +++ b/vtm/src/org/oscim/core/GeoPoint.java @@ -24,176 +24,171 @@ import org.oscim.utils.FastMath; * coordinates. */ public class GeoPoint implements Comparable { - /** - * Conversion factor from degrees to microdegrees. - */ - private static final double CONVERSION_FACTOR = 1000000d; + /** + * Conversion factor from degrees to microdegrees. + */ + private static final double CONVERSION_FACTOR = 1000000d; - /** - * The latitude value of this GeoPoint in microdegrees (degrees * 10^6). - */ - public final int latitudeE6; + /** + * The latitude value of this GeoPoint in microdegrees (degrees * 10^6). + */ + public final int latitudeE6; - /** - * The longitude value of this GeoPoint in microdegrees (degrees * 10^6). - */ - public final int longitudeE6; + /** + * The longitude value of this GeoPoint in microdegrees (degrees * 10^6). + */ + public final int longitudeE6; - /** - * The hash code of this object. - */ - private int hashCodeValue = 0; + /** + * The hash code of this object. + */ + private int hashCodeValue = 0; - /** - * @param lat - * the latitude in degrees, will be limited to the possible - * latitude range. - * @param lon - * the longitude in degrees, will be limited to the possible - * longitude range. - */ - public GeoPoint(double lat, double lon) { - lat = FastMath.clamp(lat, - MercatorProjection.LATITUDE_MIN, - MercatorProjection.LATITUDE_MAX); - this.latitudeE6 = (int) (lat * CONVERSION_FACTOR); - lon = FastMath.clamp(lon, - MercatorProjection.LONGITUDE_MIN, - MercatorProjection.LONGITUDE_MAX); - this.longitudeE6 = (int) (lon * CONVERSION_FACTOR); - } + /** + * @param lat the latitude in degrees, will be limited to the possible + * latitude range. + * @param lon the longitude in degrees, will be limited to the possible + * longitude range. + */ + public GeoPoint(double lat, double lon) { + lat = FastMath.clamp(lat, + MercatorProjection.LATITUDE_MIN, + MercatorProjection.LATITUDE_MAX); + this.latitudeE6 = (int) (lat * CONVERSION_FACTOR); + lon = FastMath.clamp(lon, + MercatorProjection.LONGITUDE_MIN, + MercatorProjection.LONGITUDE_MAX); + this.longitudeE6 = (int) (lon * CONVERSION_FACTOR); + } - /** - * @param latitudeE6 - * the latitude in microdegrees (degrees * 10^6), will be limited - * to the possible latitude range. - * @param longitudeE6 - * the longitude in microdegrees (degrees * 10^6), will be - * limited to the possible longitude range. - */ - public GeoPoint(int latitudeE6, int longitudeE6) { - this(latitudeE6 / CONVERSION_FACTOR, longitudeE6 / CONVERSION_FACTOR); - } + /** + * @param latitudeE6 the latitude in microdegrees (degrees * 10^6), will be limited + * to the possible latitude range. + * @param longitudeE6 the longitude in microdegrees (degrees * 10^6), will be + * limited to the possible longitude range. + */ + public GeoPoint(int latitudeE6, int longitudeE6) { + this(latitudeE6 / CONVERSION_FACTOR, longitudeE6 / CONVERSION_FACTOR); + } - public void project(Point out) { - out.x = MercatorProjection.longitudeToX(this.longitudeE6 / CONVERSION_FACTOR); - out.y = MercatorProjection.latitudeToY(this.latitudeE6 / CONVERSION_FACTOR); - } + public void project(Point out) { + out.x = MercatorProjection.longitudeToX(this.longitudeE6 / CONVERSION_FACTOR); + out.y = MercatorProjection.latitudeToY(this.latitudeE6 / CONVERSION_FACTOR); + } - @Override - public int compareTo(GeoPoint geoPoint) { - if (this.longitudeE6 > geoPoint.longitudeE6) { - return 1; - } else if (this.longitudeE6 < geoPoint.longitudeE6) { - return -1; - } else if (this.latitudeE6 > geoPoint.latitudeE6) { - return 1; - } else if (this.latitudeE6 < geoPoint.latitudeE6) { - return -1; - } - return 0; - } + @Override + public int compareTo(GeoPoint geoPoint) { + if (this.longitudeE6 > geoPoint.longitudeE6) { + return 1; + } else if (this.longitudeE6 < geoPoint.longitudeE6) { + return -1; + } else if (this.latitudeE6 > geoPoint.latitudeE6) { + return 1; + } else if (this.latitudeE6 < geoPoint.latitudeE6) { + return -1; + } + return 0; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (!(obj instanceof GeoPoint)) { - return false; - } - GeoPoint other = (GeoPoint) obj; - if (this.latitudeE6 != other.latitudeE6) { - return false; - } else if (this.longitudeE6 != other.longitudeE6) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof GeoPoint)) { + return false; + } + GeoPoint other = (GeoPoint) obj; + if (this.latitudeE6 != other.latitudeE6) { + return false; + } else if (this.longitudeE6 != other.longitudeE6) { + return false; + } + return true; + } - /** - * @return the latitude value of this GeoPoint in degrees. - */ - public double getLatitude() { - return this.latitudeE6 / CONVERSION_FACTOR; - } + /** + * @return the latitude value of this GeoPoint in degrees. + */ + public double getLatitude() { + return this.latitudeE6 / CONVERSION_FACTOR; + } - /** - * @return the longitude value of this GeoPoint in degrees. - */ - public double getLongitude() { - return this.longitudeE6 / CONVERSION_FACTOR; - } + /** + * @return the longitude value of this GeoPoint in degrees. + */ + public double getLongitude() { + return this.longitudeE6 / CONVERSION_FACTOR; + } - @Override - public int hashCode() { - if (this.hashCodeValue == 0) - this.hashCodeValue = calculateHashCode(); + @Override + public int hashCode() { + if (this.hashCodeValue == 0) + this.hashCodeValue = calculateHashCode(); - return this.hashCodeValue; - } + return this.hashCodeValue; + } - @Override - public String toString() { - return new StringBuilder() - .append("[lat=") - .append(this.getLatitude()) - .append(",lon=") - .append(this.getLongitude()) - .append("]") - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("[lat=") + .append(this.getLatitude()) + .append(",lon=") + .append(this.getLongitude()) + .append("]") + .toString(); + } - /** - * @return the hash code of this object. - */ - private int calculateHashCode() { - int result = 7; - result = 31 * result + this.latitudeE6; - result = 31 * result + this.longitudeE6; - return result; - } + /** + * @return the hash code of this object. + */ + private int calculateHashCode() { + int result = 7; + result = 31 * result + this.latitudeE6; + result = 31 * result + this.longitudeE6; + return result; + } - // =========================================================== - // Methods from osmdroid - // Copyright 2012 osmdroid authors: Nicolas Gramlich, - // Theodore Hong - // =========================================================== + // =========================================================== + // Methods from osmdroid + // Copyright 2012 osmdroid authors: Nicolas Gramlich, + // Theodore Hong + // =========================================================== - public static final float DEG2RAD = (float) (Math.PI / 180.0); - public static final float RAD2DEG = (float) (180.0 / Math.PI); - // http://en.wikipedia.org/wiki/Earth_radius#Equatorial_radius - public static final int RADIUS_EARTH_METERS = 6378137; + public static final float DEG2RAD = (float) (Math.PI / 180.0); + public static final float RAD2DEG = (float) (180.0 / Math.PI); + // http://en.wikipedia.org/wiki/Earth_radius#Equatorial_radius + public static final int RADIUS_EARTH_METERS = 6378137; - /** - * @see "http://www.geocities.com/DrChengalva/GPSDistance.html" - * @param other - * ... - * @return distance in meters - */ - public double distanceTo(GeoPoint other) { - return distance(latitudeE6 / 1E6, - longitudeE6 / 1E6, - other.latitudeE6 / 1E6, - other.longitudeE6 / 1E6); - } + /** + * @param other ... + * @return distance in meters + * @see "http://www.geocities.com/DrChengalva/GPSDistance.html" + */ + public double distanceTo(GeoPoint other) { + return distance(latitudeE6 / 1E6, + longitudeE6 / 1E6, + other.latitudeE6 / 1E6, + other.longitudeE6 / 1E6); + } - public static double distance(double lat1, double lon1, double lat2, double lon2) { + public static double distance(double lat1, double lon1, double lat2, double lon2) { - double a1 = DEG2RAD * lat1; - double a2 = DEG2RAD * lon1; - double b1 = DEG2RAD * lat2; - double b2 = DEG2RAD * lon2; + double a1 = DEG2RAD * lat1; + double a2 = DEG2RAD * lon1; + double b1 = DEG2RAD * lat2; + double b2 = DEG2RAD * lon2; - double cosa1 = Math.cos(a1); - double cosb1 = Math.cos(b1); + double cosa1 = Math.cos(a1); + double cosb1 = Math.cos(b1); - double t1 = cosa1 * Math.cos(a2) * cosb1 * Math.cos(b2); - double t2 = cosa1 * Math.sin(a2) * cosb1 * Math.sin(b2); + double t1 = cosa1 * Math.cos(a2) * cosb1 * Math.cos(b2); + double t2 = cosa1 * Math.sin(a2) * cosb1 * Math.sin(b2); - double t3 = Math.sin(a1) * Math.sin(b1); + double t3 = Math.sin(a1) * Math.sin(b1); - double tt = Math.acos(t1 + t2 + t3); + double tt = Math.acos(t1 + t2 + t3); - return (RADIUS_EARTH_METERS * tt); - } + return (RADIUS_EARTH_METERS * tt); + } } diff --git a/vtm/src/org/oscim/core/GeometryBuffer.java b/vtm/src/org/oscim/core/GeometryBuffer.java index 40319b1a..d9a62f76 100644 --- a/vtm/src/org/oscim/core/GeometryBuffer.java +++ b/vtm/src/org/oscim/core/GeometryBuffer.java @@ -20,431 +20,442 @@ package org.oscim.core; * - check indexPos < Short.Max * - should make internals private, maybe */ + /** * The GeometryBuffer class holds temporary geometry data for processing. * Only One geometry type can be set at a time. Use 'clear()' to reset the * internal state. - *

+ *

* 'points[]' holds interleaved x,y coordinates - *

+ *

* 'index[]' is used to store number of points within a geometry and encode * multi-linestrings and (multi-)polygons. */ public class GeometryBuffer { - private final static int GROW_INDICES = 64; - private final static int GROW_POINTS = 512; + private final static int GROW_INDICES = 64; + private final static int GROW_POINTS = 512; - /** - * The Enum GeometryType. - */ - public enum GeometryType { - NONE(0), - POINT(1), - LINE(2), - POLY(3), - TRIS(4); + /** + * The Enum GeometryType. + */ + public enum GeometryType { + NONE(0), + POINT(1), + LINE(2), + POLY(3), + TRIS(4); - private GeometryType(int type) { - nativeInt = type; - } + private GeometryType(int type) { + nativeInt = type; + } - public final int nativeInt; - } + public final int nativeInt; + } - /** The points. */ - public float[] points; + /** + * The points. + */ + public float[] points; - /** The indexes. */ - public int[] index; + /** + * The indexes. + */ + public int[] index; - /** The current index position. */ - public int indexPos; + /** + * The current index position. + */ + public int indexPos; - /** The current position in points array. */ - public int pointPos; + /** + * The current position in points array. + */ + public int pointPos; - /** The current geometry type. */ - public GeometryType type; + /** + * The current geometry type. + */ + public GeometryType type; - private PointF mTmpPoint = new PointF(); - private int pointLimit; + private PointF mTmpPoint = new PointF(); + private int pointLimit; - public GeometryBuffer() { - this(32, 4); - } + public GeometryBuffer() { + this(32, 4); + } - /** - * Instantiates a new geometry buffer. - * - * @param numPoints the num of expected points - * @param numIndices the num of expected indices - */ - public GeometryBuffer(int numPoints, int numIndices) { - this(new float[numPoints * 2], new int[numIndices]); - } + /** + * Instantiates a new geometry buffer. + * + * @param numPoints the num of expected points + * @param numIndices the num of expected indices + */ + public GeometryBuffer(int numPoints, int numIndices) { + this(new float[numPoints * 2], new int[numIndices]); + } - /** - * Instantiates a new geometry buffer. - * - * @param points the points - * @param index the index - */ - public GeometryBuffer(float[] points, int[] index) { - if (points == null) - points = new float[GROW_POINTS]; - if (index == null) - index = new int[GROW_INDICES]; + /** + * Instantiates a new geometry buffer. + * + * @param points the points + * @param index the index + */ + public GeometryBuffer(float[] points, int[] index) { + if (points == null) + points = new float[GROW_POINTS]; + if (index == null) + index = new int[GROW_INDICES]; - this.points = points; - this.index = index; - this.type = GeometryType.NONE; - this.indexPos = 0; - this.pointPos = 0; - this.pointLimit = points.length - 2; - } + this.points = points; + this.index = index; + this.type = GeometryType.NONE; + this.indexPos = 0; + this.pointPos = 0; + this.pointLimit = points.length - 2; + } - /** - * @param out PointF to set coordinates to. - * @return when out is null a temporary PointF is - * returned which belongs to GeometryBuffer. - */ - public void getPoint(int i, PointF out) { - out.x = points[(i << 1)]; - out.y = points[(i << 1) + 1]; - } + /** + * @param out PointF to set coordinates to. + * @return when out is null a temporary PointF is + * returned which belongs to GeometryBuffer. + */ + public void getPoint(int i, PointF out) { + out.x = points[(i << 1)]; + out.y = points[(i << 1) + 1]; + } - public float getPointX(int i) { - return points[(i << 1)]; - } + public float getPointX(int i) { + return points[(i << 1)]; + } - public float getPointY(int i) { - return points[(i << 1) + 1]; - } + public float getPointY(int i) { + return points[(i << 1) + 1]; + } - /** - * @return PointF belongs to GeometryBuffer. - */ - public PointF getPoint(int i) { - PointF out = mTmpPoint; - out.x = points[(i << 1)]; - out.y = points[(i << 1) + 1]; - return out; - } + /** + * @return PointF belongs to GeometryBuffer. + */ + public PointF getPoint(int i) { + PointF out = mTmpPoint; + out.x = points[(i << 1)]; + out.y = points[(i << 1) + 1]; + return out; + } - public int getNumPoints() { - return pointPos >> 1; - } + public int getNumPoints() { + return pointPos >> 1; + } - /** - * Reset buffer. - */ - public GeometryBuffer clear() { - index[0] = 0; - indexPos = 0; - pointPos = 0; - type = GeometryType.NONE; - return this; - } + /** + * Reset buffer. + */ + public GeometryBuffer clear() { + index[0] = 0; + indexPos = 0; + pointPos = 0; + type = GeometryType.NONE; + return this; + } - /** - * Adds a point with the coordinate x, y. - * - * @param x the x ordinate - * @param y the y ordinate - */ - public GeometryBuffer addPoint(float x, float y) { - if (pointPos > pointLimit) - ensurePointSize((pointPos >> 1) + 1, true); + /** + * Adds a point with the coordinate x, y. + * + * @param x the x ordinate + * @param y the y ordinate + */ + public GeometryBuffer addPoint(float x, float y) { + if (pointPos > pointLimit) + ensurePointSize((pointPos >> 1) + 1, true); - points[pointPos++] = x; - points[pointPos++] = y; + points[pointPos++] = x; + points[pointPos++] = y; - index[indexPos] += 2; - return this; - } + index[indexPos] += 2; + return this; + } - public boolean isPoly() { - return type == GeometryType.POLY; - } + public boolean isPoly() { + return type == GeometryType.POLY; + } - public boolean isLine() { - return type == GeometryType.LINE; - } + public boolean isLine() { + return type == GeometryType.LINE; + } - public boolean isPoint() { - return type == GeometryType.POINT; - } + public boolean isPoint() { + return type == GeometryType.POINT; + } - /** - * Sets the point x,y at position pos. - * - * @param pos the pos - * @param x the x ordinate - * @param y the y ordinate - */ - public void setPoint(int pos, float x, float y) { - points[(pos << 1) + 0] = x; - points[(pos << 1) + 1] = y; - } + /** + * Sets the point x,y at position pos. + * + * @param pos the pos + * @param x the x ordinate + * @param y the y ordinate + */ + public void setPoint(int pos, float x, float y) { + points[(pos << 1) + 0] = x; + points[(pos << 1) + 1] = y; + } - /** - * Set geometry type for points. - */ - public void startPoints() { - setOrCheckMode(GeometryType.POINT); - } + /** + * Set geometry type for points. + */ + public void startPoints() { + setOrCheckMode(GeometryType.POINT); + } - /** - * Start a new line. Sets geometry type for lines. - */ - public GeometryBuffer startLine() { - setOrCheckMode(GeometryType.LINE); + /** + * Start a new line. Sets geometry type for lines. + */ + public GeometryBuffer startLine() { + setOrCheckMode(GeometryType.LINE); /* ignore */ - if (index[indexPos] > 0) { + if (index[indexPos] > 0) { /* start next */ - if ((index[0] >= 0) && (++indexPos >= index.length)) - ensureIndexSize(indexPos, true); + if ((index[0] >= 0) && (++indexPos >= index.length)) + ensureIndexSize(indexPos, true); /* initialize with zero points */ - index[indexPos] = 0; - } + index[indexPos] = 0; + } /* set new end marker */ - if (index.length > indexPos + 1) - index[indexPos + 1] = -1; - return this; - } + if (index.length > indexPos + 1) + index[indexPos + 1] = -1; + return this; + } - /** - * Start a new polygon. Sets geometry type for polygons. - */ - public GeometryBuffer startPolygon() { - boolean start = (type == GeometryType.NONE); - setOrCheckMode(GeometryType.POLY); + /** + * Start a new polygon. Sets geometry type for polygons. + */ + public GeometryBuffer startPolygon() { + boolean start = (type == GeometryType.NONE); + setOrCheckMode(GeometryType.POLY); - if ((indexPos + 3) > index.length) - ensureIndexSize(indexPos + 2, true); + if ((indexPos + 3) > index.length) + ensureIndexSize(indexPos + 2, true); - if (!start && index[indexPos] != 0) { - /* end polygon */ - index[++indexPos] = 0; + if (!start && index[indexPos] != 0) { + /* end polygon */ + index[++indexPos] = 0; /* next polygon start */ - indexPos++; - } + indexPos++; + } /* initialize with zero points */ - index[indexPos] = 0; + index[indexPos] = 0; /* set new end marker */ - if (index.length > indexPos + 1) - index[indexPos + 1] = -1; + if (index.length > indexPos + 1) + index[indexPos + 1] = -1; - return this; - } + return this; + } - /** - * Starts a new polygon hole (inner ring). - */ - public void startHole() { - checkMode(GeometryType.POLY); + /** + * Starts a new polygon hole (inner ring). + */ + public void startHole() { + checkMode(GeometryType.POLY); - if ((indexPos + 2) > index.length) - ensureIndexSize(indexPos + 1, true); + if ((indexPos + 2) > index.length) + ensureIndexSize(indexPos + 1, true); /* initialize with zero points */ - index[++indexPos] = 0; + index[++indexPos] = 0; /* set new end marker */ - if (index.length > indexPos + 1) - index[indexPos + 1] = -1; - } + if (index.length > indexPos + 1) + index[indexPos + 1] = -1; + } - public GeometryBuffer translate(float dx, float dy) { - for (int i = 0; i < pointPos; i += 2) { - points[i] += dx; - points[i + 1] += dy; - } - return this; - } + public GeometryBuffer translate(float dx, float dy) { + for (int i = 0; i < pointPos; i += 2) { + points[i] += dx; + points[i + 1] += dy; + } + return this; + } - public GeometryBuffer scale(float scaleX, float scaleY) { - for (int i = 0; i < pointPos; i += 2) { - points[i] *= scaleX; - points[i + 1] *= scaleY; - } - return this; - } + public GeometryBuffer scale(float scaleX, float scaleY) { + for (int i = 0; i < pointPos; i += 2) { + points[i] *= scaleX; + points[i + 1] *= scaleY; + } + return this; + } - /** - * Ensure that 'points' array can hold the number of points. - * - * @param size the number of points to hold - * @param copy the the current data when array is reallocated - * @return the float[] array holding current coordinates - */ - public float[] ensurePointSize(int size, boolean copy) { - if (size * 2 < points.length) - return points; + /** + * Ensure that 'points' array can hold the number of points. + * + * @param size the number of points to hold + * @param copy the the current data when array is reallocated + * @return the float[] array holding current coordinates + */ + public float[] ensurePointSize(int size, boolean copy) { + if (size * 2 < points.length) + return points; - size = size * 2 + GROW_POINTS; + size = size * 2 + GROW_POINTS; - float[] newPoints = new float[size]; - if (copy) - System.arraycopy(points, 0, newPoints, 0, points.length); + float[] newPoints = new float[size]; + if (copy) + System.arraycopy(points, 0, newPoints, 0, points.length); - points = newPoints; - pointLimit = size - 2; + points = newPoints; + pointLimit = size - 2; - return points; - } + return points; + } - /** - * Ensure index size. - * - * @param size the size - * @param copy the copy - * @return the short[] array holding current index - */ - public int[] ensureIndexSize(int size, boolean copy) { - if (size < index.length) - return index; + /** + * Ensure index size. + * + * @param size the size + * @param copy the copy + * @return the short[] array holding current index + */ + public int[] ensureIndexSize(int size, boolean copy) { + if (size < index.length) + return index; - int[] newIndex = new int[size + GROW_INDICES]; - if (copy) - System.arraycopy(index, 0, newIndex, 0, index.length); + int[] newIndex = new int[size + GROW_INDICES]; + if (copy) + System.arraycopy(index, 0, newIndex, 0, index.length); - index = newIndex; + index = newIndex; - return index; - } + return index; + } - private void setOrCheckMode(GeometryType m) { - if (type == m) - return; + private void setOrCheckMode(GeometryType m) { + if (type == m) + return; - if (type != GeometryType.NONE) - throw new IllegalArgumentException("not cleared " + m + "<>" + type); + if (type != GeometryType.NONE) + throw new IllegalArgumentException("not cleared " + m + "<>" + type); - type = m; - } + type = m; + } - private void checkMode(GeometryType m) { - if (type != m) - throw new IllegalArgumentException("not cleared " + m + "<>" + type); - } + private void checkMode(GeometryType m) { + if (type != m) + throw new IllegalArgumentException("not cleared " + m + "<>" + type); + } - public void addPoint(Point p) { - addPoint((float) p.x, (float) p.y); - } + public void addPoint(Point p) { + addPoint((float) p.x, (float) p.y); + } - public void addPoint(PointF p) { - addPoint(p.x, p.y); - } + public void addPoint(PointF p) { + addPoint(p.x, p.y); + } - /** - * Remove points with distance less than minSqDist - * - * TODO could avoid superfluous copying - * - * @param minSqDist - * @param keepLines keep endpoint when line would - * otherwise collapse into a single point - */ - public void simplify(float minSqDist, boolean keepLines) { - int outPos = 0; - int inPos = 0; - for (int idx = 0; idx < index.length; idx++) { - if (index[idx] < 0) - break; - if (index[idx] == 0) - continue; + /** + * Remove points with distance less than minSqDist + *

+ * TODO could avoid superfluous copying + * + * @param minSqDist + * @param keepLines keep endpoint when line would + * otherwise collapse into a single point + */ + public void simplify(float minSqDist, boolean keepLines) { + int outPos = 0; + int inPos = 0; + for (int idx = 0; idx < index.length; idx++) { + if (index[idx] < 0) + break; + if (index[idx] == 0) + continue; - int first = inPos; - float px = points[inPos++]; - float py = points[inPos++]; + int first = inPos; + float px = points[inPos++]; + float py = points[inPos++]; /* add first point */ - points[outPos++] = px; - points[outPos++] = py; - int cnt = 2; + points[outPos++] = px; + points[outPos++] = py; + int cnt = 2; - for (int pt = 2, end = index[idx]; pt < end; pt += 2) { - float cx = points[inPos++]; - float cy = points[inPos++]; - float dx = cx - px; - float dy = cy - py; + for (int pt = 2, end = index[idx]; pt < end; pt += 2) { + float cx = points[inPos++]; + float cy = points[inPos++]; + float dx = cx - px; + float dy = cy - py; - if ((dx * dx + dy * dy) < minSqDist) { - if (!keepLines || (pt < end - 2)) - continue; - } - px = cx; - py = cy; - points[outPos++] = cx; - points[outPos++] = cy; - cnt += 2; - } + if ((dx * dx + dy * dy) < minSqDist) { + if (!keepLines || (pt < end - 2)) + continue; + } + px = cx; + py = cy; + points[outPos++] = cx; + points[outPos++] = cy; + cnt += 2; + } - if ((type == GeometryType.POLY) && - (points[first] == px) && - (points[first + 1] == py)) { - /* remove identical start/end point */ - cnt -= 2; - outPos -= 2; - } - index[idx] = cnt; - } - } + if ((type == GeometryType.POLY) && + (points[first] == px) && + (points[first + 1] == py)) { + /* remove identical start/end point */ + cnt -= 2; + outPos -= 2; + } + index[idx] = cnt; + } + } - public String toString() { - StringBuffer sb = new StringBuffer(); - int o = 0; - for (int i = 0; i < index.length; i++) { - if (index[i] < 0) - break; - if (index[i] == 0) - continue; - sb.append(":"); - sb.append(index[i]); - sb.append('\n'); + public String toString() { + StringBuffer sb = new StringBuffer(); + int o = 0; + for (int i = 0; i < index.length; i++) { + if (index[i] < 0) + break; + if (index[i] == 0) + continue; + sb.append(":"); + sb.append(index[i]); + sb.append('\n'); - for (int j = 0; j < index[i]; j += 2) { - sb.append('[') - .append(points[o + j]) - .append(',') - .append(points[o + j + 1]) - .append(']'); + for (int j = 0; j < index[i]; j += 2) { + sb.append('[') + .append(points[o + j]) + .append(',') + .append(points[o + j + 1]) + .append(']'); - if (j % 4 == 0) - sb.append('\n'); - } - sb.append('\n'); - o += index[i]; - } - return sb.toString(); - } + if (j % 4 == 0) + sb.append('\n'); + } + sb.append('\n'); + o += index[i]; + } + return sb.toString(); + } - public static GeometryBuffer makeCircle(float x, float y, - float radius, int segments) { - GeometryBuffer g = new GeometryBuffer(segments, 1); - makeCircle(g, x, y, radius, segments); - return g; - } + public static GeometryBuffer makeCircle(float x, float y, + float radius, int segments) { + GeometryBuffer g = new GeometryBuffer(segments, 1); + makeCircle(g, x, y, radius, segments); + return g; + } - public static GeometryBuffer makeCircle(GeometryBuffer g, - float x, float y, float radius, int segments) { - g.clear(); - g.startPolygon(); - for (int i = 0; i < segments; i++) { - double rad = Math.toRadians(i * (360f / segments)); + public static GeometryBuffer makeCircle(GeometryBuffer g, + float x, float y, float radius, int segments) { + g.clear(); + g.startPolygon(); + for (int i = 0; i < segments; i++) { + double rad = Math.toRadians(i * (360f / segments)); - g.addPoint((float) (x + Math.cos(rad) * radius), - (float) (y + Math.sin(rad) * radius)); - } - return g; - } + g.addPoint((float) (x + Math.cos(rad) * radius), + (float) (y + Math.sin(rad) * radius)); + } + return g; + } } diff --git a/vtm/src/org/oscim/core/MapElement.java b/vtm/src/org/oscim/core/MapElement.java index 81331e3c..fd2187f6 100644 --- a/vtm/src/org/oscim/core/MapElement.java +++ b/vtm/src/org/oscim/core/MapElement.java @@ -26,34 +26,36 @@ package org.oscim.core; */ public class MapElement extends GeometryBuffer { - /** layer of the element (0-10) overrides the theme drawing order */ - public int layer; + /** + * layer of the element (0-10) overrides the theme drawing order + */ + public int layer; - public final TagSet tags = new TagSet(); + public final TagSet tags = new TagSet(); - public MapElement() { - super(1024, 16); - } + public MapElement() { + super(1024, 16); + } - public MapElement(int points, int indices) { - super(points, indices); - } + public MapElement(int points, int indices) { + super(points, indices); + } - public void setLayer(int layer) { - this.layer = layer; - } + public void setLayer(int layer) { + this.layer = layer; + } - @Override - public MapElement clear() { - layer = 5; - super.clear(); - return this; - } + @Override + public MapElement clear() { + layer = 5; + super.clear(); + return this; + } - @Override - public String toString() { + @Override + public String toString() { - return tags.toString() + '\n' + super.toString() + '\n'; + return tags.toString() + '\n' + super.toString() + '\n'; - } + } } diff --git a/vtm/src/org/oscim/core/MapPosition.java b/vtm/src/org/oscim/core/MapPosition.java index 34d39a52..d595fd6d 100644 --- a/vtm/src/org/oscim/core/MapPosition.java +++ b/vtm/src/org/oscim/core/MapPosition.java @@ -21,183 +21,191 @@ import org.oscim.utils.FastMath; public class MapPosition { - /** Projected position x 0..1 */ - public double x; + /** + * Projected position x 0..1 + */ + public double x; - /** Projected position y 0..1 */ - public double y; + /** + * Projected position y 0..1 + */ + public double y; - /** - * Absolute scale - * - use setScale() to modify - */ - public double scale; + /** + * Absolute scale + * - use setScale() to modify + */ + public double scale; - /** Rotation angle */ - public float bearing; + /** + * Rotation angle + */ + public float bearing; - /** Perspective tilt */ - public float tilt; + /** + * Perspective tilt + */ + public float tilt; - /** - * Zoom-level for current scale. - * - To be removed: FastMath.log2(scale) - * - use setZoomLevel() to modify - */ - public int zoomLevel; + /** + * Zoom-level for current scale. + * - To be removed: FastMath.log2(scale) + * - use setZoomLevel() to modify + */ + public int zoomLevel; - public MapPosition() { - this.scale = 1; - this.x = 0.5; - this.y = 0.5; - this.zoomLevel = 1; - this.bearing = 0; - } + public MapPosition() { + this.scale = 1; + this.x = 0.5; + this.y = 0.5; + this.zoomLevel = 1; + this.bearing = 0; + } - public MapPosition(double latitude, double longitude, double scale) { - setPosition(latitude, longitude); - setScale(scale); - } + public MapPosition(double latitude, double longitude, double scale) { + setPosition(latitude, longitude); + setScale(scale); + } - public double getX() { - return x; - } + public double getX() { + return x; + } - public MapPosition setX(double x) { - this.x = x; - return this; - } + public MapPosition setX(double x) { + this.x = x; + return this; + } - public double getY() { - return y; - } + public double getY() { + return y; + } - public MapPosition setY(double y) { - this.y = y; - return this; - } + public MapPosition setY(double y) { + this.y = y; + return this; + } - public float getBearing() { - return bearing; - } + public float getBearing() { + return bearing; + } - public MapPosition setBearing(float bearing) { - this.bearing = bearing; - return this; - } + public MapPosition setBearing(float bearing) { + this.bearing = bearing; + return this; + } - public float getTilt() { - return tilt; - } + public float getTilt() { + return tilt; + } - public MapPosition setTilt(float tilt) { - this.tilt = tilt; - return this; - } + public MapPosition setTilt(float tilt) { + this.tilt = tilt; + return this; + } - public double getScale() { - return scale; - } + public double getScale() { + return scale; + } - public int getZoomLevel() { - return zoomLevel; - } + public int getZoomLevel() { + return zoomLevel; + } - public MapPosition setZoomLevel(int zoomLevel) { - this.zoomLevel = zoomLevel; - this.scale = 1 << zoomLevel; - return this; - } + public MapPosition setZoomLevel(int zoomLevel) { + this.zoomLevel = zoomLevel; + this.scale = 1 << zoomLevel; + return this; + } - public MapPosition setScale(double scale) { - this.zoomLevel = FastMath.log2((int) scale); - this.scale = scale; - return this; - } + public MapPosition setScale(double scale) { + this.zoomLevel = FastMath.log2((int) scale); + this.scale = scale; + return this; + } - public void setPosition(GeoPoint geoPoint) { - setPosition(geoPoint.getLatitude(), geoPoint.getLongitude()); - } + public void setPosition(GeoPoint geoPoint) { + setPosition(geoPoint.getLatitude(), geoPoint.getLongitude()); + } - public void setPosition(double latitude, double longitude) { - latitude = MercatorProjection.limitLatitude(latitude); - longitude = MercatorProjection.limitLongitude(longitude); - this.x = MercatorProjection.longitudeToX(longitude); - this.y = MercatorProjection.latitudeToY(latitude); - } + public void setPosition(double latitude, double longitude) { + latitude = MercatorProjection.limitLatitude(latitude); + longitude = MercatorProjection.limitLongitude(longitude); + this.x = MercatorProjection.longitudeToX(longitude); + this.y = MercatorProjection.latitudeToY(latitude); + } - public void copy(MapPosition other) { - this.x = other.x; - this.y = other.y; + public void copy(MapPosition other) { + this.x = other.x; + this.y = other.y; - this.bearing = other.bearing; - this.scale = other.scale; - this.tilt = other.tilt; - this.zoomLevel = other.zoomLevel; - } + this.bearing = other.bearing; + this.scale = other.scale; + this.tilt = other.tilt; + this.zoomLevel = other.zoomLevel; + } - public void set(double x, double y, double scale, float bearing, float tilt) { - this.x = x; - this.y = y; - this.scale = scale; + public void set(double x, double y, double scale, float bearing, float tilt) { + this.x = x; + this.y = y; + this.scale = scale; - while (bearing > 180) - bearing -= 360; - while (bearing < -180) - bearing += 360; - this.bearing = bearing; + while (bearing > 180) + bearing -= 360; + while (bearing < -180) + bearing += 360; + this.bearing = bearing; - this.tilt = tilt; - this.zoomLevel = FastMath.log2((int) scale); - } + this.tilt = tilt; + this.zoomLevel = FastMath.log2((int) scale); + } - /** - * @return scale relative to zoom-level. - */ - public double getZoomScale() { - return scale / (1 << zoomLevel); - } + /** + * @return scale relative to zoom-level. + */ + public double getZoomScale() { + return scale / (1 << zoomLevel); + } - public GeoPoint getGeoPoint() { - return new GeoPoint(MercatorProjection.toLatitude(y), - MercatorProjection.toLongitude(x)); - } + public GeoPoint getGeoPoint() { + return new GeoPoint(MercatorProjection.toLatitude(y), + MercatorProjection.toLongitude(x)); + } - public double getLatitude() { - return MercatorProjection.toLatitude(y); - } + public double getLatitude() { + return MercatorProjection.toLatitude(y); + } - public double getLongitude() { - return MercatorProjection.toLongitude(x); - } + public double getLongitude() { + return MercatorProjection.toLongitude(x); + } - public void setByBoundingBox(BoundingBox bbox, int viewWidth, int viewHeight) { - double minx = MercatorProjection.longitudeToX(bbox.getMinLongitude()); - double miny = MercatorProjection.latitudeToY(bbox.getMaxLatitude()); + public void setByBoundingBox(BoundingBox bbox, int viewWidth, int viewHeight) { + double minx = MercatorProjection.longitudeToX(bbox.getMinLongitude()); + double miny = MercatorProjection.latitudeToY(bbox.getMaxLatitude()); - double dx = Math.abs(MercatorProjection.longitudeToX(bbox.getMaxLongitude()) - minx); - double dy = Math.abs(MercatorProjection.latitudeToY(bbox.getMinLatitude()) - miny); - double zx = viewWidth / (dx * Tile.SIZE); - double zy = viewHeight / (dy * Tile.SIZE); + double dx = Math.abs(MercatorProjection.longitudeToX(bbox.getMaxLongitude()) - minx); + double dy = Math.abs(MercatorProjection.latitudeToY(bbox.getMinLatitude()) - miny); + double zx = viewWidth / (dx * Tile.SIZE); + double zy = viewHeight / (dy * Tile.SIZE); - scale = Math.min(zx, zy); - zoomLevel = FastMath.log2((int) scale); - x = minx + dx / 2; - y = miny + dy / 2; - bearing = 0; - tilt = 0; - } + scale = Math.min(zx, zy); + zoomLevel = FastMath.log2((int) scale); + x = minx + dx / 2; + y = miny + dy / 2; + bearing = 0; + tilt = 0; + } - @Override - public String toString() { - return new StringBuilder() - .append("[X:").append(x) - .append(", Y:").append(y) - .append(", Z:").append(zoomLevel) - .append("] lat:") - .append(MercatorProjection.toLatitude(y)) - .append(", lon:") - .append(MercatorProjection.toLongitude(x)) - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("[X:").append(x) + .append(", Y:").append(y) + .append(", Z:").append(zoomLevel) + .append("] lat:") + .append(MercatorProjection.toLatitude(y)) + .append(", lon:") + .append(MercatorProjection.toLongitude(x)) + .toString(); + } } diff --git a/vtm/src/org/oscim/core/MercatorProjection.java b/vtm/src/org/oscim/core/MercatorProjection.java index 08c7d659..e4e8d422 100644 --- a/vtm/src/org/oscim/core/MercatorProjection.java +++ b/vtm/src/org/oscim/core/MercatorProjection.java @@ -21,143 +21,137 @@ package org.oscim.core; * An implementation of the spherical Mercator projection. */ public final class MercatorProjection { - /** - * The circumference of the earth at the equator in meters. - */ - public static final double EARTH_CIRCUMFERENCE = 40075016.686; + /** + * The circumference of the earth at the equator in meters. + */ + public static final double EARTH_CIRCUMFERENCE = 40075016.686; - /** - * Maximum possible latitude coordinate of the map. - */ - public static final double LATITUDE_MAX = 85.05112877980659; + /** + * Maximum possible latitude coordinate of the map. + */ + public static final double LATITUDE_MAX = 85.05112877980659; - /** - * Minimum possible latitude coordinate of the map. - */ - public static final double LATITUDE_MIN = -LATITUDE_MAX; + /** + * Minimum possible latitude coordinate of the map. + */ + public static final double LATITUDE_MIN = -LATITUDE_MAX; - /** - * Maximum possible longitude coordinate of the map. - */ - public static final double LONGITUDE_MAX = 180; + /** + * Maximum possible longitude coordinate of the map. + */ + public static final double LONGITUDE_MAX = 180; - /** - * Minimum possible longitude coordinate of the map. - */ - public static final double LONGITUDE_MIN = -LONGITUDE_MAX; + /** + * Minimum possible longitude coordinate of the map. + */ + public static final double LONGITUDE_MIN = -LONGITUDE_MAX; - /** - * Calculates the distance on the ground that is represented by a single - * pixel on the map. - * - * @param latitude - * the latitude coordinate at which the resolution should be - * calculated. - * @param scale - * the map scale at which the resolution should be calculated. - * @return the ground resolution at the given latitude and zoom level. - */ - public static double groundResolution(double latitude, double scale) { - return Math.cos(latitude * (Math.PI / 180)) * EARTH_CIRCUMFERENCE - / (Tile.SIZE * scale); - } + /** + * Calculates the distance on the ground that is represented by a single + * pixel on the map. + * + * @param latitude the latitude coordinate at which the resolution should be + * calculated. + * @param scale the map scale at which the resolution should be calculated. + * @return the ground resolution at the given latitude and zoom level. + */ + public static double groundResolution(double latitude, double scale) { + return Math.cos(latitude * (Math.PI / 180)) * EARTH_CIRCUMFERENCE + / (Tile.SIZE * scale); + } - public static float groundResolution(MapPosition pos) { - double lat = MercatorProjection.toLatitude(pos.y); - return (float) (Math.cos(lat * (Math.PI / 180)) - * MercatorProjection.EARTH_CIRCUMFERENCE - / (Tile.SIZE * pos.scale)); - } + public static float groundResolution(MapPosition pos) { + double lat = MercatorProjection.toLatitude(pos.y); + return (float) (Math.cos(lat * (Math.PI / 180)) + * MercatorProjection.EARTH_CIRCUMFERENCE + / (Tile.SIZE * pos.scale)); + } - /** - * Projects a longitude coordinate (in degrees) to the range [0.0,1.0] - * - * @param latitude - * the latitude coordinate that should be converted. - * @return the position . - */ - public static double latitudeToY(double latitude) { - double sinLatitude = Math.sin(latitude * (Math.PI / 180)); - return 0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI); - } + /** + * Projects a longitude coordinate (in degrees) to the range [0.0,1.0] + * + * @param latitude the latitude coordinate that should be converted. + * @return the position . + */ + public static double latitudeToY(double latitude) { + double sinLatitude = Math.sin(latitude * (Math.PI / 180)); + return 0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI); + } - public static double toLatitude(double y) { - return 90 - 360 * Math.atan(Math.exp((y - 0.5) * (2 * Math.PI))) / Math.PI; - } + public static double toLatitude(double y) { + return 90 - 360 * Math.atan(Math.exp((y - 0.5) * (2 * Math.PI))) / Math.PI; + } - /** - * Projects a longitude coordinate (in degrees) to the range [0.0,1.0] - * - * @param longitude - * the longitude coordinate that should be converted. - * @return the position . - */ - public static double longitudeToX(double longitude) { - return (longitude + 180.0) / 360.0; - } + /** + * Projects a longitude coordinate (in degrees) to the range [0.0,1.0] + * + * @param longitude the longitude coordinate that should be converted. + * @return the position . + */ + public static double longitudeToX(double longitude) { + return (longitude + 180.0) / 360.0; + } - public static double toLongitude(double x) { - return 360.0 * (x - 0.5); - } + public static double toLongitude(double x) { + return 360.0 * (x - 0.5); + } - public static Point project(GeoPoint p, Point reuse) { - if (reuse == null) - reuse = new Point(); + public static Point project(GeoPoint p, Point reuse) { + if (reuse == null) + reuse = new Point(); - reuse.x = ((p.longitudeE6 / 1E6) + 180.0) / 360.0; + reuse.x = ((p.longitudeE6 / 1E6) + 180.0) / 360.0; - double sinLatitude = Math.sin((p.latitudeE6 / 1E6) * (Math.PI / 180.0)); - reuse.y = 0.5 - Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude)) / (4.0 * Math.PI); + double sinLatitude = Math.sin((p.latitudeE6 / 1E6) * (Math.PI / 180.0)); + reuse.y = 0.5 - Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude)) / (4.0 * Math.PI); - return reuse; - } + return reuse; + } - public static void project(GeoPoint p, double[] out, int pos) { + public static void project(GeoPoint p, double[] out, int pos) { - out[pos * 2] = ((p.longitudeE6 / 1E6) + 180.0) / 360.0; + out[pos * 2] = ((p.longitudeE6 / 1E6) + 180.0) / 360.0; - double sinLatitude = Math.sin((p.latitudeE6 / 1E6) * (Math.PI / 180.0)); - out[pos * 2 + 1] = 0.5 - Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude)) - / (4.0 * Math.PI); - } + double sinLatitude = Math.sin((p.latitudeE6 / 1E6) * (Math.PI / 180.0)); + out[pos * 2 + 1] = 0.5 - Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude)) + / (4.0 * Math.PI); + } - public static void project(double latitude, double longitude, double[] out, int pos) { + public static void project(double latitude, double longitude, double[] out, int pos) { - out[pos * 2] = (longitude + 180.0) / 360.0; + out[pos * 2] = (longitude + 180.0) / 360.0; - double sinLatitude = Math.sin(latitude * (Math.PI / 180.0)); - out[pos * 2 + 1] = 0.5 - Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude)) - / (4.0 * Math.PI); - } + double sinLatitude = Math.sin(latitude * (Math.PI / 180.0)); + out[pos * 2 + 1] = 0.5 - Math.log((1.0 + sinLatitude) / (1.0 - sinLatitude)) + / (4.0 * Math.PI); + } - /** - * @param latitude - * the latitude value which should be checked. - * @return the given latitude value, limited to the possible latitude range. - */ - public static double limitLatitude(double latitude) { - return Math.max(Math.min(latitude, LATITUDE_MAX), LATITUDE_MIN); - } + /** + * @param latitude the latitude value which should be checked. + * @return the given latitude value, limited to the possible latitude range. + */ + public static double limitLatitude(double latitude) { + return Math.max(Math.min(latitude, LATITUDE_MAX), LATITUDE_MIN); + } - /** - * @param longitude - * the longitude value which should be checked. - * @return the given longitude value, limited to the possible longitude - * range. - */ - public static double limitLongitude(double longitude) { - return Math.max(Math.min(longitude, LONGITUDE_MAX), LONGITUDE_MIN); - } + /** + * @param longitude the longitude value which should be checked. + * @return the given longitude value, limited to the possible longitude + * range. + */ + public static double limitLongitude(double longitude) { + return Math.max(Math.min(longitude, LONGITUDE_MAX), LONGITUDE_MIN); + } - public static double wrapLongitude(double longitude) { - if (longitude < -180) - return Math.max(Math.min(360 + longitude, LONGITUDE_MAX), LONGITUDE_MIN); - else if (longitude > 180) - return Math.max(Math.min(longitude - 360, LONGITUDE_MAX), LONGITUDE_MIN); + public static double wrapLongitude(double longitude) { + if (longitude < -180) + return Math.max(Math.min(360 + longitude, LONGITUDE_MAX), LONGITUDE_MIN); + else if (longitude > 180) + return Math.max(Math.min(longitude - 360, LONGITUDE_MAX), LONGITUDE_MIN); - return longitude; - } + return longitude; + } - private MercatorProjection() { - } + private MercatorProjection() { + } } diff --git a/vtm/src/org/oscim/core/Point.java b/vtm/src/org/oscim/core/Point.java index eced246e..1c43d0a3 100644 --- a/vtm/src/org/oscim/core/Point.java +++ b/vtm/src/org/oscim/core/Point.java @@ -17,56 +17,56 @@ package org.oscim.core; public class Point { - public double x; - public double y; + public double x; + public double y; - public Point() { - } + public Point() { + } - public Point(double x, double y) { - this.x = x; - this.y = y; - } + public Point(double x, double y) { + this.x = x; + this.y = y; + } - public double getX() { - return x; - } + public double getX() { + return x; + } - public double getY() { - return y; - } + public double getY() { + return y; + } - public double distance(Point other) { - return Math.sqrt((x - other.x) * (x - other.x) + (y - other.y) + (y - other.y)); - } + public double distance(Point other) { + return Math.sqrt((x - other.x) * (x - other.x) + (y - other.y) + (y - other.y)); + } - public double distanceSq(Point other) { - return (x - other.x) * (x - other.x) + (y - other.y) + (y - other.y); - } + public double distanceSq(Point other) { + return (x - other.x) * (x - other.x) + (y - other.y) + (y - other.y); + } - @Override - public String toString() { - return x + " " + y; - } + @Override + public String toString() { + return x + " " + y; + } - public void setPerpendicular(Point other) { - x = -other.y; - y = other.x; - } + public void setPerpendicular(Point other) { + x = -other.y; + y = other.x; + } - public void setPerpendicular(Point p1, Point p2) { - x = p1.x + p2.x; - y = p1.y + p2.y; + public void setPerpendicular(Point p1, Point p2) { + x = p1.x + p2.x; + y = p1.y + p2.y; - double a = p2.x * y - p2.y * x; + double a = p2.x * y - p2.y * x; - if (a < 0.01 && a > -0.01) { - /* Almost straight */ - x = -p2.y; - y = p2.x; - } else { - x /= a; - y /= a; - } - } + if (a < 0.01 && a > -0.01) { + /* Almost straight */ + x = -p2.y; + y = p2.x; + } else { + x /= a; + y /= a; + } + } } diff --git a/vtm/src/org/oscim/core/PointF.java b/vtm/src/org/oscim/core/PointF.java index f449291c..dba1023d 100644 --- a/vtm/src/org/oscim/core/PointF.java +++ b/vtm/src/org/oscim/core/PointF.java @@ -21,39 +21,43 @@ package org.oscim.core; */ public class PointF { - /** The x ordinate */ - public float x; + /** + * The x ordinate + */ + public float x; - /** The y ordinate */ - public float y; + /** + * The y ordinate + */ + public float y; - /** - * Instantiates a new Point. - */ - public PointF() { - } + /** + * Instantiates a new Point. + */ + public PointF() { + } - /** - * Instantiates a new Point with coordinates x and y. - * - * @param x the x - * @param y the y - */ - public PointF(float x, float y) { - this.x = x; - this.y = y; - } + /** + * Instantiates a new Point with coordinates x and y. + * + * @param x the x + * @param y the y + */ + public PointF(float x, float y) { + this.x = x; + this.y = y; + } - public float getX() { - return x; - } + public float getX() { + return x; + } - public float getY() { - return y; - } + public float getY() { + return y; + } - @Override - public String toString() { - return x + " " + y; - } + @Override + public String toString() { + return x + " " + y; + } } diff --git a/vtm/src/org/oscim/core/Tag.java b/vtm/src/org/oscim/core/Tag.java index 8cd78f30..cd76fbb3 100644 --- a/vtm/src/org/oscim/core/Tag.java +++ b/vtm/src/org/oscim/core/Tag.java @@ -22,140 +22,142 @@ package org.oscim.core; */ public class Tag { - /** The key of the house number OpenStreetMap tag. */ - public static final String KEY_HOUSE_NUMBER = "addr:housenumber"; + /** + * The key of the house number OpenStreetMap tag. + */ + public static final String KEY_HOUSE_NUMBER = "addr:housenumber"; - /** The key of the name OpenStreetMap tag. */ - public static final String KEY_NAME = "name"; + /** + * The key of the name OpenStreetMap tag. + */ + public static final String KEY_NAME = "name"; - /** The key of the reference OpenStreetMap tag. */ - public static final String KEY_REF = "ref"; + /** + * The key of the reference OpenStreetMap tag. + */ + public static final String KEY_REF = "ref"; - /** The key of the elevation OpenStreetMap tag. */ - public static final String KEY_ELE = "ele"; + /** + * The key of the elevation OpenStreetMap tag. + */ + public static final String KEY_ELE = "ele"; - public static final String KEY_AMENITY = "amenity"; - public static final String KEY_BUILDING = "building"; - public static final String KEY_HIGHWAY = "highway"; - public static final String KEY_LANDUSE = "landuse"; - public static final String KEY_HEIGHT = "height"; - public static final String KEY_MIN_HEIGHT = "min_height"; + public static final String KEY_AMENITY = "amenity"; + public static final String KEY_BUILDING = "building"; + public static final String KEY_HIGHWAY = "highway"; + public static final String KEY_LANDUSE = "landuse"; + public static final String KEY_HEIGHT = "height"; + public static final String KEY_MIN_HEIGHT = "min_height"; - public static final String VALUE_YES = "yes"; - public static final String VALUE_NO = "no"; + public static final String VALUE_YES = "yes"; + public static final String VALUE_NO = "no"; - /** - * The key of this tag. - */ - public final String key; + /** + * The key of this tag. + */ + public final String key; - /** - * The value of this tag. - */ - public String value; + /** + * The value of this tag. + */ + public String value; - /** - * true when value is intern(). - */ - private final boolean intern; + /** + * true when value is intern(). + */ + private final boolean intern; - private int hashCodeValue = 0; + private int hashCodeValue = 0; - /** - * @param key - * the key of the tag. - * @param value - * the value of the tag. - */ - public Tag(String key, String value) { - this.key = key == null ? null : key.intern(); - this.value = value == null ? null : value.intern(); - this.intern = true; - } + /** + * @param key the key of the tag. + * @param value the value of the tag. + */ + public Tag(String key, String value) { + this.key = key == null ? null : key.intern(); + this.value = value == null ? null : value.intern(); + this.intern = true; + } - /** - * Create Tag with interned Key. - * - * @param key - * the key of the tag. - * @param value - * the value of the tag. - * @param internValue - * true when value string should be intern()alized. - */ - public Tag(String key, String value, boolean internValue) { - this.key = key; - this.value = (value == null || !internValue) ? value : value.intern(); - this.intern = internValue; - } + /** + * Create Tag with interned Key. + * + * @param key the key of the tag. + * @param value the value of the tag. + * @param internValue true when value string should be intern()alized. + */ + public Tag(String key, String value, boolean internValue) { + this.key = key; + this.value = (value == null || !internValue) ? value : value.intern(); + this.intern = internValue; + } - public Tag(String key, String value, boolean internKey, boolean internValue) { - this.key = (key == null || !internKey) ? key : key.intern(); - this.value = (value == null || !internValue) ? value : value.intern(); - this.intern = internValue; - } + public Tag(String key, String value, boolean internKey, boolean internValue) { + this.key = (key == null || !internKey) ? key : key.intern(); + this.value = (value == null || !internValue) ? value : value.intern(); + this.intern = internValue; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (!(obj instanceof Tag)) { - return false; - } - Tag other = (Tag) obj; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof Tag)) { + return false; + } + Tag other = (Tag) obj; - if (key != other.key) - return false; + if (key != other.key) + return false; - if (intern && other.intern) { - if (value == other.value) - return true; + if (intern && other.intern) { + if (value == other.value) + return true; - } else if (!intern && value.equals(other.value)) { - return true; - } - return false; - } + } else if (!intern && value.equals(other.value)) { + return true; + } + return false; + } - @Override - public int hashCode() { - if (hashCodeValue == 0) - hashCodeValue = calculateHashCode(); + @Override + public int hashCode() { + if (hashCodeValue == 0) + hashCodeValue = calculateHashCode(); - return hashCodeValue; - } + return hashCodeValue; + } - @Override - public String toString() { - return new StringBuilder() - .append("Tag[") - .append(key) - .append(',') - .append(value) - .append(']') - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("Tag[") + .append(key) + .append(',') + .append(value) + .append(']') + .toString(); + } - /** - * @return the hash code of this object. - */ - private int calculateHashCode() { - int result = 7; - result = 31 * result + ((key == null) ? 0 : key.hashCode()); - result = 31 * result + ((value == null) ? 0 : value.hashCode()); - return result; - } + /** + * @return the hash code of this object. + */ + private int calculateHashCode() { + int result = 7; + result = 31 * result + ((key == null) ? 0 : key.hashCode()); + result = 31 * result + ((value == null) ? 0 : value.hashCode()); + return result; + } - /** - * @param tag - * the textual representation of the tag. - */ - public static Tag parse(String tag) { - int splitPosition = tag.indexOf('='); - if (splitPosition < 0) { - return new Tag(tag, ""); - } + /** + * @param tag the textual representation of the tag. + */ + public static Tag parse(String tag) { + int splitPosition = tag.indexOf('='); + if (splitPosition < 0) { + return new Tag(tag, ""); + } - return new Tag(tag.substring(0, splitPosition), tag.substring(splitPosition + 1)); - } + return new Tag(tag.substring(0, splitPosition), tag.substring(splitPosition + 1)); + } } diff --git a/vtm/src/org/oscim/core/TagSet.java b/vtm/src/org/oscim/core/TagSet.java index 14eeb84a..dfbae077 100644 --- a/vtm/src/org/oscim/core/TagSet.java +++ b/vtm/src/org/oscim/core/TagSet.java @@ -23,160 +23,164 @@ import java.util.Arrays; */ public class TagSet { - /** The Tags. */ - public Tag[] tags; + /** + * The Tags. + */ + public Tag[] tags; - /** The number of current Tags in set. */ - public int numTags; + /** + * The number of current Tags in set. + */ + public int numTags; - /** - * Instantiates a new TagSet with initial size of 10. - */ - public TagSet() { - tags = new Tag[10]; - } + /** + * Instantiates a new TagSet with initial size of 10. + */ + public TagSet() { + tags = new Tag[10]; + } - /** - * Instantiates a new tag set initialized with the given size. - * - * @param size the initial size. - */ - public TagSet(int size) { - tags = new Tag[size]; - } + /** + * Instantiates a new tag set initialized with the given size. + * + * @param size the initial size. + */ + public TagSet(int size) { + tags = new Tag[size]; + } - /** - * Reset the TagSet to contain 0 tags. - */ - public void clear() { - numTags = 0; - } + /** + * Reset the TagSet to contain 0 tags. + */ + public void clear() { + numTags = 0; + } - /** - * Clear. Reset the TagSet to contain 0 tags and null out tags. - */ - public void clearAndNullTags() { - Arrays.fill(tags, null); - numTags = 0; - } + /** + * Clear. Reset the TagSet to contain 0 tags and null out tags. + */ + public void clearAndNullTags() { + Arrays.fill(tags, null); + numTags = 0; + } - /** - * Return Tags contained in TagSet as new array. - * - * @return the tag[] - */ - public Tag[] asArray() { - Tag[] result = new Tag[numTags]; - System.arraycopy(tags, 0, result, 0, numTags); - return result; - } + /** + * Return Tags contained in TagSet as new array. + * + * @return the tag[] + */ + public Tag[] asArray() { + Tag[] result = new Tag[numTags]; + System.arraycopy(tags, 0, result, 0, numTags); + return result; + } - /** - * Find Tag by given key. - * - * @param key the key as intern String. - * @return the tag if found, null otherwise. - */ - public Tag get(String key) { - for (int i = 0; i < numTags; i++) { - if (tags[i].key == key) - return tags[i]; - } - return null; - } + /** + * Find Tag by given key. + * + * @param key the key as intern String. + * @return the tag if found, null otherwise. + */ + public Tag get(String key) { + for (int i = 0; i < numTags; i++) { + if (tags[i].key == key) + return tags[i]; + } + return null; + } - /** - * Checks if any tag has the key 'key'. - * - * @param key the key as intern String. - * @return true, iff any tag has the given key - */ - public boolean containsKey(String key) { - for (int i = 0; i < numTags; i++) { - if (tags[i].key == key) - return true; - } - return false; - } + /** + * Checks if any tag has the key 'key'. + * + * @param key the key as intern String. + * @return true, iff any tag has the given key + */ + public boolean containsKey(String key) { + for (int i = 0; i < numTags; i++) { + if (tags[i].key == key) + return true; + } + return false; + } - /** - * Get the value for a given key. - * - * @param key the key as intern String - * @return the value when found, null otherwise - */ - public String getValue(String key) { - for (int i = 0; i < numTags; i++) { - if (tags[i].key == key) - return tags[i].value; - } - return null; - } + /** + * Get the value for a given key. + * + * @param key the key as intern String + * @return the value when found, null otherwise + */ + public String getValue(String key) { + for (int i = 0; i < numTags; i++) { + if (tags[i].key == key) + return tags[i].value; + } + return null; + } - /** - * Adds the Tag tag to TagSet. - * - * @param tag the Tag to be added - */ - public void add(Tag tag) { - if (numTags >= tags.length) { - Tag[] tmp = tags; - tags = new Tag[numTags + 4]; - System.arraycopy(tmp, 0, tags, 0, numTags); - } - tags[numTags++] = tag; - } + /** + * Adds the Tag tag to TagSet. + * + * @param tag the Tag to be added + */ + public void add(Tag tag) { + if (numTags >= tags.length) { + Tag[] tmp = tags; + tags = new Tag[numTags + 4]; + System.arraycopy(tmp, 0, tags, 0, numTags); + } + tags[numTags++] = tag; + } - /** - * Sets the tags from 'tagArray'. - * - * @param tagArray the tag array - */ - public void set(Tag[] tagArray) { - int newTags = tagArray.length; - if (newTags > tags.length) - tags = new Tag[tagArray.length]; - System.arraycopy(tagArray, 0, tags, 0, newTags); + /** + * Sets the tags from 'tagArray'. + * + * @param tagArray the tag array + */ + public void set(Tag[] tagArray) { + int newTags = tagArray.length; + if (newTags > tags.length) + tags = new Tag[tagArray.length]; + System.arraycopy(tagArray, 0, tags, 0, newTags); - numTags = newTags; - } + numTags = newTags; + } - /** - * Checks if 'tag' is contained in TagSet. - * - * @param tag the tag - * @return true, iff tag is in TagSet - */ - public boolean contains(Tag tag) { - for (int i = 0; i < numTags; i++) { - Tag t = tags[i]; - if ((t == tag) || (t.key == tag.key && t.value == tag.value)) - return true; - } - return false; - } + /** + * Checks if 'tag' is contained in TagSet. + * + * @param tag the tag + * @return true, iff tag is in TagSet + */ + public boolean contains(Tag tag) { + for (int i = 0; i < numTags; i++) { + Tag t = tags[i]; + if ((t == tag) || (t.key == tag.key && t.value == tag.value)) + return true; + } + return false; + } - /** - * Checks if a Tag with given key and value is contained in TagSet. - * - * @param key the key as intern String - * @param value the value as intern String - * @return true, iff any tag has the given key and value - */ - public boolean contains(String key, String value) { - for (int i = 0; i < numTags; i++) { - if (tags[i].key == key) - return value.equals(tags[i].value); - } - return false; - } + /** + * Checks if a Tag with given key and value is contained in TagSet. + * + * @param key the key as intern String + * @param value the value as intern String + * @return true, iff any tag has the given key and value + */ + public boolean contains(String key, String value) { + for (int i = 0; i < numTags; i++) { + if (tags[i].key == key) + return value.equals(tags[i].value); + } + return false; + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < numTags; i++) - sb.append(tags[i]); + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < numTags; i++) + sb.append(tags[i]); - return sb.toString(); - } + return sb.toString(); + } } diff --git a/vtm/src/org/oscim/core/Tile.java b/vtm/src/org/oscim/core/Tile.java index 93deb8af..cfbc1bee 100644 --- a/vtm/src/org/oscim/core/Tile.java +++ b/vtm/src/org/oscim/core/Tile.java @@ -24,81 +24,78 @@ package org.oscim.core; */ public class Tile { - /** - * Width and height of a map tile in pixel. - */ - public static int SIZE = 400; + /** + * Width and height of a map tile in pixel. + */ + public static int SIZE = 400; - /** - * The X number of this tile. - */ - public final int tileX; + /** + * The X number of this tile. + */ + public final int tileX; - /** - * The Y number of this tile. - */ - public final int tileY; + /** + * The Y number of this tile. + */ + public final int tileY; - /** - * The Zoom level of this tile. - */ - public final byte zoomLevel; + /** + * The Zoom level of this tile. + */ + public final byte zoomLevel; - /** - * @param tileX - * the X number of the tile. - * @param tileY - * the Y number of the tile. - * @param zoomLevel - * the zoom level of the tile. - */ - public Tile(int tileX, int tileY, byte zoomLevel) { - this.tileX = tileX; - this.tileY = tileY; - this.zoomLevel = zoomLevel; - } + /** + * @param tileX the X number of the tile. + * @param tileY the Y number of the tile. + * @param zoomLevel the zoom level of the tile. + */ + public Tile(int tileX, int tileY, byte zoomLevel) { + this.tileX = tileX; + this.tileY = tileY; + this.zoomLevel = zoomLevel; + } - @Override - public String toString() { - return new StringBuilder() - .append("[X:") - .append(this.tileX) - .append(", Y:") - .append(this.tileY) - .append(", Z:") - .append(this.zoomLevel) - .append("]") - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("[X:") + .append(this.tileX) + .append(", Y:") + .append(this.tileY) + .append(", Z:") + .append(this.zoomLevel) + .append("]") + .toString(); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; - if (!(obj instanceof Tile)) - return false; + if (!(obj instanceof Tile)) + return false; - Tile o = (Tile) obj; + Tile o = (Tile) obj; - if (o.tileX == this.tileX && o.tileY == this.tileY - && o.zoomLevel == this.zoomLevel) - return true; + if (o.tileX == this.tileX && o.tileY == this.tileY + && o.zoomLevel == this.zoomLevel) + return true; - return false; - } + return false; + } - private int mHash = 0; + private int mHash = 0; - @Override - public int hashCode() { - if (mHash == 0) { - int result = 7; - result = 31 * result + this.tileX; - result = 31 * result + this.tileY; - result = 31 * result + this.zoomLevel; - mHash = result; - } - return mHash; - } + @Override + public int hashCode() { + if (mHash == 0) { + int result = 7; + result = 31 * result + this.tileX; + result = 31 * result + this.tileY; + result = 31 * result + this.zoomLevel; + mHash = result; + } + return mHash; + } } diff --git a/vtm/src/org/oscim/event/EventDispatcher.java b/vtm/src/org/oscim/event/EventDispatcher.java index 6d471255..ef03e191 100644 --- a/vtm/src/org/oscim/event/EventDispatcher.java +++ b/vtm/src/org/oscim/event/EventDispatcher.java @@ -4,47 +4,49 @@ import org.oscim.utils.pool.LList; /** * The Class EventDispatcher. - * + *

* Events MUST be dispatched from main-loop! To add events from other * threads use: * Map.post(new Runnable(){ public void run(tell(event,data);)};); - * + * * @param the event source type * @param the event 'data' type */ public abstract class EventDispatcher { - /** The list of listeners. */ - protected LList mListeners; + /** + * The list of listeners. + */ + protected LList mListeners; - /** - * Bind listener for event notifications. - */ - public void bind(E listener) { - if (LList.find(mListeners, listener) != null) { - return; - } - mListeners = LList.push(mListeners, new LList(listener)); - } + /** + * Bind listener for event notifications. + */ + public void bind(E listener) { + if (LList.find(mListeners, listener) != null) { + return; + } + mListeners = LList.push(mListeners, new LList(listener)); + } - /** - * Remove listener. - */ - public void unbind(E listener) { - mListeners = LList.remove(mListeners, listener); - } + /** + * Remove listener. + */ + public void unbind(E listener) { + mListeners = LList.remove(mListeners, listener); + } - /** - * Tell listeners whats going on. - * - * @param event the event - * @param data the data - */ - public abstract void tell(E listener, Event event, T data); + /** + * Tell listeners whats going on. + * + * @param event the event + * @param data the data + */ + public abstract void tell(E listener, Event event, T data); - public void fire(Event event, T data) { - for (LList l = mListeners; l != null; l = l.next) { - tell(l.data, event, data); - } - } + public void fire(Event event, T data) { + for (LList l = mListeners; l != null; l = l.next) { + tell(l.data, event, data); + } + } } diff --git a/vtm/src/org/oscim/event/Gesture.java b/vtm/src/org/oscim/event/Gesture.java index 6d2d5cba..7fbfb05e 100644 --- a/vtm/src/org/oscim/event/Gesture.java +++ b/vtm/src/org/oscim/event/Gesture.java @@ -18,20 +18,20 @@ package org.oscim.event; public interface Gesture { - static final class Press implements Gesture { - } + static final class Press implements Gesture { + } - static final class LongPress implements Gesture { - } + static final class LongPress implements Gesture { + } - static final class Tap implements Gesture { - } + static final class Tap implements Gesture { + } - static final class DoubleTap implements Gesture { - } + static final class DoubleTap implements Gesture { + } - public static Gesture PRESS = new Press(); - public static Gesture LONG_PRESS = new LongPress(); - public static Gesture TAP = new Tap(); - public static Gesture DOUBLE_TAP = new DoubleTap(); + public static Gesture PRESS = new Press(); + public static Gesture LONG_PRESS = new LongPress(); + public static Gesture TAP = new Tap(); + public static Gesture DOUBLE_TAP = new DoubleTap(); } diff --git a/vtm/src/org/oscim/event/GestureDetector.java b/vtm/src/org/oscim/event/GestureDetector.java index c2052251..c2ce39f8 100644 --- a/vtm/src/org/oscim/event/GestureDetector.java +++ b/vtm/src/org/oscim/event/GestureDetector.java @@ -20,17 +20,17 @@ import org.oscim.map.Map; public class GestureDetector { - private final Map mMap; + private final Map mMap; - public GestureDetector(Map map) { - mMap = map; - } + public GestureDetector(Map map) { + mMap = map; + } - public boolean onTouchEvent(MotionEvent e) { - if (e.getAction() == MotionEvent.ACTION_DOWN) { - return mMap.handleGesture(Gesture.PRESS, e); - } + public boolean onTouchEvent(MotionEvent e) { + if (e.getAction() == MotionEvent.ACTION_DOWN) { + return mMap.handleGesture(Gesture.PRESS, e); + } - return false; - } + return false; + } } diff --git a/vtm/src/org/oscim/event/GestureListener.java b/vtm/src/org/oscim/event/GestureListener.java index 3dfc635d..bcee5c68 100644 --- a/vtm/src/org/oscim/event/GestureListener.java +++ b/vtm/src/org/oscim/event/GestureListener.java @@ -18,6 +18,6 @@ package org.oscim.event; public interface GestureListener { - boolean onGesture(Gesture g, MotionEvent e); + boolean onGesture(Gesture g, MotionEvent e); } diff --git a/vtm/src/org/oscim/event/MotionEvent.java b/vtm/src/org/oscim/event/MotionEvent.java index 151b4a65..89327068 100644 --- a/vtm/src/org/oscim/event/MotionEvent.java +++ b/vtm/src/org/oscim/event/MotionEvent.java @@ -18,30 +18,30 @@ package org.oscim.event; public abstract class MotionEvent { - public static final int ACTION_DOWN = 0; - public static final int ACTION_UP = 1; - public static final int ACTION_MOVE = 2; - public static final int ACTION_CANCEL = 3; - public static final int ACTION_POINTER_DOWN = 5; - public static final int ACTION_POINTER_UP = 6; + public static final int ACTION_DOWN = 0; + public static final int ACTION_UP = 1; + public static final int ACTION_MOVE = 2; + public static final int ACTION_CANCEL = 3; + public static final int ACTION_POINTER_DOWN = 5; + public static final int ACTION_POINTER_UP = 6; - // FIXME this should not be in the API! - public static final int ACTION_MASK = 0xff; - public static final int ACTION_POINTER_INDEX_MASK = 0xff00; - public static final int ACTION_POINTER_INDEX_SHIFT = 8; + // FIXME this should not be in the API! + public static final int ACTION_MASK = 0xff; + public static final int ACTION_POINTER_INDEX_MASK = 0xff00; + public static final int ACTION_POINTER_INDEX_SHIFT = 8; - public abstract long getTime(); + public abstract long getTime(); - public abstract int getAction(); + public abstract int getAction(); - public abstract float getX(); + public abstract float getX(); - public abstract float getY(); + public abstract float getY(); - public abstract float getX(int idx); + public abstract float getX(int idx); - public abstract float getY(int idx); + public abstract float getY(int idx); - public abstract int getPointerCount(); + public abstract int getPointerCount(); } diff --git a/vtm/src/org/oscim/layers/BitmapLayer.java b/vtm/src/org/oscim/layers/BitmapLayer.java index 447304ef..2a6f57af 100644 --- a/vtm/src/org/oscim/layers/BitmapLayer.java +++ b/vtm/src/org/oscim/layers/BitmapLayer.java @@ -22,17 +22,17 @@ import org.oscim.renderer.LayerRenderer; public class BitmapLayer extends GenericLayer { - /** - * Class for rendering a Bitmap as overlay. The - * set Bitmap can be modified and updated: - * See {@link BitmapRenderer} - */ - public BitmapLayer(Map map, LayerRenderer renderer) { - super(map, new BitmapRenderer()); - } + /** + * Class for rendering a Bitmap as overlay. The + * set Bitmap can be modified and updated: + * See {@link BitmapRenderer} + */ + public BitmapLayer(Map map, LayerRenderer renderer) { + super(map, new BitmapRenderer()); + } - public BitmapRenderer getBitmapRenderer() { - return (BitmapRenderer) mRenderer; - } + public BitmapRenderer getBitmapRenderer() { + return (BitmapRenderer) mRenderer; + } } diff --git a/vtm/src/org/oscim/layers/CustomRenderLayer.java b/vtm/src/org/oscim/layers/CustomRenderLayer.java index 2058dda8..a62fba3e 100644 --- a/vtm/src/org/oscim/layers/CustomRenderLayer.java +++ b/vtm/src/org/oscim/layers/CustomRenderLayer.java @@ -27,45 +27,45 @@ import org.slf4j.LoggerFactory; public class CustomRenderLayer extends Layer implements UpdateListener { - static final Logger log = LoggerFactory.getLogger(CustomRenderLayer.class); + static final Logger log = LoggerFactory.getLogger(CustomRenderLayer.class); - class CustomRenderer extends LayerRenderer { + class CustomRenderer extends LayerRenderer { - // functions running on MapRender Thread - @Override - public void update(GLViewport v) { - int currentState; + // functions running on MapRender Thread + @Override + public void update(GLViewport v) { + int currentState; - synchronized (this) { - currentState = someConccurentVariable; - compile(); - } - log.debug("state " + currentState); + synchronized (this) { + currentState = someConccurentVariable; + compile(); + } + log.debug("state " + currentState); - } + } - protected void compile() { - setReady(true); - } + protected void compile() { + setReady(true); + } - @Override - public void render(GLViewport v) { - } - } + @Override + public void render(GLViewport v) { + } + } - public CustomRenderLayer(Map map, LayerRenderer renderer) { + public CustomRenderLayer(Map map, LayerRenderer renderer) { - super(map); - mRenderer = new CustomRenderer(); - } + super(map); + mRenderer = new CustomRenderer(); + } - private int someConccurentVariable; + private int someConccurentVariable; - @Override - public void onMapEvent(Event e, MapPosition mapPosition) { + @Override + public void onMapEvent(Event e, MapPosition mapPosition) { - synchronized (mRenderer) { - someConccurentVariable++; - } - } + synchronized (mRenderer) { + someConccurentVariable++; + } + } } diff --git a/vtm/src/org/oscim/layers/GenericLayer.java b/vtm/src/org/oscim/layers/GenericLayer.java index 34e92b15..d9e70024 100644 --- a/vtm/src/org/oscim/layers/GenericLayer.java +++ b/vtm/src/org/oscim/layers/GenericLayer.java @@ -20,14 +20,12 @@ import org.oscim.map.Map; import org.oscim.renderer.LayerRenderer; public class GenericLayer extends Layer { - /** - * @param map - * ... - * @param renderer - * ... - */ - public GenericLayer(Map map, LayerRenderer renderer) { - super(map); - mRenderer = renderer; - } + /** + * @param map ... + * @param renderer ... + */ + public GenericLayer(Map map, LayerRenderer renderer) { + super(map); + mRenderer = renderer; + } } diff --git a/vtm/src/org/oscim/layers/Layer.java b/vtm/src/org/oscim/layers/Layer.java index 8ff7b7b5..969a221b 100644 --- a/vtm/src/org/oscim/layers/Layer.java +++ b/vtm/src/org/oscim/layers/Layer.java @@ -21,40 +21,40 @@ import org.oscim.renderer.LayerRenderer; public abstract class Layer { - public Layer(Map map) { - mMap = map; - } + public Layer(Map map) { + mMap = map; + } - private boolean mEnabled = true; - protected final Map mMap; + private boolean mEnabled = true; + protected final Map mMap; - protected LayerRenderer mRenderer; + protected LayerRenderer mRenderer; - public LayerRenderer getRenderer() { - return mRenderer; - } + public LayerRenderer getRenderer() { + return mRenderer; + } - /** - * Enabled layers will be considered for rendering and receive onMapUpdate() - * calls when they implement MapUpdateListener. - * - * @param enabled - */ - public void setEnabled(boolean enabled) { - mEnabled = enabled; - } + /** + * Enabled layers will be considered for rendering and receive onMapUpdate() + * calls when they implement MapUpdateListener. + * + * @param enabled + */ + public void setEnabled(boolean enabled) { + mEnabled = enabled; + } - public boolean isEnabled() { - return mEnabled; - } + public boolean isEnabled() { + return mEnabled; + } - /** - * Override to perform clean up of resources before shutdown. - */ - public void onDetach() { - } + /** + * Override to perform clean up of resources before shutdown. + */ + public void onDetach() { + } - public Map map() { - return mMap; - } + public Map map() { + return mMap; + } } diff --git a/vtm/src/org/oscim/layers/MapEventLayer.java b/vtm/src/org/oscim/layers/MapEventLayer.java index 745ef9e1..6814e789 100644 --- a/vtm/src/org/oscim/layers/MapEventLayer.java +++ b/vtm/src/org/oscim/layers/MapEventLayer.java @@ -17,9 +17,6 @@ */ package org.oscim.layers; -import static org.oscim.backend.CanvasAdapter.dpi; -import static org.oscim.utils.FastMath.withinSquaredDist; - import org.oscim.core.Tile; import org.oscim.event.Event; import org.oscim.event.Gesture; @@ -31,483 +28,490 @@ import org.oscim.map.ViewController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.backend.CanvasAdapter.dpi; +import static org.oscim.utils.FastMath.withinSquaredDist; + /** * Changes Viewport by handling move, fling, scale, rotation and tilt gestures. - * + *

* TODO rewrite using gesture primitives to build more complex gestures: * maybe something similar to this https://github.com/ucbvislab/Proton */ public class MapEventLayer extends Layer implements InputListener, GestureListener { - static final Logger log = LoggerFactory.getLogger(MapEventLayer.class); + static final Logger log = LoggerFactory.getLogger(MapEventLayer.class); - private boolean mEnableRotate = true; - private boolean mEnableTilt = true; - private boolean mEnableMove = true; - private boolean mEnableScale = true; - private boolean mFixOnCenter = false; + private boolean mEnableRotate = true; + private boolean mEnableTilt = true; + private boolean mEnableMove = true; + private boolean mEnableScale = true; + private boolean mFixOnCenter = false; - /* possible state transitions */ - private boolean mCanScale; - private boolean mCanRotate; - private boolean mCanTilt; + /* possible state transitions */ + private boolean mCanScale; + private boolean mCanRotate; + private boolean mCanTilt; - /* current gesture state */ - private boolean mDoRotate; - private boolean mDoScale; - private boolean mDoTilt; + /* current gesture state */ + private boolean mDoRotate; + private boolean mDoScale; + private boolean mDoTilt; - private boolean mDown; - private boolean mDoubleTap; - private boolean mDragZoom; + private boolean mDown; + private boolean mDoubleTap; + private boolean mDragZoom; - private float mPrevX1; - private float mPrevY1; - private float mPrevX2; - private float mPrevY2; + private float mPrevX1; + private float mPrevY1; + private float mPrevX2; + private float mPrevY2; - private double mAngle; - private double mPrevPinchWidth; - private long mStartMove; + private double mAngle; + private double mPrevPinchWidth; + private long mStartMove; - /** 2mm as minimal distance to start move: dpi / 25.4 */ - protected static final float MIN_SLOP = 25.4f / 2; + /** + * 2mm as minimal distance to start move: dpi / 25.4 + */ + protected static final float MIN_SLOP = 25.4f / 2; - protected static final float PINCH_ZOOM_THRESHOLD = MIN_SLOP / 2; - protected static final float PINCH_TILT_THRESHOLD = MIN_SLOP / 2; - protected static final float PINCH_TILT_SLOPE = 0.75f; - protected static final float PINCH_ROTATE_THRESHOLD = 0.2f; - protected static final float PINCH_ROTATE_THRESHOLD2 = 0.5f; + protected static final float PINCH_ZOOM_THRESHOLD = MIN_SLOP / 2; + protected static final float PINCH_TILT_THRESHOLD = MIN_SLOP / 2; + protected static final float PINCH_TILT_SLOPE = 0.75f; + protected static final float PINCH_ROTATE_THRESHOLD = 0.2f; + protected static final float PINCH_ROTATE_THRESHOLD2 = 0.5f; - /** 100 ms since start of move to reduce fling scroll */ - protected static final float FLING_MIN_THREHSHOLD = 100; + /** + * 100 ms since start of move to reduce fling scroll + */ + protected static final float FLING_MIN_THREHSHOLD = 100; - private final VelocityTracker mTracker; + private final VelocityTracker mTracker; - public MapEventLayer(Map map) { - super(map); - mTracker = new VelocityTracker(); - } + public MapEventLayer(Map map) { + super(map); + mTracker = new VelocityTracker(); + } - @Override - public void onInputEvent(Event e, MotionEvent motionEvent) { - onTouchEvent(motionEvent); - } + @Override + public void onInputEvent(Event e, MotionEvent motionEvent) { + onTouchEvent(motionEvent); + } - public void enableRotation(boolean enable) { - mEnableRotate = enable; - } + public void enableRotation(boolean enable) { + mEnableRotate = enable; + } - public boolean rotationEnabled() { - return mEnableRotate; - } + public boolean rotationEnabled() { + return mEnableRotate; + } - public void enableTilt(boolean enable) { - mEnableTilt = enable; - } + public void enableTilt(boolean enable) { + mEnableTilt = enable; + } - public boolean tiltEnabled() { - return mEnableTilt; - } + public boolean tiltEnabled() { + return mEnableTilt; + } - public void enableMove(boolean enable) { - mEnableMove = enable; - } + public void enableMove(boolean enable) { + mEnableMove = enable; + } - public boolean moveEnabled() { - return mEnableMove; - } + public boolean moveEnabled() { + return mEnableMove; + } - public void enableZoom(boolean enable) { - mEnableScale = enable; - } + public void enableZoom(boolean enable) { + mEnableScale = enable; + } - public boolean zoomEnabled() { - return mEnableScale; - } + public boolean zoomEnabled() { + return mEnableScale; + } - /** - * When enabled zoom- and rotation-gestures will not move the viewport. - */ - public void setFixOnCenter(boolean enable) { - mFixOnCenter = enable; - } + /** + * When enabled zoom- and rotation-gestures will not move the viewport. + */ + public void setFixOnCenter(boolean enable) { + mFixOnCenter = enable; + } - public boolean onTouchEvent(MotionEvent e) { + public boolean onTouchEvent(MotionEvent e) { - int action = getAction(e); + int action = getAction(e); - if (action == MotionEvent.ACTION_DOWN) { - mMap.animator().cancel(); + if (action == MotionEvent.ACTION_DOWN) { + mMap.animator().cancel(); - mStartMove = -1; - mDoubleTap = false; - mDragZoom = false; + mStartMove = -1; + mDoubleTap = false; + mDragZoom = false; - mPrevX1 = e.getX(0); - mPrevY1 = e.getY(0); + mPrevX1 = e.getX(0); + mPrevY1 = e.getY(0); - mDown = true; - return true; - } - if (!(mDown || mDoubleTap)) { - /* no down event received */ - return false; - } + mDown = true; + return true; + } + if (!(mDown || mDoubleTap)) { + /* no down event received */ + return false; + } - if (action == MotionEvent.ACTION_MOVE) { - onActionMove(e); - return true; - } - if (action == MotionEvent.ACTION_UP) { - mDown = false; - if (mDoubleTap && !mDragZoom) { - float pivotX = 0, pivotY = 0; - if (!mFixOnCenter) { - pivotX = mPrevX1 - mMap.getWidth() / 2; - pivotY = mPrevY1 - mMap.getHeight() / 2; - } + if (action == MotionEvent.ACTION_MOVE) { + onActionMove(e); + return true; + } + if (action == MotionEvent.ACTION_UP) { + mDown = false; + if (mDoubleTap && !mDragZoom) { + float pivotX = 0, pivotY = 0; + if (!mFixOnCenter) { + pivotX = mPrevX1 - mMap.getWidth() / 2; + pivotY = mPrevY1 - mMap.getHeight() / 2; + } /* handle double tap zoom */ - mMap.animator().animateZoom(300, 2, pivotX, pivotY); + mMap.animator().animateZoom(300, 2, pivotX, pivotY); - } else if (mStartMove > 0) { - /* handle fling gesture */ - mTracker.update(e.getX(), e.getY(), e.getTime()); - float vx = mTracker.getVelocityX(); - float vy = mTracker.getVelocityY(); + } else if (mStartMove > 0) { + /* handle fling gesture */ + mTracker.update(e.getX(), e.getY(), e.getTime()); + float vx = mTracker.getVelocityX(); + float vy = mTracker.getVelocityY(); /* reduce velocity for short moves */ - float t = e.getTime() - mStartMove; - if (t < FLING_MIN_THREHSHOLD) { - t = t / FLING_MIN_THREHSHOLD; - vy *= t * t; - vx *= t * t; - } - doFling(vx, vy); - } - return true; - } - if (action == MotionEvent.ACTION_CANCEL) { - return false; - } - if (action == MotionEvent.ACTION_POINTER_DOWN) { - mStartMove = -1; - updateMulti(e); - return true; - } - if (action == MotionEvent.ACTION_POINTER_UP) { - updateMulti(e); - return true; - } + float t = e.getTime() - mStartMove; + if (t < FLING_MIN_THREHSHOLD) { + t = t / FLING_MIN_THREHSHOLD; + vy *= t * t; + vx *= t * t; + } + doFling(vx, vy); + } + return true; + } + if (action == MotionEvent.ACTION_CANCEL) { + return false; + } + if (action == MotionEvent.ACTION_POINTER_DOWN) { + mStartMove = -1; + updateMulti(e); + return true; + } + if (action == MotionEvent.ACTION_POINTER_UP) { + updateMulti(e); + return true; + } - return false; - } + return false; + } - private static int getAction(MotionEvent e) { - return e.getAction() & MotionEvent.ACTION_MASK; - } + private static int getAction(MotionEvent e) { + return e.getAction() & MotionEvent.ACTION_MASK; + } - private void onActionMove(MotionEvent e) { - ViewController mViewport = mMap.viewport(); - float x1 = e.getX(0); - float y1 = e.getY(0); + private void onActionMove(MotionEvent e) { + ViewController mViewport = mMap.viewport(); + float x1 = e.getX(0); + float y1 = e.getY(0); - float mx = x1 - mPrevX1; - float my = y1 - mPrevY1; + float mx = x1 - mPrevX1; + float my = y1 - mPrevY1; - float width = mMap.getWidth(); - float height = mMap.getHeight(); + float width = mMap.getWidth(); + float height = mMap.getHeight(); - if (e.getPointerCount() < 2) { - mPrevX1 = x1; - mPrevY1 = y1; + if (e.getPointerCount() < 2) { + mPrevX1 = x1; + mPrevY1 = y1; /* double-tap drag zoom */ - if (mDoubleTap) { + if (mDoubleTap) { /* just ignore first move event to set mPrevX/Y */ - if (!mDown) { - mDown = true; - return; - } - if (!mDragZoom && !isMinimalMove(mx, my)) { - mPrevX1 -= mx; - mPrevY1 -= my; - return; - } + if (!mDown) { + mDown = true; + return; + } + if (!mDragZoom && !isMinimalMove(mx, my)) { + mPrevX1 -= mx; + mPrevY1 -= my; + return; + } - // TODO limit scale properly - mDragZoom = true; - mViewport.scaleMap(1 + my / (height / 6), 0, 0); - mMap.updateMap(true); - mStartMove = -1; - return; - } + // TODO limit scale properly + mDragZoom = true; + mViewport.scaleMap(1 + my / (height / 6), 0, 0); + mMap.updateMap(true); + mStartMove = -1; + return; + } /* simple move */ - if (!mEnableMove) - return; + if (!mEnableMove) + return; - if (mStartMove < 0) { - if (!isMinimalMove(mx, my)) { - mPrevX1 -= mx; - mPrevY1 -= my; - return; - } + if (mStartMove < 0) { + if (!isMinimalMove(mx, my)) { + mPrevX1 -= mx; + mPrevY1 -= my; + return; + } - mStartMove = e.getTime(); - mTracker.start(x1, y1, mStartMove); - return; - } - mViewport.moveMap(mx, my); - mTracker.update(x1, y1, e.getTime()); - mMap.updateMap(true); - return; - } - mStartMove = -1; + mStartMove = e.getTime(); + mTracker.start(x1, y1, mStartMove); + return; + } + mViewport.moveMap(mx, my); + mTracker.update(x1, y1, e.getTime()); + mMap.updateMap(true); + return; + } + mStartMove = -1; - float x2 = e.getX(1); - float y2 = e.getY(1); - float dx = (x1 - x2); - float dy = (y1 - y2); + float x2 = e.getX(1); + float y2 = e.getY(1); + float dx = (x1 - x2); + float dy = (y1 - y2); - double rotateBy = 0; - float scaleBy = 1; - float tiltBy = 0; + double rotateBy = 0; + float scaleBy = 1; + float tiltBy = 0; - mx = ((x1 + x2) - (mPrevX1 + mPrevX2)) / 2; - my = ((y1 + y2) - (mPrevY1 + mPrevY2)) / 2; + mx = ((x1 + x2) - (mPrevX1 + mPrevX2)) / 2; + my = ((y1 + y2) - (mPrevY1 + mPrevY2)) / 2; - if (mCanTilt) { - float slope = (dx == 0) ? 0 : dy / dx; + if (mCanTilt) { + float slope = (dx == 0) ? 0 : dy / dx; - if (Math.abs(slope) < PINCH_TILT_SLOPE) { + if (Math.abs(slope) < PINCH_TILT_SLOPE) { - if (mDoTilt) { - tiltBy = my / 5; - } else if (Math.abs(my) > (dpi / PINCH_TILT_THRESHOLD)) { + if (mDoTilt) { + tiltBy = my / 5; + } else if (Math.abs(my) > (dpi / PINCH_TILT_THRESHOLD)) { /* enter exclusive tilt mode */ - mCanScale = false; - mCanRotate = false; - mDoTilt = true; - } - } - } + mCanScale = false; + mCanRotate = false; + mDoTilt = true; + } + } + } - double pinchWidth = Math.sqrt(dx * dx + dy * dy); - double deltaPinch = pinchWidth - mPrevPinchWidth; + double pinchWidth = Math.sqrt(dx * dx + dy * dy); + double deltaPinch = pinchWidth - mPrevPinchWidth; - if (mCanRotate) { - double rad = Math.atan2(dy, dx); - double r = rad - mAngle; + if (mCanRotate) { + double rad = Math.atan2(dy, dx); + double r = rad - mAngle; - if (mDoRotate) { - double da = rad - mAngle; + if (mDoRotate) { + double da = rad - mAngle; - if (Math.abs(da) > 0.0001) { - rotateBy = da; - mAngle = rad; + if (Math.abs(da) > 0.0001) { + rotateBy = da; + mAngle = rad; - deltaPinch = 0; - } - } else { - r = Math.abs(r); - if (r > PINCH_ROTATE_THRESHOLD) { + deltaPinch = 0; + } + } else { + r = Math.abs(r); + if (r > PINCH_ROTATE_THRESHOLD) { /* start rotate, disable tilt */ - mDoRotate = true; - mCanTilt = false; + mDoRotate = true; + mCanTilt = false; - mAngle = rad; - } else if (!mDoScale) { + mAngle = rad; + } else if (!mDoScale) { /* reduce pinch trigger by the amount of rotation */ - deltaPinch *= 1 - (r / PINCH_ROTATE_THRESHOLD); - } else { - mPrevPinchWidth = pinchWidth; - } - } - } else if (mDoScale && mEnableRotate) { + deltaPinch *= 1 - (r / PINCH_ROTATE_THRESHOLD); + } else { + mPrevPinchWidth = pinchWidth; + } + } + } else if (mDoScale && mEnableRotate) { /* re-enable rotation when higher threshold is reached */ - double rad = Math.atan2(dy, dx); - double r = rad - mAngle; + double rad = Math.atan2(dy, dx); + double r = rad - mAngle; - if (r > PINCH_ROTATE_THRESHOLD2) { + if (r > PINCH_ROTATE_THRESHOLD2) { /* start rotate again */ - mDoRotate = true; - mCanRotate = true; - mAngle = rad; - } - } + mDoRotate = true; + mCanRotate = true; + mAngle = rad; + } + } - if (mCanScale || mDoRotate) { - if (!(mDoScale || mDoRotate)) { + if (mCanScale || mDoRotate) { + if (!(mDoScale || mDoRotate)) { /* enter exclusive scale mode */ - if (Math.abs(deltaPinch) > (dpi / PINCH_ZOOM_THRESHOLD)) { + if (Math.abs(deltaPinch) > (dpi / PINCH_ZOOM_THRESHOLD)) { - if (!mDoRotate) { - mPrevPinchWidth = pinchWidth; - mCanRotate = false; - } + if (!mDoRotate) { + mPrevPinchWidth = pinchWidth; + mCanRotate = false; + } - mCanTilt = false; - mDoScale = true; - } - } - if (mDoScale || mDoRotate) { - scaleBy = (float) (pinchWidth / mPrevPinchWidth); - mPrevPinchWidth = pinchWidth; - } - } + mCanTilt = false; + mDoScale = true; + } + } + if (mDoScale || mDoRotate) { + scaleBy = (float) (pinchWidth / mPrevPinchWidth); + mPrevPinchWidth = pinchWidth; + } + } - if (!(mDoRotate || mDoScale || mDoTilt)) - return; + if (!(mDoRotate || mDoScale || mDoTilt)) + return; - float pivotX = 0, pivotY = 0; + float pivotX = 0, pivotY = 0; - if (!mFixOnCenter) { - pivotX = (x2 + x1) / 2 - width / 2; - pivotY = (y2 + y1) / 2 - height / 2; - } + if (!mFixOnCenter) { + pivotX = (x2 + x1) / 2 - width / 2; + pivotY = (y2 + y1) / 2 - height / 2; + } - synchronized (mViewport) { - if (!mDoTilt) { - if (rotateBy != 0) - mViewport.rotateMap(rotateBy, pivotX, pivotY); - if (scaleBy != 1) - mViewport.scaleMap(scaleBy, pivotX, pivotY); + synchronized (mViewport) { + if (!mDoTilt) { + if (rotateBy != 0) + mViewport.rotateMap(rotateBy, pivotX, pivotY); + if (scaleBy != 1) + mViewport.scaleMap(scaleBy, pivotX, pivotY); - if (!mFixOnCenter) - mViewport.moveMap(mx, my); - } else { - if (tiltBy != 0 && mViewport.tiltMap(-tiltBy)) - mViewport.moveMap(0, my / 2); - } - } + if (!mFixOnCenter) + mViewport.moveMap(mx, my); + } else { + if (tiltBy != 0 && mViewport.tiltMap(-tiltBy)) + mViewport.moveMap(0, my / 2); + } + } - mPrevX1 = x1; - mPrevY1 = y1; - mPrevX2 = x2; - mPrevY2 = y2; + mPrevX1 = x1; + mPrevY1 = y1; + mPrevX2 = x2; + mPrevY2 = y2; - mMap.updateMap(true); - } + mMap.updateMap(true); + } - private void updateMulti(MotionEvent e) { - int cnt = e.getPointerCount(); + private void updateMulti(MotionEvent e) { + int cnt = e.getPointerCount(); - mPrevX1 = e.getX(0); - mPrevY1 = e.getY(0); + mPrevX1 = e.getX(0); + mPrevY1 = e.getY(0); - if (cnt == 2) { - mDoScale = false; - mDoRotate = false; - mDoTilt = false; - mCanScale = mEnableScale; - mCanRotate = mEnableRotate; - mCanTilt = mEnableTilt; + if (cnt == 2) { + mDoScale = false; + mDoRotate = false; + mDoTilt = false; + mCanScale = mEnableScale; + mCanRotate = mEnableRotate; + mCanTilt = mEnableTilt; - mPrevX2 = e.getX(1); - mPrevY2 = e.getY(1); - double dx = mPrevX1 - mPrevX2; - double dy = mPrevY1 - mPrevY2; + mPrevX2 = e.getX(1); + mPrevY2 = e.getY(1); + double dx = mPrevX1 - mPrevX2; + double dy = mPrevY1 - mPrevY2; - mAngle = Math.atan2(dy, dx); - mPrevPinchWidth = Math.sqrt(dx * dx + dy * dy); - } - } + mAngle = Math.atan2(dy, dx); + mPrevPinchWidth = Math.sqrt(dx * dx + dy * dy); + } + } - private boolean isMinimalMove(float mx, float my) { - float minSlop = (dpi / MIN_SLOP); - return !withinSquaredDist(mx, my, minSlop * minSlop); - } + private boolean isMinimalMove(float mx, float my) { + float minSlop = (dpi / MIN_SLOP); + return !withinSquaredDist(mx, my, minSlop * minSlop); + } - private boolean doFling(float velocityX, float velocityY) { + private boolean doFling(float velocityX, float velocityY) { - int w = Tile.SIZE * 5; - int h = Tile.SIZE * 5; + int w = Tile.SIZE * 5; + int h = Tile.SIZE * 5; - mMap.animator().animateFling(velocityX * 2, velocityY * 2, - -w, w, -h, h); - return true; - } + mMap.animator().animateFling(velocityX * 2, velocityY * 2, + -w, w, -h, h); + return true; + } - @Override - public boolean onGesture(Gesture g, MotionEvent e) { - if (g == Gesture.DOUBLE_TAP) { - mDoubleTap = true; - return true; - } - return false; - } + @Override + public boolean onGesture(Gesture g, MotionEvent e) { + if (g == Gesture.DOUBLE_TAP) { + mDoubleTap = true; + return true; + } + return false; + } - static class VelocityTracker { - /* sample window, 200ms */ - private static final int MAX_MS = 200; - private static final int SAMPLES = 32; + static class VelocityTracker { + /* sample window, 200ms */ + private static final int MAX_MS = 200; + private static final int SAMPLES = 32; - private float mLastX, mLastY; - private long mLastTime; - private int mNumSamples; - private int mIndex; + private float mLastX, mLastY; + private long mLastTime; + private int mNumSamples; + private int mIndex; - private float[] mMeanX = new float[SAMPLES]; - private float[] mMeanY = new float[SAMPLES]; - private int[] mMeanTime = new int[SAMPLES]; + private float[] mMeanX = new float[SAMPLES]; + private float[] mMeanY = new float[SAMPLES]; + private int[] mMeanTime = new int[SAMPLES]; - public void start(float x, float y, long time) { - mLastX = x; - mLastY = y; - mNumSamples = 0; - mIndex = SAMPLES; - mLastTime = time; - } + public void start(float x, float y, long time) { + mLastX = x; + mLastY = y; + mNumSamples = 0; + mIndex = SAMPLES; + mLastTime = time; + } - public void update(float x, float y, long time) { - if (time == mLastTime) - return; + public void update(float x, float y, long time) { + if (time == mLastTime) + return; - if (--mIndex < 0) - mIndex = SAMPLES - 1; + if (--mIndex < 0) + mIndex = SAMPLES - 1; - mMeanX[mIndex] = x - mLastX; - mMeanY[mIndex] = y - mLastY; - mMeanTime[mIndex] = (int) (time - mLastTime); + mMeanX[mIndex] = x - mLastX; + mMeanY[mIndex] = y - mLastY; + mMeanTime[mIndex] = (int) (time - mLastTime); - mLastTime = time; - mLastX = x; - mLastY = y; + mLastTime = time; + mLastX = x; + mLastY = y; - mNumSamples++; - } + mNumSamples++; + } - private float getVelocity(float[] move) { - mNumSamples = Math.min(SAMPLES, mNumSamples); + private float getVelocity(float[] move) { + mNumSamples = Math.min(SAMPLES, mNumSamples); - double duration = 0; - double amount = 0; + double duration = 0; + double amount = 0; - for (int c = 0; c < mNumSamples; c++) { - int index = (mIndex + c) % SAMPLES; + for (int c = 0; c < mNumSamples; c++) { + int index = (mIndex + c) % SAMPLES; - float d = mMeanTime[index]; - if (c > 0 && duration + d > MAX_MS) - break; + float d = mMeanTime[index]; + if (c > 0 && duration + d > MAX_MS) + break; - duration += d; - amount += move[index] * (d / duration); - } + duration += d; + amount += move[index] * (d / duration); + } - if (duration == 0) - return 0; + if (duration == 0) + return 0; - return (float) ((amount * 1000) / duration); - } + return (float) ((amount * 1000) / duration); + } - public float getVelocityY() { - return getVelocity(mMeanY); - } + public float getVelocityY() { + return getVelocity(mMeanY); + } - public float getVelocityX() { - return getVelocity(mMeanX); - } - } + public float getVelocityX() { + return getVelocity(mMeanX); + } + } } diff --git a/vtm/src/org/oscim/layers/PathLayer.java b/vtm/src/org/oscim/layers/PathLayer.java index 47fbcf29..245360b1 100644 --- a/vtm/src/org/oscim/layers/PathLayer.java +++ b/vtm/src/org/oscim/layers/PathLayer.java @@ -18,9 +18,6 @@ package org.oscim.layers; -import java.util.ArrayList; -import java.util.List; - import org.oscim.backend.canvas.Paint.Cap; import org.oscim.core.GeoPoint; import org.oscim.core.GeometryBuffer; @@ -37,374 +34,377 @@ import org.oscim.utils.FastMath; import org.oscim.utils.async.SimpleWorker; import org.oscim.utils.geom.LineClipper; -/** This class draws a path line in given color. */ +import java.util.ArrayList; +import java.util.List; + +/** + * This class draws a path line in given color. + */ public class PathLayer extends Layer { - /** Stores points, converted to the map projection. */ - protected final ArrayList mPoints; - protected boolean mUpdatePoints; + /** + * Stores points, converted to the map projection. + */ + protected final ArrayList mPoints; + protected boolean mUpdatePoints; - /** Line style */ - LineStyle mLineStyle; + /** + * Line style + */ + LineStyle mLineStyle; - final Worker mWorker; + final Worker mWorker; - public PathLayer(Map map, int lineColor, float lineWidth) { - super(map); - mWorker = new Worker(map); - mLineStyle = new LineStyle(lineColor, lineWidth, Cap.BUTT); - mRenderer = new RenderPath(); - mPoints = new ArrayList(); - } + public PathLayer(Map map, int lineColor, float lineWidth) { + super(map); + mWorker = new Worker(map); + mLineStyle = new LineStyle(lineColor, lineWidth, Cap.BUTT); + mRenderer = new RenderPath(); + mPoints = new ArrayList(); + } - public PathLayer(Map map, int lineColor) { - this(map, lineColor, 2); - } + public PathLayer(Map map, int lineColor) { + this(map, lineColor, 2); + } - public void clearPath() { - if (mPoints.isEmpty()) - return; + public void clearPath() { + if (mPoints.isEmpty()) + return; - synchronized (mPoints) { - mPoints.clear(); - } - updatePoints(); - } + synchronized (mPoints) { + mPoints.clear(); + } + updatePoints(); + } - public void setPoints(List pts) { - synchronized (mPoints) { - mPoints.clear(); - mPoints.addAll(pts); - } - updatePoints(); - } + public void setPoints(List pts) { + synchronized (mPoints) { + mPoints.clear(); + mPoints.addAll(pts); + } + updatePoints(); + } - public void addPoint(GeoPoint pt) { - synchronized (mPoints) { - mPoints.add(pt); - } - updatePoints(); - } + public void addPoint(GeoPoint pt) { + synchronized (mPoints) { + mPoints.add(pt); + } + updatePoints(); + } - public void addPoint(int latitudeE6, int longitudeE6) { - synchronized (mPoints) { - mPoints.add(new GeoPoint(latitudeE6, longitudeE6)); - } - updatePoints(); - } + public void addPoint(int latitudeE6, int longitudeE6) { + synchronized (mPoints) { + mPoints.add(new GeoPoint(latitudeE6, longitudeE6)); + } + updatePoints(); + } - private void updatePoints() { - mWorker.submit(10); - mUpdatePoints = true; - } + private void updatePoints() { + mWorker.submit(10); + mUpdatePoints = true; + } - public List getPoints() { - return mPoints; - } + public List getPoints() { + return mPoints; + } - /** - * FIXME To be removed - * - * @deprecated - * - */ - public void setGeom(GeometryBuffer geom) { - mGeom = geom; - mWorker.submit(10); - } + /** + * FIXME To be removed + * + * @deprecated + */ + public void setGeom(GeometryBuffer geom) { + mGeom = geom; + mWorker.submit(10); + } - GeometryBuffer mGeom; + GeometryBuffer mGeom; - /** - * Draw a great circle. Calculate a point for every 100km along the path. - * - * @param startPoint - * start point of the great circle - * @param endPoint - * end point of the great circle - */ - public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint) { - synchronized (mPoints) { + /** + * Draw a great circle. Calculate a point for every 100km along the path. + * + * @param startPoint start point of the great circle + * @param endPoint end point of the great circle + */ + public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint) { + synchronized (mPoints) { /* get the great circle path length in meters */ - double length = startPoint.distanceTo(endPoint); + double length = startPoint.distanceTo(endPoint); /* add one point for every 100kms of the great circle path */ - int numberOfPoints = (int) (length / 100000); + int numberOfPoints = (int) (length / 100000); - addGreatCircle(startPoint, endPoint, numberOfPoints); - } - } + addGreatCircle(startPoint, endPoint, numberOfPoints); + } + } - /** - * Draw a great circle. - * - * @param startPoint - * start point of the great circle - * @param endPoint - * end point of the great circle - * @param numberOfPoints - * number of points to calculate along the path - */ - public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint, - final int numberOfPoints) { - // adapted from page - // http://compastic.blogspot.co.uk/2011/07/how-to-draw-great-circle-on-map-in.html - // which was adapted from page http://maps.forum.nu/gm_flight_path.html + /** + * Draw a great circle. + * + * @param startPoint start point of the great circle + * @param endPoint end point of the great circle + * @param numberOfPoints number of points to calculate along the path + */ + public void addGreatCircle(GeoPoint startPoint, GeoPoint endPoint, + final int numberOfPoints) { + // adapted from page + // http://compastic.blogspot.co.uk/2011/07/how-to-draw-great-circle-on-map-in.html + // which was adapted from page http://maps.forum.nu/gm_flight_path.html - // convert to radians - double lat1 = startPoint.getLatitude() * Math.PI / 180; - double lon1 = startPoint.getLongitude() * Math.PI / 180; - double lat2 = endPoint.getLatitude() * Math.PI / 180; - double lon2 = endPoint.getLongitude() * Math.PI / 180; + // convert to radians + double lat1 = startPoint.getLatitude() * Math.PI / 180; + double lon1 = startPoint.getLongitude() * Math.PI / 180; + double lat2 = endPoint.getLatitude() * Math.PI / 180; + double lon2 = endPoint.getLongitude() * Math.PI / 180; - double d = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) - + Math.cos(lat1) * Math.cos(lat2) - * Math.pow(Math.sin((lon1 - lon2) / 2), 2))); - double bearing = Math.atan2( - Math.sin(lon1 - lon2) * Math.cos(lat2), - Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) - * Math.cos(lat2) - * Math.cos(lon1 - lon2)) - / -(Math.PI / 180); - bearing = bearing < 0 ? 360 + bearing : bearing; + double d = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + + Math.cos(lat1) * Math.cos(lat2) + * Math.pow(Math.sin((lon1 - lon2) / 2), 2))); + double bearing = Math.atan2( + Math.sin(lon1 - lon2) * Math.cos(lat2), + Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) + * Math.cos(lat2) + * Math.cos(lon1 - lon2)) + / -(Math.PI / 180); + bearing = bearing < 0 ? 360 + bearing : bearing; - for (int i = 0, j = numberOfPoints + 1; i < j; i++) { - double f = 1.0 / numberOfPoints * i; - double A = Math.sin((1 - f) * d) / Math.sin(d); - double B = Math.sin(f * d) / Math.sin(d); - double x = A * Math.cos(lat1) * Math.cos(lon1) + B * Math.cos(lat2) - * Math.cos(lon2); - double y = A * Math.cos(lat1) * Math.sin(lon1) + B * Math.cos(lat2) - * Math.sin(lon2); - double z = A * Math.sin(lat1) + B * Math.sin(lat2); + for (int i = 0, j = numberOfPoints + 1; i < j; i++) { + double f = 1.0 / numberOfPoints * i; + double A = Math.sin((1 - f) * d) / Math.sin(d); + double B = Math.sin(f * d) / Math.sin(d); + double x = A * Math.cos(lat1) * Math.cos(lon1) + B * Math.cos(lat2) + * Math.cos(lon2); + double y = A * Math.cos(lat1) * Math.sin(lon1) + B * Math.cos(lat2) + * Math.sin(lon2); + double z = A * Math.sin(lat1) + B * Math.sin(lat2); - double latN = Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))); - double lonN = Math.atan2(y, x); - addPoint((int) (latN / (Math.PI / 180) * 1E6), (int) (lonN / (Math.PI / 180) * 1E6)); - } - } + double latN = Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))); + double lonN = Math.atan2(y, x); + addPoint((int) (latN / (Math.PI / 180) * 1E6), (int) (lonN / (Math.PI / 180) * 1E6)); + } + } - /*** - * everything below runs on GL- and Worker-Thread - ***/ - final class RenderPath extends BucketRenderer { + /*** + * everything below runs on GL- and Worker-Thread + ***/ + final class RenderPath extends BucketRenderer { - public RenderPath() { + public RenderPath() { - buckets.addLineBucket(0, mLineStyle); - } + buckets.addLineBucket(0, mLineStyle); + } - private int mCurX = -1; - private int mCurY = -1; - private int mCurZ = -1; + private int mCurX = -1; + private int mCurY = -1; + private int mCurZ = -1; - @Override - public synchronized void update(GLViewport v) { - int tz = 1 << v.pos.zoomLevel; - int tx = (int) (v.pos.x * tz); - int ty = (int) (v.pos.y * tz); + @Override + public synchronized void update(GLViewport v) { + int tz = 1 << v.pos.zoomLevel; + int tx = (int) (v.pos.x * tz); + int ty = (int) (v.pos.y * tz); - // update layers when map moved by at least one tile - if ((tx != mCurX || ty != mCurY || tz != mCurZ)) { - mWorker.submit(100); - mCurX = tx; - mCurY = ty; - mCurZ = tz; - } + // update layers when map moved by at least one tile + if ((tx != mCurX || ty != mCurY || tz != mCurZ)) { + mWorker.submit(100); + mCurX = tx; + mCurY = ty; + mCurZ = tz; + } - Task t = mWorker.poll(); - if (t == null) - return; + Task t = mWorker.poll(); + if (t == null) + return; - // keep position to render relative to current state - mMapPosition.copy(t.pos); + // keep position to render relative to current state + mMapPosition.copy(t.pos); - // compile new layers - buckets.set(t.bucket.get()); - compile(); - } - } + // compile new layers + buckets.set(t.bucket.get()); + compile(); + } + } - final static class Task { - RenderBuckets bucket = new RenderBuckets(); - MapPosition pos = new MapPosition(); - } + final static class Task { + RenderBuckets bucket = new RenderBuckets(); + MapPosition pos = new MapPosition(); + } - final class Worker extends SimpleWorker { + final class Worker extends SimpleWorker { - // limit coords - private final int max = 2048; + // limit coords + private final int max = 2048; - public Worker(Map map) { - super(map, 0, new Task(), new Task()); - mClipper = new LineClipper(-max, -max, max, max); - mPPoints = new float[0]; - } + public Worker(Map map) { + super(map, 0, new Task(), new Task()); + mClipper = new LineClipper(-max, -max, max, max); + mPPoints = new float[0]; + } - private static final int MIN_DIST = 3; + private static final int MIN_DIST = 3; - // pre-projected points - private double[] mPreprojected = new double[2]; + // pre-projected points + private double[] mPreprojected = new double[2]; - // projected points - private float[] mPPoints; - private final LineClipper mClipper; - private int mNumPoints; + // projected points + private float[] mPPoints; + private final LineClipper mClipper; + private int mNumPoints; - @Override - public boolean doWork(Task task) { + @Override + public boolean doWork(Task task) { - int size = mNumPoints; + int size = mNumPoints; - if (mUpdatePoints) { - synchronized (mPoints) { - mUpdatePoints = false; - mNumPoints = size = mPoints.size(); + if (mUpdatePoints) { + synchronized (mPoints) { + mUpdatePoints = false; + mNumPoints = size = mPoints.size(); - ArrayList geopoints = mPoints; - double[] points = mPreprojected; + ArrayList geopoints = mPoints; + double[] points = mPreprojected; - if (size * 2 >= points.length) { - points = mPreprojected = new double[size * 2]; - mPPoints = new float[size * 2]; - } + if (size * 2 >= points.length) { + points = mPreprojected = new double[size * 2]; + mPPoints = new float[size * 2]; + } - for (int i = 0; i < size; i++) - MercatorProjection.project(geopoints.get(i), points, i); - } + for (int i = 0; i < size; i++) + MercatorProjection.project(geopoints.get(i), points, i); + } - } else if (mGeom != null) { - GeometryBuffer geom = mGeom; - mGeom = null; - size = geom.index[0]; + } else if (mGeom != null) { + GeometryBuffer geom = mGeom; + mGeom = null; + size = geom.index[0]; - double[] points = mPreprojected; + double[] points = mPreprojected; - if (size > points.length) { - points = mPreprojected = new double[size * 2]; - mPPoints = new float[size * 2]; - } + if (size > points.length) { + points = mPreprojected = new double[size * 2]; + mPPoints = new float[size * 2]; + } - for (int i = 0; i < size; i += 2) - MercatorProjection.project(geom.points[i + 1], - geom.points[i], points, - i >> 1); - mNumPoints = size = size >> 1; + for (int i = 0; i < size; i += 2) + MercatorProjection.project(geom.points[i + 1], + geom.points[i], points, + i >> 1); + mNumPoints = size = size >> 1; - } - if (size == 0) { - if (task.bucket.get() != null) { - task.bucket.clear(); - mMap.render(); - } - return true; - } + } + if (size == 0) { + if (task.bucket.get() != null) { + task.bucket.clear(); + mMap.render(); + } + return true; + } - RenderBuckets layers = task.bucket; + RenderBuckets layers = task.bucket; - LineBucket ll = layers.getLineBucket(0); - ll.line = mLineStyle; - ll.scale = ll.line.width; + LineBucket ll = layers.getLineBucket(0); + ll.line = mLineStyle; + ll.scale = ll.line.width; - mMap.getMapPosition(task.pos); + mMap.getMapPosition(task.pos); - int zoomlevel = task.pos.zoomLevel; - task.pos.scale = 1 << zoomlevel; + int zoomlevel = task.pos.zoomLevel; + task.pos.scale = 1 << zoomlevel; - double mx = task.pos.x; - double my = task.pos.y; - double scale = Tile.SIZE * task.pos.scale; + double mx = task.pos.x; + double my = task.pos.y; + double scale = Tile.SIZE * task.pos.scale; - // flip around dateline - int flip = 0; - int maxx = Tile.SIZE << (zoomlevel - 1); + // flip around dateline + int flip = 0; + int maxx = Tile.SIZE << (zoomlevel - 1); - int x = (int) ((mPreprojected[0] - mx) * scale); - int y = (int) ((mPreprojected[1] - my) * scale); + int x = (int) ((mPreprojected[0] - mx) * scale); + int y = (int) ((mPreprojected[1] - my) * scale); - if (x > maxx) { - x -= (maxx * 2); - flip = -1; - } else if (x < -maxx) { - x += (maxx * 2); - flip = 1; - } + if (x > maxx) { + x -= (maxx * 2); + flip = -1; + } else if (x < -maxx) { + x += (maxx * 2); + flip = 1; + } - mClipper.clipStart(x, y); + mClipper.clipStart(x, y); - float[] projected = mPPoints; - int i = addPoint(projected, 0, x, y); + float[] projected = mPPoints; + int i = addPoint(projected, 0, x, y); - float prevX = x; - float prevY = y; + float prevX = x; + float prevY = y; - float[] segment = null; + float[] segment = null; - for (int j = 2; j < size * 2; j += 2) { - x = (int) ((mPreprojected[j + 0] - mx) * scale); - y = (int) ((mPreprojected[j + 1] - my) * scale); + for (int j = 2; j < size * 2; j += 2) { + x = (int) ((mPreprojected[j + 0] - mx) * scale); + y = (int) ((mPreprojected[j + 1] - my) * scale); - int flipDirection = 0; - if (x > maxx) { - x -= maxx * 2; - flipDirection = -1; - } else if (x < -maxx) { - x += maxx * 2; - flipDirection = 1; - } + int flipDirection = 0; + if (x > maxx) { + x -= maxx * 2; + flipDirection = -1; + } else if (x < -maxx) { + x += maxx * 2; + flipDirection = 1; + } - if (flip != flipDirection) { - flip = flipDirection; - if (i > 2) - ll.addLine(projected, i, false); + if (flip != flipDirection) { + flip = flipDirection; + if (i > 2) + ll.addLine(projected, i, false); - mClipper.clipStart(x, y); - i = addPoint(projected, 0, x, y); - continue; - } + mClipper.clipStart(x, y); + i = addPoint(projected, 0, x, y); + continue; + } - int clip = mClipper.clipNext(x, y); - if (clip < 1) { - if (i > 2) - ll.addLine(projected, i, false); + int clip = mClipper.clipNext(x, y); + if (clip < 1) { + if (i > 2) + ll.addLine(projected, i, false); - if (clip < 0) { - /* add line segment */ - segment = mClipper.getLine(segment, 0); - ll.addLine(segment, 4, false); - prevX = mClipper.outX2; - prevY = mClipper.outY2; - } - i = 0; - continue; - } + if (clip < 0) { + /* add line segment */ + segment = mClipper.getLine(segment, 0); + ll.addLine(segment, 4, false); + prevX = mClipper.outX2; + prevY = mClipper.outY2; + } + i = 0; + continue; + } - float dx = x - prevX; - float dy = y - prevY; - if ((i == 0) || FastMath.absMaxCmp(dx, dy, MIN_DIST)) { - projected[i++] = prevX = x; - projected[i++] = prevY = y; - } - } - if (i > 2) - ll.addLine(projected, i, false); + float dx = x - prevX; + float dy = y - prevY; + if ((i == 0) || FastMath.absMaxCmp(dx, dy, MIN_DIST)) { + projected[i++] = prevX = x; + projected[i++] = prevY = y; + } + } + if (i > 2) + ll.addLine(projected, i, false); - // trigger redraw to let renderer fetch the result. - mMap.render(); + // trigger redraw to let renderer fetch the result. + mMap.render(); - return true; - } + return true; + } - @Override - public void cleanup(Task task) { - task.bucket.clear(); - } + @Override + public void cleanup(Task task) { + task.bucket.clear(); + } - private int addPoint(float[] points, int i, int x, int y) { - points[i++] = x; - points[i++] = y; - return i; - } - } + private int addPoint(float[] points, int i, int x, int y) { + points[i++] = x; + points[i++] = y; + return i; + } + } } diff --git a/vtm/src/org/oscim/layers/TileGridLayer.java b/vtm/src/org/oscim/layers/TileGridLayer.java index 541521d9..f2446571 100644 --- a/vtm/src/org/oscim/layers/TileGridLayer.java +++ b/vtm/src/org/oscim/layers/TileGridLayer.java @@ -8,15 +8,15 @@ import org.oscim.theme.styles.TextStyle; public class TileGridLayer extends GenericLayer { - public TileGridLayer(Map map) { - super(map, new GridRenderer()); - } + public TileGridLayer(Map map) { + super(map, new GridRenderer()); + } - public TileGridLayer(Map map, int color, float width, int repeat) { - super(map, new GridRenderer(repeat, new LineStyle(color, width, Cap.BUTT), null)); - } + public TileGridLayer(Map map, int color, float width, int repeat) { + super(map, new GridRenderer(repeat, new LineStyle(color, width, Cap.BUTT), null)); + } - public TileGridLayer(Map map, int color, float width, TextStyle text, int repeat) { - super(map, new GridRenderer(repeat, new LineStyle(color, width, Cap.BUTT), text)); - } + public TileGridLayer(Map map, int color, float width, TextStyle text, int repeat) { + super(map, new GridRenderer(repeat, new LineStyle(color, width, Cap.BUTT), text)); + } } diff --git a/vtm/src/org/oscim/layers/marker/ItemizedLayer.java b/vtm/src/org/oscim/layers/marker/ItemizedLayer.java index a7bbcf5e..a13866da 100644 --- a/vtm/src/org/oscim/layers/marker/ItemizedLayer.java +++ b/vtm/src/org/oscim/layers/marker/ItemizedLayer.java @@ -19,9 +19,6 @@ */ package org.oscim.layers.marker; -import java.util.ArrayList; -import java.util.List; - import org.oscim.core.Box; import org.oscim.core.Point; import org.oscim.event.Gesture; @@ -32,228 +29,230 @@ import org.oscim.map.Viewport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + public class ItemizedLayer extends MarkerLayer implements GestureListener { - static final Logger log = LoggerFactory.getLogger(ItemizedLayer.class); + static final Logger log = LoggerFactory.getLogger(ItemizedLayer.class); - protected final List mItemList; - protected final Point mTmpPoint = new Point(); - protected OnItemGestureListener mOnItemGestureListener; - protected int mDrawnItemsLimit = Integer.MAX_VALUE; + protected final List mItemList; + protected final Point mTmpPoint = new Point(); + protected OnItemGestureListener mOnItemGestureListener; + protected int mDrawnItemsLimit = Integer.MAX_VALUE; - public ItemizedLayer(Map map, MarkerSymbol defaulMarker) { - this(map, new ArrayList(), defaulMarker, null); - } + public ItemizedLayer(Map map, MarkerSymbol defaulMarker) { + this(map, new ArrayList(), defaulMarker, null); + } - public ItemizedLayer(Map map, List list, - MarkerSymbol defaultMarker, - OnItemGestureListener listener) { + public ItemizedLayer(Map map, List list, + MarkerSymbol defaultMarker, + OnItemGestureListener listener) { - super(map, defaultMarker); + super(map, defaultMarker); - mItemList = list; - mOnItemGestureListener = listener; - populate(); - } + mItemList = list; + mOnItemGestureListener = listener; + populate(); + } - public void setOnItemGestureListener(OnItemGestureListener listener) { - mOnItemGestureListener = listener; - } + public void setOnItemGestureListener(OnItemGestureListener listener) { + mOnItemGestureListener = listener; + } - @Override - protected Item createItem(int index) { - return mItemList.get(index); - } + @Override + protected Item createItem(int index) { + return mItemList.get(index); + } - @Override - public int size() { - return Math.min(mItemList.size(), mDrawnItemsLimit); - } + @Override + public int size() { + return Math.min(mItemList.size(), mDrawnItemsLimit); + } - public boolean addItem(Item item) { - final boolean result = mItemList.add(item); - populate(); - return result; - } + public boolean addItem(Item item) { + final boolean result = mItemList.add(item); + populate(); + return result; + } - public void addItem(int location, Item item) { - mItemList.add(location, item); - } + public void addItem(int location, Item item) { + mItemList.add(location, item); + } - public boolean addItems(List items) { - final boolean result = mItemList.addAll(items); - populate(); - return result; - } + public boolean addItems(List items) { + final boolean result = mItemList.addAll(items); + populate(); + return result; + } - public void removeAllItems() { - removeAllItems(true); - } + public void removeAllItems() { + removeAllItems(true); + } - public void removeAllItems(boolean withPopulate) { - mItemList.clear(); - if (withPopulate) { - populate(); - } - } + public void removeAllItems(boolean withPopulate) { + mItemList.clear(); + if (withPopulate) { + populate(); + } + } - public boolean removeItem(Item item) { - final boolean result = mItemList.remove(item); - populate(); - return result; - } + public boolean removeItem(Item item) { + final boolean result = mItemList.remove(item); + populate(); + return result; + } - public Item removeItem(int position) { - final Item result = mItemList.remove(position); - populate(); - return result; - } + public Item removeItem(int position) { + final Item result = mItemList.remove(position); + populate(); + return result; + } - /** - * Each of these methods performs a item sensitive check. If the item is - * located its corresponding method is called. The result of the call is - * returned. Helper methods are provided so that child classes may more - * easily override behavior without resorting to overriding the - * ItemGestureListener methods. - */ - // @Override - // public boolean onTap(MotionEvent event, MapPosition pos) { - // return activateSelectedItems(event, mActiveItemSingleTap); - // } + /** + * Each of these methods performs a item sensitive check. If the item is + * located its corresponding method is called. The result of the call is + * returned. Helper methods are provided so that child classes may more + * easily override behavior without resorting to overriding the + * ItemGestureListener methods. + */ + // @Override + // public boolean onTap(MotionEvent event, MapPosition pos) { + // return activateSelectedItems(event, mActiveItemSingleTap); + // } + protected boolean onSingleTapUpHelper(int index, Item item) { + return mOnItemGestureListener.onItemSingleTapUp(index, item); + } - protected boolean onSingleTapUpHelper(int index, Item item) { - return mOnItemGestureListener.onItemSingleTapUp(index, item); - } + private final ActiveItem mActiveItemSingleTap = new ActiveItem() { + @Override + public boolean run(int index) { + final ItemizedLayer that = ItemizedLayer.this; + if (mOnItemGestureListener == null) { + return false; + } + return onSingleTapUpHelper(index, that.mItemList.get(index)); + } + }; - private final ActiveItem mActiveItemSingleTap = new ActiveItem() { - @Override - public boolean run(int index) { - final ItemizedLayer that = ItemizedLayer.this; - if (mOnItemGestureListener == null) { - return false; - } - return onSingleTapUpHelper(index, that.mItemList.get(index)); - } - }; + protected boolean onLongPressHelper(int index, Item item) { + return this.mOnItemGestureListener.onItemLongPress(index, item); + } - protected boolean onLongPressHelper(int index, Item item) { - return this.mOnItemGestureListener.onItemLongPress(index, item); - } + private final ActiveItem mActiveItemLongPress = new ActiveItem() { + @Override + public boolean run(final int index) { + final ItemizedLayer that = ItemizedLayer.this; + if (that.mOnItemGestureListener == null) { + return false; + } + return onLongPressHelper(index, that.mItemList.get(index)); + } + }; - private final ActiveItem mActiveItemLongPress = new ActiveItem() { - @Override - public boolean run(final int index) { - final ItemizedLayer that = ItemizedLayer.this; - if (that.mOnItemGestureListener == null) { - return false; - } - return onLongPressHelper(index, that.mItemList.get(index)); - } - }; + /** + * When a content sensitive action is performed the content item needs to be + * identified. This method does that and then performs the assigned task on + * that item. + * + * @return true if event is handled false otherwise + */ + protected boolean activateSelectedItems(MotionEvent event, ActiveItem task) { + int size = mItemList.size(); + if (size == 0) + return false; - /** - * When a content sensitive action is performed the content item needs to be - * identified. This method does that and then performs the assigned task on - * that item. - * - * @return true if event is handled false otherwise - */ - protected boolean activateSelectedItems(MotionEvent event, ActiveItem task) { - int size = mItemList.size(); - if (size == 0) - return false; + int eventX = (int) event.getX() - mMap.getWidth() / 2; + int eventY = (int) event.getY() - mMap.getHeight() / 2; + Viewport mapPosition = mMap.viewport(); - int eventX = (int) event.getX() - mMap.getWidth() / 2; - int eventY = (int) event.getY() - mMap.getHeight() / 2; - Viewport mapPosition = mMap.viewport(); + Box box = mapPosition.getBBox(null, 128); + box.map2mercator(); + box.scale(1E6); - Box box = mapPosition.getBBox(null, 128); - box.map2mercator(); - box.scale(1E6); - - int nearest = -1; - int inside = -1; - double insideY = -Double.MAX_VALUE; + int nearest = -1; + int inside = -1; + double insideY = -Double.MAX_VALUE; /* squared dist: 50*50 pixel ~ 2mm on 400dpi */ - double dist = 2500; + double dist = 2500; - for (int i = 0; i < size; i++) { - Item item = mItemList.get(i); + for (int i = 0; i < size; i++) { + Item item = mItemList.get(i); - if (!box.contains(item.getPoint().longitudeE6, - item.getPoint().latitudeE6)) - continue; + if (!box.contains(item.getPoint().longitudeE6, + item.getPoint().latitudeE6)) + continue; - mapPosition.toScreenPoint(item.getPoint(), mTmpPoint); + mapPosition.toScreenPoint(item.getPoint(), mTmpPoint); - float dx = (float) (mTmpPoint.x - eventX); - float dy = (float) (mTmpPoint.y - eventY); + float dx = (float) (mTmpPoint.x - eventX); + float dy = (float) (mTmpPoint.y - eventY); - MarkerSymbol it = item.getMarker(); - if (it == null) - it = mMarkerRenderer.mDefaultMarker; + MarkerSymbol it = item.getMarker(); + if (it == null) + it = mMarkerRenderer.mDefaultMarker; - if (it.isInside(dx, dy)) { - if (mTmpPoint.y > insideY) { - insideY = mTmpPoint.y; - inside = i; - } - } - if (inside >= 0) - continue; + if (it.isInside(dx, dy)) { + if (mTmpPoint.y > insideY) { + insideY = mTmpPoint.y; + inside = i; + } + } + if (inside >= 0) + continue; - double d = dx * dx + dy * dy; - if (d > dist) - continue; + double d = dx * dx + dy * dy; + if (d > dist) + continue; - dist = d; - nearest = i; - } + dist = d; + nearest = i; + } - if (inside >= 0) - nearest = inside; + if (inside >= 0) + nearest = inside; - if (nearest >= 0 && task.run(nearest)) { - mMarkerRenderer.update(); - mMap.render(); - return true; - } - return false; - } + if (nearest >= 0 && task.run(nearest)) { + mMarkerRenderer.update(); + mMap.render(); + return true; + } + return false; + } - /** - * When the item is touched one of these methods may be invoked depending on - * the type of touch. Each of them returns true if the event was completely - * handled. - */ - public static interface OnItemGestureListener { - public boolean onItemSingleTapUp(int index, T item); + /** + * When the item is touched one of these methods may be invoked depending on + * the type of touch. Each of them returns true if the event was completely + * handled. + */ + public static interface OnItemGestureListener { + public boolean onItemSingleTapUp(int index, T item); - public boolean onItemLongPress(int index, T item); - } + public boolean onItemLongPress(int index, T item); + } - public static interface ActiveItem { - public boolean run(int aIndex); - } + public static interface ActiveItem { + public boolean run(int aIndex); + } - @Override - public boolean onGesture(Gesture g, MotionEvent e) { - if (g instanceof Gesture.Tap) - return activateSelectedItems(e, mActiveItemSingleTap); + @Override + public boolean onGesture(Gesture g, MotionEvent e) { + if (g instanceof Gesture.Tap) + return activateSelectedItems(e, mActiveItemSingleTap); - if (g instanceof Gesture.LongPress) - return activateSelectedItems(e, mActiveItemLongPress); + if (g instanceof Gesture.LongPress) + return activateSelectedItems(e, mActiveItemLongPress); - return false; - } + return false; + } - public Item getByUid(Object uid) { - for (Item it : mItemList) - if (it.getUid() == uid) - return it; + public Item getByUid(Object uid) { + for (Item it : mItemList) + if (it.getUid() == uid) + return it; - return null; - } + return null; + } } diff --git a/vtm/src/org/oscim/layers/marker/MarkerItem.java b/vtm/src/org/oscim/layers/marker/MarkerItem.java index eb1bb999..8cf6a518 100644 --- a/vtm/src/org/oscim/layers/marker/MarkerItem.java +++ b/vtm/src/org/oscim/layers/marker/MarkerItem.java @@ -29,66 +29,64 @@ import org.oscim.core.GeoPoint; */ public class MarkerItem { - public static final int ITEM_STATE_FOCUSED_MASK = 4; - public static final int ITEM_STATE_PRESSED_MASK = 1; - public static final int ITEM_STATE_SELECTED_MASK = 2; + public static final int ITEM_STATE_FOCUSED_MASK = 4; + public static final int ITEM_STATE_PRESSED_MASK = 1; + public static final int ITEM_STATE_SELECTED_MASK = 2; - /** - * Indicates a hotspot for an area. This is where the origin (0,0) of a - * point will be located relative to the area. In otherwords this acts as an - * offset. NONE indicates that no adjustment should be made. - */ - public enum HotspotPlace { - NONE, CENTER, BOTTOM_CENTER, - TOP_CENTER, RIGHT_CENTER, LEFT_CENTER, - UPPER_RIGHT_CORNER, LOWER_RIGHT_CORNER, - UPPER_LEFT_CORNER, LOWER_LEFT_CORNER - } + /** + * Indicates a hotspot for an area. This is where the origin (0,0) of a + * point will be located relative to the area. In otherwords this acts as an + * offset. NONE indicates that no adjustment should be made. + */ + public enum HotspotPlace { + NONE, CENTER, BOTTOM_CENTER, + TOP_CENTER, RIGHT_CENTER, LEFT_CENTER, + UPPER_RIGHT_CORNER, LOWER_RIGHT_CORNER, + UPPER_LEFT_CORNER, LOWER_LEFT_CORNER + } - public final Object uid; - public final String title; - public final String description; - public final GeoPoint geoPoint; - protected MarkerSymbol mMarker; + public final Object uid; + public final String title; + public final String description; + public final GeoPoint geoPoint; + protected MarkerSymbol mMarker; - /** - * @param title - * this should be singleLine (no '\n' ) - * @param description - * a multiLine description ( '\n' possible) - */ - public MarkerItem(String title, String description, GeoPoint geoPoint) { - this(null, title, description, geoPoint); - } + /** + * @param title this should be singleLine (no '\n' ) + * @param description a multiLine description ( '\n' possible) + */ + public MarkerItem(String title, String description, GeoPoint geoPoint) { + this(null, title, description, geoPoint); + } - public MarkerItem(Object uid, String title, String description, GeoPoint geoPoint) { - this.title = title; - this.description = description; - this.geoPoint = geoPoint; - this.uid = uid; - } + public MarkerItem(Object uid, String title, String description, GeoPoint geoPoint) { + this.title = title; + this.description = description; + this.geoPoint = geoPoint; + this.uid = uid; + } - public Object getUid() { - return uid; - } + public Object getUid() { + return uid; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public String getSnippet() { - return description; - } + public String getSnippet() { + return description; + } - public GeoPoint getPoint() { - return geoPoint; - } + public GeoPoint getPoint() { + return geoPoint; + } - public MarkerSymbol getMarker() { - return mMarker; - } + public MarkerSymbol getMarker() { + return mMarker; + } - public void setMarker(MarkerSymbol marker) { - mMarker = marker; - } + public void setMarker(MarkerSymbol marker) { + mMarker = marker; + } } diff --git a/vtm/src/org/oscim/layers/marker/MarkerLayer.java b/vtm/src/org/oscim/layers/marker/MarkerLayer.java index d14a24be..662f4410 100644 --- a/vtm/src/org/oscim/layers/marker/MarkerLayer.java +++ b/vtm/src/org/oscim/layers/marker/MarkerLayer.java @@ -34,82 +34,79 @@ import org.oscim.map.Map; */ public abstract class MarkerLayer extends Layer { - protected final MarkerRenderer mMarkerRenderer; - protected Item mFocusedItem; + protected final MarkerRenderer mMarkerRenderer; + protected Item mFocusedItem; - /** - * Method by which subclasses create the actual Items. This will only be - * called from populate() we'll cache them for later use. - */ - protected abstract Item createItem(int i); + /** + * Method by which subclasses create the actual Items. This will only be + * called from populate() we'll cache them for later use. + */ + protected abstract Item createItem(int i); - /** - * The number of items in this overlay. - */ - public abstract int size(); + /** + * The number of items in this overlay. + */ + public abstract int size(); - @SuppressWarnings("unchecked") - public MarkerLayer(Map map, MarkerSymbol defaultSymbol) { - super(map); + @SuppressWarnings("unchecked") + public MarkerLayer(Map map, MarkerSymbol defaultSymbol) { + super(map); - mMarkerRenderer = new MarkerRenderer((MarkerLayer) this, defaultSymbol); - mRenderer = mMarkerRenderer; - } + mMarkerRenderer = new MarkerRenderer((MarkerLayer) this, defaultSymbol); + mRenderer = mMarkerRenderer; + } - /** - * Utility method to perform all processing on a new ItemizedOverlay. - * Subclasses provide Items through the createItem(int) method. The subclass - * should call this as soon as it has data, before anything else gets - * called. - */ - protected final void populate() { - mMarkerRenderer.populate(size()); - } + /** + * Utility method to perform all processing on a new ItemizedOverlay. + * Subclasses provide Items through the createItem(int) method. The subclass + * should call this as soon as it has data, before anything else gets + * called. + */ + protected final void populate() { + mMarkerRenderer.populate(size()); + } - /** - * TODO - * If the given Item is found in the overlay, force it to be the current - * focus-bearer. Any registered {link ItemizedLayer#OnFocusChangeListener} - * will be notified. This does not move the map, so if the Item isn't - * already centered, the user may get confused. If the Item is not found, - * this is a no-op. You can also pass null to remove focus. - * - * @param item - */ - public void setFocus(Item item) { - mFocusedItem = item; - } + /** + * TODO + * If the given Item is found in the overlay, force it to be the current + * focus-bearer. Any registered {link ItemizedLayer#OnFocusChangeListener} + * will be notified. This does not move the map, so if the Item isn't + * already centered, the user may get confused. If the Item is not found, + * this is a no-op. You can also pass null to remove focus. + * + * @param item + */ + public void setFocus(Item item) { + mFocusedItem = item; + } - /** - * @return the currently-focused item, or null if no item is currently - * focused. - */ - public Item getFocus() { - return mFocusedItem; - } + /** + * @return the currently-focused item, or null if no item is currently + * focused. + */ + public Item getFocus() { + return mFocusedItem; + } - /** - * TODO - * Interface definition for overlays that contain items that can be snapped - * to (for example, when the user invokes a zoom, this could be called - * allowing the user to snap the zoom to an interesting point.) - */ - public interface Snappable { + /** + * TODO + * Interface definition for overlays that contain items that can be snapped + * to (for example, when the user invokes a zoom, this could be called + * allowing the user to snap the zoom to an interesting point.) + */ + public interface Snappable { - /** - * Checks to see if the given x and y are close enough to an item - * resulting in snapping the current action (e.g. zoom) to the item. - * - * @param x - * The x in screen coordinates. - * @param y - * The y in screen coordinates. - * @param snapPoint - * To be filled with the the interesting point (in screen - * coordinates) that is closest to the given x and y. Can be - * untouched if not snapping. - * @return Whether or not to snap to the interesting point. - */ - boolean onSnapToItem(int x, int y, Point snapPoint); - } + /** + * Checks to see if the given x and y are close enough to an item + * resulting in snapping the current action (e.g. zoom) to the item. + * + * @param x The x in screen coordinates. + * @param y The y in screen coordinates. + * @param snapPoint To be filled with the the interesting point (in screen + * coordinates) that is closest to the given x and y. Can be + * untouched if not snapping. + * @return Whether or not to snap to the interesting point. + */ + boolean onSnapToItem(int x, int y, Point snapPoint); + } } diff --git a/vtm/src/org/oscim/layers/marker/MarkerRenderer.java b/vtm/src/org/oscim/layers/marker/MarkerRenderer.java index 07725152..297e7291 100644 --- a/vtm/src/org/oscim/layers/marker/MarkerRenderer.java +++ b/vtm/src/org/oscim/layers/marker/MarkerRenderer.java @@ -17,8 +17,6 @@ package org.oscim.layers.marker; -import java.util.Comparator; - import org.oscim.core.MercatorProjection; import org.oscim.core.Point; import org.oscim.core.Tile; @@ -29,219 +27,225 @@ import org.oscim.renderer.bucket.SymbolItem; import org.oscim.utils.TimSort; import org.oscim.utils.geom.GeometryUtils; +import java.util.Comparator; + public class MarkerRenderer extends BucketRenderer { - protected final MarkerSymbol mDefaultMarker; + protected final MarkerSymbol mDefaultMarker; - private final SymbolBucket mSymbolLayer; - private final float[] mBox = new float[8]; - private final MarkerLayer mMarkerLayer; - private final Point mMapPoint = new Point(); + private final SymbolBucket mSymbolLayer; + private final float[] mBox = new float[8]; + private final MarkerLayer mMarkerLayer; + private final Point mMapPoint = new Point(); - /** increase view to show items that are partially visible */ - protected int mExtents = 100; + /** + * increase view to show items that are partially visible + */ + protected int mExtents = 100; - /** flag to force update of markers */ - private boolean mUpdate; + /** + * flag to force update of markers + */ + private boolean mUpdate; - private InternalItem[] mItems; + private InternalItem[] mItems; - static class InternalItem { - MarkerItem item; - boolean visible; - boolean changes; - float x, y; - double px, py; - float dy; + static class InternalItem { + MarkerItem item; + boolean visible; + boolean changes; + float x, y; + double px, py; + float dy; - @Override - public String toString() { - return "\n" + x + ":" + y + " / " + dy + " " + visible; - } - } + @Override + public String toString() { + return "\n" + x + ":" + y + " / " + dy + " " + visible; + } + } - public MarkerRenderer(MarkerLayer markerLayer, MarkerSymbol defaultSymbol) { - mSymbolLayer = new SymbolBucket(); - mMarkerLayer = markerLayer; - mDefaultMarker = defaultSymbol; - } + public MarkerRenderer(MarkerLayer markerLayer, MarkerSymbol defaultSymbol) { + mSymbolLayer = new SymbolBucket(); + mMarkerLayer = markerLayer; + mDefaultMarker = defaultSymbol; + } - @Override - public synchronized void update(GLViewport v) { - if (!v.changed() && !mUpdate) - return; + @Override + public synchronized void update(GLViewport v) { + if (!v.changed() && !mUpdate) + return; - mUpdate = false; + mUpdate = false; - double mx = v.pos.x; - double my = v.pos.y; - double scale = Tile.SIZE * v.pos.scale; + double mx = v.pos.x; + double my = v.pos.y; + double scale = Tile.SIZE * v.pos.scale; - //int changesInvisible = 0; - //int changedVisible = 0; - int numVisible = 0; + //int changesInvisible = 0; + //int changedVisible = 0; + int numVisible = 0; - mMarkerLayer.map().viewport().getMapExtents(mBox, mExtents); + mMarkerLayer.map().viewport().getMapExtents(mBox, mExtents); - long flip = (long) (Tile.SIZE * v.pos.scale) >> 1; + long flip = (long) (Tile.SIZE * v.pos.scale) >> 1; - if (mItems == null) { - if (buckets.get() != null) { - buckets.clear(); - compile(); - } - return; - } + if (mItems == null) { + if (buckets.get() != null) { + buckets.clear(); + compile(); + } + return; + } - double angle = Math.toRadians(v.pos.bearing); - float cos = (float) Math.cos(angle); - float sin = (float) Math.sin(angle); + double angle = Math.toRadians(v.pos.bearing); + float cos = (float) Math.cos(angle); + float sin = (float) Math.sin(angle); /* check visibility */ - for (InternalItem it : mItems) { - it.changes = false; - it.x = (float) ((it.px - mx) * scale); - it.y = (float) ((it.py - my) * scale); + for (InternalItem it : mItems) { + it.changes = false; + it.x = (float) ((it.px - mx) * scale); + it.y = (float) ((it.py - my) * scale); - if (it.x > flip) - it.x -= (flip << 1); - else if (it.x < -flip) - it.x += (flip << 1); + if (it.x > flip) + it.x -= (flip << 1); + else if (it.x < -flip) + it.x += (flip << 1); - if (!GeometryUtils.pointInPoly(it.x, it.y, mBox, 8, 0)) { - if (it.visible) { - it.changes = true; - //changesInvisible++; - } - continue; - } + if (!GeometryUtils.pointInPoly(it.x, it.y, mBox, 8, 0)) { + if (it.visible) { + it.changes = true; + //changesInvisible++; + } + continue; + } - it.dy = sin * it.x + cos * it.y; + it.dy = sin * it.x + cos * it.y; - if (!it.visible) { - it.visible = true; - //changedVisible++; - } - numVisible++; - } + if (!it.visible) { + it.visible = true; + //changedVisible++; + } + numVisible++; + } - //log.debug(numVisible + " " + changedVisible + " " + changesInvisible); + //log.debug(numVisible + " " + changedVisible + " " + changesInvisible); /* only update when zoomlevel changed, new items are visible - * or more than 10 of the current items became invisible */ - //if ((numVisible == 0) && (changedVisible == 0 && changesInvisible < 10)) - // return; - buckets.clear(); + * or more than 10 of the current items became invisible */ + //if ((numVisible == 0) && (changedVisible == 0 && changesInvisible < 10)) + // return; + buckets.clear(); - if (numVisible == 0) { - compile(); - return; - } - /* keep position for current state */ - mMapPosition.copy(v.pos); - mMapPosition.bearing = -mMapPosition.bearing; + if (numVisible == 0) { + compile(); + return; + } + /* keep position for current state */ + mMapPosition.copy(v.pos); + mMapPosition.bearing = -mMapPosition.bearing; - sort(mItems, 0, mItems.length); - //log.debug(Arrays.toString(mItems)); - for (InternalItem it : mItems) { - if (!it.visible) - continue; + sort(mItems, 0, mItems.length); + //log.debug(Arrays.toString(mItems)); + for (InternalItem it : mItems) { + if (!it.visible) + continue; - if (it.changes) { - it.visible = false; - continue; - } + if (it.changes) { + it.visible = false; + continue; + } - MarkerSymbol marker = it.item.getMarker(); - if (marker == null) - marker = mDefaultMarker; + MarkerSymbol marker = it.item.getMarker(); + if (marker == null) + marker = mDefaultMarker; - SymbolItem s = SymbolItem.pool.get(); - s.set(it.x, it.y, marker.getBitmap(), true); - s.offset = marker.getHotspot(); - s.billboard = marker.isBillboard(); - mSymbolLayer.pushSymbol(s); - } + SymbolItem s = SymbolItem.pool.get(); + s.set(it.x, it.y, marker.getBitmap(), true); + s.offset = marker.getHotspot(); + s.billboard = marker.isBillboard(); + mSymbolLayer.pushSymbol(s); + } - buckets.set(mSymbolLayer); - buckets.prepare(); + buckets.set(mSymbolLayer); + buckets.prepare(); - compile(); - } + compile(); + } - protected void populate(int size) { + protected void populate(int size) { - InternalItem[] tmp = new InternalItem[size]; + InternalItem[] tmp = new InternalItem[size]; - for (int i = 0; i < size; i++) { - InternalItem it = new InternalItem(); - tmp[i] = it; - it.item = mMarkerLayer.createItem(i); + for (int i = 0; i < size; i++) { + InternalItem it = new InternalItem(); + tmp[i] = it; + it.item = mMarkerLayer.createItem(i); /* pre-project points */ - MercatorProjection.project(it.item.getPoint(), mMapPoint); - it.px = mMapPoint.x; - it.py = mMapPoint.y; - } - synchronized (this) { - mUpdate = true; - mItems = tmp; - } - } + MercatorProjection.project(it.item.getPoint(), mMapPoint); + it.px = mMapPoint.x; + it.py = mMapPoint.y; + } + synchronized (this) { + mUpdate = true; + mItems = tmp; + } + } - public void update() { - mUpdate = true; - } + public void update() { + mUpdate = true; + } - static TimSort ZSORT = new TimSort(); + static TimSort ZSORT = new TimSort(); - public static void sort(InternalItem[] a, int lo, int hi) { - int nRemaining = hi - lo; - if (nRemaining < 2) { - return; - } + public static void sort(InternalItem[] a, int lo, int hi) { + int nRemaining = hi - lo; + if (nRemaining < 2) { + return; + } - ZSORT.doSort(a, zComparator, lo, hi); - } + ZSORT.doSort(a, zComparator, lo, hi); + } - final static Comparator zComparator = new Comparator() { - @Override - public int compare(InternalItem a, InternalItem b) { - if (a.visible && b.visible) { - if (a.dy > b.dy) { - return -1; - } - if (a.dy < b.dy) { - return 1; - } - } else if (a.visible) { - return -1; - } else if (b.visible) { - return 1; - } + final static Comparator zComparator = new Comparator() { + @Override + public int compare(InternalItem a, InternalItem b) { + if (a.visible && b.visible) { + if (a.dy > b.dy) { + return -1; + } + if (a.dy < b.dy) { + return 1; + } + } else if (a.visible) { + return -1; + } else if (b.visible) { + return 1; + } - return 0; - } - }; + return 0; + } + }; - // /** - // * Returns the Item at the given index. - // * - // * @param position - // * the position of the item to return - // * @return the Item of the given index. - // */ - // public final Item getItem(int position) { - // - // synchronized (lock) { - // InternalItem item = mItems; - // for (int i = mSize - position - 1; i > 0 && item != null; i--) - // item = item.next; - // - // if (item != null) - // return item.item; - // - // return null; - // } - // } + // /** + // * Returns the Item at the given index. + // * + // * @param position + // * the position of the item to return + // * @return the Item of the given index. + // */ + // public final Item getItem(int position) { + // + // synchronized (lock) { + // InternalItem item = mItems; + // for (int i = mSize - position - 1; i > 0 && item != null; i--) + // item = item.next; + // + // if (item != null) + // return item.item; + // + // return null; + // } + // } } diff --git a/vtm/src/org/oscim/layers/marker/MarkerSymbol.java b/vtm/src/org/oscim/layers/marker/MarkerSymbol.java index ea38ce44..c7ed654d 100644 --- a/vtm/src/org/oscim/layers/marker/MarkerSymbol.java +++ b/vtm/src/org/oscim/layers/marker/MarkerSymbol.java @@ -21,81 +21,83 @@ import org.oscim.core.PointF; import org.oscim.layers.marker.MarkerItem.HotspotPlace; public class MarkerSymbol { - final Bitmap[] mBitmap; - /** Hotspot offset */ - final PointF mOffset; - final boolean mBillboard; + final Bitmap[] mBitmap; + /** + * Hotspot offset + */ + final PointF mOffset; + final boolean mBillboard; - public MarkerSymbol(Bitmap bitmap, float relX, float relY) { - this(bitmap, relX, relY, true); - } + public MarkerSymbol(Bitmap bitmap, float relX, float relY) { + this(bitmap, relX, relY, true); + } - public MarkerSymbol(Bitmap bitmap, float relX, float relY, boolean billboard) { - mBitmap = new Bitmap[1]; - mBitmap[0] = bitmap; - mOffset = new PointF(relX, relY); - mBillboard = billboard; - } + public MarkerSymbol(Bitmap bitmap, float relX, float relY, boolean billboard) { + mBitmap = new Bitmap[1]; + mBitmap[0] = bitmap; + mOffset = new PointF(relX, relY); + mBillboard = billboard; + } - public MarkerSymbol(Bitmap bitmap, HotspotPlace hotspot) { - this(bitmap, hotspot, true); - } + public MarkerSymbol(Bitmap bitmap, HotspotPlace hotspot) { + this(bitmap, hotspot, true); + } - public MarkerSymbol(Bitmap bitmap, HotspotPlace hotspot, boolean billboard) { + public MarkerSymbol(Bitmap bitmap, HotspotPlace hotspot, boolean billboard) { - switch (hotspot) { - case BOTTOM_CENTER: - mOffset = new PointF(0.5f, 1); - break; - case TOP_CENTER: - mOffset = new PointF(0.5f, 0); - break; - case RIGHT_CENTER: - mOffset = new PointF(1, 0.5f); - break; - case LEFT_CENTER: - mOffset = new PointF(0, 0.5f); - break; - case UPPER_RIGHT_CORNER: - mOffset = new PointF(1, 0); - break; - case LOWER_RIGHT_CORNER: - mOffset = new PointF(1, 1); - break; - case UPPER_LEFT_CORNER: - mOffset = new PointF(0, 0); - break; - case LOWER_LEFT_CORNER: - mOffset = new PointF(0, 1); - break; - default: - mOffset = new PointF(0.5f, 0.5f); - } + switch (hotspot) { + case BOTTOM_CENTER: + mOffset = new PointF(0.5f, 1); + break; + case TOP_CENTER: + mOffset = new PointF(0.5f, 0); + break; + case RIGHT_CENTER: + mOffset = new PointF(1, 0.5f); + break; + case LEFT_CENTER: + mOffset = new PointF(0, 0.5f); + break; + case UPPER_RIGHT_CORNER: + mOffset = new PointF(1, 0); + break; + case LOWER_RIGHT_CORNER: + mOffset = new PointF(1, 1); + break; + case UPPER_LEFT_CORNER: + mOffset = new PointF(0, 0); + break; + case LOWER_LEFT_CORNER: + mOffset = new PointF(0, 1); + break; + default: + mOffset = new PointF(0.5f, 0.5f); + } - mBitmap = new Bitmap[1]; - mBitmap[0] = bitmap; - mBillboard = billboard; - } + mBitmap = new Bitmap[1]; + mBitmap[0] = bitmap; + mBillboard = billboard; + } - public boolean isBillboard() { - return mBillboard; - } + public boolean isBillboard() { + return mBillboard; + } - public PointF getHotspot() { - return mOffset; - } + public PointF getHotspot() { + return mOffset; + } - public Bitmap getBitmap() { - return mBitmap[0]; - } + public Bitmap getBitmap() { + return mBitmap[0]; + } - public boolean isInside(float dx, float dy) { - /* TODO handle no-billboard */ - int w = mBitmap[0].getWidth(); - int h = mBitmap[0].getHeight(); - float ox = -w * mOffset.x; - float oy = -h * (1 - mOffset.y); + public boolean isInside(float dx, float dy) { + /* TODO handle no-billboard */ + int w = mBitmap[0].getWidth(); + int h = mBitmap[0].getHeight(); + float ox = -w * mOffset.x; + float oy = -h * (1 - mOffset.y); - return dx >= ox && dy >= oy && dx <= ox + w && dy <= oy + h; - } + return dx >= ox && dy >= oy && dx <= ox + w && dy <= oy + h; + } } diff --git a/vtm/src/org/oscim/layers/tile/JobQueue.java b/vtm/src/org/oscim/layers/tile/JobQueue.java index 8a9edb61..e8c3c64a 100644 --- a/vtm/src/org/oscim/layers/tile/JobQueue.java +++ b/vtm/src/org/oscim/layers/tile/JobQueue.java @@ -16,82 +16,81 @@ */ package org.oscim.layers.tile; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static org.oscim.layers.tile.MapTile.State.CANCEL; import static org.oscim.layers.tile.MapTile.State.LOADING; import static org.oscim.layers.tile.MapTile.State.NONE; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * A JobQueue keeps the list of pending jobs for a MapView and prioritizes them. */ public class JobQueue { - static final Logger log = LoggerFactory.getLogger(JobQueue.class); + static final Logger log = LoggerFactory.getLogger(JobQueue.class); - private int mCurrentJob = 0; - private MapTile[] mJobs; + private int mCurrentJob = 0; + private MapTile[] mJobs; - /** - * @param tiles - * the jobs to be added to this queue. - */ - public synchronized void setJobs(MapTile[] tiles) { - mJobs = tiles; - mCurrentJob = 0; - } + /** + * @param tiles the jobs to be added to this queue. + */ + public synchronized void setJobs(MapTile[] tiles) { + mJobs = tiles; + mCurrentJob = 0; + } - /** - * Removes all jobs from this queue. - */ - public synchronized void clear() { - if (mJobs == null) { - mCurrentJob = 0; - return; - } - MapTile[] tiles = mJobs; + /** + * Removes all jobs from this queue. + */ + public synchronized void clear() { + if (mJobs == null) { + mCurrentJob = 0; + return; + } + MapTile[] tiles = mJobs; - for (int i = mCurrentJob, n = mJobs.length; i < n; i++) { - MapTile t = tiles[i]; - if (t.state(LOADING | CANCEL)) { - t.setState(NONE); - } else { - log.error("Wrong tile in queue {} {}", t, t.state()); - } - tiles[i] = null; - } - mCurrentJob = 0; - mJobs = null; - } + for (int i = mCurrentJob, n = mJobs.length; i < n; i++) { + MapTile t = tiles[i]; + if (t.state(LOADING | CANCEL)) { + t.setState(NONE); + } else { + log.error("Wrong tile in queue {} {}", t, t.state()); + } + tiles[i] = null; + } + mCurrentJob = 0; + mJobs = null; + } - /** - * @return true if this queue contains no jobs, false otherwise. - */ - public synchronized boolean isEmpty() { - return (mJobs == null); - } + /** + * @return true if this queue contains no jobs, false otherwise. + */ + public synchronized boolean isEmpty() { + return (mJobs == null); + } - /** - * @return the most important job from this queue or null, if empty. - */ - public synchronized MapTile poll() { - if (mJobs == null) - return null; + /** + * @return the most important job from this queue or null, if empty. + */ + public synchronized MapTile poll() { + if (mJobs == null) + return null; - if (mCurrentJob == 0) { - int len = mJobs.length; - if (len > 1) - TileDistanceSort.sort(mJobs, 0, len); - } + if (mCurrentJob == 0) { + int len = mJobs.length; + if (len > 1) + TileDistanceSort.sort(mJobs, 0, len); + } - MapTile t = mJobs[mCurrentJob]; - mJobs[mCurrentJob] = null; + MapTile t = mJobs[mCurrentJob]; + mJobs[mCurrentJob] = null; - if (++mCurrentJob == mJobs.length) - mJobs = null; + if (++mCurrentJob == mJobs.length) + mJobs = null; - return t; + return t; - } + } } diff --git a/vtm/src/org/oscim/layers/tile/MapTile.java b/vtm/src/org/oscim/layers/tile/MapTile.java index 6a91e026..4790d4ab 100644 --- a/vtm/src/org/oscim/layers/tile/MapTile.java +++ b/vtm/src/org/oscim/layers/tile/MapTile.java @@ -16,13 +16,6 @@ */ package org.oscim.layers.tile; -import static org.oscim.layers.tile.MapTile.State.CANCEL; -import static org.oscim.layers.tile.MapTile.State.DEADBEEF; -import static org.oscim.layers.tile.MapTile.State.LOADING; -import static org.oscim.layers.tile.MapTile.State.NEW_DATA; -import static org.oscim.layers.tile.MapTile.State.NONE; -import static org.oscim.layers.tile.MapTile.State.READY; - import org.oscim.core.Tile; import org.oscim.layers.tile.vector.VectorTileLoader; import org.oscim.layers.tile.vector.labeling.LabelTileLoaderHook; @@ -33,422 +26,435 @@ import org.oscim.utils.quadtree.TreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.layers.tile.MapTile.State.CANCEL; +import static org.oscim.layers.tile.MapTile.State.DEADBEEF; +import static org.oscim.layers.tile.MapTile.State.LOADING; +import static org.oscim.layers.tile.MapTile.State.NEW_DATA; +import static org.oscim.layers.tile.MapTile.State.NONE; +import static org.oscim.layers.tile.MapTile.State.READY; + /** * Extends Tile class to hold state and data. - * + *

* Used concurrently in: TileManager (Main Thread), TileLoader (Worker Thread) * and TileRenderer (GL Thread). */ public class MapTile extends Tile { - static final Logger log = LoggerFactory.getLogger(MapTile.class); + static final Logger log = LoggerFactory.getLogger(MapTile.class); - public static class TileNode extends TreeNode { - } + public static class TileNode extends TreeNode { + } - public static final class State { - public final static byte NONE = (1 << 0); + public static final class State { + public final static byte NONE = (1 << 0); - /** - * STATE_LOADING means the tile is about to be loaded / loading. - * Tile belongs to TileLoader thread. - */ - public final static byte LOADING = (1 << 1); + /** + * STATE_LOADING means the tile is about to be loaded / loading. + * Tile belongs to TileLoader thread. + */ + public final static byte LOADING = (1 << 1); - /** - * STATE_NEW_DATA: tile data is prepared for rendering. - * While 'locked' it belongs to GL Thread. - */ - public final static byte NEW_DATA = (1 << 2); + /** + * STATE_NEW_DATA: tile data is prepared for rendering. + * While 'locked' it belongs to GL Thread. + */ + public final static byte NEW_DATA = (1 << 2); - /** - * STATE_READY: tile data is uploaded to GL. - * While 'locked' it belongs to GL Thread. - */ - public final static byte READY = (1 << 3); + /** + * STATE_READY: tile data is uploaded to GL. + * While 'locked' it belongs to GL Thread. + */ + public final static byte READY = (1 << 3); - /** - * STATE_CANCEL: tile is removed from TileManager, - * but may still be processed by TileLoader. - */ - public final static byte CANCEL = (1 << 4); + /** + * STATE_CANCEL: tile is removed from TileManager, + * but may still be processed by TileLoader. + */ + public final static byte CANCEL = (1 << 4); - /** - * Dont touch if you find some. - */ - public final static byte DEADBEEF = (1 << 6); - } + /** + * Dont touch if you find some. + */ + public final static byte DEADBEEF = (1 << 6); + } - public final static int PROXY_CHILD00 = (1 << 0); - public final static int PROXY_CHILD01 = (1 << 1); - public final static int PROXY_CHILD10 = (1 << 2); - public final static int PROXY_CHILD11 = (1 << 3); - public final static int PROXY_PARENT = (1 << 4); - public final static int PROXY_GRAMPA = (1 << 5); - public final static int PROXY_HOLDER = (1 << 6); + public final static int PROXY_CHILD00 = (1 << 0); + public final static int PROXY_CHILD01 = (1 << 1); + public final static int PROXY_CHILD10 = (1 << 2); + public final static int PROXY_CHILD11 = (1 << 3); + public final static int PROXY_PARENT = (1 << 4); + public final static int PROXY_GRAMPA = (1 << 5); + public final static int PROXY_HOLDER = (1 << 6); - /** Tile state */ - byte state = State.NONE; + /** + * Tile state + */ + byte state = State.NONE; - /** - * absolute tile coordinates: tileX,Y / Math.pow(2, zoomLevel) - */ - public final double x; - public final double y; + /** + * absolute tile coordinates: tileX,Y / Math.pow(2, zoomLevel) + */ + public final double x; + public final double y; - /** - * List of TileData for rendering. ElementLayers is always at first - * position (for VectorTileLayer). TileLoaderHooks may add additional - * data. See e.g. {@link LabelTileLoaderHook}. - */ - public TileData data; + /** + * List of TileData for rendering. ElementLayers is always at first + * position (for VectorTileLayer). TileLoaderHooks may add additional + * data. See e.g. {@link LabelTileLoaderHook}. + */ + public TileData data; - /** - * Pointer to access relatives in {@link TileIndex} - */ - public final TileNode node; + /** + * Pointer to access relatives in {@link TileIndex} + */ + public final TileNode node; - /** - * current distance from map center - */ - public float distance; + /** + * current distance from map center + */ + public float distance; - /** - * Tile is in view region. Set by TileRenderer. - */ - public boolean isVisible; + /** + * Tile is in view region. Set by TileRenderer. + */ + public boolean isVisible; - /** - * Used for fade-effects - */ - public long fadeTime; + /** + * Used for fade-effects + */ + public long fadeTime; - /** - * Used to avoid drawing a tile twice per frame - */ - int lastDraw = 0; + /** + * Used to avoid drawing a tile twice per frame + */ + int lastDraw = 0; - /** Keep track which tiles are locked as proxy for this tile */ - private int proxy = 0; + /** + * Keep track which tiles are locked as proxy for this tile + */ + private int proxy = 0; - /** Tile lock counter, synced in TileManager */ - private int locked = 0; + /** + * Tile lock counter, synced in TileManager + */ + private int locked = 0; - private int refs = 0; + private int refs = 0; - /** - * Only used GLRenderer when this tile sits in for another tile. - * e.g. x:-1,y:0,z:1 for x:1,y:0 - */ - MapTile holder; + /** + * Only used GLRenderer when this tile sits in for another tile. + * e.g. x:-1,y:0,z:1 for x:1,y:0 + */ + MapTile holder; - public static abstract class TileData extends Inlist { - Object id; + public static abstract class TileData extends Inlist { + Object id; - protected abstract void dispose(); + protected abstract void dispose(); - public TileData next() { - return (TileData) next; - } - } + public TileData next() { + return (TileData) next; + } + } - public MapTile(TileNode node, int tileX, int tileY, int zoomLevel) { - super(tileX, tileY, (byte) zoomLevel); - this.x = (double) tileX / (1 << zoomLevel); - this.y = (double) tileY / (1 << zoomLevel); - this.node = node; - } + public MapTile(TileNode node, int tileX, int tileY, int zoomLevel) { + super(tileX, tileY, (byte) zoomLevel); + this.x = (double) tileX / (1 << zoomLevel); + this.y = (double) tileY / (1 << zoomLevel); + this.node = node; + } - public boolean state(int testState) { - return (state & testState) != 0; - } + public boolean state(int testState) { + return (state & testState) != 0; + } - public int getState() { - return state; - } + public int getState() { + return state; + } - /** - * @return true when tile could be used by another thread. - */ - boolean isLocked() { - return locked > 0 || refs > 0; - } + /** + * @return true when tile could be used by another thread. + */ + boolean isLocked() { + return locked > 0 || refs > 0; + } - /** - * Set this tile to be locked, i.e. to no be modified or cleared - * while rendering. Renderable parent, grand-parent and children - * will also be locked. Dont forget to unlock when tile is not longer - * used. This function should only be called through {@link TileManager} - */ - void lock() { - if (state == DEADBEEF) { - log.debug("Locking dead tile {}", this); - return; - } + /** + * Set this tile to be locked, i.e. to no be modified or cleared + * while rendering. Renderable parent, grand-parent and children + * will also be locked. Dont forget to unlock when tile is not longer + * used. This function should only be called through {@link TileManager} + */ + void lock() { + if (state == DEADBEEF) { + log.debug("Locking dead tile {}", this); + return; + } - if (locked++ > 0) - return; + if (locked++ > 0) + return; - MapTile p; - /* lock all tiles that could serve as proxy */ - for (int i = 0; i < 4; i++) { - p = node.child(i); - if (p == null) - continue; + MapTile p; + /* lock all tiles that could serve as proxy */ + for (int i = 0; i < 4; i++) { + p = node.child(i); + if (p == null) + continue; - if (p.state(READY | NEW_DATA)) { - proxy |= (1 << i); - p.refs++; - } - } + if (p.state(READY | NEW_DATA)) { + proxy |= (1 << i); + p.refs++; + } + } - if (node.isRoot()) - return; + if (node.isRoot()) + return; - p = node.parent(); - if (p != null && p.state(READY | NEW_DATA)) { - proxy |= PROXY_PARENT; - p.refs++; - } + p = node.parent(); + if (p != null && p.state(READY | NEW_DATA)) { + proxy |= PROXY_PARENT; + p.refs++; + } - if (node.parent.isRoot()) - return; + if (node.parent.isRoot()) + return; - p = node.parent.parent(); - if (p != null && p.state(READY | NEW_DATA)) { - proxy |= PROXY_GRAMPA; - p.refs++; - } - } + p = node.parent.parent(); + if (p != null && p.state(READY | NEW_DATA)) { + proxy |= PROXY_GRAMPA; + p.refs++; + } + } - /** - * Unlocks this tile when it cannot be used by render-thread. - */ - void unlock() { - if (--locked > 0) - return; + /** + * Unlocks this tile when it cannot be used by render-thread. + */ + void unlock() { + if (--locked > 0) + return; - TileNode parent = node.parent; - if ((proxy & PROXY_PARENT) != 0) - parent.item.refs--; + TileNode parent = node.parent; + if ((proxy & PROXY_PARENT) != 0) + parent.item.refs--; - if ((proxy & PROXY_GRAMPA) != 0) { - parent = parent.parent; - parent.item.refs--; - } - for (int i = 0; i < 4; i++) { - if ((proxy & (1 << i)) != 0) - node.child(i).refs--; - } + if ((proxy & PROXY_GRAMPA) != 0) { + parent = parent.parent; + parent.item.refs--; + } + for (int i = 0; i < 4; i++) { + if ((proxy & (1 << i)) != 0) + node.child(i).refs--; + } /* removed all proxy references for this tile */ - proxy = 0; + proxy = 0; - if (state == DEADBEEF) { - log.debug("Unlock dead tile {}", this); - clear(); - } - } + if (state == DEADBEEF) { + log.debug("Unlock dead tile {}", this); + clear(); + } + } - /** - * @return true if tile is state is not NONE. - */ - public boolean isActive() { - return state > State.NONE; - } + /** + * @return true if tile is state is not NONE. + */ + public boolean isActive() { + return state > State.NONE; + } - /** - * Test whether it is save to access a proxy item - * through this.node.* - */ - public boolean hasProxy(int proxy) { - return (this.proxy & proxy) != 0; - } + /** + * Test whether it is save to access a proxy item + * through this.node.* + */ + public boolean hasProxy(int proxy) { + return (this.proxy & proxy) != 0; + } - /** - * CAUTION: This function may only be called - * by {@link TileManager} - */ - protected void clear() { - while (data != null) { - data.dispose(); - data = data.next; - } - setState(NONE); - } + /** + * CAUTION: This function may only be called + * by {@link TileManager} + */ + protected void clear() { + while (data != null) { + data.dispose(); + data = data.next; + } + setState(NONE); + } - /** - * Get the default ElementLayers which are added - * by {@link VectorTileLoader} - */ - public RenderBuckets getBuckets() { - if (!(data instanceof RenderBuckets)) - return null; + /** + * Get the default ElementLayers which are added + * by {@link VectorTileLoader} + */ + public RenderBuckets getBuckets() { + if (!(data instanceof RenderBuckets)) + return null; - return (RenderBuckets) data; - } + return (RenderBuckets) data; + } - public TileData getData(Object id) { - for (TileData d = data; d != null; d = d.next) - if (d.id == id) - return d; - return null; - } + public TileData getData(Object id) { + for (TileData d = data; d != null; d = d.next) + if (d.id == id) + return d; + return null; + } - public void addData(Object id, TileData td) { - /* keeping ElementLayers at position 0! */ - td.id = id; - if (data != null) { - td.next = data.next; - data.next = td; - } else { - data = td; - } - } + public void addData(Object id, TileData td) { + /* keeping ElementLayers at position 0! */ + td.id = id; + if (data != null) { + td.next = data.next; + data.next = td; + } else { + data = td; + } + } - public TileData removeData(Object id) { - if (data == null) - return null; + public TileData removeData(Object id) { + if (data == null) + return null; - TileData prev = data; - if (data.id == id) { - data = data.next; - return prev; - } - for (TileData d = data.next; d != null; d = d.next) { - if (d.id == id) { - prev.next = d.next; - return d; - } - prev = d; - } - return null; - } + TileData prev = data; + if (data.id == id) { + data = data.next; + return prev; + } + for (TileData d = data.next; d != null; d = d.next) { + if (d.id == id) { + prev.next = d.next; + return d; + } + prev = d; + } + return null; + } - public static int depthOffset(MapTile t) { - return ((t.tileX % 4) + (t.tileY % 4 * 4) + 1); - } + public static int depthOffset(MapTile t) { + return ((t.tileX % 4) + (t.tileY % 4 * 4) + 1); + } - public MapTile getProxyChild(int id, byte state) { - if ((proxy & (1 << id)) == 0) - return null; + public MapTile getProxyChild(int id, byte state) { + if ((proxy & (1 << id)) == 0) + return null; - MapTile child = node.child(id); - if (child == null || (child.state & state) == 0) - return null; + MapTile child = node.child(id); + if (child == null || (child.state & state) == 0) + return null; - return child; - } + return child; + } - public MapTile getParent() { - if ((proxy & PROXY_PARENT) == 0) - return null; + public MapTile getParent() { + if ((proxy & PROXY_PARENT) == 0) + return null; - return node.parent.item; - } + return node.parent.item; + } - public MapTile getProxy(int proxy, byte state) { + public MapTile getProxy(int proxy, byte state) { - if ((this.proxy & proxy) == 0) - return null; + if ((this.proxy & proxy) == 0) + return null; - MapTile p = null; - switch (proxy) { - case PROXY_CHILD00: - p = node.child(0); - break; - case PROXY_CHILD01: - p = node.child(1); - break; - case PROXY_CHILD10: - p = node.child(2); - break; - case PROXY_CHILD11: - p = node.child(3); - break; - case PROXY_PARENT: - p = node.parent(); - break; - case PROXY_GRAMPA: - p = node.parent.parent(); - break; - case PROXY_HOLDER: - p = holder; - break; - } + MapTile p = null; + switch (proxy) { + case PROXY_CHILD00: + p = node.child(0); + break; + case PROXY_CHILD01: + p = node.child(1); + break; + case PROXY_CHILD10: + p = node.child(2); + break; + case PROXY_CHILD11: + p = node.child(3); + break; + case PROXY_PARENT: + p = node.parent(); + break; + case PROXY_GRAMPA: + p = node.parent.parent(); + break; + case PROXY_HOLDER: + p = holder; + break; + } - if (p == null || (p.state & state) == 0) - return null; + if (p == null || (p.state & state) == 0) + return null; - return p; - } + return p; + } - public String state() { - switch (state) { - case State.NONE: - return "None"; - case State.LOADING: - return "Loading"; - case State.NEW_DATA: - return "Data"; - case State.READY: - return "Ready"; - case State.CANCEL: - return "Cancel"; - case State.DEADBEEF: - return "Dead"; - } - return ""; - } + public String state() { + switch (state) { + case State.NONE: + return "None"; + case State.LOADING: + return "Loading"; + case State.NEW_DATA: + return "Data"; + case State.READY: + return "Ready"; + case State.CANCEL: + return "Cancel"; + case State.DEADBEEF: + return "Dead"; + } + return ""; + } - public synchronized void setState(byte newState) { - if (state == newState) - return; + public synchronized void setState(byte newState) { + if (state == newState) + return; /* Renderer could have uploaded the tile while the layer * was cleared. This prevents to set tile to READY state. */ /* All other state changes are on the main-thread. */ - if (state == DEADBEEF) - return; + if (state == DEADBEEF) + return; - switch (newState) { - case NONE: - state = newState; - return; + switch (newState) { + case NONE: + state = newState; + return; - case LOADING: - if (state == NONE) { - state = newState; - return; - } - throw new IllegalStateException("Loading" - + " <= " + state() + " " + this); - case NEW_DATA: - if (state == LOADING) { - state = newState; - return; - } - throw new IllegalStateException("NewData" - + " <= " + state() + " " + this); + case LOADING: + if (state == NONE) { + state = newState; + return; + } + throw new IllegalStateException("Loading" + + " <= " + state() + " " + this); + case NEW_DATA: + if (state == LOADING) { + state = newState; + return; + } + throw new IllegalStateException("NewData" + + " <= " + state() + " " + this); - case READY: - if (state == NEW_DATA) { - state = newState; - return; - } - throw new IllegalStateException("Ready" - + " <= " + state() + " " + this); + case READY: + if (state == NEW_DATA) { + state = newState; + return; + } + throw new IllegalStateException("Ready" + + " <= " + state() + " " + this); - case CANCEL: - if (state == LOADING) { - state = newState; - return; - } - throw new IllegalStateException("Cancel" + - " <= " + state() + " " + this); - case DEADBEEF: - state = newState; - return; - } - } + case CANCEL: + if (state == LOADING) { + state = newState; + return; + } + throw new IllegalStateException("Cancel" + + " <= " + state() + " " + this); + case DEADBEEF: + state = newState; + return; + } + } } diff --git a/vtm/src/org/oscim/layers/tile/TileDistanceSort.java b/vtm/src/org/oscim/layers/tile/TileDistanceSort.java index fdbb38e4..33c76708 100644 --- a/vtm/src/org/oscim/layers/tile/TileDistanceSort.java +++ b/vtm/src/org/oscim/layers/tile/TileDistanceSort.java @@ -16,48 +16,48 @@ */ package org.oscim.layers.tile; -import java.util.Comparator; - import org.oscim.utils.TimSort; +import java.util.Comparator; + public class TileDistanceSort extends TimSort { - static TileDistanceSort INSTANCE = new TileDistanceSort(); + static TileDistanceSort INSTANCE = new TileDistanceSort(); - private TileDistanceSort() { - super(); - } + private TileDistanceSort() { + super(); + } - public static void sort(MapTile[] a, int lo, int hi) { - int nRemaining = hi - lo; - if (nRemaining < 2) { - return; - } + public static void sort(MapTile[] a, int lo, int hi) { + int nRemaining = hi - lo; + if (nRemaining < 2) { + return; + } - synchronized (INSTANCE) { - INSTANCE.doSort(a, DistanceComparator, lo, hi); - } - } + synchronized (INSTANCE) { + INSTANCE.doSort(a, DistanceComparator, lo, hi); + } + } - final static Comparator DistanceComparator = new Comparator() { - @Override - public int compare(MapTile a, MapTile b) { - if (a == null) { - if (b == null) - return 0; + final static Comparator DistanceComparator = new Comparator() { + @Override + public int compare(MapTile a, MapTile b) { + if (a == null) { + if (b == null) + return 0; - return 1; - } - if (b == null) - return -1; + return 1; + } + if (b == null) + return -1; - if (a.distance < b.distance) { - return -1; - } - if (a.distance > b.distance) { - return 1; - } - return 0; - } - }; + if (a.distance < b.distance) { + return -1; + } + if (a.distance > b.distance) { + return 1; + } + return 0; + } + }; } diff --git a/vtm/src/org/oscim/layers/tile/TileLayer.java b/vtm/src/org/oscim/layers/tile/TileLayer.java index 495760c9..b64749c4 100644 --- a/vtm/src/org/oscim/layers/tile/TileLayer.java +++ b/vtm/src/org/oscim/layers/tile/TileLayer.java @@ -29,115 +29,115 @@ import org.slf4j.LoggerFactory; */ public abstract class TileLayer extends Layer implements UpdateListener { - static final Logger log = LoggerFactory.getLogger(TileLayer.class); + static final Logger log = LoggerFactory.getLogger(TileLayer.class); - private static final int NUM_LOADERS = 4; + private static final int NUM_LOADERS = 4; - /** - * TileManager responsible for adding visible tiles - * to load queue and managing in-memory tile cache. - */ - protected final TileManager mTileManager; + /** + * TileManager responsible for adding visible tiles + * to load queue and managing in-memory tile cache. + */ + protected final TileManager mTileManager; - protected TileLoader[] mTileLoader; + protected TileLoader[] mTileLoader; - public TileLayer(Map map, TileManager tileManager, TileRenderer renderer) { - super(map); - renderer.setTileManager(tileManager); + public TileLayer(Map map, TileManager tileManager, TileRenderer renderer) { + super(map); + renderer.setTileManager(tileManager); - mTileManager = tileManager; - mRenderer = renderer; + mTileManager = tileManager; + mRenderer = renderer; - } + } - public TileLayer(Map map, TileManager tileManager) { - super(map); - mTileManager = tileManager; - } + public TileLayer(Map map, TileManager tileManager) { + super(map); + mTileManager = tileManager; + } - protected void setRenderer(TileRenderer renderer) { - renderer.setTileManager(mTileManager); - mRenderer = renderer; - } + protected void setRenderer(TileRenderer renderer) { + renderer.setTileManager(mTileManager); + mRenderer = renderer; + } - abstract protected TileLoader createLoader(); + abstract protected TileLoader createLoader(); - public TileRenderer tileRenderer() { - return (TileRenderer) mRenderer; - } + public TileRenderer tileRenderer() { + return (TileRenderer) mRenderer; + } - protected void initLoader(int numLoaders) { - mTileLoader = new TileLoader[numLoaders]; + protected void initLoader(int numLoaders) { + mTileLoader = new TileLoader[numLoaders]; - for (int i = 0; i < numLoaders; i++) { - mTileLoader[i] = createLoader(); - mTileLoader[i].start(); - } - } + for (int i = 0; i < numLoaders; i++) { + mTileLoader[i] = createLoader(); + mTileLoader[i].start(); + } + } - /** - * Override to set number of loader threads. Default is 4. - */ - protected int getNumLoaders() { - return NUM_LOADERS; - } + /** + * Override to set number of loader threads. Default is 4. + */ + protected int getNumLoaders() { + return NUM_LOADERS; + } - @Override - public void onMapEvent(Event event, MapPosition mapPosition) { + @Override + public void onMapEvent(Event event, MapPosition mapPosition) { - if (event == Map.CLEAR_EVENT) { - /* sync with TileRenderer */ - synchronized (mRenderer) { - tileRenderer().clearTiles(); - mTileManager.init(); - } + if (event == Map.CLEAR_EVENT) { + /* sync with TileRenderer */ + synchronized (mRenderer) { + tileRenderer().clearTiles(); + mTileManager.init(); + } - if (mTileManager.update(mapPosition)) - notifyLoaders(); + if (mTileManager.update(mapPosition)) + notifyLoaders(); - } else if (event == Map.POSITION_EVENT) { - if (mTileManager.update(mapPosition)) - notifyLoaders(); - } - } + } else if (event == Map.POSITION_EVENT) { + if (mTileManager.update(mapPosition)) + notifyLoaders(); + } + } - @Override - public void onDetach() { - for (TileLoader loader : mTileLoader) { - loader.pause(); - loader.finish(); - loader.dispose(); - } - } + @Override + public void onDetach() { + for (TileLoader loader : mTileLoader) { + loader.pause(); + loader.finish(); + loader.dispose(); + } + } - void notifyLoaders() { - for (TileLoader loader : mTileLoader) - loader.go(); - } + void notifyLoaders() { + for (TileLoader loader : mTileLoader) + loader.go(); + } - protected void pauseLoaders(boolean wait) { - for (TileLoader loader : mTileLoader) { - loader.cancel(); + protected void pauseLoaders(boolean wait) { + for (TileLoader loader : mTileLoader) { + loader.cancel(); - if (!loader.isPausing()) - loader.pause(); - } + if (!loader.isPausing()) + loader.pause(); + } - if (!wait) - return; + if (!wait) + return; - for (TileLoader loader : mTileLoader) { - if (!loader.isPausing()) - loader.awaitPausing(); - } - } + for (TileLoader loader : mTileLoader) { + if (!loader.isPausing()) + loader.awaitPausing(); + } + } - protected void resumeLoaders() { - for (TileLoader loader : mTileLoader) - loader.proceed(); - } + protected void resumeLoaders() { + for (TileLoader loader : mTileLoader) + loader.proceed(); + } - public TileManager getManager() { - return mTileManager; - } + public TileManager getManager() { + return mTileManager; + } } diff --git a/vtm/src/org/oscim/layers/tile/TileLoader.java b/vtm/src/org/oscim/layers/tile/TileLoader.java index d77726c5..70da7e3a 100644 --- a/vtm/src/org/oscim/layers/tile/TileLoader.java +++ b/vtm/src/org/oscim/layers/tile/TileLoader.java @@ -16,9 +16,6 @@ */ package org.oscim.layers.tile; -import static org.oscim.tiling.QueryResult.FAILED; -import static org.oscim.tiling.QueryResult.SUCCESS; - import org.oscim.backend.canvas.Bitmap; import org.oscim.core.MapElement; import org.oscim.tiling.ITileDataSink; @@ -27,94 +24,99 @@ import org.oscim.utils.PausableThread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.tiling.QueryResult.FAILED; +import static org.oscim.tiling.QueryResult.SUCCESS; + public abstract class TileLoader extends PausableThread implements ITileDataSink { - static final Logger log = LoggerFactory.getLogger(TileLoader.class); + static final Logger log = LoggerFactory.getLogger(TileLoader.class); - private static int id; + private static int id; - private final String THREAD_NAME; - private final TileManager mTileManager; + private final String THREAD_NAME; + private final TileManager mTileManager; - /** currently processed tile */ - protected MapTile mTile; + /** + * currently processed tile + */ + protected MapTile mTile; - public TileLoader(TileManager tileManager) { - super(); - mTileManager = tileManager; - THREAD_NAME = "TileLoader" + (id++); - } + public TileLoader(TileManager tileManager) { + super(); + mTileManager = tileManager; + THREAD_NAME = "TileLoader" + (id++); + } - protected abstract boolean loadTile(MapTile tile); + protected abstract boolean loadTile(MapTile tile); - public void go() { - synchronized (this) { - notify(); - } - } + public void go() { + synchronized (this) { + notify(); + } + } - @Override - protected void doWork() { - mTile = mTileManager.getTileJob(); + @Override + protected void doWork() { + mTile = mTileManager.getTileJob(); - if (mTile == null) - return; + if (mTile == null) + return; - try { - loadTile(mTile); - } catch (Exception e) { - e.printStackTrace(); - completed(FAILED); - } - } + try { + loadTile(mTile); + } catch (Exception e) { + e.printStackTrace(); + completed(FAILED); + } + } - @Override - protected String getThreadName() { - return THREAD_NAME; - } + @Override + protected String getThreadName() { + return THREAD_NAME; + } - @Override - protected int getThreadPriority() { - return (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2; - } + @Override + protected int getThreadPriority() { + return (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2; + } - @Override - protected boolean hasWork() { - return mTileManager.hasTileJobs(); - } + @Override + protected boolean hasWork() { + return mTileManager.hasTileJobs(); + } - public abstract void dispose(); + public abstract void dispose(); - public abstract void cancel(); + public abstract void cancel(); - /** - * Callback to be called by TileDataSource when finished - * loading or on failure. MUST BE CALLED IN ANY CASE! - */ - @Override - public void completed(QueryResult result) { - boolean ok = (result == SUCCESS); + /** + * Callback to be called by TileDataSource when finished + * loading or on failure. MUST BE CALLED IN ANY CASE! + */ + @Override + public void completed(QueryResult result) { + boolean ok = (result == SUCCESS); - if (ok && (isCanceled() || isInterrupted())) - result = QueryResult.FAILED; + if (ok && (isCanceled() || isInterrupted())) + result = QueryResult.FAILED; - mTileManager.jobCompleted(mTile, result); - mTile = null; - } + mTileManager.jobCompleted(mTile, result); + mTile = null; + } - /** - * Called by TileDataSource - */ - @Override - public void process(MapElement element) { + /** + * Called by TileDataSource + */ + @Override + public void process(MapElement element) { - } + } - /** - * Called by TileDataSource - */ - @Override - public void setTileImage(Bitmap bitmap) { + /** + * Called by TileDataSource + */ + @Override + public void setTileImage(Bitmap bitmap) { - } + } } diff --git a/vtm/src/org/oscim/layers/tile/TileManager.java b/vtm/src/org/oscim/layers/tile/TileManager.java index d953be4a..b54275b4 100644 --- a/vtm/src/org/oscim/layers/tile/TileManager.java +++ b/vtm/src/org/oscim/layers/tile/TileManager.java @@ -17,17 +17,6 @@ package org.oscim.layers.tile; -import static org.oscim.layers.tile.MapTile.State.CANCEL; -import static org.oscim.layers.tile.MapTile.State.DEADBEEF; -import static org.oscim.layers.tile.MapTile.State.LOADING; -import static org.oscim.layers.tile.MapTile.State.NEW_DATA; -import static org.oscim.layers.tile.MapTile.State.NONE; -import static org.oscim.layers.tile.MapTile.State.READY; -import static org.oscim.utils.FastMath.clamp; - -import java.util.ArrayList; -import java.util.Arrays; - import org.oscim.core.MapPosition; import org.oscim.core.Tile; import org.oscim.event.Event; @@ -43,674 +32,702 @@ import org.oscim.utils.quadtree.TileIndex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; + +import static org.oscim.layers.tile.MapTile.State.CANCEL; +import static org.oscim.layers.tile.MapTile.State.DEADBEEF; +import static org.oscim.layers.tile.MapTile.State.LOADING; +import static org.oscim.layers.tile.MapTile.State.NEW_DATA; +import static org.oscim.layers.tile.MapTile.State.NONE; +import static org.oscim.layers.tile.MapTile.State.READY; +import static org.oscim.utils.FastMath.clamp; + public class TileManager { - static final Logger log = LoggerFactory.getLogger(TileManager.class); - static final boolean dbg = false; + static final Logger log = LoggerFactory.getLogger(TileManager.class); + static final boolean dbg = false; - public final static Event TILE_LOADED = new Event(); - public final static Event TILE_REMOVED = new Event(); + public final static Event TILE_LOADED = new Event(); + public final static Event TILE_REMOVED = new Event(); - private final int mCacheLimit; - private int mCacheReduce; + private final int mCacheLimit; + private int mCacheReduce; - private int mMinZoom; - private int mMaxZoom; + private int mMinZoom; + private int mMaxZoom; - private int[] mZoomTable; + private int[] mZoomTable; - /** - * limit number tiles with new data not uploaded to GL - * TODO this should depend on the number of tiles displayed - */ - private static final int MAX_TILES_IN_QUEUE = 20; + /** + * limit number tiles with new data not uploaded to GL + * TODO this should depend on the number of tiles displayed + */ + private static final int MAX_TILES_IN_QUEUE = 20; - /** cache limit threshold */ - private static final int CACHE_THRESHOLD = 25; - private static final int CACHE_CLEAR_THRESHOLD = 10; + /** + * cache limit threshold + */ + private static final int CACHE_THRESHOLD = 25; + private static final int CACHE_CLEAR_THRESHOLD = 10; - private final Map mMap; - private final Viewport mViewport; + private final Map mMap; + private final Viewport mViewport; - /** cache for all tiles */ - private MapTile[] mTiles; + /** + * cache for all tiles + */ + private MapTile[] mTiles; - /** actual number of tiles in mTiles */ - private int mTilesCount; + /** + * actual number of tiles in mTiles + */ + private int mTilesCount; - /** current end position in mTiles */ - private int mTilesEnd; + /** + * current end position in mTiles + */ + private int mTilesEnd; - /** counter for tiles with new data not yet loaded to GL */ - private int mTilesToUpload; + /** + * counter for tiles with new data not yet loaded to GL + */ + private int mTilesToUpload; - /** new tile jobs for MapWorkers */ - private final ArrayList mJobs; + /** + * new tile jobs for MapWorkers + */ + private final ArrayList mJobs; - /** counter to check whether current TileSet has changed */ - private int mUpdateSerial; + /** + * counter to check whether current TileSet has changed + */ + private int mUpdateSerial; - /** lock for TileSets while updating MapTile locks - still needed? */ - private final Object mTilelock = new Object(); + /** + * lock for TileSets while updating MapTile locks - still needed? + */ + private final Object mTilelock = new Object(); - private TileSet mCurrentTiles; - /* package */TileSet mNewTiles; + private TileSet mCurrentTiles; + /* package */ TileSet mNewTiles; - /** job queue filled in TileManager and polled by TileLoaders */ - private final JobQueue jobQueue; + /** + * job queue filled in TileManager and polled by TileLoaders + */ + private final JobQueue jobQueue; - private final float[] mMapPlane = new float[8]; + private final float[] mMapPlane = new float[8]; - private boolean mLoadParent; - private int mPrevZoomlevel; + private boolean mLoadParent; + private int mPrevZoomlevel; - private double mLevelUpThreshold = 1; - private double mLevelDownThreshold = 2; + private double mLevelUpThreshold = 1; + private double mLevelDownThreshold = 2; - private final TileIndex mIndex = - new TileIndex() { - @Override - public void removeItem(MapTile t) { - if (t.node == null) - throw new IllegalStateException("Already removed: " + t); + private final TileIndex mIndex = + new TileIndex() { + @Override + public void removeItem(MapTile t) { + if (t.node == null) + throw new IllegalStateException("Already removed: " + t); - super.remove(t.node); - t.node.item = null; - } + super.remove(t.node); + t.node.item = null; + } - @Override - public TileNode create() { - return new TileNode(); - } - }; + @Override + public TileNode create() { + return new TileNode(); + } + }; - public final EventDispatcher events = - new EventDispatcher() { - @Override - public void tell(Listener l, Event event, MapTile tile) { - l.onTileManagerEvent(event, tile); - } - }; + public final EventDispatcher events = + new EventDispatcher() { + @Override + public void tell(Listener l, Event event, MapTile tile) { + l.onTileManagerEvent(event, tile); + } + }; - public interface Listener extends EventListener { - void onTileManagerEvent(Event event, MapTile tile); - }; + public interface Listener extends EventListener { + void onTileManagerEvent(Event event, MapTile tile); + } - public TileManager(Map map, int cacheLimit) { - mMap = map; - mMaxZoom = 20; - mMinZoom = 0; - mCacheLimit = cacheLimit; - mCacheReduce = 0; + ; - mViewport = map.viewport(); + public TileManager(Map map, int cacheLimit) { + mMap = map; + mMaxZoom = 20; + mMinZoom = 0; + mCacheLimit = cacheLimit; + mCacheReduce = 0; - jobQueue = new JobQueue(); - mJobs = new ArrayList(); - mTiles = new MapTile[mCacheLimit]; + mViewport = map.viewport(); - mTilesEnd = 0; - mTilesToUpload = 0; - mUpdateSerial = 0; - } + jobQueue = new JobQueue(); + mJobs = new ArrayList(); + mTiles = new MapTile[mCacheLimit]; - public void setZoomTable(int[] zoomTable) { - mZoomTable = zoomTable; - } + mTilesEnd = 0; + mTilesToUpload = 0; + mUpdateSerial = 0; + } - /** - * TESTING: avoid flickering when switching zoom-levels: - * 1.85, 1.15 seems to work well - */ - public void setZoomThresholds(float down, float up) { - mLevelDownThreshold = clamp(down, 1, 2); - mLevelUpThreshold = clamp(up, 1, 2); - } + public void setZoomTable(int[] zoomTable) { + mZoomTable = zoomTable; + } - public MapTile getTile(int x, int y, int z) { - synchronized (mTilelock) { - return mIndex.getTile(x, y, z); - } - } + /** + * TESTING: avoid flickering when switching zoom-levels: + * 1.85, 1.15 seems to work well + */ + public void setZoomThresholds(float down, float up) { + mLevelDownThreshold = clamp(down, 1, 2); + mLevelUpThreshold = clamp(up, 1, 2); + } - public void init() { - if (mCurrentTiles != null) - mCurrentTiles.releaseTiles(); + public MapTile getTile(int x, int y, int z) { + synchronized (mTilelock) { + return mIndex.getTile(x, y, z); + } + } - mIndex.drop(); + public void init() { + if (mCurrentTiles != null) + mCurrentTiles.releaseTiles(); + + mIndex.drop(); /* Pass VBOs and VertexItems back to pools */ - for (int i = 0; i < mTilesEnd; i++) { - MapTile t = mTiles[i]; - if (t == null) - continue; + for (int i = 0; i < mTilesEnd; i++) { + MapTile t = mTiles[i]; + if (t == null) + continue; /* Check if tile is used by another thread */ - if (!t.isLocked()) - t.clear(); + if (!t.isLocked()) + t.clear(); /* In case the tile is still loading or used by - * another thread: clear when returned from loader + * another thread: clear when returned from loader * or becomes unlocked */ - t.setState(DEADBEEF); - } + t.setState(DEADBEEF); + } /* clear references to cached MapTiles */ - Arrays.fill(mTiles, null); - mTilesEnd = 0; - mTilesCount = 0; + Arrays.fill(mTiles, null); + mTilesEnd = 0; + mTilesCount = 0; /* set up TileSet large enough to hold current tiles */ - int num = Math.max(mMap.getWidth(), mMap.getHeight()); - int size = Tile.SIZE >> 1; - int numTiles = (num * num) / (size * size) * 4; + int num = Math.max(mMap.getWidth(), mMap.getHeight()); + int size = Tile.SIZE >> 1; + int numTiles = (num * num) / (size * size) * 4; - mNewTiles = new TileSet(numTiles); - mCurrentTiles = new TileSet(numTiles); - } + mNewTiles = new TileSet(numTiles); + mCurrentTiles = new TileSet(numTiles); + } - /** - * 1. Update mCurrentTiles TileSet of currently visible tiles. - * 2. Add not yet loaded (or loading) tiles to JobQueue. - * 3. Manage cache - * - * @param pos - * current MapPosition - */ - public boolean update(MapPosition pos) { + /** + * 1. Update mCurrentTiles TileSet of currently visible tiles. + * 2. Add not yet loaded (or loading) tiles to JobQueue. + * 3. Manage cache + * + * @param pos current MapPosition + */ + public boolean update(MapPosition pos) { - // FIXME cant expect init to be called otherwise - // Should use some onLayerAttached callback instead. - if (mNewTiles == null || mNewTiles.tiles.length == 0) { - mPrevZoomlevel = pos.zoomLevel; - init(); - } - /* clear JobQueue and set tiles to state == NONE. + // FIXME cant expect init to be called otherwise + // Should use some onLayerAttached callback instead. + if (mNewTiles == null || mNewTiles.tiles.length == 0) { + mPrevZoomlevel = pos.zoomLevel; + init(); + } + /* clear JobQueue and set tiles to state == NONE. * one could also append new tiles and sort in JobQueue * but this has the nice side-effect that MapWorkers dont * start with old jobs while new jobs are calculated, which * should increase the chance that they are free when new * jobs come in. */ - jobQueue.clear(); + jobQueue.clear(); - if (pos.zoomLevel < mMinZoom) { - if (mCurrentTiles.cnt > 0 && pos.zoomLevel < mMinZoom - 4) { - synchronized (mTilelock) { - mCurrentTiles.releaseTiles(); - } - } - return false; - } + if (pos.zoomLevel < mMinZoom) { + if (mCurrentTiles.cnt > 0 && pos.zoomLevel < mMinZoom - 4) { + synchronized (mTilelock) { + mCurrentTiles.releaseTiles(); + } + } + return false; + } - int tileZoom = clamp(pos.zoomLevel, mMinZoom, mMaxZoom); + int tileZoom = clamp(pos.zoomLevel, mMinZoom, mMaxZoom); - if (mZoomTable == null) { + if (mZoomTable == null) { /* greater 1 when zoomed in further than * tile zoomlevel, so [1..2] while whithin * min/maxZoom */ - double scaleDiv = pos.scale / (1 << tileZoom); - mLoadParent = scaleDiv < 1.5; + double scaleDiv = pos.scale / (1 << tileZoom); + mLoadParent = scaleDiv < 1.5; - int zoomDiff = tileZoom - mPrevZoomlevel; - if (zoomDiff == 1) { + int zoomDiff = tileZoom - mPrevZoomlevel; + if (zoomDiff == 1) { /* dont switch zoomlevel up yet */ - if (scaleDiv < mLevelUpThreshold) { - tileZoom = mPrevZoomlevel; - mLoadParent = false; - } - } else if (zoomDiff == -1) { + if (scaleDiv < mLevelUpThreshold) { + tileZoom = mPrevZoomlevel; + mLoadParent = false; + } + } else if (zoomDiff == -1) { /* dont switch zoomlevel down yet */ - if (scaleDiv > mLevelDownThreshold) { - tileZoom = mPrevZoomlevel; - mLoadParent = true; - } - } - // log.debug("p:{} {}:{}=>{} | {} <> {}", mLoadParent, - // mPrevZoomlevel, pos.zoomLevel, tileZoom, - // scaleDiv, (pos.scale / (1 << tileZoom))); - } else { - mLoadParent = false; - int match = 0; - for (int z : mZoomTable) { - if (z <= tileZoom && z > match) - match = z; - } - if (match == 0) - return false; + if (scaleDiv > mLevelDownThreshold) { + tileZoom = mPrevZoomlevel; + mLoadParent = true; + } + } + // log.debug("p:{} {}:{}=>{} | {} <> {}", mLoadParent, + // mPrevZoomlevel, pos.zoomLevel, tileZoom, + // scaleDiv, (pos.scale / (1 << tileZoom))); + } else { + mLoadParent = false; + int match = 0; + for (int z : mZoomTable) { + if (z <= tileZoom && z > match) + match = z; + } + if (match == 0) + return false; - tileZoom = match; - } - mPrevZoomlevel = tileZoom; + tileZoom = match; + } + mPrevZoomlevel = tileZoom; - mViewport.getMapExtents(mMapPlane, Tile.SIZE / 2); + mViewport.getMapExtents(mMapPlane, Tile.SIZE / 2); /* scan visible tiles. callback function calls 'addTile' * which updates mNewTiles */ - mNewTiles.cnt = 0; - mScanBox.scan(pos.x, pos.y, pos.scale, tileZoom, mMapPlane); + mNewTiles.cnt = 0; + mScanBox.scan(pos.x, pos.y, pos.scale, tileZoom, mMapPlane); - MapTile[] newTiles = mNewTiles.tiles; - int newCnt = mNewTiles.cnt; + MapTile[] newTiles = mNewTiles.tiles; + int newCnt = mNewTiles.cnt; - MapTile[] curTiles = mCurrentTiles.tiles; - int curCnt = mCurrentTiles.cnt; + MapTile[] curTiles = mCurrentTiles.tiles; + int curCnt = mCurrentTiles.cnt; - boolean changed = (newCnt != curCnt); + boolean changed = (newCnt != curCnt); - Arrays.sort(newTiles, 0, newCnt, TileSet.coordComparator); + Arrays.sort(newTiles, 0, newCnt, TileSet.coordComparator); - if (!changed) { + if (!changed) { /* compare if any tile has changed */ - for (int i = 0; i < newCnt; i++) { - if (newTiles[i] != curTiles[i]) { - changed = true; - break; - } - } - } + for (int i = 0; i < newCnt; i++) { + if (newTiles[i] != curTiles[i]) { + changed = true; + break; + } + } + } - if (changed) { - synchronized (mTilelock) { + if (changed) { + synchronized (mTilelock) { /* lock new tiles */ - mNewTiles.lockTiles(); + mNewTiles.lockTiles(); /* unlock previous tiles */ - mCurrentTiles.releaseTiles(); + mCurrentTiles.releaseTiles(); /* swap newTiles with currentTiles */ - TileSet tmp = mCurrentTiles; - mCurrentTiles = mNewTiles; - mNewTiles = tmp; + TileSet tmp = mCurrentTiles; + mCurrentTiles = mNewTiles; + mNewTiles = tmp; - mUpdateSerial++; - } + mUpdateSerial++; + } /* request rendering as tiles changed */ - mMap.render(); - } + mMap.render(); + } /* Add tile jobs to queue */ - if (mJobs.isEmpty()) - return false; + if (mJobs.isEmpty()) + return false; - MapTile[] jobs = new MapTile[mJobs.size()]; - jobs = mJobs.toArray(jobs); - updateDistances(jobs, jobs.length, pos); + MapTile[] jobs = new MapTile[mJobs.size()]; + jobs = mJobs.toArray(jobs); + updateDistances(jobs, jobs.length, pos); /* sets tiles to state == LOADING */ - jobQueue.setJobs(jobs); - mJobs.clear(); + jobQueue.setJobs(jobs); + mJobs.clear(); - if (mCacheReduce < mCacheLimit / 2) { - if (BufferObject.isMaxFill()) { - mCacheReduce += 10; - if (dbg) - log.debug("reduce cache {}", (mCacheLimit - mCacheReduce)); - } else { - mCacheReduce = 0; - } - } + if (mCacheReduce < mCacheLimit / 2) { + if (BufferObject.isMaxFill()) { + mCacheReduce += 10; + if (dbg) + log.debug("reduce cache {}", (mCacheLimit - mCacheReduce)); + } else { + mCacheReduce = 0; + } + } /* limit cache items */ - int remove = mTilesCount - (mCacheLimit - mCacheReduce); + int remove = mTilesCount - (mCacheLimit - mCacheReduce); - if (remove > CACHE_THRESHOLD || mTilesToUpload > MAX_TILES_IN_QUEUE) { - synchronized (mTilelock) { - limitCache(pos, remove); - } - } - return true; - } + if (remove > CACHE_THRESHOLD || mTilesToUpload > MAX_TILES_IN_QUEUE) { + synchronized (mTilelock) { + limitCache(pos, remove); + } + } + return true; + } - public void clearJobs() { - jobQueue.clear(); - } + public void clearJobs() { + jobQueue.clear(); + } - public boolean hasTileJobs() { - return !jobQueue.isEmpty(); - } + public boolean hasTileJobs() { + return !jobQueue.isEmpty(); + } - public MapTile getTileJob() { - return jobQueue.poll(); - } + public MapTile getTileJob() { + return jobQueue.poll(); + } - /** - * Retrive a TileSet of current tiles. Tiles remain locked in cache until - * the set is unlocked by either passing it again to this function or to - * releaseTiles. - * - * @threadsafe - * @param tileSet - * to be updated - * @return true if TileSet has changed - */ - public boolean getActiveTiles(TileSet tileSet) { - if (mCurrentTiles == null) - return false; + /** + * Retrive a TileSet of current tiles. Tiles remain locked in cache until + * the set is unlocked by either passing it again to this function or to + * releaseTiles. + * + * @param tileSet to be updated + * @return true if TileSet has changed + * @threadsafe + */ + public boolean getActiveTiles(TileSet tileSet) { + if (mCurrentTiles == null) + return false; - if (tileSet == null) - return false; + if (tileSet == null) + return false; - if (tileSet.serial == mUpdateSerial) - return false; + if (tileSet.serial == mUpdateSerial) + return false; /* do not flip mNew/mCurrentTiles while copying */ - synchronized (mTilelock) { - tileSet.setTiles(mCurrentTiles); - tileSet.serial = mUpdateSerial; - } - return true; - } + synchronized (mTilelock) { + tileSet.setTiles(mCurrentTiles); + tileSet.serial = mUpdateSerial; + } + return true; + } - MapTile addTile(int x, int y, int zoomLevel) { - MapTile tile = mIndex.getTile(x, y, zoomLevel); + MapTile addTile(int x, int y, int zoomLevel) { + MapTile tile = mIndex.getTile(x, y, zoomLevel); - if (tile == null) { - TileNode n = mIndex.add(x, y, zoomLevel); - tile = n.item = new MapTile(n, x, y, zoomLevel); - tile.setState(LOADING); - mJobs.add(tile); - addToCache(tile); - } else if (!tile.isActive()) { - tile.setState(LOADING); - mJobs.add(tile); - } + if (tile == null) { + TileNode n = mIndex.add(x, y, zoomLevel); + tile = n.item = new MapTile(n, x, y, zoomLevel); + tile.setState(LOADING); + mJobs.add(tile); + addToCache(tile); + } else if (!tile.isActive()) { + tile.setState(LOADING); + mJobs.add(tile); + } - if (mLoadParent && (zoomLevel > mMinZoom) && (mZoomTable == null)) { + if (mLoadParent && (zoomLevel > mMinZoom) && (mZoomTable == null)) { /* prefetch parent */ - MapTile p = tile.node.parent(); - if (p == null) { - TileNode n = mIndex.add(x >> 1, y >> 1, zoomLevel - 1); - p = n.item = new MapTile(n, x >> 1, y >> 1, zoomLevel - 1); - addToCache(p); + MapTile p = tile.node.parent(); + if (p == null) { + TileNode n = mIndex.add(x >> 1, y >> 1, zoomLevel - 1); + p = n.item = new MapTile(n, x >> 1, y >> 1, zoomLevel - 1); + addToCache(p); /* this prevents to add tile twice to queue */ - p.setState(LOADING); - mJobs.add(p); - } else if (!p.isActive()) { - p.setState(LOADING); - mJobs.add(p); - } - } - return tile; - } + p.setState(LOADING); + mJobs.add(p); + } else if (!p.isActive()) { + p.setState(LOADING); + mJobs.add(p); + } + } + return tile; + } - private void addToCache(MapTile tile) { + private void addToCache(MapTile tile) { - if (mTilesEnd == mTiles.length) { - if (mTilesEnd > mTilesCount) { - TileDistanceSort.sort(mTiles, 0, mTilesEnd); + if (mTilesEnd == mTiles.length) { + if (mTilesEnd > mTilesCount) { + TileDistanceSort.sort(mTiles, 0, mTilesEnd); /* sorting also repacks the 'sparse' filled array * so end of mTiles is at mTilesCount now */ - mTilesEnd = mTilesCount; - } + mTilesEnd = mTilesCount; + } - if (mTilesEnd == mTiles.length) { - log.debug("realloc tiles {}", mTilesEnd); - MapTile[] tmp = new MapTile[mTiles.length + 20]; - System.arraycopy(mTiles, 0, tmp, 0, mTilesCount); - mTiles = tmp; - } - } + if (mTilesEnd == mTiles.length) { + log.debug("realloc tiles {}", mTilesEnd); + MapTile[] tmp = new MapTile[mTiles.length + 20]; + System.arraycopy(mTiles, 0, tmp, 0, mTilesCount); + mTiles = tmp; + } + } - mTiles[mTilesEnd++] = tile; - mTilesCount++; - } + mTiles[mTilesEnd++] = tile; + mTilesCount++; + } - private boolean removeFromCache(MapTile t) { + private boolean removeFromCache(MapTile t) { /* TODO check valid states here:When in CANCEL state tile belongs to * TileLoader thread, defer clearing to jobCompleted() */ - if (dbg) - log.debug("remove from cache {} {} {}", - t, t.state(), t.isLocked()); + if (dbg) + log.debug("remove from cache {} {} {}", + t, t.state(), t.isLocked()); - if (t.isLocked()) - return false; + if (t.isLocked()) + return false; - if (t.state(NEW_DATA | READY)) - events.fire(TILE_REMOVED, t); + if (t.state(NEW_DATA | READY)) + events.fire(TILE_REMOVED, t); - t.clear(); + t.clear(); - mIndex.removeItem(t); - mTilesCount--; - return true; - } + mIndex.removeItem(t); + mTilesCount--; + return true; + } - private void limitCache(MapPosition pos, int remove) { - MapTile[] tiles = mTiles; + private void limitCache(MapPosition pos, int remove) { + MapTile[] tiles = mTiles; /* count tiles that have new data */ - int newTileCnt = 0; + int newTileCnt = 0; /* remove tiles that were never loaded */ - for (int i = 0; i < mTilesEnd; i++) { - MapTile t = tiles[i]; - if (t == null) - continue; + for (int i = 0; i < mTilesEnd; i++) { + MapTile t = tiles[i]; + if (t == null) + continue; - if (t.state(NEW_DATA)) - newTileCnt++; + if (t.state(NEW_DATA)) + newTileCnt++; - if (t.state(DEADBEEF)) { - log.debug("found DEADBEEF {}", t); - t.clear(); - tiles[i] = null; - continue; - } + if (t.state(DEADBEEF)) { + log.debug("found DEADBEEF {}", t); + t.clear(); + tiles[i] = null; + continue; + } /* make sure tile cannot be used by GL or MapWorker Thread */ - if (t.state(NONE) && removeFromCache(t)) { - tiles[i] = null; - remove--; - } - } + if (t.state(NONE) && removeFromCache(t)) { + tiles[i] = null; + remove--; + } + } - if ((remove < CACHE_CLEAR_THRESHOLD) && (newTileCnt < MAX_TILES_IN_QUEUE)) - return; + if ((remove < CACHE_CLEAR_THRESHOLD) && (newTileCnt < MAX_TILES_IN_QUEUE)) + return; - updateDistances(tiles, mTilesEnd, pos); - TileDistanceSort.sort(tiles, 0, mTilesEnd); + updateDistances(tiles, mTilesEnd, pos); + TileDistanceSort.sort(tiles, 0, mTilesEnd); /* sorting also repacks the 'sparse' filled array * so end of mTiles is at mTilesCount now */ - mTilesEnd = mTilesCount; + mTilesEnd = mTilesCount; /* start with farest away tile */ - for (int i = mTilesCount - 1; i >= 0 && remove > 0; i--) { - MapTile t = tiles[i]; + for (int i = mTilesCount - 1; i >= 0 && remove > 0; i--) { + MapTile t = tiles[i]; /* dont remove tile used by TileRenderer, or somewhere else * try again in next run. */ - if (t.isLocked()) { - if (dbg) - log.debug("{} locked (state={}, d={})", - t, t.state(), t.distance); - continue; - } + if (t.isLocked()) { + if (dbg) + log.debug("{} locked (state={}, d={})", + t, t.state(), t.distance); + continue; + } - if (t.state(CANCEL)) { - continue; - } + if (t.state(CANCEL)) { + continue; + } /* cancel loading of tiles that should not even be cached */ - if (t.state(LOADING)) { - t.setState(CANCEL); - if (dbg) - log.debug("{} canceled (d={})", t, t.distance); - continue; - } + if (t.state(LOADING)) { + t.setState(CANCEL); + if (dbg) + log.debug("{} canceled (d={})", t, t.distance); + continue; + } /* clear new and unused tile */ - if (t.state(NEW_DATA)) { - newTileCnt--; - if (dbg) - log.debug("{} unused (d=({})", t, t.distance); - } + if (t.state(NEW_DATA)) { + newTileCnt--; + if (dbg) + log.debug("{} unused (d=({})", t, t.distance); + } - if (!t.state(READY | NEW_DATA)) { - log.error("stuff that should be here! {} {}", t, t.state()); - } + if (!t.state(READY | NEW_DATA)) { + log.error("stuff that should be here! {} {}", t, t.state()); + } - if (removeFromCache(t)) { - tiles[i] = null; - remove--; - } - } + if (removeFromCache(t)) { + tiles[i] = null; + remove--; + } + } - for (int i = mTilesCount - 1; i >= 0 && newTileCnt > MAX_TILES_IN_QUEUE; i--) { - MapTile t = tiles[i]; - if ((t != null) && (t.state(NEW_DATA))) { - if (removeFromCache(t)) { - tiles[i] = null; - newTileCnt--; - } - } - } + for (int i = mTilesCount - 1; i >= 0 && newTileCnt > MAX_TILES_IN_QUEUE; i--) { + MapTile t = tiles[i]; + if ((t != null) && (t.state(NEW_DATA))) { + if (removeFromCache(t)) { + tiles[i] = null; + newTileCnt--; + } + } + } - mTilesToUpload = newTileCnt; - } + mTilesToUpload = newTileCnt; + } - /** - * Called by TileLoader thread when tile is loaded. - * - * @threadsafe - * @param tile - * Tile ready for upload in TileRenderLayer - */ - public void jobCompleted(MapTile tile, QueryResult result) { + /** + * Called by TileLoader thread when tile is loaded. + * + * @param tile Tile ready for upload in TileRenderLayer + * @threadsafe + */ + public void jobCompleted(MapTile tile, QueryResult result) { /* send TILE_LOADED event on main-loop */ - mMap.post(new JobCompletedEvent(tile, result)); + mMap.post(new JobCompletedEvent(tile, result)); /* locked means the tile is visible or referenced by * a tile that might be visible. */ - if (tile.isLocked()) { - if (result == QueryResult.DELAYED && tile.isLocked()) - mMap.updateMap(false); - else - mMap.render(); - } - } + if (tile.isLocked()) { + if (result == QueryResult.DELAYED && tile.isLocked()) + mMap.updateMap(false); + else + mMap.render(); + } + } - class JobCompletedEvent implements Runnable { - final MapTile tile; - final QueryResult result; + class JobCompletedEvent implements Runnable { + final MapTile tile; + final QueryResult result; - public JobCompletedEvent(MapTile tile, QueryResult result) { - this.tile = tile; - this.result = result; - } + public JobCompletedEvent(MapTile tile, QueryResult result) { + this.tile = tile; + this.result = result; + } - @Override - public void run() { - if (result == QueryResult.SUCCESS && tile.state(LOADING)) { - tile.setState(NEW_DATA); - events.fire(TILE_LOADED, tile); - mTilesToUpload++; - return; - } - // TODO use mMap.update(true) to retry tile loading? - log.debug("Load: {} {} state:{}", - tile, result, - tile.state()); + @Override + public void run() { + if (result == QueryResult.SUCCESS && tile.state(LOADING)) { + tile.setState(NEW_DATA); + events.fire(TILE_LOADED, tile); + mTilesToUpload++; + return; + } + // TODO use mMap.update(true) to retry tile loading? + log.debug("Load: {} {} state:{}", + tile, result, + tile.state()); /* got orphaned tile */ - if (tile.state(DEADBEEF)) { - tile.clear(); - return; - } + if (tile.state(DEADBEEF)) { + tile.clear(); + return; + } - tile.clear(); - } - } + tile.clear(); + } + } - private static void updateDistances(MapTile[] tiles, int size, MapPosition pos) { + private static void updateDistances(MapTile[] tiles, int size, MapPosition pos) { /* TODO there is probably a better quad-tree distance function */ - int zoom = 20; - long x = (long) (pos.x * (1 << zoom)); - long y = (long) (pos.y * (1 << zoom)); + int zoom = 20; + long x = (long) (pos.x * (1 << zoom)); + long y = (long) (pos.y * (1 << zoom)); - for (int i = 0; i < size; i++) { - MapTile t = tiles[i]; - if (t == null) - continue; + for (int i = 0; i < size; i++) { + MapTile t = tiles[i]; + if (t == null) + continue; - int diff = (zoom - t.zoomLevel); - long dx, dy; + int diff = (zoom - t.zoomLevel); + long dx, dy; - if (diff == 0) { - dx = t.tileX - x; - dy = t.tileY - y; - } else { // diff > 0 - long mx = x >> diff; - long my = y >> diff; + if (diff == 0) { + dx = t.tileX - x; + dy = t.tileY - y; + } else { // diff > 0 + long mx = x >> diff; + long my = y >> diff; - dx = t.tileX - mx; - dy = t.tileY - my; - } + dx = t.tileX - mx; + dy = t.tileY - my; + } - int dz = (pos.zoomLevel - t.zoomLevel); - if (dz == 0) - dz = 1; - else if (dz < -1) - dz *= 0.75; + int dz = (pos.zoomLevel - t.zoomLevel); + if (dz == 0) + dz = 1; + else if (dz < -1) + dz *= 0.75; - t.distance = (dx * dx + dy * dy) * (dz * dz); - } - } + t.distance = (dx * dx + dy * dy) * (dz * dz); + } + } - private final ScanBox mScanBox = new ScanBox() { + private final ScanBox mScanBox = new ScanBox() { - @Override - protected void setVisible(int y, int x1, int x2) { - MapTile[] tiles = mNewTiles.tiles; - int cnt = mNewTiles.cnt; - int maxTiles = tiles.length; + @Override + protected void setVisible(int y, int x1, int x2) { + MapTile[] tiles = mNewTiles.tiles; + int cnt = mNewTiles.cnt; + int maxTiles = tiles.length; - int xmax = 1 << mZoom; + int xmax = 1 << mZoom; - for (int x = x1; x < x2; x++) { - MapTile tile = null; + for (int x = x1; x < x2; x++) { + MapTile tile = null; - if (cnt == maxTiles) { - log.debug("too many tiles {}", maxTiles); - break; - } - int xx = x; + if (cnt == maxTiles) { + log.debug("too many tiles {}", maxTiles); + break; + } + int xx = x; - if (x < 0 || x >= xmax) { + if (x < 0 || x >= xmax) { /* flip-around date line */ - if (x < 0) - xx = xmax + x; - else - xx = x - xmax; + if (x < 0) + xx = xmax + x; + else + xx = x - xmax; - if (xx < 0 || xx >= xmax) - continue; - } + if (xx < 0 || xx >= xmax) + continue; + } /* check if tile is already added */ - for (int i = 0; i < cnt; i++) - if (tiles[i].tileX == xx && tiles[i].tileY == y) { - tile = tiles[i]; - break; - } + for (int i = 0; i < cnt; i++) + if (tiles[i].tileX == xx && tiles[i].tileY == y) { + tile = tiles[i]; + break; + } - if (tile == null) { - tile = addTile(xx, y, mZoom); - tiles[cnt++] = tile; - } - } - mNewTiles.cnt = cnt; - } - }; + if (tile == null) { + tile = addTile(xx, y, mZoom); + tiles[cnt++] = tile; + } + } + mNewTiles.cnt = cnt; + } + }; - public MapTile getTile(int tileX, int tileY, byte zoomLevel) { - return mIndex.getTile(tileX, tileY, zoomLevel); - } + public MapTile getTile(int tileX, int tileY, byte zoomLevel) { + return mIndex.getTile(tileX, tileY, zoomLevel); + } - public void setZoomLevel(int zoomLevelMin, int zoomLevelMax) { - mMinZoom = zoomLevelMin; - mMaxZoom = zoomLevelMax; - } + public void setZoomLevel(int zoomLevelMin, int zoomLevelMax) { + mMinZoom = zoomLevelMin; + mMaxZoom = zoomLevelMax; + } } diff --git a/vtm/src/org/oscim/layers/tile/TileRenderer.java b/vtm/src/org/oscim/layers/tile/TileRenderer.java index 67e5407d..bff8422d 100644 --- a/vtm/src/org/oscim/layers/tile/TileRenderer.java +++ b/vtm/src/org/oscim/layers/tile/TileRenderer.java @@ -16,10 +16,6 @@ */ package org.oscim.layers.tile; -import static org.oscim.layers.tile.MapTile.PROXY_PARENT; -import static org.oscim.layers.tile.MapTile.State.NEW_DATA; -import static org.oscim.layers.tile.MapTile.State.READY; - import org.oscim.layers.tile.MapTile.TileNode; import org.oscim.renderer.BufferObject; import org.oscim.renderer.GLViewport; @@ -30,329 +26,340 @@ import org.oscim.utils.ScanBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.layers.tile.MapTile.PROXY_PARENT; +import static org.oscim.layers.tile.MapTile.State.NEW_DATA; +import static org.oscim.layers.tile.MapTile.State.READY; + public abstract class TileRenderer extends LayerRenderer { - static final Logger log = LoggerFactory.getLogger(TileRenderer.class); + static final Logger log = LoggerFactory.getLogger(TileRenderer.class); - /** fade-in time */ - protected static final float FADE_TIME = 500; - protected static final int MAX_TILE_LOAD = 8; + /** + * fade-in time + */ + protected static final float FADE_TIME = 500; + protected static final int MAX_TILE_LOAD = 8; - private TileManager mTileManager; + private TileManager mTileManager; - protected final TileSet mDrawTiles; - protected int mProxyTileCnt; + protected final TileSet mDrawTiles; + protected int mProxyTileCnt; - private int mOverdraw = 0; - private float mAlpha = 1; + private int mOverdraw = 0; + private float mAlpha = 1; - protected int mOverdrawColor; - protected float mLayerAlpha; + protected int mOverdrawColor; + protected float mLayerAlpha; - private int mUploadSerial; + private int mUploadSerial; - public TileRenderer() { - mUploadSerial = 0; - mDrawTiles = new TileSet(); - } + public TileRenderer() { + mUploadSerial = 0; + mDrawTiles = new TileSet(); + } - protected void setTileManager(TileManager tileManager) { - mTileManager = tileManager; - } + protected void setTileManager(TileManager tileManager) { + mTileManager = tileManager; + } - /** - * Threadsafe - */ - public synchronized void setOverdrawColor(int color) { - mOverdraw = color; - } + /** + * Threadsafe + */ + public synchronized void setOverdrawColor(int color) { + mOverdraw = color; + } - /** - * Threadsafe - */ - public synchronized void setBitmapAlpha(float alpha) { - mAlpha = alpha; - } + /** + * Threadsafe + */ + public synchronized void setBitmapAlpha(float alpha) { + mAlpha = alpha; + } - /** - * synced with clearTiles, setOverdrawColor and setBitmapAlpha - */ - @Override - public synchronized void update(GLViewport v) { - /* count placeholder tiles */ + /** + * synced with clearTiles, setOverdrawColor and setBitmapAlpha + */ + @Override + public synchronized void update(GLViewport v) { + /* count placeholder tiles */ - if (mAlpha == 0) { - mDrawTiles.releaseTiles(); - setReady(false); - return; - } + if (mAlpha == 0) { + mDrawTiles.releaseTiles(); + setReady(false); + return; + } /* keep constant while rendering frame */ - mLayerAlpha = mAlpha; - mOverdrawColor = mOverdraw; + mLayerAlpha = mAlpha; + mOverdrawColor = mOverdraw; /* get current tiles to draw */ - synchronized (tilelock) { - boolean tilesChanged = mTileManager.getActiveTiles(mDrawTiles); + synchronized (tilelock) { + boolean tilesChanged = mTileManager.getActiveTiles(mDrawTiles); - if (mDrawTiles.cnt == 0) { - setReady(false); - mProxyTileCnt = 0; - return; - } + if (mDrawTiles.cnt == 0) { + setReady(false); + mProxyTileCnt = 0; + return; + } /* update isVisible flag true for tiles that intersect view */ - if (tilesChanged || v.changed()) { + if (tilesChanged || v.changed()) { /* lock tiles while updating isVisible state */ - mProxyTileCnt = 0; + mProxyTileCnt = 0; - MapTile[] tiles = mDrawTiles.tiles; - int tileZoom = tiles[0].zoomLevel; + MapTile[] tiles = mDrawTiles.tiles; + int tileZoom = tiles[0].zoomLevel; - for (int i = 0; i < mDrawTiles.cnt; i++) - tiles[i].isVisible = false; + for (int i = 0; i < mDrawTiles.cnt; i++) + tiles[i].isVisible = false; /* check visibile tiles */ - mScanBox.scan(v.pos.x, v.pos.y, v.pos.scale, tileZoom, v.plane); - } - } - /* prepare tiles for rendering */ - if (compileTileLayers(mDrawTiles.tiles, mDrawTiles.cnt + mProxyTileCnt) > 0) { - mUploadSerial++; - BufferObject.checkBufferUsage(false); - } - setReady(true); - } + mScanBox.scan(v.pos.x, v.pos.y, v.pos.scale, tileZoom, v.plane); + } + } + /* prepare tiles for rendering */ + if (compileTileLayers(mDrawTiles.tiles, mDrawTiles.cnt + mProxyTileCnt) > 0) { + mUploadSerial++; + BufferObject.checkBufferUsage(false); + } + setReady(true); + } - public void clearTiles() { - synchronized (tilelock) { + public void clearTiles() { + synchronized (tilelock) { /* Clear all references to MapTiles as all current * tiles will also be removed from TileManager. */ - mDrawTiles.releaseTiles(); - mDrawTiles.tiles = new MapTile[1]; - mDrawTiles.cnt = 0; - } - } + mDrawTiles.releaseTiles(); + mDrawTiles.tiles = new MapTile[1]; + mDrawTiles.cnt = 0; + } + } - /** compile tile layer data and upload to VBOs */ - private static int compileTileLayers(MapTile[] tiles, int tileCnt) { - int uploadCnt = 0; + /** + * compile tile layer data and upload to VBOs + */ + private static int compileTileLayers(MapTile[] tiles, int tileCnt) { + int uploadCnt = 0; - for (int i = 0; i < tileCnt; i++) { - MapTile tile = tiles[i]; + for (int i = 0; i < tileCnt; i++) { + MapTile tile = tiles[i]; - if (!tile.isVisible) - continue; + if (!tile.isVisible) + continue; - if (tile.state(READY)) - continue; + if (tile.state(READY)) + continue; - if (tile.state(NEW_DATA)) { - uploadCnt += uploadTileData(tile); - continue; - } + if (tile.state(NEW_DATA)) { + uploadCnt += uploadTileData(tile); + continue; + } /* load tile that is referenced by this holder */ - MapTile proxy = tile.holder; - if (proxy != null && proxy.state(NEW_DATA)) { - uploadCnt += uploadTileData(proxy); - tile.state = proxy.state; - continue; - } + MapTile proxy = tile.holder; + if (proxy != null && proxy.state(NEW_DATA)) { + uploadCnt += uploadTileData(proxy); + tile.state = proxy.state; + continue; + } /* check near relatives than can serve as proxy */ - proxy = tile.getProxy(PROXY_PARENT, NEW_DATA); - if (proxy != null) { - uploadCnt += uploadTileData(proxy); + proxy = tile.getProxy(PROXY_PARENT, NEW_DATA); + if (proxy != null) { + uploadCnt += uploadTileData(proxy); /* dont load child proxies */ - continue; - } + continue; + } - for (int c = 0; c < 4; c++) { - proxy = tile.getProxyChild(c, NEW_DATA); - if (proxy != null) - uploadCnt += uploadTileData(proxy); - } + for (int c = 0; c < 4; c++) { + proxy = tile.getProxyChild(c, NEW_DATA); + if (proxy != null) + uploadCnt += uploadTileData(proxy); + } - if (uploadCnt >= MAX_TILE_LOAD) - break; - } - return uploadCnt; - } + if (uploadCnt >= MAX_TILE_LOAD) + break; + } + return uploadCnt; + } - private static int uploadTileData(MapTile tile) { - tile.setState(READY); - RenderBuckets buckets = tile.getBuckets(); + private static int uploadTileData(MapTile tile) { + tile.setState(READY); + RenderBuckets buckets = tile.getBuckets(); /* tile might only contain label layers */ - if (buckets == null) - return 0; + if (buckets == null) + return 0; - if (!buckets.compile(true)) { - buckets.clear(); - return 0; - } + if (!buckets.compile(true)) { + buckets.clear(); + return 0; + } - return 1; - } + return 1; + } - private final Object tilelock = new Object(); + private final Object tilelock = new Object(); - /** - * Update tileSet with currently visible tiles get a TileSet of currently - * visible tiles - */ - public boolean getVisibleTiles(TileSet tileSet) { - if (tileSet == null) - return false; + /** + * Update tileSet with currently visible tiles get a TileSet of currently + * visible tiles + */ + public boolean getVisibleTiles(TileSet tileSet) { + if (tileSet == null) + return false; - if (mDrawTiles == null) { - releaseTiles(tileSet); - return false; - } + if (mDrawTiles == null) { + releaseTiles(tileSet); + return false; + } - int prevSerial = tileSet.serial; + int prevSerial = tileSet.serial; /* ensure tiles keep visible state */ - synchronized (tilelock) { + synchronized (tilelock) { - MapTile[] newTiles = mDrawTiles.tiles; - int cnt = mDrawTiles.cnt; + MapTile[] newTiles = mDrawTiles.tiles; + int cnt = mDrawTiles.cnt; /* ensure same size */ - if (tileSet.tiles.length != newTiles.length) { - tileSet.tiles = new MapTile[newTiles.length]; - } + if (tileSet.tiles.length != newTiles.length) { + tileSet.tiles = new MapTile[newTiles.length]; + } /* lock tiles to not be removed from cache */ - tileSet.cnt = 0; - for (int i = 0; i < cnt; i++) { - MapTile t = newTiles[i]; - if (t.isVisible && t.state(READY)) - t.lock(); - } + tileSet.cnt = 0; + for (int i = 0; i < cnt; i++) { + MapTile t = newTiles[i]; + if (t.isVisible && t.state(READY)) + t.lock(); + } /* unlock previous tiles */ - tileSet.releaseTiles(); + tileSet.releaseTiles(); - for (int i = 0; i < cnt; i++) { - MapTile t = newTiles[i]; - if (t.isVisible && t.state(READY)) - tileSet.tiles[tileSet.cnt++] = t; - } + for (int i = 0; i < cnt; i++) { + MapTile t = newTiles[i]; + if (t.isVisible && t.state(READY)) + tileSet.tiles[tileSet.cnt++] = t; + } - tileSet.serial = mUploadSerial; - } + tileSet.serial = mUploadSerial; + } - return prevSerial != tileSet.serial; - } + return prevSerial != tileSet.serial; + } - public void releaseTiles(TileSet tileSet) { - tileSet.releaseTiles(); - } + public void releaseTiles(TileSet tileSet) { + tileSet.releaseTiles(); + } - /** scanline fill class used to check tile visibility */ - private final ScanBox mScanBox = new ScanBox() { - @Override - protected void setVisible(int y, int x1, int x2) { + /** + * scanline fill class used to check tile visibility + */ + private final ScanBox mScanBox = new ScanBox() { + @Override + protected void setVisible(int y, int x1, int x2) { - MapTile[] tiles = mDrawTiles.tiles; - int proxyOffset = mDrawTiles.cnt; + MapTile[] tiles = mDrawTiles.tiles; + int proxyOffset = mDrawTiles.cnt; - for (int i = 0; i < proxyOffset; i++) { - MapTile t = tiles[i]; - if (t.tileY == y && t.tileX >= x1 && t.tileX < x2) - t.isVisible = true; - } + for (int i = 0; i < proxyOffset; i++) { + MapTile t = tiles[i]; + if (t.tileY == y && t.tileX >= x1 && t.tileX < x2) + t.isVisible = true; + } /* add placeholder tiles to show both sides * of date line. a little too complicated... */ - int xmax = 1 << mZoom; - if (x1 >= 0 && x2 < xmax) - return; + int xmax = 1 << mZoom; + if (x1 >= 0 && x2 < xmax) + return; - O: for (int x = x1; x < x2; x++) { - if (x >= 0 && x < xmax) - continue; + O: + for (int x = x1; x < x2; x++) { + if (x >= 0 && x < xmax) + continue; - int xx = x; - if (x < 0) - xx = xmax + x; - else - xx = x - xmax; + int xx = x; + if (x < 0) + xx = xmax + x; + else + xx = x - xmax; - if (xx < 0 || xx >= xmax) - continue; + if (xx < 0 || xx >= xmax) + continue; - for (int i = proxyOffset; i < proxyOffset + mProxyTileCnt; i++) - if (tiles[i].tileX == x && tiles[i].tileY == y) - continue O; + for (int i = proxyOffset; i < proxyOffset + mProxyTileCnt; i++) + if (tiles[i].tileX == x && tiles[i].tileY == y) + continue O; - MapTile tile = null; - for (int i = 0; i < proxyOffset; i++) - if (tiles[i].tileX == xx && tiles[i].tileY == y) { - tile = tiles[i]; - break; - } + MapTile tile = null; + for (int i = 0; i < proxyOffset; i++) + if (tiles[i].tileX == xx && tiles[i].tileY == y) { + tile = tiles[i]; + break; + } - if (tile == null) - continue; + if (tile == null) + continue; - if (proxyOffset + mProxyTileCnt >= tiles.length) { - //log.error(" + mNumTileHolder"); - break; - } + if (proxyOffset + mProxyTileCnt >= tiles.length) { + //log.error(" + mNumTileHolder"); + break; + } - MapTile holder = new MapTile(null, x, y, (byte) mZoom); - holder.isVisible = true; - holder.holder = tile; - holder.state = tile.state; - tile.isVisible = true; - tiles[proxyOffset + mProxyTileCnt++] = holder; - } - } - }; + MapTile holder = new MapTile(null, x, y, (byte) mZoom); + holder.isVisible = true; + holder.holder = tile; + holder.state = tile.state; + tile.isVisible = true; + tiles[proxyOffset + mProxyTileCnt++] = holder; + } + } + }; - /** - * @param proxyLevel zoom-level of tile relative to current TileSet - */ - public static long getMinFade(MapTile tile, int proxyLevel) { - long minFade = MapRenderer.frametime - 50; + /** + * @param proxyLevel zoom-level of tile relative to current TileSet + */ + public static long getMinFade(MapTile tile, int proxyLevel) { + long minFade = MapRenderer.frametime - 50; /* check children for grandparent, parent or current */ - if (proxyLevel <= 0) { - for (int c = 0; c < 4; c++) { - MapTile ci = tile.node.child(c); - if (ci == null) - continue; + if (proxyLevel <= 0) { + for (int c = 0; c < 4; c++) { + MapTile ci = tile.node.child(c); + if (ci == null) + continue; - if (ci.fadeTime > 0 && ci.fadeTime < minFade) - minFade = ci.fadeTime; + if (ci.fadeTime > 0 && ci.fadeTime < minFade) + minFade = ci.fadeTime; /* when drawing the parent of the current level * we also check if the children of current level * are visible */ - if (proxyLevel >= -1) { - long m = getMinFade(ci, proxyLevel - 1); - if (m < minFade) - minFade = m; - } - } - } + if (proxyLevel >= -1) { + long m = getMinFade(ci, proxyLevel - 1); + if (m < minFade) + minFade = m; + } + } + } /* check parents for child, current or parent */ - TileNode p = tile.node.parent; + TileNode p = tile.node.parent; - for (int i = proxyLevel; i >= -1; i--) { - if (p == null) - break; + for (int i = proxyLevel; i >= -1; i--) { + if (p == null) + break; - if (p.item != null && p.item.fadeTime > 0 && p.item.fadeTime < minFade) - minFade = p.item.fadeTime; + if (p.item != null && p.item.fadeTime > 0 && p.item.fadeTime < minFade) + minFade = p.item.fadeTime; - p = p.parent; - } + p = p.parent; + } - return minFade; - } + return minFade; + } } diff --git a/vtm/src/org/oscim/layers/tile/TileSet.java b/vtm/src/org/oscim/layers/tile/TileSet.java index ad58a2d3..919e2279 100644 --- a/vtm/src/org/oscim/layers/tile/TileSet.java +++ b/vtm/src/org/oscim/layers/tile/TileSet.java @@ -25,99 +25,101 @@ import java.util.Comparator; * back to TileManager on a second invocation or TileManager.releaseTiles(). */ public final class TileSet { - public int cnt = 0; - public MapTile[] tiles; + public int cnt = 0; + public MapTile[] tiles; - /** update counter will be set by getActiveTiles when TileSet has changed */ - int serial; + /** + * update counter will be set by getActiveTiles when TileSet has changed + */ + int serial; - public TileSet() { - tiles = new MapTile[1]; - } + public TileSet() { + tiles = new MapTile[1]; + } - public TileSet(int numTiles) { - tiles = new MapTile[numTiles]; - } + public TileSet(int numTiles) { + tiles = new MapTile[numTiles]; + } - public MapTile getTile(int x, int y) { - for (int i = 0; i < cnt; i++) - if (tiles[i].tileX == x && tiles[i].tileY == y) - return tiles[i]; + public MapTile getTile(int x, int y) { + for (int i = 0; i < cnt; i++) + if (tiles[i].tileX == x && tiles[i].tileY == y) + return tiles[i]; - return null; - } + return null; + } - /** - * Locked tiles to ensure that they are not released from cache. - * Call releaseTiles() when tiles are not needed any longer. - */ - public void lockTiles() { - synchronized (TileSet.class) { - for (int i = 0; i < cnt; i++) - tiles[i].lock(); - } - } + /** + * Locked tiles to ensure that they are not released from cache. + * Call releaseTiles() when tiles are not needed any longer. + */ + public void lockTiles() { + synchronized (TileSet.class) { + for (int i = 0; i < cnt; i++) + tiles[i].lock(); + } + } - /** - * Release locked tiles. - */ - public void releaseTiles() { - synchronized (TileSet.class) { - for (int i = 0; i < cnt; i++) - tiles[i].unlock(); - } - Arrays.fill(tiles, null); - cnt = 0; - serial = 0; - } + /** + * Release locked tiles. + */ + public void releaseTiles() { + synchronized (TileSet.class) { + for (int i = 0; i < cnt; i++) + tiles[i].unlock(); + } + Arrays.fill(tiles, null); + cnt = 0; + serial = 0; + } - /** - * Clone TileSet from source. Release previous tiles and lock - * new tiles. - */ - public void setTiles(TileSet source) { - /* lock tiles (and their proxies) to not be removed from cache */ - source.lockTiles(); + /** + * Clone TileSet from source. Release previous tiles and lock + * new tiles. + */ + public void setTiles(TileSet source) { + /* lock tiles (and their proxies) to not be removed from cache */ + source.lockTiles(); /* unlock previous tiles */ - releaseTiles(); + releaseTiles(); - if (source.tiles.length != tiles.length) { - tiles = new MapTile[source.tiles.length]; - } + if (source.tiles.length != tiles.length) { + tiles = new MapTile[source.tiles.length]; + } - System.arraycopy(source.tiles, 0, tiles, 0, source.cnt); + System.arraycopy(source.tiles, 0, tiles, 0, source.cnt); - cnt = source.cnt; - } + cnt = source.cnt; + } - public static Comparator coordComparator = new CoordComparator(); + public static Comparator coordComparator = new CoordComparator(); - public static class CoordComparator implements Comparator { + public static class CoordComparator implements Comparator { - @Override - public int compare(MapTile lhs, MapTile rhs) { - if (lhs.tileX == rhs.tileX) { - if (lhs.tileY == rhs.tileY) - return 0; + @Override + public int compare(MapTile lhs, MapTile rhs) { + if (lhs.tileX == rhs.tileX) { + if (lhs.tileY == rhs.tileY) + return 0; - if (lhs.tileY < rhs.tileY) - return 1; + if (lhs.tileY < rhs.tileY) + return 1; - return -1; - } - if (lhs.tileX < rhs.tileX) - return 1; + return -1; + } + if (lhs.tileX < rhs.tileX) + return 1; - return -1; - } - } + return -1; + } + } - public boolean contains(MapTile t) { - for (int i = 0; i < cnt; i++) - if (tiles[i].equals(t)) - return true; + public boolean contains(MapTile t) { + for (int i = 0; i < cnt; i++) + if (tiles[i].equals(t)) + return true; - return false; - } + return false; + } } diff --git a/vtm/src/org/oscim/layers/tile/VectorTileRenderer.java b/vtm/src/org/oscim/layers/tile/VectorTileRenderer.java index 5c989e03..a26043f1 100644 --- a/vtm/src/org/oscim/layers/tile/VectorTileRenderer.java +++ b/vtm/src/org/oscim/layers/tile/VectorTileRenderer.java @@ -1,17 +1,5 @@ package org.oscim.layers.tile; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.layers.tile.MapTile.PROXY_GRAMPA; -import static org.oscim.layers.tile.MapTile.PROXY_PARENT; -import static org.oscim.layers.tile.MapTile.State.READY; -import static org.oscim.renderer.MapRenderer.COORD_SCALE; -import static org.oscim.renderer.bucket.RenderBucket.BITMAP; -import static org.oscim.renderer.bucket.RenderBucket.HAIRLINE; -import static org.oscim.renderer.bucket.RenderBucket.LINE; -import static org.oscim.renderer.bucket.RenderBucket.MESH; -import static org.oscim.renderer.bucket.RenderBucket.POLYGON; -import static org.oscim.renderer.bucket.RenderBucket.TEXLINE; - import org.oscim.backend.GL; import org.oscim.backend.canvas.Color; import org.oscim.core.MapPosition; @@ -29,261 +17,273 @@ import org.oscim.renderer.bucket.RenderBucket; import org.oscim.renderer.bucket.RenderBuckets; import org.oscim.utils.FastMath; +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.layers.tile.MapTile.PROXY_GRAMPA; +import static org.oscim.layers.tile.MapTile.PROXY_PARENT; +import static org.oscim.layers.tile.MapTile.State.READY; +import static org.oscim.renderer.MapRenderer.COORD_SCALE; +import static org.oscim.renderer.bucket.RenderBucket.BITMAP; +import static org.oscim.renderer.bucket.RenderBucket.HAIRLINE; +import static org.oscim.renderer.bucket.RenderBucket.LINE; +import static org.oscim.renderer.bucket.RenderBucket.MESH; +import static org.oscim.renderer.bucket.RenderBucket.POLYGON; +import static org.oscim.renderer.bucket.RenderBucket.TEXLINE; + public class VectorTileRenderer extends TileRenderer { - static final boolean debugOverdraw = false; + static final boolean debugOverdraw = false; - protected int mClipMode; + protected int mClipMode; - protected GLMatrix mClipProj = new GLMatrix(); - protected GLMatrix mClipMVP = new GLMatrix(); + protected GLMatrix mClipProj = new GLMatrix(); + protected GLMatrix mClipMVP = new GLMatrix(); - /** - * Current number of frames drawn, used to not draw a - * tile twice per frame. - */ - protected int mDrawSerial; + /** + * Current number of frames drawn, used to not draw a + * tile twice per frame. + */ + protected int mDrawSerial; - @Override - public synchronized void render(GLViewport v) { + @Override + public synchronized void render(GLViewport v) { /* discard depth projection from tilt, depth buffer - * is used for clipping */ - mClipProj.copy(v.proj); - mClipProj.setValue(10, 0); - mClipProj.setValue(14, 0); - mClipProj.multiplyRhs(v.view); + * is used for clipping */ + mClipProj.copy(v.proj); + mClipProj.setValue(10, 0); + mClipProj.setValue(14, 0); + mClipProj.multiplyRhs(v.view); - mClipMode = PolygonBucket.CLIP_STENCIL; + mClipMode = PolygonBucket.CLIP_STENCIL; - int tileCnt = mDrawTiles.cnt + mProxyTileCnt; + int tileCnt = mDrawTiles.cnt + mProxyTileCnt; - MapTile[] tiles = mDrawTiles.tiles; + MapTile[] tiles = mDrawTiles.tiles; - boolean drawProxies = false; + boolean drawProxies = false; - mDrawSerial++; + mDrawSerial++; - for (int i = 0; i < tileCnt; i++) { - MapTile t = tiles[i]; + for (int i = 0; i < tileCnt; i++) { + MapTile t = tiles[i]; - if (t.isVisible && !t.state(READY)) { - gl.depthMask(true); - gl.clear(GL.DEPTH_BUFFER_BIT); + if (t.isVisible && !t.state(READY)) { + gl.depthMask(true); + gl.clear(GL.DEPTH_BUFFER_BIT); /* always write depth for non-proxy tiles - * this is used in drawProxies pass to not + * this is used in drawProxies pass to not * draw where tiles were already drawn */ - gl.depthFunc(GL.ALWAYS); + gl.depthFunc(GL.ALWAYS); - mClipMode = PolygonBucket.CLIP_DEPTH; - drawProxies = true; + mClipMode = PolygonBucket.CLIP_DEPTH; + drawProxies = true; - break; - } - } + break; + } + } /* draw visible tiles */ - for (int i = 0; i < tileCnt; i++) { - MapTile t = tiles[i]; - if (t.isVisible && t.state(READY)) - drawTile(t, v, 0); - } + for (int i = 0; i < tileCnt; i++) { + MapTile t = tiles[i]; + if (t.isVisible && t.state(READY)) + drawTile(t, v, 0); + } /* draw parent or children as proxy for visibile tiles that dont * have data yet. Proxies are clipped to the region where nothing * was drawn to depth buffer. * TODO draw proxies for placeholder */ - if (!drawProxies) - return; + if (!drawProxies) + return; /* only draw where no other tile is drawn */ - gl.depthFunc(GL.LESS); + gl.depthFunc(GL.LESS); /* draw child or parent proxies */ - boolean preferParent = (v.pos.getZoomScale() < 1.5) - || (v.pos.zoomLevel < tiles[0].zoomLevel); + boolean preferParent = (v.pos.getZoomScale() < 1.5) + || (v.pos.zoomLevel < tiles[0].zoomLevel); - if (preferParent) { - for (int i = 0; i < tileCnt; i++) { - MapTile t = tiles[i]; - if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) - continue; - if (!drawParent(t, v)) - drawChildren(t, v); - } - } else { - for (int i = 0; i < tileCnt; i++) { - MapTile t = tiles[i]; - if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) - continue; - drawChildren(t, v); - } - for (int i = 0; i < tileCnt; i++) { - MapTile t = tiles[i]; - if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) - continue; - drawParent(t, v); - } - } + if (preferParent) { + for (int i = 0; i < tileCnt; i++) { + MapTile t = tiles[i]; + if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) + continue; + if (!drawParent(t, v)) + drawChildren(t, v); + } + } else { + for (int i = 0; i < tileCnt; i++) { + MapTile t = tiles[i]; + if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) + continue; + drawChildren(t, v); + } + for (int i = 0; i < tileCnt; i++) { + MapTile t = tiles[i]; + if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) + continue; + drawParent(t, v); + } + } /* draw grandparents */ - for (int i = 0; i < tileCnt; i++) { - MapTile t = tiles[i]; - if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) - continue; - drawGrandParent(t, v); - } + for (int i = 0; i < tileCnt; i++) { + MapTile t = tiles[i]; + if ((!t.isVisible) || (t.lastDraw == mDrawSerial)) + continue; + drawGrandParent(t, v); + } - gl.depthMask(false); + gl.depthMask(false); /* make sure stencil buffer write is disabled */ - //GL.stencilMask(0x00); - } + //GL.stencilMask(0x00); + } - private void drawTile(MapTile tile, GLViewport v, int proxyLevel) { + private void drawTile(MapTile tile, GLViewport v, int proxyLevel) { /* ensure to draw parents only once */ - if (tile.lastDraw == mDrawSerial) - return; + if (tile.lastDraw == mDrawSerial) + return; - tile.lastDraw = mDrawSerial; + tile.lastDraw = mDrawSerial; /* use holder proxy when it is set */ - RenderBuckets buckets = (tile.holder == null) - ? tile.getBuckets() - : tile.holder.getBuckets(); + RenderBuckets buckets = (tile.holder == null) + ? tile.getBuckets() + : tile.holder.getBuckets(); - if (buckets == null || buckets.vbo == null) { - //log.debug("{} no buckets!", tile); - return; - } + if (buckets == null || buckets.vbo == null) { + //log.debug("{} no buckets!", tile); + return; + } - MapPosition pos = v.pos; + MapPosition pos = v.pos; /* place tile relative to map position */ - int z = tile.zoomLevel; - float div = FastMath.pow(z - pos.zoomLevel); - double tileScale = Tile.SIZE * pos.scale; - float x = (float) ((tile.x - pos.x) * tileScale); - float y = (float) ((tile.y - pos.y) * tileScale); + int z = tile.zoomLevel; + float div = FastMath.pow(z - pos.zoomLevel); + double tileScale = Tile.SIZE * pos.scale; + float x = (float) ((tile.x - pos.x) * tileScale); + float y = (float) ((tile.y - pos.y) * tileScale); /* scale relative to zoom-level of this tile */ - float scale = (float) (pos.scale / (1 << z)); + float scale = (float) (pos.scale / (1 << z)); - v.mvp.setTransScale(x, y, scale / COORD_SCALE); - v.mvp.multiplyLhs(v.viewproj); + v.mvp.setTransScale(x, y, scale / COORD_SCALE); + v.mvp.multiplyLhs(v.viewproj); - mClipMVP.setTransScale(x, y, scale / COORD_SCALE); - mClipMVP.multiplyLhs(mClipProj); + mClipMVP.setTransScale(x, y, scale / COORD_SCALE); + mClipMVP.multiplyLhs(mClipProj); - buckets.bind(); + buckets.bind(); - PolygonBucket.Renderer.clip(mClipMVP, mClipMode); - boolean first = true; + PolygonBucket.Renderer.clip(mClipMVP, mClipMode); + boolean first = true; - for (RenderBucket b = buckets.get(); b != null;) { - switch (b.type) { - case POLYGON: - b = PolygonBucket.Renderer.draw(b, v, div, first); - first = false; + for (RenderBucket b = buckets.get(); b != null; ) { + switch (b.type) { + case POLYGON: + b = PolygonBucket.Renderer.draw(b, v, div, first); + first = false; /* set test for clip to tile region */ - gl.stencilFunc(GL.EQUAL, 0x80, 0x80); - break; - case LINE: - b = LineBucket.Renderer.draw(b, v, scale, buckets); - break; - case TEXLINE: - b = LineTexBucket.Renderer.draw(b, v, div, buckets); - break; - case MESH: - b = MeshBucket.Renderer.draw(b, v); - break; - case HAIRLINE: - b = HairLineBucket.Renderer.draw(b, v); - break; - case BITMAP: - b = BitmapBucket.Renderer.draw(b, v, 1, mLayerAlpha); - break; - default: + gl.stencilFunc(GL.EQUAL, 0x80, 0x80); + break; + case LINE: + b = LineBucket.Renderer.draw(b, v, scale, buckets); + break; + case TEXLINE: + b = LineTexBucket.Renderer.draw(b, v, div, buckets); + break; + case MESH: + b = MeshBucket.Renderer.draw(b, v); + break; + case HAIRLINE: + b = HairLineBucket.Renderer.draw(b, v); + break; + case BITMAP: + b = BitmapBucket.Renderer.draw(b, v, 1, mLayerAlpha); + break; + default: /* just in case */ - log.error("unknown layer {}", b.type); - b = b.next; - break; - } + log.error("unknown layer {}", b.type); + b = b.next; + break; + } /* make sure buffers are bound again */ - buckets.bind(); - } + buckets.bind(); + } - if (debugOverdraw) { - if (tile.zoomLevel > pos.zoomLevel) - PolygonBucket.Renderer.drawOver(mClipMVP, Color.BLUE, 0.5f); - else if (tile.zoomLevel < pos.zoomLevel) - PolygonBucket.Renderer.drawOver(mClipMVP, Color.RED, 0.5f); - else - PolygonBucket.Renderer.drawOver(mClipMVP, Color.GREEN, 0.5f); + if (debugOverdraw) { + if (tile.zoomLevel > pos.zoomLevel) + PolygonBucket.Renderer.drawOver(mClipMVP, Color.BLUE, 0.5f); + else if (tile.zoomLevel < pos.zoomLevel) + PolygonBucket.Renderer.drawOver(mClipMVP, Color.RED, 0.5f); + else + PolygonBucket.Renderer.drawOver(mClipMVP, Color.GREEN, 0.5f); - return; - } + return; + } - long fadeTime = tile.fadeTime; - if (fadeTime == 0) { - if (tile.holder == null) { - fadeTime = getMinFade(tile, proxyLevel); - } else { + long fadeTime = tile.fadeTime; + if (fadeTime == 0) { + if (tile.holder == null) { + fadeTime = getMinFade(tile, proxyLevel); + } else { /* need to use time from original tile */ - fadeTime = tile.holder.fadeTime; - if (fadeTime == 0) - fadeTime = getMinFade(tile.holder, proxyLevel); - } - tile.fadeTime = fadeTime; - } + fadeTime = tile.holder.fadeTime; + if (fadeTime == 0) + fadeTime = getMinFade(tile.holder, proxyLevel); + } + tile.fadeTime = fadeTime; + } - long dTime = MapRenderer.frametime - fadeTime; + long dTime = MapRenderer.frametime - fadeTime; - if (mOverdrawColor == 0 || dTime > FADE_TIME) { - PolygonBucket.Renderer.drawOver(mClipMVP, 0, 1); - return; - } + if (mOverdrawColor == 0 || dTime > FADE_TIME) { + PolygonBucket.Renderer.drawOver(mClipMVP, 0, 1); + return; + } - float fade = 1 - dTime / FADE_TIME; - PolygonBucket.Renderer.drawOver(mClipMVP, mOverdrawColor, fade * fade); + float fade = 1 - dTime / FADE_TIME; + PolygonBucket.Renderer.drawOver(mClipMVP, mOverdrawColor, fade * fade); - MapRenderer.animate(); - } + MapRenderer.animate(); + } - protected boolean drawChildren(MapTile t, GLViewport v) { - int drawn = 0; - for (int i = 0; i < 4; i++) { - MapTile c = t.getProxyChild(i, READY); - if (c == null) - continue; + protected boolean drawChildren(MapTile t, GLViewport v) { + int drawn = 0; + for (int i = 0; i < 4; i++) { + MapTile c = t.getProxyChild(i, READY); + if (c == null) + continue; - drawTile(c, v, 1); - drawn++; - } - if (drawn == 4) { - t.lastDraw = mDrawSerial; - return true; - } - return false; - } + drawTile(c, v, 1); + drawn++; + } + if (drawn == 4) { + t.lastDraw = mDrawSerial; + return true; + } + return false; + } - protected boolean drawParent(MapTile t, GLViewport v) { - MapTile proxy = t.getProxy(PROXY_PARENT, READY); - if (proxy != null) { - drawTile(proxy, v, -1); - t.lastDraw = mDrawSerial; - return true; - } - return false; - } + protected boolean drawParent(MapTile t, GLViewport v) { + MapTile proxy = t.getProxy(PROXY_PARENT, READY); + if (proxy != null) { + drawTile(proxy, v, -1); + t.lastDraw = mDrawSerial; + return true; + } + return false; + } - protected void drawGrandParent(MapTile t, GLViewport v) { - MapTile proxy = t.getProxy(PROXY_GRAMPA, READY); - if (proxy != null) { - drawTile(proxy, v, -2); - t.lastDraw = mDrawSerial; - } - } + protected void drawGrandParent(MapTile t, GLViewport v) { + MapTile proxy = t.getProxy(PROXY_GRAMPA, READY); + if (proxy != null) { + drawTile(proxy, v, -2); + t.lastDraw = mDrawSerial; + } + } } diff --git a/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLayer.java b/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLayer.java index 1989f51a..cdd701ea 100644 --- a/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLayer.java +++ b/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLayer.java @@ -31,114 +31,116 @@ import org.slf4j.LoggerFactory; public class BitmapTileLayer extends TileLayer { - protected static final Logger log = LoggerFactory.getLogger(BitmapTileLayer.class); + protected static final Logger log = LoggerFactory.getLogger(BitmapTileLayer.class); - private final static int CACHE_LIMIT = 40; + private final static int CACHE_LIMIT = 40; - protected final TileSource mTileSource; + protected final TileSource mTileSource; - public static class FadeStep { - public final double scaleStart, scaleEnd; - public final float alphaStart, alphaEnd; + public static class FadeStep { + public final double scaleStart, scaleEnd; + public final float alphaStart, alphaEnd; - public FadeStep(int zoomStart, int zoomEnd, float alphaStart, float alphaEnd) { - this.scaleStart = 1 << zoomStart; - this.scaleEnd = 1 << zoomEnd; - this.alphaStart = alphaStart; - this.alphaEnd = alphaEnd; - } - } + public FadeStep(int zoomStart, int zoomEnd, float alphaStart, float alphaEnd) { + this.scaleStart = 1 << zoomStart; + this.scaleEnd = 1 << zoomEnd; + this.alphaStart = alphaStart; + this.alphaEnd = alphaEnd; + } + } - public BitmapTileLayer(Map map, TileSource tileSource) { - this(map, tileSource, CACHE_LIMIT); - } + public BitmapTileLayer(Map map, TileSource tileSource) { + this(map, tileSource, CACHE_LIMIT); + } - public BitmapTileLayer(Map map, TileSource tileSource, int cacheLimit) { - super(map, - new TileManager(map, cacheLimit), - new VectorTileRenderer()); + public BitmapTileLayer(Map map, TileSource tileSource, int cacheLimit) { + super(map, + new TileManager(map, cacheLimit), + new VectorTileRenderer()); - mTileManager.setZoomLevel(tileSource.getZoomLevelMin(), - tileSource.getZoomLevelMax()); + mTileManager.setZoomLevel(tileSource.getZoomLevelMin(), + tileSource.getZoomLevelMax()); - mTileSource = tileSource; - initLoader(getNumLoaders()); - } + mTileSource = tileSource; + initLoader(getNumLoaders()); + } - @Override - public void onMapEvent(Event event, MapPosition pos) { - super.onMapEvent(event, pos); + @Override + public void onMapEvent(Event event, MapPosition pos) { + super.onMapEvent(event, pos); - if (event != Map.POSITION_EVENT) - return; + if (event != Map.POSITION_EVENT) + return; - FadeStep[] fade = mTileSource.getFadeSteps(); + FadeStep[] fade = mTileSource.getFadeSteps(); - if (fade == null) { - //mRenderLayer.setBitmapAlpha(1); - return; - } + if (fade == null) { + //mRenderLayer.setBitmapAlpha(1); + return; + } - float alpha = 0; - for (FadeStep f : fade) { - if (pos.scale < f.scaleStart || pos.scale > f.scaleEnd) - continue; + float alpha = 0; + for (FadeStep f : fade) { + if (pos.scale < f.scaleStart || pos.scale > f.scaleEnd) + continue; - if (f.alphaStart == f.alphaEnd) { - alpha = f.alphaStart; - break; - } - double range = f.scaleEnd / f.scaleStart; - float a = (float) ((range - (pos.scale / f.scaleStart)) / range); - a = FastMath.clamp(a, 0, 1); - // interpolate alpha between start and end - alpha = a * f.alphaStart + (1 - a) * f.alphaEnd; - break; - } + if (f.alphaStart == f.alphaEnd) { + alpha = f.alphaStart; + break; + } + double range = f.scaleEnd / f.scaleStart; + float a = (float) ((range - (pos.scale / f.scaleStart)) / range); + a = FastMath.clamp(a, 0, 1); + // interpolate alpha between start and end + alpha = a * f.alphaStart + (1 - a) * f.alphaEnd; + break; + } - tileRenderer().setBitmapAlpha(alpha); - } + tileRenderer().setBitmapAlpha(alpha); + } - @Override - protected TileLoader createLoader() { - return new BitmapTileLoader(this, mTileSource); - } + @Override + protected TileLoader createLoader() { + return new BitmapTileLoader(this, mTileSource); + } - @Override - public void onDetach() { - super.onDetach(); - pool.clear(); - } + @Override + public void onDetach() { + super.onDetach(); + pool.clear(); + } - final static int POOL_FILL = 20; + final static int POOL_FILL = 20; - /** pool shared by TextLayers */ - final TexturePool pool = new TexturePool(POOL_FILL) { + /** + * pool shared by TextLayers + */ + final TexturePool pool = new TexturePool(POOL_FILL) { - // int sum = 0; - // - // public TextureItem release(TextureItem item) { - // log.debug(getFill() + " " + sum + " release tex " + item.id); - // return super.release(item); - // }; - // - // public synchronized TextureItem get() { - // log.debug(getFill() + " " + sum + " get tex "); - // - // return super.get(); - // }; - // - // protected TextureItem createItem() { - // log.debug(getFill() + " " + (sum++) + " create tex "); - // - // return super.createItem(); - // }; - // - // protected void freeItem(TextureItem t) { - // log.debug(getFill() + " " + (sum--) + " free tex "); - // super.freeItem(t); - // - // }; - }; + // int sum = 0; + // + // public TextureItem release(TextureItem item) { + // log.debug(getFill() + " " + sum + " release tex " + item.id); + // return super.release(item); + // }; + // + // public synchronized TextureItem get() { + // log.debug(getFill() + " " + sum + " get tex "); + // + // return super.get(); + // }; + // + // protected TextureItem createItem() { + // log.debug(getFill() + " " + (sum++) + " create tex "); + // + // return super.createItem(); + // }; + // + // protected void freeItem(TextureItem t) { + // log.debug(getFill() + " " + (sum--) + " free tex "); + // super.freeItem(t); + // + // }; + }; } diff --git a/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLoader.java b/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLoader.java index ff1074eb..4e426b37 100644 --- a/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLoader.java +++ b/vtm/src/org/oscim/layers/tile/bitmap/BitmapTileLoader.java @@ -16,8 +16,6 @@ */ package org.oscim.layers.tile.bitmap; -import static org.oscim.layers.tile.MapTile.State.LOADING; - import org.oscim.backend.canvas.Bitmap; import org.oscim.core.Tile; import org.oscim.layers.tile.MapTile; @@ -29,52 +27,54 @@ import org.oscim.tiling.TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.layers.tile.MapTile.State.LOADING; + public class BitmapTileLoader extends TileLoader { - protected static final Logger log = LoggerFactory.getLogger(BitmapTileLoader.class); + protected static final Logger log = LoggerFactory.getLogger(BitmapTileLoader.class); - private final ITileDataSource mTileDataSource; - private final BitmapTileLayer mLayer; + private final ITileDataSource mTileDataSource; + private final BitmapTileLayer mLayer; - public BitmapTileLoader(BitmapTileLayer tileLayer, TileSource tileSource) { - super(tileLayer.getManager()); - mTileDataSource = tileSource.getDataSource(); - mLayer = tileLayer; - } + public BitmapTileLoader(BitmapTileLayer tileLayer, TileSource tileSource) { + super(tileLayer.getManager()); + mTileDataSource = tileSource.getDataSource(); + mLayer = tileLayer; + } - @Override - protected boolean loadTile(MapTile tile) { - try { - mTileDataSource.query(tile, this); - } catch (Exception e) { - log.debug("{} {}", tile, e.getMessage()); - return false; - } - return true; - } + @Override + protected boolean loadTile(MapTile tile) { + try { + mTileDataSource.query(tile, this); + } catch (Exception e) { + log.debug("{} {}", tile, e.getMessage()); + return false; + } + return true; + } - @Override - public void setTileImage(Bitmap bitmap) { - if (isCanceled() || !mTile.state(LOADING)) { - bitmap.recycle(); - return; - } + @Override + public void setTileImage(Bitmap bitmap) { + if (isCanceled() || !mTile.state(LOADING)) { + bitmap.recycle(); + return; + } - BitmapBucket l = new BitmapBucket(false); - l.setBitmap(bitmap, Tile.SIZE, Tile.SIZE, mLayer.pool); + BitmapBucket l = new BitmapBucket(false); + l.setBitmap(bitmap, Tile.SIZE, Tile.SIZE, mLayer.pool); - RenderBuckets buckets = new RenderBuckets(); - buckets.set(l); - mTile.data = buckets; - } + RenderBuckets buckets = new RenderBuckets(); + buckets.set(l); + mTile.data = buckets; + } - @Override - public void dispose() { - mTileDataSource.cancel(); - } + @Override + public void dispose() { + mTileDataSource.cancel(); + } - @Override - public void cancel() { - mTileDataSource.cancel(); - } + @Override + public void cancel() { + mTileDataSource.cancel(); + } } diff --git a/vtm/src/org/oscim/layers/tile/buildings/BuildingLayer.java b/vtm/src/org/oscim/layers/tile/buildings/BuildingLayer.java index 1851efa9..71b4e22d 100644 --- a/vtm/src/org/oscim/layers/tile/buildings/BuildingLayer.java +++ b/vtm/src/org/oscim/layers/tile/buildings/BuildingLayer.java @@ -37,118 +37,120 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BuildingLayer extends Layer implements TileLoaderThemeHook { - static final Logger log = LoggerFactory.getLogger(BuildingLayer.class); + static final Logger log = LoggerFactory.getLogger(BuildingLayer.class); - private final static int MIN_ZOOM = 17; - private final static int MAX_ZOOM = 17; + private final static int MIN_ZOOM = 17; + private final static int MAX_ZOOM = 17; - private final static boolean POST_AA = false; - public static boolean TRANSLUCENT = true; + private final static boolean POST_AA = false; + public static boolean TRANSLUCENT = true; - private static final Object BUILDING_DATA = BuildingLayer.class.getName(); + private static final Object BUILDING_DATA = BuildingLayer.class.getName(); - public BuildingLayer(Map map, VectorTileLayer tileLayer) { - this(map, tileLayer, MIN_ZOOM, MAX_ZOOM); - } + public BuildingLayer(Map map, VectorTileLayer tileLayer) { + this(map, tileLayer, MIN_ZOOM, MAX_ZOOM); + } - public BuildingLayer(Map map, VectorTileLayer tileLayer, int zoomMin, int zoomMax) { + public BuildingLayer(Map map, VectorTileLayer tileLayer, int zoomMin, int zoomMax) { - super(map); + super(map); - tileLayer.addHook(this); + tileLayer.addHook(this); - mRenderer = new BuildingRenderer(tileLayer.tileRenderer(), - zoomMin, zoomMax, - false, TRANSLUCENT); - if (POST_AA) - mRenderer = new OffscreenRenderer(Mode.SSAO_FXAA, mRenderer); - } + mRenderer = new BuildingRenderer(tileLayer.tileRenderer(), + zoomMin, zoomMax, + false, TRANSLUCENT); + if (POST_AA) + mRenderer = new OffscreenRenderer(Mode.SSAO_FXAA, mRenderer); + } - /** TileLoaderThemeHook */ - @Override - public boolean process(MapTile tile, RenderBuckets buckets, MapElement element, - RenderStyle style, int level) { + /** + * TileLoaderThemeHook + */ + @Override + public boolean process(MapTile tile, RenderBuckets buckets, MapElement element, + RenderStyle style, int level) { - if (!(style instanceof ExtrusionStyle)) - return false; + if (!(style instanceof ExtrusionStyle)) + return false; - ExtrusionStyle extrusion = (ExtrusionStyle) style; + ExtrusionStyle extrusion = (ExtrusionStyle) style; - int height = 0; - int minHeight = 0; + int height = 0; + int minHeight = 0; - String v = element.tags.getValue(Tag.KEY_HEIGHT); - if (v != null) - height = Integer.parseInt(v); + String v = element.tags.getValue(Tag.KEY_HEIGHT); + if (v != null) + height = Integer.parseInt(v); - v = element.tags.getValue(Tag.KEY_MIN_HEIGHT); - if (v != null) - minHeight = Integer.parseInt(v); + v = element.tags.getValue(Tag.KEY_MIN_HEIGHT); + if (v != null) + minHeight = Integer.parseInt(v); /* 12m default */ - if (height == 0) - height = 12 * 100; + if (height == 0) + height = 12 * 100; - ExtrusionBuckets ebs = get(tile); + ExtrusionBuckets ebs = get(tile); - for (ExtrusionBucket b = ebs.buckets; b != null; b = b.next()) { - if (b.colors == extrusion.colors) { - b.add(element, height, minHeight); - return true; - } - } + for (ExtrusionBucket b = ebs.buckets; b != null; b = b.next()) { + if (b.colors == extrusion.colors) { + b.add(element, height, minHeight); + return true; + } + } - double lat = MercatorProjection.toLatitude(tile.y); - float groundScale = (float) MercatorProjection - .groundResolution(lat, 1 << tile.zoomLevel); + double lat = MercatorProjection.toLatitude(tile.y); + float groundScale = (float) MercatorProjection + .groundResolution(lat, 1 << tile.zoomLevel); - ebs.buckets = Inlist.push(ebs.buckets, - new ExtrusionBucket(0, groundScale, - extrusion.colors)); + ebs.buckets = Inlist.push(ebs.buckets, + new ExtrusionBucket(0, groundScale, + extrusion.colors)); - ebs.buckets.add(element, height, minHeight); + ebs.buckets.add(element, height, minHeight); - return true; - } + return true; + } - public static ExtrusionBuckets get(MapTile tile) { - ExtrusionBuckets eb = (ExtrusionBuckets) tile.getData(BUILDING_DATA); - if (eb == null) { - eb = new ExtrusionBuckets(tile); - tile.addData(BUILDING_DATA, eb); - } - return eb; - } + public static ExtrusionBuckets get(MapTile tile) { + ExtrusionBuckets eb = (ExtrusionBuckets) tile.getData(BUILDING_DATA); + if (eb == null) { + eb = new ExtrusionBuckets(tile); + tile.addData(BUILDING_DATA, eb); + } + return eb; + } - @Override - public void complete(MapTile tile, boolean success) { - if (success) - get(tile).prepare(); - else - get(tile).setBuckets(null); - } + @Override + public void complete(MapTile tile, boolean success) { + if (success) + get(tile).prepare(); + else + get(tile).setBuckets(null); + } - // private int multi; - // @Override - // public void onInputEvent(Event event, MotionEvent e) { - // int action = e.getAction() & MotionEvent.ACTION_MASK; - // if (action == MotionEvent.ACTION_POINTER_DOWN) { - // multi++; - // } else if (action == MotionEvent.ACTION_POINTER_UP) { - // multi--; - // if (!mActive && mAlpha > 0) { - // // finish hiding - // //log.debug("add multi hide timer " + mAlpha); - // addShowTimer(mFadeTime * mAlpha, false); - // } - // } else if (action == MotionEvent.ACTION_CANCEL) { - // multi = 0; - // log.debug("cancel " + multi); - // if (mTimer != null) { - // mTimer.cancel(); - // mTimer = null; - // } - // } - // } + // private int multi; + // @Override + // public void onInputEvent(Event event, MotionEvent e) { + // int action = e.getAction() & MotionEvent.ACTION_MASK; + // if (action == MotionEvent.ACTION_POINTER_DOWN) { + // multi++; + // } else if (action == MotionEvent.ACTION_POINTER_UP) { + // multi--; + // if (!mActive && mAlpha > 0) { + // // finish hiding + // //log.debug("add multi hide timer " + mAlpha); + // addShowTimer(mFadeTime * mAlpha, false); + // } + // } else if (action == MotionEvent.ACTION_CANCEL) { + // multi = 0; + // log.debug("cancel " + multi); + // if (mTimer != null) { + // mTimer.cancel(); + // mTimer = null; + // } + // } + // } } diff --git a/vtm/src/org/oscim/layers/tile/buildings/BuildingRenderer.java b/vtm/src/org/oscim/layers/tile/buildings/BuildingRenderer.java index 745f167a..fe82e901 100644 --- a/vtm/src/org/oscim/layers/tile/buildings/BuildingRenderer.java +++ b/vtm/src/org/oscim/layers/tile/buildings/BuildingRenderer.java @@ -1,10 +1,5 @@ package org.oscim.layers.tile.buildings; -import static java.lang.System.currentTimeMillis; -import static org.oscim.layers.tile.MapTile.State.NEW_DATA; -import static org.oscim.layers.tile.MapTile.State.READY; -import static org.oscim.utils.FastMath.clamp; - import org.oscim.layers.tile.MapTile; import org.oscim.layers.tile.TileDistanceSort; import org.oscim.layers.tile.TileRenderer; @@ -17,187 +12,192 @@ import org.oscim.renderer.bucket.RenderBuckets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.lang.System.currentTimeMillis; +import static org.oscim.layers.tile.MapTile.State.NEW_DATA; +import static org.oscim.layers.tile.MapTile.State.READY; +import static org.oscim.utils.FastMath.clamp; + public class BuildingRenderer extends ExtrusionRenderer { - static final Logger log = LoggerFactory.getLogger(BuildingRenderer.class); + static final Logger log = LoggerFactory.getLogger(BuildingRenderer.class); - private final TileRenderer mTileRenderer; - private final TileSet mTileSet; + private final TileRenderer mTileRenderer; + private final TileSet mTileSet; - private final int mZoomMin; - private final int mZoomMax; + private final int mZoomMin; + private final int mZoomMax; - private final float mFadeInTime = 250; - private final float mFadeOutTime = 400; + private final float mFadeInTime = 250; + private final float mFadeOutTime = 400; - private long mAnimTime; - private boolean mShow; + private long mAnimTime; + private boolean mShow; - public BuildingRenderer(TileRenderer tileRenderer, int zoomMin, int zoomMax, - boolean mesh, boolean alpha) { - super(mesh, alpha); + public BuildingRenderer(TileRenderer tileRenderer, int zoomMin, int zoomMax, + boolean mesh, boolean alpha) { + super(mesh, alpha); - mZoomMax = zoomMax; - mZoomMin = zoomMin; - mTileRenderer = tileRenderer; - mTileSet = new TileSet(); - } + mZoomMax = zoomMax; + mZoomMin = zoomMin; + mTileRenderer = tileRenderer; + mTileSet = new TileSet(); + } - @Override - public boolean setup() { - mAlpha = 0; - return super.setup(); + @Override + public boolean setup() { + mAlpha = 0; + return super.setup(); - } + } - @Override - public void update(GLViewport v) { + @Override + public void update(GLViewport v) { - int diff = (v.pos.zoomLevel - mZoomMin); + int diff = (v.pos.zoomLevel - mZoomMin); /* if below min zoom or already faded out */ - if (diff < -1) { - mAlpha = 0; - mShow = false; - setReady(false); - return; - } + if (diff < -1) { + mAlpha = 0; + mShow = false; + setReady(false); + return; + } - if (diff >= 0) { - if (mAlpha < 1) { - long now = currentTimeMillis(); - if (!mShow) - mAnimTime = now - (long) (mAlpha * mFadeInTime); + if (diff >= 0) { + if (mAlpha < 1) { + long now = currentTimeMillis(); + if (!mShow) + mAnimTime = now - (long) (mAlpha * mFadeInTime); - mShow = true; - mAlpha = clamp((now - mAnimTime) / mFadeInTime, 0, 1); - MapRenderer.animate(); - } - } else { - if (mAlpha > 0) { - long now = currentTimeMillis(); - if (mShow) - mAnimTime = now - (long) ((1 - mAlpha) * mFadeOutTime); + mShow = true; + mAlpha = clamp((now - mAnimTime) / mFadeInTime, 0, 1); + MapRenderer.animate(); + } + } else { + if (mAlpha > 0) { + long now = currentTimeMillis(); + if (mShow) + mAnimTime = now - (long) ((1 - mAlpha) * mFadeOutTime); - mShow = false; - mAlpha = clamp(1 - (now - mAnimTime) / mFadeOutTime, 0, 1); - MapRenderer.animate(); - } - } + mShow = false; + mAlpha = clamp(1 - (now - mAnimTime) / mFadeOutTime, 0, 1); + MapRenderer.animate(); + } + } - if (mAlpha == 0) { - setReady(false); - return; - } + if (mAlpha == 0) { + setReady(false); + return; + } - mTileRenderer.getVisibleTiles(mTileSet); + mTileRenderer.getVisibleTiles(mTileSet); - if (mTileSet.cnt == 0) { - mTileRenderer.releaseTiles(mTileSet); - setReady(false); - return; - } + if (mTileSet.cnt == 0) { + mTileRenderer.releaseTiles(mTileSet); + setReady(false); + return; + } - MapTile[] tiles = mTileSet.tiles; - TileDistanceSort.sort(tiles, 0, mTileSet.cnt); + MapTile[] tiles = mTileSet.tiles; + TileDistanceSort.sort(tiles, 0, mTileSet.cnt); /* keep a list of tiles available for rendering */ - int maxTiles = mTileSet.cnt * 4; - if (mExtrusionBucketSet.length < maxTiles) - mExtrusionBucketSet = new ExtrusionBuckets[maxTiles]; + int maxTiles = mTileSet.cnt * 4; + if (mExtrusionBucketSet.length < maxTiles) + mExtrusionBucketSet = new ExtrusionBuckets[maxTiles]; /* compile one tile max per frame */ - boolean compiled = false; + boolean compiled = false; - int activeTiles = 0; - int zoom = tiles[0].zoomLevel; + int activeTiles = 0; + int zoom = tiles[0].zoomLevel; - if (zoom >= mZoomMin && zoom <= mZoomMax) { - /* TODO - if tile is not available try parent or children */ + if (zoom >= mZoomMin && zoom <= mZoomMax) { + /* TODO - if tile is not available try parent or children */ - for (int i = 0; i < mTileSet.cnt; i++) { - ExtrusionBuckets ebs = getBuckets(tiles[i]); - if (ebs == null) - continue; + for (int i = 0; i < mTileSet.cnt; i++) { + ExtrusionBuckets ebs = getBuckets(tiles[i]); + if (ebs == null) + continue; - if (ebs.compiled) - mExtrusionBucketSet[activeTiles++] = ebs; - else if (!compiled && ebs.compile()) { - mExtrusionBucketSet[activeTiles++] = ebs; - compiled = true; - } - } - } else if (zoom == mZoomMax + 1) { - /* special case for s3db: render from parent tiles */ - for (int i = 0; i < mTileSet.cnt; i++) { - MapTile t = tiles[i].node.parent(); + if (ebs.compiled) + mExtrusionBucketSet[activeTiles++] = ebs; + else if (!compiled && ebs.compile()) { + mExtrusionBucketSet[activeTiles++] = ebs; + compiled = true; + } + } + } else if (zoom == mZoomMax + 1) { + /* special case for s3db: render from parent tiles */ + for (int i = 0; i < mTileSet.cnt; i++) { + MapTile t = tiles[i].node.parent(); - if (t == null) - continue; + if (t == null) + continue; - // for (MapTile c : mTiles) - // if (c == t) - // continue O; + // for (MapTile c : mTiles) + // if (c == t) + // continue O; - ExtrusionBuckets ebs = getBuckets(t); - if (ebs == null) - continue; + ExtrusionBuckets ebs = getBuckets(t); + if (ebs == null) + continue; - if (ebs.compiled) - mExtrusionBucketSet[activeTiles++] = ebs; + if (ebs.compiled) + mExtrusionBucketSet[activeTiles++] = ebs; - else if (!compiled && ebs.compile()) { - mExtrusionBucketSet[activeTiles++] = ebs; - compiled = true; - } - } - } else if (zoom == mZoomMin - 1) { + else if (!compiled && ebs.compile()) { + mExtrusionBucketSet[activeTiles++] = ebs; + compiled = true; + } + } + } else if (zoom == mZoomMin - 1) { /* check if proxy children are ready */ - for (int i = 0; i < mTileSet.cnt; i++) { - MapTile t = tiles[i]; - for (byte j = 0; j < 4; j++) { - if (!t.hasProxy(1 << j)) - continue; + for (int i = 0; i < mTileSet.cnt; i++) { + MapTile t = tiles[i]; + for (byte j = 0; j < 4; j++) { + if (!t.hasProxy(1 << j)) + continue; - MapTile c = t.node.child(j); - ExtrusionBuckets eb = getBuckets(c); + MapTile c = t.node.child(j); + ExtrusionBuckets eb = getBuckets(c); - if (eb == null || !eb.compiled) - continue; + if (eb == null || !eb.compiled) + continue; - mExtrusionBucketSet[activeTiles++] = eb; - } - } - } + mExtrusionBucketSet[activeTiles++] = eb; + } + } + } /* load more tiles on next frame */ - if (compiled) - MapRenderer.animate(); + if (compiled) + MapRenderer.animate(); - mBucketsCnt = activeTiles; + mBucketsCnt = activeTiles; - //log.debug("active tiles: {}", mExtrusionLayerCnt); + //log.debug("active tiles: {}", mExtrusionLayerCnt); - if (activeTiles == 0) { - mTileRenderer.releaseTiles(mTileSet); - setReady(false); - return; - } - setReady(true); - } + if (activeTiles == 0) { + mTileRenderer.releaseTiles(mTileSet); + setReady(false); + return; + } + setReady(true); + } - @Override - public void render(GLViewport v) { - super.render(v); + @Override + public void render(GLViewport v) { + super.render(v); /* release lock on tile data */ - mTileRenderer.releaseTiles(mTileSet); - } + mTileRenderer.releaseTiles(mTileSet); + } - private static ExtrusionBuckets getBuckets(MapTile t) { - RenderBuckets buckets = t.getBuckets(); - if (buckets != null && !t.state(READY | NEW_DATA)) - return null; + private static ExtrusionBuckets getBuckets(MapTile t) { + RenderBuckets buckets = t.getBuckets(); + if (buckets != null && !t.state(READY | NEW_DATA)) + return null; - return BuildingLayer.get(t); - } + return BuildingLayer.get(t); + } } diff --git a/vtm/src/org/oscim/layers/tile/buildings/S3DBLayer.java b/vtm/src/org/oscim/layers/tile/buildings/S3DBLayer.java index 1bdfa888..b5ccb7fd 100644 --- a/vtm/src/org/oscim/layers/tile/buildings/S3DBLayer.java +++ b/vtm/src/org/oscim/layers/tile/buildings/S3DBLayer.java @@ -16,172 +16,172 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class S3DBLayer extends TileLayer { - static final Logger log = LoggerFactory.getLogger(S3DBLayer.class); + static final Logger log = LoggerFactory.getLogger(S3DBLayer.class); - private final static int MAX_CACHE = 32; - private final static int SRC_ZOOM = 16; + private final static int MAX_CACHE = 32; + private final static int SRC_ZOOM = 16; - /* TODO get from theme */ - private final static double HSV_S = 0.7; - private final static double HSV_V = 1.2; + /* TODO get from theme */ + private final static double HSV_S = 0.7; + private final static double HSV_V = 1.2; - private final TileSource mTileSource; + private final TileSource mTileSource; - public S3DBLayer(Map map, TileSource tileSource) { - this(map, tileSource, true, false); - } + public S3DBLayer(Map map, TileSource tileSource) { + this(map, tileSource, true, false); + } - public S3DBLayer(Map map, TileSource tileSource, boolean fxaa, boolean ssao) { - super(map, new TileManager(map, MAX_CACHE)); - setRenderer(new S3DBRenderer(fxaa, ssao)); + public S3DBLayer(Map map, TileSource tileSource, boolean fxaa, boolean ssao) { + super(map, new TileManager(map, MAX_CACHE)); + setRenderer(new S3DBRenderer(fxaa, ssao)); - mTileManager.setZoomLevel(SRC_ZOOM, SRC_ZOOM); - mTileSource = tileSource; - initLoader(2); - } + mTileManager.setZoomLevel(SRC_ZOOM, SRC_ZOOM); + mTileSource = tileSource; + initLoader(2); + } - @Override - protected S3DBTileLoader createLoader() { - return new S3DBTileLoader(getManager(), mTileSource); - } + @Override + protected S3DBTileLoader createLoader() { + return new S3DBTileLoader(getManager(), mTileSource); + } - public static class S3DBRenderer extends TileRenderer { - LayerRenderer mRenderer; + public static class S3DBRenderer extends TileRenderer { + LayerRenderer mRenderer; - public S3DBRenderer(boolean fxaa, boolean ssao) { - mRenderer = new BuildingRenderer(this, SRC_ZOOM, SRC_ZOOM, true, false); + public S3DBRenderer(boolean fxaa, boolean ssao) { + mRenderer = new BuildingRenderer(this, SRC_ZOOM, SRC_ZOOM, true, false); - if (fxaa || ssao) { - Mode mode = Mode.FXAA; - if (fxaa && ssao) - mode = Mode.SSAO_FXAA; - else if (ssao) - mode = Mode.SSAO; - mRenderer = new OffscreenRenderer(mode, mRenderer); - } - } + if (fxaa || ssao) { + Mode mode = Mode.FXAA; + if (fxaa && ssao) + mode = Mode.SSAO_FXAA; + else if (ssao) + mode = Mode.SSAO; + mRenderer = new OffscreenRenderer(mode, mRenderer); + } + } - @Override - public synchronized void update(GLViewport v) { - super.update(v); - mRenderer.update(v); - setReady(mRenderer.isReady()); - } + @Override + public synchronized void update(GLViewport v) { + super.update(v); + mRenderer.update(v); + setReady(mRenderer.isReady()); + } - @Override - public synchronized void render(GLViewport v) { - mRenderer.render(v); - } + @Override + public synchronized void render(GLViewport v) { + mRenderer.render(v); + } - @Override - public boolean setup() { - mRenderer.setup(); - return super.setup(); - } - } + @Override + public boolean setup() { + mRenderer.setup(); + return super.setup(); + } + } - static int getColor(String color, boolean roof) { + static int getColor(String color, boolean roof) { - if (color.charAt(0) == '#') { - int c = Color.parseColor(color, Color.CYAN); - /* hardcoded colors are way too saturated for my taste */ - return ColorUtil.modHsv(c, 1.0, 0.4, HSV_V, true); - } + if (color.charAt(0) == '#') { + int c = Color.parseColor(color, Color.CYAN); + /* hardcoded colors are way too saturated for my taste */ + return ColorUtil.modHsv(c, 1.0, 0.4, HSV_V, true); + } - if (roof) { - if ("brown" == color) - return Color.get(120, 110, 110); - if ("red" == color) - return Color.get(235, 140, 130); - if ("green" == color) - return Color.get(150, 200, 130); - if ("blue" == color) - return Color.get(100, 50, 200); - } - if ("white" == color) - return Color.get(240, 240, 240); - if ("black" == color) - return Color.get(86, 86, 86); - if ("grey" == color || "gray" == color) - return Color.get(120, 120, 120); - if ("red" == color) - return Color.get(255, 190, 190); - if ("green" == color) - return Color.get(190, 255, 190); - if ("blue" == color) - return Color.get(190, 190, 255); - if ("yellow" == color) - return Color.get(255, 255, 175); - if ("darkgray" == color || "darkgrey" == color) - return Color.DKGRAY; - if ("lightgray" == color || "lightgrey" == color) - return Color.LTGRAY; + if (roof) { + if ("brown" == color) + return Color.get(120, 110, 110); + if ("red" == color) + return Color.get(235, 140, 130); + if ("green" == color) + return Color.get(150, 200, 130); + if ("blue" == color) + return Color.get(100, 50, 200); + } + if ("white" == color) + return Color.get(240, 240, 240); + if ("black" == color) + return Color.get(86, 86, 86); + if ("grey" == color || "gray" == color) + return Color.get(120, 120, 120); + if ("red" == color) + return Color.get(255, 190, 190); + if ("green" == color) + return Color.get(190, 255, 190); + if ("blue" == color) + return Color.get(190, 190, 255); + if ("yellow" == color) + return Color.get(255, 255, 175); + if ("darkgray" == color || "darkgrey" == color) + return Color.DKGRAY; + if ("lightgray" == color || "lightgrey" == color) + return Color.LTGRAY; - if ("transparent" == color) - return Color.get(0, 1, 1, 1); + if ("transparent" == color) + return Color.get(0, 1, 1, 1); - Integer css = ColorsCSS.get(color); + Integer css = ColorsCSS.get(color); - if (css != null) - return ColorUtil.modHsv(css.intValue(), 1.0, HSV_S, HSV_V, true); + if (css != null) + return ColorUtil.modHsv(css.intValue(), 1.0, HSV_S, HSV_V, true); - log.debug("unknown color:{}", color); - return 0; - } + log.debug("unknown color:{}", color); + return 0; + } - static int getMaterialColor(String material, boolean roof) { + static int getMaterialColor(String material, boolean roof) { - if (roof) { - if ("glass" == material) - return Color.fade(Color.get(130, 224, 255), 0.9f); - } - if ("roof_tiles" == material) - return Color.get(216, 167, 111); - if ("tile" == material) - return Color.get(216, 167, 111); + if (roof) { + if ("glass" == material) + return Color.fade(Color.get(130, 224, 255), 0.9f); + } + if ("roof_tiles" == material) + return Color.get(216, 167, 111); + if ("tile" == material) + return Color.get(216, 167, 111); - if ("concrete" == material || - "cement_block" == material) - return Color.get(210, 212, 212); + if ("concrete" == material || + "cement_block" == material) + return Color.get(210, 212, 212); - if ("metal" == material) - return 0xFFC0C0C0; - if ("tar_paper" == material) - return 0xFF969998; - if ("eternit" == material) - return Color.get(216, 167, 111); - if ("tin" == material) - return 0xFFC0C0C0; - if ("asbestos" == material) - return Color.get(160, 152, 141); - if ("glass" == material) - return Color.get(130, 224, 255); - if ("slate" == material) - return 0xFF605960; - if ("zink" == material) - return Color.get(180, 180, 180); - if ("gravel" == material) - return Color.get(170, 130, 80); - if ("copper" == material) - // same as roof color:green - return Color.get(150, 200, 130); - if ("wood" == material) - return Color.get(170, 130, 80); - if ("grass" == material) - return 0xFF50AA50; - if ("stone" == material) - return Color.get(206, 207, 181); - if ("plaster" == material) - return Color.get(236, 237, 181); - if ("brick" == material) - return Color.get(255, 217, 191); - if ("stainless_steel" == material) - return Color.get(153, 157, 160); - if ("gold" == material) - return 0xFFFFD700; + if ("metal" == material) + return 0xFFC0C0C0; + if ("tar_paper" == material) + return 0xFF969998; + if ("eternit" == material) + return Color.get(216, 167, 111); + if ("tin" == material) + return 0xFFC0C0C0; + if ("asbestos" == material) + return Color.get(160, 152, 141); + if ("glass" == material) + return Color.get(130, 224, 255); + if ("slate" == material) + return 0xFF605960; + if ("zink" == material) + return Color.get(180, 180, 180); + if ("gravel" == material) + return Color.get(170, 130, 80); + if ("copper" == material) + // same as roof color:green + return Color.get(150, 200, 130); + if ("wood" == material) + return Color.get(170, 130, 80); + if ("grass" == material) + return 0xFF50AA50; + if ("stone" == material) + return Color.get(206, 207, 181); + if ("plaster" == material) + return Color.get(236, 237, 181); + if ("brick" == material) + return Color.get(255, 217, 191); + if ("stainless_steel" == material) + return Color.get(153, 157, 160); + if ("gold" == material) + return 0xFFFFD700; - log.debug("unknown material:{}", material); + log.debug("unknown material:{}", material); - return 0; - } + return 0; + } } diff --git a/vtm/src/org/oscim/layers/tile/buildings/S3DBTileLoader.java b/vtm/src/org/oscim/layers/tile/buildings/S3DBTileLoader.java index b8219ca7..37b0eba0 100644 --- a/vtm/src/org/oscim/layers/tile/buildings/S3DBTileLoader.java +++ b/vtm/src/org/oscim/layers/tile/buildings/S3DBTileLoader.java @@ -1,7 +1,5 @@ package org.oscim.layers.tile.buildings; -import static org.oscim.layers.tile.buildings.S3DBLayer.getMaterialColor; - import org.oscim.backend.canvas.Color; import org.oscim.core.GeometryBuffer; import org.oscim.core.GeometryBuffer.GeometryType; @@ -18,138 +16,142 @@ import org.oscim.tiling.TileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.layers.tile.buildings.S3DBLayer.getMaterialColor; + class S3DBTileLoader extends TileLoader { - static final Logger log = LoggerFactory.getLogger(S3DBTileLoader.class); + static final Logger log = LoggerFactory.getLogger(S3DBTileLoader.class); - /** current TileDataSource used by this MapTileLoader */ - private final ITileDataSource mTileDataSource; + /** + * current TileDataSource used by this MapTileLoader + */ + private final ITileDataSource mTileDataSource; - private ExtrusionBucket mParts; - private ExtrusionBucket mRoofs; + private ExtrusionBucket mParts; + private ExtrusionBucket mRoofs; - private float mGroundScale; + private float mGroundScale; - static MapElement mTilePlane = new MapElement(); + static MapElement mTilePlane = new MapElement(); - static { - mTilePlane = new MapElement(); - GeometryBuffer g = mTilePlane; - g.type = GeometryType.TRIS; - g.points = new float[] { - 0, 0, 0, - 4096, 0, 0, - 0, 4096, 0, - 4096, 4096, 0 }; - g.index = new int[] { 0, 1, 2, 2, 1, 3 }; - mTilePlane.tags.add(new Tag("c", "transparent")); - } + static { + mTilePlane = new MapElement(); + GeometryBuffer g = mTilePlane; + g.type = GeometryType.TRIS; + g.points = new float[]{ + 0, 0, 0, + 4096, 0, 0, + 0, 4096, 0, + 4096, 4096, 0}; + g.index = new int[]{0, 1, 2, 2, 1, 3}; + mTilePlane.tags.add(new Tag("c", "transparent")); + } - public S3DBTileLoader(TileManager tileManager, TileSource tileSource) { - super(tileManager); - mTileDataSource = tileSource.getDataSource(); + public S3DBTileLoader(TileManager tileManager, TileSource tileSource) { + super(tileManager); + mTileDataSource = tileSource.getDataSource(); - } + } - @Override - public void dispose() { - mTileDataSource.dispose(); - } + @Override + public void dispose() { + mTileDataSource.dispose(); + } - @Override - public void cancel() { - mTileDataSource.cancel(); - } + @Override + public void cancel() { + mTileDataSource.cancel(); + } - @Override - protected boolean loadTile(MapTile tile) { - mTile = tile; + @Override + protected boolean loadTile(MapTile tile) { + mTile = tile; - try { - /* query database, which calls process() callback */ - mTileDataSource.query(mTile, this); - } catch (Exception e) { - log.debug("{}", e); - return false; - } + try { + /* query database, which calls process() callback */ + mTileDataSource.query(mTile, this); + } catch (Exception e) { + log.debug("{}", e); + return false; + } - return true; - } + return true; + } - private void initTile(MapTile tile) { - double lat = MercatorProjection.toLatitude(tile.y); - mGroundScale = (float) MercatorProjection - .groundResolution(lat, 1 << mTile.zoomLevel); + private void initTile(MapTile tile) { + double lat = MercatorProjection.toLatitude(tile.y); + mGroundScale = (float) MercatorProjection + .groundResolution(lat, 1 << mTile.zoomLevel); - mRoofs = new ExtrusionBucket(0, mGroundScale, Color.get(247, 249, 250)); + mRoofs = new ExtrusionBucket(0, mGroundScale, Color.get(247, 249, 250)); - mParts = new ExtrusionBucket(0, mGroundScale, Color.get(255, 254, 252)); - //mRoofs = new ExtrusionLayer(0, mGroundScale, Color.get(207, 209, 210)); - mRoofs.next = mParts; + mParts = new ExtrusionBucket(0, mGroundScale, Color.get(255, 254, 252)); + //mRoofs = new ExtrusionLayer(0, mGroundScale, Color.get(207, 209, 210)); + mRoofs.next = mParts; - BuildingLayer.get(tile).setBuckets(mRoofs); + BuildingLayer.get(tile).setBuckets(mRoofs); - process(mTilePlane); - } + process(mTilePlane); + } - String COLOR_KEY = "c"; - String MATERIAL_KEY = "m"; - String ROOF_KEY = "roof"; - String ROOF_SHAPE_KEY = "roof:shape"; + String COLOR_KEY = "c"; + String MATERIAL_KEY = "m"; + String ROOF_KEY = "roof"; + String ROOF_SHAPE_KEY = "roof:shape"; - @Override - public void process(MapElement element) { + @Override + public void process(MapElement element) { - if (element.type != GeometryType.TRIS) { - log.debug("wrong type " + element.type); - return; - } + if (element.type != GeometryType.TRIS) { + log.debug("wrong type " + element.type); + return; + } - if (mParts == null) - initTile(mTile); + if (mParts == null) + initTile(mTile); - boolean isRoof = element.tags.containsKey(ROOF_KEY); - //if (isRoof) - // log.debug(element.tags.toString()); + boolean isRoof = element.tags.containsKey(ROOF_KEY); + //if (isRoof) + // log.debug(element.tags.toString()); - int c = 0; - if (element.tags.containsKey(COLOR_KEY)) { - c = S3DBLayer.getColor(element.tags.getValue(COLOR_KEY), isRoof); - } + int c = 0; + if (element.tags.containsKey(COLOR_KEY)) { + c = S3DBLayer.getColor(element.tags.getValue(COLOR_KEY), isRoof); + } - if (c == 0 && element.tags.containsKey(MATERIAL_KEY)) { - c = getMaterialColor(element.tags.getValue(MATERIAL_KEY), isRoof); - } + if (c == 0 && element.tags.containsKey(MATERIAL_KEY)) { + c = getMaterialColor(element.tags.getValue(MATERIAL_KEY), isRoof); + } - if (c == 0) { - String roofShape = element.tags.getValue(ROOF_SHAPE_KEY); + if (c == 0) { + String roofShape = element.tags.getValue(ROOF_SHAPE_KEY); - if (isRoof && (roofShape == null || "flat".equals(roofShape))) - mRoofs.add(element); - else - mParts.add(element); - return; - } + if (isRoof && (roofShape == null || "flat".equals(roofShape))) + mRoofs.add(element); + else + mParts.add(element); + return; + } - for (ExtrusionBucket l = mParts; l != null; l = l.next()) { - if (l.color == c) { - l.add(element); - return; - } - } - ExtrusionBucket l = new ExtrusionBucket(0, mGroundScale, c); + for (ExtrusionBucket l = mParts; l != null; l = l.next()) { + if (l.color == c) { + l.add(element); + return; + } + } + ExtrusionBucket l = new ExtrusionBucket(0, mGroundScale, c); - l.next = mParts.next; - mParts.next = l; + l.next = mParts.next; + mParts.next = l; - l.add(element); - } + l.add(element); + } - @Override - public void completed(QueryResult result) { + @Override + public void completed(QueryResult result) { - mParts = null; - mRoofs = null; + mParts = null; + mRoofs = null; - super.completed(result); - } + super.completed(result); + } } diff --git a/vtm/src/org/oscim/layers/tile/example/TestTileLayer.java b/vtm/src/org/oscim/layers/tile/example/TestTileLayer.java index ec61c30c..770cba3d 100644 --- a/vtm/src/org/oscim/layers/tile/example/TestTileLayer.java +++ b/vtm/src/org/oscim/layers/tile/example/TestTileLayer.java @@ -33,62 +33,62 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestTileLayer extends TileLayer { - static final Logger log = LoggerFactory.getLogger(TestTileLayer.class); + static final Logger log = LoggerFactory.getLogger(TestTileLayer.class); - public TestTileLayer(Map map) { - super(map, - new TileManager(map, 10), - new VectorTileRenderer()); - } + public TestTileLayer(Map map) { + super(map, + new TileManager(map, 10), + new VectorTileRenderer()); + } - @Override - protected TestTileLoader createLoader() { - return new TestTileLoader(this); - } + @Override + protected TestTileLoader createLoader() { + return new TestTileLoader(this); + } - static class TestTileLoader extends TileLoader { + static class TestTileLoader extends TileLoader { - public TestTileLoader(TileLayer tileLayer) { - super(tileLayer.getManager()); - } + public TestTileLoader(TileLayer tileLayer) { + super(tileLayer.getManager()); + } - GeometryBuffer mGeom = new GeometryBuffer(128, 16); - LineStyle mLineStyle = new LineStyle(Color.BLUE, 2f, Cap.ROUND); + GeometryBuffer mGeom = new GeometryBuffer(128, 16); + LineStyle mLineStyle = new LineStyle(Color.BLUE, 2f, Cap.ROUND); - @Override - public boolean loadTile(MapTile tile) { - log.debug("load tile " + tile); - RenderBuckets buckets = new RenderBuckets(); - tile.data = buckets; + @Override + public boolean loadTile(MapTile tile) { + log.debug("load tile " + tile); + RenderBuckets buckets = new RenderBuckets(); + tile.data = buckets; - LineBucket lb = buckets.getLineBucket(0); - lb.line = mLineStyle; - lb.scale = 2; + LineBucket lb = buckets.getLineBucket(0); + lb.line = mLineStyle; + lb.scale = 2; - int m = 20; - int s = Tile.SIZE - m * 2; - GeometryBuffer g = mGeom; + int m = 20; + int s = Tile.SIZE - m * 2; + GeometryBuffer g = mGeom; - g.clear(); - g.startLine(); - g.addPoint(m, m); - g.addPoint(m, s); - g.addPoint(s, s); - g.addPoint(s, m); - g.addPoint(m, m); + g.clear(); + g.startLine(); + g.addPoint(m, m); + g.addPoint(m, s); + g.addPoint(s, s); + g.addPoint(s, m); + g.addPoint(m, m); - lb.addLine(g); + lb.addLine(g); - return true; - } + return true; + } - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public void cancel() { - } + @Override + public void cancel() { + } - } + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/OsmTileLayer.java b/vtm/src/org/oscim/layers/tile/vector/OsmTileLayer.java index 3a008e2c..2f3c95ed 100644 --- a/vtm/src/org/oscim/layers/tile/vector/OsmTileLayer.java +++ b/vtm/src/org/oscim/layers/tile/vector/OsmTileLayer.java @@ -7,60 +7,61 @@ import org.oscim.map.Map; public class OsmTileLayer extends VectorTileLayer { - protected final static int MAX_ZOOMLEVEL = 17; - protected final static int MIN_ZOOMLEVEL = 2; - protected final static int CACHE_LIMIT = 150; + protected final static int MAX_ZOOMLEVEL = 17; + protected final static int MIN_ZOOMLEVEL = 2; + protected final static int CACHE_LIMIT = 150; - public OsmTileLayer(Map map) { - super(map, CACHE_LIMIT); - mTileManager.setZoomLevel(MIN_ZOOMLEVEL, MAX_ZOOMLEVEL); - } + public OsmTileLayer(Map map) { + super(map, CACHE_LIMIT); + mTileManager.setZoomLevel(MIN_ZOOMLEVEL, MAX_ZOOMLEVEL); + } - @Override - protected TileLoader createLoader() { - return new OsmTileLoader(this); - } + @Override + protected TileLoader createLoader() { + return new OsmTileLoader(this); + } - static class OsmTileLoader extends VectorTileLoader { - private final TagSet mFilteredTags; + static class OsmTileLoader extends VectorTileLoader { + private final TagSet mFilteredTags; - public OsmTileLoader(VectorTileLayer tileLayer) { - super(tileLayer); - mFilteredTags = new TagSet(); - } + public OsmTileLoader(VectorTileLayer tileLayer) { + super(tileLayer); + mFilteredTags = new TagSet(); + } - /* Replace tags that should only be matched by key in RenderTheme - * to avoid caching RenderInstructions for each way of the same type - * only with different name. - * Maybe this should be done within RenderTheme, also allowing - * to set these replacement rules in theme file. */ - private static final TagReplacement[] mTagReplacement = { - new TagReplacement(Tag.KEY_NAME), - new TagReplacement(Tag.KEY_HOUSE_NUMBER), - new TagReplacement(Tag.KEY_REF), - new TagReplacement(Tag.KEY_HEIGHT), - new TagReplacement(Tag.KEY_MIN_HEIGHT) - }; + /* Replace tags that should only be matched by key in RenderTheme + * to avoid caching RenderInstructions for each way of the same type + * only with different name. + * Maybe this should be done within RenderTheme, also allowing + * to set these replacement rules in theme file. */ + private static final TagReplacement[] mTagReplacement = { + new TagReplacement(Tag.KEY_NAME), + new TagReplacement(Tag.KEY_HOUSE_NUMBER), + new TagReplacement(Tag.KEY_REF), + new TagReplacement(Tag.KEY_HEIGHT), + new TagReplacement(Tag.KEY_MIN_HEIGHT) + }; - protected TagSet filterTags(TagSet tagSet) { - Tag[] tags = tagSet.tags; + protected TagSet filterTags(TagSet tagSet) { + Tag[] tags = tagSet.tags; - mFilteredTags.clear(); + mFilteredTags.clear(); - O: for (int i = 0, n = tagSet.numTags; i < n; i++) { - Tag t = tags[i]; + O: + for (int i = 0, n = tagSet.numTags; i < n; i++) { + Tag t = tags[i]; - for (TagReplacement replacement : mTagReplacement) { - if (t.key == replacement.key) { - mFilteredTags.add(replacement.tag); - continue O; - } - } + for (TagReplacement replacement : mTagReplacement) { + if (t.key == replacement.key) { + mFilteredTags.add(replacement.tag); + continue O; + } + } - mFilteredTags.add(t); - } + mFilteredTags.add(t); + } - return mFilteredTags; - } - } + return mFilteredTags; + } + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/VectorTileLayer.java b/vtm/src/org/oscim/layers/tile/vector/VectorTileLayer.java index f5b628c2..65bcd21a 100644 --- a/vtm/src/org/oscim/layers/tile/vector/VectorTileLayer.java +++ b/vtm/src/org/oscim/layers/tile/vector/VectorTileLayer.java @@ -39,177 +39,183 @@ import org.slf4j.LoggerFactory; * for rendering. */ public class VectorTileLayer extends TileLayer { - static final Logger log = LoggerFactory.getLogger(VectorTileLayer.class); + static final Logger log = LoggerFactory.getLogger(VectorTileLayer.class); - protected TileSource mTileSource; + protected TileSource mTileSource; - public VectorTileLayer(Map map, TileSource tileSource) { - this(map, new TileManager(map, - 100), - new VectorTileRenderer()); + public VectorTileLayer(Map map, TileSource tileSource) { + this(map, new TileManager(map, + 100), + new VectorTileRenderer()); - setTileSource(tileSource); - } + setTileSource(tileSource); + } - public VectorTileLayer(Map map, int cacheLimit) { - this(map, new TileManager(map, cacheLimit), - new VectorTileRenderer()); - } + public VectorTileLayer(Map map, int cacheLimit) { + this(map, new TileManager(map, cacheLimit), + new VectorTileRenderer()); + } - public VectorTileLayer(Map map, TileManager tileManager, - VectorTileRenderer renderer) { - super(map, tileManager, renderer); + public VectorTileLayer(Map map, TileManager tileManager, + VectorTileRenderer renderer) { + super(map, tileManager, renderer); - initLoader(getNumLoaders()); - } + initLoader(getNumLoaders()); + } - @Override - protected TileLoader createLoader() { - return new VectorTileLoader(this); - } + @Override + protected TileLoader createLoader() { + return new VectorTileLoader(this); + } - /** - * Sets the {@link TileSource} used by {@link TileLoader}. - * - * @return true when new TileSource was set (has changed) - */ - public boolean setTileSource(TileSource tileSource) { - pauseLoaders(true); - mTileManager.clearJobs(); - mTileManager.setZoomLevel(tileSource.getZoomLevelMin(), - tileSource.getZoomLevelMax()); + /** + * Sets the {@link TileSource} used by {@link TileLoader}. + * + * @return true when new TileSource was set (has changed) + */ + public boolean setTileSource(TileSource tileSource) { + pauseLoaders(true); + mTileManager.clearJobs(); + mTileManager.setZoomLevel(tileSource.getZoomLevelMin(), + tileSource.getZoomLevelMax()); - if (mTileSource != null) { - mTileSource.close(); - mTileSource = null; - } + if (mTileSource != null) { + mTileSource.close(); + mTileSource = null; + } - OpenResult msg = tileSource.open(); + OpenResult msg = tileSource.open(); - if (msg != OpenResult.SUCCESS) { - log.debug(msg.getErrorMessage()); - return false; - } + if (msg != OpenResult.SUCCESS) { + log.debug(msg.getErrorMessage()); + return false; + } - mTileSource = tileSource; + mTileSource = tileSource; - for (TileLoader l : mTileLoader) - ((VectorTileLoader) l).setDataSource(tileSource.getDataSource()); + for (TileLoader l : mTileLoader) + ((VectorTileLoader) l).setDataSource(tileSource.getDataSource()); - mMap.clearMap(); - resumeLoaders(); + mMap.clearMap(); + resumeLoaders(); - return true; - } + return true; + } - /** - * Set {@link IRenderTheme} used by {@link TileLoader} - */ - public void setRenderTheme(IRenderTheme theme) { - /* wait for loaders to finish all current jobs to - * not change theme instance hold by loader instance + /** + * Set {@link IRenderTheme} used by {@link TileLoader} + */ + public void setRenderTheme(IRenderTheme theme) { + /* wait for loaders to finish all current jobs to + * not change theme instance hold by loader instance * while running */ - pauseLoaders(true); - mTileManager.clearJobs(); + pauseLoaders(true); + mTileManager.clearJobs(); - mTheme = theme; - // for (TileLoader l : mTileLoader) - // ((VectorTileLoader) l).setRenderTheme(theme); + mTheme = theme; + // for (TileLoader l : mTileLoader) + // ((VectorTileLoader) l).setRenderTheme(theme); - tileRenderer().setOverdrawColor(theme.getMapBackground()); + tileRenderer().setOverdrawColor(theme.getMapBackground()); - resumeLoaders(); - } + resumeLoaders(); + } - private IRenderTheme mTheme; + private IRenderTheme mTheme; - public IRenderTheme getTheme() { - return mTheme; - } + public IRenderTheme getTheme() { + return mTheme; + } - /** - * Hook to intercept tile data processing. Called concurently by tile - * loader threads, so dont keep tile specific state. - */ - public interface TileLoaderProcessHook { - public boolean process(MapTile tile, RenderBuckets layers, MapElement element); + /** + * Hook to intercept tile data processing. Called concurently by tile + * loader threads, so dont keep tile specific state. + */ + public interface TileLoaderProcessHook { + public boolean process(MapTile tile, RenderBuckets layers, MapElement element); - /** Called on loader thread when tile loading is completed */ - public void complete(MapTile tile, boolean success); - } + /** + * Called on loader thread when tile loading is completed + */ + public void complete(MapTile tile, boolean success); + } - /** - * Hook to intercept tile data processing after theme style lookup. Called - * concurently by tile loader threads, so dont keep tile specific state. See - * e.g. LabelTileLoaderHook. - */ - public interface TileLoaderThemeHook { - /** Called for each RenderStyle found for a MapElement. */ - public boolean process(MapTile tile, RenderBuckets buckets, - MapElement element, RenderStyle style, int level); + /** + * Hook to intercept tile data processing after theme style lookup. Called + * concurently by tile loader threads, so dont keep tile specific state. See + * e.g. LabelTileLoaderHook. + */ + public interface TileLoaderThemeHook { + /** + * Called for each RenderStyle found for a MapElement. + */ + public boolean process(MapTile tile, RenderBuckets buckets, + MapElement element, RenderStyle style, int level); - /** Called on loader thread when tile loading is completed */ - public void complete(MapTile tile, boolean success); - } + /** + * Called on loader thread when tile loading is completed + */ + public void complete(MapTile tile, boolean success); + } - private List> mLoaderProcessHooks = - new List>(); + private List> mLoaderProcessHooks = + new List>(); - private List> mLoaderThemeHooks = - new List>(); + private List> mLoaderThemeHooks = + new List>(); - public void addHook(TileLoaderProcessHook h) { - mLoaderProcessHooks.append(new LList(h)); - } + public void addHook(TileLoaderProcessHook h) { + mLoaderProcessHooks.append(new LList(h)); + } - public void addHook(TileLoaderThemeHook h) { - mLoaderThemeHooks.append(new LList(h)); - } + public void addHook(TileLoaderThemeHook h) { + mLoaderThemeHooks.append(new LList(h)); + } - @Override - public void onDetach() { - super.onDetach(); - mTileSource.close(); - } + @Override + public void onDetach() { + super.onDetach(); + mTileSource.close(); + } - public void callThemeHooks(MapTile tile, RenderBuckets layers, MapElement element, - RenderStyle style, int level) { + public void callThemeHooks(MapTile tile, RenderBuckets layers, MapElement element, + RenderStyle style, int level) { - LList th = mLoaderThemeHooks.head(); - while (th != null) { - if (th.data.process(tile, layers, element, style, level)) - return; + LList th = mLoaderThemeHooks.head(); + while (th != null) { + if (th.data.process(tile, layers, element, style, level)) + return; - th = th.next; - } - } + th = th.next; + } + } - public boolean callProcessHooks(MapTile tile, RenderBuckets layers, MapElement element) { + public boolean callProcessHooks(MapTile tile, RenderBuckets layers, MapElement element) { - LList ph = mLoaderProcessHooks.head(); - while (ph != null) { - if (ph.data.process(tile, layers, element)) - return true; - ph = ph.next; - } + LList ph = mLoaderProcessHooks.head(); + while (ph != null) { + if (ph.data.process(tile, layers, element)) + return true; + ph = ph.next; + } - return false; - } + return false; + } - public void callHooksComplete(MapTile tile, boolean success) { + public void callHooksComplete(MapTile tile, boolean success) { /* NB: cannot use internal iterater as this function * is called concurently by TileLoaders */ - LList th = mLoaderThemeHooks.head(); - while (th != null) { - th.data.complete(tile, success); - th = th.next; - } + LList th = mLoaderThemeHooks.head(); + while (th != null) { + th.data.complete(tile, success); + th = th.next; + } - LList ph = mLoaderProcessHooks.head(); - while (ph != null) { - ph.data.complete(tile, success); - ph = ph.next; - } - } + LList ph = mLoaderProcessHooks.head(); + while (ph != null) { + ph.data.complete(tile, success); + ph = ph.next; + } + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/VectorTileLoader.java b/vtm/src/org/oscim/layers/tile/vector/VectorTileLoader.java index 7debfb4f..71171233 100644 --- a/vtm/src/org/oscim/layers/tile/vector/VectorTileLoader.java +++ b/vtm/src/org/oscim/layers/tile/vector/VectorTileLoader.java @@ -17,8 +17,6 @@ */ package org.oscim.layers.tile.vector; -import static org.oscim.layers.tile.MapTile.State.LOADING; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.MercatorProjection; @@ -46,272 +44,286 @@ import org.oscim.tiling.QueryResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.layers.tile.MapTile.State.LOADING; + public class VectorTileLoader extends TileLoader implements RenderStyle.Callback { - static final Logger log = LoggerFactory.getLogger(VectorTileLoader.class); + static final Logger log = LoggerFactory.getLogger(VectorTileLoader.class); - protected static final double STROKE_INCREASE = Math.sqrt(2.5); - protected static final byte LAYERS = 11; + protected static final double STROKE_INCREASE = Math.sqrt(2.5); + protected static final byte LAYERS = 11; - public static final byte STROKE_MIN_ZOOM = 12; - public static final byte STROKE_MAX_ZOOM = 17; + public static final byte STROKE_MIN_ZOOM = 12; + public static final byte STROKE_MAX_ZOOM = 17; - protected IRenderTheme renderTheme; + protected IRenderTheme renderTheme; - /** current TileDataSource used by this MapTileLoader */ - protected ITileDataSource mTileDataSource; + /** + * current TileDataSource used by this MapTileLoader + */ + protected ITileDataSource mTileDataSource; - /** currently processed MapElement */ - protected MapElement mElement; + /** + * currently processed MapElement + */ + protected MapElement mElement; - /** current line bucket (will be used for outline bucket) */ - protected LineBucket mCurLineBucket; + /** + * current line bucket (will be used for outline bucket) + */ + protected LineBucket mCurLineBucket; - /** Current bucket for adding elements */ - protected int mCurBucket; + /** + * Current bucket for adding elements + */ + protected int mCurBucket; - /** Line-scale-factor depending on zoom and latitude */ - protected float mLineScale = 1.0f; + /** + * Line-scale-factor depending on zoom and latitude + */ + protected float mLineScale = 1.0f; - protected RenderBuckets mBuckets; + protected RenderBuckets mBuckets; - private final VectorTileLayer mTileLayer; + private final VectorTileLayer mTileLayer; - public VectorTileLoader(VectorTileLayer tileLayer) { - super(tileLayer.getManager()); - mTileLayer = tileLayer; - } + public VectorTileLoader(VectorTileLayer tileLayer) { + super(tileLayer.getManager()); + mTileLayer = tileLayer; + } - @Override - public void dispose() { - if (mTileDataSource != null) - mTileDataSource.dispose(); - } + @Override + public void dispose() { + if (mTileDataSource != null) + mTileDataSource.dispose(); + } - @Override - public void cancel() { - if (mTileDataSource != null) - mTileDataSource.cancel(); - } + @Override + public void cancel() { + if (mTileDataSource != null) + mTileDataSource.cancel(); + } - @Override - public boolean loadTile(MapTile tile) { + @Override + public boolean loadTile(MapTile tile) { - if (mTileDataSource == null) { - log.error("no tile source is set"); - return false; - } - renderTheme = mTileLayer.getTheme(); - if (renderTheme == null) { - log.error("no theme is set"); - return false; - } + if (mTileDataSource == null) { + log.error("no tile source is set"); + return false; + } + renderTheme = mTileLayer.getTheme(); + if (renderTheme == null) { + log.error("no theme is set"); + return false; + } - //mTileLayer.getLoaderHooks(); + //mTileLayer.getLoaderHooks(); /* account for area changes with latitude */ - double lat = MercatorProjection.toLatitude(tile.y); - mLineScale = (float) Math.pow(STROKE_INCREASE, tile.zoomLevel - STROKE_MIN_ZOOM); - if (mLineScale < 1) - mLineScale = 1; + double lat = MercatorProjection.toLatitude(tile.y); + mLineScale = (float) Math.pow(STROKE_INCREASE, tile.zoomLevel - STROKE_MIN_ZOOM); + if (mLineScale < 1) + mLineScale = 1; /* scale line width relative to latitude + PI * thumb */ - mLineScale *= 0.4f + 0.6f * ((float) Math.sin(Math.abs(lat) * (Math.PI / 180))); - mBuckets = new RenderBuckets(); - tile.data = mBuckets; + mLineScale *= 0.4f + 0.6f * ((float) Math.sin(Math.abs(lat) * (Math.PI / 180))); + mBuckets = new RenderBuckets(); + tile.data = mBuckets; - try { - /* query data source, which calls process() callback */ - mTileDataSource.query(tile, this); - } catch (NullPointerException e) { - log.debug("NPE {} {}", tile, e.getMessage()); - e.printStackTrace(); - } catch (Exception e) { - log.debug("{} {}", tile, e.getMessage()); - e.printStackTrace(); - return false; - } - return true; - } + try { + /* query data source, which calls process() callback */ + mTileDataSource.query(tile, this); + } catch (NullPointerException e) { + log.debug("NPE {} {}", tile, e.getMessage()); + e.printStackTrace(); + } catch (Exception e) { + log.debug("{} {}", tile, e.getMessage()); + e.printStackTrace(); + return false; + } + return true; + } - @Override - public void completed(QueryResult result) { - boolean ok = (result == QueryResult.SUCCESS); + @Override + public void completed(QueryResult result) { + boolean ok = (result == QueryResult.SUCCESS); - mTileLayer.callHooksComplete(mTile, ok); + mTileLayer.callHooksComplete(mTile, ok); /* finish buckets- tessellate and cleanup on worker-thread */ - mBuckets.prepare(); - clearState(); + mBuckets.prepare(); + clearState(); - super.completed(result); - } + super.completed(result); + } - protected static int getValidLayer(int layer) { - if (layer < 0) { - return 0; - } else if (layer >= LAYERS) { - return LAYERS - 1; - } else { - return layer; - } - } + protected static int getValidLayer(int layer) { + if (layer < 0) { + return 0; + } else if (layer >= LAYERS) { + return LAYERS - 1; + } else { + return layer; + } + } - public void setDataSource(ITileDataSource dataSource) { - dispose(); - mTileDataSource = dataSource; - } + public void setDataSource(ITileDataSource dataSource) { + dispose(); + mTileDataSource = dataSource; + } - static class TagReplacement { - public TagReplacement(String key) { - this.key = key; - this.tag = new Tag(key, null); - } + static class TagReplacement { + public TagReplacement(String key) { + this.key = key; + this.tag = new Tag(key, null); + } - String key; - Tag tag; - } + String key; + Tag tag; + } - /** - * Override this method to change tags that should be passed - * to {@link RenderTheme} matching. - * E.g. to replace tags that should not be cached in Rendertheme - */ - protected TagSet filterTags(TagSet tagSet) { - return tagSet; - } + /** + * Override this method to change tags that should be passed + * to {@link RenderTheme} matching. + * E.g. to replace tags that should not be cached in Rendertheme + */ + protected TagSet filterTags(TagSet tagSet) { + return tagSet; + } - @Override - public void process(MapElement element) { - if (isCanceled() || !mTile.state(LOADING)) - return; + @Override + public void process(MapElement element) { + if (isCanceled() || !mTile.state(LOADING)) + return; - if (mTileLayer.callProcessHooks(mTile, mBuckets, element)) - return; + if (mTileLayer.callProcessHooks(mTile, mBuckets, element)) + return; - TagSet tags = filterTags(element.tags); - if (tags == null) - return; + TagSet tags = filterTags(element.tags); + if (tags == null) + return; - mElement = element; + mElement = element; /* get and apply render instructions */ - if (element.type == GeometryType.POINT) { - renderNode(renderTheme.matchElement(element.type, tags, mTile.zoomLevel)); - } else { - mCurBucket = getValidLayer(element.layer) * renderTheme.getLevels(); - renderWay(renderTheme.matchElement(element.type, tags, mTile.zoomLevel)); - } - clearState(); - } + if (element.type == GeometryType.POINT) { + renderNode(renderTheme.matchElement(element.type, tags, mTile.zoomLevel)); + } else { + mCurBucket = getValidLayer(element.layer) * renderTheme.getLevels(); + renderWay(renderTheme.matchElement(element.type, tags, mTile.zoomLevel)); + } + clearState(); + } - protected void renderWay(RenderStyle[] style) { - if (style == null) - return; + protected void renderWay(RenderStyle[] style) { + if (style == null) + return; - for (int i = 0, n = style.length; i < n; i++) - style[i].renderWay(this); - } + for (int i = 0, n = style.length; i < n; i++) + style[i].renderWay(this); + } - protected void renderNode(RenderStyle[] style) { - if (style == null) - return; + protected void renderNode(RenderStyle[] style) { + if (style == null) + return; - for (int i = 0, n = style.length; i < n; i++) - style[i].renderNode(this); - } + for (int i = 0, n = style.length; i < n; i++) + style[i].renderNode(this); + } - protected void clearState() { - mCurLineBucket = null; - mElement = null; - } + protected void clearState() { + mCurLineBucket = null; + mElement = null; + } - /*** RenderThemeCallback ***/ - @Override - public void renderWay(LineStyle line, int level) { - int nLevel = mCurBucket + level; + /*** + * RenderThemeCallback + ***/ + @Override + public void renderWay(LineStyle line, int level) { + int nLevel = mCurBucket + level; - if (line.stipple == 0) { - if (line.outline && mCurLineBucket == null) { - log.debug("missing line for outline! " + mElement.tags - + " lvl:" + level + " layer:" + mElement.layer); - return; - } + if (line.stipple == 0) { + if (line.outline && mCurLineBucket == null) { + log.debug("missing line for outline! " + mElement.tags + + " lvl:" + level + " layer:" + mElement.layer); + return; + } - LineBucket lb = mBuckets.getLineBucket(nLevel); + LineBucket lb = mBuckets.getLineBucket(nLevel); - if (lb.line == null) { - lb.line = line; - lb.scale = line.fixed ? 1 : mLineScale; - lb.setExtents(-4, Tile.SIZE + 4); - } + if (lb.line == null) { + lb.line = line; + lb.scale = line.fixed ? 1 : mLineScale; + lb.setExtents(-4, Tile.SIZE + 4); + } - if (line.outline) { - lb.addOutline(mCurLineBucket); - return; - } + if (line.outline) { + lb.addOutline(mCurLineBucket); + return; + } - lb.addLine(mElement); + lb.addLine(mElement); /* keep reference for outline layer(s) */ - mCurLineBucket = lb; + mCurLineBucket = lb; - } else { - LineTexBucket lb = mBuckets.getLineTexBucket(nLevel); + } else { + LineTexBucket lb = mBuckets.getLineTexBucket(nLevel); - if (lb.line == null) { - lb.line = line; + if (lb.line == null) { + lb.line = line; - float w = line.width; - if (!line.fixed) - w *= mLineScale; + float w = line.width; + if (!line.fixed) + w *= mLineScale; - lb.width = w; - } + lb.width = w; + } - lb.addLine(mElement); - } - } + lb.addLine(mElement); + } + } - /* slower to load (requires tesselation) and uses - * more memory but should be faster to render */ - public static boolean USE_MESH_POLY = false; + /* slower to load (requires tesselation) and uses + * more memory but should be faster to render */ + public static boolean USE_MESH_POLY = false; - @Override - public void renderArea(AreaStyle area, int level) { - /* dont add faded out polygon layers */ - if (mTile.zoomLevel < area.fadeScale) - return; + @Override + public void renderArea(AreaStyle area, int level) { + /* dont add faded out polygon layers */ + if (mTile.zoomLevel < area.fadeScale) + return; - int nLevel = mCurBucket + level; + int nLevel = mCurBucket + level; - if (USE_MESH_POLY || area.mesh) { - MeshBucket mb = mBuckets.getMeshBucket(nLevel); - mb.area = area; - mb.addMesh(mElement); - } else { - PolygonBucket pb = mBuckets.getPolygonBucket(nLevel); - pb.area = area; - pb.addPolygon(mElement.points, mElement.index); - } - } + if (USE_MESH_POLY || area.mesh) { + MeshBucket mb = mBuckets.getMeshBucket(nLevel); + mb.area = area; + mb.addMesh(mElement); + } else { + PolygonBucket pb = mBuckets.getPolygonBucket(nLevel); + pb.area = area; + pb.addPolygon(mElement.points, mElement.index); + } + } - @Override - public void renderSymbol(SymbolStyle symbol) { - mTileLayer.callThemeHooks(mTile, mBuckets, mElement, symbol, 0); - } + @Override + public void renderSymbol(SymbolStyle symbol) { + mTileLayer.callThemeHooks(mTile, mBuckets, mElement, symbol, 0); + } - @Override - public void renderExtrusion(ExtrusionStyle extrusion, int level) { - mTileLayer.callThemeHooks(mTile, mBuckets, mElement, extrusion, level); - } + @Override + public void renderExtrusion(ExtrusionStyle extrusion, int level) { + mTileLayer.callThemeHooks(mTile, mBuckets, mElement, extrusion, level); + } - @Override - public void renderCircle(CircleStyle circle, int level) { - } + @Override + public void renderCircle(CircleStyle circle, int level) { + } - @Override - public void renderText(TextStyle text) { - mTileLayer.callThemeHooks(mTile, mBuckets, mElement, text, 0); - } + @Override + public void renderText(TextStyle text) { + mTileLayer.callThemeHooks(mTile, mBuckets, mElement, text, 0); + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/Debug.java b/vtm/src/org/oscim/layers/tile/vector/labeling/Debug.java index 1c86eb5c..45b4acca 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/Debug.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/Debug.java @@ -26,72 +26,71 @@ import org.oscim.theme.styles.LineStyle; class Debug { - private final static float[] mDebugPoints = new float[8]; - // TODO Auto-generated method stub - static RenderBuckets dbg; + private final static float[] mDebugPoints = new float[8]; + // TODO Auto-generated method stub + static RenderBuckets dbg; - static void addDebugBox(Label l, TextItem ti, int overlaps, boolean prev, - float scale) { + static void addDebugBox(Label l, TextItem ti, int overlaps, boolean prev, + float scale) { - LineBucket ll; - if (prev) { - if (overlaps == 1) - ll = dbg.getLineBucket(4); - else - ll = dbg.getLineBucket(5); + LineBucket ll; + if (prev) { + if (overlaps == 1) + ll = dbg.getLineBucket(4); + else + ll = dbg.getLineBucket(5); - } else { - if (ti.width > ti.length * scale) { - ll = dbg.getLineBucket(1); - overlaps = 3; - } - else if (overlaps == 1) - ll = dbg.getLineBucket(0); - else if (overlaps == 2) - ll = dbg.getLineBucket(3); - else - ll = dbg.getLineBucket(2); - } - float[] points = mDebugPoints; - float width = (ti.x2 - ti.x1) / 2f; - float height = (ti.y2 - ti.y1) / 2f; - points[0] = (l.x - width * scale); - points[1] = (l.y - height * scale); - points[2] = (l.x + width * scale); - points[3] = (l.y + height * scale); - ll.addLine(points, 4, false); + } else { + if (ti.width > ti.length * scale) { + ll = dbg.getLineBucket(1); + overlaps = 3; + } else if (overlaps == 1) + ll = dbg.getLineBucket(0); + else if (overlaps == 2) + ll = dbg.getLineBucket(3); + else + ll = dbg.getLineBucket(2); + } + float[] points = mDebugPoints; + float width = (ti.x2 - ti.x1) / 2f; + float height = (ti.y2 - ti.y1) / 2f; + points[0] = (l.x - width * scale); + points[1] = (l.y - height * scale); + points[2] = (l.x + width * scale); + points[3] = (l.y + height * scale); + ll.addLine(points, 4, false); - System.arraycopy(l.bbox.vec, 2, points, 0, 8); - if (l.bbox != null && overlaps != 3) { - ll.addLine(points, 8, true); - } - } + System.arraycopy(l.bbox.vec, 2, points, 0, 8); + if (l.bbox != null && overlaps != 3) { + ll.addLine(points, 8, true); + } + } - static void addDebugLayers(RenderBuckets dbg) { - int alpha = 0xaaffffff; + static void addDebugLayers(RenderBuckets dbg) { + int alpha = 0xaaffffff; - dbg.clear(); - dbg.addLineBucket(0, new LineStyle((Color.BLUE & alpha), 2)); - dbg.addLineBucket(1, new LineStyle((Color.RED & alpha), 2)); - dbg.addLineBucket(3, new LineStyle((Color.YELLOW & alpha), 2)); - dbg.addLineBucket(2, new LineStyle((Color.GREEN & alpha), 2)); - dbg.addLineBucket(4, new LineStyle((Color.CYAN & alpha), 2)); - dbg.addLineBucket(5, new LineStyle((Color.MAGENTA & alpha), 2)); - } + dbg.clear(); + dbg.addLineBucket(0, new LineStyle((Color.BLUE & alpha), 2)); + dbg.addLineBucket(1, new LineStyle((Color.RED & alpha), 2)); + dbg.addLineBucket(3, new LineStyle((Color.YELLOW & alpha), 2)); + dbg.addLineBucket(2, new LineStyle((Color.GREEN & alpha), 2)); + dbg.addLineBucket(4, new LineStyle((Color.CYAN & alpha), 2)); + dbg.addLineBucket(5, new LineStyle((Color.MAGENTA & alpha), 2)); + } - public static void draw(MapPosition pos, GLViewport m, RenderBuckets layers) { - // if (layers.baseLayers != null) { - // //setMatrix(pos, m, true); - // - // for (RenderElement l = layers.baseLayers; l != null;) { - // if (l.type == RenderElement.POLYGON) { - // l = PolygonLayer.Renderer.draw(pos, l, m, true, 1, false); - // } else { - // //float div = (float) (mMapPosition.scale / (1 << pos.zoomLevel)); - // l = LineLayer.Renderer.draw(layers, l, pos, m, div); - // } - // } - // } - } + public static void draw(MapPosition pos, GLViewport m, RenderBuckets layers) { + // if (layers.baseLayers != null) { + // //setMatrix(pos, m, true); + // + // for (RenderElement l = layers.baseLayers; l != null;) { + // if (l.type == RenderElement.POLYGON) { + // l = PolygonLayer.Renderer.draw(pos, l, m, true, 1, false); + // } else { + // //float div = (float) (mMapPosition.scale / (1 << pos.zoomLevel)); + // l = LineLayer.Renderer.draw(layers, l, pos, m, div); + // } + // } + // } + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/Label.java b/vtm/src/org/oscim/layers/tile/vector/labeling/Label.java index 00efeda1..3e624a94 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/Label.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/Label.java @@ -20,82 +20,82 @@ import org.oscim.renderer.bucket.TextItem; import org.oscim.utils.geom.OBB2D; final class Label extends TextItem { - TextItem item; + TextItem item; - //Link blocking; - //Link blockedBy; - // shared list of all label for a tile - //Link siblings; + //Link blocking; + //Link blockedBy; + // shared list of all label for a tile + //Link siblings; - int tileX; - int tileY; - int tileZ; + int tileX; + int tileY; + int tileZ; - public int active; - public OBB2D bbox; + public int active; + public OBB2D bbox; - public Label clone(TextItem ti) { - this.string = ti.string; - this.text = ti.text; - this.width = ti.width; - this.length = ti.length; - return this; - } + public Label clone(TextItem ti) { + this.string = ti.string; + this.text = ti.text; + this.width = ti.width; + this.length = ti.length; + return this; + } - static int comparePriority(Label l1, Label l2) { + static int comparePriority(Label l1, Label l2) { - return 0; - } + return 0; + } - public static boolean shareText(Label l, Label ll) { - if (l.text != ll.text) - return false; + public static boolean shareText(Label l, Label ll) { + if (l.text != ll.text) + return false; - if (l.string == ll.string) - return true; + if (l.string == ll.string) + return true; - if (l.string.equals(ll.string)) { - // make strings unique, should be done only once.. - l.string = ll.string; - return true; - } + if (l.string.equals(ll.string)) { + // make strings unique, should be done only once.. + l.string = ll.string; + return true; + } - return false; - } + return false; + } - public static boolean bboxOverlaps(TextItem it1, TextItem it2, float add) { - if (it1.y1 < it1.y2) { - if (it2.y1 < it2.y2) - return (it1.x1 - add < it2.x2) - && (it2.x1 < it1.x2 + add) - && (it1.y1 - add < it2.y2) - && (it2.y1 < it1.y2 + add); + public static boolean bboxOverlaps(TextItem it1, TextItem it2, float add) { + if (it1.y1 < it1.y2) { + if (it2.y1 < it2.y2) + return (it1.x1 - add < it2.x2) + && (it2.x1 < it1.x2 + add) + && (it1.y1 - add < it2.y2) + && (it2.y1 < it1.y2 + add); - // flip it2 - return (it1.x1 - add < it2.x2) - && (it2.x1 < it1.x2 + add) - && (it1.y1 - add < it2.y1) - && (it2.y2 < it1.y2 + add); - } + // flip it2 + return (it1.x1 - add < it2.x2) + && (it2.x1 < it1.x2 + add) + && (it1.y1 - add < it2.y1) + && (it2.y2 < it1.y2 + add); + } - // flip it1 - if (it2.y1 < it2.y2) - return (it1.x1 - add < it2.x2) - && (it2.x1 < it1.x2 + add) - && (it1.y2 - add < it2.y2) - && (it2.y1 < it1.y1 + add); + // flip it1 + if (it2.y1 < it2.y2) + return (it1.x1 - add < it2.x2) + && (it2.x1 < it1.x2 + add) + && (it1.y2 - add < it2.y2) + && (it2.y1 < it1.y1 + add); - // flip both - return (it1.x1 - add < it2.x2) - && (it2.x1 < it1.x2 + add) - && (it1.y2 - add < it2.y1) - && (it2.y2 < it1.y1 + add); - } + // flip both + return (it1.x1 - add < it2.x2) + && (it2.x1 < it1.x2 + add) + && (it1.y2 - add < it2.y1) + && (it2.y2 < it1.y1 + add); + } - public void setAxisAlignedBBox() { - this.x1 = (int) (x - width / 2); - this.y1 = (int) (y - text.fontHeight / 2); - this.x2 = (int) (x + width / 2); - this.y2 = (int) (y + text.fontHeight / 2); - } + public void setAxisAlignedBBox() { + this.x1 = (int) (x - width / 2); + this.y1 = (int) (y - text.fontHeight / 2); + this.x2 = (int) (x + width / 2); + this.y2 = (int) (y + text.fontHeight / 2); + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelLayer.java b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelLayer.java index e5affebc..e877efc2 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelLayer.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelLayer.java @@ -29,106 +29,106 @@ import org.slf4j.LoggerFactory; public class LabelLayer extends Layer implements Map.UpdateListener, TileManager.Listener { - static final Logger log = LoggerFactory.getLogger(LabelLayer.class); + static final Logger log = LoggerFactory.getLogger(LabelLayer.class); - public final static String LABEL_DATA = LabelLayer.class.getName(); + public final static String LABEL_DATA = LabelLayer.class.getName(); - private final static long MAX_RELABEL_DELAY = 100; + private final static long MAX_RELABEL_DELAY = 100; - private final LabelPlacement mLabelPlacer; - private final Worker mWorker; + private final LabelPlacement mLabelPlacer; + private final Worker mWorker; - public LabelLayer(Map map, VectorTileLayer l) { - super(map); - l.getManager().events.bind(this); - l.addHook(new LabelTileLoaderHook()); + public LabelLayer(Map map, VectorTileLayer l) { + super(map); + l.getManager().events.bind(this); + l.addHook(new LabelTileLoaderHook()); - mLabelPlacer = new LabelPlacement(map, l.tileRenderer()); - mWorker = new Worker(map); - mRenderer = new TextRenderer(mWorker); - } + mLabelPlacer = new LabelPlacement(map, l.tileRenderer()); + mWorker = new Worker(map); + mRenderer = new TextRenderer(mWorker); + } - class Worker extends SimpleWorker { + class Worker extends SimpleWorker { - public Worker(Map map) { - super(map, 50, new LabelTask(), new LabelTask()); - } + public Worker(Map map) { + super(map, 50, new LabelTask(), new LabelTask()); + } - @Override - public boolean doWork(LabelTask t) { + @Override + public boolean doWork(LabelTask t) { - if (mLabelPlacer.updateLabels(t)) { - mMap.render(); - return true; - } + if (mLabelPlacer.updateLabels(t)) { + mMap.render(); + return true; + } - return false; - } + return false; + } - @Override - public void cleanup(LabelTask t) { - } + @Override + public void cleanup(LabelTask t) { + } - @Override - public void finish() { - mLabelPlacer.cleanup(); - } + @Override + public void finish() { + mLabelPlacer.cleanup(); + } - public synchronized boolean isRunning() { - return mRunning; - } - } + public synchronized boolean isRunning() { + return mRunning; + } + } - public void clearLabels() { - mWorker.cancel(true); - } + public void clearLabels() { + mWorker.cancel(true); + } - public void update() { - mWorker.submit(MAX_RELABEL_DELAY); - } + public void update() { + mWorker.submit(MAX_RELABEL_DELAY); + } - @Override - public void onDetach() { - mWorker.cancel(true); - super.onDetach(); - } + @Override + public void onDetach() { + mWorker.cancel(true); + super.onDetach(); + } - @Override - public void onMapEvent(Event event, MapPosition mapPosition) { + @Override + public void onMapEvent(Event event, MapPosition mapPosition) { - if (event == Map.CLEAR_EVENT) - mWorker.cancel(true); + if (event == Map.CLEAR_EVENT) + mWorker.cancel(true); - if (event == Map.POSITION_EVENT) - mWorker.submit(MAX_RELABEL_DELAY); - } + if (event == Map.POSITION_EVENT) + mWorker.submit(MAX_RELABEL_DELAY); + } - // @Override - // public void onMotionEvent(MotionEvent e) { - // // int action = e.getAction() & MotionEvent.ACTION_MASK; - // // if (action == MotionEvent.ACTION_POINTER_DOWN) { - // // multi++; - // // mTextRenderer.hold(true); - // // } else if (action == MotionEvent.ACTION_POINTER_UP) { - // // multi--; - // // if (multi == 0) - // // mTextRenderer.hold(false); - // // } else if (action == MotionEvent.ACTION_CANCEL) { - // // multi = 0; - // // log.debug("cancel " + multi); - // // mTextRenderer.hold(false); - // // } - // } + // @Override + // public void onMotionEvent(MotionEvent e) { + // // int action = e.getAction() & MotionEvent.ACTION_MASK; + // // if (action == MotionEvent.ACTION_POINTER_DOWN) { + // // multi++; + // // mTextRenderer.hold(true); + // // } else if (action == MotionEvent.ACTION_POINTER_UP) { + // // multi--; + // // if (multi == 0) + // // mTextRenderer.hold(false); + // // } else if (action == MotionEvent.ACTION_CANCEL) { + // // multi = 0; + // // log.debug("cancel " + multi); + // // mTextRenderer.hold(false); + // // } + // } - @Override - public void onTileManagerEvent(Event e, MapTile tile) { - if (e == TileManager.TILE_LOADED) { - if (tile.isVisible) - mWorker.submit(MAX_RELABEL_DELAY / 4); - //log.debug("tile loaded: {}", tile); - } else if (e == TileManager.TILE_REMOVED) { - //log.debug("tile removed: {}", tile); - } - } + @Override + public void onTileManagerEvent(Event e, MapTile tile) { + if (e == TileManager.TILE_LOADED) { + if (tile.isVisible) + mWorker.submit(MAX_RELABEL_DELAY / 4); + //log.debug("tile loaded: {}", tile); + } else if (e == TileManager.TILE_REMOVED) { + //log.debug("tile removed: {}", tile); + } + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPlacement.java b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPlacement.java index 33ae789c..1654dd56 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPlacement.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPlacement.java @@ -1,8 +1,5 @@ package org.oscim.layers.tile.vector.labeling; -import static org.oscim.layers.tile.MapTile.State.NEW_DATA; -import static org.oscim.layers.tile.MapTile.State.READY; - import org.oscim.core.MapPosition; import org.oscim.core.Tile; import org.oscim.layers.tile.MapTile; @@ -18,502 +15,514 @@ import org.oscim.utils.geom.OBB2D; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.layers.tile.MapTile.State.NEW_DATA; +import static org.oscim.layers.tile.MapTile.State.READY; + public class LabelPlacement { - static final boolean dbg = false; - static final Logger log = LoggerFactory.getLogger(LabelPlacement.class); + static final boolean dbg = false; + static final Logger log = LoggerFactory.getLogger(LabelPlacement.class); - public final static LabelTileData getLabels(MapTile tile) { - return (LabelTileData) tile.getData(LabelLayer.LABEL_DATA); - } + public final static LabelTileData getLabels(MapTile tile) { + return (LabelTileData) tile.getData(LabelLayer.LABEL_DATA); + } - private final static float MIN_CAPTION_DIST = 5; - private final static float MIN_WAY_DIST = 3; + private final static float MIN_CAPTION_DIST = 5; + private final static float MIN_WAY_DIST = 3; - /** thread local pool of for unused label items */ - private final LabelPool mPool = new LabelPool(); + /** + * thread local pool of for unused label items + */ + private final LabelPool mPool = new LabelPool(); - private final TileSet mTileSet = new TileSet(); - private final TileRenderer mTileRenderer; - private final Map mMap; + private final TileSet mTileSet = new TileSet(); + private final TileRenderer mTileRenderer; + private final Map mMap; - /** list of current labels */ - private Label mLabels; + /** + * list of current labels + */ + private Label mLabels; - private float mSquareRadius; + private float mSquareRadius; - /** - * incremented each update, to prioritize labels - * that became visible ealier. - */ - private int mRelabelCnt; + /** + * incremented each update, to prioritize labels + * that became visible ealier. + */ + private int mRelabelCnt; - public LabelPlacement(Map map, TileRenderer tileRenderer) { - mMap = map; - mTileRenderer = tileRenderer; - } + public LabelPlacement(Map map, TileRenderer tileRenderer) { + mMap = map; + mTileRenderer = tileRenderer; + } - /** remove Label l from mLabels and return l.next */ - private Label removeLabel(Label l) { - Label ret = (Label) l.next; - mLabels = (Label) mPool.release(mLabels, l); - return ret; - } + /** + * remove Label l from mLabels and return l.next + */ + private Label removeLabel(Label l) { + Label ret = (Label) l.next; + mLabels = (Label) mPool.release(mLabels, l); + return ret; + } - public void addLabel(Label l) { - l.next = mLabels; - mLabels = l; - } + public void addLabel(Label l) { + l.next = mLabels; + mLabels = l; + } - private byte checkOverlap(Label l) { + private byte checkOverlap(Label l) { - for (Label o = mLabels; o != null;) { - //check bounding box - if (!Label.bboxOverlaps(l, o, 100)) { - o = (Label) o.next; - continue; - } + for (Label o = mLabels; o != null; ) { + //check bounding box + if (!Label.bboxOverlaps(l, o, 100)) { + o = (Label) o.next; + continue; + } - if (Label.shareText(l, o)) { - // keep the label that was active earlier - if (o.active <= l.active) - return 1; + if (Label.shareText(l, o)) { + // keep the label that was active earlier + if (o.active <= l.active) + return 1; - // keep the label with longer segment - if (o.length < l.length) { - o = removeLabel(o); - continue; - } - // keep other - return 2; - } - if (l.bbox.overlaps(o.bbox)) { - if (o.active <= l.active) - return 1; + // keep the label with longer segment + if (o.length < l.length) { + o = removeLabel(o); + continue; + } + // keep other + return 2; + } + if (l.bbox.overlaps(o.bbox)) { + if (o.active <= l.active) + return 1; - if (!o.text.caption - && (o.text.priority > l.text.priority - || o.length < l.length)) { + if (!o.text.caption + && (o.text.priority > l.text.priority + || o.length < l.length)) { - o = removeLabel(o); - continue; - } - // keep other - return 1; - } - o = (Label) o.next; - } - return 0; - } + o = removeLabel(o); + continue; + } + // keep other + return 1; + } + o = (Label) o.next; + } + return 0; + } - private boolean isVisible(float x, float y) { - // rough filter - float dist = x * x + y * y; - if (dist > mSquareRadius) - return false; + private boolean isVisible(float x, float y) { + // rough filter + float dist = x * x + y * y; + if (dist > mSquareRadius) + return false; - return true; - } + return true; + } - private boolean wayIsVisible(Label ti) { - // rough filter - float dist = ti.x * ti.x + ti.y * ti.y; - if (dist < mSquareRadius) - return true; + private boolean wayIsVisible(Label ti) { + // rough filter + float dist = ti.x * ti.x + ti.y * ti.y; + if (dist < mSquareRadius) + return true; - dist = ti.x1 * ti.x1 + ti.y1 * ti.y1; - if (dist < mSquareRadius) - return true; + dist = ti.x1 * ti.x1 + ti.y1 * ti.y1; + if (dist < mSquareRadius) + return true; - dist = ti.x2 * ti.x2 + ti.y2 * ti.y2; - if (dist < mSquareRadius) - return true; + dist = ti.x2 * ti.x2 + ti.y2 * ti.y2; + if (dist < mSquareRadius) + return true; - return false; - } + return false; + } - private Label getLabel() { - Label l = (Label) mPool.get(); - l.active = Integer.MAX_VALUE; + private Label getLabel() { + Label l = (Label) mPool.get(); + l.active = Integer.MAX_VALUE; - return l; - } + return l; + } - private static float flipLongitude(float dx, int max) { - // flip around date-line - if (dx > max) - dx = dx - max * 2; - else if (dx < -max) - dx = dx + max * 2; + private static float flipLongitude(float dx, int max) { + // flip around date-line + if (dx > max) + dx = dx - max * 2; + else if (dx < -max) + dx = dx + max * 2; - return dx; - } + return dx; + } - private void placeLabelFrom(Label l, TextItem ti) { - // set line endpoints relative to view to be able to - // check intersections with label from other tiles - float w = (ti.x2 - ti.x1) / 2f; - float h = (ti.y2 - ti.y1) / 2f; + private void placeLabelFrom(Label l, TextItem ti) { + // set line endpoints relative to view to be able to + // check intersections with label from other tiles + float w = (ti.x2 - ti.x1) / 2f; + float h = (ti.y2 - ti.y1) / 2f; - l.x1 = l.x - w; - l.y1 = l.y - h; - l.x2 = l.x + w; - l.y2 = l.y + h; - } + l.x1 = l.x - w; + l.y1 = l.y - h; + l.x2 = l.x + w; + l.y2 = l.y + h; + } - private Label addWayLabels(MapTile t, Label l, float dx, float dy, - double scale) { + private Label addWayLabels(MapTile t, Label l, float dx, float dy, + double scale) { - LabelTileData ld = getLabels(t); - if (ld == null) - return l; + LabelTileData ld = getLabels(t); + if (ld == null) + return l; - for (TextItem ti : ld.labels) { - if (ti.text.caption) - continue; + for (TextItem ti : ld.labels) { + if (ti.text.caption) + continue; /* acquire a TextItem to add to TextLayer */ - if (l == null) - l = getLabel(); + if (l == null) + l = getLabel(); /* check if path at current scale is long enough */ - if (!dbg && ti.width > ti.length * scale) - continue; + if (!dbg && ti.width > ti.length * scale) + continue; - l.clone(ti); - l.x = (float) ((dx + ti.x) * scale); - l.y = (float) ((dy + ti.y) * scale); - placeLabelFrom(l, ti); + l.clone(ti); + l.x = (float) ((dx + ti.x) * scale); + l.y = (float) ((dy + ti.y) * scale); + placeLabelFrom(l, ti); - if (!wayIsVisible(l)) - continue; + if (!wayIsVisible(l)) + continue; - byte overlaps = -1; + byte overlaps = -1; - if (l.bbox == null) - l.bbox = new OBB2D(l.x, l.y, l.x1, l.y1, - l.width + MIN_WAY_DIST, - l.text.fontHeight + MIN_WAY_DIST); - else - l.bbox.set(l.x, l.y, l.x1, l.y1, - l.width + MIN_WAY_DIST, - l.text.fontHeight + MIN_WAY_DIST); + if (l.bbox == null) + l.bbox = new OBB2D(l.x, l.y, l.x1, l.y1, + l.width + MIN_WAY_DIST, + l.text.fontHeight + MIN_WAY_DIST); + else + l.bbox.set(l.x, l.y, l.x1, l.y1, + l.width + MIN_WAY_DIST, + l.text.fontHeight + MIN_WAY_DIST); - if (dbg || ti.width < ti.length * scale) - overlaps = checkOverlap(l); + if (dbg || ti.width < ti.length * scale) + overlaps = checkOverlap(l); - if (dbg) - Debug.addDebugBox(l, ti, overlaps, false, (float) scale); + if (dbg) + Debug.addDebugBox(l, ti, overlaps, false, (float) scale); - if (overlaps == 0) { - addLabel(l); - l.item = TextItem.copy(ti); - l.tileX = t.tileX; - l.tileY = t.tileY; - l.tileZ = t.zoomLevel; - l.active = mRelabelCnt; - l = null; - } - } - return l; - } + if (overlaps == 0) { + addLabel(l); + l.item = TextItem.copy(ti); + l.tileX = t.tileX; + l.tileY = t.tileY; + l.tileZ = t.zoomLevel; + l.active = mRelabelCnt; + l = null; + } + } + return l; + } - private Label addNodeLabels(MapTile t, Label l, float dx, float dy, - double scale, float cos, float sin) { + private Label addNodeLabels(MapTile t, Label l, float dx, float dy, + double scale, float cos, float sin) { - LabelTileData ld = getLabels(t); - if (ld == null) - return l; + LabelTileData ld = getLabels(t); + if (ld == null) + return l; - O: for (TextItem ti : ld.labels) { - if (!ti.text.caption) - continue; + O: + for (TextItem ti : ld.labels) { + if (!ti.text.caption) + continue; - // acquire a TextItem to add to TextLayer - if (l == null) - l = getLabel(); + // acquire a TextItem to add to TextLayer + if (l == null) + l = getLabel(); - l.clone(ti); - l.x = (float) ((dx + ti.x) * scale); - l.y = (float) ((dy + ti.y) * scale); - if (!isVisible(l.x, l.y)) - continue; + l.clone(ti); + l.x = (float) ((dx + ti.x) * scale); + l.y = (float) ((dy + ti.y) * scale); + if (!isVisible(l.x, l.y)) + continue; - if (l.bbox == null) - l.bbox = new OBB2D(); + if (l.bbox == null) + l.bbox = new OBB2D(); - l.bbox.setNormalized(l.x, l.y, cos, -sin, - l.width + MIN_CAPTION_DIST, - l.text.fontHeight + MIN_CAPTION_DIST, - l.text.dy); + l.bbox.setNormalized(l.x, l.y, cos, -sin, + l.width + MIN_CAPTION_DIST, + l.text.fontHeight + MIN_CAPTION_DIST, + l.text.dy); - for (Label o = mLabels; o != null;) { - if (l.bbox.overlaps(o.bbox)) { - if (l.text.priority < o.text.priority) { - o = removeLabel(o); - continue; - } - continue O; - } - o = (Label) o.next; - } + for (Label o = mLabels; o != null; ) { + if (l.bbox.overlaps(o.bbox)) { + if (l.text.priority < o.text.priority) { + o = removeLabel(o); + continue; + } + continue O; + } + o = (Label) o.next; + } - addLabel(l); - l.item = TextItem.copy(ti); - l.tileX = t.tileX; - l.tileY = t.tileY; - l.tileZ = t.zoomLevel; - l.active = mRelabelCnt; - l = null; - } - return l; - } + addLabel(l); + l.item = TextItem.copy(ti); + l.tileX = t.tileX; + l.tileY = t.tileY; + l.tileZ = t.zoomLevel; + l.active = mRelabelCnt; + l = null; + } + return l; + } - boolean updateLabels(LabelTask work) { + boolean updateLabels(LabelTask work) { /* get current tiles */ - boolean changedTiles = mTileRenderer.getVisibleTiles(mTileSet); + boolean changedTiles = mTileRenderer.getVisibleTiles(mTileSet); - if (mTileSet.cnt == 0) { - return false; - } + if (mTileSet.cnt == 0) { + return false; + } - MapPosition pos = work.pos; - boolean changedPos = mMap.viewport().getMapPosition(pos); + MapPosition pos = work.pos; + boolean changedPos = mMap.viewport().getMapPosition(pos); /* do not loop! */ - if (!changedTiles && !changedPos) - return false; + if (!changedTiles && !changedPos) + return false; - mRelabelCnt++; + mRelabelCnt++; - MapTile[] tiles = mTileSet.tiles; - int zoom = tiles[0].zoomLevel; + MapTile[] tiles = mTileSet.tiles; + int zoom = tiles[0].zoomLevel; /* estimation for visible area to be labeled */ - int mw = (mMap.getWidth() + Tile.SIZE) / 2; - int mh = (mMap.getHeight() + Tile.SIZE) / 2; - mSquareRadius = mw * mw + mh * mh; + int mw = (mMap.getWidth() + Tile.SIZE) / 2; + int mh = (mMap.getHeight() + Tile.SIZE) / 2; + mSquareRadius = mw * mw + mh * mh; /* scale of tiles zoom-level relative to current position */ - double scale = pos.scale / (1 << zoom); + double scale = pos.scale / (1 << zoom); - double angle = Math.toRadians(pos.bearing); - float cos = (float) Math.cos(angle); - float sin = (float) Math.sin(angle); + double angle = Math.toRadians(pos.bearing); + float cos = (float) Math.cos(angle); + float sin = (float) Math.sin(angle); - int maxx = Tile.SIZE << (zoom - 1); + int maxx = Tile.SIZE << (zoom - 1); - // FIXME ??? - SymbolBucket sl = work.symbolLayer; - sl.clearItems(); + // FIXME ??? + SymbolBucket sl = work.symbolLayer; + sl.clearItems(); - double tileX = (pos.x * (Tile.SIZE << zoom)); - double tileY = (pos.y * (Tile.SIZE << zoom)); + double tileX = (pos.x * (Tile.SIZE << zoom)); + double tileY = (pos.y * (Tile.SIZE << zoom)); /* put current label to previous label */ - Label prevLabels = mLabels; + Label prevLabels = mLabels; /* new labels */ - mLabels = null; - Label l = null; + mLabels = null; + Label l = null; /* add currently active labels first */ - for (l = prevLabels; l != null;) { + for (l = prevLabels; l != null; ) { - if (l.text.caption) { - // TODO!!! - l = mPool.releaseAndGetNext(l); - continue; - } + if (l.text.caption) { + // TODO!!! + l = mPool.releaseAndGetNext(l); + continue; + } - int diff = l.tileZ - zoom; - if (diff > 1 || diff < -1) { - l = mPool.releaseAndGetNext(l); - continue; - } + int diff = l.tileZ - zoom; + if (diff > 1 || diff < -1) { + l = mPool.releaseAndGetNext(l); + continue; + } - float div = FastMath.pow(diff); - float sscale = (float) (pos.scale / (1 << l.tileZ)); + float div = FastMath.pow(diff); + float sscale = (float) (pos.scale / (1 << l.tileZ)); - // plus 10 to rather keep label and avoid flickering - if (l.width > (l.length + 10) * sscale) { - l = mPool.releaseAndGetNext(l); - continue; - } + // plus 10 to rather keep label and avoid flickering + if (l.width > (l.length + 10) * sscale) { + l = mPool.releaseAndGetNext(l); + continue; + } - float dx = (float) (l.tileX * Tile.SIZE - tileX * div); - float dy = (float) (l.tileY * Tile.SIZE - tileY * div); + float dx = (float) (l.tileX * Tile.SIZE - tileX * div); + float dy = (float) (l.tileY * Tile.SIZE - tileY * div); - dx = flipLongitude(dx, maxx); - l.x = (float) ((dx + l.item.x) * sscale); - l.y = (float) ((dy + l.item.y) * sscale); - placeLabelFrom(l, l.item); + dx = flipLongitude(dx, maxx); + l.x = (float) ((dx + l.item.x) * sscale); + l.y = (float) ((dy + l.item.y) * sscale); + placeLabelFrom(l, l.item); - if (!wayIsVisible(l)) { - l = mPool.releaseAndGetNext(l); - continue; - } + if (!wayIsVisible(l)) { + l = mPool.releaseAndGetNext(l); + continue; + } - l.bbox.set(l.x, l.y, l.x1, l.y1, - l.width + MIN_WAY_DIST, - l.text.fontHeight + MIN_WAY_DIST); + l.bbox.set(l.x, l.y, l.x1, l.y1, + l.width + MIN_WAY_DIST, + l.text.fontHeight + MIN_WAY_DIST); - byte overlaps = checkOverlap(l); + byte overlaps = checkOverlap(l); - if (dbg) - Debug.addDebugBox(l, l.item, overlaps, true, sscale); + if (dbg) + Debug.addDebugBox(l, l.item, overlaps, true, sscale); - if (overlaps == 0) { - Label ll = l; - l = (Label) l.next; + if (overlaps == 0) { + Label ll = l; + l = (Label) l.next; - ll.next = null; - addLabel(ll); - continue; - } - l = mPool.releaseAndGetNext(l); - } + ll.next = null; + addLabel(ll); + continue; + } + l = mPool.releaseAndGetNext(l); + } /* add way labels */ - for (int i = 0, n = mTileSet.cnt; i < n; i++) { - MapTile t = tiles[i]; - if (!t.state(READY | NEW_DATA)) - continue; + for (int i = 0, n = mTileSet.cnt; i < n; i++) { + MapTile t = tiles[i]; + if (!t.state(READY | NEW_DATA)) + continue; - float dx = (float) (t.tileX * Tile.SIZE - tileX); - float dy = (float) (t.tileY * Tile.SIZE - tileY); - dx = flipLongitude(dx, maxx); + float dx = (float) (t.tileX * Tile.SIZE - tileX); + float dy = (float) (t.tileY * Tile.SIZE - tileY); + dx = flipLongitude(dx, maxx); - l = addWayLabels(t, l, dx, dy, scale); - } + l = addWayLabels(t, l, dx, dy, scale); + } /* add caption */ - for (int i = 0, n = mTileSet.cnt; i < n; i++) { - MapTile t = tiles[i]; - if (!t.state(READY | NEW_DATA)) - continue; + for (int i = 0, n = mTileSet.cnt; i < n; i++) { + MapTile t = tiles[i]; + if (!t.state(READY | NEW_DATA)) + continue; - float dx = (float) (t.tileX * Tile.SIZE - tileX); - float dy = (float) (t.tileY * Tile.SIZE - tileY); - dx = flipLongitude(dx, maxx); + float dx = (float) (t.tileX * Tile.SIZE - tileX); + float dy = (float) (t.tileY * Tile.SIZE - tileY); + dx = flipLongitude(dx, maxx); - l = addNodeLabels(t, l, dx, dy, scale, cos, sin); - } + l = addNodeLabels(t, l, dx, dy, scale, cos, sin); + } - for (Label ti = mLabels; ti != null; ti = (Label) ti.next) { - /* add caption symbols */ - if (ti.text.caption) { - if (ti.text.texture != null) { - SymbolItem s = SymbolItem.pool.get(); - s.texRegion = ti.text.texture; - s.x = ti.x; - s.y = ti.y; - s.billboard = true; - sl.addSymbol(s); - } - continue; - } + for (Label ti = mLabels; ti != null; ti = (Label) ti.next) { + /* add caption symbols */ + if (ti.text.caption) { + if (ti.text.texture != null) { + SymbolItem s = SymbolItem.pool.get(); + s.texRegion = ti.text.texture; + s.x = ti.x; + s.y = ti.y; + s.billboard = true; + sl.addSymbol(s); + } + continue; + } /* flip way label orientation */ - if (cos * (ti.x2 - ti.x1) - sin * (ti.y2 - ti.y1) < 0) { - float tmp = ti.x1; - ti.x1 = ti.x2; - ti.x2 = tmp; + if (cos * (ti.x2 - ti.x1) - sin * (ti.y2 - ti.y1) < 0) { + float tmp = ti.x1; + ti.x1 = ti.x2; + ti.x2 = tmp; - tmp = ti.y1; - ti.y1 = ti.y2; - ti.y2 = tmp; - } - } + tmp = ti.y1; + ti.y1 = ti.y2; + ti.y2 = tmp; + } + } /* add symbol items */ - for (int i = 0, n = mTileSet.cnt; i < n; i++) { - MapTile t = tiles[i]; - if (!t.state(READY | NEW_DATA)) - continue; + for (int i = 0, n = mTileSet.cnt; i < n; i++) { + MapTile t = tiles[i]; + if (!t.state(READY | NEW_DATA)) + continue; - float dx = (float) (t.tileX * Tile.SIZE - tileX); - float dy = (float) (t.tileY * Tile.SIZE - tileY); - dx = flipLongitude(dx, maxx); + float dx = (float) (t.tileX * Tile.SIZE - tileX); + float dy = (float) (t.tileY * Tile.SIZE - tileY); + dx = flipLongitude(dx, maxx); - LabelTileData ld = getLabels(t); - if (ld == null) - continue; + LabelTileData ld = getLabels(t); + if (ld == null) + continue; - for (SymbolItem ti : ld.symbols) { - if (ti.texRegion == null) - continue; + for (SymbolItem ti : ld.symbols) { + if (ti.texRegion == null) + continue; - int x = (int) ((dx + ti.x) * scale); - int y = (int) ((dy + ti.y) * scale); + int x = (int) ((dx + ti.x) * scale); + int y = (int) ((dy + ti.y) * scale); - if (!isVisible(x, y)) - continue; + if (!isVisible(x, y)) + continue; - SymbolItem s = SymbolItem.pool.get(); - s.texRegion = ti.texRegion; - s.x = x; - s.y = y; - s.billboard = true; - sl.addSymbol(s); - } - } + SymbolItem s = SymbolItem.pool.get(); + s.texRegion = ti.texRegion; + s.x = x; + s.y = y; + s.billboard = true; + sl.addSymbol(s); + } + } /* temporary used Label */ - l = (Label) mPool.release(l); + l = (Label) mPool.release(l); /* draw text to bitmaps and create vertices */ - work.textLayer.labels = groupLabels(mLabels); - work.textLayer.prepare(); - work.textLayer.labels = null; + work.textLayer.labels = groupLabels(mLabels); + work.textLayer.prepare(); + work.textLayer.labels = null; /* remove tile locks */ - mTileRenderer.releaseTiles(mTileSet); + mTileRenderer.releaseTiles(mTileSet); - return true; - } + return true; + } - public void cleanup() { - mLabels = (Label) mPool.releaseAll(mLabels); - mTileSet.releaseTiles(); - } + public void cleanup() { + mLabels = (Label) mPool.releaseAll(mLabels); + mTileSet.releaseTiles(); + } - /** group labels by string and type */ - protected Label groupLabels(Label labels) { - for (Label cur = labels; cur != null; cur = (Label) cur.next) { - /* keep pointer to previous for removal */ - Label p = cur; - TextStyle t = cur.text; - float w = cur.width; + /** + * group labels by string and type + */ + protected Label groupLabels(Label labels) { + for (Label cur = labels; cur != null; cur = (Label) cur.next) { + /* keep pointer to previous for removal */ + Label p = cur; + TextStyle t = cur.text; + float w = cur.width; /* iterate through following */ - for (Label l = (Label) cur.next; l != null; l = (Label) l.next) { + for (Label l = (Label) cur.next; l != null; l = (Label) l.next) { - if (w != l.width || t != l.text || !cur.string.equals(l.string)) { - p = l; - continue; - } else if (cur.next == l) { - l.string = cur.string; - p = l; - continue; - } - l.string = cur.string; + if (w != l.width || t != l.text || !cur.string.equals(l.string)) { + p = l; + continue; + } else if (cur.next == l) { + l.string = cur.string; + p = l; + continue; + } + l.string = cur.string; /* insert l after cur */ - Label tmp = (Label) cur.next; - cur.next = l; + Label tmp = (Label) cur.next; + cur.next = l; /* continue outer loop at l */ - cur = l; + cur = l; /* remove l from previous place */ - p.next = l.next; - l.next = tmp; + p.next = l.next; + l.next = tmp; /* continue from previous */ - l = p; - } - } - return labels; - } + l = p; + } + } + return labels; + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPool.java b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPool.java index 179e1afc..5d78c72c 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPool.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelPool.java @@ -4,22 +4,22 @@ import org.oscim.renderer.bucket.TextItem; import org.oscim.utils.pool.Pool; final class LabelPool extends Pool { - Label releaseAndGetNext(Label l) { - if (l.item != null) - l.item = TextItem.pool.release(l.item); + Label releaseAndGetNext(Label l) { + if (l.item != null) + l.item = TextItem.pool.release(l.item); - // drop references - l.item = null; - l.string = null; - Label ret = (Label) l.next; + // drop references + l.item = null; + l.string = null; + Label ret = (Label) l.next; - // ignore warning - super.release(l); - return ret; - } + // ignore warning + super.release(l); + return ret; + } - @Override - protected Label createItem() { - return new Label(); - } + @Override + protected Label createItem() { + return new Label(); + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTask.java b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTask.java index 3bc51be6..c368eaae 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTask.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTask.java @@ -7,20 +7,20 @@ import org.oscim.renderer.bucket.TextureBucket; final class LabelTask { - final TextureBucket layers; - final TextBucket textLayer; - final SymbolBucket symbolLayer; + final TextureBucket layers; + final TextBucket textLayer; + final SymbolBucket symbolLayer; - final MapPosition pos; + final MapPosition pos; - LabelTask() { - pos = new MapPosition(); + LabelTask() { + pos = new MapPosition(); - symbolLayer = new SymbolBucket(); - textLayer = new TextBucket(); + symbolLayer = new SymbolBucket(); + textLayer = new TextBucket(); - layers = symbolLayer; - symbolLayer.next = textLayer; - } + layers = symbolLayer; + symbolLayer.next = textLayer; + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileData.java b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileData.java index 37dcecf9..662525bc 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileData.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileData.java @@ -5,12 +5,12 @@ import org.oscim.renderer.bucket.SymbolItem; import org.oscim.renderer.bucket.TextItem; public class LabelTileData extends TileData { - public final List symbols = new List(); - public final List labels = new List(); + public final List symbols = new List(); + public final List labels = new List(); - @Override - protected void dispose() { - TextItem.pool.releaseAll(labels.clear()); - SymbolItem.pool.releaseAll(symbols.clear()); - } + @Override + protected void dispose() { + TextItem.pool.releaseAll(labels.clear()); + SymbolItem.pool.releaseAll(symbols.clear()); + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileLoaderHook.java b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileLoaderHook.java index 6686014c..297f4c17 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileLoaderHook.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/LabelTileLoaderHook.java @@ -1,10 +1,5 @@ package org.oscim.layers.tile.vector.labeling; -import static org.oscim.core.GeometryBuffer.GeometryType.LINE; -import static org.oscim.core.GeometryBuffer.GeometryType.POINT; -import static org.oscim.core.GeometryBuffer.GeometryType.POLY; -import static org.oscim.layers.tile.vector.labeling.LabelLayer.LABEL_DATA; - import org.oscim.core.MapElement; import org.oscim.core.PointF; import org.oscim.layers.tile.MapTile; @@ -16,95 +11,97 @@ import org.oscim.theme.styles.RenderStyle; import org.oscim.theme.styles.SymbolStyle; import org.oscim.theme.styles.TextStyle; +import static org.oscim.core.GeometryBuffer.GeometryType.LINE; +import static org.oscim.core.GeometryBuffer.GeometryType.POINT; +import static org.oscim.core.GeometryBuffer.GeometryType.POLY; +import static org.oscim.layers.tile.vector.labeling.LabelLayer.LABEL_DATA; + public class LabelTileLoaderHook implements TileLoaderThemeHook { - //public final static LabelTileData EMPTY = new LabelTileData(); + //public final static LabelTileData EMPTY = new LabelTileData(); - private LabelTileData get(MapTile tile) { - // FIXME could be 'this'.. - LabelTileData ld = (LabelTileData) tile.getData(LABEL_DATA); - if (ld == null) { - ld = new LabelTileData(); - tile.addData(LABEL_DATA, ld); - } - return ld; - } + private LabelTileData get(MapTile tile) { + // FIXME could be 'this'.. + LabelTileData ld = (LabelTileData) tile.getData(LABEL_DATA); + if (ld == null) { + ld = new LabelTileData(); + tile.addData(LABEL_DATA, ld); + } + return ld; + } - @Override - public boolean process(MapTile tile, RenderBuckets buckets, MapElement element, - RenderStyle style, int level) { + @Override + public boolean process(MapTile tile, RenderBuckets buckets, MapElement element, + RenderStyle style, int level) { - if (style instanceof TextStyle) { - LabelTileData ld = get(tile); + if (style instanceof TextStyle) { + LabelTileData ld = get(tile); - TextStyle text = (TextStyle) style; - if (element.type == LINE) { - String value = element.tags.getValue(text.textKey); - if (value == null || value.length() == 0) - return false; + TextStyle text = (TextStyle) style; + if (element.type == LINE) { + String value = element.tags.getValue(text.textKey); + if (value == null || value.length() == 0) + return false; - int offset = 0; - for (int i = 0, n = element.index.length; i < n; i++) { - int length = element.index[i]; - if (length < 4) - break; + int offset = 0; + for (int i = 0, n = element.index.length; i < n; i++) { + int length = element.index[i]; + if (length < 4) + break; - WayDecorator.renderText(null, element.points, value, text, - offset, length, ld); - offset += length; - } - } - else if (element.type == POLY) { - // TODO place somewhere on polygon - String value = element.tags.getValue(text.textKey); - if (value == null || value.length() == 0) - return false; + WayDecorator.renderText(null, element.points, value, text, + offset, length, ld); + offset += length; + } + } else if (element.type == POLY) { + // TODO place somewhere on polygon + String value = element.tags.getValue(text.textKey); + if (value == null || value.length() == 0) + return false; - float x = 0; - float y = 0; - int n = element.index[0]; + float x = 0; + float y = 0; + int n = element.index[0]; - for (int i = 0; i < n;) { - x += element.points[i++]; - y += element.points[i++]; - } - x /= (n / 2); - y /= (n / 2); + for (int i = 0; i < n; ) { + x += element.points[i++]; + y += element.points[i++]; + } + x /= (n / 2); + y /= (n / 2); - ld.labels.push(TextItem.pool.get().set(x, y, value, text)); - } - else if (element.type == POINT) { - String value = element.tags.getValue(text.textKey); - if (value == null || value.length() == 0) - return false; + ld.labels.push(TextItem.pool.get().set(x, y, value, text)); + } else if (element.type == POINT) { + String value = element.tags.getValue(text.textKey); + if (value == null || value.length() == 0) + return false; - for (int i = 0, n = element.getNumPoints(); i < n; i++) { - PointF p = element.getPoint(i); - ld.labels.push(TextItem.pool.get().set(p.x, p.y, value, text)); - } - } - } - else if ((element.type == POINT) && (style instanceof SymbolStyle)) { - SymbolStyle symbol = (SymbolStyle) style; + for (int i = 0, n = element.getNumPoints(); i < n; i++) { + PointF p = element.getPoint(i); + ld.labels.push(TextItem.pool.get().set(p.x, p.y, value, text)); + } + } + } else if ((element.type == POINT) && (style instanceof SymbolStyle)) { + SymbolStyle symbol = (SymbolStyle) style; - if (symbol.texture == null) - return false; + if (symbol.texture == null) + return false; - LabelTileData ld = get(tile); + LabelTileData ld = get(tile); - for (int i = 0, n = element.getNumPoints(); i < n; i++) { - PointF p = element.getPoint(i); + for (int i = 0, n = element.getNumPoints(); i < n; i++) { + PointF p = element.getPoint(i); - SymbolItem it = SymbolItem.pool.get(); - it.set(p.x, p.y, symbol.texture, true); - ld.symbols.push(it); - } - } - return false; - } + SymbolItem it = SymbolItem.pool.get(); + it.set(p.x, p.y, symbol.texture, true); + ld.symbols.push(it); + } + } + return false; + } - @Override - public void complete(MapTile tile, boolean success) { - } + @Override + public void complete(MapTile tile, boolean success) { + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/TextRenderer.java b/vtm/src/org/oscim/layers/tile/vector/labeling/TextRenderer.java index 825c28d3..e08c03fe 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/TextRenderer.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/TextRenderer.java @@ -40,51 +40,51 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class TextRenderer extends BucketRenderer { - static final Logger log = LoggerFactory.getLogger(TextRenderer.class); - static final boolean dbg = false; + static final Logger log = LoggerFactory.getLogger(TextRenderer.class); + static final boolean dbg = false; - private final Worker mWorker; + private final Worker mWorker; - public TextRenderer(Worker worker) { - mWorker = worker; - } + public TextRenderer(Worker worker) { + mWorker = worker; + } - long lastDraw = 0; + long lastDraw = 0; - @Override - public synchronized void update(GLViewport v) { + @Override + public synchronized void update(GLViewport v) { - LabelTask t; - synchronized (mWorker) { - t = mWorker.poll(); - if (t == null) { - if (!mWorker.isRunning()) { - mWorker.submit(50); - } - return; - } - buckets.clear(); - } + LabelTask t; + synchronized (mWorker) { + t = mWorker.poll(); + if (t == null) { + if (!mWorker.isRunning()) { + mWorker.submit(50); + } + return; + } + buckets.clear(); + } - // set new TextLayer to be uploaded and rendered - buckets.set(t.layers); - mMapPosition = t.pos; - compile(); - } + // set new TextLayer to be uploaded and rendered + buckets.set(t.layers); + mMapPosition = t.pos; + compile(); + } - @Override - public synchronized void render(GLViewport v) { - GLState.test(false, false); - //Debug.draw(pos, layers); + @Override + public synchronized void render(GLViewport v) { + GLState.test(false, false); + //Debug.draw(pos, layers); - buckets.vbo.bind(); + buckets.vbo.bind(); - float scale = (float) (v.pos.scale / mMapPosition.scale); + float scale = (float) (v.pos.scale / mMapPosition.scale); - setMatrix(v, false); + setMatrix(v, false); - for (RenderBucket l = buckets.get(); l != null;) - l = TextureBucket.Renderer.draw(l, v, scale); - } + for (RenderBucket l = buckets.get(); l != null; ) + l = TextureBucket.Renderer.draw(l, v, scale); + } } diff --git a/vtm/src/org/oscim/layers/tile/vector/labeling/WayDecorator.java b/vtm/src/org/oscim/layers/tile/vector/labeling/WayDecorator.java index 23268503..a20d4910 100644 --- a/vtm/src/org/oscim/layers/tile/vector/labeling/WayDecorator.java +++ b/vtm/src/org/oscim/layers/tile/vector/labeling/WayDecorator.java @@ -25,203 +25,203 @@ import org.oscim.utils.geom.LineClipper; public final class WayDecorator { - public static void renderText(LineClipper clipper, float[] coordinates, String string, - TextStyle text, int pos, int len, LabelTileData ld) { - //TextItem items = textItems; - TextItem t = null; + public static void renderText(LineClipper clipper, float[] coordinates, String string, + TextStyle text, int pos, int len, LabelTileData ld) { + //TextItem items = textItems; + TextItem t = null; - // calculate the way name length plus some margin of safety - float labelWidth = -1; - float minWidth = Tile.SIZE / 10; + // calculate the way name length plus some margin of safety + float labelWidth = -1; + float minWidth = Tile.SIZE / 10; - //final int min = 0; - //final int max = Tile.SIZE; + //final int min = 0; + //final int max = Tile.SIZE; - // find way segments long enough to draw the way name on them - for (int i = pos; i < pos + len - 2; i += 2) { - // get the first way point coordinates - float prevX = coordinates[i + 0]; - float prevY = coordinates[i + 1]; + // find way segments long enough to draw the way name on them + for (int i = pos; i < pos + len - 2; i += 2) { + // get the first way point coordinates + float prevX = coordinates[i + 0]; + float prevY = coordinates[i + 1]; - byte edge = 0; - //clipper.clipStart(prevX, prevY); + byte edge = 0; + //clipper.clipStart(prevX, prevY); - // get the current way point coordinates - float curX = coordinates[i + 2]; - float curY = coordinates[i + 3]; + // get the current way point coordinates + float curX = coordinates[i + 2]; + float curY = coordinates[i + 3]; - //int clip; - //if ((clip = clipper.clipNext(curX, curY)) != 0) { - // if (clip < 0) { - // prevX = clipper.out[0]; - // prevY = clipper.out[1]; - // curX = clipper.out[2]; - // curY = clipper.out[3]; - // - // if (prevX == min) - // edge |= 1 << 0; - // else if (prevX == max) - // edge |= 1 << 1; - // - // if (prevY == min) - // edge |= 1 << 2; - // else if (prevY == max) - // edge |= 1 << 3; - // - // if (curX == min) - // edge |= 1 << 4; - // else if (curX == max) - // edge |= 1 << 5; - // - // if (curY == min) - // edge |= 1 << 5; - // else if (curY == max) - // edge |= 1 << 6; - // } - //} + //int clip; + //if ((clip = clipper.clipNext(curX, curY)) != 0) { + // if (clip < 0) { + // prevX = clipper.out[0]; + // prevY = clipper.out[1]; + // curX = clipper.out[2]; + // curY = clipper.out[3]; + // + // if (prevX == min) + // edge |= 1 << 0; + // else if (prevX == max) + // edge |= 1 << 1; + // + // if (prevY == min) + // edge |= 1 << 2; + // else if (prevY == max) + // edge |= 1 << 3; + // + // if (curX == min) + // edge |= 1 << 4; + // else if (curX == max) + // edge |= 1 << 5; + // + // if (curY == min) + // edge |= 1 << 5; + // else if (curY == max) + // edge |= 1 << 6; + // } + //} - int last = i; + int last = i; - // calculate the length of the current segment (Euclidian distance) - float vx = prevX - curX; - float vy = prevY - curY; - if (vx == 0 && vy == 0) - continue; + // calculate the length of the current segment (Euclidian distance) + float vx = prevX - curX; + float vy = prevY - curY; + if (vx == 0 && vy == 0) + continue; - float a = (float) Math.sqrt(vx * vx + vy * vy); + float a = (float) Math.sqrt(vx * vx + vy * vy); - // only if not cur segment crosses edge - if (edge < (1 << 4)) { - vx /= a; - vy /= a; + // only if not cur segment crosses edge + if (edge < (1 << 4)) { + vx /= a; + vy /= a; - // add additional segments if possible - for (int j = i + 4; j < pos + len; j += 2) { - float nextX = coordinates[j + 0]; - float nextY = coordinates[j + 1]; + // add additional segments if possible + for (int j = i + 4; j < pos + len; j += 2) { + float nextX = coordinates[j + 0]; + float nextY = coordinates[j + 1]; - //if ((clip = clipper.clipNext(nextX, nextY)) != 0) { - // if (clip < 0) { - // curX = clipper.out[0]; - // curY = clipper.out[1]; - // // TODO break when cur has changed - // nextX = clipper.out[2]; - // nextY = clipper.out[3]; - // } - //} + //if ((clip = clipper.clipNext(nextX, nextY)) != 0) { + // if (clip < 0) { + // curX = clipper.out[0]; + // curY = clipper.out[1]; + // // TODO break when cur has changed + // nextX = clipper.out[2]; + // nextY = clipper.out[3]; + // } + //} - float wx = nextX - curX; - float wy = nextY - curY; - if (wx == 0 && wy == 0) - continue; + float wx = nextX - curX; + float wy = nextY - curY; + if (wx == 0 && wy == 0) + continue; - float area = GeometryUtils.area(prevX, prevY, curX, curY, nextX, nextY); + float area = GeometryUtils.area(prevX, prevY, curX, curY, nextX, nextY); - if (area > 1000) { - //log.debug("b: " + string + " " + area ); - break; - } + if (area > 1000) { + //log.debug("b: " + string + " " + area ); + break; + } - a = (float) Math.sqrt(wx * wx + wy * wy); - wx /= a; - wy /= a; + a = (float) Math.sqrt(wx * wx + wy * wy); + wx /= a; + wy /= a; - // avoid adding short segments that add much area - if (area / 2 > a * a) { - //log.debug("a: " +string + " " + area + " " + a*a); - break; - } + // avoid adding short segments that add much area + if (area / 2 > a * a) { + //log.debug("a: " +string + " " + area + " " + a*a); + break; + } - float ux = vx + wx; - float uy = vy + wy; - float diff = wx * uy - wy * ux; + float ux = vx + wx; + float uy = vy + wy; + float diff = wx * uy - wy * ux; - // maximum angle between segments - if (diff > 0.1 || diff < -0.1) { - //log.debug("c: " + string + " " + area ); - break; - } - curX = nextX; - curY = nextY; - last = j - 2; + // maximum angle between segments + if (diff > 0.1 || diff < -0.1) { + //log.debug("c: " + string + " " + area ); + break; + } + curX = nextX; + curY = nextY; + last = j - 2; - //if (clip < 0) { - // if (nextX == min) - // edge |= 1 << 4; - // else if (nextX == max) - // edge |= 1 << 5; - // - // if (nextY == min) - // edge |= 1 << 6; - // else if (nextY == max) - // edge |= 1 << 7; - //} - } + //if (clip < 0) { + // if (nextX == min) + // edge |= 1 << 4; + // else if (nextX == max) + // edge |= 1 << 5; + // + // if (nextY == min) + // edge |= 1 << 6; + // else if (nextY == max) + // edge |= 1 << 7; + //} + } - vx = curX - prevX; - vy = curY - prevY; - a = (float) Math.sqrt(vx * vx + vy * vy); - } + vx = curX - prevX; + vy = curY - prevY; + a = (float) Math.sqrt(vx * vx + vy * vy); + } - float segmentLength = a; + float segmentLength = a; - if (edge == 0) { - if (segmentLength < minWidth) { - continue; - } + if (edge == 0) { + if (segmentLength < minWidth) { + continue; + } - if (labelWidth < 0) { - labelWidth = text.paint.measureText(string); - } + if (labelWidth < 0) { + labelWidth = text.paint.measureText(string); + } - if (segmentLength < labelWidth * 0.50) { - continue; - } - } else if (labelWidth < 0) { - labelWidth = text.paint.measureText(string); - } + if (segmentLength < labelWidth * 0.50) { + continue; + } + } else if (labelWidth < 0) { + labelWidth = text.paint.measureText(string); + } - float x1, y1, x2, y2; - if (prevX < curX) { - x1 = prevX; - y1 = prevY; - x2 = curX; - y2 = curY; - } else { - x1 = curX; - y1 = curY; - x2 = prevX; - y2 = prevY; - } + float x1, y1, x2, y2; + if (prevX < curX) { + x1 = prevX; + y1 = prevY; + x2 = curX; + y2 = curY; + } else { + x1 = curX; + y1 = curY; + x2 = prevX; + y2 = prevY; + } - TextItem n = TextItem.pool.get(); + TextItem n = TextItem.pool.get(); - // link items together - //if (t != null) { - // t.n1 = n; - // n.n2 = t; - //} + // link items together + //if (t != null) { + // t.n1 = n; + // n.n2 = t; + //} - t = n; - t.x = x1 + (x2 - x1) / 2f; - t.y = y1 + (y2 - y1) / 2f; - t.string = string; - t.text = text; - t.width = labelWidth; - t.x1 = x1; - t.y1 = y1; - t.x2 = x2; - t.y2 = y2; - t.length = (short) segmentLength; + t = n; + t.x = x1 + (x2 - x1) / 2f; + t.y = y1 + (y2 - y1) / 2f; + t.string = string; + t.text = text; + t.width = labelWidth; + t.x1 = x1; + t.y1 = y1; + t.x2 = x2; + t.y2 = y2; + t.length = (short) segmentLength; - t.edges = edge; - ld.labels.push(t); + t.edges = edge; + ld.labels.push(t); - i = last; - } - } + i = last; + } + } - private WayDecorator() { - throw new IllegalStateException(); - } + private WayDecorator() { + throw new IllegalStateException(); + } } diff --git a/vtm/src/org/oscim/layers/vector/AbstractVectorLayer.java b/vtm/src/org/oscim/layers/vector/AbstractVectorLayer.java index a3c90a20..9f5ea31a 100644 --- a/vtm/src/org/oscim/layers/vector/AbstractVectorLayer.java +++ b/vtm/src/org/oscim/layers/vector/AbstractVectorLayer.java @@ -17,146 +17,150 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractVectorLayer extends Layer implements UpdateListener { - public static final Logger log = LoggerFactory.getLogger(AbstractVectorLayer.class); + public static final Logger log = LoggerFactory.getLogger(AbstractVectorLayer.class); - protected final static double UNSCALE_COORD = 4; + protected final static double UNSCALE_COORD = 4; - protected final GeometryBuffer mGeom = new GeometryBuffer(128, 4); - protected final TileClipper mClipper = new TileClipper(-1024, -1024, 1024, 1024); + protected final GeometryBuffer mGeom = new GeometryBuffer(128, 4); + protected final TileClipper mClipper = new TileClipper(-1024, -1024, 1024, 1024); - protected final Worker mWorker; - protected long mUpdateDelay = 50; + protected final Worker mWorker; + protected long mUpdateDelay = 50; - protected boolean mUpdate = true; + protected boolean mUpdate = true; - public AbstractVectorLayer(Map map) { - super(map); - mWorker = new Worker(mMap); - mRenderer = new Renderer(); - } + public AbstractVectorLayer(Map map) { + super(map); + mWorker = new Worker(mMap); + mRenderer = new Renderer(); + } - @Override - public void onDetach() { - super.onDetach(); + @Override + public void onDetach() { + super.onDetach(); - mWorker.cancel(true); - } + mWorker.cancel(true); + } - @Override - public void onMapEvent(Event e, MapPosition pos) { - if (mUpdate) { - mUpdate = false; - mWorker.submit(0); - } else if (e == Map.POSITION_EVENT || e == Map.CLEAR_EVENT) { - /* throttle worker */ - mWorker.submit(mUpdateDelay); - } - } + @Override + public void onMapEvent(Event e, MapPosition pos) { + if (mUpdate) { + mUpdate = false; + mWorker.submit(0); + } else if (e == Map.POSITION_EVENT || e == Map.CLEAR_EVENT) { + /* throttle worker */ + mWorker.submit(mUpdateDelay); + } + } - public void update() { - mWorker.submit(0); - } + public void update() { + mWorker.submit(0); + } - abstract protected void processFeatures(Task t, Box b); + abstract protected void processFeatures(Task t, Box b); - protected static class Task { - public final RenderBuckets buckets = new RenderBuckets(); - public final MapPosition position = new MapPosition(); - } + protected static class Task { + public final RenderBuckets buckets = new RenderBuckets(); + public final MapPosition position = new MapPosition(); + } - protected class Worker extends SimpleWorker { + protected class Worker extends SimpleWorker { - public Worker(Map map) { - super(map, 50, new Task(), new Task()); - } + public Worker(Map map) { + super(map, 50, new Task(), new Task()); + } - /** automatically in sync with worker thread */ - @Override - public void cleanup(Task t) { - if (t.buckets != null) - t.buckets.clear(); - } + /** + * automatically in sync with worker thread + */ + @Override + public void cleanup(Task t) { + if (t.buckets != null) + t.buckets.clear(); + } - /** running on worker thread */ - @Override - public boolean doWork(Task t) { + /** + * running on worker thread + */ + @Override + public boolean doWork(Task t) { - Box bbox; - float[] box = new float[8]; + Box bbox; + float[] box = new float[8]; - Viewport v = mMap.viewport().getSyncViewport(); - synchronized (v) { - bbox = v.getBBox(null, 0); - v.getMapExtents(box, 0); - v.getMapPosition(t.position); - } + Viewport v = mMap.viewport().getSyncViewport(); + synchronized (v) { + bbox = v.getBBox(null, 0); + v.getMapExtents(box, 0); + v.getMapPosition(t.position); + } /* Hmm what is this for? */ - // double scale = t.position.scale * Tile.SIZE; - // t.position.x = (long) (t.position.x * scale) / scale; - // t.position.y = (long) (t.position.y * scale) / scale; + // double scale = t.position.scale * Tile.SIZE; + // t.position.x = (long) (t.position.x * scale) / scale; + // t.position.y = (long) (t.position.y * scale) / scale; - bbox.map2mercator(); + bbox.map2mercator(); - // double xmin = bbox.xmin; - // double xmax = bbox.xmax; - // Box lbox = null; - // Box rbox = null; - // if (bbox.xmin < -180) { - // bbox.xmin = -180; - // lbox = new Box(bbox); - // } - // if (bbox.xmax > 180) { - // bbox.xmax = 180; - // rbox = new Box(bbox); - // } + // double xmin = bbox.xmin; + // double xmax = bbox.xmax; + // Box lbox = null; + // Box rbox = null; + // if (bbox.xmin < -180) { + // bbox.xmin = -180; + // lbox = new Box(bbox); + // } + // if (bbox.xmax > 180) { + // bbox.xmax = 180; + // rbox = new Box(bbox); + // } - processFeatures(t, bbox); + processFeatures(t, bbox); - //if (lbox != null) { - // t.position.x += 1; - // lbox.xmax = 180; - // lbox.xmin = xmin + 180; - // processFeatures(t, lbox); - // t.position.x -= 1; - //} - // - //if (rbox != null) { - // t.position.x -= 1; - // rbox.xmin = -180; - // rbox.xmax = xmax - 180; - // processFeatures(t, rbox); - // t.position.x += 1; - //} + //if (lbox != null) { + // t.position.x += 1; + // lbox.xmax = 180; + // lbox.xmin = xmin + 180; + // processFeatures(t, lbox); + // t.position.x -= 1; + //} + // + //if (rbox != null) { + // t.position.x -= 1; + // rbox.xmin = -180; + // rbox.xmax = xmax - 180; + // processFeatures(t, rbox); + // t.position.x += 1; + //} - t.buckets.prepare(); + t.buckets.prepare(); - mMap.render(); - return true; - } - } + mMap.render(); + return true; + } + } - public class Renderer extends BucketRenderer { - MapPosition mTmpPos = new MapPosition(); + public class Renderer extends BucketRenderer { + MapPosition mTmpPos = new MapPosition(); - public Renderer() { - mFlipOnDateLine = true; - } + public Renderer() { + mFlipOnDateLine = true; + } - @Override - public void update(GLViewport v) { + @Override + public void update(GLViewport v) { - Task t = mWorker.poll(); + Task t = mWorker.poll(); - if (t == null) - return; + if (t == null) + return; - mMapPosition.copy(t.position); - mMapPosition.setScale(mMapPosition.scale / UNSCALE_COORD); + mMapPosition.copy(t.position); + mMapPosition.setScale(mMapPosition.scale / UNSCALE_COORD); - buckets.setFrom(t.buckets); + buckets.setFrom(t.buckets); - compile(); - } - } + compile(); + } + } } diff --git a/vtm/src/org/oscim/map/Animator.java b/vtm/src/org/oscim/map/Animator.java index 50ced660..421a76bb 100644 --- a/vtm/src/org/oscim/map/Animator.java +++ b/vtm/src/org/oscim/map/Animator.java @@ -16,10 +16,6 @@ */ package org.oscim.map; -import static org.oscim.core.MercatorProjection.latitudeToY; -import static org.oscim.core.MercatorProjection.longitudeToX; -import static org.oscim.utils.FastMath.clamp; - import org.oscim.backend.CanvasAdapter; import org.oscim.core.BoundingBox; import org.oscim.core.GeoPoint; @@ -32,266 +28,270 @@ import org.oscim.utils.async.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.core.MercatorProjection.latitudeToY; +import static org.oscim.core.MercatorProjection.longitudeToX; +import static org.oscim.utils.FastMath.clamp; + public class Animator { - static final Logger log = LoggerFactory.getLogger(Animator.class); + static final Logger log = LoggerFactory.getLogger(Animator.class); - private final static int ANIM_NONE = 0; - private final static int ANIM_MOVE = 1 << 0; - private final static int ANIM_SCALE = 1 << 1; - private final static int ANIM_ROTATE = 1 << 2; - private final static int ANIM_TILT = 1 << 3; - private final static int ANIM_FLING = 1 << 4; + private final static int ANIM_NONE = 0; + private final static int ANIM_MOVE = 1 << 0; + private final static int ANIM_SCALE = 1 << 1; + private final static int ANIM_ROTATE = 1 << 2; + private final static int ANIM_TILT = 1 << 3; + private final static int ANIM_FLING = 1 << 4; - private final Map mMap; + private final Map mMap; - private final MapPosition mCurPos = new MapPosition(); - private final MapPosition mStartPos = new MapPosition(); - private final MapPosition mDeltaPos = new MapPosition(); + private final MapPosition mCurPos = new MapPosition(); + private final MapPosition mStartPos = new MapPosition(); + private final MapPosition mDeltaPos = new MapPosition(); - private final Point mScroll = new Point(); - private final Point mPivot = new Point(); - private final Point mVelocity = new Point(); + private final Point mScroll = new Point(); + private final Point mPivot = new Point(); + private final Point mVelocity = new Point(); - private float mDuration = 500; - private long mAnimEnd = -1; + private float mDuration = 500; + private long mAnimEnd = -1; - private int mState = ANIM_NONE; + private int mState = ANIM_NONE; - public Animator(Map map) { - mMap = map; - } + public Animator(Map map) { + mMap = map; + } - public synchronized void animateTo(long duration, BoundingBox bbox) { - ThreadUtils.assertMainThread(); + public synchronized void animateTo(long duration, BoundingBox bbox) { + ThreadUtils.assertMainThread(); - mMap.getMapPosition(mStartPos); - /* TODO for large distance first scale out, then in - * calculate the maximum scale at which the BoundingBox + mMap.getMapPosition(mStartPos); + /* TODO for large distance first scale out, then in + * calculate the maximum scale at which the BoundingBox * is completely visible */ - double dx = Math.abs(longitudeToX(bbox.getMaxLongitude()) - - longitudeToX(bbox.getMinLongitude())); + double dx = Math.abs(longitudeToX(bbox.getMaxLongitude()) + - longitudeToX(bbox.getMinLongitude())); - double dy = Math.abs(latitudeToY(bbox.getMinLatitude()) - - latitudeToY(bbox.getMaxLatitude())); + double dy = Math.abs(latitudeToY(bbox.getMinLatitude()) + - latitudeToY(bbox.getMaxLatitude())); - log.debug("anim bbox " + bbox); + log.debug("anim bbox " + bbox); - double zx = mMap.getWidth() / (dx * Tile.SIZE); - double zy = mMap.getHeight() / (dy * Tile.SIZE); - double newScale = Math.min(zx, zy); + double zx = mMap.getWidth() / (dx * Tile.SIZE); + double zy = mMap.getHeight() / (dy * Tile.SIZE); + double newScale = Math.min(zx, zy); - GeoPoint p = bbox.getCenterPoint(); + GeoPoint p = bbox.getCenterPoint(); - mDeltaPos.set(longitudeToX(p.getLongitude()) - mStartPos.x, - latitudeToY(p.getLatitude()) - mStartPos.y, - newScale - mStartPos.scale, - -mStartPos.bearing, - -mStartPos.tilt); + mDeltaPos.set(longitudeToX(p.getLongitude()) - mStartPos.x, + latitudeToY(p.getLatitude()) - mStartPos.y, + newScale - mStartPos.scale, + -mStartPos.bearing, + -mStartPos.tilt); - animStart(duration, ANIM_MOVE | ANIM_SCALE | ANIM_ROTATE | ANIM_TILT); - } + animStart(duration, ANIM_MOVE | ANIM_SCALE | ANIM_ROTATE | ANIM_TILT); + } - public void animateTo(BoundingBox bbox) { - animateTo(1000, bbox); - } + public void animateTo(BoundingBox bbox) { + animateTo(1000, bbox); + } - /** - * Animate to GeoPoint - * - * @param duration in ms - * @param geoPoint - * @param scale - * @param relative alter scale relative to current scale - */ - public void animateTo(long duration, GeoPoint geoPoint, - double scale, boolean relative) { - ThreadUtils.assertMainThread(); + /** + * Animate to GeoPoint + * + * @param duration in ms + * @param geoPoint + * @param scale + * @param relative alter scale relative to current scale + */ + public void animateTo(long duration, GeoPoint geoPoint, + double scale, boolean relative) { + ThreadUtils.assertMainThread(); - mMap.getMapPosition(mStartPos); + mMap.getMapPosition(mStartPos); - if (relative) - scale = mStartPos.scale * scale; + if (relative) + scale = mStartPos.scale * scale; - scale = mMap.viewport().limitScale(scale); + scale = mMap.viewport().limitScale(scale); - mDeltaPos.set(longitudeToX(geoPoint.getLongitude()) - mStartPos.x, - latitudeToY(geoPoint.getLatitude()) - mStartPos.y, - scale - mStartPos.scale, - 0, 0); + mDeltaPos.set(longitudeToX(geoPoint.getLongitude()) - mStartPos.x, + latitudeToY(geoPoint.getLatitude()) - mStartPos.y, + scale - mStartPos.scale, + 0, 0); - animStart(duration, ANIM_MOVE | ANIM_SCALE); - } + animStart(duration, ANIM_MOVE | ANIM_SCALE); + } - public void animateTo(GeoPoint p) { - animateTo(500, p, 1, true); - } + public void animateTo(GeoPoint p) { + animateTo(500, p, 1, true); + } - public void animateTo(long duration, MapPosition pos) { - ThreadUtils.assertMainThread(); + public void animateTo(long duration, MapPosition pos) { + ThreadUtils.assertMainThread(); - mMap.getMapPosition(mStartPos); + mMap.getMapPosition(mStartPos); - pos.scale = mMap.viewport().limitScale(pos.scale); + pos.scale = mMap.viewport().limitScale(pos.scale); - mDeltaPos.set(pos.x - mStartPos.x, - pos.y - mStartPos.y, - pos.scale - mStartPos.scale, - pos.bearing - mStartPos.bearing, - mMap.viewport().limitTilt(pos.tilt) - mStartPos.tilt); + mDeltaPos.set(pos.x - mStartPos.x, + pos.y - mStartPos.y, + pos.scale - mStartPos.scale, + pos.bearing - mStartPos.bearing, + mMap.viewport().limitTilt(pos.tilt) - mStartPos.tilt); - animStart(duration, ANIM_MOVE | ANIM_SCALE | ANIM_ROTATE | ANIM_TILT); - } + animStart(duration, ANIM_MOVE | ANIM_SCALE | ANIM_ROTATE | ANIM_TILT); + } - public void animateZoom(long duration, double scaleBy, - float pivotX, float pivotY) { - ThreadUtils.assertMainThread(); + public void animateZoom(long duration, double scaleBy, + float pivotX, float pivotY) { + ThreadUtils.assertMainThread(); - mMap.getMapPosition(mCurPos); + mMap.getMapPosition(mCurPos); - if (mState == ANIM_SCALE) - scaleBy = (mStartPos.scale + mDeltaPos.scale) * scaleBy; - else - scaleBy = mCurPos.scale * scaleBy; + if (mState == ANIM_SCALE) + scaleBy = (mStartPos.scale + mDeltaPos.scale) * scaleBy; + else + scaleBy = mCurPos.scale * scaleBy; - mStartPos.copy(mCurPos); - scaleBy = mMap.viewport().limitScale(scaleBy); + mStartPos.copy(mCurPos); + scaleBy = mMap.viewport().limitScale(scaleBy); - mDeltaPos.scale = scaleBy - mStartPos.scale; + mDeltaPos.scale = scaleBy - mStartPos.scale; - mPivot.x = pivotX; - mPivot.y = pivotY; + mPivot.x = pivotX; + mPivot.y = pivotY; - animStart(duration, ANIM_SCALE); - } + animStart(duration, ANIM_SCALE); + } - public void animateFling(float velocityX, float velocityY, - int xmin, int xmax, int ymin, int ymax) { + public void animateFling(float velocityX, float velocityY, + int xmin, int xmax, int ymin, int ymax) { - ThreadUtils.assertMainThread(); + ThreadUtils.assertMainThread(); - if (velocityX * velocityX + velocityY * velocityY < 2048) - return; + if (velocityX * velocityX + velocityY * velocityY < 2048) + return; - mMap.getMapPosition(mStartPos); + mMap.getMapPosition(mStartPos); - mScroll.x = 0; - mScroll.y = 0; + mScroll.x = 0; + mScroll.y = 0; - float duration = 500; + float duration = 500; - float flingFactor = 240 / CanvasAdapter.dpi; - mVelocity.x = velocityX * flingFactor; - mVelocity.y = velocityY * flingFactor; - mVelocity.x = clamp(mVelocity.x, xmin, xmax); - mVelocity.y = clamp(mVelocity.y, ymin, ymax); - if (Double.isNaN(mVelocity.x) || Double.isNaN(mVelocity.y)) { - log.debug("fling NaN!"); - return; - } + float flingFactor = 240 / CanvasAdapter.dpi; + mVelocity.x = velocityX * flingFactor; + mVelocity.y = velocityY * flingFactor; + mVelocity.x = clamp(mVelocity.x, xmin, xmax); + mVelocity.y = clamp(mVelocity.y, ymin, ymax); + if (Double.isNaN(mVelocity.x) || Double.isNaN(mVelocity.y)) { + log.debug("fling NaN!"); + return; + } - animStart(duration, ANIM_FLING); - } + animStart(duration, ANIM_FLING); + } - private void animStart(float duration, int state) { - mCurPos.copy(mStartPos); - mState = state; - mDuration = duration; - mAnimEnd = System.currentTimeMillis() + (long) duration; - mMap.render(); - } + private void animStart(float duration, int state) { + mCurPos.copy(mStartPos); + mState = state; + mDuration = duration; + mAnimEnd = System.currentTimeMillis() + (long) duration; + mMap.render(); + } - /** - * called by MapRenderer at begin of each frame. - */ - void updateAnimation() { - if (mState == ANIM_NONE) - return; + /** + * called by MapRenderer at begin of each frame. + */ + void updateAnimation() { + if (mState == ANIM_NONE) + return; - long millisLeft = mAnimEnd - MapRenderer.frametime; + long millisLeft = mAnimEnd - MapRenderer.frametime; - ViewController v = mMap.viewport(); + ViewController v = mMap.viewport(); /* cancel animation when position was changed since last * update, i.e. when it was modified outside the animator. */ - if (v.getMapPosition(mCurPos)) { - log.debug("cancel anim - changed"); - cancel(); - return; - } + if (v.getMapPosition(mCurPos)) { + log.debug("cancel anim - changed"); + cancel(); + return; + } - float adv = clamp(1.0f - millisLeft / mDuration, 0, 1); + float adv = clamp(1.0f - millisLeft / mDuration, 0, 1); - double scaleAdv = 1; - if ((mState & ANIM_SCALE) != 0) { - scaleAdv = doScale(v, adv); - } + double scaleAdv = 1; + if ((mState & ANIM_SCALE) != 0) { + scaleAdv = doScale(v, adv); + } - if ((mState & ANIM_MOVE) != 0) { - v.moveTo(mStartPos.x + mDeltaPos.x * (adv / scaleAdv), - mStartPos.y + mDeltaPos.y * (adv / scaleAdv)); - } + if ((mState & ANIM_MOVE) != 0) { + v.moveTo(mStartPos.x + mDeltaPos.x * (adv / scaleAdv), + mStartPos.y + mDeltaPos.y * (adv / scaleAdv)); + } - if ((mState & ANIM_FLING) != 0) { - adv = (float) Math.sqrt(adv); - double dx = mVelocity.x * adv; - double dy = mVelocity.y * adv; - if ((dx - mScroll.x) != 0 || (dy - mScroll.y) != 0) { - v.moveMap((float) (dx - mScroll.x), - (float) (dy - mScroll.y)); - mScroll.x = dx; - mScroll.y = dy; - } - } - if ((mState & ANIM_ROTATE) != 0) { - v.setRotation(mStartPos.bearing + mDeltaPos.bearing * adv); - } + if ((mState & ANIM_FLING) != 0) { + adv = (float) Math.sqrt(adv); + double dx = mVelocity.x * adv; + double dy = mVelocity.y * adv; + if ((dx - mScroll.x) != 0 || (dy - mScroll.y) != 0) { + v.moveMap((float) (dx - mScroll.x), + (float) (dy - mScroll.y)); + mScroll.x = dx; + mScroll.y = dy; + } + } + if ((mState & ANIM_ROTATE) != 0) { + v.setRotation(mStartPos.bearing + mDeltaPos.bearing * adv); + } - if ((mState & ANIM_TILT) != 0) { - v.setTilt(mStartPos.tilt + mDeltaPos.tilt * adv); - } + if ((mState & ANIM_TILT) != 0) { + v.setTilt(mStartPos.tilt + mDeltaPos.tilt * adv); + } - if (millisLeft <= 0) { - //log.debug("animate END"); - cancel(); - } + if (millisLeft <= 0) { + //log.debug("animate END"); + cancel(); + } /* remember current map position */ - final boolean changed = v.getMapPosition(mCurPos); + final boolean changed = v.getMapPosition(mCurPos); - if (changed) { - mMap.updateMap(true); - } else { - mMap.postDelayed(updateTask, 10); - } - } + if (changed) { + mMap.updateMap(true); + } else { + mMap.postDelayed(updateTask, 10); + } + } - private Task updateTask = new Task() { - @Override - public int go(boolean canceled) { - if (!canceled) - updateAnimation(); - return Task.DONE; - } - }; + private Task updateTask = new Task() { + @Override + public int go(boolean canceled) { + if (!canceled) + updateAnimation(); + return Task.DONE; + } + }; - private double doScale(ViewController v, float adv) { - double newScale = mStartPos.scale + mDeltaPos.scale * Math.sqrt(adv); + private double doScale(ViewController v, float adv) { + double newScale = mStartPos.scale + mDeltaPos.scale * Math.sqrt(adv); - v.scaleMap((float) (newScale / mCurPos.scale), - (float) mPivot.x, (float) mPivot.y); + v.scaleMap((float) (newScale / mCurPos.scale), + (float) mPivot.x, (float) mPivot.y); - return newScale / (mStartPos.scale + mDeltaPos.scale); - } + return newScale / (mStartPos.scale + mDeltaPos.scale); + } - public void cancel() { - //ThreadUtils.assertMainThread(); - mState = ANIM_NONE; - mPivot.x = 0; - mPivot.y = 0; - mMap.events.fire(Map.ANIM_END, mMap.mMapPosition); - } + public void cancel() { + //ThreadUtils.assertMainThread(); + mState = ANIM_NONE; + mPivot.x = 0; + mPivot.y = 0; + mMap.events.fire(Map.ANIM_END, mMap.mMapPosition); + } - public boolean isActive() { - return mState != ANIM_NONE; - } + public boolean isActive() { + return mState != ANIM_NONE; + } } diff --git a/vtm/src/org/oscim/map/Layers.java b/vtm/src/org/oscim/map/Layers.java index 18e546d6..4b80be82 100644 --- a/vtm/src/org/oscim/map/Layers.java +++ b/vtm/src/org/oscim/map/Layers.java @@ -16,9 +16,6 @@ */ package org.oscim.map; -import java.util.AbstractList; -import java.util.concurrent.CopyOnWriteArrayList; - import org.oscim.event.Gesture; import org.oscim.event.GestureListener; import org.oscim.event.MotionEvent; @@ -27,130 +24,133 @@ import org.oscim.map.Map.InputListener; import org.oscim.map.Map.UpdateListener; import org.oscim.renderer.LayerRenderer; +import java.util.AbstractList; +import java.util.concurrent.CopyOnWriteArrayList; + public final class Layers extends AbstractList { - private final CopyOnWriteArrayList mLayerList; - private final Map mMap; + private final CopyOnWriteArrayList mLayerList; + private final Map mMap; - private boolean mDirtyLayers; - private LayerRenderer[] mLayerRenderer; - private Layer[] mLayers; + private boolean mDirtyLayers; + private LayerRenderer[] mLayerRenderer; + private Layer[] mLayers; - Layers(Map map) { - mMap = map; - mLayerList = new CopyOnWriteArrayList(); - } + Layers(Map map) { + mMap = map; + mLayerList = new CopyOnWriteArrayList(); + } - @Override - public synchronized Layer get(int index) { - return mLayerList.get(index); - } + @Override + public synchronized Layer get(int index) { + return mLayerList.get(index); + } - @Override - public synchronized int size() { - return mLayerList.size(); - } + @Override + public synchronized int size() { + return mLayerList.size(); + } - @Override - public synchronized void add(int index, Layer layer) { - if (mLayerList.contains(layer)) - throw new IllegalArgumentException("layer added twice"); + @Override + public synchronized void add(int index, Layer layer) { + if (mLayerList.contains(layer)) + throw new IllegalArgumentException("layer added twice"); - if (layer instanceof UpdateListener) - mMap.events.bind((UpdateListener) layer); + if (layer instanceof UpdateListener) + mMap.events.bind((UpdateListener) layer); - if (layer instanceof InputListener) - mMap.input.bind((InputListener) layer); + if (layer instanceof InputListener) + mMap.input.bind((InputListener) layer); - mLayerList.add(index, layer); - mDirtyLayers = true; - } + mLayerList.add(index, layer); + mDirtyLayers = true; + } - @Override - public synchronized Layer remove(int index) { - mDirtyLayers = true; + @Override + public synchronized Layer remove(int index) { + mDirtyLayers = true; - Layer remove = mLayerList.remove(index); + Layer remove = mLayerList.remove(index); - if (remove instanceof UpdateListener) - mMap.events.unbind((UpdateListener) remove); - if (remove instanceof InputListener) - mMap.input.unbind((InputListener) remove); + if (remove instanceof UpdateListener) + mMap.events.unbind((UpdateListener) remove); + if (remove instanceof InputListener) + mMap.input.unbind((InputListener) remove); - return remove; - } + return remove; + } - @Override - public synchronized Layer set(int index, Layer layer) { - if (mLayerList.contains(layer)) - throw new IllegalArgumentException("layer added twice"); + @Override + public synchronized Layer set(int index, Layer layer) { + if (mLayerList.contains(layer)) + throw new IllegalArgumentException("layer added twice"); - mDirtyLayers = true; - Layer remove = mLayerList.set(index, layer); + mDirtyLayers = true; + Layer remove = mLayerList.set(index, layer); - // unbind replaced layer - if (remove instanceof UpdateListener) - mMap.events.unbind((UpdateListener) remove); - if (remove instanceof InputListener) - mMap.input.unbind((InputListener) remove); + // unbind replaced layer + if (remove instanceof UpdateListener) + mMap.events.unbind((UpdateListener) remove); + if (remove instanceof InputListener) + mMap.input.unbind((InputListener) remove); - return remove; - } + return remove; + } - /** - * Should only be used by MapRenderer. - * - * @return the current LayerRenderer as array. - * */ - public LayerRenderer[] getLayerRenderer() { - if (mDirtyLayers) - updateLayers(); + /** + * Should only be used by MapRenderer. + * + * @return the current LayerRenderer as array. + */ + public LayerRenderer[] getLayerRenderer() { + if (mDirtyLayers) + updateLayers(); - return mLayerRenderer; - } + return mLayerRenderer; + } - void destroy() { - if (mDirtyLayers) - updateLayers(); + void destroy() { + if (mDirtyLayers) + updateLayers(); - for (Layer o : mLayers) - o.onDetach(); - } + for (Layer o : mLayers) + o.onDetach(); + } - boolean handleGesture(Gesture g, MotionEvent e) { - if (mDirtyLayers) - updateLayers(); + boolean handleGesture(Gesture g, MotionEvent e) { + if (mDirtyLayers) + updateLayers(); - for (Layer o : mLayers) - if (o instanceof GestureListener) - if (((GestureListener) o).onGesture(g, e)) - return true; + for (Layer o : mLayers) + if (o instanceof GestureListener) + if (((GestureListener) o).onGesture(g, e)) + return true; - return false; - } + return false; + } - private synchronized void updateLayers() { - mLayers = new Layer[mLayerList.size()]; - int numRenderLayers = 0; + private synchronized void updateLayers() { + mLayers = new Layer[mLayerList.size()]; + int numRenderLayers = 0; - for (int i = 0, n = mLayerList.size(); i < n; i++) { - Layer o = mLayerList.get(i); + for (int i = 0, n = mLayerList.size(); i < n; i++) { + Layer o = mLayerList.get(i); - if (o.getRenderer() != null) - numRenderLayers++; + if (o.getRenderer() != null) + numRenderLayers++; - mLayers[n - i - 1] = o; - } + mLayers[n - i - 1] = o; + } - mLayerRenderer = new LayerRenderer[numRenderLayers]; + mLayerRenderer = new LayerRenderer[numRenderLayers]; - for (int i = 0, cnt = 0, n = mLayerList.size(); i < n; i++) { - Layer o = mLayerList.get(i); - LayerRenderer l = o.getRenderer(); - if (l != null) - mLayerRenderer[cnt++] = l; - } + for (int i = 0, cnt = 0, n = mLayerList.size(); i < n; i++) { + Layer o = mLayerList.get(i); + LayerRenderer l = o.getRenderer(); + if (l != null) + mLayerRenderer[cnt++] = l; + } - mDirtyLayers = false; - } + mDirtyLayers = false; + } } diff --git a/vtm/src/org/oscim/map/Map.java b/vtm/src/org/oscim/map/Map.java index 65c5acd5..b84473a6 100644 --- a/vtm/src/org/oscim/map/Map.java +++ b/vtm/src/org/oscim/map/Map.java @@ -42,316 +42,320 @@ import org.slf4j.LoggerFactory; public abstract class Map implements TaskQueue { - static final Logger log = LoggerFactory.getLogger(Map.class); + static final Logger log = LoggerFactory.getLogger(Map.class); - /** - * Listener interface for map update notifications. - * Layers implementing this interface they will be automatically register - * when the layer is added to the map and unregistered when the layer is - * removed. Otherwise use map.events.bind(UpdateListener). - */ - public interface UpdateListener extends EventListener { - void onMapEvent(Event e, MapPosition mapPosition); - } + /** + * Listener interface for map update notifications. + * Layers implementing this interface they will be automatically register + * when the layer is added to the map and unregistered when the layer is + * removed. Otherwise use map.events.bind(UpdateListener). + */ + public interface UpdateListener extends EventListener { + void onMapEvent(Event e, MapPosition mapPosition); + } - /** - * Listener interface for input events. - * Layers implementing this interface they will be automatically register - * when the layer is added to the map and unregistered when the layer is - * removed. - */ + /** + * Listener interface for input events. + * Layers implementing this interface they will be automatically register + * when the layer is added to the map and unregistered when the layer is + * removed. + */ - public interface InputListener extends EventListener { - void onInputEvent(Event e, MotionEvent motionEvent); - } + public interface InputListener extends EventListener { + void onInputEvent(Event e, MotionEvent motionEvent); + } - /** - * UpdateListener event. Map position has changed. - */ - public static final Event POSITION_EVENT = new Event(); + /** + * UpdateListener event. Map position has changed. + */ + public static final Event POSITION_EVENT = new Event(); - /** - * UpdateLister event. Delivered on main-thread when updateMap() was called - * and no CLEAR_EVENT or POSITION_EVENT was triggered. - */ - public static final Event UPDATE_EVENT = new Event(); + /** + * UpdateLister event. Delivered on main-thread when updateMap() was called + * and no CLEAR_EVENT or POSITION_EVENT was triggered. + */ + public static final Event UPDATE_EVENT = new Event(); - /** - * UpdateListerner event. Map state has changed in a way that all layers - * should clear their state e.g. the theme or the TilesSource has changed. - * TODO should have an event-source to only clear affected layers. - */ - public static final Event CLEAR_EVENT = new Event(); + /** + * UpdateListerner event. Map state has changed in a way that all layers + * should clear their state e.g. the theme or the TilesSource has changed. + * TODO should have an event-source to only clear affected layers. + */ + public static final Event CLEAR_EVENT = new Event(); - public static final Event ANIM_END = new Event(); + public static final Event ANIM_END = new Event(); - public final EventDispatcher input; - public final EventDispatcher events; + public final EventDispatcher input; + public final EventDispatcher events; - private final Layers mLayers; - private final ViewController mViewport; - private final AsyncExecutor mAsyncExecutor; + private final Layers mLayers; + private final ViewController mViewport; + private final AsyncExecutor mAsyncExecutor; - protected final Animator mAnimator; - protected final MapPosition mMapPosition; + protected final Animator mAnimator; + protected final MapPosition mMapPosition; - protected final MapEventLayer mEventLayer; - protected GestureDetector mGestureDetector; + protected final MapEventLayer mEventLayer; + protected GestureDetector mGestureDetector; - private TileLayer mBaseLayer; + private TileLayer mBaseLayer; - protected boolean mClearMap = true; + protected boolean mClearMap = true; - public Map() { - ThreadUtils.init(); + public Map() { + ThreadUtils.init(); - mViewport = new ViewController(); - mAnimator = new Animator(this); - mLayers = new Layers(this); + mViewport = new ViewController(); + mAnimator = new Animator(this); + mLayers = new Layers(this); - input = new EventDispatcher() { + input = new EventDispatcher() { - @Override - public void tell(InputListener l, Event e, MotionEvent d) { - l.onInputEvent(e, d); - } - }; - events = new EventDispatcher() { + @Override + public void tell(InputListener l, Event e, MotionEvent d) { + l.onInputEvent(e, d); + } + }; + events = new EventDispatcher() { - @Override - public void tell(UpdateListener l, Event e, MapPosition d) { - l.onMapEvent(e, d); - } - }; + @Override + public void tell(UpdateListener l, Event e, MapPosition d) { + l.onMapEvent(e, d); + } + }; - mAsyncExecutor = new AsyncExecutor(4, this); - mMapPosition = new MapPosition(); + mAsyncExecutor = new AsyncExecutor(4, this); + mMapPosition = new MapPosition(); - mEventLayer = new MapEventLayer(this); - mLayers.add(0, mEventLayer); + mEventLayer = new MapEventLayer(this); + mLayers.add(0, mEventLayer); - } + } - public MapEventLayer getEventLayer() { - return mEventLayer; - } + public MapEventLayer getEventLayer() { + return mEventLayer; + } - /** - * Create OsmTileLayer with given TileSource and - * set as base map (layer 1) - * - * TODO deprecate - */ - public VectorTileLayer setBaseMap(TileSource tileSource) { - VectorTileLayer l = new OsmTileLayer(this); - l.setTileSource(tileSource); - setBaseMap(l); - return l; - } + /** + * Create OsmTileLayer with given TileSource and + * set as base map (layer 1) + *

+ * TODO deprecate + */ + public VectorTileLayer setBaseMap(TileSource tileSource) { + VectorTileLayer l = new OsmTileLayer(this); + l.setTileSource(tileSource); + setBaseMap(l); + return l; + } - public TileLayer setBaseMap(TileLayer tileLayer) { - mLayers.add(1, tileLayer); - mBaseLayer = tileLayer; - return tileLayer; - } + public TileLayer setBaseMap(TileLayer tileLayer) { + mLayers.add(1, tileLayer); + mBaseLayer = tileLayer; + return tileLayer; + } - /** - * Utility function to set theme of base vector-layer and - * use map background color from theme. - */ - public void setTheme(ThemeFile theme) { - if (mBaseLayer == null) { - log.error("No base layer set"); - throw new IllegalStateException(); - } - setTheme(ThemeLoader.load(theme)); - } + /** + * Utility function to set theme of base vector-layer and + * use map background color from theme. + */ + public void setTheme(ThemeFile theme) { + if (mBaseLayer == null) { + log.error("No base layer set"); + throw new IllegalStateException(); + } + setTheme(ThemeLoader.load(theme)); + } - public void setTheme(IRenderTheme theme) { - if (theme == null) { - throw new IllegalArgumentException("Theme cannot be null."); - } + public void setTheme(IRenderTheme theme) { + if (theme == null) { + throw new IllegalArgumentException("Theme cannot be null."); + } - if (mBaseLayer == null) { - log.warn("No base layer set."); - } else if (mBaseLayer instanceof VectorTileLayer) { - ((VectorTileLayer) mBaseLayer).setRenderTheme(theme); - } + if (mBaseLayer == null) { + log.warn("No base layer set."); + } else if (mBaseLayer instanceof VectorTileLayer) { + ((VectorTileLayer) mBaseLayer).setRenderTheme(theme); + } - MapRenderer.setBackgroundColor(theme.getMapBackground()); + MapRenderer.setBackgroundColor(theme.getMapBackground()); - clearMap(); - } + clearMap(); + } - public void destroy() { - mLayers.destroy(); - mAsyncExecutor.dispose(); - } + public void destroy() { + mLayers.destroy(); + mAsyncExecutor.dispose(); + } - /** - * Request call to onUpdate for all layers. This function can - * be called from any thread. Request will be handled on main - * thread. - * - * @param redraw pass true to render next frame afterwards - */ - public abstract void updateMap(boolean redraw); + /** + * Request call to onUpdate for all layers. This function can + * be called from any thread. Request will be handled on main + * thread. + * + * @param redraw pass true to render next frame afterwards + */ + public abstract void updateMap(boolean redraw); - /** - * Request to render a frame. Request will be handled on main - * thread. Use this for animations in RenderLayers. - */ - public abstract void render(); + /** + * Request to render a frame. Request will be handled on main + * thread. Use this for animations in RenderLayers. + */ + public abstract void render(); - /** - * Post a runnable to be executed on main-thread - */ - @Override - public abstract boolean post(Runnable action); + /** + * Post a runnable to be executed on main-thread + */ + @Override + public abstract boolean post(Runnable action); - /** - * Post a runnable to be executed on main-thread. Execution is delayed for - * at least 'delay' milliseconds. - */ - public abstract boolean postDelayed(Runnable action, long delay); + /** + * Post a runnable to be executed on main-thread. Execution is delayed for + * at least 'delay' milliseconds. + */ + public abstract boolean postDelayed(Runnable action, long delay); - /** - * Post a task to run on a shared worker-thread. Shoul only use for - * tasks running less than a second. - */ - @Override - public void addTask(Runnable task) { - mAsyncExecutor.post(task); - } + /** + * Post a task to run on a shared worker-thread. Shoul only use for + * tasks running less than a second. + */ + @Override + public void addTask(Runnable task) { + mAsyncExecutor.post(task); + } - /** - * Return screen width in pixel. - */ - public abstract int getWidth(); + /** + * Return screen width in pixel. + */ + public abstract int getWidth(); - /** - * Return screen height in pixel. - */ - public abstract int getHeight(); + /** + * Return screen height in pixel. + */ + public abstract int getHeight(); - /** - * Request to clear all layers before rendering next frame - */ - public void clearMap() { - mClearMap = true; - updateMap(true); - } + /** + * Request to clear all layers before rendering next frame + */ + public void clearMap() { + mClearMap = true; + updateMap(true); + } - /** - * Set {@link MapPosition} of {@link Viewport} and trigger a redraw. - */ - public void setMapPosition(final MapPosition mapPosition) { - if (!ThreadUtils.isMainThread()) - post(new Runnable() { - @Override - public void run() { - mViewport.setMapPosition(mapPosition); - updateMap(true); - } - }); - else { - mViewport.setMapPosition(mapPosition); - updateMap(true); - } - } + /** + * Set {@link MapPosition} of {@link Viewport} and trigger a redraw. + */ + public void setMapPosition(final MapPosition mapPosition) { + if (!ThreadUtils.isMainThread()) + post(new Runnable() { + @Override + public void run() { + mViewport.setMapPosition(mapPosition); + updateMap(true); + } + }); + else { + mViewport.setMapPosition(mapPosition); + updateMap(true); + } + } - public void setMapPosition(double latitude, double longitude, double scale) { - mViewport.setMapPosition(new MapPosition(latitude, longitude, scale)); - updateMap(true); - } + public void setMapPosition(double latitude, double longitude, double scale) { + mViewport.setMapPosition(new MapPosition(latitude, longitude, scale)); + updateMap(true); + } - /** - * Get current {@link MapPosition}. - * - * @return true when MapPosition was updated (has changed) - */ - public boolean getMapPosition(MapPosition mapPosition) { - if (!ThreadUtils.isMainThread()) { - return mViewport.getSyncMapPosition(mapPosition); - } + /** + * Get current {@link MapPosition}. + * + * @return true when MapPosition was updated (has changed) + */ + public boolean getMapPosition(MapPosition mapPosition) { + if (!ThreadUtils.isMainThread()) { + return mViewport.getSyncMapPosition(mapPosition); + } - return mViewport.getMapPosition(mapPosition); - } + return mViewport.getMapPosition(mapPosition); + } - /** - * Get current {@link MapPosition}. Consider using - * getViewport.getMapPosition(pos) instead to reuse - * MapPosition instance. - */ - public MapPosition getMapPosition() { - MapPosition pos = new MapPosition(); - mViewport.getMapPosition(pos); - return pos; - } + /** + * Get current {@link MapPosition}. Consider using + * getViewport.getMapPosition(pos) instead to reuse + * MapPosition instance. + */ + public MapPosition getMapPosition() { + MapPosition pos = new MapPosition(); + mViewport.getMapPosition(pos); + return pos; + } - public BoundingBox getBoundingBox(int expand) { - Box box = new Box(); - mViewport.getBBox(box, expand); - box.map2mercator(); - return new BoundingBox(box.ymin, box.xmin, box.ymax, box.xmax); - } + public BoundingBox getBoundingBox(int expand) { + Box box = new Box(); + mViewport.getBBox(box, expand); + box.map2mercator(); + return new BoundingBox(box.ymin, box.xmin, box.ymax, box.xmax); + } - /** - * @return Viewport instance - */ - public ViewController viewport() { - return mViewport; - } + /** + * @return Viewport instance + */ + public ViewController viewport() { + return mViewport; + } - /** - * @return Layers instance - */ - public Layers layers() { - return mLayers; - } + /** + * @return Layers instance + */ + public Layers layers() { + return mLayers; + } - /** - * @return MapAnimator instance - */ - public Animator animator() { - return mAnimator; - } + /** + * @return MapAnimator instance + */ + public Animator animator() { + return mAnimator; + } - /** - * This function is run on main-thread before rendering a frame. - * - * For internal use only. Do not call! - */ - protected void prepareFrame() { - ThreadUtils.assertMainThread(); + /** + * This function is run on main-thread before rendering a frame. + *

+ * For internal use only. Do not call! + */ + protected void prepareFrame() { + ThreadUtils.assertMainThread(); - MapPosition pos = mMapPosition; + MapPosition pos = mMapPosition; - mAnimator.updateAnimation(); + mAnimator.updateAnimation(); - boolean changed = mViewport.getMapPosition(pos); + boolean changed = mViewport.getMapPosition(pos); - if (mClearMap) - events.fire(CLEAR_EVENT, pos); - else if (changed) - events.fire(POSITION_EVENT, pos); - else - events.fire(UPDATE_EVENT, pos); + if (mClearMap) + events.fire(CLEAR_EVENT, pos); + else if (changed) + events.fire(POSITION_EVENT, pos); + else + events.fire(UPDATE_EVENT, pos); - mClearMap = false; + mClearMap = false; - mAnimator.updateAnimation(); + mAnimator.updateAnimation(); - mViewport.syncViewport(); - } + mViewport.syncViewport(); + } - public boolean handleGesture(Gesture g, MotionEvent e) { - return mLayers.handleGesture(g, e); - } + public boolean handleGesture(Gesture g, MotionEvent e) { + return mLayers.handleGesture(g, e); + } - /** Called on render thread, use synchronized! */ - public abstract void beginFrame(); + /** + * Called on render thread, use synchronized! + */ + public abstract void beginFrame(); - /** Called on render thread, use synchronized! */ - public abstract void doneFrame(boolean needsRedraw); + /** + * Called on render thread, use synchronized! + */ + public abstract void doneFrame(boolean needsRedraw); } diff --git a/vtm/src/org/oscim/map/ViewController.java b/vtm/src/org/oscim/map/ViewController.java index 17b3a303..5b7ca085 100644 --- a/vtm/src/org/oscim/map/ViewController.java +++ b/vtm/src/org/oscim/map/ViewController.java @@ -16,8 +16,6 @@ */ package org.oscim.map; -import static org.oscim.utils.FastMath.clamp; - import org.oscim.core.MapPosition; import org.oscim.core.Point; import org.oscim.core.Tile; @@ -25,264 +23,268 @@ import org.oscim.renderer.GLMatrix; import org.oscim.utils.FastMath; import org.oscim.utils.ThreadUtils; +import static org.oscim.utils.FastMath.clamp; + public class ViewController extends Viewport { - protected float mPivotY = 0.0f; + protected float mPivotY = 0.0f; - private final float[] mat = new float[16]; + private final float[] mat = new float[16]; - public void setScreenSize(int width, int height) { - ThreadUtils.assertMainThread(); + public void setScreenSize(int width, int height) { + ThreadUtils.assertMainThread(); - mHeight = height; - mWidth = width; + mHeight = height; + mWidth = width; /* setup projection matrix: - * 0. scale to window coordinates + * 0. scale to window coordinates * 1. translate to VIEW_DISTANCE * 2. apply projection * setup inverse projection: * 0. invert projection * 1. invert translate to VIEW_DISTANCE */ - float ratio = (mHeight / mWidth) * VIEW_SCALE; + float ratio = (mHeight / mWidth) * VIEW_SCALE; - GLMatrix.frustumM(mat, 0, -VIEW_SCALE, VIEW_SCALE, - ratio, -ratio, VIEW_NEAR, VIEW_FAR); + GLMatrix.frustumM(mat, 0, -VIEW_SCALE, VIEW_SCALE, + ratio, -ratio, VIEW_NEAR, VIEW_FAR); - mProjMatrix.set(mat); + mProjMatrix.set(mat); - mTmpMatrix.setTranslation(0, 0, -VIEW_DISTANCE); - mProjMatrix.multiplyRhs(mTmpMatrix); + mTmpMatrix.setTranslation(0, 0, -VIEW_DISTANCE); + mProjMatrix.multiplyRhs(mTmpMatrix); /* set inverse projection matrix (without scaling) */ - mProjMatrix.get(mat); - GLMatrix.invertM(mat, 0, mat, 0); - mProjMatrixInverse.set(mat); + mProjMatrix.get(mat); + GLMatrix.invertM(mat, 0, mat, 0); + mProjMatrixInverse.set(mat); - mProjMatrixUnscaled.copy(mProjMatrix); + mProjMatrixUnscaled.copy(mProjMatrix); /* scale to window coordinates */ - mTmpMatrix.setScale(1 / mWidth, 1 / mWidth, 1 / mWidth); - mProjMatrix.multiplyRhs(mTmpMatrix); + mTmpMatrix.setScale(1 / mWidth, 1 / mWidth, 1 / mWidth); + mProjMatrix.multiplyRhs(mTmpMatrix); - updateMatrices(); - } + updateMatrices(); + } - /** - * Set pivot height relative to screen center. E.g. 0.5 is usually preferred - * for navigation, moving the center to 25% of the screen height. - * Range is [-1, 1]. - */ - public void setMapScreenCenter(float pivotY) { - mPivotY = FastMath.clamp(pivotY, -1, 1) * 0.5f; - } + /** + * Set pivot height relative to screen center. E.g. 0.5 is usually preferred + * for navigation, moving the center to 25% of the screen height. + * Range is [-1, 1]. + */ + public void setMapScreenCenter(float pivotY) { + mPivotY = FastMath.clamp(pivotY, -1, 1) * 0.5f; + } - /** - * Moves this Viewport by the given amount of pixels. - * - * @param mx the amount of pixels to move the map horizontally. - * @param my the amount of pixels to move the map vertically. - */ - public void moveMap(float mx, float my) { - ThreadUtils.assertMainThread(); + /** + * Moves this Viewport by the given amount of pixels. + * + * @param mx the amount of pixels to move the map horizontally. + * @param my the amount of pixels to move the map vertically. + */ + public void moveMap(float mx, float my) { + ThreadUtils.assertMainThread(); - Point p = applyRotation(mx, my); - double tileScale = mPos.scale * Tile.SIZE; - moveTo(mPos.x - p.x / tileScale, mPos.y - p.y / tileScale); - } + Point p = applyRotation(mx, my); + double tileScale = mPos.scale * Tile.SIZE; + moveTo(mPos.x - p.x / tileScale, mPos.y - p.y / tileScale); + } - /* used by MapAnimator */ - void moveTo(double x, double y) { - mPos.x = x; - mPos.y = y; + /* used by MapAnimator */ + void moveTo(double x, double y) { + mPos.x = x; + mPos.y = y; /* clamp latitude */ - mPos.y = FastMath.clamp(mPos.y, 0, 1); + mPos.y = FastMath.clamp(mPos.y, 0, 1); /* wrap longitude */ - while (mPos.x > 1) - mPos.x -= 1; - while (mPos.x < 0) - mPos.x += 1; + while (mPos.x > 1) + mPos.x -= 1; + while (mPos.x < 0) + mPos.x += 1; /* limit longitude */ - if (mPos.x > mMaxX) - mPos.x = mMaxX; - else if (mPos.x < mMinX) - mPos.x = mMinX; - /* limit latitude */ - if (mPos.y > mMaxY) - mPos.y = mMaxY; - else if (mPos.y < mMinY) - mPos.y = mMinY; - } + if (mPos.x > mMaxX) + mPos.x = mMaxX; + else if (mPos.x < mMinX) + mPos.x = mMinX; + /* limit latitude */ + if (mPos.y > mMaxY) + mPos.y = mMaxY; + else if (mPos.y < mMinY) + mPos.y = mMinY; + } - private Point applyRotation(double mx, double my) { - if (mPos.bearing == 0) { - mMovePoint.x = mx; - mMovePoint.y = my; - } else { - double rad = Math.toRadians(mPos.bearing); - double rcos = Math.cos(rad); - double rsin = Math.sin(rad); - mMovePoint.x = mx * rcos + my * rsin; - mMovePoint.y = mx * -rsin + my * rcos; - } - return mMovePoint; - } + private Point applyRotation(double mx, double my) { + if (mPos.bearing == 0) { + mMovePoint.x = mx; + mMovePoint.y = my; + } else { + double rad = Math.toRadians(mPos.bearing); + double rcos = Math.cos(rad); + double rsin = Math.sin(rad); + mMovePoint.x = mx * rcos + my * rsin; + mMovePoint.y = mx * -rsin + my * rcos; + } + return mMovePoint; + } - /** - * Scale map by scale width center at pivot in pixel relative to - * screen center. Map scale is clamp to MIN_SCALE and MAX_SCALE. - * - * @param scale - * @param pivotX - * @param pivotY - * @return true if scale was changed - */ - public boolean scaleMap(float scale, float pivotX, float pivotY) { - ThreadUtils.assertMainThread(); + /** + * Scale map by scale width center at pivot in pixel relative to + * screen center. Map scale is clamp to MIN_SCALE and MAX_SCALE. + * + * @param scale + * @param pivotX + * @param pivotY + * @return true if scale was changed + */ + public boolean scaleMap(float scale, float pivotX, float pivotY) { + ThreadUtils.assertMainThread(); - // just sanitize input - //scale = FastMath.clamp(scale, 0.5f, 2); - if (scale < 0.000001) - return false; + // just sanitize input + //scale = FastMath.clamp(scale, 0.5f, 2); + if (scale < 0.000001) + return false; - double newScale = mPos.scale * scale; + double newScale = mPos.scale * scale; - newScale = clamp(newScale, mMinScale, mMaxScale); + newScale = clamp(newScale, mMinScale, mMaxScale); - if (newScale == mPos.scale) - return false; + if (newScale == mPos.scale) + return false; - scale = (float) (newScale / mPos.scale); + scale = (float) (newScale / mPos.scale); - mPos.scale = newScale; + mPos.scale = newScale; - if (pivotX != 0 || pivotY != 0) { - pivotY -= mHeight * mPivotY; + if (pivotX != 0 || pivotY != 0) { + pivotY -= mHeight * mPivotY; - moveMap(pivotX * (1.0f - scale), - pivotY * (1.0f - scale)); - } - return true; - } + moveMap(pivotX * (1.0f - scale), + pivotY * (1.0f - scale)); + } + return true; + } - /** - * Rotate map by radians around pivot. Pivot is in pixel relative - * to screen center. - * - * @param radians - * @param pivotX - * @param pivotY - */ - public void rotateMap(double radians, float pivotX, float pivotY) { - ThreadUtils.assertMainThread(); + /** + * Rotate map by radians around pivot. Pivot is in pixel relative + * to screen center. + * + * @param radians + * @param pivotX + * @param pivotY + */ + public void rotateMap(double radians, float pivotX, float pivotY) { + ThreadUtils.assertMainThread(); - double rsin = Math.sin(radians); - double rcos = Math.cos(radians); + double rsin = Math.sin(radians); + double rcos = Math.cos(radians); - pivotY -= mHeight * mPivotY; + pivotY -= mHeight * mPivotY; - float x = (float) (pivotX - pivotX * rcos + pivotY * rsin); - float y = (float) (pivotY - pivotX * rsin - pivotY * rcos); + float x = (float) (pivotX - pivotX * rcos + pivotY * rsin); + float y = (float) (pivotY - pivotX * rsin - pivotY * rcos); - moveMap(x, y); + moveMap(x, y); - setRotation(mPos.bearing + Math.toDegrees(radians)); - } + setRotation(mPos.bearing + Math.toDegrees(radians)); + } - public void setRotation(double degree) { - ThreadUtils.assertMainThread(); + public void setRotation(double degree) { + ThreadUtils.assertMainThread(); - while (degree > 180) - degree -= 360; - while (degree < -180) - degree += 360; + while (degree > 180) + degree -= 360; + while (degree < -180) + degree += 360; - mPos.bearing = (float) degree; + mPos.bearing = (float) degree; - updateMatrices(); - } + updateMatrices(); + } - public boolean tiltMap(float move) { - return setTilt(mPos.tilt + move); - } + public boolean tiltMap(float move) { + return setTilt(mPos.tilt + move); + } - public boolean setTilt(float tilt) { - ThreadUtils.assertMainThread(); + public boolean setTilt(float tilt) { + ThreadUtils.assertMainThread(); - tilt = limitTilt(tilt); - if (tilt == mPos.tilt) - return false; + tilt = limitTilt(tilt); + if (tilt == mPos.tilt) + return false; - mPos.tilt = tilt; - updateMatrices(); - return true; - } + mPos.tilt = tilt; + updateMatrices(); + return true; + } - public void setMapPosition(MapPosition mapPosition) { - ThreadUtils.assertMainThread(); + public void setMapPosition(MapPosition mapPosition) { + ThreadUtils.assertMainThread(); - mPos.copy(mapPosition); - limitPosition(mPos); + mPos.copy(mapPosition); + limitPosition(mPos); - // mPos.scale = clamp(mapPosition.scale, mMinScale, mMaxScale); - // mPos.x = mapPosition.x; - // mPos.y = mapPosition.y; - // mPos.tilt = limitTilt(mapPosition.tilt); - // mPos.bearing = mapPosition.bearing; + // mPos.scale = clamp(mapPosition.scale, mMinScale, mMaxScale); + // mPos.x = mapPosition.x; + // mPos.y = mapPosition.y; + // mPos.tilt = limitTilt(mapPosition.tilt); + // mPos.bearing = mapPosition.bearing; - updateMatrices(); - } + updateMatrices(); + } - private void updateMatrices() { + private void updateMatrices() { /* - view matrix: * 0. apply rotate * 1. apply tilt */ - mRotationMatrix.setRotation(mPos.bearing, 0, 0, 1); - mTmpMatrix.setRotation(mPos.tilt, 1, 0, 0); + mRotationMatrix.setRotation(mPos.bearing, 0, 0, 1); + mTmpMatrix.setRotation(mPos.tilt, 1, 0, 0); /* apply first rotation, then tilt */ - mRotationMatrix.multiplyLhs(mTmpMatrix); + mRotationMatrix.multiplyLhs(mTmpMatrix); - mViewMatrix.copy(mRotationMatrix); + mViewMatrix.copy(mRotationMatrix); - mTmpMatrix.setTranslation(0, mPivotY * mHeight, 0); - mViewMatrix.multiplyLhs(mTmpMatrix); + mTmpMatrix.setTranslation(0, mPivotY * mHeight, 0); + mViewMatrix.multiplyLhs(mTmpMatrix); - mViewProjMatrix.multiplyMM(mProjMatrix, mViewMatrix); + mViewProjMatrix.multiplyMM(mProjMatrix, mViewMatrix); - mViewProjMatrix.get(mat); - GLMatrix.invertM(mat, 0, mat, 0); - mUnprojMatrix.set(mat); - } + mViewProjMatrix.get(mat); + GLMatrix.invertM(mat, 0, mat, 0); + mUnprojMatrix.set(mat); + } - public final Viewport mNextFrame = new Viewport(); + public final Viewport mNextFrame = new Viewport(); - /** synchronize on this object when doing multiple calls on it */ - public final Viewport getSyncViewport() { - return mNextFrame; - } + /** + * synchronize on this object when doing multiple calls on it + */ + public final Viewport getSyncViewport() { + return mNextFrame; + } - void syncViewport() { - synchronized (mNextFrame) { - mNextFrame.copy(this); - } - } + void syncViewport() { + synchronized (mNextFrame) { + mNextFrame.copy(this); + } + } - public boolean getSyncViewport(Viewport v) { - synchronized (mNextFrame) { - return v.copy(mNextFrame); - } - } + public boolean getSyncViewport(Viewport v) { + synchronized (mNextFrame) { + return v.copy(mNextFrame); + } + } - public boolean getSyncMapPosition(MapPosition mapPosition) { - synchronized (mNextFrame) { - return mNextFrame.getMapPosition(mapPosition); - } - } + public boolean getSyncMapPosition(MapPosition mapPosition) { + synchronized (mNextFrame) { + return mNextFrame.getMapPosition(mapPosition); + } + } } diff --git a/vtm/src/org/oscim/map/Viewport.java b/vtm/src/org/oscim/map/Viewport.java index 5dbe068b..7d9d0267 100644 --- a/vtm/src/org/oscim/map/Viewport.java +++ b/vtm/src/org/oscim/map/Viewport.java @@ -32,444 +32,445 @@ import org.slf4j.LoggerFactory; * The Viewport class contains a MapPosition and the projection matrices. * It provides functions to modify the MapPosition and translate between * map and screen coordinates. - *

+ *

* Public methods are thread safe. */ public class Viewport { - static final Logger log = LoggerFactory.getLogger(Viewport.class); + static final Logger log = LoggerFactory.getLogger(Viewport.class); - private final static int MAX_ZOOMLEVEL = 20; - private final static int MIN_ZOOMLEVEL = 2; - private final static float MIN_TILT = 0; - private final static float MAX_TILT = 65; + private final static int MAX_ZOOMLEVEL = 20; + private final static int MIN_ZOOMLEVEL = 2; + private final static float MIN_TILT = 0; + private final static float MAX_TILT = 65; - protected double mMaxScale = (1 << MAX_ZOOMLEVEL); - protected double mMinScale = (1 << MIN_ZOOMLEVEL); + protected double mMaxScale = (1 << MAX_ZOOMLEVEL); + protected double mMinScale = (1 << MIN_ZOOMLEVEL); - protected float mMinTilt = MIN_TILT; - protected float mMaxTilt = MAX_TILT; + protected float mMinTilt = MIN_TILT; + protected float mMaxTilt = MAX_TILT; - protected float mMinBearing = -180; - protected float mMaxBearing = 180; + protected float mMinBearing = -180; + protected float mMaxBearing = 180; - protected double mMinX = 0; - protected double mMaxX = 1; - protected double mMinY = 0; - protected double mMaxY = 1; + protected double mMinX = 0; + protected double mMaxX = 1; + protected double mMinY = 0; + protected double mMaxY = 1; - protected final MapPosition mPos = new MapPosition(); + protected final MapPosition mPos = new MapPosition(); - protected final GLMatrix mProjMatrix = new GLMatrix(); - protected final GLMatrix mProjMatrixUnscaled = new GLMatrix(); - protected final GLMatrix mProjMatrixInverse = new GLMatrix(); - protected final GLMatrix mRotationMatrix = new GLMatrix(); - protected final GLMatrix mViewMatrix = new GLMatrix(); - protected final GLMatrix mViewProjMatrix = new GLMatrix(); - protected final GLMatrix mUnprojMatrix = new GLMatrix(); - protected final GLMatrix mTmpMatrix = new GLMatrix(); + protected final GLMatrix mProjMatrix = new GLMatrix(); + protected final GLMatrix mProjMatrixUnscaled = new GLMatrix(); + protected final GLMatrix mProjMatrixInverse = new GLMatrix(); + protected final GLMatrix mRotationMatrix = new GLMatrix(); + protected final GLMatrix mViewMatrix = new GLMatrix(); + protected final GLMatrix mViewProjMatrix = new GLMatrix(); + protected final GLMatrix mUnprojMatrix = new GLMatrix(); + protected final GLMatrix mTmpMatrix = new GLMatrix(); - /* temporary vars: only use in synchronized functions! */ - protected final Point mMovePoint = new Point(); - protected final float[] mv = new float[4]; - protected final float[] mu = new float[4]; - protected final float[] mViewCoords = new float[8]; + /* temporary vars: only use in synchronized functions! */ + protected final Point mMovePoint = new Point(); + protected final float[] mv = new float[4]; + protected final float[] mu = new float[4]; + protected final float[] mViewCoords = new float[8]; - protected float mHeight, mWidth; + protected float mHeight, mWidth; - public final static float VIEW_DISTANCE = 3.0f; - public final static float VIEW_NEAR = 1; - public final static float VIEW_FAR = 8; - /** scale map plane at VIEW_DISTANCE to near plane */ - public final static float VIEW_SCALE = (VIEW_NEAR / VIEW_DISTANCE) * 0.5f; + public final static float VIEW_DISTANCE = 3.0f; + public final static float VIEW_NEAR = 1; + public final static float VIEW_FAR = 8; + /** + * scale map plane at VIEW_DISTANCE to near plane + */ + public final static float VIEW_SCALE = (VIEW_NEAR / VIEW_DISTANCE) * 0.5f; - public Viewport() { - mPos.scale = mMinScale; - mPos.x = 0.5; - mPos.y = 0.5; - mPos.bearing = 0; - mPos.tilt = 0; - } + public Viewport() { + mPos.scale = mMinScale; + mPos.x = 0.5; + mPos.y = 0.5; + mPos.bearing = 0; + mPos.tilt = 0; + } - public double limitScale(double scale) { - if (scale > mMaxScale) - return mMaxScale; - else if (scale < mMinScale) - return mMinScale; + public double limitScale(double scale) { + if (scale > mMaxScale) + return mMaxScale; + else if (scale < mMinScale) + return mMinScale; - return scale; - } + return scale; + } - public float limitTilt(float tilt) { - if (tilt > mMaxTilt) - return mMaxTilt; - else if (tilt < mMinTilt) - return mMinTilt; + public float limitTilt(float tilt) { + if (tilt > mMaxTilt) + return mMaxTilt; + else if (tilt < mMinTilt) + return mMinTilt; - return tilt; - } + return tilt; + } - public boolean limitPosition(MapPosition pos) { - boolean changed = false; - if (pos.scale > mMaxScale) { - pos.scale = mMaxScale; - changed = true; - } else if (pos.scale < mMinScale) { - pos.scale = mMinScale; - changed = true; - } + public boolean limitPosition(MapPosition pos) { + boolean changed = false; + if (pos.scale > mMaxScale) { + pos.scale = mMaxScale; + changed = true; + } else if (pos.scale < mMinScale) { + pos.scale = mMinScale; + changed = true; + } - if (pos.tilt > mMaxTilt) { - pos.tilt = mMaxTilt; - changed = true; - } else if (pos.tilt < mMinTilt) { - pos.tilt = mMinTilt; - changed = true; - } + if (pos.tilt > mMaxTilt) { + pos.tilt = mMaxTilt; + changed = true; + } else if (pos.tilt < mMinTilt) { + pos.tilt = mMinTilt; + changed = true; + } - if (pos.bearing > mMaxBearing) { - pos.bearing = mMaxBearing; - changed = true; - } else if (pos.bearing < mMinBearing) { - pos.bearing = mMinBearing; - changed = true; - } + if (pos.bearing > mMaxBearing) { + pos.bearing = mMaxBearing; + changed = true; + } else if (pos.bearing < mMinBearing) { + pos.bearing = mMinBearing; + changed = true; + } - if (pos.x > mMaxX) { - pos.x = mMaxX; - changed = true; - } else if (pos.x < mMinX) { - pos.x = mMinX; - changed = true; - } + if (pos.x > mMaxX) { + pos.x = mMaxX; + changed = true; + } else if (pos.x < mMinX) { + pos.x = mMinX; + changed = true; + } - if (pos.y > mMaxY) { - pos.y = mMaxY; - changed = true; - } else if (pos.y < mMinY) { - pos.y = mMinY; - changed = true; - } + if (pos.y > mMaxY) { + pos.y = mMaxY; + changed = true; + } else if (pos.y < mMinY) { + pos.y = mMinY; + changed = true; + } - return changed; - } + return changed; + } - /** - * Get the current MapPosition. - * - * @param pos MapPosition to be updated. - * - * @return true iff current position is different from - * passed position. - */ - public boolean getMapPosition(MapPosition pos) { + /** + * Get the current MapPosition. + * + * @param pos MapPosition to be updated. + * @return true iff current position is different from + * passed position. + */ + public boolean getMapPosition(MapPosition pos) { - boolean changed = (pos.scale != mPos.scale - || pos.x != mPos.x - || pos.y != mPos.y - || pos.bearing != mPos.bearing - || pos.tilt != mPos.tilt); + boolean changed = (pos.scale != mPos.scale + || pos.x != mPos.x + || pos.y != mPos.y + || pos.bearing != mPos.bearing + || pos.tilt != mPos.tilt); - pos.bearing = mPos.bearing; - pos.tilt = mPos.tilt; + pos.bearing = mPos.bearing; + pos.tilt = mPos.tilt; - pos.x = mPos.x; - pos.y = mPos.y; - pos.scale = mPos.scale; - pos.zoomLevel = FastMath.log2((int) mPos.scale); + pos.x = mPos.x; + pos.y = mPos.y; + pos.scale = mPos.scale; + pos.zoomLevel = FastMath.log2((int) mPos.scale); - return changed; - } + return changed; + } - /** - * Get the inverse projection of the viewport, i.e. the - * coordinates with z==0 that will be projected exactly - * to screen corners by current view-projection-matrix. - * - * @param box float[8] will be set. - * @param add increase extents of box - */ - public void getMapExtents(float[] box, float add) { - /* top-right */ - unproject(1, -1, box, 0); - /* top-left */ - unproject(-1, -1, box, 2); + /** + * Get the inverse projection of the viewport, i.e. the + * coordinates with z==0 that will be projected exactly + * to screen corners by current view-projection-matrix. + * + * @param box float[8] will be set. + * @param add increase extents of box + */ + public void getMapExtents(float[] box, float add) { + /* top-right */ + unproject(1, -1, box, 0); + /* top-left */ + unproject(-1, -1, box, 2); /* bottom-left */ - unproject(-1, 1, box, 4); + unproject(-1, 1, box, 4); /* bottom-right */ - unproject(1, 1, box, 6); + unproject(1, 1, box, 6); - if (add == 0) - return; + if (add == 0) + return; - for (int i = 0; i < 8; i += 2) { - float x = box[i]; - float y = box[i + 1]; - float len = (float) Math.sqrt(x * x + y * y); - box[i + 0] += x / len * add; - box[i + 1] += y / len * add; - } - } + for (int i = 0; i < 8; i += 2) { + float x = box[i]; + float y = box[i + 1]; + float len = (float) Math.sqrt(x * x + y * y); + box[i + 0] += x / len * add; + box[i + 1] += y / len * add; + } + } - protected void unproject(float x, float y, float[] coords, int position) { - mv[0] = x; - mv[1] = y; - mv[2] = -1; - mUnprojMatrix.prj(mv); - double nx = mv[0]; - double ny = mv[1]; - double nz = mv[2]; + protected void unproject(float x, float y, float[] coords, int position) { + mv[0] = x; + mv[1] = y; + mv[2] = -1; + mUnprojMatrix.prj(mv); + double nx = mv[0]; + double ny = mv[1]; + double nz = mv[2]; - mv[0] = x; - mv[1] = y; - mv[2] = 1; - mUnprojMatrix.prj(mv); - double fx = mv[0]; - double fy = mv[1]; - double fz = mv[2]; + mv[0] = x; + mv[1] = y; + mv[2] = 1; + mUnprojMatrix.prj(mv); + double fx = mv[0]; + double fy = mv[1]; + double fz = mv[2]; - double dx = fx - nx; - double dy = fy - ny; - double dz = fz - nz; + double dx = fx - nx; + double dy = fy - ny; + double dz = fz - nz; - double dist = -nz / dz; + double dist = -nz / dz; - coords[position + 0] = (float) (nx + dist * dx); - coords[position + 1] = (float) (ny + dist * dy); - } + coords[position + 0] = (float) (nx + dist * dx); + coords[position + 1] = (float) (ny + dist * dy); + } - /** - * Get the minimal axis-aligned BoundingBox that encloses - * the visible part of the map. Sets box to map coordinates: - * xmin,ymin,xmax,ymax - */ - public Box getBBox(Box box, int expand) { - if (box == null) - box = new Box(); + /** + * Get the minimal axis-aligned BoundingBox that encloses + * the visible part of the map. Sets box to map coordinates: + * xmin,ymin,xmax,ymax + */ + public Box getBBox(Box box, int expand) { + if (box == null) + box = new Box(); - float[] coords = mViewCoords; - getMapExtents(coords, expand); + float[] coords = mViewCoords; + getMapExtents(coords, expand); - box.xmin = coords[0]; - box.xmax = coords[0]; - box.ymin = coords[1]; - box.ymax = coords[1]; + box.xmin = coords[0]; + box.xmax = coords[0]; + box.ymin = coords[1]; + box.ymax = coords[1]; - for (int i = 2; i < 8; i += 2) { - box.xmin = Math.min(box.xmin, coords[i]); - box.xmax = Math.max(box.xmax, coords[i]); - box.ymin = Math.min(box.ymin, coords[i + 1]); - box.ymax = Math.max(box.ymax, coords[i + 1]); - } + for (int i = 2; i < 8; i += 2) { + box.xmin = Math.min(box.xmin, coords[i]); + box.xmax = Math.max(box.xmax, coords[i]); + box.ymin = Math.min(box.ymin, coords[i + 1]); + box.ymax = Math.max(box.ymax, coords[i + 1]); + } - double cs = mPos.scale * Tile.SIZE; - double cx = mPos.x * cs; - double cy = mPos.y * cs; + double cs = mPos.scale * Tile.SIZE; + double cx = mPos.x * cs; + double cy = mPos.y * cs; - box.xmin = (cx + box.xmin) / cs; - box.xmax = (cx + box.xmax) / cs; - box.ymin = (cy + box.ymin) / cs; - box.ymax = (cy + box.ymax) / cs; + box.xmin = (cx + box.xmin) / cs; + box.xmax = (cx + box.xmax) / cs; + box.ymin = (cy + box.ymin) / cs; + box.ymax = (cy + box.ymax) / cs; - return box; - } + return box; + } - /** - * Get the GeoPoint for x,y in screen coordinates. - * - * @param x screen coordinate - * @param y screen coordinate - * @return the corresponding GeoPoint - */ - public GeoPoint fromScreenPoint(float x, float y) { - fromScreenPoint(x, y, mMovePoint); - return new GeoPoint( - MercatorProjection.toLatitude(mMovePoint.y), - MercatorProjection.toLongitude(mMovePoint.x)); - } + /** + * Get the GeoPoint for x,y in screen coordinates. + * + * @param x screen coordinate + * @param y screen coordinate + * @return the corresponding GeoPoint + */ + public GeoPoint fromScreenPoint(float x, float y) { + fromScreenPoint(x, y, mMovePoint); + return new GeoPoint( + MercatorProjection.toLatitude(mMovePoint.y), + MercatorProjection.toLongitude(mMovePoint.x)); + } - protected void unprojectScreen(double x, double y, float[] out) { + protected void unprojectScreen(double x, double y, float[] out) { /* scale to -1..1 */ - float mx = (float) (1 - (x / mWidth * 2)); - float my = (float) (1 - (y / mHeight * 2)); + float mx = (float) (1 - (x / mWidth * 2)); + float my = (float) (1 - (y / mHeight * 2)); - unproject(-mx, my, out, 0); - } + unproject(-mx, my, out, 0); + } - /** - * Get the map position for x,y in screen coordinates. - * - * @param x screen coordinate - * @param y screen coordinate - */ - public void fromScreenPoint(double x, double y, Point out) { - unprojectScreen(x, y, mu); + /** + * Get the map position for x,y in screen coordinates. + * + * @param x screen coordinate + * @param y screen coordinate + */ + public void fromScreenPoint(double x, double y, Point out) { + unprojectScreen(x, y, mu); - double cs = mPos.scale * Tile.SIZE; - double cx = mPos.x * cs; - double cy = mPos.y * cs; + double cs = mPos.scale * Tile.SIZE; + double cx = mPos.x * cs; + double cy = mPos.y * cs; - double dx = cx + mu[0]; - double dy = cy + mu[1]; + double dx = cx + mu[0]; + double dy = cy + mu[1]; - dx /= cs; - dy /= cs; + dx /= cs; + dy /= cs; - while (dx > 1) - dx -= 1; - while (dx < 0) - dx += 1; + while (dx > 1) + dx -= 1; + while (dx < 0) + dx += 1; - if (dy > 1) - dy = 1; - else if (dy < 0) - dy = 0; + if (dy > 1) + dy = 1; + else if (dy < 0) + dy = 0; - out.x = dx; - out.y = dy; - } + out.x = dx; + out.y = dy; + } - /** - * Get the screen pixel for a GeoPoint - * - * @param geoPoint the GeoPoint - * @param out Point projected to screen pixel relative to center - */ - public void toScreenPoint(GeoPoint geoPoint, Point out) { - MercatorProjection.project(geoPoint, out); - toScreenPoint(out.x, out.y, out); - } + /** + * Get the screen pixel for a GeoPoint + * + * @param geoPoint the GeoPoint + * @param out Point projected to screen pixel relative to center + */ + public void toScreenPoint(GeoPoint geoPoint, Point out) { + MercatorProjection.project(geoPoint, out); + toScreenPoint(out.x, out.y, out); + } - /** - * Get the screen pixel for map coordinates - * - * @param out Point projected to screen coordinate - */ - public void toScreenPoint(double x, double y, Point out) { + /** + * Get the screen pixel for map coordinates + * + * @param out Point projected to screen coordinate + */ + public void toScreenPoint(double x, double y, Point out) { - double cs = mPos.scale * Tile.SIZE; - double cx = mPos.x * cs; - double cy = mPos.y * cs; + double cs = mPos.scale * Tile.SIZE; + double cx = mPos.x * cs; + double cy = mPos.y * cs; - mv[0] = (float) (x * cs - cx); - mv[1] = (float) (y * cs - cy); + mv[0] = (float) (x * cs - cx); + mv[1] = (float) (y * cs - cy); - mv[2] = 0; - mv[3] = 1; + mv[2] = 0; + mv[3] = 1; - mViewProjMatrix.prj(mv); + mViewProjMatrix.prj(mv); - out.x = (mv[0] * (mWidth / 2)); - out.y = -(mv[1] * (mHeight / 2)); - } + out.x = (mv[0] * (mWidth / 2)); + out.y = -(mv[1] * (mHeight / 2)); + } - protected boolean copy(Viewport viewport) { - mHeight = viewport.mHeight; - mWidth = viewport.mWidth; - mProjMatrix.copy(viewport.mProjMatrix); - mProjMatrixUnscaled.copy(viewport.mProjMatrixUnscaled); - mProjMatrixInverse.copy(viewport.mProjMatrixInverse); + protected boolean copy(Viewport viewport) { + mHeight = viewport.mHeight; + mWidth = viewport.mWidth; + mProjMatrix.copy(viewport.mProjMatrix); + mProjMatrixUnscaled.copy(viewport.mProjMatrixUnscaled); + mProjMatrixInverse.copy(viewport.mProjMatrixInverse); - mUnprojMatrix.copy(viewport.mUnprojMatrix); - mRotationMatrix.copy(viewport.mRotationMatrix); - mViewMatrix.copy(viewport.mViewMatrix); - mViewProjMatrix.copy(viewport.mViewProjMatrix); - return viewport.getMapPosition(mPos); - } + mUnprojMatrix.copy(viewport.mUnprojMatrix); + mRotationMatrix.copy(viewport.mRotationMatrix); + mViewMatrix.copy(viewport.mViewMatrix); + mViewProjMatrix.copy(viewport.mViewProjMatrix); + return viewport.getMapPosition(mPos); + } - public double getMaxScale() { - return mMaxScale; - } + public double getMaxScale() { + return mMaxScale; + } - public void setMaxScale(double maxScale) { - this.mMaxScale = maxScale; - } + public void setMaxScale(double maxScale) { + this.mMaxScale = maxScale; + } - public double getMinScale() { - return mMinScale; - } + public double getMinScale() { + return mMinScale; + } - public void setMinScale(double minScale) { - this.mMinScale = minScale; - } + public void setMinScale(double minScale) { + this.mMinScale = minScale; + } - public int getMaxZoomLevel() { - return FastMath.log2((int) mMaxScale); - } + public int getMaxZoomLevel() { + return FastMath.log2((int) mMaxScale); + } - public void setMaxZoomLevel(int maxZoomLevel) { - this.mMaxScale = (1 << maxZoomLevel); - } + public void setMaxZoomLevel(int maxZoomLevel) { + this.mMaxScale = (1 << maxZoomLevel); + } - public int getMinZoomLevel() { - return FastMath.log2((int) mMinScale); - } + public int getMinZoomLevel() { + return FastMath.log2((int) mMinScale); + } - public void setMinZoomLevel(int minZoomLevel) { - this.mMinScale = (1 << minZoomLevel); - } + public void setMinZoomLevel(int minZoomLevel) { + this.mMinScale = (1 << minZoomLevel); + } - public float getMaxTilt() { - return mMaxTilt; - } + public float getMaxTilt() { + return mMaxTilt; + } - public void setMaxTilt(float maxTilt) { - this.mMaxTilt = maxTilt; - } + public void setMaxTilt(float maxTilt) { + this.mMaxTilt = maxTilt; + } - public float getMinTilt() { - return mMinTilt; - } + public float getMinTilt() { + return mMinTilt; + } - public void setMinTilt(float minTilt) { - this.mMinTilt = minTilt; - } + public void setMinTilt(float minTilt) { + this.mMinTilt = minTilt; + } - public float getMaxBearing() { - return mMaxBearing; - } + public float getMaxBearing() { + return mMaxBearing; + } - public void setMaxBearing(float maxBearing) { - this.mMaxBearing = maxBearing; - } + public void setMaxBearing(float maxBearing) { + this.mMaxBearing = maxBearing; + } - public float getMinBearing() { - return mMinBearing; - } + public float getMinBearing() { + return mMinBearing; + } - public void setMinBearing(float minBearing) { - this.mMinBearing = minBearing; - } + public void setMinBearing(float minBearing) { + this.mMinBearing = minBearing; + } - public double getMaxX() { - return mMaxX; - } + public double getMaxX() { + return mMaxX; + } - public void setMaxX(double maxX) { - this.mMaxX = maxX; - } + public void setMaxX(double maxX) { + this.mMaxX = maxX; + } - public double getMinX() { - return mMinX; - } + public double getMinX() { + return mMinX; + } - public void setMinX(double minX) { - this.mMinX = minX; - } + public void setMinX(double minX) { + this.mMinX = minX; + } - public double getMaxY() { - return mMaxY; - } + public double getMaxY() { + return mMaxY; + } - public void setMaxY(double maxY) { - this.mMaxY = maxY; - } + public void setMaxY(double maxY) { + this.mMaxY = maxY; + } - public double getMinY() { - return mMinY; - } + public double getMinY() { + return mMinY; + } - public void setMinY(double minY) { - this.mMinY = minY; - } + public void setMinY(double minY) { + this.mMinY = minY; + } } diff --git a/vtm/src/org/oscim/renderer/BitmapRenderer.java b/vtm/src/org/oscim/renderer/BitmapRenderer.java index ce64ee12..8ad96af0 100644 --- a/vtm/src/org/oscim/renderer/BitmapRenderer.java +++ b/vtm/src/org/oscim/renderer/BitmapRenderer.java @@ -26,64 +26,61 @@ import org.oscim.renderer.bucket.BitmapBucket; */ public class BitmapRenderer extends BucketRenderer { - private Bitmap mBitmap; - private int mWidth; - private int mHeight; - private boolean initialized; - private boolean mUpdateBitmap; + private Bitmap mBitmap; + private int mWidth; + private int mHeight; + private boolean initialized; + private boolean mUpdateBitmap; - /** - * @param bitmap - * with dimension being power of two - * @param srcWidth - * TODO width used - * @param srcHeight - * TODO height used - */ - public synchronized void setBitmap(Bitmap bitmap, - int srcWidth, int srcHeight, - int targetWidth, int targetHeight) { - mWidth = targetWidth; - mHeight = targetHeight; - mBitmap = bitmap; - initialized = false; - } + /** + * @param bitmap with dimension being power of two + * @param srcWidth TODO width used + * @param srcHeight TODO height used + */ + public synchronized void setBitmap(Bitmap bitmap, + int srcWidth, int srcHeight, + int targetWidth, int targetHeight) { + mWidth = targetWidth; + mHeight = targetHeight; + mBitmap = bitmap; + initialized = false; + } - public synchronized void updateBitmap() { - mUpdateBitmap = true; - } + public synchronized void updateBitmap() { + mUpdateBitmap = true; + } - @Override - public synchronized void update(GLViewport v) { - if (!initialized) { - buckets.clear(); + @Override + public synchronized void update(GLViewport v) { + if (!initialized) { + buckets.clear(); - BitmapBucket l = new BitmapBucket(true); - l.setBitmap(mBitmap, mWidth, mHeight); - buckets.set(l); + BitmapBucket l = new BitmapBucket(true); + l.setBitmap(mBitmap, mWidth, mHeight); + buckets.set(l); - mUpdateBitmap = true; - } + mUpdateBitmap = true; + } - if (mUpdateBitmap) { - mUpdateBitmap = false; - compile(); - } - } + if (mUpdateBitmap) { + mUpdateBitmap = false; + compile(); + } + } - @Override - protected synchronized void compile() { - if (mBitmap == null) - return; + @Override + protected synchronized void compile() { + if (mBitmap == null) + return; - synchronized (mBitmap) { - super.compile(); - } - } + synchronized (mBitmap) { + super.compile(); + } + } - @Override - public synchronized void render(GLViewport v) { - v.useScreenCoordinates(false, 8); - BitmapBucket.Renderer.draw(buckets.get(), v, 1, 1); - } + @Override + public synchronized void render(GLViewport v) { + v.useScreenCoordinates(false, 8); + BitmapBucket.Renderer.draw(buckets.get(), v, 1, 1); + } } diff --git a/vtm/src/org/oscim/renderer/BucketRenderer.java b/vtm/src/org/oscim/renderer/BucketRenderer.java index 41fd29ac..678a324c 100644 --- a/vtm/src/org/oscim/renderer/BucketRenderer.java +++ b/vtm/src/org/oscim/renderer/BucketRenderer.java @@ -16,14 +16,6 @@ */ package org.oscim.renderer; -import static org.oscim.renderer.bucket.RenderBucket.BITMAP; -import static org.oscim.renderer.bucket.RenderBucket.HAIRLINE; -import static org.oscim.renderer.bucket.RenderBucket.LINE; -import static org.oscim.renderer.bucket.RenderBucket.MESH; -import static org.oscim.renderer.bucket.RenderBucket.POLYGON; -import static org.oscim.renderer.bucket.RenderBucket.SYMBOL; -import static org.oscim.renderer.bucket.RenderBucket.TEXLINE; - import org.oscim.core.MapPosition; import org.oscim.core.Tile; import org.oscim.renderer.bucket.BitmapBucket; @@ -38,165 +30,175 @@ import org.oscim.renderer.bucket.TextureBucket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.renderer.bucket.RenderBucket.BITMAP; +import static org.oscim.renderer.bucket.RenderBucket.HAIRLINE; +import static org.oscim.renderer.bucket.RenderBucket.LINE; +import static org.oscim.renderer.bucket.RenderBucket.MESH; +import static org.oscim.renderer.bucket.RenderBucket.POLYGON; +import static org.oscim.renderer.bucket.RenderBucket.SYMBOL; +import static org.oscim.renderer.bucket.RenderBucket.TEXLINE; + /** * Base class to use the renderer.elements for drawing. - * + *

* All methods that modify 'buckets' MUST be synchronized! */ public class BucketRenderer extends LayerRenderer { - public static final Logger log = LoggerFactory.getLogger(BucketRenderer.class); + public static final Logger log = LoggerFactory.getLogger(BucketRenderer.class); - /** - * Use mMapPosition.copy(position) to keep the position for which - * the Overlay is *compiled*. NOTE: required by setMatrix utility - * functions to draw this layer fixed to the map - */ - protected MapPosition mMapPosition; + /** + * Use mMapPosition.copy(position) to keep the position for which + * the Overlay is *compiled*. NOTE: required by setMatrix utility + * functions to draw this layer fixed to the map + */ + protected MapPosition mMapPosition; - /** Wrap around dateline */ - protected boolean mFlipOnDateLine = true; + /** + * Wrap around dateline + */ + protected boolean mFlipOnDateLine = true; - /** Buckets for rendering */ - public final RenderBuckets buckets; + /** + * Buckets for rendering + */ + public final RenderBuckets buckets; - public BucketRenderer() { - buckets = new RenderBuckets(); - mMapPosition = new MapPosition(); - } + public BucketRenderer() { + buckets = new RenderBuckets(); + mMapPosition = new MapPosition(); + } - protected boolean mInititialzed; + protected boolean mInititialzed; - /** - * Default implementation: - * Copy initial Viewport position and compile buckets. - */ - @Override - public void update(GLViewport v) { - if (!mInititialzed) { - mMapPosition.copy(v.pos); - mInititialzed = true; - compile(); - } - } + /** + * Default implementation: + * Copy initial Viewport position and compile buckets. + */ + @Override + public void update(GLViewport v) { + if (!mInititialzed) { + mMapPosition.copy(v.pos); + mInititialzed = true; + compile(); + } + } - /** - * Render all 'buckets' - */ - @Override - public synchronized void render(GLViewport v) { - MapPosition layerPos = mMapPosition; + /** + * Render all 'buckets' + */ + @Override + public synchronized void render(GLViewport v) { + MapPosition layerPos = mMapPosition; - GLState.test(false, false); - GLState.blend(true); + GLState.test(false, false); + GLState.blend(true); - float div = (float) (v.pos.scale / layerPos.scale); + float div = (float) (v.pos.scale / layerPos.scale); - boolean project = true; + boolean project = true; - setMatrix(v, project); + setMatrix(v, project); - for (RenderBucket b = buckets.get(); b != null;) { + for (RenderBucket b = buckets.get(); b != null; ) { - buckets.bind(); + buckets.bind(); - if (!project && b.type != SYMBOL) { - project = true; - setMatrix(v, project); - } + if (!project && b.type != SYMBOL) { + project = true; + setMatrix(v, project); + } - switch (b.type) { - case POLYGON: - b = PolygonBucket.Renderer.draw(b, v, 1, true); - break; - case LINE: - b = LineBucket.Renderer.draw(b, v, div, buckets); - break; - case TEXLINE: - b = LineTexBucket.Renderer.draw(b, v, div, buckets); - break; - case MESH: - b = MeshBucket.Renderer.draw(b, v); - break; - case HAIRLINE: - b = HairLineBucket.Renderer.draw(b, v); - break; - case BITMAP: - b = BitmapBucket.Renderer.draw(b, v, 1, 1); - break; - case SYMBOL: - if (project) { - project = false; - setMatrix(v, project); - } - b = TextureBucket.Renderer.draw(b, v, div); - break; - default: - log.error("invalid bucket {}", b.type); - b = b.next; - break; - } - } - } + switch (b.type) { + case POLYGON: + b = PolygonBucket.Renderer.draw(b, v, 1, true); + break; + case LINE: + b = LineBucket.Renderer.draw(b, v, div, buckets); + break; + case TEXLINE: + b = LineTexBucket.Renderer.draw(b, v, div, buckets); + break; + case MESH: + b = MeshBucket.Renderer.draw(b, v); + break; + case HAIRLINE: + b = HairLineBucket.Renderer.draw(b, v); + break; + case BITMAP: + b = BitmapBucket.Renderer.draw(b, v, 1, 1); + break; + case SYMBOL: + if (project) { + project = false; + setMatrix(v, project); + } + b = TextureBucket.Renderer.draw(b, v, div); + break; + default: + log.error("invalid bucket {}", b.type); + b = b.next; + break; + } + } + } - /** - * Compile all buckets into one BufferObject. Sets renderer to be ready - * when successful. When no data is available (buckets.countVboSize() == 0) - * then BufferObject will be released and buckets will not be rendered. - */ - protected synchronized void compile() { - boolean ok = buckets.compile(true); - setReady(ok); - } + /** + * Compile all buckets into one BufferObject. Sets renderer to be ready + * when successful. When no data is available (buckets.countVboSize() == 0) + * then BufferObject will be released and buckets will not be rendered. + */ + protected synchronized void compile() { + boolean ok = buckets.compile(true); + setReady(ok); + } - /** - * Utility: Set matrices.mvp matrix relative to the difference of current - * MapPosition and the last updated Overlay MapPosition. - * Use this to 'stick' your layer to the map. Note: Vertex coordinates - * are assumed to be scaled by MapRenderer.COORD_SCALE (== 8). - * - * @param v - * GLViewport - * @param project - * if true apply view- and projection, or just view otherwise. - */ - protected void setMatrix(GLViewport v, boolean project) { - setMatrix(v, project, MapRenderer.COORD_SCALE); - } + /** + * Utility: Set matrices.mvp matrix relative to the difference of current + * MapPosition and the last updated Overlay MapPosition. + * Use this to 'stick' your layer to the map. Note: Vertex coordinates + * are assumed to be scaled by MapRenderer.COORD_SCALE (== 8). + * + * @param v GLViewport + * @param project if true apply view- and projection, or just view otherwise. + */ + protected void setMatrix(GLViewport v, boolean project) { + setMatrix(v, project, MapRenderer.COORD_SCALE); + } - protected void setMatrix(GLViewport v, boolean project, float coordScale) { - setMatrix(v.mvp, v, project, coordScale); - } + protected void setMatrix(GLViewport v, boolean project, float coordScale) { + setMatrix(v.mvp, v, project, coordScale); + } - protected void setMatrix(GLMatrix mvp, GLViewport v, boolean project, float coordScale) { - MapPosition oPos = mMapPosition; + protected void setMatrix(GLMatrix mvp, GLViewport v, boolean project, float coordScale) { + MapPosition oPos = mMapPosition; - double tileScale = Tile.SIZE * v.pos.scale; + double tileScale = Tile.SIZE * v.pos.scale; - double x = oPos.x - v.pos.x; - double y = oPos.y - v.pos.y; + double x = oPos.x - v.pos.x; + double y = oPos.y - v.pos.y; - if (mFlipOnDateLine) { - //wrap around date-line - while (x < 0.5) - x += 1.0; - while (x > 0.5) - x -= 1.0; - } + if (mFlipOnDateLine) { + //wrap around date-line + while (x < 0.5) + x += 1.0; + while (x > 0.5) + x -= 1.0; + } - mvp.setTransScale((float) (x * tileScale), - (float) (y * tileScale), - (float) (v.pos.scale / oPos.scale) / coordScale); + mvp.setTransScale((float) (x * tileScale), + (float) (y * tileScale), + (float) (v.pos.scale / oPos.scale) / coordScale); - mvp.multiplyLhs(project ? v.viewproj : v.view); - } + mvp.multiplyLhs(project ? v.viewproj : v.view); + } - /** - * Utility: Set matrices.mvp matrix relative to the difference of current - * MapPosition and the last updated Overlay MapPosition and applies - * view-projection-matrix. - */ - protected void setMatrix(GLViewport v) { - setMatrix(v, true); - } + /** + * Utility: Set matrices.mvp matrix relative to the difference of current + * MapPosition and the last updated Overlay MapPosition and applies + * view-projection-matrix. + */ + protected void setMatrix(GLViewport v) { + setMatrix(v, true); + } } diff --git a/vtm/src/org/oscim/renderer/BufferObject.java b/vtm/src/org/oscim/renderer/BufferObject.java index 1abd3cd5..e1f53bd4 100644 --- a/vtm/src/org/oscim/renderer/BufferObject.java +++ b/vtm/src/org/oscim/renderer/BufferObject.java @@ -17,222 +17,228 @@ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.Buffer; - -import javax.annotation.CheckReturnValue; - import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; import org.oscim.utils.pool.Inlist; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.Buffer; + +import javax.annotation.CheckReturnValue; + +import static org.oscim.backend.GLAdapter.gl; + public final class BufferObject extends Inlist { - static final Logger log = LoggerFactory.getLogger(BufferObject.class); - private static final int MB = 1024 * 1024; - private static final int LIMIT_BUFFERS = 16 * MB; + static final Logger log = LoggerFactory.getLogger(BufferObject.class); + private static final int MB = 1024 * 1024; + private static final int LIMIT_BUFFERS = 16 * MB; - /** GL identifier */ - private int id; + /** + * GL identifier + */ + private int id; - /** allocated bytes */ - private int size; + /** + * allocated bytes + */ + private int size; - /** GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER */ - private int target; + /** + * GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER + */ + private int target; - private BufferObject(int target, int id) { - this.id = id; - this.target = target; - } + private BufferObject(int target, int id) { + this.id = id; + this.target = target; + } - /** - * @param newSize size required in bytes - */ - public void loadBufferData(Buffer buf, int newSize) { - boolean clear = false; + /** + * @param newSize size required in bytes + */ + public void loadBufferData(Buffer buf, int newSize) { + boolean clear = false; - if (buf.position() != 0) { - log.debug("flip your buffer!"); - buf.flip(); - } + if (buf.position() != 0) { + log.debug("flip your buffer!"); + buf.flip(); + } - GLState.bindBuffer(target, id); + GLState.bindBuffer(target, id); /* reuse memory allocated for vbo when possible and allocated - * memory is less then four times the new data */ - if (!GLAdapter.NO_BUFFER_SUB_DATA && !clear && - (size > newSize) && (size < newSize * 4)) { - gl.bufferSubData(target, 0, newSize, buf); - } else { - mBufferMemoryUsage += newSize - size; - size = newSize; - //GL.bufferData(target, size, buf, GL20.DYNAMIC_DRAW); - gl.bufferData(target, size, buf, GL.STATIC_DRAW); - } - } + * memory is less then four times the new data */ + if (!GLAdapter.NO_BUFFER_SUB_DATA && !clear && + (size > newSize) && (size < newSize * 4)) { + gl.bufferSubData(target, 0, newSize, buf); + } else { + mBufferMemoryUsage += newSize - size; + size = newSize; + //GL.bufferData(target, size, buf, GL20.DYNAMIC_DRAW); + gl.bufferData(target, size, buf, GL.STATIC_DRAW); + } + } - public void bind() { - GLState.bindBuffer(target, id); - } + public void bind() { + GLState.bindBuffer(target, id); + } - public void unbind() { - GLState.bindBuffer(target, 0); - } + public void unbind() { + GLState.bindBuffer(target, 0); + } - // ---------------------------- pool ---------------------------- - // bytes currently loaded in VBOs - private static int mBufferMemoryUsage; + // ---------------------------- pool ---------------------------- + // bytes currently loaded in VBOs + private static int mBufferMemoryUsage; - public static void checkBufferUsage(boolean force) { - // try to clear some unused vbo when exceding limit - if (mBufferMemoryUsage < LIMIT_BUFFERS) - return; + public static void checkBufferUsage(boolean force) { + // try to clear some unused vbo when exceding limit + if (mBufferMemoryUsage < LIMIT_BUFFERS) + return; - log.debug("use: " + mBufferMemoryUsage / MB + "MB"); - mBufferMemoryUsage -= BufferObject.limitUsage(MB); - log.debug("now: " + mBufferMemoryUsage / MB + "MB"); - } + log.debug("use: " + mBufferMemoryUsage / MB + "MB"); + mBufferMemoryUsage -= BufferObject.limitUsage(MB); + log.debug("now: " + mBufferMemoryUsage / MB + "MB"); + } - private final static BufferObject pool[] = new BufferObject[2]; - private final static int counter[] = new int[2]; + private final static BufferObject pool[] = new BufferObject[2]; + private final static int counter[] = new int[2]; - /** - * @param target can be GL20.ARRAY_BUFFER or GL20.ELEMENT_ARRAY_BUFFER - * @param size requested size in bytes. optional - can be 0. - */ - public static synchronized BufferObject get(int target, int size) { + /** + * @param target can be GL20.ARRAY_BUFFER or GL20.ELEMENT_ARRAY_BUFFER + * @param size requested size in bytes. optional - can be 0. + */ + public static synchronized BufferObject get(int target, int size) { - int t = (target == GL.ARRAY_BUFFER) ? 0 : 1; + int t = (target == GL.ARRAY_BUFFER) ? 0 : 1; - if (pool[t] == null) { - if (counter[t] != 0) - throw new IllegalStateException("lost objects: " + counter[t]); + if (pool[t] == null) { + if (counter[t] != 0) + throw new IllegalStateException("lost objects: " + counter[t]); - createBuffers(target, 10); - counter[t] += 10; - } - counter[t]--; + createBuffers(target, 10); + counter[t] += 10; + } + counter[t]--; - if (size != 0) { - /* find the item with minimal size greater 'size' bytes. */ - BufferObject bo = pool[t]; + if (size != 0) { + /* find the item with minimal size greater 'size' bytes. */ + BufferObject bo = pool[t]; /* actually points to BufferObject before min */ - BufferObject min = null; - BufferObject prev = null; + BufferObject min = null; + BufferObject prev = null; - for (; bo != null; bo = bo.next) { - if (bo.size > size) { - if (min == null || min.next.size > bo.size) - min = prev; - } - prev = bo; - } + for (; bo != null; bo = bo.next) { + if (bo.size > size) { + if (min == null || min.next.size > bo.size) + min = prev; + } + prev = bo; + } - if (min != null && min != pool[t]) { - bo = min.next; - min.next = bo.next; - bo.next = null; - return bo; - } - } + if (min != null && min != pool[t]) { + bo = min.next; + min.next = bo.next; + bo.next = null; + return bo; + } + } - BufferObject bo = pool[t]; - pool[t] = pool[t].next; - bo.next = null; - return bo; - } + BufferObject bo = pool[t]; + pool[t] = pool[t].next; + bo.next = null; + return bo; + } - @CheckReturnValue - public static synchronized BufferObject release(BufferObject bo) { - if (bo == null) - return null; + @CheckReturnValue + public static synchronized BufferObject release(BufferObject bo) { + if (bo == null) + return null; - // if (counter > 200) { - // log.debug("should clear some buffers " + counter); - // } - int t = (bo.target == GL.ARRAY_BUFFER) ? 0 : 1; + // if (counter > 200) { + // log.debug("should clear some buffers " + counter); + // } + int t = (bo.target == GL.ARRAY_BUFFER) ? 0 : 1; - bo.next = pool[t]; - pool[t] = bo; - counter[t]++; + bo.next = pool[t]; + pool[t] = bo; + counter[t]++; - return null; - } + return null; + } - // Note: only call from GL-Thread - static synchronized int limitUsage(int reduce) { + // Note: only call from GL-Thread + static synchronized int limitUsage(int reduce) { - int vboIds[] = new int[10]; - int freed = 0; + int vboIds[] = new int[10]; + int freed = 0; - for (int t = 0; t < 2; t++) { + for (int t = 0; t < 2; t++) { - int removed = 0; - BufferObject prev = pool[t]; + int removed = 0; + BufferObject prev = pool[t]; - if (prev == null) { - log.debug("nothing to free"); - continue; - } + if (prev == null) { + log.debug("nothing to free"); + continue; + } - for (BufferObject bo = pool[t].next; bo != null;) { - if (bo.size > 0) { - freed += bo.size; - bo.size = 0; + for (BufferObject bo = pool[t].next; bo != null; ) { + if (bo.size > 0) { + freed += bo.size; + bo.size = 0; - vboIds[removed++] = bo.id; - prev.next = bo.next; - bo = bo.next; + vboIds[removed++] = bo.id; + prev.next = bo.next; + bo = bo.next; - if (removed == 10 || reduce < freed) - break; + if (removed == 10 || reduce < freed) + break; - } else { - prev = bo; - bo = bo.next; - } - } + } else { + prev = bo; + bo = bo.next; + } + } - if (removed > 0) { - GLUtils.glDeleteBuffers(removed, vboIds); - counter[t] -= removed; - } + if (removed > 0) { + GLUtils.glDeleteBuffers(removed, vboIds); + counter[t] -= removed; + } - } + } - return freed; - } + return freed; + } - static void createBuffers(int target, int num) { - int[] mVboIds = GLUtils.glGenBuffers(num); + static void createBuffers(int target, int num) { + int[] mVboIds = GLUtils.glGenBuffers(num); - int t = (target == GL.ARRAY_BUFFER) ? 0 : 1; + int t = (target == GL.ARRAY_BUFFER) ? 0 : 1; - for (int i = 0; i < num; i++) { - BufferObject bo = new BufferObject(target, mVboIds[i]); - bo.next = pool[t]; - pool[t] = bo; - } - } + for (int i = 0; i < num; i++) { + BufferObject bo = new BufferObject(target, mVboIds[i]); + bo.next = pool[t]; + pool[t] = bo; + } + } - static synchronized void clear() { - mBufferMemoryUsage = 0; + static synchronized void clear() { + mBufferMemoryUsage = 0; - pool[0] = null; - pool[1] = null; - counter[0] = 0; - counter[1] = 0; - } + pool[0] = null; + pool[1] = null; + counter[0] = 0; + counter[1] = 0; + } - static synchronized void init(int num) { - createBuffers(GL.ARRAY_BUFFER, num); - counter[0] += num; - } + static synchronized void init(int num) { + createBuffers(GL.ARRAY_BUFFER, num); + counter[0] += num; + } - public static boolean isMaxFill() { - return mBufferMemoryUsage > LIMIT_BUFFERS; - } + public static boolean isMaxFill() { + return mBufferMemoryUsage > LIMIT_BUFFERS; + } } diff --git a/vtm/src/org/oscim/renderer/ExtrusionRenderer.java b/vtm/src/org/oscim/renderer/ExtrusionRenderer.java index 0404f911..255ff9a4 100644 --- a/vtm/src/org/oscim/renderer/ExtrusionRenderer.java +++ b/vtm/src/org/oscim/renderer/ExtrusionRenderer.java @@ -16,8 +16,6 @@ */ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - import org.oscim.backend.GL; import org.oscim.core.Tile; import org.oscim.renderer.bucket.ExtrusionBucket; @@ -26,245 +24,247 @@ import org.oscim.utils.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.backend.GLAdapter.gl; + public abstract class ExtrusionRenderer extends LayerRenderer { - static final Logger log = LoggerFactory.getLogger(ExtrusionRenderer.class); + static final Logger log = LoggerFactory.getLogger(ExtrusionRenderer.class); - private final boolean mTranslucent; - private final int mMode; - private Shader mShader; + private final boolean mTranslucent; + private final int mMode; + private Shader mShader; - protected ExtrusionBuckets[] mExtrusionBucketSet = {}; - protected int mBucketsCnt; - protected float mAlpha = 1; + protected ExtrusionBuckets[] mExtrusionBucketSet = {}; + protected int mBucketsCnt; + protected float mAlpha = 1; - public ExtrusionRenderer(boolean mesh, boolean alpha) { - mMode = mesh ? 1 : 0; - mTranslucent = alpha; - } + public ExtrusionRenderer(boolean mesh, boolean alpha) { + mMode = mesh ? 1 : 0; + mTranslucent = alpha; + } - public static class Shader extends GLShader { - int uMVP, uColor, uAlpha, uMode, aPos, aLight; + public static class Shader extends GLShader { + int uMVP, uColor, uAlpha, uMode, aPos, aLight; - public Shader(String shader) { - if (!create(shader)) - return; + public Shader(String shader) { + if (!create(shader)) + return; - uMVP = getUniform("u_mvp"); - uColor = getUniform("u_color"); - uAlpha = getUniform("u_alpha"); - uMode = getUniform("u_mode"); - aPos = getAttrib("a_pos"); - aLight = getAttrib("a_light"); - } - } + uMVP = getUniform("u_mvp"); + uColor = getUniform("u_color"); + uAlpha = getUniform("u_alpha"); + uMode = getUniform("u_mode"); + aPos = getAttrib("a_pos"); + aLight = getAttrib("a_light"); + } + } - @Override - public boolean setup() { - if (mMode == 0) - mShader = new Shader("extrusion_layer_ext"); - else - mShader = new Shader("extrusion_layer_mesh"); + @Override + public boolean setup() { + if (mMode == 0) + mShader = new Shader("extrusion_layer_ext"); + else + mShader = new Shader("extrusion_layer_mesh"); - return true; - } + return true; + } - private void renderCombined(int vertexPointer, ExtrusionBuckets ebs) { + private void renderCombined(int vertexPointer, ExtrusionBuckets ebs) { - for (ExtrusionBucket eb = ebs.buckets(); eb != null; eb = eb.next()) { + for (ExtrusionBucket eb = ebs.buckets(); eb != null; eb = eb.next()) { - gl.vertexAttribPointer(vertexPointer, 3, - GL.SHORT, false, 8, - eb.getVertexOffset()); + gl.vertexAttribPointer(vertexPointer, 3, + GL.SHORT, false, 8, + eb.getVertexOffset()); - int sumIndices = eb.idx[0] + eb.idx[1] + eb.idx[2]; + int sumIndices = eb.idx[0] + eb.idx[1] + eb.idx[2]; /* extrusion */ - if (sumIndices > 0) - gl.drawElements(GL.TRIANGLES, sumIndices, - GL.UNSIGNED_SHORT, eb.off[0]); + if (sumIndices > 0) + gl.drawElements(GL.TRIANGLES, sumIndices, + GL.UNSIGNED_SHORT, eb.off[0]); /* mesh */ - if (eb.idx[4] > 0) { - gl.drawElements(GL.TRIANGLES, eb.idx[4], - GL.UNSIGNED_SHORT, eb.off[4]); - } - } - } + if (eb.idx[4] > 0) { + gl.drawElements(GL.TRIANGLES, eb.idx[4], + GL.UNSIGNED_SHORT, eb.off[4]); + } + } + } - @Override - public void render(GLViewport v) { + @Override + public void render(GLViewport v) { - float[] currentColor = null; - float currentAlpha = 0; + float[] currentColor = null; + float currentAlpha = 0; - gl.depthMask(true); - gl.clear(GL.DEPTH_BUFFER_BIT); + gl.depthMask(true); + gl.clear(GL.DEPTH_BUFFER_BIT); - GLState.test(true, false); + GLState.test(true, false); - Shader s = mShader; - s.useProgram(); - GLState.enableVertexArrays(s.aPos, -1); + Shader s = mShader; + s.useProgram(); + GLState.enableVertexArrays(s.aPos, -1); /* only use face-culling when it's unlikely - * that one'moves through the building' */ - if (v.pos.zoomLevel < 18) - gl.enable(GL.CULL_FACE); + * that one'moves through the building' */ + if (v.pos.zoomLevel < 18) + gl.enable(GL.CULL_FACE); - gl.depthFunc(GL.LESS); - gl.uniform1f(s.uAlpha, mAlpha); + gl.depthFunc(GL.LESS); + gl.uniform1f(s.uAlpha, mAlpha); - ExtrusionBuckets[] ebs = mExtrusionBucketSet; + ExtrusionBuckets[] ebs = mExtrusionBucketSet; - if (mTranslucent) { - /* only draw to depth buffer */ - GLState.blend(false); - gl.colorMask(false, false, false, false); - gl.uniform1i(s.uMode, -1); + if (mTranslucent) { + /* only draw to depth buffer */ + GLState.blend(false); + gl.colorMask(false, false, false, false); + gl.uniform1i(s.uMode, -1); - for (int i = 0; i < mBucketsCnt; i++) { - if (ebs[i].ibo == null) - return; + for (int i = 0; i < mBucketsCnt; i++) { + if (ebs[i].ibo == null) + return; - ebs[i].ibo.bind(); - ebs[i].vbo.bind(); + ebs[i].ibo.bind(); + ebs[i].vbo.bind(); - setMatrix(s, v, ebs[i]); + setMatrix(s, v, ebs[i]); - float alpha = mAlpha * getFade(ebs[i]); - if (alpha != currentAlpha) { - gl.uniform1f(s.uAlpha, alpha); - currentAlpha = alpha; - } + float alpha = mAlpha * getFade(ebs[i]); + if (alpha != currentAlpha) { + gl.uniform1f(s.uAlpha, alpha); + currentAlpha = alpha; + } - renderCombined(s.aPos, ebs[i]); - } + renderCombined(s.aPos, ebs[i]); + } /* only draw to color buffer */ - gl.colorMask(true, true, true, true); - gl.depthMask(false); - gl.depthFunc(GL.EQUAL); - } + gl.colorMask(true, true, true, true); + gl.depthMask(false); + gl.depthFunc(GL.EQUAL); + } - GLState.blend(true); + GLState.blend(true); - GLState.enableVertexArrays(s.aPos, s.aLight); + GLState.enableVertexArrays(s.aPos, s.aLight); - for (int i = 0; i < mBucketsCnt; i++) { - if (ebs[i].ibo == null) - continue; + for (int i = 0; i < mBucketsCnt; i++) { + if (ebs[i].ibo == null) + continue; - ebs[i].ibo.bind(); - ebs[i].vbo.bind(); + ebs[i].ibo.bind(); + ebs[i].vbo.bind(); - if (!mTranslucent) - setMatrix(s, v, ebs[i]); + if (!mTranslucent) + setMatrix(s, v, ebs[i]); - float alpha = mAlpha * getFade(ebs[i]); - if (alpha != currentAlpha) { - gl.uniform1f(s.uAlpha, alpha); - currentAlpha = alpha; - } + float alpha = mAlpha * getFade(ebs[i]); + if (alpha != currentAlpha) { + gl.uniform1f(s.uAlpha, alpha); + currentAlpha = alpha; + } - ExtrusionBucket eb = ebs[i].buckets(); + ExtrusionBucket eb = ebs[i].buckets(); - for (; eb != null; eb = eb.next()) { + for (; eb != null; eb = eb.next()) { - if (eb.colors != currentColor) { - currentColor = eb.colors; - GLUtils.glUniform4fv(s.uColor, - mMode == 0 ? 4 : 1, - eb.colors); - } + if (eb.colors != currentColor) { + currentColor = eb.colors; + GLUtils.glUniform4fv(s.uColor, + mMode == 0 ? 4 : 1, + eb.colors); + } - gl.vertexAttribPointer(s.aPos, 3, GL.SHORT, - false, 8, eb.getVertexOffset()); + gl.vertexAttribPointer(s.aPos, 3, GL.SHORT, + false, 8, eb.getVertexOffset()); - gl.vertexAttribPointer(s.aLight, 2, GL.UNSIGNED_BYTE, - false, 8, eb.getVertexOffset() + 6); + gl.vertexAttribPointer(s.aLight, 2, GL.UNSIGNED_BYTE, + false, 8, eb.getVertexOffset() + 6); /* draw extruded outlines */ - if (eb.idx[0] > 0) { - if (mTranslucent) { - gl.depthFunc(GL.EQUAL); - setMatrix(s, v, ebs[i]); - } + if (eb.idx[0] > 0) { + if (mTranslucent) { + gl.depthFunc(GL.EQUAL); + setMatrix(s, v, ebs[i]); + } /* draw roof */ - gl.uniform1i(s.uMode, 0); - gl.drawElements(GL.TRIANGLES, eb.idx[2], - GL.UNSIGNED_SHORT, eb.off[2]); + gl.uniform1i(s.uMode, 0); + gl.drawElements(GL.TRIANGLES, eb.idx[2], + GL.UNSIGNED_SHORT, eb.off[2]); /* draw sides 1 */ - gl.uniform1i(s.uMode, 1); - gl.drawElements(GL.TRIANGLES, eb.idx[0], - GL.UNSIGNED_SHORT, eb.off[0]); + gl.uniform1i(s.uMode, 1); + gl.drawElements(GL.TRIANGLES, eb.idx[0], + GL.UNSIGNED_SHORT, eb.off[0]); /* draw sides 2 */ - gl.uniform1i(s.uMode, 2); - gl.drawElements(GL.TRIANGLES, eb.idx[1], - GL.UNSIGNED_SHORT, eb.off[1]); + gl.uniform1i(s.uMode, 2); + gl.drawElements(GL.TRIANGLES, eb.idx[1], + GL.UNSIGNED_SHORT, eb.off[1]); - if (mTranslucent) { + if (mTranslucent) { /* drawing gl_lines with the same coordinates * does not result in same depth values as * polygons, so add offset and draw gl_lequal */ - gl.depthFunc(GL.LEQUAL); - v.mvp.addDepthOffset(100); - v.mvp.setAsUniform(s.uMVP); - } + gl.depthFunc(GL.LEQUAL); + v.mvp.addDepthOffset(100); + v.mvp.setAsUniform(s.uMVP); + } - gl.uniform1i(s.uMode, 3); + gl.uniform1i(s.uMode, 3); - gl.drawElements(GL.LINES, eb.idx[3], - GL.UNSIGNED_SHORT, eb.off[3]); - } + gl.drawElements(GL.LINES, eb.idx[3], + GL.UNSIGNED_SHORT, eb.off[3]); + } /* draw triangle meshes */ - if (eb.idx[4] > 0) { - gl.drawElements(GL.TRIANGLES, eb.idx[4], - GL.UNSIGNED_SHORT, eb.off[4]); - } - } + if (eb.idx[4] > 0) { + gl.drawElements(GL.TRIANGLES, eb.idx[4], + GL.UNSIGNED_SHORT, eb.off[4]); + } + } /* just a temporary reference! */ - ebs[i] = null; - } + ebs[i] = null; + } - if (!mTranslucent) - gl.depthMask(false); + if (!mTranslucent) + gl.depthMask(false); - if (v.pos.zoomLevel < 18) - gl.disable(GL.CULL_FACE); - } + if (v.pos.zoomLevel < 18) + gl.disable(GL.CULL_FACE); + } - private float getFade(ExtrusionBuckets ebs) { - if (ebs.animTime == 0) - ebs.animTime = MapRenderer.frametime - 50; + private float getFade(ExtrusionBuckets ebs) { + if (ebs.animTime == 0) + ebs.animTime = MapRenderer.frametime - 50; - return FastMath.clamp((float) (MapRenderer.frametime - ebs.animTime) / 300f, 0f, 1f); - } + return FastMath.clamp((float) (MapRenderer.frametime - ebs.animTime) / 300f, 0f, 1f); + } - private void setMatrix(Shader s, GLViewport v, ExtrusionBuckets l) { + private void setMatrix(Shader s, GLViewport v, ExtrusionBuckets l) { - int z = l.zoomLevel; - double curScale = Tile.SIZE * v.pos.scale; - float scale = (float) (v.pos.scale / (1 << z)); + int z = l.zoomLevel; + double curScale = Tile.SIZE * v.pos.scale; + float scale = (float) (v.pos.scale / (1 << z)); - float x = (float) ((l.x - v.pos.x) * curScale); - float y = (float) ((l.y - v.pos.y) * curScale); + float x = (float) ((l.x - v.pos.x) * curScale); + float y = (float) ((l.y - v.pos.y) * curScale); - v.mvp.setTransScale(x, y, scale / MapRenderer.COORD_SCALE); - v.mvp.setValue(10, scale / 10); - v.mvp.multiplyLhs(v.viewproj); + v.mvp.setTransScale(x, y, scale / MapRenderer.COORD_SCALE); + v.mvp.setValue(10, scale / 10); + v.mvp.multiplyLhs(v.viewproj); - if (mTranslucent) { + if (mTranslucent) { /* should avoid z-fighting of overlapping * building from different tiles */ - int zoom = (1 << z); - int delta = (int) (l.x * zoom) % 4 + (int) (l.y * zoom) % 4 * 4; - v.mvp.addDepthOffset(delta); - } - v.mvp.setAsUniform(s.uMVP); - } + int zoom = (1 << z); + int delta = (int) (l.x * zoom) % 4 + (int) (l.y * zoom) % 4 * 4; + v.mvp.addDepthOffset(delta); + } + v.mvp.setAsUniform(s.uMVP); + } } diff --git a/vtm/src/org/oscim/renderer/GLMatrix.java b/vtm/src/org/oscim/renderer/GLMatrix.java index 8ac12e9e..c2512d66 100644 --- a/vtm/src/org/oscim/renderer/GLMatrix.java +++ b/vtm/src/org/oscim/renderer/GLMatrix.java @@ -16,293 +16,292 @@ */ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.oscim.backend.GLAdapter.gl; public class GLMatrix { - static final Logger log = LoggerFactory.getLogger(GLMatrix.class); - private final static boolean dbg = false; + static final Logger log = LoggerFactory.getLogger(GLMatrix.class); + private final static boolean dbg = false; - private final long pointer; - private final FloatBuffer buffer; + private final long pointer; + private final FloatBuffer buffer; - private final static String INVALID_INPUT = "Bad Array!"; + private final static String INVALID_INPUT = "Bad Array!"; - public GLMatrix() { - pointer = alloc(); - buffer = (getBuffer(pointer)).order(ByteOrder.nativeOrder()).asFloatBuffer(); - } + public GLMatrix() { + pointer = alloc(); + buffer = (getBuffer(pointer)).order(ByteOrder.nativeOrder()).asFloatBuffer(); + } - /** - * Set the Matrix from float array - * - * @param m float array to copy - */ - public void set(float[] m) { - if (m == null || m.length != 16) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Set the Matrix from float array + * + * @param m float array to copy + */ + public void set(float[] m) { + if (m == null || m.length != 16) + throw new IllegalArgumentException(INVALID_INPUT); - set(pointer, m); - } + set(pointer, m); + } - /** - * Get the Matrix as float array - * - * @param m float array to store Matrix - */ - public void get(float[] m) { - if (m == null || m.length != 16) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Get the Matrix as float array + * + * @param m float array to store Matrix + */ + public void get(float[] m) { + if (m == null || m.length != 16) + throw new IllegalArgumentException(INVALID_INPUT); - get(pointer, m); - } + get(pointer, m); + } - /** - * Copy values from mat - * - * @param mat Matrix to copy - */ - public void copy(GLMatrix mat) { - copy(pointer, mat.pointer); - } + /** + * Copy values from mat + * + * @param mat Matrix to copy + */ + public void copy(GLMatrix mat) { + copy(pointer, mat.pointer); + } - /** - * Project Vector with Matrix - * - * @param vec3 Vector to project - */ - public void prj(float[] vec3) { - if (vec3 == null || vec3.length < 3) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Project Vector with Matrix + * + * @param vec3 Vector to project + */ + public void prj(float[] vec3) { + if (vec3 == null || vec3.length < 3) + throw new IllegalArgumentException(INVALID_INPUT); - prj(pointer, vec3); - } + prj(pointer, vec3); + } - /** - * Project Vectors with Matrix - * - * @param vec3 Vector to project - */ - public void prj3D(float[] vec3, int offset, int length) { - if (vec3 == null || vec3.length / (offset + length) < 1) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Project Vectors with Matrix + * + * @param vec3 Vector to project + */ + public void prj3D(float[] vec3, int offset, int length) { + if (vec3 == null || vec3.length / (offset + length) < 1) + throw new IllegalArgumentException(INVALID_INPUT); - prj3D(pointer, vec3, offset, length); - } + prj3D(pointer, vec3, offset, length); + } - /** - * Project Vectors with Matrix - * - * @param vec2 Vector to project - */ - public void prj2D(float[] vec2, int offset, int length) { - if (vec2 == null || offset < 0 || (length + offset) * 2 > vec2.length) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Project Vectors with Matrix + * + * @param vec2 Vector to project + */ + public void prj2D(float[] vec2, int offset, int length) { + if (vec2 == null || offset < 0 || (length + offset) * 2 > vec2.length) + throw new IllegalArgumentException(INVALID_INPUT); - prj2D(pointer, vec2, offset, length); - } + prj2D(pointer, vec2, offset, length); + } - /** - * Project Vectors with Matrix - * - * - * @param vec2 Vector to project - */ - public void prj2D(float[] src, int src_offset, float[] dst, int dst_offset, int length) { - if (src == null || src_offset < 0 || length + src_offset * 2 > src.length) - throw new IllegalArgumentException(INVALID_INPUT); + /** + * Project Vectors with Matrix + * + * @param vec2 Vector to project + */ + public void prj2D(float[] src, int src_offset, float[] dst, int dst_offset, int length) { + if (src == null || src_offset < 0 || length + src_offset * 2 > src.length) + throw new IllegalArgumentException(INVALID_INPUT); - prj2D2(pointer, src, src_offset, dst, dst_offset, length); - } + prj2D2(pointer, src, src_offset, dst, dst_offset, length); + } - /** - * Multiply rhs onto Matrix. - * - * @param rhs right hand side - */ - public void multiplyRhs(GLMatrix rhs) { - smulrhs(pointer, rhs.pointer); - } + /** + * Multiply rhs onto Matrix. + * + * @param rhs right hand side + */ + public void multiplyRhs(GLMatrix rhs) { + smulrhs(pointer, rhs.pointer); + } - /** - * Use this matrix as rhs, multiply it on lhs and store result. - * - * @param lhs right hand side - */ - public void multiplyLhs(GLMatrix lhs) { - smullhs(pointer, lhs.pointer); - } + /** + * Use this matrix as rhs, multiply it on lhs and store result. + * + * @param lhs right hand side + */ + public void multiplyLhs(GLMatrix lhs) { + smullhs(pointer, lhs.pointer); + } - /** - * Multiply rhs onto lhs and store result in Matrix. - * - * This matrix MUST be different from lhs and rhs! - * - * when combining matrices for vector projection this - * has the same effect first as applying rhs then lhs. - * - * @param lhs left hand side - * @param rhs right hand side - */ - public void multiplyMM(GLMatrix lhs, GLMatrix rhs) { - smul(pointer, lhs.pointer, rhs.pointer); - } + /** + * Multiply rhs onto lhs and store result in Matrix. + *

+ * This matrix MUST be different from lhs and rhs! + *

+ * when combining matrices for vector projection this + * has the same effect first as applying rhs then lhs. + * + * @param lhs left hand side + * @param rhs right hand side + */ + public void multiplyMM(GLMatrix lhs, GLMatrix rhs) { + smul(pointer, lhs.pointer, rhs.pointer); + } - /** - * Transpose mat and store result in Matrix - * - * @param mat to transpose - */ - public void transposeM(GLMatrix mat) { - strans(pointer, mat.pointer); - } + /** + * Transpose mat and store result in Matrix + * + * @param mat to transpose + */ + public void transposeM(GLMatrix mat) { + strans(pointer, mat.pointer); + } - /** - * Set rotation - * - * @param a angle in degree - * @param x around x-axis - * @param y around y-axis - * @param z around z-axis - */ - public void setRotation(float a, float x, float y, float z) { - setRotation(pointer, a, x, y, z); - } + /** + * Set rotation + * + * @param a angle in degree + * @param x around x-axis + * @param y around y-axis + * @param z around z-axis + */ + public void setRotation(float a, float x, float y, float z) { + setRotation(pointer, a, x, y, z); + } - /** - * Set translation - * - * @param x along x-axis - * @param y along y-axis - * @param z along z-axis - */ - public void setTranslation(float x, float y, float z) { - setTranslation(pointer, x, y, z); - } + /** + * Set translation + * + * @param x along x-axis + * @param y along y-axis + * @param z along z-axis + */ + public void setTranslation(float x, float y, float z) { + setTranslation(pointer, x, y, z); + } - /** - * Set scale factor - * - * @param x axis - * @param y axis - * @param z axis - */ - public void setScale(float x, float y, float z) { - setScale(pointer, x, y, z); - } + /** + * Set scale factor + * + * @param x axis + * @param y axis + * @param z axis + */ + public void setScale(float x, float y, float z) { + setScale(pointer, x, y, z); + } - /** - * Set translation and x,y scale - * - * @param tx translate x - * @param ty translate y - * @param scale factor x,y - */ - public void setTransScale(float tx, float ty, float scale) { - setTransScale(pointer, tx, ty, scale); - } + /** + * Set translation and x,y scale + * + * @param tx translate x + * @param ty translate y + * @param scale factor x,y + */ + public void setTransScale(float tx, float ty, float scale) { + setTransScale(pointer, tx, ty, scale); + } - /** - * Set Matrix with glUniformMatrix - * - * @param location GL location id - */ - public void setAsUniform(int location) { - gl.uniformMatrix4fv(location, 1, false, buffer); - //setAsUniform(pointer, location); - } + /** + * Set Matrix with glUniformMatrix + * + * @param location GL location id + */ + public void setAsUniform(int location) { + gl.uniformMatrix4fv(location, 1, false, buffer); + //setAsUniform(pointer, location); + } - /** - * Set single value - * - * @param pos at position - * @param value value to set - */ - public void setValue(int pos, float value) { - setValueAt(pointer, pos, value); - } + /** + * Set single value + * + * @param pos at position + * @param value value to set + */ + public void setValue(int pos, float value) { + setValueAt(pointer, pos, value); + } - /** - * add some offset (similar to glDepthOffset) - * - * @param delta offset - */ - public void addDepthOffset(int delta) { - addDepthOffset(pointer, delta); - } + /** + * add some offset (similar to glDepthOffset) + * + * @param delta offset + */ + public void addDepthOffset(int delta) { + addDepthOffset(pointer, delta); + } - /** - * Set identity matrix - */ - public void setIdentity() { - identity(pointer); - } + /** + * Set identity matrix + */ + public void setIdentity() { + identity(pointer); + } - /** - * Free native object - * */ - @Override - public void finalize() { - if (pointer != 0) - delete(pointer); - } + /** + * Free native object + */ + @Override + public void finalize() { + if (pointer != 0) + delete(pointer); + } - private native static long alloc(); + private native static long alloc(); - private native static void delete(long self); + private native static void delete(long self); - private native static void set(long self, float[] m); + private native static void set(long self, float[] m); - private native static void copy(long self, long other); + private native static void copy(long self, long other); - private native static void identity(long self); + private native static void identity(long self); - private native static void get(long self, float[] m); + private native static void get(long self, float[] m); - private native static void mul(long self, long lhs_ptr); + private native static void mul(long self, long lhs_ptr); - private native static void smul(long self, long rhs_ptr, long lhs_ptr); + private native static void smul(long self, long rhs_ptr, long lhs_ptr); - private native static void smulrhs(long self, long rhs_ptr); + private native static void smulrhs(long self, long rhs_ptr); - private native static void smullhs(long self, long lhs_ptr); + private native static void smullhs(long self, long lhs_ptr); - private native static void strans(long self, long rhs_ptr); + private native static void strans(long self, long rhs_ptr); - private native static void prj(long self, float[] vec3); + private native static void prj(long self, float[] vec3); - private native static void prj3D(long self, float[] vec3, int start, int cnt); + private native static void prj3D(long self, float[] vec3, int start, int cnt); - private native static void prj2D(long self, float[] vec2, int start, int cnt); + private native static void prj2D(long self, float[] vec2, int start, int cnt); - private native static void prj2D2(long self, float[] vec2, int src_offset, - float[] dst_vec, int dst_offset, int length); + private native static void prj2D2(long self, float[] vec2, int src_offset, + float[] dst_vec, int dst_offset, int length); - private native static void setRotation(long self, float a, float x, float y, float z); + private native static void setRotation(long self, float a, float x, float y, float z); - private native static void setScale(long self, float x, float y, float z); + private native static void setScale(long self, float x, float y, float z); - private native static void setTranslation(long self, float x, float y, float z); + private native static void setTranslation(long self, float x, float y, float z); - private native static void setTransScale(long self, float tx, float ty, float scale); + private native static void setTransScale(long self, float tx, float ty, float scale); - //private native static void setAsUniform(long self, int handle); + //private native static void setAsUniform(long self, int handle); - private native static void setValueAt(long self, int pos, float value); + private native static void setValueAt(long self, int pos, float value); - private native static void addDepthOffset(long self, int delta); + private native static void addDepthOffset(long self, int delta); - private native static ByteBuffer getBuffer(long self); + private native static ByteBuffer getBuffer(long self); /* Copyright (C) 2007 The Android Open Source Project - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -315,187 +314,187 @@ public class GLMatrix { * See the License for the specific language governing permissions and * limitations under the License. */ - /** - * Define a projection matrix in terms of six clip planes - * - * @param m the float array that holds the perspective matrix - * @param offset the offset into float array m where the perspective - * matrix data is written - */ - public static void frustumM(float[] m, int offset, - float left, float right, float bottom, float top, - float near, float far) { - if (left == right) { - throw new IllegalArgumentException("left == right"); - } - if (top == bottom) { - throw new IllegalArgumentException("top == bottom"); - } - if (near == far) { - throw new IllegalArgumentException("near == far"); - } - if (near <= 0.0f) { - throw new IllegalArgumentException("near <= 0.0f"); - } - if (far <= 0.0f) { - throw new IllegalArgumentException("far <= 0.0f"); - } - final float r_width = 1.0f / (right - left); - final float r_height = 1.0f / (top - bottom); - final float r_depth = 1.0f / (near - far); - final float x = 2.0f * (near * r_width); - final float y = 2.0f * (near * r_height); - final float A = (right + left) * r_width; - final float B = (top + bottom) * r_height; - final float C = (far + near) * r_depth; - final float D = 2.0f * (far * near * r_depth); - m[offset + 0] = x; - m[offset + 5] = y; - m[offset + 8] = A; - m[offset + 9] = B; - m[offset + 10] = C; - m[offset + 14] = D; - m[offset + 11] = -1.0f; - m[offset + 1] = 0.0f; - m[offset + 2] = 0.0f; - m[offset + 3] = 0.0f; - m[offset + 4] = 0.0f; - m[offset + 6] = 0.0f; - m[offset + 7] = 0.0f; - m[offset + 12] = 0.0f; - m[offset + 13] = 0.0f; - m[offset + 15] = 0.0f; - } + /** + * Define a projection matrix in terms of six clip planes + * + * @param m the float array that holds the perspective matrix + * @param offset the offset into float array m where the perspective + * matrix data is written + */ + public static void frustumM(float[] m, int offset, + float left, float right, float bottom, float top, + float near, float far) { + if (left == right) { + throw new IllegalArgumentException("left == right"); + } + if (top == bottom) { + throw new IllegalArgumentException("top == bottom"); + } + if (near == far) { + throw new IllegalArgumentException("near == far"); + } + if (near <= 0.0f) { + throw new IllegalArgumentException("near <= 0.0f"); + } + if (far <= 0.0f) { + throw new IllegalArgumentException("far <= 0.0f"); + } + final float r_width = 1.0f / (right - left); + final float r_height = 1.0f / (top - bottom); + final float r_depth = 1.0f / (near - far); + final float x = 2.0f * (near * r_width); + final float y = 2.0f * (near * r_height); + final float A = (right + left) * r_width; + final float B = (top + bottom) * r_height; + final float C = (far + near) * r_depth; + final float D = 2.0f * (far * near * r_depth); + m[offset + 0] = x; + m[offset + 5] = y; + m[offset + 8] = A; + m[offset + 9] = B; + m[offset + 10] = C; + m[offset + 14] = D; + m[offset + 11] = -1.0f; + m[offset + 1] = 0.0f; + m[offset + 2] = 0.0f; + m[offset + 3] = 0.0f; + m[offset + 4] = 0.0f; + m[offset + 6] = 0.0f; + m[offset + 7] = 0.0f; + m[offset + 12] = 0.0f; + m[offset + 13] = 0.0f; + m[offset + 15] = 0.0f; + } - /** - * Inverts a 4 x 4 matrix. - * - * @param mInv the array that holds the output inverted matrix - * @param mInvOffset an offset into mInv where the inverted matrix is - * stored. - * @param m the input array - * @param mOffset an offset into m where the matrix is stored. - * @return true if the matrix could be inverted, false if it could not. - */ - public static boolean invertM(float[] mInv, int mInvOffset, float[] m, - int mOffset) { - // Invert a 4 x 4 matrix using Cramer's Rule + /** + * Inverts a 4 x 4 matrix. + * + * @param mInv the array that holds the output inverted matrix + * @param mInvOffset an offset into mInv where the inverted matrix is + * stored. + * @param m the input array + * @param mOffset an offset into m where the matrix is stored. + * @return true if the matrix could be inverted, false if it could not. + */ + public static boolean invertM(float[] mInv, int mInvOffset, float[] m, + int mOffset) { + // Invert a 4 x 4 matrix using Cramer's Rule - // transpose matrix - final float src0 = m[mOffset + 0]; - final float src4 = m[mOffset + 1]; - final float src8 = m[mOffset + 2]; - final float src12 = m[mOffset + 3]; + // transpose matrix + final float src0 = m[mOffset + 0]; + final float src4 = m[mOffset + 1]; + final float src8 = m[mOffset + 2]; + final float src12 = m[mOffset + 3]; - final float src1 = m[mOffset + 4]; - final float src5 = m[mOffset + 5]; - final float src9 = m[mOffset + 6]; - final float src13 = m[mOffset + 7]; + final float src1 = m[mOffset + 4]; + final float src5 = m[mOffset + 5]; + final float src9 = m[mOffset + 6]; + final float src13 = m[mOffset + 7]; - final float src2 = m[mOffset + 8]; - final float src6 = m[mOffset + 9]; - final float src10 = m[mOffset + 10]; - final float src14 = m[mOffset + 11]; + final float src2 = m[mOffset + 8]; + final float src6 = m[mOffset + 9]; + final float src10 = m[mOffset + 10]; + final float src14 = m[mOffset + 11]; - final float src3 = m[mOffset + 12]; - final float src7 = m[mOffset + 13]; - final float src11 = m[mOffset + 14]; - final float src15 = m[mOffset + 15]; + final float src3 = m[mOffset + 12]; + final float src7 = m[mOffset + 13]; + final float src11 = m[mOffset + 14]; + final float src15 = m[mOffset + 15]; - // calculate pairs for first 8 elements (cofactors) - final float atmp0 = src10 * src15; - final float atmp1 = src11 * src14; - final float atmp2 = src9 * src15; - final float atmp3 = src11 * src13; - final float atmp4 = src9 * src14; - final float atmp5 = src10 * src13; - final float atmp6 = src8 * src15; - final float atmp7 = src11 * src12; - final float atmp8 = src8 * src14; - final float atmp9 = src10 * src12; - final float atmp10 = src8 * src13; - final float atmp11 = src9 * src12; + // calculate pairs for first 8 elements (cofactors) + final float atmp0 = src10 * src15; + final float atmp1 = src11 * src14; + final float atmp2 = src9 * src15; + final float atmp3 = src11 * src13; + final float atmp4 = src9 * src14; + final float atmp5 = src10 * src13; + final float atmp6 = src8 * src15; + final float atmp7 = src11 * src12; + final float atmp8 = src8 * src14; + final float atmp9 = src10 * src12; + final float atmp10 = src8 * src13; + final float atmp11 = src9 * src12; - // calculate first 8 elements (cofactors) - final float dst0 = (atmp0 * src5 + atmp3 * src6 + atmp4 * src7) - - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7); - final float dst1 = (atmp1 * src4 + atmp6 * src6 + atmp9 * src7) - - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7); - final float dst2 = (atmp2 * src4 + atmp7 * src5 + atmp10 * src7) - - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7); - final float dst3 = (atmp5 * src4 + atmp8 * src5 + atmp11 * src6) - - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6); - final float dst4 = (atmp1 * src1 + atmp2 * src2 + atmp5 * src3) - - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3); - final float dst5 = (atmp0 * src0 + atmp7 * src2 + atmp8 * src3) - - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3); - final float dst6 = (atmp3 * src0 + atmp6 * src1 + atmp11 * src3) - - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3); - final float dst7 = (atmp4 * src0 + atmp9 * src1 + atmp10 * src2) - - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2); + // calculate first 8 elements (cofactors) + final float dst0 = (atmp0 * src5 + atmp3 * src6 + atmp4 * src7) + - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7); + final float dst1 = (atmp1 * src4 + atmp6 * src6 + atmp9 * src7) + - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7); + final float dst2 = (atmp2 * src4 + atmp7 * src5 + atmp10 * src7) + - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7); + final float dst3 = (atmp5 * src4 + atmp8 * src5 + atmp11 * src6) + - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6); + final float dst4 = (atmp1 * src1 + atmp2 * src2 + atmp5 * src3) + - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3); + final float dst5 = (atmp0 * src0 + atmp7 * src2 + atmp8 * src3) + - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3); + final float dst6 = (atmp3 * src0 + atmp6 * src1 + atmp11 * src3) + - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3); + final float dst7 = (atmp4 * src0 + atmp9 * src1 + atmp10 * src2) + - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2); - // calculate pairs for second 8 elements (cofactors) - final float btmp0 = src2 * src7; - final float btmp1 = src3 * src6; - final float btmp2 = src1 * src7; - final float btmp3 = src3 * src5; - final float btmp4 = src1 * src6; - final float btmp5 = src2 * src5; - final float btmp6 = src0 * src7; - final float btmp7 = src3 * src4; - final float btmp8 = src0 * src6; - final float btmp9 = src2 * src4; - final float btmp10 = src0 * src5; - final float btmp11 = src1 * src4; + // calculate pairs for second 8 elements (cofactors) + final float btmp0 = src2 * src7; + final float btmp1 = src3 * src6; + final float btmp2 = src1 * src7; + final float btmp3 = src3 * src5; + final float btmp4 = src1 * src6; + final float btmp5 = src2 * src5; + final float btmp6 = src0 * src7; + final float btmp7 = src3 * src4; + final float btmp8 = src0 * src6; + final float btmp9 = src2 * src4; + final float btmp10 = src0 * src5; + final float btmp11 = src1 * src4; - // calculate second 8 elements (cofactors) - final float dst8 = (btmp0 * src13 + btmp3 * src14 + btmp4 * src15) - - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15); - final float dst9 = (btmp1 * src12 + btmp6 * src14 + btmp9 * src15) - - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15); - final float dst10 = (btmp2 * src12 + btmp7 * src13 + btmp10 * src15) - - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15); - final float dst11 = (btmp5 * src12 + btmp8 * src13 + btmp11 * src14) - - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14); - final float dst12 = (btmp2 * src10 + btmp5 * src11 + btmp1 * src9) - - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10); - final float dst13 = (btmp8 * src11 + btmp0 * src8 + btmp7 * src10) - - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8); - final float dst14 = (btmp6 * src9 + btmp11 * src11 + btmp3 * src8) - - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9); - final float dst15 = (btmp10 * src10 + btmp4 * src8 + btmp9 * src9) - - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8); + // calculate second 8 elements (cofactors) + final float dst8 = (btmp0 * src13 + btmp3 * src14 + btmp4 * src15) + - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15); + final float dst9 = (btmp1 * src12 + btmp6 * src14 + btmp9 * src15) + - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15); + final float dst10 = (btmp2 * src12 + btmp7 * src13 + btmp10 * src15) + - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15); + final float dst11 = (btmp5 * src12 + btmp8 * src13 + btmp11 * src14) + - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14); + final float dst12 = (btmp2 * src10 + btmp5 * src11 + btmp1 * src9) + - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10); + final float dst13 = (btmp8 * src11 + btmp0 * src8 + btmp7 * src10) + - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8); + final float dst14 = (btmp6 * src9 + btmp11 * src11 + btmp3 * src8) + - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9); + final float dst15 = (btmp10 * src10 + btmp4 * src8 + btmp9 * src9) + - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8); - // calculate determinant - final float det = - src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3; + // calculate determinant + final float det = + src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3; - if (det == 0.0f) { - return false; - } + if (det == 0.0f) { + return false; + } - // calculate matrix inverse - final float invdet = 1.0f / det; - mInv[mInvOffset] = dst0 * invdet; - mInv[1 + mInvOffset] = dst1 * invdet; - mInv[2 + mInvOffset] = dst2 * invdet; - mInv[3 + mInvOffset] = dst3 * invdet; + // calculate matrix inverse + final float invdet = 1.0f / det; + mInv[mInvOffset] = dst0 * invdet; + mInv[1 + mInvOffset] = dst1 * invdet; + mInv[2 + mInvOffset] = dst2 * invdet; + mInv[3 + mInvOffset] = dst3 * invdet; - mInv[4 + mInvOffset] = dst4 * invdet; - mInv[5 + mInvOffset] = dst5 * invdet; - mInv[6 + mInvOffset] = dst6 * invdet; - mInv[7 + mInvOffset] = dst7 * invdet; + mInv[4 + mInvOffset] = dst4 * invdet; + mInv[5 + mInvOffset] = dst5 * invdet; + mInv[6 + mInvOffset] = dst6 * invdet; + mInv[7 + mInvOffset] = dst7 * invdet; - mInv[8 + mInvOffset] = dst8 * invdet; - mInv[9 + mInvOffset] = dst9 * invdet; - mInv[10 + mInvOffset] = dst10 * invdet; - mInv[11 + mInvOffset] = dst11 * invdet; + mInv[8 + mInvOffset] = dst8 * invdet; + mInv[9 + mInvOffset] = dst9 * invdet; + mInv[10 + mInvOffset] = dst10 * invdet; + mInv[11 + mInvOffset] = dst11 * invdet; - mInv[12 + mInvOffset] = dst12 * invdet; - mInv[13 + mInvOffset] = dst13 * invdet; - mInv[14 + mInvOffset] = dst14 * invdet; - mInv[15 + mInvOffset] = dst15 * invdet; + mInv[12 + mInvOffset] = dst12 * invdet; + mInv[13 + mInvOffset] = dst13 * invdet; + mInv[14 + mInvOffset] = dst14 * invdet; + mInv[15 + mInvOffset] = dst15 * invdet; - return true; - } + return true; + } } diff --git a/vtm/src/org/oscim/renderer/GLShader.java b/vtm/src/org/oscim/renderer/GLShader.java index 3d1aa8a2..a4331e10 100644 --- a/vtm/src/org/oscim/renderer/GLShader.java +++ b/vtm/src/org/oscim/renderer/GLShader.java @@ -1,125 +1,125 @@ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.IntBuffer; - import org.oscim.backend.AssetAdapter; import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.IntBuffer; + +import static org.oscim.backend.GLAdapter.gl; + public abstract class GLShader { - final static Logger log = LoggerFactory.getLogger(GLShader.class); + final static Logger log = LoggerFactory.getLogger(GLShader.class); - public int program; + public int program; - protected boolean create(String vertexSource, String fragmentSource) { - program = createProgram(vertexSource, fragmentSource); - return program != 0; - } + protected boolean create(String vertexSource, String fragmentSource) { + program = createProgram(vertexSource, fragmentSource); + return program != 0; + } - protected boolean create(String fileName) { - program = loadShader(fileName); - return program != 0; - } + protected boolean create(String fileName) { + program = loadShader(fileName); + return program != 0; + } - protected int getAttrib(String name) { - int loc = gl.getAttribLocation(program, name); - if (loc < 0) - log.debug("missing attribute: {}", name); - return loc; - } + protected int getAttrib(String name) { + int loc = gl.getAttribLocation(program, name); + if (loc < 0) + log.debug("missing attribute: {}", name); + return loc; + } - protected int getUniform(String name) { - int loc = gl.getUniformLocation(program, name); - if (loc < 0) - log.debug("missing uniform: {}", name); - return loc; - } + protected int getUniform(String name) { + int loc = gl.getUniformLocation(program, name); + if (loc < 0) + log.debug("missing uniform: {}", name); + return loc; + } - public boolean useProgram() { - return GLState.useProgram(program); - } + public boolean useProgram() { + return GLState.useProgram(program); + } - public static int loadShader(String file) { - String path = "shaders/" + file + ".glsl"; - String vs = AssetAdapter.readTextFile(path); + public static int loadShader(String file) { + String path = "shaders/" + file + ".glsl"; + String vs = AssetAdapter.readTextFile(path); - if (vs == null) - throw new IllegalArgumentException("shader file not found: " + path); + if (vs == null) + throw new IllegalArgumentException("shader file not found: " + path); - // TODO ... - int fsStart = vs.indexOf('$'); - if (fsStart < 0 || vs.charAt(fsStart + 1) != '$') - throw new IllegalArgumentException("not a shader file " + path); + // TODO ... + int fsStart = vs.indexOf('$'); + if (fsStart < 0 || vs.charAt(fsStart + 1) != '$') + throw new IllegalArgumentException("not a shader file " + path); - String fs = vs.substring(fsStart + 2); - vs = vs.substring(0, fsStart); + String fs = vs.substring(fsStart + 2); + vs = vs.substring(0, fsStart); - int shader = createProgram(vs, fs); - if (shader == 0) { - System.out.println(vs + " \n\n" + fs); - } - return shader; - } + int shader = createProgram(vs, fs); + if (shader == 0) { + System.out.println(vs + " \n\n" + fs); + } + return shader; + } - public static int loadShader(int shaderType, String source) { + public static int loadShader(int shaderType, String source) { - int shader = gl.createShader(shaderType); - if (shader != 0) { - gl.shaderSource(shader, source); - gl.compileShader(shader); - IntBuffer compiled = MapRenderer.getIntBuffer(1); + int shader = gl.createShader(shaderType); + if (shader != 0) { + gl.shaderSource(shader, source); + gl.compileShader(shader); + IntBuffer compiled = MapRenderer.getIntBuffer(1); - gl.getShaderiv(shader, GL.COMPILE_STATUS, compiled); - compiled.position(0); - if (compiled.get() == 0) { - log.error("Could not compile shader " + shaderType + ":"); - log.error(gl.getShaderInfoLog(shader)); - gl.deleteShader(shader); - shader = 0; - } - } - return shader; - } + gl.getShaderiv(shader, GL.COMPILE_STATUS, compiled); + compiled.position(0); + if (compiled.get() == 0) { + log.error("Could not compile shader " + shaderType + ":"); + log.error(gl.getShaderInfoLog(shader)); + gl.deleteShader(shader); + shader = 0; + } + } + return shader; + } - public static int createProgram(String vertexSource, String fragmentSource) { - String defs = ""; - if (GLAdapter.GDX_DESKTOP_QUIRKS) - defs += "#define DESKTOP_QUIRKS 1\n"; - else - defs += "#define GLES 1\n"; + public static int createProgram(String vertexSource, String fragmentSource) { + String defs = ""; + if (GLAdapter.GDX_DESKTOP_QUIRKS) + defs += "#define DESKTOP_QUIRKS 1\n"; + else + defs += "#define GLES 1\n"; - int vertexShader = loadShader(GL.VERTEX_SHADER, defs + vertexSource); - if (vertexShader == 0) { - return 0; - } + int vertexShader = loadShader(GL.VERTEX_SHADER, defs + vertexSource); + if (vertexShader == 0) { + return 0; + } - int pixelShader = loadShader(GL.FRAGMENT_SHADER, defs + fragmentSource); - if (pixelShader == 0) { - return 0; - } + int pixelShader = loadShader(GL.FRAGMENT_SHADER, defs + fragmentSource); + if (pixelShader == 0) { + return 0; + } - int program = gl.createProgram(); - if (program != 0) { - GLUtils.checkGlError("glCreateProgram"); - gl.attachShader(program, vertexShader); - GLUtils.checkGlError("glAttachShader"); - gl.attachShader(program, pixelShader); - GLUtils.checkGlError("glAttachShader"); - gl.linkProgram(program); - IntBuffer linkStatus = MapRenderer.getIntBuffer(1); - gl.getProgramiv(program, GL.LINK_STATUS, linkStatus); - linkStatus.position(0); - if (linkStatus.get() != GL.TRUE) { - log.error("Could not link program: "); - log.error(gl.getProgramInfoLog(program)); - gl.deleteProgram(program); - program = 0; - } - } - return program; - } + int program = gl.createProgram(); + if (program != 0) { + GLUtils.checkGlError("glCreateProgram"); + gl.attachShader(program, vertexShader); + GLUtils.checkGlError("glAttachShader"); + gl.attachShader(program, pixelShader); + GLUtils.checkGlError("glAttachShader"); + gl.linkProgram(program); + IntBuffer linkStatus = MapRenderer.getIntBuffer(1); + gl.getProgramiv(program, GL.LINK_STATUS, linkStatus); + linkStatus.position(0); + if (linkStatus.get() != GL.TRUE) { + log.error("Could not link program: "); + log.error(gl.getProgramInfoLog(program)); + gl.deleteProgram(program); + program = 0; + } + } + return program; + } } diff --git a/vtm/src/org/oscim/renderer/GLState.java b/vtm/src/org/oscim/renderer/GLState.java index e380514e..f2b30670 100644 --- a/vtm/src/org/oscim/renderer/GLState.java +++ b/vtm/src/org/oscim/renderer/GLState.java @@ -17,196 +17,194 @@ */ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.backend.GLAdapter.gl; + public class GLState { - static final Logger log = LoggerFactory.getLogger(GLState.class); + static final Logger log = LoggerFactory.getLogger(GLState.class); - private final static boolean[] vertexArray = { false, false }; - private static boolean blend = false; - private static boolean depth = false; - private static boolean stencil = false; - private static int shader; - private static float[] clearColor; - private static int glVertexBuffer; - private static int glIndexBuffer; + private final static boolean[] vertexArray = {false, false}; + private static boolean blend = false; + private static boolean depth = false; + private static boolean stencil = false; + private static int shader; + private static float[] clearColor; + private static int glVertexBuffer; + private static int glIndexBuffer; - private static int currentTexId; + private static int currentTexId; - static void init() { - vertexArray[0] = false; - vertexArray[1] = false; - blend = false; - depth = false; - stencil = false; - shader = -1; - currentTexId = -1; - glVertexBuffer = -1; - glIndexBuffer = -1; - clearColor = null; + static void init() { + vertexArray[0] = false; + vertexArray[1] = false; + blend = false; + depth = false; + stencil = false; + shader = -1; + currentTexId = -1; + glVertexBuffer = -1; + glIndexBuffer = -1; + clearColor = null; - gl.disable(GL.STENCIL_TEST); - gl.disable(GL.DEPTH_TEST); - gl.disable(GL.BLEND); - } + gl.disable(GL.STENCIL_TEST); + gl.disable(GL.DEPTH_TEST); + gl.disable(GL.BLEND); + } - public static boolean useProgram(int shaderProgram) { - if (shaderProgram < 0) { - shader = -1; - } else if (shaderProgram != shader) { - gl.useProgram(shaderProgram); - shader = shaderProgram; - return true; - } - return false; - } + public static boolean useProgram(int shaderProgram) { + if (shaderProgram < 0) { + shader = -1; + } else if (shaderProgram != shader) { + gl.useProgram(shaderProgram); + shader = shaderProgram; + return true; + } + return false; + } - public static void blend(boolean enable) { - if (blend == enable) - return; + public static void blend(boolean enable) { + if (blend == enable) + return; - if (enable) - gl.enable(GL.BLEND); - else - gl.disable(GL.BLEND); - blend = enable; - } + if (enable) + gl.enable(GL.BLEND); + else + gl.disable(GL.BLEND); + blend = enable; + } - public static void testDepth(boolean enable) { - if (depth != enable) { + public static void testDepth(boolean enable) { + if (depth != enable) { - if (enable) - gl.enable(GL.DEPTH_TEST); - else - gl.disable(GL.DEPTH_TEST); + if (enable) + gl.enable(GL.DEPTH_TEST); + else + gl.disable(GL.DEPTH_TEST); - depth = enable; - } - } + depth = enable; + } + } - public static void test(boolean depthTest, boolean stencilTest) { - if (depth != depthTest) { + public static void test(boolean depthTest, boolean stencilTest) { + if (depth != depthTest) { - if (depthTest) - gl.enable(GL.DEPTH_TEST); - else - gl.disable(GL.DEPTH_TEST); + if (depthTest) + gl.enable(GL.DEPTH_TEST); + else + gl.disable(GL.DEPTH_TEST); - depth = depthTest; - } + depth = depthTest; + } - if (stencil != stencilTest) { + if (stencil != stencilTest) { - if (stencilTest) - gl.enable(GL.STENCIL_TEST); - else - gl.disable(GL.STENCIL_TEST); + if (stencilTest) + gl.enable(GL.STENCIL_TEST); + else + gl.disable(GL.STENCIL_TEST); - stencil = stencilTest; - } - } + stencil = stencilTest; + } + } - public static void enableVertexArrays(int va1, int va2) { - if (va1 > 1 || va2 > 1) - log.debug("FIXME: enableVertexArrays..."); + public static void enableVertexArrays(int va1, int va2) { + if (va1 > 1 || va2 > 1) + log.debug("FIXME: enableVertexArrays..."); - if ((va1 == 0 || va2 == 0)) { - if (!vertexArray[0]) { - gl.enableVertexAttribArray(0); - vertexArray[0] = true; - } - } else { - if (vertexArray[0]) { - gl.disableVertexAttribArray(0); - vertexArray[0] = false; - } - } + if ((va1 == 0 || va2 == 0)) { + if (!vertexArray[0]) { + gl.enableVertexAttribArray(0); + vertexArray[0] = true; + } + } else { + if (vertexArray[0]) { + gl.disableVertexAttribArray(0); + vertexArray[0] = false; + } + } - if ((va1 == 1 || va2 == 1)) { - if (!vertexArray[1]) { - gl.enableVertexAttribArray(1); - vertexArray[1] = true; - } - } else { - if (vertexArray[1]) { - gl.disableVertexAttribArray(1); - vertexArray[1] = false; - } - } - } + if ((va1 == 1 || va2 == 1)) { + if (!vertexArray[1]) { + gl.enableVertexAttribArray(1); + vertexArray[1] = true; + } + } else { + if (vertexArray[1]) { + gl.disableVertexAttribArray(1); + vertexArray[1] = false; + } + } + } - public static void bindTex2D(int id) { - if (id < 0) { - gl.bindTexture(GL.TEXTURE_2D, 0); - currentTexId = 0; - } else if (currentTexId != id) { - gl.bindTexture(GL.TEXTURE_2D, id); - currentTexId = id; - } - } + public static void bindTex2D(int id) { + if (id < 0) { + gl.bindTexture(GL.TEXTURE_2D, 0); + currentTexId = 0; + } else if (currentTexId != id) { + gl.bindTexture(GL.TEXTURE_2D, id); + currentTexId = id; + } + } - public static void setClearColor(float[] color) { - // Workaround for artifacts at canvas resize on desktop - if (!GLAdapter.GDX_DESKTOP_QUIRKS) { - if (clearColor != null && - color[0] == clearColor[0] && - color[1] == clearColor[1] && - color[2] == clearColor[2] && - color[3] == clearColor[3]) - return; - } + public static void setClearColor(float[] color) { + // Workaround for artifacts at canvas resize on desktop + if (!GLAdapter.GDX_DESKTOP_QUIRKS) { + if (clearColor != null && + color[0] == clearColor[0] && + color[1] == clearColor[1] && + color[2] == clearColor[2] && + color[3] == clearColor[3]) + return; + } - clearColor = color; - gl.clearColor(color[0], color[1], color[2], color[3]); - } + clearColor = color; + gl.clearColor(color[0], color[1], color[2], color[3]); + } - public static void bindBuffer(int target, int id) { - //log.debug(">> buffer {} {}", target == GL20.ARRAY_BUFFER, id); + public static void bindBuffer(int target, int id) { + //log.debug(">> buffer {} {}", target == GL20.ARRAY_BUFFER, id); - if (target == GL.ARRAY_BUFFER) { - if (glVertexBuffer == id) - return; - glVertexBuffer = id; - } - else if (target == GL.ELEMENT_ARRAY_BUFFER) { - if (glIndexBuffer == id) - return; - glIndexBuffer = id; - } - else { - log.debug("invalid target {}", target); - return; - } - //log.debug("bind buffer {} {}", target == GL20.ARRAY_BUFFER, id); + if (target == GL.ARRAY_BUFFER) { + if (glVertexBuffer == id) + return; + glVertexBuffer = id; + } else if (target == GL.ELEMENT_ARRAY_BUFFER) { + if (glIndexBuffer == id) + return; + glIndexBuffer = id; + } else { + log.debug("invalid target {}", target); + return; + } + //log.debug("bind buffer {} {}", target == GL20.ARRAY_BUFFER, id); - if (id >= 0) - gl.bindBuffer(target, id); - } + if (id >= 0) + gl.bindBuffer(target, id); + } - public static void bindElementBuffer(int id) { + public static void bindElementBuffer(int id) { - if (glIndexBuffer == id) - return; - glIndexBuffer = id; + if (glIndexBuffer == id) + return; + glIndexBuffer = id; - if (id >= 0) - gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, id); + if (id >= 0) + gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, id); - } + } - public static void bindVertexBuffer(int id) { + public static void bindVertexBuffer(int id) { - if (glVertexBuffer == id) - return; - glVertexBuffer = id; + if (glVertexBuffer == id) + return; + glVertexBuffer = id; - if (id >= 0) - gl.bindBuffer(GL.ARRAY_BUFFER, id); + if (id >= 0) + gl.bindBuffer(GL.ARRAY_BUFFER, id); - } + } } diff --git a/vtm/src/org/oscim/renderer/GLUtils.java b/vtm/src/org/oscim/renderer/GLUtils.java index 6abce470..4332f340 100644 --- a/vtm/src/org/oscim/renderer/GLUtils.java +++ b/vtm/src/org/oscim/renderer/GLUtils.java @@ -17,265 +17,263 @@ */ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; - import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; import org.oscim.utils.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; + +import static org.oscim.backend.GLAdapter.gl; + /** * Utility functions */ public class GLUtils { - static final Logger log = LoggerFactory.getLogger(GLUtils.class); + static final Logger log = LoggerFactory.getLogger(GLUtils.class); - public static void setColor(int location, int color, float alpha) { - if (alpha >= 1) - alpha = ((color >>> 24) & 0xff) / 255f; - else if (alpha < 0) - alpha = 0; - else - alpha *= ((color >>> 24) & 0xff) / 255f; + public static void setColor(int location, int color, float alpha) { + if (alpha >= 1) + alpha = ((color >>> 24) & 0xff) / 255f; + else if (alpha < 0) + alpha = 0; + else + alpha *= ((color >>> 24) & 0xff) / 255f; - if (alpha == 1) { - gl.uniform4f(location, - ((color >>> 16) & 0xff) / 255f, - ((color >>> 8) & 0xff) / 255f, - ((color >>> 0) & 0xff) / 255f, - alpha); - } else { - gl.uniform4f(location, - ((color >>> 16) & 0xff) / 255f * alpha, - ((color >>> 8) & 0xff) / 255f * alpha, - ((color >>> 0) & 0xff) / 255f * alpha, - alpha); - } - } + if (alpha == 1) { + gl.uniform4f(location, + ((color >>> 16) & 0xff) / 255f, + ((color >>> 8) & 0xff) / 255f, + ((color >>> 0) & 0xff) / 255f, + alpha); + } else { + gl.uniform4f(location, + ((color >>> 16) & 0xff) / 255f * alpha, + ((color >>> 8) & 0xff) / 255f * alpha, + ((color >>> 0) & 0xff) / 255f * alpha, + alpha); + } + } - public static void setColorBlend(int location, int color1, int color2, float mix) { - float a1 = (((color1 >>> 24) & 0xff) / 255f) * (1 - mix); - float a2 = (((color2 >>> 24) & 0xff) / 255f) * mix; - gl.uniform4f(location, - ((((color1 >>> 16) & 0xff) / 255f) * a1 - + (((color2 >>> 16) & 0xff) / 255f) * a2), - ((((color1 >>> 8) & 0xff) / 255f) * a1 - + (((color2 >>> 8) & 0xff) / 255f) * a2), - ((((color1 >>> 0) & 0xff) / 255f) * a1 - + (((color2 >>> 0) & 0xff) / 255f) * a2), - (a1 + a2)); - } + public static void setColorBlend(int location, int color1, int color2, float mix) { + float a1 = (((color1 >>> 24) & 0xff) / 255f) * (1 - mix); + float a2 = (((color2 >>> 24) & 0xff) / 255f) * mix; + gl.uniform4f(location, + ((((color1 >>> 16) & 0xff) / 255f) * a1 + + (((color2 >>> 16) & 0xff) / 255f) * a2), + ((((color1 >>> 8) & 0xff) / 255f) * a1 + + (((color2 >>> 8) & 0xff) / 255f) * a2), + ((((color1 >>> 0) & 0xff) / 255f) * a1 + + (((color2 >>> 0) & 0xff) / 255f) * a2), + (a1 + a2)); + } - public static void setTextureParameter(int min_filter, int mag_filter, int wrap_s, int wrap_t) { - gl.texParameterf(GL.TEXTURE_2D, - GL.TEXTURE_MIN_FILTER, - min_filter); - gl.texParameterf(GL.TEXTURE_2D, - GL.TEXTURE_MAG_FILTER, - mag_filter); - gl.texParameterf(GL.TEXTURE_2D, - GL.TEXTURE_WRAP_S, - wrap_s); // Set U Wrapping - gl.texParameterf(GL.TEXTURE_2D, - GL.TEXTURE_WRAP_T, - wrap_t); // Set V Wrapping - } + public static void setTextureParameter(int min_filter, int mag_filter, int wrap_s, int wrap_t) { + gl.texParameterf(GL.TEXTURE_2D, + GL.TEXTURE_MIN_FILTER, + min_filter); + gl.texParameterf(GL.TEXTURE_2D, + GL.TEXTURE_MAG_FILTER, + mag_filter); + gl.texParameterf(GL.TEXTURE_2D, + GL.TEXTURE_WRAP_S, + wrap_s); // Set U Wrapping + gl.texParameterf(GL.TEXTURE_2D, + GL.TEXTURE_WRAP_T, + wrap_t); // Set V Wrapping + } - public static int loadTexture(byte[] pixel, int width, int height, int format, - int min_filter, int mag_filter, int wrap_s, int wrap_t) { + public static int loadTexture(byte[] pixel, int width, int height, int format, + int min_filter, int mag_filter, int wrap_s, int wrap_t) { - int[] textureIds = GLUtils.glGenTextures(1); - GLState.bindTex2D(textureIds[0]); + int[] textureIds = GLUtils.glGenTextures(1); + GLState.bindTex2D(textureIds[0]); - setTextureParameter(min_filter, mag_filter, wrap_s, wrap_t); + setTextureParameter(min_filter, mag_filter, wrap_s, wrap_t); - ByteBuffer buf = ByteBuffer.allocateDirect(width * height).order(ByteOrder.nativeOrder()); - buf.put(pixel); - buf.position(0); - IntBuffer intBuf = buf.asIntBuffer(); - gl.texImage2D(GL.TEXTURE_2D, 0, format, width, height, 0, format, - GL.UNSIGNED_BYTE, intBuf); + ByteBuffer buf = ByteBuffer.allocateDirect(width * height).order(ByteOrder.nativeOrder()); + buf.put(pixel); + buf.position(0); + IntBuffer intBuf = buf.asIntBuffer(); + gl.texImage2D(GL.TEXTURE_2D, 0, format, width, height, 0, format, + GL.UNSIGNED_BYTE, intBuf); - GLState.bindTex2D(0); + GLState.bindTex2D(0); - return textureIds[0]; - } + return textureIds[0]; + } - public static int loadStippleTexture(byte[] stipple) { - int sum = 0; - for (byte flip : stipple) - sum += flip; + public static int loadStippleTexture(byte[] stipple) { + int sum = 0; + for (byte flip : stipple) + sum += flip; - byte[] pixel = new byte[sum]; + byte[] pixel = new byte[sum]; - boolean on = true; - int pos = 0; - for (byte flip : stipple) { - float max = flip; + boolean on = true; + int pos = 0; + for (byte flip : stipple) { + float max = flip; - for (int s = 0; s < flip; s++) { - float color = Math.abs(s / (max - 1) - 0.5f); - if (on) - color = 255 * (1 - color); - else - color = 255 * color; + for (int s = 0; s < flip; s++) { + float color = Math.abs(s / (max - 1) - 0.5f); + if (on) + color = 255 * (1 - color); + else + color = 255 * color; - pixel[pos + s] = FastMath.clampToByte((int) color); - } - on = !on; - pos += flip; - } + pixel[pos + s] = FastMath.clampToByte((int) color); + } + on = !on; + pos += flip; + } - return loadTexture(pixel, sum, 1, GL.ALPHA, - GL.LINEAR, GL.LINEAR, - // GLES20.GL_NEAREST, GLES20.GL_NEAREST, - GL.REPEAT, - GL.REPEAT); - } + return loadTexture(pixel, sum, 1, GL.ALPHA, + GL.LINEAR, GL.LINEAR, + // GLES20.GL_NEAREST, GLES20.GL_NEAREST, + GL.REPEAT, + GL.REPEAT); + } - public static void checkGlError(String op) { - //GL = GLAdapter.get(); + public static void checkGlError(String op) { + //GL = GLAdapter.get(); - int error; - while ((error = gl.getError()) != 0) { // GL20.NO_ERROR) { - log.error(op + ": glError " + error); - // throw new RuntimeException(op + ": glError " + error); - } - } + int error; + while ((error = gl.getError()) != 0) { // GL20.NO_ERROR) { + log.error(op + ": glError " + error); + // throw new RuntimeException(op + ": glError " + error); + } + } - public static boolean checkGlOutOfMemory(String op) { - int error; - boolean oom = false; - while ((error = gl.getError()) != 0) {// GL20.NO_ERROR) { - log.error(op + ": glError " + error); - // throw new RuntimeException(op + ": glError " + error); - if (error == 1285) - oom = true; - } - return oom; - } + public static boolean checkGlOutOfMemory(String op) { + int error; + boolean oom = false; + while ((error = gl.getError()) != 0) {// GL20.NO_ERROR) { + log.error(op + ": glError " + error); + // throw new RuntimeException(op + ": glError " + error); + if (error == 1285) + oom = true; + } + return oom; + } - public static void setColor(int handle, float[] c, float alpha) { - if (alpha >= 1) { - gl.uniform4f(handle, c[0], c[1], c[2], c[3]); - } else { - if (alpha < 0) { - log.debug("setColor: " + alpha); - alpha = 0; - gl.uniform4f(handle, 0, 0, 0, 0); - } + public static void setColor(int handle, float[] c, float alpha) { + if (alpha >= 1) { + gl.uniform4f(handle, c[0], c[1], c[2], c[3]); + } else { + if (alpha < 0) { + log.debug("setColor: " + alpha); + alpha = 0; + gl.uniform4f(handle, 0, 0, 0, 0); + } - gl.uniform4f(handle, - c[0] * alpha, c[1] * alpha, - c[2] * alpha, c[3] * alpha); - } - } + gl.uniform4f(handle, + c[0] * alpha, c[1] * alpha, + c[2] * alpha, c[3] * alpha); + } + } - public static float[] colorToFloat(int color) { - float[] c = new float[4]; - c[3] = (color >> 24 & 0xff) / 255.0f; - c[0] = (color >> 16 & 0xff) / 255.0f; - c[1] = (color >> 8 & 0xff) / 255.0f; - c[2] = (color >> 0 & 0xff) / 255.0f; - return c; - } + public static float[] colorToFloat(int color) { + float[] c = new float[4]; + c[3] = (color >> 24 & 0xff) / 255.0f; + c[0] = (color >> 16 & 0xff) / 255.0f; + c[1] = (color >> 8 & 0xff) / 255.0f; + c[2] = (color >> 0 & 0xff) / 255.0f; + return c; + } - // premultiply alpha - public static float[] colorToFloatP(int color) { - float[] c = new float[4]; - c[3] = (color >> 24 & 0xff) / 255.0f; - c[0] = (color >> 16 & 0xff) / 255.0f * c[3]; - c[1] = (color >> 8 & 0xff) / 255.0f * c[3]; - c[2] = (color >> 0 & 0xff) / 255.0f * c[3]; - return c; - } + // premultiply alpha + public static float[] colorToFloatP(int color) { + float[] c = new float[4]; + c[3] = (color >> 24 & 0xff) / 255.0f; + c[0] = (color >> 16 & 0xff) / 255.0f * c[3]; + c[1] = (color >> 8 & 0xff) / 255.0f * c[3]; + c[2] = (color >> 0 & 0xff) / 255.0f * c[3]; + return c; + } - /** - * public-domain function by Darel Rex Finley from - * http://alienryderflex.com/saturation.html - * - * @param color - * The passed-in RGB values can be on any desired scale, such as - * 0 to 1, or 0 to 255. - * @param change - * 0.0 creates a black-and-white image. 0.5 reduces the color - * saturation by half. 1.0 causes no change. 2.0 doubles the - * color saturation. - */ - public static void changeSaturation(float color[], float change) { - float r = color[0]; - float g = color[1]; - float b = color[2]; - double p = Math.sqrt(r * r * 0.299f + g * g * 0.587f + b * b * 0.114f); - color[0] = FastMath.clampN((float) (p + (r - p) * change)); - color[1] = FastMath.clampN((float) (p + (g - p) * change)); - color[2] = FastMath.clampN((float) (p + (b - p) * change)); - } + /** + * public-domain function by Darel Rex Finley from + * http://alienryderflex.com/saturation.html + * + * @param color The passed-in RGB values can be on any desired scale, such as + * 0 to 1, or 0 to 255. + * @param change 0.0 creates a black-and-white image. 0.5 reduces the color + * saturation by half. 1.0 causes no change. 2.0 doubles the + * color saturation. + */ + public static void changeSaturation(float color[], float change) { + float r = color[0]; + float g = color[1]; + float b = color[2]; + double p = Math.sqrt(r * r * 0.299f + g * g * 0.587f + b * b * 0.114f); + color[0] = FastMath.clampN((float) (p + (r - p) * change)); + color[1] = FastMath.clampN((float) (p + (g - p) * change)); + color[2] = FastMath.clampN((float) (p + (b - p) * change)); + } - public static void glUniform4fv(int location, int count, float[] val) { - FloatBuffer buf = MapRenderer.getFloatBuffer(count * 4); - buf.put(val); - buf.flip(); - gl.uniform4fv(location, count, buf); - } + public static void glUniform4fv(int location, int count, float[] val) { + FloatBuffer buf = MapRenderer.getFloatBuffer(count * 4); + buf.put(val); + buf.flip(); + gl.uniform4fv(location, count, buf); + } - public static int[] glGenBuffers(int num) { - IntBuffer buf = MapRenderer.getIntBuffer(num); - buf.position(0); - buf.limit(num); - gl.genBuffers(num, buf); - int[] ret = new int[num]; - buf.position(0); - buf.limit(num); - buf.get(ret); - return ret; - } + public static int[] glGenBuffers(int num) { + IntBuffer buf = MapRenderer.getIntBuffer(num); + buf.position(0); + buf.limit(num); + gl.genBuffers(num, buf); + int[] ret = new int[num]; + buf.position(0); + buf.limit(num); + buf.get(ret); + return ret; + } - public static void glDeleteBuffers(int num, int[] ids) { - IntBuffer buf = MapRenderer.getIntBuffer(num); - buf.put(ids, 0, num); - buf.flip(); - gl.deleteBuffers(num, buf); - } + public static void glDeleteBuffers(int num, int[] ids) { + IntBuffer buf = MapRenderer.getIntBuffer(num); + buf.put(ids, 0, num); + buf.flip(); + gl.deleteBuffers(num, buf); + } - public static int[] glGenTextures(int num) { - if (num <= 0) - return null; + public static int[] glGenTextures(int num) { + if (num <= 0) + return null; - int[] ret = new int[num]; - // Workaround for texture memory leaks on desktop - IntBuffer buf; - if (GLAdapter.GDX_DESKTOP_QUIRKS) - buf = ByteBuffer.allocateDirect(num * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); - else - buf = MapRenderer.getIntBuffer(num); + int[] ret = new int[num]; + // Workaround for texture memory leaks on desktop + IntBuffer buf; + if (GLAdapter.GDX_DESKTOP_QUIRKS) + buf = ByteBuffer.allocateDirect(num * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + else + buf = MapRenderer.getIntBuffer(num); - if (GLAdapter.GDX_WEBGL_QUIRKS) { - for (int i = 0; i < num; i++) { - gl.genTextures(num, buf); - buf.position(0); - ret[i] = buf.get(); - buf.position(0); - } - } else { - gl.genTextures(num, buf); - buf.position(0); - buf.get(ret); - } + if (GLAdapter.GDX_WEBGL_QUIRKS) { + for (int i = 0; i < num; i++) { + gl.genTextures(num, buf); + buf.position(0); + ret[i] = buf.get(); + buf.position(0); + } + } else { + gl.genTextures(num, buf); + buf.position(0); + buf.get(ret); + } - return ret; - } + return ret; + } - public static void glDeleteTextures(int num, int[] ids) { - IntBuffer buf = MapRenderer.getIntBuffer(num); - buf.put(ids, 0, num); - buf.flip(); - gl.deleteTextures(num, buf); - } + public static void glDeleteTextures(int num, int[] ids) { + IntBuffer buf = MapRenderer.getIntBuffer(num); + buf.put(ids, 0, num); + buf.flip(); + gl.deleteTextures(num, buf); + } } diff --git a/vtm/src/org/oscim/renderer/GLViewport.java b/vtm/src/org/oscim/renderer/GLViewport.java index c6f25a2d..e9d88d81 100644 --- a/vtm/src/org/oscim/renderer/GLViewport.java +++ b/vtm/src/org/oscim/renderer/GLViewport.java @@ -6,51 +6,61 @@ import org.oscim.map.Viewport; public class GLViewport extends Viewport { - /** Do not modify! */ - public final GLMatrix viewproj = mViewProjMatrix; - /** Do not modify! */ - public final GLMatrix proj = mProjMatrix; - /** Do not modify! */ - public final GLMatrix view = mViewMatrix; - /** Do not modify! */ - public final float[] plane = new float[8]; + /** + * Do not modify! + */ + public final GLMatrix viewproj = mViewProjMatrix; + /** + * Do not modify! + */ + public final GLMatrix proj = mProjMatrix; + /** + * Do not modify! + */ + public final GLMatrix view = mViewMatrix; + /** + * Do not modify! + */ + public final float[] plane = new float[8]; - /** For temporary use, to setup MVP-Matrix */ - public final GLMatrix mvp = new GLMatrix(); + /** + * For temporary use, to setup MVP-Matrix + */ + public final GLMatrix mvp = new GLMatrix(); - public final MapPosition pos = mPos; + public final MapPosition pos = mPos; - /** - * Set MVP so that coordinates are in screen pixel coordinates with 0,0 - * being center - */ - public void useScreenCoordinates(boolean center, float scale) { - float invScale = 1f / scale; + /** + * Set MVP so that coordinates are in screen pixel coordinates with 0,0 + * being center + */ + public void useScreenCoordinates(boolean center, float scale) { + float invScale = 1f / scale; - if (center) - mvp.setScale(invScale, invScale, invScale); - else - mvp.setTransScale(-mWidth / 2, -mHeight / 2, invScale); + if (center) + mvp.setScale(invScale, invScale, invScale); + else + mvp.setTransScale(-mWidth / 2, -mHeight / 2, invScale); - mvp.multiplyLhs(proj); - } + mvp.multiplyLhs(proj); + } - protected boolean changed; + protected boolean changed; - public boolean changed() { - return changed; - } + public boolean changed() { + return changed; + } - void setFrom(Map map) { - changed = map.viewport().getSyncViewport(this); - getMapExtents(plane, 0); - } + void setFrom(Map map) { + changed = map.viewport().getSyncViewport(this); + getMapExtents(plane, 0); + } - public float getWidth() { - return mWidth; - } + public float getWidth() { + return mWidth; + } - public float getHeight() { - return mHeight; - } + public float getHeight() { + return mHeight; + } } diff --git a/vtm/src/org/oscim/renderer/GridRenderer.java b/vtm/src/org/oscim/renderer/GridRenderer.java index f53d77df..a513b97b 100644 --- a/vtm/src/org/oscim/renderer/GridRenderer.java +++ b/vtm/src/org/oscim/renderer/GridRenderer.java @@ -29,118 +29,118 @@ import org.oscim.theme.styles.TextStyle; public class GridRenderer extends BucketRenderer { - private final TextBucket mTextBucket; - private final TextStyle mText; - private final LineBucket mLineBucket; - private final GeometryBuffer mLines; - private final StringBuilder mStringBuffer; + private final TextBucket mTextBucket; + private final TextStyle mText; + private final LineBucket mLineBucket; + private final GeometryBuffer mLines; + private final StringBuilder mStringBuffer; - private int mCurX, mCurY, mCurZ; + private int mCurX, mCurY, mCurZ; - public GridRenderer() { - this(1, new LineStyle(Color.LTGRAY, 1.2f, Cap.BUTT), - TextStyle.builder() - .fontSize(22) - .color(Color.RED) - .build()); - } + public GridRenderer() { + this(1, new LineStyle(Color.LTGRAY, 1.2f, Cap.BUTT), + TextStyle.builder() + .fontSize(22) + .color(Color.RED) + .build()); + } - public GridRenderer(int numLines, LineStyle lineStyle, TextStyle textStyle) { - int size = Tile.SIZE; + public GridRenderer(int numLines, LineStyle lineStyle, TextStyle textStyle) { + int size = Tile.SIZE; /* not needed to set but we know: 16 lines 'a' two points */ - mLines = new GeometryBuffer(2 * 16, 16); + mLines = new GeometryBuffer(2 * 16, 16); - float pos = -size * 4; + float pos = -size * 4; /* 8 vertical lines */ - for (int i = 0; i < 8 * numLines; i++) { - float x = pos + i * size / numLines; - mLines.startLine(); - mLines.addPoint(x, pos); - mLines.addPoint(x, pos + size * 8); - } + for (int i = 0; i < 8 * numLines; i++) { + float x = pos + i * size / numLines; + mLines.startLine(); + mLines.addPoint(x, pos); + mLines.addPoint(x, pos + size * 8); + } /* 8 horizontal lines */ - for (int j = 0; j < 8 * numLines; j++) { - float y = pos + j * size / numLines; - mLines.startLine(); - mLines.addPoint(pos, y); - mLines.addPoint(pos + size * 8, y); - } + for (int j = 0; j < 8 * numLines; j++) { + float y = pos + j * size / numLines; + mLines.startLine(); + mLines.addPoint(pos, y); + mLines.addPoint(pos + size * 8, y); + } - mText = textStyle; + mText = textStyle; - mLineBucket = new LineBucket(0); - mLineBucket.line = lineStyle; + mLineBucket = new LineBucket(0); + mLineBucket.line = lineStyle; - if (mText != null) { - mTextBucket = new TextBucket(); - mTextBucket.next = mLineBucket; - } else { - mTextBucket = null; - mLineBucket.addLine(mLines); - buckets.set(mLineBucket); - } + if (mText != null) { + mTextBucket = new TextBucket(); + mTextBucket.next = mLineBucket; + } else { + mTextBucket = null; + mLineBucket.addLine(mLines); + buckets.set(mLineBucket); + } - mStringBuffer = new StringBuilder(32); - } + mStringBuffer = new StringBuilder(32); + } - private void addLabels(int x, int y, int z) { - int s = Tile.SIZE; + private void addLabels(int x, int y, int z) { + int s = Tile.SIZE; - TextBucket tl = mTextBucket; - tl.clear(); + TextBucket tl = mTextBucket; + tl.clear(); - StringBuilder sb = mStringBuffer; + StringBuilder sb = mStringBuffer; - for (int yy = -2; yy < 2; yy++) { - for (int xx = -2; xx < 2; xx++) { + for (int yy = -2; yy < 2; yy++) { + for (int xx = -2; xx < 2; xx++) { - sb.setLength(0); - sb.append(z) - .append(" / ") - .append(x + xx) - .append(" / ") - .append(y + yy); + sb.setLength(0); + sb.append(z) + .append(" / ") + .append(x + xx) + .append(" / ") + .append(y + yy); - TextItem ti = TextItem.pool.get(); - ti.set(s * xx + s / 2, s * yy + s / 2, sb.toString(), mText); - tl.addText(ti); - } - } - } + TextItem ti = TextItem.pool.get(); + ti.set(s * xx + s / 2, s * yy + s / 2, sb.toString(), mText); + tl.addText(ti); + } + } + } - @Override - public void update(GLViewport v) { - /* scale coordinates relative to current 'zoom-level' to - * get the position as the nearest tile coordinate */ - int z = 1 << v.pos.zoomLevel; - int x = (int) (v.pos.x * z); - int y = (int) (v.pos.y * z); + @Override + public void update(GLViewport v) { + /* scale coordinates relative to current 'zoom-level' to + * get the position as the nearest tile coordinate */ + int z = 1 << v.pos.zoomLevel; + int x = (int) (v.pos.x * z); + int y = (int) (v.pos.y * z); /* update buckets when map moved by at least one tile */ - if (x == mCurX && y == mCurY && z == mCurZ) - return; + if (x == mCurX && y == mCurY && z == mCurZ) + return; - mCurX = x; - mCurY = y; - mCurZ = z; + mCurX = x; + mCurY = y; + mCurZ = z; - mMapPosition.copy(v.pos); - mMapPosition.x = (double) x / z; - mMapPosition.y = (double) y / z; - mMapPosition.scale = z; + mMapPosition.copy(v.pos); + mMapPosition.x = (double) x / z; + mMapPosition.y = (double) y / z; + mMapPosition.scale = z; - if (mText != null) { - buckets.set(mTextBucket); - addLabels(x, y, v.pos.zoomLevel); - mLineBucket.addLine(mLines); - buckets.prepare(); - setReady(false); - } + if (mText != null) { + buckets.set(mTextBucket); + addLabels(x, y, v.pos.zoomLevel); + mLineBucket.addLine(mLines); + buckets.prepare(); + setReady(false); + } - if (!isReady()) - compile(); - } + if (!isReady()) + compile(); + } } diff --git a/vtm/src/org/oscim/renderer/LayerRenderer.java b/vtm/src/org/oscim/renderer/LayerRenderer.java index 7f4a243e..84e54e2b 100644 --- a/vtm/src/org/oscim/renderer/LayerRenderer.java +++ b/vtm/src/org/oscim/renderer/LayerRenderer.java @@ -18,52 +18,55 @@ package org.oscim.renderer; public abstract class LayerRenderer { - /** flag to set when layer is ready for rendering */ - boolean isReady; + /** + * flag to set when layer is ready for rendering + */ + boolean isReady; - /** set by MapRenderer */ - boolean isInitialized; + /** + * set by MapRenderer + */ + boolean isInitialized; - /** - * Set 'ready for render' state when layer data is ready for rendering. - * - * @param ready true if render() should be called, false otherwise. - */ - protected void setReady(boolean ready) { - isReady = ready; - } + /** + * Set 'ready for render' state when layer data is ready for rendering. + * + * @param ready true if render() should be called, false otherwise. + */ + protected void setReady(boolean ready) { + isReady = ready; + } - public boolean isReady() { - return isReady; - } + public boolean isReady() { + return isReady; + } - /** - * 0. Called on GL Thread before first update(). - */ - public boolean setup() { - return true; - } + /** + * 0. Called on GL Thread before first update(). + */ + public boolean setup() { + return true; + } - /** - * 1. Called first by MapRenderer: Update the state here, compile - * vertex-data and set setReady(true). - * - * @param position current MapPosition - * @param changed - * true when MapPosition has changed since last frame - * @param matrices contains the current view- and projection-matrices - * and 'mvp' matrix for temporary use. - */ - public abstract void update(GLViewport viewport); + /** + * 1. Called first by MapRenderer: Update the state here, compile + * vertex-data and set setReady(true). + * + * @param position current MapPosition + * @param changed true when MapPosition has changed since last frame + * @param matrices contains the current view- and projection-matrices + * and 'mvp' matrix for temporary use. + */ + public abstract void update(GLViewport viewport); - /** - * 2. Draw layer: called by MapRenderer when isReady == true. - * - * @param position current MapPosition - * @param matrices contains the current view- and projection-matrices. - * 'matrices.mvp' is for temporary use to build the model- - * view-projection to set as uniform. - */ - public abstract void render(GLViewport viewport); + /** + * 2. Draw layer: called by MapRenderer when isReady == true. + * + * @param position current MapPosition + * @param matrices contains the current view- and projection-matrices. + * 'matrices.mvp' is for temporary use to build the model- + * view-projection to set as uniform. + */ + public abstract void render(GLViewport viewport); } diff --git a/vtm/src/org/oscim/renderer/MapRenderer.java b/vtm/src/org/oscim/renderer/MapRenderer.java index f55fc2bc..9209ae1e 100644 --- a/vtm/src/org/oscim/renderer/MapRenderer.java +++ b/vtm/src/org/oscim/renderer/MapRenderer.java @@ -16,12 +16,6 @@ */ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; import org.oscim.backend.canvas.Color; @@ -31,253 +25,265 @@ import org.oscim.renderer.bucket.TextureItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; + +import static org.oscim.backend.GLAdapter.gl; + public class MapRenderer { - static final Logger log = LoggerFactory.getLogger(MapRenderer.class); + static final Logger log = LoggerFactory.getLogger(MapRenderer.class); - /** scale factor used for short vertices */ - public static final float COORD_SCALE = 8.0f; + /** + * scale factor used for short vertices + */ + public static final float COORD_SCALE = 8.0f; - private final Map mMap; - private final GLViewport mViewport; + private final Map mMap; + private final GLViewport mViewport; - private static float[] mClearColor; + private static float[] mClearColor; - private static int mQuadIndicesID; - private static int mQuadVerticesID; + private static int mQuadIndicesID; + private static int mQuadVerticesID; - /** Number of Quads that can be rendered with bindQuadIndicesVBO() */ - public final static int MAX_QUADS = 512; - /** Number of Indices that can be rendered with bindQuadIndicesVBO() */ - public final static int MAX_INDICES = MAX_QUADS * 6; + /** + * Number of Quads that can be rendered with bindQuadIndicesVBO() + */ + public final static int MAX_QUADS = 512; + /** + * Number of Indices that can be rendered with bindQuadIndicesVBO() + */ + public final static int MAX_INDICES = MAX_QUADS * 6; - public static long frametime; - private static boolean rerender; + public static long frametime; + private static boolean rerender; - private static NativeBufferPool mBufferPool; + private static NativeBufferPool mBufferPool; - public MapRenderer(Map map) { - mMap = map; - mViewport = new GLViewport(); - mBufferPool = new NativeBufferPool(); + public MapRenderer(Map map) { + mMap = map; + mViewport = new GLViewport(); + mBufferPool = new NativeBufferPool(); /* FIXME should be done in 'destroy' method - * clear all previous vbo refs */ - BufferObject.clear(); - setBackgroundColor(Color.DKGRAY); - } + * clear all previous vbo refs */ + BufferObject.clear(); + setBackgroundColor(Color.DKGRAY); + } - public static void setBackgroundColor(int color) { - mClearColor = GLUtils.colorToFloat(color); - } + public static void setBackgroundColor(int color) { + mClearColor = GLUtils.colorToFloat(color); + } - public void onDrawFrame() { - frametime = System.currentTimeMillis(); - rerender = false; + public void onDrawFrame() { + frametime = System.currentTimeMillis(); + rerender = false; - mMap.beginFrame(); + mMap.beginFrame(); - draw(); + draw(); - mMap.doneFrame(rerender); + mMap.doneFrame(rerender); - mBufferPool.releaseBuffers(); - TextureItem.disposeTextures(); - } + mBufferPool.releaseBuffers(); + TextureItem.disposeTextures(); + } - private void draw() { + private void draw() { - GLState.setClearColor(mClearColor); + GLState.setClearColor(mClearColor); - gl.depthMask(true); - gl.stencilMask(0xFF); + gl.depthMask(true); + gl.stencilMask(0xFF); - gl.clear(GL.COLOR_BUFFER_BIT - | GL.DEPTH_BUFFER_BIT - | GL.STENCIL_BUFFER_BIT); + gl.clear(GL.COLOR_BUFFER_BIT + | GL.DEPTH_BUFFER_BIT + | GL.STENCIL_BUFFER_BIT); - gl.depthMask(false); - gl.stencilMask(0); + gl.depthMask(false); + gl.stencilMask(0); - GLState.test(false, false); - GLState.blend(false); - GLState.bindTex2D(-1); - GLState.useProgram(-1); - GLState.bindElementBuffer(-1); - GLState.bindVertexBuffer(-1); + GLState.test(false, false); + GLState.blend(false); + GLState.bindTex2D(-1); + GLState.useProgram(-1); + GLState.bindElementBuffer(-1); + GLState.bindVertexBuffer(-1); - mViewport.setFrom(mMap); + mViewport.setFrom(mMap); - if (GLAdapter.debugView) { - /* modify this to scale only the view, to see + if (GLAdapter.debugView) { + /* modify this to scale only the view, to see * which tiles are rendered */ - mViewport.mvp.setScale(0.5f, 0.5f, 1); - mViewport.viewproj.multiplyLhs(mViewport.mvp); - mViewport.proj.multiplyLhs(mViewport.mvp); - } + mViewport.mvp.setScale(0.5f, 0.5f, 1); + mViewport.viewproj.multiplyLhs(mViewport.mvp); + mViewport.proj.multiplyLhs(mViewport.mvp); + } /* update layers */ - LayerRenderer[] layers = mMap.layers().getLayerRenderer(); + LayerRenderer[] layers = mMap.layers().getLayerRenderer(); - for (int i = 0, n = layers.length; i < n; i++) { - LayerRenderer renderer = layers[i]; + for (int i = 0, n = layers.length; i < n; i++) { + LayerRenderer renderer = layers[i]; - if (!renderer.isInitialized) { - renderer.setup(); - renderer.isInitialized = true; - } + if (!renderer.isInitialized) { + renderer.setup(); + renderer.isInitialized = true; + } - renderer.update(mViewport); + renderer.update(mViewport); - if (renderer.isReady) - renderer.render(mViewport); + if (renderer.isReady) + renderer.render(mViewport); - if (GLAdapter.debug) - GLUtils.checkGlError(renderer.getClass().getName()); - } + if (GLAdapter.debug) + GLUtils.checkGlError(renderer.getClass().getName()); + } - if (GLUtils.checkGlOutOfMemory("finish")) { - BufferObject.checkBufferUsage(true); - // FIXME also throw out some textures etc - } - } + if (GLUtils.checkGlOutOfMemory("finish")) { + BufferObject.checkBufferUsage(true); + // FIXME also throw out some textures etc + } + } - public void onSurfaceChanged(int width, int height) { - //log.debug("onSurfaceChanged: new={}, {}x{}", mNewSurface, width, height); + public void onSurfaceChanged(int width, int height) { + //log.debug("onSurfaceChanged: new={}, {}x{}", mNewSurface, width, height); - if (width <= 0 || height <= 0) - return; + if (width <= 0 || height <= 0) + return; - gl.viewport(0, 0, width, height); + gl.viewport(0, 0, width, height); - //GL.scissor(0, 0, width, height); - //GL.enable(GL20.SCISSOR_TEST); + //GL.scissor(0, 0, width, height); + //GL.enable(GL20.SCISSOR_TEST); - gl.clearStencil(0x00); + gl.clearStencil(0x00); - gl.disable(GL.CULL_FACE); - gl.blendFunc(GL.ONE, GL.ONE_MINUS_SRC_ALPHA); + gl.disable(GL.CULL_FACE); + gl.blendFunc(GL.ONE, GL.ONE_MINUS_SRC_ALPHA); - gl.frontFace(GL.CW); - gl.cullFace(GL.BACK); + gl.frontFace(GL.CW); + gl.cullFace(GL.BACK); - if (!mNewSurface) { - mMap.updateMap(false); - return; - } + if (!mNewSurface) { + mMap.updateMap(false); + return; + } - mNewSurface = false; + mNewSurface = false; - /** initialize quad indices used by Texture- and LineTexRenderer */ - int[] vboIds = GLUtils.glGenBuffers(2); + /** initialize quad indices used by Texture- and LineTexRenderer */ + int[] vboIds = GLUtils.glGenBuffers(2); - mQuadIndicesID = vboIds[0]; + mQuadIndicesID = vboIds[0]; - short[] indices = new short[MAX_INDICES]; - for (int i = 0, j = 0; i < MAX_INDICES; i += 6, j += 4) { - indices[i + 0] = (short) (j + 0); - indices[i + 1] = (short) (j + 1); - indices[i + 2] = (short) (j + 2); + short[] indices = new short[MAX_INDICES]; + for (int i = 0, j = 0; i < MAX_INDICES; i += 6, j += 4) { + indices[i + 0] = (short) (j + 0); + indices[i + 1] = (short) (j + 1); + indices[i + 2] = (short) (j + 2); - indices[i + 3] = (short) (j + 2); - indices[i + 4] = (short) (j + 1); - indices[i + 5] = (short) (j + 3); - } - ShortBuffer buf = MapRenderer.getShortBuffer(indices.length); - buf.put(indices); - buf.flip(); + indices[i + 3] = (short) (j + 2); + indices[i + 4] = (short) (j + 1); + indices[i + 5] = (short) (j + 3); + } + ShortBuffer buf = MapRenderer.getShortBuffer(indices.length); + buf.put(indices); + buf.flip(); - GLState.bindElementBuffer(mQuadIndicesID); - gl.bufferData(GL.ELEMENT_ARRAY_BUFFER, - indices.length * 2, buf, - GL.STATIC_DRAW); - GLState.bindElementBuffer(0); + GLState.bindElementBuffer(mQuadIndicesID); + gl.bufferData(GL.ELEMENT_ARRAY_BUFFER, + indices.length * 2, buf, + GL.STATIC_DRAW); + GLState.bindElementBuffer(0); - /** initialize default quad */ - FloatBuffer floatBuffer = MapRenderer.getFloatBuffer(8); - float[] quad = new float[] { -1, -1, -1, 1, 1, -1, 1, 1 }; - floatBuffer.put(quad); - floatBuffer.flip(); - mQuadVerticesID = vboIds[1]; + /** initialize default quad */ + FloatBuffer floatBuffer = MapRenderer.getFloatBuffer(8); + float[] quad = new float[]{-1, -1, -1, 1, 1, -1, 1, 1}; + floatBuffer.put(quad); + floatBuffer.flip(); + mQuadVerticesID = vboIds[1]; - GLState.bindVertexBuffer(mQuadVerticesID); - gl.bufferData(GL.ARRAY_BUFFER, - quad.length * 4, floatBuffer, - GL.STATIC_DRAW); - GLState.bindVertexBuffer(0); + GLState.bindVertexBuffer(mQuadVerticesID); + gl.bufferData(GL.ARRAY_BUFFER, + quad.length * 4, floatBuffer, + GL.STATIC_DRAW); + GLState.bindVertexBuffer(0); - GLState.init(); + GLState.init(); - mMap.updateMap(true); - } + mMap.updateMap(true); + } - public void onSurfaceCreated() { - // log.debug(GL.getString(GL20.EXTENSIONS)); - String vendor = gl.getString(GL.VENDOR); - String renderer = gl.getString(GL.RENDERER); - String version = gl.getString(GL.VERSION); - log.debug("{}/{}/{}", vendor, renderer, version); + public void onSurfaceCreated() { + // log.debug(GL.getString(GL20.EXTENSIONS)); + String vendor = gl.getString(GL.VENDOR); + String renderer = gl.getString(GL.RENDERER); + String version = gl.getString(GL.VERSION); + log.debug("{}/{}/{}", vendor, renderer, version); - // Prevent issue with Adreno 3xx series - if (renderer != null && renderer.startsWith("Adreno (TM) 3")) { - log.debug("==> not using glBufferSubData"); - GLAdapter.NO_BUFFER_SUB_DATA = true; - } + // Prevent issue with Adreno 3xx series + if (renderer != null && renderer.startsWith("Adreno (TM) 3")) { + log.debug("==> not using glBufferSubData"); + GLAdapter.NO_BUFFER_SUB_DATA = true; + } - GLState.init(); + GLState.init(); - // Set up some vertex buffer objects - BufferObject.init(200); + // Set up some vertex buffer objects + BufferObject.init(200); - // classes that require GL context for initialization - RenderBuckets.initRenderer(); + // classes that require GL context for initialization + RenderBuckets.initRenderer(); - mNewSurface = true; - } + mNewSurface = true; + } - private boolean mNewSurface; + private boolean mNewSurface; - /** - * Bind VBO for a simple quad. Handy for simple custom RenderLayers - * Vertices: float[]{ -1, -1, -1, 1, 1, -1, 1, 1 } - * - * GL.drawArrays(GL20.TRIANGLE_STRIP, 0, 4); - */ - public static void bindQuadVertexVBO(int location) { + /** + * Bind VBO for a simple quad. Handy for simple custom RenderLayers + * Vertices: float[]{ -1, -1, -1, 1, 1, -1, 1, 1 } + *

+ * GL.drawArrays(GL20.TRIANGLE_STRIP, 0, 4); + */ + public static void bindQuadVertexVBO(int location) { - if (location >= 0) { - GLState.bindVertexBuffer(mQuadVerticesID); - GLState.enableVertexArrays(location, -1); - gl.vertexAttribPointer(location, 2, GL.FLOAT, false, 0, 0); - } - } + if (location >= 0) { + GLState.bindVertexBuffer(mQuadVerticesID); + GLState.enableVertexArrays(location, -1); + gl.vertexAttribPointer(location, 2, GL.FLOAT, false, 0, 0); + } + } - /** - * Bind indices for rendering up to MAX_QUADS (512), - * ie. MAX_INDICES (512*6) in one draw call. - * Vertex order is 0-1-2 2-1-3 - */ - public static void bindQuadIndicesVBO() { - GLState.bindElementBuffer(mQuadIndicesID); - } + /** + * Bind indices for rendering up to MAX_QUADS (512), + * ie. MAX_INDICES (512*6) in one draw call. + * Vertex order is 0-1-2 2-1-3 + */ + public static void bindQuadIndicesVBO() { + GLState.bindElementBuffer(mQuadIndicesID); + } - /** - * Trigger next redraw from GL-Thread. This should be used to animate - * LayerRenderers instead of calling Map.render(). - */ - public static void animate() { - rerender = true; - } + /** + * Trigger next redraw from GL-Thread. This should be used to animate + * LayerRenderers instead of calling Map.render(). + */ + public static void animate() { + rerender = true; + } - public static FloatBuffer getFloatBuffer(int size) { - return mBufferPool.getFloatBuffer(size); - } + public static FloatBuffer getFloatBuffer(int size) { + return mBufferPool.getFloatBuffer(size); + } - public static ShortBuffer getShortBuffer(int size) { - return mBufferPool.getShortBuffer(size); - } + public static ShortBuffer getShortBuffer(int size) { + return mBufferPool.getShortBuffer(size); + } - public static IntBuffer getIntBuffer(int size) { - return mBufferPool.getIntBuffer(size); - } + public static IntBuffer getIntBuffer(int size) { + return mBufferPool.getIntBuffer(size); + } } diff --git a/vtm/src/org/oscim/renderer/NativeBufferPool.java b/vtm/src/org/oscim/renderer/NativeBufferPool.java index 5f2d72ab..269ee66a 100644 --- a/vtm/src/org/oscim/renderer/NativeBufferPool.java +++ b/vtm/src/org/oscim/renderer/NativeBufferPool.java @@ -1,15 +1,15 @@ package org.oscim.renderer; +import org.oscim.renderer.NativeBufferPool.BufferItem; +import org.oscim.utils.pool.Inlist; +import org.oscim.utils.pool.Pool; + import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; -import org.oscim.renderer.NativeBufferPool.BufferItem; -import org.oscim.utils.pool.Inlist; -import org.oscim.utils.pool.Pool; - /** * Pool to retrieve temporary native buffer on GL-Thread: * This pool ensures to not use the same buffer to upload data twice @@ -21,103 +21,103 @@ import org.oscim.utils.pool.Pool; */ public class NativeBufferPool extends Pool { - static final class BufferItem extends Inlist { - ByteBuffer byteBuffer; - ShortBuffer sBuffer; - FloatBuffer fBuffer; - IntBuffer iBuffer; + static final class BufferItem extends Inlist { + ByteBuffer byteBuffer; + ShortBuffer sBuffer; + FloatBuffer fBuffer; + IntBuffer iBuffer; - int size; + int size; - void growBuffer(int size) { - //log.debug("grow buffer " + size); - // 32kb min size - if (size < (1 << 15)) - size = (1 << 15); + void growBuffer(int size) { + //log.debug("grow buffer " + size); + // 32kb min size + if (size < (1 << 15)) + size = (1 << 15); - byteBuffer = ByteBuffer - .allocateDirect(size) - .order(ByteOrder.nativeOrder()); - this.size = size; + byteBuffer = ByteBuffer + .allocateDirect(size) + .order(ByteOrder.nativeOrder()); + this.size = size; - sBuffer = null; - iBuffer = null; - fBuffer = null; - } - } + sBuffer = null; + iBuffer = null; + fBuffer = null; + } + } - private BufferItem mUsedBuffers; + private BufferItem mUsedBuffers; - @Override - protected BufferItem createItem() { - // unused; - return null; - } + @Override + protected BufferItem createItem() { + // unused; + return null; + } - public BufferItem get(int size) { - BufferItem b = mPool; + public BufferItem get(int size) { + BufferItem b = mPool; - if (b == null) { - b = new BufferItem(); - } else { - mPool = b.next; - b.next = null; - } - if (b.size < size) - b.growBuffer(size); + if (b == null) { + b = new BufferItem(); + } else { + mPool = b.next; + b.next = null; + } + if (b.size < size) + b.growBuffer(size); - mUsedBuffers = Inlist.push(mUsedBuffers, b); + mUsedBuffers = Inlist.push(mUsedBuffers, b); - return b; - } + return b; + } - public void releaseBuffers() { - mUsedBuffers = releaseAll(mUsedBuffers); - } + public void releaseBuffers() { + mUsedBuffers = releaseAll(mUsedBuffers); + } - /** - * Only use on GL Thread! Get a native ShortBuffer for temporary use. - */ - public ShortBuffer getShortBuffer(int size) { - BufferItem b = get(size * 2); + /** + * Only use on GL Thread! Get a native ShortBuffer for temporary use. + */ + public ShortBuffer getShortBuffer(int size) { + BufferItem b = get(size * 2); - if (b.sBuffer == null) { - b.byteBuffer.clear(); - b.sBuffer = b.byteBuffer.asShortBuffer(); - } else { - b.sBuffer.clear(); - } - return b.sBuffer; - } + if (b.sBuffer == null) { + b.byteBuffer.clear(); + b.sBuffer = b.byteBuffer.asShortBuffer(); + } else { + b.sBuffer.clear(); + } + return b.sBuffer; + } - /** - * Only use on GL Thread! Get a native FloatBuffer for temporary use. - */ - public FloatBuffer getFloatBuffer(int size) { - BufferItem b = get(size * 4); - if (b.fBuffer == null) { - b.byteBuffer.clear(); - b.fBuffer = b.byteBuffer.asFloatBuffer(); - } else { - b.fBuffer.clear(); - } - b.fBuffer.clear(); + /** + * Only use on GL Thread! Get a native FloatBuffer for temporary use. + */ + public FloatBuffer getFloatBuffer(int size) { + BufferItem b = get(size * 4); + if (b.fBuffer == null) { + b.byteBuffer.clear(); + b.fBuffer = b.byteBuffer.asFloatBuffer(); + } else { + b.fBuffer.clear(); + } + b.fBuffer.clear(); - return b.fBuffer; - } + return b.fBuffer; + } - /** - * Only use on GL Thread! Get a native IntBuffer for temporary use. - */ - public IntBuffer getIntBuffer(int size) { - BufferItem b = get(size * 4); - if (b.iBuffer == null) { - b.byteBuffer.clear(); - b.iBuffer = b.byteBuffer.asIntBuffer(); - } else { - b.iBuffer.clear(); - } - return b.iBuffer; - } + /** + * Only use on GL Thread! Get a native IntBuffer for temporary use. + */ + public IntBuffer getIntBuffer(int size) { + BufferItem b = get(size * 4); + if (b.iBuffer == null) { + b.byteBuffer.clear(); + b.iBuffer = b.byteBuffer.asIntBuffer(); + } else { + b.iBuffer.clear(); + } + return b.iBuffer; + } } diff --git a/vtm/src/org/oscim/renderer/OffscreenRenderer.java b/vtm/src/org/oscim/renderer/OffscreenRenderer.java index c032431d..a4c8b2cc 100644 --- a/vtm/src/org/oscim/renderer/OffscreenRenderer.java +++ b/vtm/src/org/oscim/renderer/OffscreenRenderer.java @@ -1,228 +1,228 @@ package org.oscim.renderer; -import static org.oscim.backend.GLAdapter.gl; - -import java.nio.IntBuffer; - import org.oscim.backend.GL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.IntBuffer; + +import static org.oscim.backend.GLAdapter.gl; + public class OffscreenRenderer extends LayerRenderer { - final static Logger log = LoggerFactory.getLogger(OffscreenRenderer.class); + final static Logger log = LoggerFactory.getLogger(OffscreenRenderer.class); - public enum Mode { - FXAA, - SSAO, - SSAO_FXAA, - BYPASS - } + public enum Mode { + FXAA, + SSAO, + SSAO_FXAA, + BYPASS + } - int fb; - int renderTex; - int renderDepth; + int fb; + int renderTex; + int renderDepth; - int texW = -1; - int texH = -1; + int texW = -1; + int texH = -1; - boolean initialized; - private float[] mClearColor = { 0, 0, 0, 0 }; + boolean initialized; + private float[] mClearColor = {0, 0, 0, 0}; - private boolean useDepthTexture = false; - private Shader mShader; + private boolean useDepthTexture = false; + private Shader mShader; - static class Shader extends GLShader { - int aPos, uTexDepth, uTexColor, uPixel; + static class Shader extends GLShader { + int aPos, uTexDepth, uTexColor, uPixel; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; - aPos = getAttrib("a_pos"); - uTexColor = getUniform("u_texColor"); - uTexDepth = getUniform("u_tex"); - uPixel = getUniform("u_pixel"); - } - } + Shader(String shaderFile) { + if (!create(shaderFile)) + return; + aPos = getAttrib("a_pos"); + uTexColor = getUniform("u_texColor"); + uTexDepth = getUniform("u_tex"); + uPixel = getUniform("u_pixel"); + } + } - public final Mode mode; + public final Mode mode; - public OffscreenRenderer(Mode mode, LayerRenderer renderer) { - this.mode = mode; - if (mode == Mode.SSAO || mode == Mode.SSAO_FXAA) - useDepthTexture = true; - setRenderer(renderer); - } + public OffscreenRenderer(Mode mode, LayerRenderer renderer) { + this.mode = mode; + if (mode == Mode.SSAO || mode == Mode.SSAO_FXAA) + useDepthTexture = true; + setRenderer(renderer); + } - protected boolean setupFBO(GLViewport viewport) { - IntBuffer buf = MapRenderer.getIntBuffer(1); + protected boolean setupFBO(GLViewport viewport) { + IntBuffer buf = MapRenderer.getIntBuffer(1); - texW = (int) viewport.getWidth(); - texH = (int) viewport.getHeight(); + texW = (int) viewport.getWidth(); + texH = (int) viewport.getHeight(); - gl.genFramebuffers(1, buf); - fb = buf.get(0); + gl.genFramebuffers(1, buf); + fb = buf.get(0); - buf.clear(); - gl.genTextures(1, buf); - renderTex = buf.get(0); + buf.clear(); + gl.genTextures(1, buf); + renderTex = buf.get(0); - GLUtils.checkGlError("0"); + GLUtils.checkGlError("0"); - gl.bindFramebuffer(GL.FRAMEBUFFER, fb); + gl.bindFramebuffer(GL.FRAMEBUFFER, fb); - // generate color texture - gl.bindTexture(GL.TEXTURE_2D, renderTex); + // generate color texture + gl.bindTexture(GL.TEXTURE_2D, renderTex); - GLUtils.setTextureParameter( - GL.LINEAR, - GL.LINEAR, - //GL20.NEAREST, - //GL20.NEAREST, - GL.CLAMP_TO_EDGE, - GL.CLAMP_TO_EDGE); + GLUtils.setTextureParameter( + GL.LINEAR, + GL.LINEAR, + //GL20.NEAREST, + //GL20.NEAREST, + GL.CLAMP_TO_EDGE, + GL.CLAMP_TO_EDGE); - gl.texImage2D(GL.TEXTURE_2D, 0, - GL.RGBA, texW, texH, 0, GL.RGBA, - GL.UNSIGNED_BYTE, null); + gl.texImage2D(GL.TEXTURE_2D, 0, + GL.RGBA, texW, texH, 0, GL.RGBA, + GL.UNSIGNED_BYTE, null); - gl.framebufferTexture2D(GL.FRAMEBUFFER, - GL.COLOR_ATTACHMENT0, - GL.TEXTURE_2D, - renderTex, 0); - GLUtils.checkGlError("1"); + gl.framebufferTexture2D(GL.FRAMEBUFFER, + GL.COLOR_ATTACHMENT0, + GL.TEXTURE_2D, + renderTex, 0); + GLUtils.checkGlError("1"); - if (useDepthTexture) { - buf.clear(); - gl.genTextures(1, buf); - renderDepth = buf.get(0); - gl.bindTexture(GL.TEXTURE_2D, renderDepth); - GLUtils.setTextureParameter(GL.NEAREST, - GL.NEAREST, - GL.CLAMP_TO_EDGE, - GL.CLAMP_TO_EDGE); + if (useDepthTexture) { + buf.clear(); + gl.genTextures(1, buf); + renderDepth = buf.get(0); + gl.bindTexture(GL.TEXTURE_2D, renderDepth); + GLUtils.setTextureParameter(GL.NEAREST, + GL.NEAREST, + GL.CLAMP_TO_EDGE, + GL.CLAMP_TO_EDGE); - gl.texImage2D(GL.TEXTURE_2D, 0, - GL.DEPTH_COMPONENT, - texW, texH, 0, - GL.DEPTH_COMPONENT, - GL.UNSIGNED_SHORT, null); + gl.texImage2D(GL.TEXTURE_2D, 0, + GL.DEPTH_COMPONENT, + texW, texH, 0, + GL.DEPTH_COMPONENT, + GL.UNSIGNED_SHORT, null); - gl.framebufferTexture2D(GL.FRAMEBUFFER, - GL.DEPTH_ATTACHMENT, - GL.TEXTURE_2D, - renderDepth, 0); - } else { - buf.clear(); - gl.genRenderbuffers(1, buf); - int depthRenderbuffer = buf.get(0); + gl.framebufferTexture2D(GL.FRAMEBUFFER, + GL.DEPTH_ATTACHMENT, + GL.TEXTURE_2D, + renderDepth, 0); + } else { + buf.clear(); + gl.genRenderbuffers(1, buf); + int depthRenderbuffer = buf.get(0); - gl.bindRenderbuffer(GL.RENDERBUFFER, depthRenderbuffer); + gl.bindRenderbuffer(GL.RENDERBUFFER, depthRenderbuffer); - gl.renderbufferStorage(GL.RENDERBUFFER, - GL.DEPTH_COMPONENT16, - texW, texH); + gl.renderbufferStorage(GL.RENDERBUFFER, + GL.DEPTH_COMPONENT16, + texW, texH); - gl.framebufferRenderbuffer(GL.FRAMEBUFFER, - GL.DEPTH_ATTACHMENT, - GL.RENDERBUFFER, - depthRenderbuffer); - } + gl.framebufferRenderbuffer(GL.FRAMEBUFFER, + GL.DEPTH_ATTACHMENT, + GL.RENDERBUFFER, + depthRenderbuffer); + } - GLUtils.checkGlError("2"); + GLUtils.checkGlError("2"); - int status = gl.checkFramebufferStatus(GL.FRAMEBUFFER); - gl.bindFramebuffer(GL.FRAMEBUFFER, 0); - gl.bindTexture(GL.TEXTURE_2D, 0); + int status = gl.checkFramebufferStatus(GL.FRAMEBUFFER); + gl.bindFramebuffer(GL.FRAMEBUFFER, 0); + gl.bindTexture(GL.TEXTURE_2D, 0); - if (status != GL.FRAMEBUFFER_COMPLETE) { - log.debug("invalid framebuffer! " + status); - return false; - } - return true; - } + if (status != GL.FRAMEBUFFER_COMPLETE) { + log.debug("invalid framebuffer! " + status); + return false; + } + return true; + } - public void enable(boolean on) { - if (on) - gl.bindFramebuffer(GL.FRAMEBUFFER, fb); - else - gl.bindFramebuffer(GL.FRAMEBUFFER, 0); - } + public void enable(boolean on) { + if (on) + gl.bindFramebuffer(GL.FRAMEBUFFER, fb); + else + gl.bindFramebuffer(GL.FRAMEBUFFER, 0); + } - public void begin() { - gl.bindFramebuffer(GL.FRAMEBUFFER, fb); - gl.depthMask(true); - gl.clear(GL.DEPTH_BUFFER_BIT); - } + public void begin() { + gl.bindFramebuffer(GL.FRAMEBUFFER, fb); + gl.depthMask(true); + gl.clear(GL.DEPTH_BUFFER_BIT); + } - LayerRenderer mRenderer; + LayerRenderer mRenderer; - public void setRenderer(LayerRenderer renderer) { - mRenderer = renderer; - } + public void setRenderer(LayerRenderer renderer) { + mRenderer = renderer; + } - @Override - public boolean setup() { - mRenderer.setup(); - return super.setup(); - } + @Override + public boolean setup() { + mRenderer.setup(); + return super.setup(); + } - @Override - public void update(GLViewport viewport) { - if (texW != viewport.getWidth() || texH != viewport.getHeight()) { - setupFBO(viewport); - switch (mode) { - case FXAA: - mShader = new Shader("post_fxaa"); - break; - case SSAO: - mShader = new Shader("post_ssao"); - break; - case SSAO_FXAA: - mShader = new Shader("post_combined"); - break; - case BYPASS: - mShader = new Shader("post_bypass"); - break; - } - } - mRenderer.update(viewport); - setReady(mRenderer.isReady()); - } + @Override + public void update(GLViewport viewport) { + if (texW != viewport.getWidth() || texH != viewport.getHeight()) { + setupFBO(viewport); + switch (mode) { + case FXAA: + mShader = new Shader("post_fxaa"); + break; + case SSAO: + mShader = new Shader("post_ssao"); + break; + case SSAO_FXAA: + mShader = new Shader("post_combined"); + break; + case BYPASS: + mShader = new Shader("post_bypass"); + break; + } + } + mRenderer.update(viewport); + setReady(mRenderer.isReady()); + } - @Override - public void render(GLViewport viewport) { - gl.bindFramebuffer(GL.FRAMEBUFFER, fb); - gl.viewport(0, 0, texW, texH); - gl.depthMask(true); - GLState.setClearColor(mClearColor); - gl.clear(GL.DEPTH_BUFFER_BIT | GL.COLOR_BUFFER_BIT); + @Override + public void render(GLViewport viewport) { + gl.bindFramebuffer(GL.FRAMEBUFFER, fb); + gl.viewport(0, 0, texW, texH); + gl.depthMask(true); + GLState.setClearColor(mClearColor); + gl.clear(GL.DEPTH_BUFFER_BIT | GL.COLOR_BUFFER_BIT); - mRenderer.render(viewport); + mRenderer.render(viewport); - gl.bindFramebuffer(GL.FRAMEBUFFER, 0); + gl.bindFramebuffer(GL.FRAMEBUFFER, 0); - mShader.useProgram(); + mShader.useProgram(); /* bind depth texture */ - if (useDepthTexture) { - gl.activeTexture(GL.TEXTURE1); - GLState.bindTex2D(renderDepth); - gl.uniform1i(mShader.uTexDepth, 1); - gl.activeTexture(GL.TEXTURE0); - } - /* bind color texture */ - GLState.bindTex2D(renderTex); - gl.uniform1i(mShader.uTexColor, 0); + if (useDepthTexture) { + gl.activeTexture(GL.TEXTURE1); + GLState.bindTex2D(renderDepth); + gl.uniform1i(mShader.uTexDepth, 1); + gl.activeTexture(GL.TEXTURE0); + } + /* bind color texture */ + GLState.bindTex2D(renderTex); + gl.uniform1i(mShader.uTexColor, 0); - MapRenderer.bindQuadVertexVBO(mShader.aPos); + MapRenderer.bindQuadVertexVBO(mShader.aPos); - gl.uniform2f(mShader.uPixel, - (float) (1.0 / texW * 0.5), - (float) (1.0 / texH * 0.5)); + gl.uniform2f(mShader.uPixel, + (float) (1.0 / texW * 0.5), + (float) (1.0 / texH * 0.5)); - GLState.test(false, false); - GLState.blend(true); - gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); - GLUtils.checkGlError("...."); - } + GLState.test(false, false); + GLState.blend(true); + gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); + GLUtils.checkGlError("...."); + } } diff --git a/vtm/src/org/oscim/renderer/atlas/TextureAtlas.java b/vtm/src/org/oscim/renderer/atlas/TextureAtlas.java index 482f7320..9b0f1b97 100644 --- a/vtm/src/org/oscim/renderer/atlas/TextureAtlas.java +++ b/vtm/src/org/oscim/renderer/atlas/TextureAtlas.java @@ -61,192 +61,200 @@ */ package org.oscim.renderer.atlas; -import java.util.HashMap; - import org.oscim.backend.canvas.Bitmap; import org.oscim.renderer.bucket.TextureItem; import org.oscim.utils.pool.Inlist; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.HashMap; + public class TextureAtlas extends Inlist { - static final Logger log = LoggerFactory.getLogger(TextureAtlas.class); + static final Logger log = LoggerFactory.getLogger(TextureAtlas.class); - /** Allocated slots */ - public Slot mSlots; - private Rect mRects; + /** + * Allocated slots + */ + public Slot mSlots; + private Rect mRects; - /** Width (in pixels) of the underlying texture */ - final int mWidth; + /** + * Width (in pixels) of the underlying texture + */ + final int mWidth; - /** Height (in pixels) of the underlying texture */ - final int mHeight; + /** + * Height (in pixels) of the underlying texture + */ + final int mHeight; - /** Depth (in bytes) of the underlying texture */ + /** Depth (in bytes) of the underlying texture */ - /** Allocated surface size */ - int mUsed; + /** + * Allocated surface size + */ + int mUsed; - public TextureItem texture; + public TextureItem texture; - public static class Slot extends Inlist { - public int x, y, w; + public static class Slot extends Inlist { + public int x, y, w; - public Slot(int x, int y, int w) { - this.x = x; - this.y = y; - this.w = w; - } - } + public Slot(int x, int y, int w) { + this.x = x; + this.y = y; + this.w = w; + } + } - public static class Rect extends Inlist { - public Rect(int x, int y, int w, int h) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } + public static class Rect extends Inlist { + public Rect(int x, int y, int w, int h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } - public int x, y, w, h; + public int x, y, w, h; - @Override - public String toString() { - return x + ":" + y + " " + w + "x" + h; - } - } + @Override + public String toString() { + return x + ":" + y + " " + w + "x" + h; + } + } - public TextureAtlas(int width, int height) { - mWidth = width; - mHeight = height; - mSlots = new Slot(1, 1, width - 2); - } + public TextureAtlas(int width, int height) { + mWidth = width; + mHeight = height; + mSlots = new Slot(1, 1, width - 2); + } - public TextureAtlas(Bitmap bitmap) { - texture = new TextureItem(bitmap); - mWidth = texture.width; - mHeight = texture.height; + public TextureAtlas(Bitmap bitmap) { + texture = new TextureItem(bitmap); + mWidth = texture.width; + mHeight = texture.height; - mRegions = new HashMap(); - } + mRegions = new HashMap(); + } - private HashMap mRegions; + private HashMap mRegions; - public void addTextureRegion(Object key, Rect r) { + public void addTextureRegion(Object key, Rect r) { - mRegions.put(key, new TextureRegion(this.texture, r)); + mRegions.put(key, new TextureRegion(this.texture, r)); - } + } - public TextureRegion getTextureRegion(Object key) { - return mRegions.get(key); - } + public TextureRegion getTextureRegion(Object key) { + return mRegions.get(key); + } - public Rect getRegion(int width, int height) { - int y, bestHeight, bestWidth; - Slot slot, prev; - Rect r = new Rect(0, 0, width, height); + public Rect getRegion(int width, int height) { + int y, bestHeight, bestWidth; + Slot slot, prev; + Rect r = new Rect(0, 0, width, height); - bestHeight = Integer.MAX_VALUE; - bestWidth = Integer.MAX_VALUE; + bestHeight = Integer.MAX_VALUE; + bestWidth = Integer.MAX_VALUE; - Slot bestSlot = null; + Slot bestSlot = null; - for (slot = mSlots; slot != null; slot = slot.next) { - // fit width - if ((slot.x + width) > (mWidth - 1)) - continue; + for (slot = mSlots; slot != null; slot = slot.next) { + // fit width + if ((slot.x + width) > (mWidth - 1)) + continue; - // fit height - y = slot.y; - int widthLeft = width; + // fit height + y = slot.y; + int widthLeft = width; - Slot fit = slot; - while (widthLeft > 0) { - if (fit.y > y) - y = fit.y; + Slot fit = slot; + while (widthLeft > 0) { + if (fit.y > y) + y = fit.y; - if ((y + height) > (mHeight - 1)) { - y = -1; - break; - } - widthLeft -= fit.w; + if ((y + height) > (mHeight - 1)) { + y = -1; + break; + } + widthLeft -= fit.w; - fit = fit.next; - } + fit = fit.next; + } - if (y < 0) - continue; + if (y < 0) + continue; - int h = y + height; - if ((h < bestHeight) || ((h == bestHeight) && (slot.w < bestWidth))) { - bestHeight = h; - bestSlot = slot; - bestWidth = slot.w; - r.x = slot.x; - r.y = y; - } - } + int h = y + height; + if ((h < bestHeight) || ((h == bestHeight) && (slot.w < bestWidth))) { + bestHeight = h; + bestSlot = slot; + bestWidth = slot.w; + r.x = slot.x; + r.y = y; + } + } - if (bestSlot == null) - return null; + if (bestSlot == null) + return null; - Slot curSlot = new Slot(r.x, r.y + height, width); - mSlots = Inlist.prependRelative(mSlots, curSlot, bestSlot); + Slot curSlot = new Slot(r.x, r.y + height, width); + mSlots = Inlist.prependRelative(mSlots, curSlot, bestSlot); - // split - for (prev = curSlot; prev.next != null;) { - slot = prev.next; + // split + for (prev = curSlot; prev.next != null; ) { + slot = prev.next; - int shrink = (prev.x + prev.w) - slot.x; + int shrink = (prev.x + prev.w) - slot.x; - if (shrink <= 0) - break; + if (shrink <= 0) + break; - slot.x += shrink; - slot.w -= shrink; - if (slot.w > 0) - break; + slot.x += shrink; + slot.w -= shrink; + if (slot.w > 0) + break; - // erease slot - prev.next = slot.next; - } + // erease slot + prev.next = slot.next; + } - // merge - for (slot = mSlots; slot.next != null;) { - Slot nextSlot = slot.next; + // merge + for (slot = mSlots; slot.next != null; ) { + Slot nextSlot = slot.next; - if (slot.y == nextSlot.y) { - slot.w += nextSlot.w; + if (slot.y == nextSlot.y) { + slot.w += nextSlot.w; - // erease 'next' slot - slot.next = nextSlot.next; - } else { - slot = nextSlot; - } - } + // erease 'next' slot + slot.next = nextSlot.next; + } else { + slot = nextSlot; + } + } - mUsed += width * height; + mUsed += width * height; - mRects = Inlist.push(mRects, r); - return r; - } + mRects = Inlist.push(mRects, r); + return r; + } - public void clear() { - mRects = null; - mSlots = new Slot(1, 1, mWidth - 2); - } + public void clear() { + mRects = null; + mSlots = new Slot(1, 1, mWidth - 2); + } - public static TextureAtlas create(int width, int height, int depth) { - if (!(depth == 1 || depth == 3 || depth == 4)) - throw new IllegalArgumentException("invalid depth"); + public static TextureAtlas create(int width, int height, int depth) { + if (!(depth == 1 || depth == 3 || depth == 4)) + throw new IllegalArgumentException("invalid depth"); - return new TextureAtlas(width, height); - } + return new TextureAtlas(width, height); + } - // /// FIXME - // @Override - // protected void finalize(){ - // if (texture != null) - // TextureItem.releaseTexture(texture); - // } + // /// FIXME + // @Override + // protected void finalize(){ + // if (texture != null) + // TextureItem.releaseTexture(texture); + // } } diff --git a/vtm/src/org/oscim/renderer/atlas/TextureRegion.java b/vtm/src/org/oscim/renderer/atlas/TextureRegion.java index ed5fcb9d..684f4625 100644 --- a/vtm/src/org/oscim/renderer/atlas/TextureRegion.java +++ b/vtm/src/org/oscim/renderer/atlas/TextureRegion.java @@ -21,11 +21,11 @@ import org.oscim.renderer.bucket.TextureItem; public class TextureRegion { - public TextureRegion(TextureItem texture, Rect r) { - this.texture = texture; - this.rect = r; - } + public TextureRegion(TextureItem texture, Rect r) { + this.texture = texture; + this.rect = r; + } - public final Rect rect; - public final TextureItem texture; + public final Rect rect; + public final TextureItem texture; } diff --git a/vtm/src/org/oscim/renderer/bucket/BitmapBucket.java b/vtm/src/org/oscim/renderer/bucket/BitmapBucket.java index bcf12ba8..77d7f9ca 100644 --- a/vtm/src/org/oscim/renderer/bucket/BitmapBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/BitmapBucket.java @@ -16,12 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.renderer.MapRenderer.MAX_INDICES; -import static org.oscim.renderer.MapRenderer.bindQuadIndicesVBO; - -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.backend.canvas.Bitmap; import org.oscim.renderer.GLShader; @@ -30,210 +24,216 @@ import org.oscim.renderer.GLViewport; import org.oscim.renderer.MapRenderer; import org.oscim.renderer.bucket.TextureItem.TexturePool; +import java.nio.ShortBuffer; + +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.renderer.MapRenderer.MAX_INDICES; +import static org.oscim.renderer.MapRenderer.bindQuadIndicesVBO; + /** * Renderer for a single bitmap, width and height must be power of 2. */ public class BitmapBucket extends TextureBucket { - // TODO share layers.vbo() between BitmapTileLayers + // TODO share layers.vbo() between BitmapTileLayers - // static final Logger log = LoggerFactory.getLogger(BitmapLayer.class); - private Bitmap mBitmap; - private final boolean mReuseBitmap; - private final short[] mVertices; - private int mWidth, mHeight; + // static final Logger log = LoggerFactory.getLogger(BitmapLayer.class); + private Bitmap mBitmap; + private final boolean mReuseBitmap; + private final short[] mVertices; + private int mWidth, mHeight; - /** - * @param reuseBitmap false if the Bitmap should be disposed - * after loading to texture. - */ - public BitmapBucket(boolean reuseBitmap) { - super(RenderBucket.BITMAP); + /** + * @param reuseBitmap false if the Bitmap should be disposed + * after loading to texture. + */ + public BitmapBucket(boolean reuseBitmap) { + super(RenderBucket.BITMAP); - mReuseBitmap = reuseBitmap; - mVertices = new short[24]; + mReuseBitmap = reuseBitmap; + mVertices = new short[24]; - // used for size calculation of Layers buffer. - numVertices = 4; - } + // used for size calculation of Layers buffer. + numVertices = 4; + } - /** - * w/h sets also target dimension to render the bitmap. - */ + /** + * w/h sets also target dimension to render the bitmap. + */ - public void setBitmap(Bitmap bitmap, int w, int h) { - setBitmap(bitmap, w, h, null); - } + public void setBitmap(Bitmap bitmap, int w, int h) { + setBitmap(bitmap, w, h, null); + } - public void setBitmap(Bitmap bitmap, int w, int h, TexturePool pool) { + public void setBitmap(Bitmap bitmap, int w, int h, TexturePool pool) { - mWidth = w; - mHeight = h; + mWidth = w; + mHeight = h; - mBitmap = bitmap; - if (textures == null) { - if (pool == null) - textures = new TextureItem(mBitmap); - else { - textures = pool.get(mBitmap); - } - } + mBitmap = bitmap; + if (textures == null) { + if (pool == null) + textures = new TextureItem(mBitmap); + else { + textures = pool.get(mBitmap); + } + } - TextureItem t = textures; - t.indices = TextureBucket.INDICES_PER_SPRITE; - } + TextureItem t = textures; + t.indices = TextureBucket.INDICES_PER_SPRITE; + } - private void setVertices(ShortBuffer vboData) { - short[] buf = mVertices; - short w = (short) (mWidth * MapRenderer.COORD_SCALE); - short h = (short) (mHeight * MapRenderer.COORD_SCALE); + private void setVertices(ShortBuffer vboData) { + short[] buf = mVertices; + short w = (short) (mWidth * MapRenderer.COORD_SCALE); + short h = (short) (mHeight * MapRenderer.COORD_SCALE); - short texMin = 0; - short texMax = 1; + short texMin = 0; + short texMax = 1; - // putSprite(buf, pos, tx, ty, x1, y1, x2, y2, u1, v1, u2, v2); - int pos = 0; + // putSprite(buf, pos, tx, ty, x1, y1, x2, y2, u1, v1, u2, v2); + int pos = 0; - // top-left - buf[pos++] = 0; - buf[pos++] = 0; - buf[pos++] = -1; - buf[pos++] = -1; - buf[pos++] = texMin; - buf[pos++] = texMin; - // bot-left - buf[pos++] = 0; - buf[pos++] = h; - buf[pos++] = -1; - buf[pos++] = -1; - buf[pos++] = texMin; - buf[pos++] = texMax; - // top-right - buf[pos++] = w; - buf[pos++] = 0; - buf[pos++] = -1; - buf[pos++] = -1; - buf[pos++] = texMax; - buf[pos++] = texMin; - // bot-right - buf[pos++] = w; - buf[pos++] = h; - buf[pos++] = -1; - buf[pos++] = -1; - buf[pos++] = texMax; - buf[pos++] = texMax; + // top-left + buf[pos++] = 0; + buf[pos++] = 0; + buf[pos++] = -1; + buf[pos++] = -1; + buf[pos++] = texMin; + buf[pos++] = texMin; + // bot-left + buf[pos++] = 0; + buf[pos++] = h; + buf[pos++] = -1; + buf[pos++] = -1; + buf[pos++] = texMin; + buf[pos++] = texMax; + // top-right + buf[pos++] = w; + buf[pos++] = 0; + buf[pos++] = -1; + buf[pos++] = -1; + buf[pos++] = texMax; + buf[pos++] = texMin; + // bot-right + buf[pos++] = w; + buf[pos++] = h; + buf[pos++] = -1; + buf[pos++] = -1; + buf[pos++] = texMax; + buf[pos++] = texMax; - this.vertexOffset = vboData.position() * 2; - vboData.put(buf); - } + this.vertexOffset = vboData.position() * 2; + vboData.put(buf); + } - @Override - protected void compile(ShortBuffer vboData, ShortBuffer iboData) { + @Override + protected void compile(ShortBuffer vboData, ShortBuffer iboData) { - if (mBitmap == null) - return; + if (mBitmap == null) + return; - setVertices(vboData); + setVertices(vboData); - textures.upload(); + textures.upload(); - if (!mReuseBitmap) { - mBitmap.recycle(); - mBitmap = null; - textures.bitmap = null; - } - } + if (!mReuseBitmap) { + mBitmap.recycle(); + mBitmap = null; + textures.bitmap = null; + } + } - @Override - protected void clear() { + @Override + protected void clear() { - // release textures and vertexItems - super.clear(); + // release textures and vertexItems + super.clear(); - if (mBitmap == null) - return; + if (mBitmap == null) + return; - if (!mReuseBitmap) - mBitmap.recycle(); + if (!mReuseBitmap) + mBitmap.recycle(); - mBitmap = null; + mBitmap = null; - //textures.bitmap = null; - //textures.dispose(); - //TextureItem.pool.releaseTexture(textures); - //textures = null; - } + //textures.bitmap = null; + //textures.dispose(); + //TextureItem.pool.releaseTexture(textures); + //textures = null; + } - static class Shader extends GLShader { - int uMVP, uAlpha, aPos, aTexCoord; + static class Shader extends GLShader { + int uMVP, uAlpha, aPos, aTexCoord; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; - uMVP = getUniform("u_mvp"); - uAlpha = getUniform("u_alpha"); - aPos = getAttrib("vertex"); - aTexCoord = getAttrib("tex_coord"); - } + Shader(String shaderFile) { + if (!create(shaderFile)) + return; + uMVP = getUniform("u_mvp"); + uAlpha = getUniform("u_alpha"); + aPos = getAttrib("vertex"); + aTexCoord = getAttrib("tex_coord"); + } - @Override - public boolean useProgram() { - if (super.useProgram()) { - GLState.enableVertexArrays(aPos, aTexCoord); - return true; - } - return false; - } - } + @Override + public boolean useProgram() { + if (super.useProgram()) { + GLState.enableVertexArrays(aPos, aTexCoord); + return true; + } + return false; + } + } - public static final class Renderer { + public static final class Renderer { - public final static int INDICES_PER_SPRITE = 6; - final static int VERTICES_PER_SPRITE = 4; - final static int SHORTS_PER_VERTICE = 6; - static Shader shader; + public final static int INDICES_PER_SPRITE = 6; + final static int VERTICES_PER_SPRITE = 4; + final static int SHORTS_PER_VERTICE = 6; + static Shader shader; - static void init() { - shader = new Shader("texture_alpha"); - } + static void init() { + shader = new Shader("texture_alpha"); + } - public static RenderBucket draw(RenderBucket b, GLViewport v, - float scale, float alpha) { + public static RenderBucket draw(RenderBucket b, GLViewport v, + float scale, float alpha) { - GLState.blend(true); - Shader s = shader; - s.useProgram(); + GLState.blend(true); + Shader s = shader; + s.useProgram(); - TextureBucket tb = (TextureBucket) b; + TextureBucket tb = (TextureBucket) b; - gl.uniform1f(s.uAlpha, alpha); - v.mvp.setAsUniform(s.uMVP); + gl.uniform1f(s.uAlpha, alpha); + v.mvp.setAsUniform(s.uMVP); - bindQuadIndicesVBO(); + bindQuadIndicesVBO(); - for (TextureItem t = tb.textures; t != null; t = t.next) { - t.bind(); + for (TextureItem t = tb.textures; t != null; t = t.next) { + t.bind(); - for (int i = 0; i < t.indices; i += MAX_INDICES) { - /* to.offset * (24(shorts) * - * 2(short-bytes) / 6(indices) == 8) */ - int off = (t.offset + i) * 8 + tb.vertexOffset; + for (int i = 0; i < t.indices; i += MAX_INDICES) { + /* to.offset * (24(shorts) * + * 2(short-bytes) / 6(indices) == 8) */ + int off = (t.offset + i) * 8 + tb.vertexOffset; - gl.vertexAttribPointer(s.aPos, 2, - GL.SHORT, false, 12, off); + gl.vertexAttribPointer(s.aPos, 2, + GL.SHORT, false, 12, off); - gl.vertexAttribPointer(s.aTexCoord, 2, - GL.SHORT, false, 12, off + 8); + gl.vertexAttribPointer(s.aTexCoord, 2, + GL.SHORT, false, 12, off + 8); - int numIndices = t.indices - i; - if (numIndices > MAX_INDICES) - numIndices = MAX_INDICES; + int numIndices = t.indices - i; + if (numIndices > MAX_INDICES) + numIndices = MAX_INDICES; - gl.drawElements(GL.TRIANGLES, numIndices, - GL.UNSIGNED_SHORT, 0); - } - } + gl.drawElements(GL.TRIANGLES, numIndices, + GL.UNSIGNED_SHORT, 0); + } + } - return b.next; - } - } + return b.next; + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/ExtrusionBucket.java b/vtm/src/org/oscim/renderer/bucket/ExtrusionBucket.java index 525dda64..417aa1ea 100644 --- a/vtm/src/org/oscim/renderer/bucket/ExtrusionBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/ExtrusionBucket.java @@ -16,8 +16,6 @@ */ package org.oscim.renderer.bucket; -import java.nio.ShortBuffer; - import org.oscim.backend.canvas.Color; import org.oscim.core.GeometryBuffer; import org.oscim.core.GeometryBuffer.GeometryType; @@ -33,596 +31,608 @@ import org.oscim.utils.pool.Pool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + public class ExtrusionBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(ExtrusionBucket.class); + static final Logger log = LoggerFactory.getLogger(ExtrusionBucket.class); - private static final float S = MapRenderer.COORD_SCALE; + private static final float S = MapRenderer.COORD_SCALE; - private VertexData mIndices[]; - private LineClipper mClipper; + private VertexData mIndices[]; + private LineClipper mClipper; - /** 16 floats rgba for top, even-side, odd-sides and outline */ - public final float[] colors; - public final int color; + /** + * 16 floats rgba for top, even-side, odd-sides and outline + */ + public final float[] colors; + public final int color; - /** indices for: 0. even sides, 1. odd sides, 2. roof, 3. roof outline */ - public int idx[] = { 0, 0, 0, 0, 0 }; - /** indices offsets in bytes */ - public int off[] = { 0, 0, 0, 0, 0 }; + /** + * indices for: 0. even sides, 1. odd sides, 2. roof, 3. roof outline + */ + public int idx[] = {0, 0, 0, 0, 0}; + /** + * indices offsets in bytes + */ + public int off[] = {0, 0, 0, 0, 0}; - //private final static int IND_EVEN_SIDE = 0; - //private final static int IND_ODD_SIDE = 1; - private final static int IND_ROOF = 2; + //private final static int IND_EVEN_SIDE = 0; + //private final static int IND_ODD_SIDE = 1; + private final static int IND_ROOF = 2; - // FIXME flip OUTLINE / MESH! - private final static int IND_OUTLINE = 3; - private final static int IND_MESH = 4; + // FIXME flip OUTLINE / MESH! + private final static int IND_OUTLINE = 3; + private final static int IND_MESH = 4; - private final float mGroundResolution; + private final float mGroundResolution; - private KeyMap mVertexMap; + private KeyMap mVertexMap; - //private static final int NORMAL_DIR_MASK = 0xFFFFFFFE; - //private int numIndexHits = 0; + //private static final int NORMAL_DIR_MASK = 0xFFFFFFFE; + //private int numIndexHits = 0; - /** - * ExtrusionLayer for polygon geometries. - */ - public ExtrusionBucket(int level, float groundResolution, float[] colors) { - super(RenderBucket.EXTRUSION, true, false); - this.level = level; - this.colors = colors; - this.color = 0; + /** + * ExtrusionLayer for polygon geometries. + */ + public ExtrusionBucket(int level, float groundResolution, float[] colors) { + super(RenderBucket.EXTRUSION, true, false); + this.level = level; + this.colors = colors; + this.color = 0; - mGroundResolution = groundResolution; + mGroundResolution = groundResolution; - mIndices = new VertexData[5]; + mIndices = new VertexData[5]; - for (int i = 0; i <= IND_MESH; i++) - mIndices[i] = new VertexData(); + for (int i = 0; i <= IND_MESH; i++) + mIndices[i] = new VertexData(); - mClipper = new LineClipper(0, 0, Tile.SIZE, Tile.SIZE); - } + mClipper = new LineClipper(0, 0, Tile.SIZE, Tile.SIZE); + } - /** - * ExtrusionLayer for triangle geometries. - */ - public ExtrusionBucket(int level, float groundResolution, int color) { - super(RenderBucket.EXTRUSION, true, false); - this.level = level; - this.color = color; + /** + * ExtrusionLayer for triangle geometries. + */ + public ExtrusionBucket(int level, float groundResolution, int color) { + super(RenderBucket.EXTRUSION, true, false); + this.level = level; + this.color = color; - float a = Color.aToFloat(color); - colors = new float[4]; - colors[0] = a * Color.rToFloat(color); - colors[1] = a * Color.gToFloat(color); - colors[2] = a * Color.bToFloat(color); - colors[3] = a; + float a = Color.aToFloat(color); + colors = new float[4]; + colors[0] = a * Color.rToFloat(color); + colors[1] = a * Color.gToFloat(color); + colors[2] = a * Color.bToFloat(color); + colors[3] = a; - mGroundResolution = groundResolution; + mGroundResolution = groundResolution; - mIndices = new VertexData[5]; - mIndices[4] = new VertexData(); + mIndices = new VertexData[5]; + mIndices[4] = new VertexData(); - synchronized (vertexPool) { - mVertexMap = vertexMapPool.get(); - } - } + synchronized (vertexPool) { + mVertexMap = vertexMapPool.get(); + } + } - static Pool vertexPool = new Pool() { - @Override - protected Vertex createItem() { - return new Vertex(); - } - }; + static Pool vertexPool = new Pool() { + @Override + protected Vertex createItem() { + return new Vertex(); + } + }; - static Pool> vertexMapPool = new Pool>() { - @Override - protected KeyMap createItem() { - return new KeyMap(2048); - } - }; + static Pool> vertexMapPool = new Pool>() { + @Override + protected KeyMap createItem() { + return new KeyMap(2048); + } + }; - static class Vertex extends HashItem { - short x, y, z, n; - int id; + static class Vertex extends HashItem { + short x, y, z, n; + int id; - @Override - public boolean equals(Object obj) { - Vertex o = (Vertex) obj; - return x == o.x && y == o.y && z == o.z && n == o.n; - } + @Override + public boolean equals(Object obj) { + Vertex o = (Vertex) obj; + return x == o.x && y == o.y && z == o.z && n == o.n; + } - @Override - public int hashCode() { - return 7 + ((x << 16 | y) ^ (n << 16 | z)) * 31; - } + @Override + public int hashCode() { + return 7 + ((x << 16 | y) ^ (n << 16 | z)) * 31; + } - public Vertex set(short x, short y, short z, short n) { - this.x = x; - this.y = y; - this.z = z; - this.n = n; - return this; - } - } + public Vertex set(short x, short y, short z, short n) { + this.x = x; + this.y = y; + this.z = z; + this.n = n; + return this; + } + } - public void add(MapElement element) { - if (element.type != GeometryType.TRIS) - return; + public void add(MapElement element) { + if (element.type != GeometryType.TRIS) + return; - int[] index = element.index; - float[] points = element.points; + int[] index = element.index; + float[] points = element.points; - int vertexCnt = numVertices; - synchronized (vertexPool) { + int vertexCnt = numVertices; + synchronized (vertexPool) { - Vertex key = vertexPool.get(); - double scale = S * Tile.SIZE / 4096; + Vertex key = vertexPool.get(); + double scale = S * Tile.SIZE / 4096; - for (int k = 0, n = index.length; k < n;) { - if (index[k] < 0) - break; + for (int k = 0, n = index.length; k < n; ) { + if (index[k] < 0) + break; /* FIXME: workaround: dont overflow max index id. */ - if (vertexCnt >= 1 << 16) - break; + if (vertexCnt >= 1 << 16) + break; - int vtx1 = index[k++] * 3; - int vtx2 = index[k++] * 3; - int vtx3 = index[k++] * 3; + int vtx1 = index[k++] * 3; + int vtx2 = index[k++] * 3; + int vtx3 = index[k++] * 3; - float vx1 = points[vtx1 + 0]; - float vy1 = points[vtx1 + 1]; - float vz1 = points[vtx1 + 2]; + float vx1 = points[vtx1 + 0]; + float vy1 = points[vtx1 + 1]; + float vz1 = points[vtx1 + 2]; - float vx2 = points[vtx2 + 0]; - float vy2 = points[vtx2 + 1]; - float vz2 = points[vtx2 + 2]; + float vx2 = points[vtx2 + 0]; + float vy2 = points[vtx2 + 1]; + float vz2 = points[vtx2 + 2]; - float vx3 = points[vtx3 + 0]; - float vy3 = points[vtx3 + 1]; - float vz3 = points[vtx3 + 2]; + float vx3 = points[vtx3 + 0]; + float vy3 = points[vtx3 + 1]; + float vz3 = points[vtx3 + 2]; - float ax = vx2 - vx1; - float ay = vy2 - vy1; - float az = vz2 - vz1; + float ax = vx2 - vx1; + float ay = vy2 - vy1; + float az = vz2 - vz1; - float bx = vx3 - vx1; - float by = vy3 - vy1; - float bz = vz3 - vz1; + float bx = vx3 - vx1; + float by = vy3 - vy1; + float bz = vz3 - vz1; - float cx = ay * bz - az * by; - float cy = az * bx - ax * bz; - float cz = ax * by - ay * bx; + float cx = ay * bz - az * by; + float cy = az * bx - ax * bz; + float cz = ax * by - ay * bx; - double len = Math.sqrt(cx * cx + cy * cy + cz * cz); + double len = Math.sqrt(cx * cx + cy * cy + cz * cz); - // packing the normal in two bytes - // int mx = FastMath.clamp(127 + (int) ((cx / len) * 128), 0, 0xff); - // int my = FastMath.clamp(127 + (int) ((cy / len) * 128), 0, 0xff); - // short normal = (short) ((my << 8) | (mx & NORMAL_DIR_MASK) | (cz > 0 ? 1 : 0)); + // packing the normal in two bytes + // int mx = FastMath.clamp(127 + (int) ((cx / len) * 128), 0, 0xff); + // int my = FastMath.clamp(127 + (int) ((cy / len) * 128), 0, 0xff); + // short normal = (short) ((my << 8) | (mx & NORMAL_DIR_MASK) | (cz > 0 ? 1 : 0)); - double p = Math.sqrt((cz / len) * 8.0 + 8.0); - int mx = FastMath.clamp(127 + (int) ((cx / len / p) * 128), 0, 255); - int my = FastMath.clamp(127 + (int) ((cy / len / p) * 128), 0, 255); - short normal = (short) ((my << 8) | mx); + double p = Math.sqrt((cz / len) * 8.0 + 8.0); + int mx = FastMath.clamp(127 + (int) ((cx / len / p) * 128), 0, 255); + int my = FastMath.clamp(127 + (int) ((cy / len / p) * 128), 0, 255); + short normal = (short) ((my << 8) | mx); - if (key == null) - key = vertexPool.get(); + if (key == null) + key = vertexPool.get(); - key.set((short) (vx1 * scale), - (short) (vy1 * scale), - (short) (vz1 * scale), - normal); + key.set((short) (vx1 * scale), + (short) (vy1 * scale), + (short) (vz1 * scale), + normal); - Vertex vertex = mVertexMap.put(key, false); + Vertex vertex = mVertexMap.put(key, false); - if (vertex == null) { - key.id = vertexCnt++; - addIndex(key, true); - key = vertexPool.get(); - } else { - //numIndexHits++; - addIndex(vertex, false); - } + if (vertex == null) { + key.id = vertexCnt++; + addIndex(key, true); + key = vertexPool.get(); + } else { + //numIndexHits++; + addIndex(vertex, false); + } - key.set((short) (vx2 * scale), - (short) (vy2 * scale), - (short) (vz2 * scale), - normal); + key.set((short) (vx2 * scale), + (short) (vy2 * scale), + (short) (vz2 * scale), + normal); - vertex = mVertexMap.put(key, false); + vertex = mVertexMap.put(key, false); - if (vertex == null) { - key.id = vertexCnt++; - addIndex(key, true); - key = vertexPool.get(); - } else { - //numIndexHits++; - addIndex(vertex, false); - } + if (vertex == null) { + key.id = vertexCnt++; + addIndex(key, true); + key = vertexPool.get(); + } else { + //numIndexHits++; + addIndex(vertex, false); + } - key.set((short) (vx3 * scale), - (short) (vy3 * scale), - (short) (vz3 * scale), - (short) normal); + key.set((short) (vx3 * scale), + (short) (vy3 * scale), + (short) (vz3 * scale), + (short) normal); - vertex = mVertexMap.put(key, false); - if (vertex == null) { - key.id = vertexCnt++; - addIndex(key, true); - key = vertexPool.get(); - } else { - //numIndexHits++; - addIndex(vertex, false); - } - } + vertex = mVertexMap.put(key, false); + if (vertex == null) { + key.id = vertexCnt++; + addIndex(key, true); + key = vertexPool.get(); + } else { + //numIndexHits++; + addIndex(vertex, false); + } + } - vertexPool.release(key); - } - numVertices = vertexCnt; - } + vertexPool.release(key); + } + numVertices = vertexCnt; + } - private void addIndex(Vertex v, boolean addVertex) { - if (addVertex) - vertexItems.add(v.x, v.y, v.z, v.n); + private void addIndex(Vertex v, boolean addVertex) { + if (addVertex) + vertexItems.add(v.x, v.y, v.z, v.n); - mIndices[IND_MESH].add((short) v.id); - numIndices++; - } + mIndices[IND_MESH].add((short) v.id); + numIndices++; + } - // private void encodeNormal(float v[], int offset) { - // var p = Math.sqrt(cartesian.z * 8.0 + 8.0); - // var result = new Cartesian2(); - // result.x = cartesian.x / p + 0.5; - // result.y = cartesian.y / p + 0.5; - // return result; - // } - // - //public void addNoNormal(MapElement element) { - // if (element.type != GeometryType.TRIS) - // return; - // - // short[] index = element.index; - // float[] points = element.points; - // - // /* current vertex id */ - // int startVertex = sumVertices; - // - // /* roof indices for convex shapes */ - // int i = mCurIndices[IND_MESH].used; - // short[] indices = mCurIndices[IND_MESH].vertices; - // - // int first = startVertex; - // - // for (int k = 0, n = index.length; k < n;) { - // if (index[k] < 0) - // break; - // - // if (i == VertexItem.SIZE) { - // mCurIndices[IND_MESH] = VertexItem.getNext(mCurIndices[IND_MESH]); - // indices = mCurIndices[IND_MESH].vertices; - // i = 0; - // } - // indices[i++] = (short) (first + index[k++]); - // indices[i++] = (short) (first + index[k++]); - // indices[i++] = (short) (first + index[k++]); - // } - // mCurIndices[IND_MESH].used = i; - // - // short[] vertices = mCurVertices.vertices; - // int v = mCurVertices.used; - // - // int vertexCnt = element.pointPos; - // - // for (int j = 0; j < vertexCnt;) { - // /* add bottom and top vertex for each point */ - // if (v == VertexItem.SIZE) { - // mCurVertices = VertexItem.getNext(mCurVertices); - // vertices = mCurVertices.vertices; - // v = 0; - // } - // /* set coordinate */ - // vertices[v++] = (short) (points[j++] * S); - // vertices[v++] = (short) (points[j++] * S); - // vertices[v++] = (short) (points[j++] * S); - // v++; - // } - // - // mCurVertices.used = v; - // sumVertices += (vertexCnt / 3); - //} + // private void encodeNormal(float v[], int offset) { + // var p = Math.sqrt(cartesian.z * 8.0 + 8.0); + // var result = new Cartesian2(); + // result.x = cartesian.x / p + 0.5; + // result.y = cartesian.y / p + 0.5; + // return result; + // } + // + //public void addNoNormal(MapElement element) { + // if (element.type != GeometryType.TRIS) + // return; + // + // short[] index = element.index; + // float[] points = element.points; + // + // /* current vertex id */ + // int startVertex = sumVertices; + // + // /* roof indices for convex shapes */ + // int i = mCurIndices[IND_MESH].used; + // short[] indices = mCurIndices[IND_MESH].vertices; + // + // int first = startVertex; + // + // for (int k = 0, n = index.length; k < n;) { + // if (index[k] < 0) + // break; + // + // if (i == VertexItem.SIZE) { + // mCurIndices[IND_MESH] = VertexItem.getNext(mCurIndices[IND_MESH]); + // indices = mCurIndices[IND_MESH].vertices; + // i = 0; + // } + // indices[i++] = (short) (first + index[k++]); + // indices[i++] = (short) (first + index[k++]); + // indices[i++] = (short) (first + index[k++]); + // } + // mCurIndices[IND_MESH].used = i; + // + // short[] vertices = mCurVertices.vertices; + // int v = mCurVertices.used; + // + // int vertexCnt = element.pointPos; + // + // for (int j = 0; j < vertexCnt;) { + // /* add bottom and top vertex for each point */ + // if (v == VertexItem.SIZE) { + // mCurVertices = VertexItem.getNext(mCurVertices); + // vertices = mCurVertices.vertices; + // v = 0; + // } + // /* set coordinate */ + // vertices[v++] = (short) (points[j++] * S); + // vertices[v++] = (short) (points[j++] * S); + // vertices[v++] = (short) (points[j++] * S); + // v++; + // } + // + // mCurVertices.used = v; + // sumVertices += (vertexCnt / 3); + //} - public void add(MapElement element, float height, float minHeight) { + public void add(MapElement element, float height, float minHeight) { - int[] index = element.index; - float[] points = element.points; + int[] index = element.index; + float[] points = element.points; /* 10 cm steps */ - float sfactor = 1 / 10f; - height *= sfactor; - minHeight *= sfactor; + float sfactor = 1 / 10f; + height *= sfactor; + minHeight *= sfactor; /* match height with ground resultion (meter per pixel) */ - height /= mGroundResolution; - minHeight /= mGroundResolution; + height /= mGroundResolution; + minHeight /= mGroundResolution; - boolean complexOutline = false; - boolean simpleOutline = true; + boolean complexOutline = false; + boolean simpleOutline = true; /* current vertex id */ - int startVertex = numVertices; - int length = 0, ipos = 0, ppos = 0; + int startVertex = numVertices; + int length = 0, ipos = 0, ppos = 0; - for (int n = index.length; ipos < n; ipos++, ppos += length) { - length = index[ipos]; + for (int n = index.length; ipos < n; ipos++, ppos += length) { + length = index[ipos]; /* end marker */ - if (length < 0) - break; + if (length < 0) + break; /* start next polygon */ - if (length == 0) { - startVertex = numVertices; - simpleOutline = true; - complexOutline = false; - continue; - } + if (length == 0) { + startVertex = numVertices; + simpleOutline = true; + complexOutline = false; + continue; + } /* check: drop last point from explicitly closed rings */ - int len = length; - if (points[ppos] == points[ppos + len - 2] - && points[ppos + 1] == points[ppos + len - 1]) { - len -= 2; - log.debug("explicit closed poly " + len); - } + int len = length; + if (points[ppos] == points[ppos + len - 2] + && points[ppos + 1] == points[ppos + len - 1]) { + len -= 2; + log.debug("explicit closed poly " + len); + } /* need at least three points */ - if (len < 6) - continue; + if (len < 6) + continue; /* check if polygon contains inner rings */ - if (simpleOutline && (ipos < n - 1) && (index[ipos + 1] > 0)) - simpleOutline = false; + if (simpleOutline && (ipos < n - 1) && (index[ipos + 1] > 0)) + simpleOutline = false; - boolean convex = extrudeOutline(points, ppos, len, minHeight, - height, simpleOutline); + boolean convex = extrudeOutline(points, ppos, len, minHeight, + height, simpleOutline); - if (simpleOutline && (convex || len <= 8)) { - addRoofSimple(startVertex, len); - } else if (!complexOutline) { - complexOutline = true; - addRoof(startVertex, element, ipos, ppos); - } - } - } + if (simpleOutline && (convex || len <= 8)) { + addRoofSimple(startVertex, len); + } else if (!complexOutline) { + complexOutline = true; + addRoof(startVertex, element, ipos, ppos); + } + } + } - /** roof indices for convex shapes */ - private void addRoofSimple(int startVertex, int len) { - short first = (short) (startVertex + 1); - VertexData it = mIndices[IND_ROOF]; - len -= 4; - for (int k = 0; k < len; k += 2) { - it.add(first, - (short) (first + k + 2), - (short) (first + k + 4)); - } - numIndices += (len / 2) * 3; - } + /** + * roof indices for convex shapes + */ + private void addRoofSimple(int startVertex, int len) { + short first = (short) (startVertex + 1); + VertexData it = mIndices[IND_ROOF]; + len -= 4; + for (int k = 0; k < len; k += 2) { + it.add(first, + (short) (first + k + 2), + (short) (first + k + 4)); + } + numIndices += (len / 2) * 3; + } - /** roof indices for concave shapes */ - private void addRoof(int startVertex, GeometryBuffer geom, int ipos, int ppos) { - int[] index = geom.index; - float[] points = geom.points; + /** + * roof indices for concave shapes + */ + private void addRoof(int startVertex, GeometryBuffer geom, int ipos, int ppos) { + int[] index = geom.index; + float[] points = geom.points; - int numPoints = 0; - int numRings = 0; + int numPoints = 0; + int numRings = 0; /* get sum of points in polygon */ - for (int i = ipos, n = index.length; i < n && index[i] > 0; i++) { - numPoints += index[i]; - numRings++; - } + for (int i = ipos, n = index.length; i < n && index[i] > 0; i++) { + numPoints += index[i]; + numRings++; + } - numIndices += Tessellator.tessellate(points, ppos, numPoints, - index, ipos, numRings, - startVertex + 1, - mIndices[IND_ROOF]); - } + numIndices += Tessellator.tessellate(points, ppos, numPoints, + index, ipos, numRings, + startVertex + 1, + mIndices[IND_ROOF]); + } - private boolean extrudeOutline(float[] points, int pos, int len, - float minHeight, float height, boolean convex) { + private boolean extrudeOutline(float[] points, int pos, int len, + float minHeight, float height, boolean convex) { /* add two vertices for last face to make zigzag indices work */ - boolean addFace = (len % 4 != 0); - int vertexCnt = len + (addFace ? 2 : 0); + boolean addFace = (len % 4 != 0); + int vertexCnt = len + (addFace ? 2 : 0); - float cx = points[pos + len - 2]; - float cy = points[pos + len - 1]; - float nx = points[pos + 0]; - float ny = points[pos + 1]; + float cx = points[pos + len - 2]; + float cy = points[pos + len - 1]; + float nx = points[pos + 0]; + float ny = points[pos + 1]; /* vector to next point */ - float vx = nx - cx; - float vy = ny - cy; - /* vector from previous point */ - float ux, uy; + float vx = nx - cx; + float vy = ny - cy; + /* vector from previous point */ + float ux, uy; - float a = (float) Math.sqrt(vx * vx + vy * vy); - short color1 = (short) ((1 + vx / a) * 127); + float a = (float) Math.sqrt(vx * vx + vy * vy); + short color1 = (short) ((1 + vx / a) * 127); - short fcolor = color1, color2 = 0; + short fcolor = color1, color2 = 0; - short h = (short) height, mh = (short) minHeight; + short h = (short) height, mh = (short) minHeight; - int even = 0; - int changeX = 0, changeY = 0, angleSign = 0; + int even = 0; + int changeX = 0, changeY = 0, angleSign = 0; /* vertex offset for all vertices in layer */ - int vOffset = numVertices; + int vOffset = numVertices; - mClipper.clipStart((int) nx, (int) ny); + mClipper.clipStart((int) nx, (int) ny); - for (int i = 2, n = vertexCnt + 2; i < n; i += 2 /* , v += 8 */) { - cx = nx; - cy = ny; + for (int i = 2, n = vertexCnt + 2; i < n; i += 2 /* , v += 8 */) { + cx = nx; + cy = ny; - ux = vx; - uy = vy; + ux = vx; + uy = vy; /* get direction to next point */ - if (i < len) { - nx = points[pos + i + 0]; - ny = points[pos + i + 1]; - } else if (i == len) { - nx = points[pos + 0]; - ny = points[pos + 1]; - } else { // if (addFace) - short c = (short) (color1 | fcolor << 8); - /* add bottom and top vertex for each point */ - vertexItems.add((short) (cx * S), (short) (cy * S), mh, c); - vertexItems.add((short) (cx * S), (short) (cy * S), h, c); + if (i < len) { + nx = points[pos + i + 0]; + ny = points[pos + i + 1]; + } else if (i == len) { + nx = points[pos + 0]; + ny = points[pos + 1]; + } else { // if (addFace) + short c = (short) (color1 | fcolor << 8); + /* add bottom and top vertex for each point */ + vertexItems.add((short) (cx * S), (short) (cy * S), mh, c); + vertexItems.add((short) (cx * S), (short) (cy * S), h, c); - //v += 8; - break; - } + //v += 8; + break; + } - vx = nx - cx; - vy = ny - cy; + vx = nx - cx; + vy = ny - cy; /* set lighting (by direction) */ - a = (float) Math.sqrt(vx * vx + vy * vy); - color2 = (short) ((1 + vx / a) * 127); + a = (float) Math.sqrt(vx * vx + vy * vy); + color2 = (short) ((1 + vx / a) * 127); - short c; - if (even == 0) - c = (short) (color1 | color2 << 8); - else - c = (short) (color2 | color1 << 8); + short c; + if (even == 0) + c = (short) (color1 | color2 << 8); + else + c = (short) (color2 | color1 << 8); /* add bottom and top vertex for each point */ - vertexItems.add((short) (cx * S), (short) (cy * S), mh, c); - vertexItems.add((short) (cx * S), (short) (cy * S), h, c); + vertexItems.add((short) (cx * S), (short) (cy * S), mh, c); + vertexItems.add((short) (cx * S), (short) (cy * S), h, c); - color1 = color2; + color1 = color2; /* check if polygon is convex */ - if (convex) { + if (convex) { /* TODO simple polys with only one concave arc * could be handled without special triangulation */ - if ((ux < 0 ? 1 : -1) != (vx < 0 ? 1 : -1)) - changeX++; - if ((uy < 0 ? 1 : -1) != (vy < 0 ? 1 : -1)) - changeY++; + if ((ux < 0 ? 1 : -1) != (vx < 0 ? 1 : -1)) + changeX++; + if ((uy < 0 ? 1 : -1) != (vy < 0 ? 1 : -1)) + changeY++; - if (changeX > 2 || changeY > 2) - convex = false; + if (changeX > 2 || changeY > 2) + convex = false; - float cross = ux * vy - uy * vy; + float cross = ux * vy - uy * vy; - if (cross > 0) { - if (angleSign == -1) - convex = false; - angleSign = 1; - } else if (cross < 0) { - if (angleSign == 1) - convex = false; - angleSign = -1; - } - } + if (cross > 0) { + if (angleSign == -1) + convex = false; + angleSign = 1; + } else if (cross < 0) { + if (angleSign == 1) + convex = false; + angleSign = -1; + } + } /* check if face is within tile */ - if (mClipper.clipNext((int) nx, (int) ny) == 0) { - even = ++even % 2; - continue; - } + if (mClipper.clipNext((int) nx, (int) ny) == 0) { + even = ++even % 2; + continue; + } /* add ZigZagQuadIndices(tm) for sides */ - short vert = (short) (vOffset + (i - 2)); - short s0 = vert++; - short s1 = vert++; - short s2 = vert++; - short s3 = vert++; + short vert = (short) (vOffset + (i - 2)); + short s0 = vert++; + short s1 = vert++; + short s2 = vert++; + short s3 = vert++; /* connect last to first (when number of faces is even) */ - if (!addFace && i == len) { - s2 -= len; - s3 -= len; - } + if (!addFace && i == len) { + s2 -= len; + s3 -= len; + } - mIndices[even].add(s0, s2, s1); - mIndices[even].add(s1, s2, s3); - numIndices += 6; + mIndices[even].add(s0, s2, s1); + mIndices[even].add(s1, s2, s3); + numIndices += 6; /* flipp even-odd */ - even = ++even % 2; + even = ++even % 2; /* add roof outline indices */ - mIndices[IND_OUTLINE].add(s1, s3); - numIndices += 2; - } + mIndices[IND_OUTLINE].add(s1, s3); + numIndices += 2; + } - numVertices += vertexCnt; - return convex; - } + numVertices += vertexCnt; + return convex; + } - @Override - public void compile(ShortBuffer vboData, ShortBuffer iboData) { + @Override + public void compile(ShortBuffer vboData, ShortBuffer iboData) { - if (numVertices == 0) - return; + if (numVertices == 0) + return; - indiceOffset = iboData.position(); + indiceOffset = iboData.position(); - int iOffset = indiceOffset; - for (int i = 0; i <= IND_MESH; i++) { - if (mIndices[i] != null) { - idx[i] = mIndices[i].compile(iboData); - off[i] = iOffset * 2; - iOffset += idx[i]; - } - } - vertexOffset = vboData.position() * 2; - vertexItems.compile(vboData); + int iOffset = indiceOffset; + for (int i = 0; i <= IND_MESH; i++) { + if (mIndices[i] != null) { + idx[i] = mIndices[i].compile(iboData); + off[i] = iOffset * 2; + iOffset += idx[i]; + } + } + vertexOffset = vboData.position() * 2; + vertexItems.compile(vboData); - clear(); - } + clear(); + } - @Override - public void clear() { - mClipper = null; - releaseVertexPool(); + @Override + public void clear() { + mClipper = null; + releaseVertexPool(); - if (mIndices != null) { - for (int i = 0; i <= IND_MESH; i++) { - if (mIndices[i] == null) - continue; - mIndices[i].dispose(); - } - mIndices = null; + if (mIndices != null) { + for (int i = 0; i <= IND_MESH; i++) { + if (mIndices[i] == null) + continue; + mIndices[i].dispose(); + } + mIndices = null; - vertexItems.dispose(); - } - } + vertexItems.dispose(); + } + } - @Override - protected void prepare() { - mClipper = null; - releaseVertexPool(); - } + @Override + protected void prepare() { + mClipper = null; + releaseVertexPool(); + } - void releaseVertexPool() { - if (mVertexMap == null) - return; + void releaseVertexPool() { + if (mVertexMap == null) + return; - synchronized (vertexPool) { - vertexPool.releaseAll(mVertexMap.releaseItems()); - mVertexMap = vertexMapPool.release(mVertexMap); - } - } + synchronized (vertexPool) { + vertexPool.releaseAll(mVertexMap.releaseItems()); + mVertexMap = vertexMapPool.release(mVertexMap); + } + } - public ExtrusionBucket next() { - return (ExtrusionBucket) next; - } + public ExtrusionBucket next() { + return (ExtrusionBucket) next; + } } diff --git a/vtm/src/org/oscim/renderer/bucket/ExtrusionBuckets.java b/vtm/src/org/oscim/renderer/bucket/ExtrusionBuckets.java index 4d9f9ad4..954d3f85 100644 --- a/vtm/src/org/oscim/renderer/bucket/ExtrusionBuckets.java +++ b/vtm/src/org/oscim/renderer/bucket/ExtrusionBuckets.java @@ -1,7 +1,5 @@ package org.oscim.renderer.bucket; -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.layers.tile.MapTile; import org.oscim.layers.tile.MapTile.TileData; @@ -10,101 +8,103 @@ import org.oscim.renderer.MapRenderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + public class ExtrusionBuckets extends TileData { - static final Logger log = LoggerFactory.getLogger(ExtrusionBuckets.class); + static final Logger log = LoggerFactory.getLogger(ExtrusionBuckets.class); - public ExtrusionBucket buckets; + public ExtrusionBucket buckets; - public boolean compiled; - public long animTime; + public boolean compiled; + public long animTime; - public final int zoomLevel; + public final int zoomLevel; - public final double x; - public final double y; + public final double x; + public final double y; - public BufferObject ibo; - public BufferObject vbo; + public BufferObject ibo; + public BufferObject vbo; - public ExtrusionBuckets(MapTile tile) { - zoomLevel = tile.zoomLevel; - x = tile.x; - y = tile.y; - } + public ExtrusionBuckets(MapTile tile) { + zoomLevel = tile.zoomLevel; + x = tile.x; + y = tile.y; + } - /** - * Set new ExtrusionLayers and clear previous. - */ - public void setBuckets(ExtrusionBucket el) { - for (RenderBucket b = buckets; b != null; b = b.next) - b.clear(); + /** + * Set new ExtrusionLayers and clear previous. + */ + public void setBuckets(ExtrusionBucket el) { + for (RenderBucket b = buckets; b != null; b = b.next) + b.clear(); - buckets = el; - } + buckets = el; + } - public ExtrusionBucket buckets() { - return buckets; - } + public ExtrusionBucket buckets() { + return buckets; + } - @Override - protected void dispose() { - setBuckets(null); + @Override + protected void dispose() { + setBuckets(null); - if (compiled) { - ibo = BufferObject.release(ibo); - vbo = BufferObject.release(vbo); - } + if (compiled) { + ibo = BufferObject.release(ibo); + vbo = BufferObject.release(vbo); + } - } + } - public void prepare() { - for (RenderBucket b = buckets; b != null; b = b.next) - b.prepare(); - } + public void prepare() { + for (RenderBucket b = buckets; b != null; b = b.next) + b.prepare(); + } - public boolean compile() { + public boolean compile() { - if (buckets == null) - return false; + if (buckets == null) + return false; - int sumIndices = 0; - int sumVertices = 0; + int sumIndices = 0; + int sumVertices = 0; - for (ExtrusionBucket b = buckets; b != null; b = b.next()) { - sumIndices += b.numIndices; - sumVertices += b.numVertices; - } - if (sumIndices == 0) - return false; + for (ExtrusionBucket b = buckets; b != null; b = b.next()) { + sumIndices += b.numIndices; + sumVertices += b.numVertices; + } + if (sumIndices == 0) + return false; - ShortBuffer vboData = MapRenderer.getShortBuffer(sumVertices * 4); - ShortBuffer iboData = MapRenderer.getShortBuffer(sumIndices); + ShortBuffer vboData = MapRenderer.getShortBuffer(sumVertices * 4); + ShortBuffer iboData = MapRenderer.getShortBuffer(sumIndices); - for (ExtrusionBucket b = buckets; b != null; b = b.next()) - b.compile(vboData, iboData); + for (ExtrusionBucket b = buckets; b != null; b = b.next()) + b.compile(vboData, iboData); - int size = sumIndices * 2; - if (iboData.position() != sumIndices) { - int pos = iboData.position(); - log.error("invalid indice size: {} {}", sumIndices, pos); - size = pos * 2; - } - ibo = BufferObject.get(GL.ELEMENT_ARRAY_BUFFER, size); - ibo.loadBufferData(iboData.flip(), size); + int size = sumIndices * 2; + if (iboData.position() != sumIndices) { + int pos = iboData.position(); + log.error("invalid indice size: {} {}", sumIndices, pos); + size = pos * 2; + } + ibo = BufferObject.get(GL.ELEMENT_ARRAY_BUFFER, size); + ibo.loadBufferData(iboData.flip(), size); - size = sumVertices * 4 * 2; - if (vboData.position() != sumVertices * 4) { - int pos = vboData.position(); - log.error("invalid vertex size: {} {}", sumVertices, pos); - size = pos * 2; - } + size = sumVertices * 4 * 2; + if (vboData.position() != sumVertices * 4) { + int pos = vboData.position(); + log.error("invalid vertex size: {} {}", sumVertices, pos); + size = pos * 2; + } - vbo = BufferObject.get(GL.ARRAY_BUFFER, size); - vbo.loadBufferData(vboData.flip(), size); + vbo = BufferObject.get(GL.ARRAY_BUFFER, size); + vbo.loadBufferData(vboData.flip(), size); - compiled = true; + compiled = true; - return true; - } + return true; + } } diff --git a/vtm/src/org/oscim/renderer/bucket/HairLineBucket.java b/vtm/src/org/oscim/renderer/bucket/HairLineBucket.java index 36f190af..840d7a46 100644 --- a/vtm/src/org/oscim/renderer/bucket/HairLineBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/HairLineBucket.java @@ -1,8 +1,5 @@ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.renderer.MapRenderer.COORD_SCALE; - import org.oscim.backend.GL; import org.oscim.core.GeometryBuffer; import org.oscim.renderer.GLShader; @@ -13,127 +10,130 @@ import org.oscim.theme.styles.LineStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.renderer.MapRenderer.COORD_SCALE; + public class HairLineBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(HairLineBucket.class); + static final Logger log = LoggerFactory.getLogger(HairLineBucket.class); - public LineStyle line; + public LineStyle line; - public HairLineBucket(int level) { - super(RenderBucket.HAIRLINE, true, false); - this.level = level; - } + public HairLineBucket(int level) { + super(RenderBucket.HAIRLINE, true, false); + this.level = level; + } - public void addLine(GeometryBuffer geom) { - short id = (short) numVertices; + public void addLine(GeometryBuffer geom) { + short id = (short) numVertices; - float pts[] = geom.points; + float pts[] = geom.points; - boolean poly = geom.isPoly(); - int inPos = 0; + boolean poly = geom.isPoly(); + int inPos = 0; - for (int i = 0, n = geom.index.length; i < n; i++) { - int len = geom.index[i]; - if (len < 0) - break; + for (int i = 0, n = geom.index.length; i < n; i++) { + int len = geom.index[i]; + if (len < 0) + break; - if (len < 4 || (poly && len < 6)) { - inPos += len; - continue; - } + if (len < 4 || (poly && len < 6)) { + inPos += len; + continue; + } - int end = inPos + len; + int end = inPos + len; - vertexItems.add((short) (pts[inPos++] * COORD_SCALE), - (short) (pts[inPos++] * COORD_SCALE)); - short first = id; + vertexItems.add((short) (pts[inPos++] * COORD_SCALE), + (short) (pts[inPos++] * COORD_SCALE)); + short first = id; - indiceItems.add(id++); - numIndices++; + indiceItems.add(id++); + numIndices++; - while (inPos < end) { + while (inPos < end) { - vertexItems.add((short) (pts[inPos++] * COORD_SCALE), - (short) (pts[inPos++] * COORD_SCALE)); + vertexItems.add((short) (pts[inPos++] * COORD_SCALE), + (short) (pts[inPos++] * COORD_SCALE)); - indiceItems.add(id); - numIndices++; + indiceItems.add(id); + numIndices++; - if (inPos == end) { - if (poly) { - indiceItems.add(id); - numIndices++; + if (inPos == end) { + if (poly) { + indiceItems.add(id); + numIndices++; - indiceItems.add(first); - numIndices++; - } - id++; - break; - } - indiceItems.add(id++); - numIndices++; - } + indiceItems.add(first); + numIndices++; + } + id++; + break; + } + indiceItems.add(id++); + numIndices++; + } - } - numVertices = id; - } + } + numVertices = id; + } - public static class Renderer { - static Shader shader; + public static class Renderer { + static Shader shader; - static boolean init() { - shader = new Shader("hairline"); - return true; - } + static boolean init() { + shader = new Shader("hairline"); + return true; + } - public static class Shader extends GLShader { - int uMVP, uColor, uWidth, uScreen, aPos; + public static class Shader extends GLShader { + int uMVP, uColor, uWidth, uScreen, aPos; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; + Shader(String shaderFile) { + if (!create(shaderFile)) + return; - uMVP = getUniform("u_mvp"); - uColor = getUniform("u_color"); - uWidth = getUniform("u_width"); - uScreen = getUniform("u_screen"); - aPos = getAttrib("a_pos"); - } + uMVP = getUniform("u_mvp"); + uColor = getUniform("u_color"); + uWidth = getUniform("u_width"); + uScreen = getUniform("u_screen"); + aPos = getAttrib("a_pos"); + } - public void set(GLViewport v) { - useProgram(); - GLState.enableVertexArrays(aPos, -1); + public void set(GLViewport v) { + useProgram(); + GLState.enableVertexArrays(aPos, -1); - v.mvp.setAsUniform(uMVP); + v.mvp.setAsUniform(uMVP); - gl.uniform2f(uScreen, v.getWidth() / 2, v.getHeight() / 2); - gl.uniform1f(uWidth, 1.5f); - gl.lineWidth(2); - } - } + gl.uniform2f(uScreen, v.getWidth() / 2, v.getHeight() / 2); + gl.uniform1f(uWidth, 1.5f); + gl.lineWidth(2); + } + } - public static RenderBucket draw(RenderBucket l, GLViewport v) { - GLState.blend(true); + public static RenderBucket draw(RenderBucket l, GLViewport v) { + GLState.blend(true); - Shader s = shader; + Shader s = shader; - s.set(v); + s.set(v); - for (; l != null && l.type == HAIRLINE; l = l.next) { - HairLineBucket ll = (HairLineBucket) l; + for (; l != null && l.type == HAIRLINE; l = l.next) { + HairLineBucket ll = (HairLineBucket) l; - GLUtils.setColor(s.uColor, ll.line.color, 1); + GLUtils.setColor(s.uColor, ll.line.color, 1); - gl.vertexAttribPointer(s.aPos, 2, GL.SHORT, - false, 0, ll.vertexOffset); + gl.vertexAttribPointer(s.aPos, 2, GL.SHORT, + false, 0, ll.vertexOffset); - gl.drawElements(GL.LINES, - ll.numIndices, - GL.UNSIGNED_SHORT, - ll.indiceOffset); - } - //GL.lineWidth(1); + gl.drawElements(GL.LINES, + ll.numIndices, + GL.UNSIGNED_SHORT, + ll.indiceOffset); + } + //GL.lineWidth(1); - return l; - } - } + return l; + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/LineBucket.java b/vtm/src/org/oscim/renderer/bucket/LineBucket.java index 3bd4c49e..63df08ae 100644 --- a/vtm/src/org/oscim/renderer/bucket/LineBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/LineBucket.java @@ -16,8 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; - import org.oscim.backend.GL; import org.oscim.backend.GLAdapter; import org.oscim.backend.canvas.Paint.Cap; @@ -32,6 +30,8 @@ import org.oscim.theme.styles.LineStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.backend.GLAdapter.gl; + /** * Note: * Coordinates must be in range [-4096..4096] and the maximum @@ -39,702 +39,706 @@ import org.slf4j.LoggerFactory; * to fixed point values. */ public final class LineBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(LineBucket.class); + static final Logger log = LoggerFactory.getLogger(LineBucket.class); - private static final float COORD_SCALE = MapRenderer.COORD_SCALE; - /** scale factor mapping extrusion vector to short values */ - public static final float DIR_SCALE = 2048; + private static final float COORD_SCALE = MapRenderer.COORD_SCALE; + /** + * scale factor mapping extrusion vector to short values + */ + public static final float DIR_SCALE = 2048; - /** maximal resolution */ - private static final float MIN_DIST = 1 / 8f; + /** + * maximal resolution + */ + private static final float MIN_DIST = 1 / 8f; - /** - * not quite right.. need to go back so that additional - * bevel vertices are at least MIN_DIST apart - */ - private static final float BEVEL_MIN = MIN_DIST * 4; + /** + * not quite right.. need to go back so that additional + * bevel vertices are at least MIN_DIST apart + */ + private static final float BEVEL_MIN = MIN_DIST * 4; - /** - * mask for packing last two bits of extrusion vector with texture - * coordinates - */ - private static final int DIR_MASK = 0xFFFFFFFC; + /** + * mask for packing last two bits of extrusion vector with texture + * coordinates + */ + private static final int DIR_MASK = 0xFFFFFFFC; - /* lines referenced by this outline layer */ - public LineBucket outlines; - public LineStyle line; - public float scale = 1; + /* lines referenced by this outline layer */ + public LineBucket outlines; + public LineStyle line; + public float scale = 1; - public boolean roundCap; - private float mMinDist = MIN_DIST; + public boolean roundCap; + private float mMinDist = MIN_DIST; - public float heightOffset; + public float heightOffset; - private int tmin = Integer.MIN_VALUE, tmax = Integer.MAX_VALUE; + private int tmin = Integer.MIN_VALUE, tmax = Integer.MAX_VALUE; - public LineBucket(int layer) { - super(RenderBucket.LINE, false, false); - this.level = layer; - } + public LineBucket(int layer) { + super(RenderBucket.LINE, false, false); + this.level = layer; + } - public void addOutline(LineBucket link) { - for (LineBucket l = outlines; l != null; l = l.outlines) - if (link == l) - return; + public void addOutline(LineBucket link) { + for (LineBucket l = outlines; l != null; l = l.outlines) + if (link == l) + return; - link.outlines = outlines; - outlines = link; - } + link.outlines = outlines; + outlines = link; + } - public void setExtents(int min, int max) { - tmin = min; - tmax = max; - } + public void setExtents(int min, int max) { + tmin = min; + tmax = max; + } - /** - * For point reduction by minimal distance. Default is 1/8. - */ - public void setDropDistance(float minDist) { - mMinDist = Math.max(minDist, MIN_DIST); - } + /** + * For point reduction by minimal distance. Default is 1/8. + */ + public void setDropDistance(float minDist) { + mMinDist = Math.max(minDist, MIN_DIST); + } - public void addLine(GeometryBuffer geom) { - if (geom.isPoly()) - addLine(geom.points, geom.index, -1, true); - else if (geom.isLine()) - addLine(geom.points, geom.index, -1, false); - else - log.debug("geometry must be LINE or POLYGON"); - } + public void addLine(GeometryBuffer geom) { + if (geom.isPoly()) + addLine(geom.points, geom.index, -1, true); + else if (geom.isLine()) + addLine(geom.points, geom.index, -1, false); + else + log.debug("geometry must be LINE or POLYGON"); + } - public void addLine(float[] points, int numPoints, boolean closed) { - if (numPoints >= 4) - addLine(points, null, numPoints, closed); - } + public void addLine(float[] points, int numPoints, boolean closed) { + if (numPoints >= 4) + addLine(points, null, numPoints, closed); + } - private void addLine(float[] points, int[] index, int numPoints, boolean closed) { + private void addLine(float[] points, int[] index, int numPoints, boolean closed) { - boolean rounded = false; - boolean squared = false; + boolean rounded = false; + boolean squared = false; - if (line.cap == Cap.ROUND) - rounded = true; - else if (line.cap == Cap.SQUARE) - squared = true; + if (line.cap == Cap.ROUND) + rounded = true; + else if (line.cap == Cap.SQUARE) + squared = true; /* Note: just a hack to save some vertices, when there are - * more than 200 lines per type. FIXME make optional! */ - if (rounded && index != null) { - int cnt = 0; - for (int i = 0, n = index.length; i < n; i++, cnt++) { - if (index[i] < 0) - break; - if (cnt > 400) { - rounded = false; - break; - } - } - } - roundCap = rounded; + * more than 200 lines per type. FIXME make optional! */ + if (rounded && index != null) { + int cnt = 0; + for (int i = 0, n = index.length; i < n; i++, cnt++) { + if (index[i] < 0) + break; + if (cnt > 400) { + rounded = false; + break; + } + } + } + roundCap = rounded; - int n; - int length = 0; + int n; + int length = 0; - if (index == null) { - n = 1; - if (numPoints > 0) { - length = numPoints; - } else { - length = points.length; - } - } else { - n = index.length; - } + if (index == null) { + n = 1; + if (numPoints > 0) { + length = numPoints; + } else { + length = points.length; + } + } else { + n = index.length; + } - for (int i = 0, pos = 0; i < n; i++) { - if (index != null) - length = index[i]; + for (int i = 0, pos = 0; i < n; i++) { + if (index != null) + length = index[i]; /* check end-marker in indices */ - if (length < 0) - break; + if (length < 0) + break; - int ipos = pos; - pos += length; + int ipos = pos; + pos += length; /* need at least two points */ - if (length < 4) - continue; + if (length < 4) + continue; /* start an enpoint are equal */ - if (length == 4 && - points[ipos] == points[ipos + 2] && - points[ipos + 1] == points[ipos + 3]) - continue; + if (length == 4 && + points[ipos] == points[ipos + 2] && + points[ipos + 1] == points[ipos + 3]) + continue; /* avoid simple 180 degree angles */ - if (length == 6 && - points[ipos] == points[ipos + 4] && - points[ipos + 1] == points[ipos + 5]) - length -= 2; + if (length == 6 && + points[ipos] == points[ipos + 4] && + points[ipos + 1] == points[ipos + 5]) + length -= 2; - addLine(vertexItems, points, ipos, length, rounded, squared, closed); + addLine(vertexItems, points, ipos, length, rounded, squared, closed); - } - } + } + } - private void addVertex(VertexData vi, - float x, float y, - float vNextX, float vNextY, - float vPrevX, float vPrevY) { + private void addVertex(VertexData vi, + float x, float y, + float vNextX, float vNextY, + float vPrevX, float vPrevY) { - float ux = vNextX + vPrevX; - float uy = vNextY + vPrevY; + float ux = vNextX + vPrevX; + float uy = vNextY + vPrevY; /* vPrev times perpendicular of sum(vNext, vPrev) */ - double a = uy * vPrevX - ux * vPrevY; + double a = uy * vPrevX - ux * vPrevY; - if (a < 0.01 && a > -0.01) { - ux = -vPrevY; - uy = vPrevX; - } else { - ux /= a; - uy /= a; - } + if (a < 0.01 && a > -0.01) { + ux = -vPrevY; + uy = vPrevX; + } else { + ux /= a; + uy /= a; + } - short ox = (short) (x * COORD_SCALE); - short oy = (short) (y * COORD_SCALE); + short ox = (short) (x * COORD_SCALE); + short oy = (short) (y * COORD_SCALE); - int ddx = (int) (ux * DIR_SCALE); - int ddy = (int) (uy * DIR_SCALE); + int ddx = (int) (ux * DIR_SCALE); + int ddy = (int) (uy * DIR_SCALE); - vi.add(ox, oy, - (short) (0 | ddx & DIR_MASK), - (short) (1 | ddy & DIR_MASK)); + vi.add(ox, oy, + (short) (0 | ddx & DIR_MASK), + (short) (1 | ddy & DIR_MASK)); - vi.add(ox, oy, - (short) (2 | -ddx & DIR_MASK), - (short) (1 | -ddy & DIR_MASK)); - } + vi.add(ox, oy, + (short) (2 | -ddx & DIR_MASK), + (short) (1 | -ddy & DIR_MASK)); + } - private void addLine(VertexData vertices, float[] points, int start, int length, - boolean rounded, boolean squared, boolean closed) { + private void addLine(VertexData vertices, float[] points, int start, int length, + boolean rounded, boolean squared, boolean closed) { - float ux, uy; - float vPrevX, vPrevY; - float vNextX, vNextY; - float curX, curY; - float nextX, nextY; - double a; + float ux, uy; + float vPrevX, vPrevY; + float vNextX, vNextY; + float curX, curY; + float nextX, nextY; + double a; /* amount of vertices used - * + 2 for drawing triangle-strip + * + 2 for drawing triangle-strip * + 4 for round caps * + 2 for closing polygons */ - numVertices += length + (rounded ? 6 : 2) + (closed ? 2 : 0); + numVertices += length + (rounded ? 6 : 2) + (closed ? 2 : 0); - int ipos = start; + int ipos = start; - curX = points[ipos++]; - curY = points[ipos++]; - nextX = points[ipos++]; - nextY = points[ipos++]; + curX = points[ipos++]; + curY = points[ipos++]; + nextX = points[ipos++]; + nextY = points[ipos++]; /* Unit vector to next node */ - vPrevX = nextX - curX; - vPrevY = nextY - curY; - a = (float) Math.sqrt(vPrevX * vPrevX + vPrevY * vPrevY); - vPrevX /= a; - vPrevY /= a; + vPrevX = nextX - curX; + vPrevY = nextY - curY; + a = (float) Math.sqrt(vPrevX * vPrevX + vPrevY * vPrevY); + vPrevX /= a; + vPrevY /= a; /* perpendicular on the first segment */ - ux = -vPrevY; - uy = vPrevX; + ux = -vPrevY; + uy = vPrevX; - int ddx, ddy; + int ddx, ddy; /* vertex point coordinate */ - short ox = (short) (curX * COORD_SCALE); - short oy = (short) (curY * COORD_SCALE); + short ox = (short) (curX * COORD_SCALE); + short oy = (short) (curY * COORD_SCALE); /* vertex extrusion vector, last two bit * encode texture coord. */ - short dx, dy; + short dx, dy; /* when the endpoint is outside the tile region omit round caps. */ - boolean outside = (curX < tmin || curX > tmax || curY < tmin || curY > tmax); + boolean outside = (curX < tmin || curX > tmax || curY < tmin || curY > tmax); - if (rounded && !outside) { - ddx = (int) ((ux - vPrevX) * DIR_SCALE); - ddy = (int) ((uy - vPrevY) * DIR_SCALE); - dx = (short) (0 | ddx & DIR_MASK); - dy = (short) (2 | ddy & DIR_MASK); + if (rounded && !outside) { + ddx = (int) ((ux - vPrevX) * DIR_SCALE); + ddy = (int) ((uy - vPrevY) * DIR_SCALE); + dx = (short) (0 | ddx & DIR_MASK); + dy = (short) (2 | ddy & DIR_MASK); - vertices.add(ox, oy, (short) dx, (short) dy); - vertices.add(ox, oy, (short) dx, (short) dy); + vertices.add(ox, oy, (short) dx, (short) dy); + vertices.add(ox, oy, (short) dx, (short) dy); - ddx = (int) (-(ux + vPrevX) * DIR_SCALE); - ddy = (int) (-(uy + vPrevY) * DIR_SCALE); + ddx = (int) (-(ux + vPrevX) * DIR_SCALE); + ddy = (int) (-(uy + vPrevY) * DIR_SCALE); - vertices.add(ox, oy, - (short) (2 | ddx & DIR_MASK), - (short) (2 | ddy & DIR_MASK)); + vertices.add(ox, oy, + (short) (2 | ddx & DIR_MASK), + (short) (2 | ddy & DIR_MASK)); /* Start of line */ - ddx = (int) (ux * DIR_SCALE); - ddy = (int) (uy * DIR_SCALE); + ddx = (int) (ux * DIR_SCALE); + ddy = (int) (uy * DIR_SCALE); - vertices.add(ox, oy, - (short) (0 | ddx & DIR_MASK), - (short) (1 | ddy & DIR_MASK)); + vertices.add(ox, oy, + (short) (0 | ddx & DIR_MASK), + (short) (1 | ddy & DIR_MASK)); - vertices.add(ox, oy, - (short) (2 | -ddx & DIR_MASK), - (short) (1 | -ddy & DIR_MASK)); - } else { + vertices.add(ox, oy, + (short) (2 | -ddx & DIR_MASK), + (short) (1 | -ddy & DIR_MASK)); + } else { /* outside means line is probably clipped * TODO should align ending with tile boundary * for now, just extend the line a little */ - float tx = vPrevX; - float ty = vPrevY; + float tx = vPrevX; + float ty = vPrevY; - if (squared) { - tx = 0; - ty = 0; - } else if (!outside) { - tx *= 0.5; - ty *= 0.5; - } + if (squared) { + tx = 0; + ty = 0; + } else if (!outside) { + tx *= 0.5; + ty *= 0.5; + } - if (rounded) - numVertices -= 2; + if (rounded) + numVertices -= 2; /* add first vertex twice */ - ddx = (int) ((ux - tx) * DIR_SCALE); - ddy = (int) ((uy - ty) * DIR_SCALE); - dx = (short) (0 | ddx & DIR_MASK); - dy = (short) (1 | ddy & DIR_MASK); + ddx = (int) ((ux - tx) * DIR_SCALE); + ddy = (int) ((uy - ty) * DIR_SCALE); + dx = (short) (0 | ddx & DIR_MASK); + dy = (short) (1 | ddy & DIR_MASK); - vertices.add(ox, oy, (short) dx, (short) dy); - vertices.add(ox, oy, (short) dx, (short) dy); + vertices.add(ox, oy, (short) dx, (short) dy); + vertices.add(ox, oy, (short) dx, (short) dy); - ddx = (int) (-(ux + tx) * DIR_SCALE); - ddy = (int) (-(uy + ty) * DIR_SCALE); + ddx = (int) (-(ux + tx) * DIR_SCALE); + ddy = (int) (-(uy + ty) * DIR_SCALE); - vertices.add(ox, oy, - (short) (2 | ddx & DIR_MASK), - (short) (1 | ddy & DIR_MASK)); - } + vertices.add(ox, oy, + (short) (2 | ddx & DIR_MASK), + (short) (1 | ddy & DIR_MASK)); + } - curX = nextX; - curY = nextY; + curX = nextX; + curY = nextY; /* Unit vector pointing back to previous node */ - vPrevX *= -1; - vPrevY *= -1; + vPrevX *= -1; + vPrevY *= -1; - // vertexItem.used = opos + 4; + // vertexItem.used = opos + 4; - for (int end = start + length;;) { + for (int end = start + length; ; ) { - if (ipos < end) { - nextX = points[ipos++]; - nextY = points[ipos++]; - } else if (closed && ipos < end + 2) { + if (ipos < end) { + nextX = points[ipos++]; + nextY = points[ipos++]; + } else if (closed && ipos < end + 2) { /* add startpoint == endpoint */ - nextX = points[start]; - nextY = points[start + 1]; - ipos += 2; - } else - break; + nextX = points[start]; + nextY = points[start + 1]; + ipos += 2; + } else + break; /* unit vector pointing forward to next node */ - vNextX = nextX - curX; - vNextY = nextY - curY; - a = Math.sqrt(vNextX * vNextX + vNextY * vNextY); + vNextX = nextX - curX; + vNextY = nextY - curY; + a = Math.sqrt(vNextX * vNextX + vNextY * vNextY); /* skip too short segmets */ - if (a < mMinDist) { - numVertices -= 2; - continue; - } - vNextX /= a; - vNextY /= a; + if (a < mMinDist) { + numVertices -= 2; + continue; + } + vNextX /= a; + vNextY /= a; - double dotp = (vNextX * vPrevX + vNextY * vPrevY); + double dotp = (vNextX * vPrevX + vNextY * vPrevY); - //log.debug("acos " + dotp); - if (dotp > 0.65) { + //log.debug("acos " + dotp); + if (dotp > 0.65) { /* add bevel join to avoid miter going to infinity */ - numVertices += 2; + numVertices += 2; - //dotp = FastMath.clamp(dotp, -1, 1); - //double cos = Math.acos(dotp); - //log.debug("cos " + Math.toDegrees(cos)); - //log.debug("back " + (mMinDist * 2 / Math.sin(cos + Math.PI / 2))); + //dotp = FastMath.clamp(dotp, -1, 1); + //double cos = Math.acos(dotp); + //log.debug("cos " + Math.toDegrees(cos)); + //log.debug("back " + (mMinDist * 2 / Math.sin(cos + Math.PI / 2))); - float px, py; - if (dotp > 0.999) { + float px, py; + if (dotp > 0.999) { /* 360 degree angle, set points aside */ - ux = vPrevX + vNextX; - uy = vPrevY + vNextY; - a = vNextX * uy - vNextY * ux; - if (a < 0.1 && a > -0.1) { + ux = vPrevX + vNextX; + uy = vPrevY + vNextY; + a = vNextX * uy - vNextY * ux; + if (a < 0.1 && a > -0.1) { /* Almost straight */ - ux = -vNextY; - uy = vNextX; - } else { - ux /= a; - uy /= a; - } - //log.debug("aside " + a + " " + ux + " " + uy); - px = curX - ux * BEVEL_MIN; - py = curY - uy * BEVEL_MIN; - curX = curX + ux * BEVEL_MIN; - curY = curY + uy * BEVEL_MIN; - } else { - //log.debug("back"); + ux = -vNextY; + uy = vNextX; + } else { + ux /= a; + uy /= a; + } + //log.debug("aside " + a + " " + ux + " " + uy); + px = curX - ux * BEVEL_MIN; + py = curY - uy * BEVEL_MIN; + curX = curX + ux * BEVEL_MIN; + curY = curY + uy * BEVEL_MIN; + } else { + //log.debug("back"); /* go back by min dist */ - px = curX + vPrevX * BEVEL_MIN; - py = curY + vPrevY * BEVEL_MIN; + px = curX + vPrevX * BEVEL_MIN; + py = curY + vPrevY * BEVEL_MIN; /* go forward by min dist */ - curX = curX + vNextX * BEVEL_MIN; - curY = curY + vNextY * BEVEL_MIN; - } + curX = curX + vNextX * BEVEL_MIN; + curY = curY + vNextY * BEVEL_MIN; + } /* unit vector pointing forward to next node */ - vNextX = curX - px; - vNextY = curY - py; - a = Math.sqrt(vNextX * vNextX + vNextY * vNextY); - vNextX /= a; - vNextY /= a; + vNextX = curX - px; + vNextY = curY - py; + a = Math.sqrt(vNextX * vNextX + vNextY * vNextY); + vNextX /= a; + vNextY /= a; - addVertex(vertices, px, py, vPrevX, vPrevY, vNextX, vNextY); + addVertex(vertices, px, py, vPrevX, vPrevY, vNextX, vNextY); /* flip unit vector to point back */ - vPrevX = -vNextX; - vPrevY = -vNextY; + vPrevX = -vNextX; + vPrevY = -vNextY; /* unit vector pointing forward to next node */ - vNextX = nextX - curX; - vNextY = nextY - curY; - a = Math.sqrt(vNextX * vNextX + vNextY * vNextY); - vNextX /= a; - vNextY /= a; - } + vNextX = nextX - curX; + vNextY = nextY - curY; + a = Math.sqrt(vNextX * vNextX + vNextY * vNextY); + vNextX /= a; + vNextY /= a; + } - addVertex(vertices, curX, curY, vPrevX, vPrevY, vNextX, vNextY); + addVertex(vertices, curX, curY, vPrevX, vPrevY, vNextX, vNextY); - curX = nextX; - curY = nextY; + curX = nextX; + curY = nextY; /* flip vector to point back */ - vPrevX = -vNextX; - vPrevY = -vNextY; - } + vPrevX = -vNextX; + vPrevY = -vNextY; + } - ux = vPrevY; - uy = -vPrevX; + ux = vPrevY; + uy = -vPrevX; - outside = (curX < tmin || curX > tmax || curY < tmin || curY > tmax); + outside = (curX < tmin || curX > tmax || curY < tmin || curY > tmax); - ox = (short) (curX * COORD_SCALE); - oy = (short) (curY * COORD_SCALE); + ox = (short) (curX * COORD_SCALE); + oy = (short) (curY * COORD_SCALE); - if (rounded && !outside) { - ddx = (int) (ux * DIR_SCALE); - ddy = (int) (uy * DIR_SCALE); + if (rounded && !outside) { + ddx = (int) (ux * DIR_SCALE); + ddy = (int) (uy * DIR_SCALE); - vertices.add(ox, oy, - (short) (0 | ddx & DIR_MASK), - (short) (1 | ddy & DIR_MASK)); + vertices.add(ox, oy, + (short) (0 | ddx & DIR_MASK), + (short) (1 | ddy & DIR_MASK)); - vertices.add(ox, oy, - (short) (2 | -ddx & DIR_MASK), - (short) (1 | -ddy & DIR_MASK)); + vertices.add(ox, oy, + (short) (2 | -ddx & DIR_MASK), + (short) (1 | -ddy & DIR_MASK)); /* For rounded line edges */ - ddx = (int) ((ux - vPrevX) * DIR_SCALE); - ddy = (int) ((uy - vPrevY) * DIR_SCALE); + ddx = (int) ((ux - vPrevX) * DIR_SCALE); + ddy = (int) ((uy - vPrevY) * DIR_SCALE); - vertices.add(ox, oy, - (short) (0 | ddx & DIR_MASK), - (short) (0 | ddy & DIR_MASK)); + vertices.add(ox, oy, + (short) (0 | ddx & DIR_MASK), + (short) (0 | ddy & DIR_MASK)); /* last vertex */ - ddx = (int) (-(ux + vPrevX) * DIR_SCALE); - ddy = (int) (-(uy + vPrevY) * DIR_SCALE); - dx = (short) (2 | ddx & DIR_MASK); - dy = (short) (0 | ddy & DIR_MASK); + ddx = (int) (-(ux + vPrevX) * DIR_SCALE); + ddy = (int) (-(uy + vPrevY) * DIR_SCALE); + dx = (short) (2 | ddx & DIR_MASK); + dy = (short) (0 | ddy & DIR_MASK); - } else { - if (squared) { - vPrevX = 0; - vPrevY = 0; - } else if (!outside) { - vPrevX *= 0.5; - vPrevY *= 0.5; - } + } else { + if (squared) { + vPrevX = 0; + vPrevY = 0; + } else if (!outside) { + vPrevX *= 0.5; + vPrevY *= 0.5; + } - if (rounded) - numVertices -= 2; + if (rounded) + numVertices -= 2; - ddx = (int) ((ux - vPrevX) * DIR_SCALE); - ddy = (int) ((uy - vPrevY) * DIR_SCALE); + ddx = (int) ((ux - vPrevX) * DIR_SCALE); + ddy = (int) ((uy - vPrevY) * DIR_SCALE); - vertices.add(ox, oy, - (short) (0 | ddx & DIR_MASK), - (short) (1 | ddy & DIR_MASK)); + vertices.add(ox, oy, + (short) (0 | ddx & DIR_MASK), + (short) (1 | ddy & DIR_MASK)); /* last vertex */ - ddx = (int) (-(ux + vPrevX) * DIR_SCALE); - ddy = (int) (-(uy + vPrevY) * DIR_SCALE); - dx = (short) (2 | ddx & DIR_MASK); - dy = (short) (1 | ddy & DIR_MASK); - } + ddx = (int) (-(ux + vPrevX) * DIR_SCALE); + ddy = (int) (-(uy + vPrevY) * DIR_SCALE); + dx = (short) (2 | ddx & DIR_MASK); + dy = (short) (1 | ddy & DIR_MASK); + } /* add last vertex twice */ - vertices.add(ox, oy, (short) dx, (short) dy); - vertices.add(ox, oy, (short) dx, (short) dy); - } + vertices.add(ox, oy, (short) dx, (short) dy); + vertices.add(ox, oy, (short) dx, (short) dy); + } - static class Shader extends GLShader { - int uMVP, uFade, uWidth, uColor, uMode, uHeight, aPos; + static class Shader extends GLShader { + int uMVP, uFade, uWidth, uColor, uMode, uHeight, aPos; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; - uMVP = getUniform("u_mvp"); - uFade = getUniform("u_fade"); - uWidth = getUniform("u_width"); - uColor = getUniform("u_color"); - uMode = getUniform("u_mode"); - uHeight = getUniform("u_height"); - aPos = getAttrib("a_pos"); - } + Shader(String shaderFile) { + if (!create(shaderFile)) + return; + uMVP = getUniform("u_mvp"); + uFade = getUniform("u_fade"); + uWidth = getUniform("u_width"); + uColor = getUniform("u_color"); + uMode = getUniform("u_mode"); + uHeight = getUniform("u_height"); + aPos = getAttrib("a_pos"); + } - @Override - public boolean useProgram() { - if (super.useProgram()) { - GLState.enableVertexArrays(aPos, -1); - return true; - } - return false; - } - } + @Override + public boolean useProgram() { + if (super.useProgram()) { + GLState.enableVertexArrays(aPos, -1); + return true; + } + return false; + } + } - public static final class Renderer { + public static final class Renderer { /* TODO: * http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter22.html */ - /* factor to normalize extrusion vector and scale to coord scale */ - private final static float COORD_SCALE_BY_DIR_SCALE = - MapRenderer.COORD_SCALE / LineBucket.DIR_SCALE; + /* factor to normalize extrusion vector and scale to coord scale */ + private final static float COORD_SCALE_BY_DIR_SCALE = + MapRenderer.COORD_SCALE / LineBucket.DIR_SCALE; - private final static int CAP_THIN = 0; - private final static int CAP_BUTT = 1; - private final static int CAP_ROUND = 2; + private final static int CAP_THIN = 0; + private final static int CAP_BUTT = 1; + private final static int CAP_ROUND = 2; - private final static int SHADER_FLAT = 1; - private final static int SHADER_PROJ = 0; + private final static int SHADER_FLAT = 1; + private final static int SHADER_PROJ = 0; - public static int mTexID; - private static Shader[] shaders = { null, null }; + public static int mTexID; + private static Shader[] shaders = {null, null}; - static boolean init() { + static boolean init() { - shaders[0] = new Shader("line_aa_proj"); - shaders[1] = new Shader("line_aa"); + shaders[0] = new Shader("line_aa_proj"); + shaders[1] = new Shader("line_aa"); /* create lookup table as texture for 'length(0..1,0..1)' * using mirrored wrap mode for 'length(-1..1,-1..1)' */ - byte[] pixel = new byte[128 * 128]; + byte[] pixel = new byte[128 * 128]; - for (int x = 0; x < 128; x++) { - float xx = x * x; - for (int y = 0; y < 128; y++) { - float yy = y * y; - int color = (int) (Math.sqrt(xx + yy) * 2); - if (color > 255) - color = 255; - pixel[x + y * 128] = (byte) color; - } - } + for (int x = 0; x < 128; x++) { + float xx = x * x; + for (int y = 0; y < 128; y++) { + float yy = y * y; + int color = (int) (Math.sqrt(xx + yy) * 2); + if (color > 255) + color = 255; + pixel[x + y * 128] = (byte) color; + } + } - mTexID = GLUtils.loadTexture(pixel, 128, 128, GL.ALPHA, - GL.NEAREST, GL.NEAREST, - GL.MIRRORED_REPEAT, - GL.MIRRORED_REPEAT); - return true; - } + mTexID = GLUtils.loadTexture(pixel, 128, 128, GL.ALPHA, + GL.NEAREST, GL.NEAREST, + GL.MIRRORED_REPEAT, + GL.MIRRORED_REPEAT); + return true; + } - public static RenderBucket draw(RenderBucket b, GLViewport v, - float scale, RenderBuckets buckets) { + public static RenderBucket draw(RenderBucket b, GLViewport v, + float scale, RenderBuckets buckets) { /* simple line shader does not take forward shortening into * account. only used when tilt is 0. */ - int mode = v.pos.tilt < 1 ? 1 : 0; + int mode = v.pos.tilt < 1 ? 1 : 0; - Shader s = shaders[mode]; - s.useProgram(); + Shader s = shaders[mode]; + s.useProgram(); - GLState.blend(true); + GLState.blend(true); /* Somehow we loose the texture after an indefinite * time, when label/symbol textures are used. * Debugging gl on Desktop is most fun imaginable, * so for now: */ - if (!GLAdapter.GDX_DESKTOP_QUIRKS) - GLState.bindTex2D(mTexID); + if (!GLAdapter.GDX_DESKTOP_QUIRKS) + GLState.bindTex2D(mTexID); - int uLineFade = s.uFade; - int uLineMode = s.uMode; - int uLineColor = s.uColor; - int uLineWidth = s.uWidth; - int uLineHeight = s.uHeight; + int uLineFade = s.uFade; + int uLineMode = s.uMode; + int uLineColor = s.uColor; + int uLineWidth = s.uWidth; + int uLineHeight = s.uHeight; - gl.vertexAttribPointer(s.aPos, 4, GL.SHORT, false, 0, - buckets.offset[LINE]); + gl.vertexAttribPointer(s.aPos, 4, GL.SHORT, false, 0, + buckets.offset[LINE]); - v.mvp.setAsUniform(s.uMVP); + v.mvp.setAsUniform(s.uMVP); /* Line scale factor for non fixed lines: Within a zoom- * level lines would be scaled by the factor 2 by view-matrix. * Though lines should only scale by sqrt(2). This is achieved * by inverting scaling of extrusion vector with: width/sqrt(s). */ - double variableScale = Math.sqrt(scale); + double variableScale = Math.sqrt(scale); /* scale factor to map one pixel on tile to one pixel on screen: * used with orthographic projection, (shader mode == 1) */ - double pixel = (mode == SHADER_PROJ) ? 0.0001 : 1.5 / scale; + double pixel = (mode == SHADER_PROJ) ? 0.0001 : 1.5 / scale; - gl.uniform1f(uLineFade, (float) pixel); + gl.uniform1f(uLineFade, (float) pixel); - int capMode = 0; - gl.uniform1f(uLineMode, capMode); + int capMode = 0; + gl.uniform1f(uLineMode, capMode); - boolean blur = false; - double width; + boolean blur = false; + double width; - float heightOffset = 0; - gl.uniform1f(uLineHeight, heightOffset); + float heightOffset = 0; + gl.uniform1f(uLineHeight, heightOffset); - for (; b != null && b.type == RenderBucket.LINE; b = b.next) { - LineBucket lb = (LineBucket) b; - LineStyle line = lb.line.current(); + for (; b != null && b.type == RenderBucket.LINE; b = b.next) { + LineBucket lb = (LineBucket) b; + LineStyle line = lb.line.current(); - if (lb.heightOffset != heightOffset) { - heightOffset = lb.heightOffset; + if (lb.heightOffset != heightOffset) { + heightOffset = lb.heightOffset; - gl.uniform1f(uLineHeight, heightOffset / - MercatorProjection.groundResolution(v.pos)); - } + gl.uniform1f(uLineHeight, heightOffset / + MercatorProjection.groundResolution(v.pos)); + } - if (line.fadeScale < v.pos.zoomLevel) { - GLUtils.setColor(uLineColor, line.color, 1); - } else if (line.fadeScale > v.pos.zoomLevel) { - continue; - } else { - float alpha = (float) (scale > 1.2 ? scale : 1.2) - 1; - GLUtils.setColor(uLineColor, line.color, alpha); - } + if (line.fadeScale < v.pos.zoomLevel) { + GLUtils.setColor(uLineColor, line.color, 1); + } else if (line.fadeScale > v.pos.zoomLevel) { + continue; + } else { + float alpha = (float) (scale > 1.2 ? scale : 1.2) - 1; + GLUtils.setColor(uLineColor, line.color, alpha); + } - if (mode == SHADER_PROJ && blur && line.blur == 0) { - gl.uniform1f(uLineFade, (float) pixel); - blur = false; - } + if (mode == SHADER_PROJ && blur && line.blur == 0) { + gl.uniform1f(uLineFade, (float) pixel); + blur = false; + } /* draw LineLayer */ - if (!line.outline) { + if (!line.outline) { /* invert scaling of extrusion vectors so that line * width stays the same. */ - if (line.fixed) { - width = Math.max(line.width, 1) / scale; - } else { - width = lb.scale * line.width / variableScale; - } + if (line.fixed) { + width = Math.max(line.width, 1) / scale; + } else { + width = lb.scale * line.width / variableScale; + } - gl.uniform1f(uLineWidth, - (float) (width * COORD_SCALE_BY_DIR_SCALE)); + gl.uniform1f(uLineWidth, + (float) (width * COORD_SCALE_BY_DIR_SCALE)); /* Line-edge fade */ - if (line.blur > 0) { - gl.uniform1f(uLineFade, line.blur); - blur = true; - } else if (mode == SHADER_FLAT) { - gl.uniform1f(uLineFade, (float) (pixel / width)); - //GL.uniform1f(uLineScale, (float)(pixel / (ll.width / s))); - } + if (line.blur > 0) { + gl.uniform1f(uLineFade, line.blur); + blur = true; + } else if (mode == SHADER_FLAT) { + gl.uniform1f(uLineFade, (float) (pixel / width)); + //GL.uniform1f(uLineScale, (float)(pixel / (ll.width / s))); + } /* Cap mode */ - if (lb.scale < 1.5 /* || ll.line.fixed */) { + if (lb.scale < 1.5 /* || ll.line.fixed */) { - if (capMode != CAP_THIN) { - capMode = CAP_THIN; - gl.uniform1f(uLineMode, capMode); - } - } else if (lb.roundCap) { - if (capMode != CAP_ROUND) { - capMode = CAP_ROUND; - gl.uniform1f(uLineMode, capMode); - } - } else if (capMode != CAP_BUTT) { - capMode = CAP_BUTT; - gl.uniform1f(uLineMode, capMode); - } + if (capMode != CAP_THIN) { + capMode = CAP_THIN; + gl.uniform1f(uLineMode, capMode); + } + } else if (lb.roundCap) { + if (capMode != CAP_ROUND) { + capMode = CAP_ROUND; + gl.uniform1f(uLineMode, capMode); + } + } else if (capMode != CAP_BUTT) { + capMode = CAP_BUTT; + gl.uniform1f(uLineMode, capMode); + } - gl.drawArrays(GL.TRIANGLE_STRIP, - b.vertexOffset, b.numVertices); + gl.drawArrays(GL.TRIANGLE_STRIP, + b.vertexOffset, b.numVertices); - continue; - } + continue; + } /* draw LineLayers references by this outline */ - for (LineBucket ref = lb.outlines; ref != null; ref = ref.outlines) { - LineStyle core = ref.line.current(); + for (LineBucket ref = lb.outlines; ref != null; ref = ref.outlines) { + LineStyle core = ref.line.current(); - // core width - if (core.fixed) { - width = Math.max(core.width, 1) / scale; - } else { - width = ref.scale * core.width / variableScale; - } - // add outline width - if (line.fixed) { - width += line.width / scale; - } else { - width += lb.scale * line.width / variableScale; - } + // core width + if (core.fixed) { + width = Math.max(core.width, 1) / scale; + } else { + width = ref.scale * core.width / variableScale; + } + // add outline width + if (line.fixed) { + width += line.width / scale; + } else { + width += lb.scale * line.width / variableScale; + } - gl.uniform1f(uLineWidth, - (float) (width * COORD_SCALE_BY_DIR_SCALE)); + gl.uniform1f(uLineWidth, + (float) (width * COORD_SCALE_BY_DIR_SCALE)); /* Line-edge fade */ - if (line.blur > 0) { - gl.uniform1f(uLineFade, line.blur); - blur = true; - } else if (mode == SHADER_FLAT) { - gl.uniform1f(uLineFade, (float) (pixel / width)); - } + if (line.blur > 0) { + gl.uniform1f(uLineFade, line.blur); + blur = true; + } else if (mode == SHADER_FLAT) { + gl.uniform1f(uLineFade, (float) (pixel / width)); + } /* Cap mode */ - if (ref.roundCap) { + if (ref.roundCap) { - if (capMode != CAP_ROUND) { - capMode = CAP_ROUND; - gl.uniform1f(uLineMode, capMode); - } - } else if (capMode != CAP_BUTT) { - capMode = CAP_BUTT; - gl.uniform1f(uLineMode, capMode); - } + if (capMode != CAP_ROUND) { + capMode = CAP_ROUND; + gl.uniform1f(uLineMode, capMode); + } + } else if (capMode != CAP_BUTT) { + capMode = CAP_BUTT; + gl.uniform1f(uLineMode, capMode); + } - gl.drawArrays(GL.TRIANGLE_STRIP, - ref.vertexOffset, ref.numVertices); - } - } + gl.drawArrays(GL.TRIANGLE_STRIP, + ref.vertexOffset, ref.numVertices); + } + } - return b; - } - } + return b; + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/LineTexBucket.java b/vtm/src/org/oscim/renderer/bucket/LineTexBucket.java index 19ffad94..478597a3 100644 --- a/vtm/src/org/oscim/renderer/bucket/LineTexBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/LineTexBucket.java @@ -16,14 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.renderer.MapRenderer.MAX_INDICES; -import static org.oscim.renderer.MapRenderer.bindQuadIndicesVBO; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.core.GeometryBuffer; import org.oscim.renderer.GLShader; @@ -35,19 +27,27 @@ import org.oscim.theme.styles.LineStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.ShortBuffer; + +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.renderer.MapRenderer.MAX_INDICES; +import static org.oscim.renderer.MapRenderer.bindQuadIndicesVBO; + /** * RenderElement for textured or stippled lines - * + *

* Interleave two segment quads in one block to be able to use * vertices twice. pos0 and pos1 use the same vertex array where * pos1 has an offset of one vertex. The vertex shader will use * pos0 when the vertexId is even, pos1 when the Id is odd. - * + *

* As there is no gl_VertexId in gles 2.0 an additional 'flip' * array is used. Depending on 'flip' extrusion is inverted. - * + *

* Indices and flip buffers can be static. - * + *

*

  * First pass: using even vertex array positions
  *   (used vertices are in braces)
@@ -55,26 +55,26 @@ import org.slf4j.LoggerFactory;
  * pos0     x (0) 1 (2) 3 (4) 5 (6) 7 x
  * pos1        x (0) 1 (2) 3 (4) 5 (6) 7 x
  * flip        0  1  0  1  0  1  0  1
- * 
+ *
  * Second pass: using odd vertex array positions
  * vertex id   0  1  2  3  4  5  6  7
  * pos0   x 0 (1) 2 (3) 4 (5) 6 (7) x
  * pos1      x 0 (1) 2 (3) 4 (5) 6 (7) x
  * flip        0  1  0  1  0  1  0  1
  * 
- * + *

* Vertex layout: * [2 short] position, * [2 short] extrusion, * [1 short] line length * [1 short] unused - * + *

* indices, for two blocks: * 0, 1, 2, * 2, 1, 3, * 4, 5, 6, * 6, 5, 7, - * + *

* BIG NOTE: renderer assumes to be able to offset vertex array position * so that in the first pass 'pos1' offset will be < 0 if no data precedes * - in our case there is always the polygon fill array at start @@ -82,354 +82,354 @@ import org.slf4j.LoggerFactory; */ public final class LineTexBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(LineTexBucket.class); + static final Logger log = LoggerFactory.getLogger(LineTexBucket.class); - private static final float COORD_SCALE = MapRenderer.COORD_SCALE; - /* scale factor mapping extrusion vector to short values */ - public static final float DIR_SCALE = 2048; + private static final float COORD_SCALE = MapRenderer.COORD_SCALE; + /* scale factor mapping extrusion vector to short values */ + public static final float DIR_SCALE = 2048; - public LineStyle line; - public float width; + public LineStyle line; + public float width; - public int evenQuads; - public int oddQuads; + public int evenQuads; + public int oddQuads; - private boolean evenSegment; + private boolean evenSegment; - protected boolean mRandomizeOffset = true; + protected boolean mRandomizeOffset = true; - LineTexBucket(int level) { - super(TEXLINE, false, true); + LineTexBucket(int level) { + super(TEXLINE, false, true); - this.level = level; - this.evenSegment = true; - } + this.level = level; + this.evenSegment = true; + } - public void addLine(GeometryBuffer geom) { - addLine(geom.points, geom.index); - } + public void addLine(GeometryBuffer geom) { + addLine(geom.points, geom.index); + } - public void addLine(float[] points, int[] index) { + public void addLine(float[] points, int[] index) { - if (vertexItems.empty()) { - /* HACK add one vertex offset when compiling - * buffer otherwise one cant use the full + if (vertexItems.empty()) { + /* HACK add one vertex offset when compiling + * buffer otherwise one cant use the full * VertexItem (see Layers.compile) * add the two 'x' at front and end */ - //numVertices = 2; + //numVertices = 2; /* the additional end vertex to make sure * not to read outside allocated memory */ - numVertices = 1; - } - VertexData vi = vertexItems; + numVertices = 1; + } + VertexData vi = vertexItems; - boolean even = evenSegment; + boolean even = evenSegment; /* reset offset to last written position */ - if (!even) - vi.seek(-12); + if (!even) + vi.seek(-12); - int n; - int length = 0; + int n; + int length = 0; - if (index == null) { - n = 1; - length = points.length; - } else { - n = index.length; - } + if (index == null) { + n = 1; + length = points.length; + } else { + n = index.length; + } - for (int i = 0, pos = 0; i < n; i++) { - if (index != null) - length = index[i]; + for (int i = 0, pos = 0; i < n; i++) { + if (index != null) + length = index[i]; /* check end-marker in indices */ - if (length < 0) - break; + if (length < 0) + break; /* need at least two points */ - if (length < 4) { - pos += length; - continue; - } + if (length < 4) { + pos += length; + continue; + } - int end = pos + length; - float x = points[pos++] * COORD_SCALE; - float y = points[pos++] * COORD_SCALE; + int end = pos + length; + float x = points[pos++] * COORD_SCALE; + float y = points[pos++] * COORD_SCALE; /* randomize a bit */ - float lineLength = mRandomizeOffset ? (x * x + y * y) % 80 : 0; + float lineLength = mRandomizeOffset ? (x * x + y * y) % 80 : 0; - while (pos < end) { - float nx = points[pos++] * COORD_SCALE; - float ny = points[pos++] * COORD_SCALE; + while (pos < end) { + float nx = points[pos++] * COORD_SCALE; + float ny = points[pos++] * COORD_SCALE; /* Calculate triangle corners for the given width */ - float vx = nx - x; - float vy = ny - y; + float vx = nx - x; + float vy = ny - y; - float a = (float) Math.sqrt(vx * vx + vy * vy); + float a = (float) Math.sqrt(vx * vx + vy * vy); /* normal vector */ - vx /= a; - vy /= a; + vx /= a; + vy /= a; /* perpendicular to line segment */ - float ux = -vy; - float uy = vx; + float ux = -vy; + float uy = vx; - short dx = (short) (ux * DIR_SCALE); - short dy = (short) (uy * DIR_SCALE); + short dx = (short) (ux * DIR_SCALE); + short dy = (short) (uy * DIR_SCALE); - vi.add((short) x, - (short) y, - dx, dy, - (short) lineLength, - (short) 0); + vi.add((short) x, + (short) y, + dx, dy, + (short) lineLength, + (short) 0); - lineLength += a; + lineLength += a; - vi.seek(6); - vi.add((short) nx, - (short) ny, - dx, dy, - (short) lineLength, - (short) 0); + vi.seek(6); + vi.add((short) nx, + (short) ny, + dx, dy, + (short) lineLength, + (short) 0); - x = nx; - y = ny; + x = nx; + y = ny; - if (even) { + if (even) { /* go to second segment */ - vi.seek(-12); - even = false; + vi.seek(-12); + even = false; /* vertex 0 and 2 were added */ - numVertices += 3; - evenQuads++; - } else { + numVertices += 3; + evenQuads++; + } else { /* go to next block */ - even = true; + even = true; /* vertex 1 and 3 were added */ - numVertices += 1; - oddQuads++; - } - } - } + numVertices += 1; + oddQuads++; + } + } + } - evenSegment = even; + evenSegment = even; /* advance offset to last written position */ - if (!even) - vi.seek(12); - } + if (!even) + vi.seek(12); + } - @Override - protected void compile(ShortBuffer vboData, ShortBuffer iboData) { - compileVertexItems(vboData); + @Override + protected void compile(ShortBuffer vboData, ShortBuffer iboData) { + compileVertexItems(vboData); /* add additional vertex for interleaving, see TexLineLayer. */ - vboData.position(vboData.position() + 6); - } + vboData.position(vboData.position() + 6); + } - static class Shader extends GLShader { - int uMVP, uColor, uWidth, uBgColor, uScale; - int uPatternWidth, uPatternScale; - int aPos0, aPos1, aLen0, aLen1, aFlip; + static class Shader extends GLShader { + int uMVP, uColor, uWidth, uBgColor, uScale; + int uPatternWidth, uPatternScale; + int aPos0, aPos1, aLen0, aLen1, aFlip; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; + Shader(String shaderFile) { + if (!create(shaderFile)) + return; - uMVP = getUniform("u_mvp"); + uMVP = getUniform("u_mvp"); - uScale = getUniform("u_scale"); - uColor = getUniform("u_color"); - uWidth = getUniform("u_width"); - uBgColor = getUniform("u_bgcolor"); + uScale = getUniform("u_scale"); + uColor = getUniform("u_color"); + uWidth = getUniform("u_width"); + uBgColor = getUniform("u_bgcolor"); - uPatternWidth = getUniform("u_pwidth"); - uPatternScale = getUniform("u_pscale"); + uPatternWidth = getUniform("u_pwidth"); + uPatternScale = getUniform("u_pscale"); - aPos0 = getAttrib("a_pos0"); - aPos1 = getAttrib("a_pos1"); - aLen0 = getAttrib("a_len0"); - aLen1 = getAttrib("a_len1"); - aFlip = getAttrib("a_flip"); - } - } + aPos0 = getAttrib("a_pos0"); + aPos1 = getAttrib("a_pos1"); + aLen0 = getAttrib("a_len0"); + aLen1 = getAttrib("a_len1"); + aFlip = getAttrib("a_flip"); + } + } - public final static class Renderer { - private static Shader shader; + public final static class Renderer { + private static Shader shader; - /* factor to normalize extrusion vector and scale to coord scale */ - private final static float COORD_SCALE_BY_DIR_SCALE = - MapRenderer.COORD_SCALE / LineBucket.DIR_SCALE; + /* factor to normalize extrusion vector and scale to coord scale */ + private final static float COORD_SCALE_BY_DIR_SCALE = + MapRenderer.COORD_SCALE / LineBucket.DIR_SCALE; - private static int mVertexFlipID; + private static int mVertexFlipID; - public static void init() { + public static void init() { - shader = new Shader("linetex_layer"); + shader = new Shader("linetex_layer"); - int[] vboIds = GLUtils.glGenBuffers(1); - mVertexFlipID = vboIds[0]; + int[] vboIds = GLUtils.glGenBuffers(1); + mVertexFlipID = vboIds[0]; /* bytes: 0, 1, 0, 1, 0, ... */ - byte[] flip = new byte[MapRenderer.MAX_QUADS * 4]; - for (int i = 0; i < flip.length; i++) - flip[i] = (byte) (i % 2); + byte[] flip = new byte[MapRenderer.MAX_QUADS * 4]; + for (int i = 0; i < flip.length; i++) + flip[i] = (byte) (i % 2); - ByteBuffer buf = ByteBuffer.allocateDirect(flip.length) - .order(ByteOrder.nativeOrder()); - buf.put(flip); - buf.flip(); + ByteBuffer buf = ByteBuffer.allocateDirect(flip.length) + .order(ByteOrder.nativeOrder()); + buf.put(flip); + buf.flip(); - ShortBuffer sbuf = buf.asShortBuffer(); + ShortBuffer sbuf = buf.asShortBuffer(); - //GL.bindBuffer(GL20.ARRAY_BUFFER, mVertexFlipID); - GLState.bindVertexBuffer(mVertexFlipID); - gl.bufferData(GL.ARRAY_BUFFER, flip.length, sbuf, - GL.STATIC_DRAW); - GLState.bindVertexBuffer(0); + //GL.bindBuffer(GL20.ARRAY_BUFFER, mVertexFlipID); + GLState.bindVertexBuffer(mVertexFlipID); + gl.bufferData(GL.ARRAY_BUFFER, flip.length, sbuf, + GL.STATIC_DRAW); + GLState.bindVertexBuffer(0); - // mTexID = new int[10]; - // byte[] stipple = new byte[2]; - // stipple[0] = 32; - // stipple[1] = 32; - // mTexID[0] = GlUtils.loadStippleTexture(stipple); - } + // mTexID = new int[10]; + // byte[] stipple = new byte[2]; + // stipple[0] = 32; + // stipple[1] = 32; + // mTexID[0] = GlUtils.loadStippleTexture(stipple); + } - private final static int STRIDE = 12; - private final static int LEN_OFFSET = 8; + private final static int STRIDE = 12; + private final static int LEN_OFFSET = 8; - public static RenderBucket draw(RenderBucket b, GLViewport v, - float div, RenderBuckets buckets) { + public static RenderBucket draw(RenderBucket b, GLViewport v, + float div, RenderBuckets buckets) { - //if (shader == 0) - // return curLayer.next; + //if (shader == 0) + // return curLayer.next; - GLState.blend(true); - //GLState.useProgram(shader); - shader.useProgram(); + GLState.blend(true); + //GLState.useProgram(shader); + shader.useProgram(); - GLState.enableVertexArrays(-1, -1); + GLState.enableVertexArrays(-1, -1); - int aLen0 = shader.aLen0; - int aLen1 = shader.aLen1; - int aPos0 = shader.aPos0; - int aPos1 = shader.aPos1; - int aFlip = shader.aFlip; + int aLen0 = shader.aLen0; + int aLen1 = shader.aLen1; + int aPos0 = shader.aPos0; + int aPos1 = shader.aPos1; + int aFlip = shader.aFlip; - gl.enableVertexAttribArray(aPos0); - gl.enableVertexAttribArray(aPos1); - gl.enableVertexAttribArray(aLen0); - gl.enableVertexAttribArray(aLen1); - gl.enableVertexAttribArray(aFlip); + gl.enableVertexAttribArray(aPos0); + gl.enableVertexAttribArray(aPos1); + gl.enableVertexAttribArray(aLen0); + gl.enableVertexAttribArray(aLen1); + gl.enableVertexAttribArray(aFlip); - v.mvp.setAsUniform(shader.uMVP); + v.mvp.setAsUniform(shader.uMVP); - bindQuadIndicesVBO(); + bindQuadIndicesVBO(); - GLState.bindVertexBuffer(mVertexFlipID); - gl.vertexAttribPointer(shader.aFlip, 1, - GL.BYTE, false, 0, 0); + GLState.bindVertexBuffer(mVertexFlipID); + gl.vertexAttribPointer(shader.aFlip, 1, + GL.BYTE, false, 0, 0); - buckets.vbo.bind(); + buckets.vbo.bind(); - float scale = (float) v.pos.getZoomScale(); + float scale = (float) v.pos.getZoomScale(); - float s = scale / div; + float s = scale / div; - //GL.bindTexture(GL20.TEXTURE_2D, mTexID[0]); + //GL.bindTexture(GL20.TEXTURE_2D, mTexID[0]); - for (; b != null && b.type == TEXLINE; b = b.next) { - LineTexBucket lb = (LineTexBucket) b; - LineStyle line = lb.line.current(); + for (; b != null && b.type == TEXLINE; b = b.next) { + LineTexBucket lb = (LineTexBucket) b; + LineStyle line = lb.line.current(); - GLUtils.setColor(shader.uColor, line.stippleColor, 1); - GLUtils.setColor(shader.uBgColor, line.color, 1); + GLUtils.setColor(shader.uColor, line.stippleColor, 1); + GLUtils.setColor(shader.uBgColor, line.color, 1); - float pScale = (int) (s + 0.5f); - if (pScale < 1) - pScale = 1; + float pScale = (int) (s + 0.5f); + if (pScale < 1) + pScale = 1; - gl.uniform1f(shader.uPatternScale, - (MapRenderer.COORD_SCALE * line.stipple) / pScale); + gl.uniform1f(shader.uPatternScale, + (MapRenderer.COORD_SCALE * line.stipple) / pScale); - gl.uniform1f(shader.uPatternWidth, line.stippleWidth); - //GL.uniform1f(hScale, scale); + gl.uniform1f(shader.uPatternWidth, line.stippleWidth); + //GL.uniform1f(hScale, scale); /* keep line width fixed */ - gl.uniform1f(shader.uWidth, lb.width / s * COORD_SCALE_BY_DIR_SCALE); + gl.uniform1f(shader.uWidth, lb.width / s * COORD_SCALE_BY_DIR_SCALE); /* add offset vertex */ - int vOffset = -STRIDE; + int vOffset = -STRIDE; - // TODO interleave 1. and 2. pass to improve vertex cache usage? + // TODO interleave 1. and 2. pass to improve vertex cache usage? /* first pass */ - int allIndices = (lb.evenQuads * 6); - for (int i = 0; i < allIndices; i += MAX_INDICES) { - int numIndices = allIndices - i; - if (numIndices > MAX_INDICES) - numIndices = MAX_INDICES; + int allIndices = (lb.evenQuads * 6); + for (int i = 0; i < allIndices; i += MAX_INDICES) { + int numIndices = allIndices - i; + if (numIndices > MAX_INDICES) + numIndices = MAX_INDICES; /* i / 6 * (24 shorts per block * 2 short bytes) */ - int add = (b.vertexOffset + i * 8) + vOffset; + int add = (b.vertexOffset + i * 8) + vOffset; - gl.vertexAttribPointer(aPos0, 4, GL.SHORT, false, STRIDE, - add + STRIDE); + gl.vertexAttribPointer(aPos0, 4, GL.SHORT, false, STRIDE, + add + STRIDE); - gl.vertexAttribPointer(aLen0, 2, GL.SHORT, false, STRIDE, - add + STRIDE + LEN_OFFSET); + gl.vertexAttribPointer(aLen0, 2, GL.SHORT, false, STRIDE, + add + STRIDE + LEN_OFFSET); - gl.vertexAttribPointer(aPos1, 4, GL.SHORT, false, STRIDE, - add); + gl.vertexAttribPointer(aPos1, 4, GL.SHORT, false, STRIDE, + add); - gl.vertexAttribPointer(aLen1, 2, GL.SHORT, false, STRIDE, - add + LEN_OFFSET); + gl.vertexAttribPointer(aLen1, 2, GL.SHORT, false, STRIDE, + add + LEN_OFFSET); - gl.drawElements(GL.TRIANGLES, numIndices, - GL.UNSIGNED_SHORT, 0); - } + gl.drawElements(GL.TRIANGLES, numIndices, + GL.UNSIGNED_SHORT, 0); + } /* second pass */ - allIndices = (lb.oddQuads * 6); - for (int i = 0; i < allIndices; i += MAX_INDICES) { - int numIndices = allIndices - i; - if (numIndices > MAX_INDICES) - numIndices = MAX_INDICES; + allIndices = (lb.oddQuads * 6); + for (int i = 0; i < allIndices; i += MAX_INDICES) { + int numIndices = allIndices - i; + if (numIndices > MAX_INDICES) + numIndices = MAX_INDICES; /* i / 6 * (24 shorts per block * 2 short bytes) */ - int add = (b.vertexOffset + i * 8) + vOffset; + int add = (b.vertexOffset + i * 8) + vOffset; - gl.vertexAttribPointer(aPos0, 4, GL.SHORT, false, STRIDE, - add + 2 * STRIDE); + gl.vertexAttribPointer(aPos0, 4, GL.SHORT, false, STRIDE, + add + 2 * STRIDE); - gl.vertexAttribPointer(aLen0, 2, GL.SHORT, false, STRIDE, - add + 2 * STRIDE + LEN_OFFSET); + gl.vertexAttribPointer(aLen0, 2, GL.SHORT, false, STRIDE, + add + 2 * STRIDE + LEN_OFFSET); - gl.vertexAttribPointer(aPos1, 4, GL.SHORT, false, STRIDE, - add + STRIDE); + gl.vertexAttribPointer(aPos1, 4, GL.SHORT, false, STRIDE, + add + STRIDE); - gl.vertexAttribPointer(aLen1, 2, GL.SHORT, false, STRIDE, - add + STRIDE + LEN_OFFSET); + gl.vertexAttribPointer(aLen1, 2, GL.SHORT, false, STRIDE, + add + STRIDE + LEN_OFFSET); - gl.drawElements(GL.TRIANGLES, numIndices, - GL.UNSIGNED_SHORT, 0); - } - //GlUtils.checkGlError(TAG); - } + gl.drawElements(GL.TRIANGLES, numIndices, + GL.UNSIGNED_SHORT, 0); + } + //GlUtils.checkGlError(TAG); + } - gl.disableVertexAttribArray(aPos0); - gl.disableVertexAttribArray(aPos1); - gl.disableVertexAttribArray(aLen0); - gl.disableVertexAttribArray(aLen1); - gl.disableVertexAttribArray(aFlip); + gl.disableVertexAttribArray(aPos0); + gl.disableVertexAttribArray(aPos1); + gl.disableVertexAttribArray(aLen0); + gl.disableVertexAttribArray(aLen1); + gl.disableVertexAttribArray(aFlip); - //GL.bindTexture(GL20.TEXTURE_2D, 0); + //GL.bindTexture(GL20.TEXTURE_2D, 0); - return b; - } - } + return b; + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/MeshBucket.java b/vtm/src/org/oscim/renderer/bucket/MeshBucket.java index 129aef16..3a462148 100644 --- a/vtm/src/org/oscim/renderer/bucket/MeshBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/MeshBucket.java @@ -16,9 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.renderer.MapRenderer.COORD_SCALE; - import org.oscim.backend.GL; import org.oscim.backend.canvas.Color; import org.oscim.core.GeometryBuffer; @@ -36,210 +33,213 @@ import org.oscim.utils.TessJNI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.renderer.MapRenderer.COORD_SCALE; + public class MeshBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(MeshBucket.class); - static final boolean dbgRender = false; + static final Logger log = LoggerFactory.getLogger(MeshBucket.class); + static final boolean dbgRender = false; - public AreaStyle area; - public float heightOffset; + public AreaStyle area; + public float heightOffset; - private TessJNI tess; + private TessJNI tess; - private int numPoints; + private int numPoints; - public MeshBucket(int level) { - super(RenderBucket.MESH, true, false); - this.level = level; - } + public MeshBucket(int level) { + super(RenderBucket.MESH, true, false); + this.level = level; + } - public void addMesh(GeometryBuffer geom) { - numPoints += geom.pointPos; - if (tess == null) - tess = new TessJNI(8); + public void addMesh(GeometryBuffer geom) { + numPoints += geom.pointPos; + if (tess == null) + tess = new TessJNI(8); - tess.addContour2D(geom.index, geom.points); - } + tess.addContour2D(geom.index, geom.points); + } - public void addConvexMesh(GeometryBuffer geom) { - short start = (short) numVertices; + public void addConvexMesh(GeometryBuffer geom) { + short start = (short) numVertices; - if (numVertices >= (1 << 16)) { - return; - } + if (numVertices >= (1 << 16)) { + return; + } - vertexItems.add(geom.points[0] * COORD_SCALE, - geom.points[1] * COORD_SCALE); + vertexItems.add(geom.points[0] * COORD_SCALE, + geom.points[1] * COORD_SCALE); - vertexItems.add(geom.points[2] * COORD_SCALE, - geom.points[3] * COORD_SCALE); - short prev = (short) (start + 1); + vertexItems.add(geom.points[2] * COORD_SCALE, + geom.points[3] * COORD_SCALE); + short prev = (short) (start + 1); - numVertices += 2; + numVertices += 2; - for (int i = 4; i < geom.index[0]; i += 2) { + for (int i = 4; i < geom.index[0]; i += 2) { - vertexItems.add(geom.points[i + 0] * COORD_SCALE, - geom.points[i + 1] * COORD_SCALE); + vertexItems.add(geom.points[i + 0] * COORD_SCALE, + geom.points[i + 1] * COORD_SCALE); - indiceItems.add(start, prev, ++prev); - numVertices++; + indiceItems.add(start, prev, ++prev); + numVertices++; - numIndices += 3; - } + numIndices += 3; + } - //numPoints += geom.pointPos; - //tess.addContour2D(geom.index, geom.points); - } + //numPoints += geom.pointPos; + //tess.addContour2D(geom.index, geom.points); + } - protected void prepare() { - if (tess == null) - return; + protected void prepare() { + if (tess == null) + return; - if (numPoints == 0) { - tess.dispose(); - return; - } - if (!tess.tesselate()) { - tess.dispose(); - log.error("error in tessellation {}", numPoints); - return; - } + if (numPoints == 0) { + tess.dispose(); + return; + } + if (!tess.tesselate()) { + tess.dispose(); + log.error("error in tessellation {}", numPoints); + return; + } - int nelems = tess.getElementCount() * 3; + int nelems = tess.getElementCount() * 3; - //int startVertex = vertexItems.countSize(); + //int startVertex = vertexItems.countSize(); - for (int offset = indiceItems.countSize(); offset < nelems;) { - int size = nelems - offset; - if (size > VertexData.SIZE) - size = VertexData.SIZE; + for (int offset = indiceItems.countSize(); offset < nelems; ) { + int size = nelems - offset; + if (size > VertexData.SIZE) + size = VertexData.SIZE; - Chunk chunk = indiceItems.obtainChunk(); + Chunk chunk = indiceItems.obtainChunk(); - tess.getElements(chunk.vertices, offset, size); - offset += size; + tess.getElements(chunk.vertices, offset, size); + offset += size; - //if (startVertex != 0) - // FIXME + //if (startVertex != 0) + // FIXME - indiceItems.releaseChunk(size); - } + indiceItems.releaseChunk(size); + } - int nverts = tess.getVertexCount() * 2; + int nverts = tess.getVertexCount() * 2; - for (int offset = 0; offset < nverts;) { - int size = nverts - offset; - if (size > VertexData.SIZE) - size = VertexData.SIZE; + for (int offset = 0; offset < nverts; ) { + int size = nverts - offset; + if (size > VertexData.SIZE) + size = VertexData.SIZE; - Chunk chunk = vertexItems.obtainChunk(); + Chunk chunk = vertexItems.obtainChunk(); - tess.getVertices(chunk.vertices, offset, size, - MapRenderer.COORD_SCALE); - offset += size; + tess.getVertices(chunk.vertices, offset, size, + MapRenderer.COORD_SCALE); + offset += size; - vertexItems.releaseChunk(size); - } + vertexItems.releaseChunk(size); + } - this.numIndices += nelems; - this.numVertices += nverts >> 1; + this.numIndices += nelems; + this.numVertices += nverts >> 1; - tess.dispose(); - } + tess.dispose(); + } - public static class Renderer { - static Shader shader; + public static class Renderer { + static Shader shader; - static boolean init() { - shader = new Shader("mesh_layer_2D"); - return true; - } + static boolean init() { + shader = new Shader("mesh_layer_2D"); + return true; + } - static class Shader extends GLShader { - int uMVP, uColor, uHeight, aPos; + static class Shader extends GLShader { + int uMVP, uColor, uHeight, aPos; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; + Shader(String shaderFile) { + if (!create(shaderFile)) + return; - uMVP = getUniform("u_mvp"); - uColor = getUniform("u_color"); - uHeight = getUniform("u_height"); - aPos = getAttrib("a_pos"); - } - } + uMVP = getUniform("u_mvp"); + uColor = getUniform("u_color"); + uHeight = getUniform("u_height"); + aPos = getAttrib("a_pos"); + } + } - public static RenderBucket draw(RenderBucket l, GLViewport v) { - GLState.blend(true); + public static RenderBucket draw(RenderBucket l, GLViewport v) { + GLState.blend(true); - Shader s = shader; + Shader s = shader; - s.useProgram(); - GLState.enableVertexArrays(s.aPos, -1); + s.useProgram(); + GLState.enableVertexArrays(s.aPos, -1); - v.mvp.setAsUniform(s.uMVP); + v.mvp.setAsUniform(s.uMVP); - float heightOffset = 0; - gl.uniform1f(s.uHeight, heightOffset); + float heightOffset = 0; + gl.uniform1f(s.uHeight, heightOffset); - for (; l != null && l.type == MESH; l = l.next) { - MeshBucket ml = (MeshBucket) l; + for (; l != null && l.type == MESH; l = l.next) { + MeshBucket ml = (MeshBucket) l; - if (ml.heightOffset != heightOffset) { - heightOffset = ml.heightOffset; + if (ml.heightOffset != heightOffset) { + heightOffset = ml.heightOffset; - gl.uniform1f(s.uHeight, heightOffset / - MercatorProjection.groundResolution(v.pos)); - } + gl.uniform1f(s.uHeight, heightOffset / + MercatorProjection.groundResolution(v.pos)); + } - if (ml.area == null) - GLUtils.setColor(s.uColor, Color.BLUE, 0.4f); - else { - setColor(ml.area.current(), s, v.pos); - } - gl.vertexAttribPointer(s.aPos, 2, GL.SHORT, - false, 0, ml.vertexOffset); + if (ml.area == null) + GLUtils.setColor(s.uColor, Color.BLUE, 0.4f); + else { + setColor(ml.area.current(), s, v.pos); + } + gl.vertexAttribPointer(s.aPos, 2, GL.SHORT, + false, 0, ml.vertexOffset); - gl.drawElements(GL.TRIANGLES, - ml.numIndices, - GL.UNSIGNED_SHORT, - ml.indiceOffset); + gl.drawElements(GL.TRIANGLES, + ml.numIndices, + GL.UNSIGNED_SHORT, + ml.indiceOffset); - if (dbgRender) { - int c = (ml.area == null) ? Color.BLUE : ml.area.color; - gl.lineWidth(1); - //c = ColorUtil.shiftHue(c, 0.5); - c = ColorUtil.modHsv(c, 1.1, 1.0, 0.8, true); - GLUtils.setColor(s.uColor, c, 1); - gl.drawElements(GL.LINES, - ml.numIndices, - GL.UNSIGNED_SHORT, - ml.vertexOffset); - } - } - return l; - } + if (dbgRender) { + int c = (ml.area == null) ? Color.BLUE : ml.area.color; + gl.lineWidth(1); + //c = ColorUtil.shiftHue(c, 0.5); + c = ColorUtil.modHsv(c, 1.1, 1.0, 0.8, true); + GLUtils.setColor(s.uColor, c, 1); + gl.drawElements(GL.LINES, + ml.numIndices, + GL.UNSIGNED_SHORT, + ml.vertexOffset); + } + } + return l; + } - private static final int OPAQUE = 0xff000000; + private static final int OPAQUE = 0xff000000; - static void setColor(AreaStyle a, Shader s, MapPosition pos) { - float fade = a.getFade(pos.scale); - float blend = a.getBlend(pos.scale); + static void setColor(AreaStyle a, Shader s, MapPosition pos) { + float fade = a.getFade(pos.scale); + float blend = a.getBlend(pos.scale); - if (fade < 1.0f) { - GLState.blend(true); - GLUtils.setColor(s.uColor, a.color, fade); - } else if (blend > 0.0f) { - if (blend == 1.0f) - GLUtils.setColor(s.uColor, a.blendColor, 1); - else - GLUtils.setColorBlend(s.uColor, a.color, - a.blendColor, blend); - } else { - /* test if color contains alpha */ - GLState.blend((a.color & OPAQUE) != OPAQUE); - GLUtils.setColor(s.uColor, a.color, 1); - } - } - } + if (fade < 1.0f) { + GLState.blend(true); + GLUtils.setColor(s.uColor, a.color, fade); + } else if (blend > 0.0f) { + if (blend == 1.0f) + GLUtils.setColor(s.uColor, a.blendColor, 1); + else + GLUtils.setColorBlend(s.uColor, a.color, + a.blendColor, blend); + } else { + /* test if color contains alpha */ + GLState.blend((a.color & OPAQUE) != OPAQUE); + GLUtils.setColor(s.uColor, a.color, 1); + } + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/PolygonBucket.java b/vtm/src/org/oscim/renderer/bucket/PolygonBucket.java index cd10b889..12b32503 100644 --- a/vtm/src/org/oscim/renderer/bucket/PolygonBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/PolygonBucket.java @@ -16,11 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.utils.FastMath.clamp; - -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.backend.canvas.Color; import org.oscim.core.GeometryBuffer; @@ -39,424 +34,424 @@ import org.oscim.utils.math.Interpolation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.utils.FastMath.clamp; + /** * Special Renderer for drawing tile polygons using the stencil buffer method */ public final class PolygonBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(PolygonBucket.class); + static final Logger log = LoggerFactory.getLogger(PolygonBucket.class); - public final static int CLIP_STENCIL = 1; - public final static int CLIP_DEPTH = 2; - public final static int CLIP_TEST_DEPTH = 3; + public final static int CLIP_STENCIL = 1; + public final static int CLIP_DEPTH = 2; + public final static int CLIP_TEST_DEPTH = 3; - private static final float S = MapRenderer.COORD_SCALE; + private static final float S = MapRenderer.COORD_SCALE; - private static final boolean enableTexture = true; + private static final boolean enableTexture = true; - public AreaStyle area; + public AreaStyle area; - PolygonBucket(int layer) { - super(RenderBucket.POLYGON, true, false); - level = layer; - } + PolygonBucket(int layer) { + super(RenderBucket.POLYGON, true, false); + level = layer; + } - public void addPolygon(GeometryBuffer geom) { - addPolygon(geom.points, geom.index); - } + public void addPolygon(GeometryBuffer geom) { + addPolygon(geom.points, geom.index); + } - float xmin = Short.MAX_VALUE; - float ymin = Short.MAX_VALUE; - float xmax = Short.MIN_VALUE; - float ymax = Short.MIN_VALUE; + float xmin = Short.MAX_VALUE; + float ymin = Short.MAX_VALUE; + float xmax = Short.MIN_VALUE; + float ymax = Short.MIN_VALUE; - final float[] bbox = new float[8]; + final float[] bbox = new float[8]; - public void addPolygon(float[] points, int[] index) { - short center = (short) ((Tile.SIZE >> 1) * S); + public void addPolygon(float[] points, int[] index) { + short center = (short) ((Tile.SIZE >> 1) * S); - boolean outline = area.strokeWidth > 0; + boolean outline = area.strokeWidth > 0; - for (int i = 0, pos = 0, n = index.length; i < n; i++) { - int length = index[i]; - if (length < 0) - break; + for (int i = 0, pos = 0, n = index.length; i < n; i++) { + int length = index[i]; + if (length < 0) + break; /* need at least three points */ - if (length < 6) { - pos += length; - continue; - } + if (length < 6) { + pos += length; + continue; + } - vertexItems.add(center, center); - numVertices++; + vertexItems.add(center, center); + numVertices++; - int inPos = pos; + int inPos = pos; - for (int j = 0; j < length; j += 2) { - float x = (points[inPos++] * S); - float y = (points[inPos++] * S); - xmax = Math.max(xmax, x); - xmin = Math.min(xmin, x); - ymax = Math.max(ymax, y); - ymin = Math.min(ymin, y); + for (int j = 0; j < length; j += 2) { + float x = (points[inPos++] * S); + float y = (points[inPos++] * S); + xmax = Math.max(xmax, x); + xmin = Math.min(xmin, x); + ymax = Math.max(ymax, y); + ymin = Math.min(ymin, y); - if (outline) { - indiceItems.add((short) numVertices); - numIndices++; - } + if (outline) { + indiceItems.add((short) numVertices); + numIndices++; + } - vertexItems.add((short) x, (short) y); - numVertices++; + vertexItems.add((short) x, (short) y); + numVertices++; - if (outline) { - indiceItems.add((short) numVertices); - numIndices++; - } - } + if (outline) { + indiceItems.add((short) numVertices); + numIndices++; + } + } - vertexItems.add((short) (points[pos + 0] * S), - (short) (points[pos + 1] * S)); - numVertices++; + vertexItems.add((short) (points[pos + 0] * S), + (short) (points[pos + 1] * S)); + numVertices++; - pos += length; - } - } + pos += length; + } + } - @Override - protected void prepare() { - ArrayUtils.setBox2D(bbox, xmin, ymin, xmax, ymax); - } + @Override + protected void prepare() { + ArrayUtils.setBox2D(bbox, xmin, ymin, xmax, ymax); + } - @Override - protected void compile(ShortBuffer vboData, ShortBuffer iboData) { - if (area.strokeWidth == 0) { - /* add vertices to shared VBO */ - compileVertexItems(vboData); - } else { - /* compile with indexed outline */ - super.compile(vboData, iboData); - } - } + @Override + protected void compile(ShortBuffer vboData, ShortBuffer iboData) { + if (area.strokeWidth == 0) { + /* add vertices to shared VBO */ + compileVertexItems(vboData); + } else { + /* compile with indexed outline */ + super.compile(vboData, iboData); + } + } - static class Shader extends GLShader { - int uMVP, uColor, uScale, aPos; + static class Shader extends GLShader { + int uMVP, uColor, uScale, aPos; - Shader(String shaderFile) { - if (!create(shaderFile)) - return; + Shader(String shaderFile) { + if (!create(shaderFile)) + return; - uMVP = getUniform("u_mvp"); - aPos = getAttrib("a_pos"); - uColor = getUniform("u_color"); - if (shaderFile == "polygon_layer_tex") - uScale = getUniform("u_scale"); - } - } + uMVP = getUniform("u_mvp"); + aPos = getAttrib("a_pos"); + uColor = getUniform("u_color"); + if (shaderFile == "polygon_layer_tex") + uScale = getUniform("u_scale"); + } + } - public static final class Renderer { + public static final class Renderer { - private static final int STENCIL_BITS = 8; - public final static int CLIP_BIT = 0x80; + private static final int STENCIL_BITS = 8; + public final static int CLIP_BIT = 0x80; - private static PolygonBucket[] mAreaLayer; + private static PolygonBucket[] mAreaLayer; - private static Shader polyShader; - private static Shader texShader; + private static Shader polyShader; + private static Shader texShader; - static boolean init() { - polyShader = new Shader("base_shader"); - texShader = new Shader("polygon_layer_tex"); + static boolean init() { + polyShader = new Shader("base_shader"); + texShader = new Shader("polygon_layer_tex"); - mAreaLayer = new PolygonBucket[STENCIL_BITS]; + mAreaLayer = new PolygonBucket[STENCIL_BITS]; - return true; - } + return true; + } - private static void fillPolygons(GLViewport v, int start, int end, - MapPosition pos, float div) { + private static void fillPolygons(GLViewport v, int start, int end, + MapPosition pos, float div) { /* draw to framebuffer */ - gl.colorMask(true, true, true, true); + gl.colorMask(true, true, true, true); /* do not modify stencil buffer */ - gl.stencilMask(0x00); - Shader s; + gl.stencilMask(0x00); + Shader s; - for (int i = start; i < end; i++) { - PolygonBucket l = mAreaLayer[i]; - AreaStyle a = l.area.current(); + for (int i = start; i < end; i++) { + PolygonBucket l = mAreaLayer[i]; + AreaStyle a = l.area.current(); - if (enableTexture && (a.texture != null)) { - s = setShader(texShader, v.mvp, false); - float num = clamp((Tile.SIZE / a.texture.width) >> 1, 1, Tile.SIZE); + if (enableTexture && (a.texture != null)) { + s = setShader(texShader, v.mvp, false); + float num = clamp((Tile.SIZE / a.texture.width) >> 1, 1, Tile.SIZE); - float scale = (float) pos.getZoomScale(); - float transition = clamp(scale - 1, 0, 1); - transition = Interpolation.exp5.apply(transition); + float scale = (float) pos.getZoomScale(); + float transition = clamp(scale - 1, 0, 1); + transition = Interpolation.exp5.apply(transition); - gl.uniform2f(s.uScale, transition, div / num); - a.texture.bind(); + gl.uniform2f(s.uScale, transition, div / num); + a.texture.bind(); - } else { - s = setShader(polyShader, v.mvp, false); - } + } else { + s = setShader(polyShader, v.mvp, false); + } - float fade = a.getFade(pos.scale); - float blendFill = a.getBlend(pos.scale); - boolean blend = (s == texShader || fade < 1.0); + float fade = a.getFade(pos.scale); + float blendFill = a.getBlend(pos.scale); + boolean blend = (s == texShader || fade < 1.0); - if (fade < 1.0) { - GLUtils.setColor(s.uColor, a.color, fade); - } else if (blendFill > 0.0f) { - if (blendFill == 1.0f) { - GLUtils.setColor(s.uColor, a.blendColor, 1); - } else { - GLUtils.setColorBlend(s.uColor, a.color, - a.blendColor, blendFill); - } - } else { - blend |= !Color.isOpaque(a.color); - GLUtils.setColor(s.uColor, a.color, fade); - } + if (fade < 1.0) { + GLUtils.setColor(s.uColor, a.color, fade); + } else if (blendFill > 0.0f) { + if (blendFill == 1.0f) { + GLUtils.setColor(s.uColor, a.blendColor, 1); + } else { + GLUtils.setColorBlend(s.uColor, a.color, + a.blendColor, blendFill); + } + } else { + blend |= !Color.isOpaque(a.color); + GLUtils.setColor(s.uColor, a.color, fade); + } - GLState.blend(blend); + GLState.blend(blend); /* set stencil buffer mask used to draw this layer * also check that clip bit is set to avoid overdraw * of other tiles */ - gl.stencilFunc(GL.EQUAL, 0xff, CLIP_BIT | 1 << i); + gl.stencilFunc(GL.EQUAL, 0xff, CLIP_BIT | 1 << i); /* draw tile fill coordinates */ - gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); + gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); - if (a.strokeWidth <= 0) - continue; + if (a.strokeWidth <= 0) + continue; - gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); + gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); - GLState.blend(true); + GLState.blend(true); - HairLineBucket.Renderer.shader.set(v); + HairLineBucket.Renderer.shader.set(v); - GLUtils.setColor(HairLineBucket.Renderer.shader.uColor, - l.area.strokeColor, 1); + GLUtils.setColor(HairLineBucket.Renderer.shader.uColor, + l.area.strokeColor, 1); - gl.vertexAttribPointer(HairLineBucket.Renderer.shader.aPos, - 2, GL.SHORT, false, 0, - // 4 bytes per vertex - l.vertexOffset << 2); + gl.vertexAttribPointer(HairLineBucket.Renderer.shader.aPos, + 2, GL.SHORT, false, 0, + // 4 bytes per vertex + l.vertexOffset << 2); - gl.uniform1f(HairLineBucket.Renderer.shader.uWidth, - a.strokeWidth); + gl.uniform1f(HairLineBucket.Renderer.shader.uWidth, + a.strokeWidth); - gl.drawElements(GL.LINES, - l.numIndices, - GL.UNSIGNED_SHORT, - l.indiceOffset); - gl.lineWidth(1); + gl.drawElements(GL.LINES, + l.numIndices, + GL.UNSIGNED_SHORT, + l.indiceOffset); + gl.lineWidth(1); - ///* disable texture shader */ - //if (s != polyShader) - // s = setShader(polyShader, v.mvp, false); - } - } + ///* disable texture shader */ + //if (s != polyShader) + // s = setShader(polyShader, v.mvp, false); + } + } - /** current layer to fill (0 - STENCIL_BITS-1) */ - private static int mCount; - /** must clear stencil for next draw */ - private static boolean mClear; + /** + * current layer to fill (0 - STENCIL_BITS-1) + */ + private static int mCount; + /** + * must clear stencil for next draw + */ + private static boolean mClear; - private static Shader setShader(Shader shader, GLMatrix mvp, boolean first) { - if (shader.useProgram() || first) { - GLState.enableVertexArrays(shader.aPos, -1); + private static Shader setShader(Shader shader, GLMatrix mvp, boolean first) { + if (shader.useProgram() || first) { + GLState.enableVertexArrays(shader.aPos, -1); - gl.vertexAttribPointer(shader.aPos, 2, - GL.SHORT, false, 0, 0); + gl.vertexAttribPointer(shader.aPos, 2, + GL.SHORT, false, 0, 0); - mvp.setAsUniform(shader.uMVP); - } - return shader; - } + mvp.setAsUniform(shader.uMVP); + } + return shader; + } - static float[] mBBox = new float[8]; - static LineClipper mScreenClip = new LineClipper(-1, -1, 1, 1); + static float[] mBBox = new float[8]; + static LineClipper mScreenClip = new LineClipper(-1, -1, 1, 1); - /** - * draw polygon buckets (until bucket.next is not polygon bucket) - * using stencil buffer method - * - * @param buckets - * layer to draw (referencing vertices in current vbo) - * @param v - * GLViewport - * @param pos - * used to fade buckets according to 'fade' in - * layer.area style - * @param div - * scale relative to 'base scale' of the tile - * @param first - * pass true to clear stencil buffer region - * @param clipMode - * clip to first quad in current vbo - * using CLIP_STENCIL / CLIP_DEPTH - * - * @return - * next layer - */ - public static RenderBucket draw(RenderBucket buckets, GLViewport v, - float div, boolean first) { + /** + * draw polygon buckets (until bucket.next is not polygon bucket) + * using stencil buffer method + * + * @param buckets layer to draw (referencing vertices in current vbo) + * @param v GLViewport + * @param pos used to fade buckets according to 'fade' in + * layer.area style + * @param div scale relative to 'base scale' of the tile + * @param first pass true to clear stencil buffer region + * @param clipMode clip to first quad in current vbo + * using CLIP_STENCIL / CLIP_DEPTH + * @return next layer + */ + public static RenderBucket draw(RenderBucket buckets, GLViewport v, + float div, boolean first) { - GLState.test(false, true); + GLState.test(false, true); - setShader(polyShader, v.mvp, first); + setShader(polyShader, v.mvp, first); - int zoom = v.pos.zoomLevel; + int zoom = v.pos.zoomLevel; - int cur = mCount; - int start = mCount; + int cur = mCount; + int start = mCount; /* draw to stencil buffer */ - gl.colorMask(false, false, false, false); + gl.colorMask(false, false, false, false); /* op for stencil method polygon drawing */ - gl.stencilOp(GL.KEEP, GL.KEEP, GL.INVERT); + gl.stencilOp(GL.KEEP, GL.KEEP, GL.INVERT); - boolean drawn = false; + boolean drawn = false; - byte stencilMask = 0; + byte stencilMask = 0; - float[] box = mBBox; + float[] box = mBBox; - RenderBucket b = buckets; - for (; b != null && b.type == POLYGON; b = b.next) { - PolygonBucket pb = (PolygonBucket) b; - AreaStyle area = pb.area.current(); + RenderBucket b = buckets; + for (; b != null && b.type == POLYGON; b = b.next) { + PolygonBucket pb = (PolygonBucket) b; + AreaStyle area = pb.area.current(); /* fade out polygon bucket (set in RenderTheme) */ - if (area.fadeScale > 0 && area.fadeScale > zoom) - continue; + if (area.fadeScale > 0 && area.fadeScale > zoom) + continue; - if (div > 0.5) { + if (div > 0.5) { /* project bbox of polygon to screen */ - v.mvp.prj2D(pb.bbox, 0, box, 0, 4); + v.mvp.prj2D(pb.bbox, 0, box, 0, 4); - int out = 0; - for (int i = 0; i < 8; i += 2) { - int o = mScreenClip.outcode(box[i], box[i + 1]); + int out = 0; + for (int i = 0; i < 8; i += 2) { + int o = mScreenClip.outcode(box[i], box[i + 1]); - if (o == 0) { + if (o == 0) { /* at least one corner is inside */ - out = 0; - break; - } - out |= o; - } + out = 0; + break; + } + out |= o; + } /* Check if any polygon-bucket edge intersects the screen. * Also check the very unlikely case where the view might * be * completly contained within box */ - if ((out != 0) && (out != 0xF)) { - mScreenClip.clipStart(box[6], box[7]); - out = 0; - for (int i = 0; i < 8 && out == 0; i += 2) - out = mScreenClip.clipNext(box[i], box[i + 1]); + if ((out != 0) && (out != 0xF)) { + mScreenClip.clipStart(box[6], box[7]); + out = 0; + for (int i = 0; i < 8 && out == 0; i += 2) + out = mScreenClip.clipNext(box[i], box[i + 1]); - if (out == 0) { - //log.debug("out {}\n {}\n {}", out, Arrays.toString(pb.bbox), Arrays.toString(box)); + if (out == 0) { + //log.debug("out {}\n {}\n {}", out, Arrays.toString(pb.bbox), Arrays.toString(box)); - // log.debug("outside {} {} {}", out, - // Arrays.toString(box), - // Arrays.toString(pb.bbox)); - continue; - } - } - } - if (mClear) { - clearStencilRegion(); + // log.debug("outside {} {} {}", out, + // Arrays.toString(box), + // Arrays.toString(pb.bbox)); + continue; + } + } + } + if (mClear) { + clearStencilRegion(); /* op for stencil method polygon drawing */ - gl.stencilOp(GL.KEEP, GL.KEEP, GL.INVERT); + gl.stencilOp(GL.KEEP, GL.KEEP, GL.INVERT); - start = cur = 0; - } + start = cur = 0; + } - mAreaLayer[cur] = pb; + mAreaLayer[cur] = pb; /* set stencil mask to draw to */ - int stencil = 1 << cur++; + int stencil = 1 << cur++; - if (area.hasAlpha(zoom)) { - gl.stencilMask(stencil); - stencilMask |= stencil; - } - else { - stencilMask |= stencil; - gl.stencilMask(stencilMask); - } + if (area.hasAlpha(zoom)) { + gl.stencilMask(stencil); + stencilMask |= stencil; + } else { + stencilMask |= stencil; + gl.stencilMask(stencilMask); + } - gl.drawArrays(GL.TRIANGLE_FAN, b.vertexOffset, b.numVertices); + gl.drawArrays(GL.TRIANGLE_FAN, b.vertexOffset, b.numVertices); /* draw up to 7 buckets into stencil buffer */ - if (cur == STENCIL_BITS - 1) { - fillPolygons(v, start, cur, v.pos, div); - drawn = true; + if (cur == STENCIL_BITS - 1) { + fillPolygons(v, start, cur, v.pos, div); + drawn = true; - mClear = true; - start = cur = 0; + mClear = true; + start = cur = 0; - if (b.next != null && b.next.type == POLYGON) { - setShader(polyShader, v.mvp, false); - stencilMask = 0; - } - } - } + if (b.next != null && b.next.type == POLYGON) { + setShader(polyShader, v.mvp, false); + stencilMask = 0; + } + } + } - if (cur > 0) { - fillPolygons(v, start, cur, v.pos, div); - drawn = true; - } + if (cur > 0) { + fillPolygons(v, start, cur, v.pos, div); + drawn = true; + } - if (!drawn) { + if (!drawn) { /* fillPolygons would re-enable color-mask * but it's possible that all polygon buckets * were skipped */ - gl.colorMask(true, true, true, true); - gl.stencilMask(0x00); - } + gl.colorMask(true, true, true, true); + gl.stencilMask(0x00); + } - mCount = cur; - return b; - } + mCount = cur; + return b; + } - public static void clip(GLMatrix mvp, int clipMode) { - setShader(polyShader, mvp, true); + public static void clip(GLMatrix mvp, int clipMode) { + setShader(polyShader, mvp, true); - drawStencilRegion(clipMode); + drawStencilRegion(clipMode); /* disable writes to stencil buffer */ - gl.stencilMask(0x00); + gl.stencilMask(0x00); /* enable writes to color buffer */ - gl.colorMask(true, true, true, true); - } + gl.colorMask(true, true, true, true); + } - /** - * Draw a tile filling rectangle to set stencil- and depth buffer - * appropriately - * - * @param first in the first run the clip region is set based on - * depth buffer and depth buffer is updated - */ - static void drawStencilRegion(int clipMode) { - //log.debug("draw stencil {}", clipMode); - mCount = 0; - mClear = false; + /** + * Draw a tile filling rectangle to set stencil- and depth buffer + * appropriately + * + * @param first in the first run the clip region is set based on + * depth buffer and depth buffer is updated + */ + static void drawStencilRegion(int clipMode) { + //log.debug("draw stencil {}", clipMode); + mCount = 0; + mClear = false; /* disable drawing to color buffer */ - gl.colorMask(false, false, false, false); + gl.colorMask(false, false, false, false); /* write to all stencil bits */ - gl.stencilMask(0xFF); + gl.stencilMask(0xFF); /* Draw clip-region into depth and stencil buffer. * This is used for tile line and polygon buckets. @@ -464,92 +459,92 @@ public final class PolygonBucket extends RenderBucket { * Together with depth test (GL20.LESS) this ensures to * only draw where no other tile has drawn yet. */ - if (clipMode == CLIP_DEPTH) { + if (clipMode == CLIP_DEPTH) { /* tests GL20.LESS/GL20.ALWAYS and */ /* write tile region to depth buffer */ - GLState.test(true, true); - gl.depthMask(true); - } else { - GLState.test(false, true); - } + GLState.test(true, true); + gl.depthMask(true); + } else { + GLState.test(false, true); + } /* always pass stencil test and set clip bit */ - gl.stencilFunc(GL.ALWAYS, CLIP_BIT, 0x00); + gl.stencilFunc(GL.ALWAYS, CLIP_BIT, 0x00); /* set clip bit (0x80) for draw region */ - gl.stencilOp(GL.KEEP, GL.KEEP, GL.REPLACE); + gl.stencilOp(GL.KEEP, GL.KEEP, GL.REPLACE); /* draw a quad for the tile region */ - gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); + gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); - if (clipMode == CLIP_DEPTH) { + if (clipMode == CLIP_DEPTH) { /* dont modify depth buffer */ - gl.depthMask(false); - GLState.test(false, true); - } - gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); - } + gl.depthMask(false); + GLState.test(false, true); + } + gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); + } - static void clearStencilRegion() { + static void clearStencilRegion() { - mCount = 0; - mClear = false; + mCount = 0; + mClear = false; /* disable drawing to color buffer */ - gl.colorMask(false, false, false, false); + gl.colorMask(false, false, false, false); /* write to all stencil bits except clip bit */ - gl.stencilMask(0xFF); + gl.stencilMask(0xFF); /* use clip bit from stencil buffer to clear stencil * 'layer-bits' (0x7f) */ - gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); + gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); /* set clip bit (0x80) for draw region */ - gl.stencilOp(GL.KEEP, GL.KEEP, GL.REPLACE); + gl.stencilOp(GL.KEEP, GL.KEEP, GL.REPLACE); /* draw a quad for the tile region */ - gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); - } + gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); + } - /** - * Clear stencilbuffer for a tile region by drawing - * a quad with func 'always' and op 'zero'. Using 'color' - * and 'alpha' to fake a fade effect. - */ - public static void drawOver(GLMatrix mvp, int color, float alpha) { + /** + * Clear stencilbuffer for a tile region by drawing + * a quad with func 'always' and op 'zero'. Using 'color' + * and 'alpha' to fake a fade effect. + */ + public static void drawOver(GLMatrix mvp, int color, float alpha) { /* TODO true could be avoided when same shader and vbo */ - setShader(polyShader, mvp, true); + setShader(polyShader, mvp, true); - if (color == 0) { - gl.colorMask(false, false, false, false); - } else { - GLUtils.setColor(polyShader.uColor, color, alpha); - GLState.blend(true); - } + if (color == 0) { + gl.colorMask(false, false, false, false); + } else { + GLUtils.setColor(polyShader.uColor, color, alpha); + GLState.blend(true); + } - // TODO always pass stencil test: <-- only if not proxy? - //GL.stencilFunc(GL20.ALWAYS, 0x00, 0x00); + // TODO always pass stencil test: <-- only if not proxy? + //GL.stencilFunc(GL20.ALWAYS, 0x00, 0x00); - gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); + gl.stencilFunc(GL.EQUAL, CLIP_BIT, CLIP_BIT); /* write to all bits */ - gl.stencilMask(0xFF); + gl.stencilMask(0xFF); - // FIXME uneeded probably - GLState.test(false, true); + // FIXME uneeded probably + GLState.test(false, true); /* zero out area to draw to */ - gl.stencilOp(GL.KEEP, GL.KEEP, GL.ZERO); + gl.stencilOp(GL.KEEP, GL.KEEP, GL.ZERO); - gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); + gl.drawArrays(GL.TRIANGLE_STRIP, 0, 4); - if (color == 0) - gl.colorMask(true, true, true, true); - } + if (color == 0) + gl.colorMask(true, true, true, true); + } - private Renderer() { + private Renderer() { /* Singleton */ - } - } + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/RenderBucket.java b/vtm/src/org/oscim/renderer/bucket/RenderBucket.java index 98aa1d50..3f791965 100644 --- a/vtm/src/org/oscim/renderer/bucket/RenderBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/RenderBucket.java @@ -16,108 +16,116 @@ */ package org.oscim.renderer.bucket; -import java.nio.ShortBuffer; - import org.oscim.utils.pool.Inlist; +import java.nio.ShortBuffer; + public abstract class RenderBucket extends Inlist { - public static final int LINE = 0; - public static final int TEXLINE = 1; - public static final int POLYGON = 2; - public static final int MESH = 3; - public static final int EXTRUSION = 4; - public static final int HAIRLINE = 5; - public static final int SYMBOL = 6; - public static final int BITMAP = 7; - public static final int SDF = 8; + public static final int LINE = 0; + public static final int TEXLINE = 1; + public static final int POLYGON = 2; + public static final int MESH = 3; + public static final int EXTRUSION = 4; + public static final int HAIRLINE = 5; + public static final int SYMBOL = 6; + public static final int BITMAP = 7; + public static final int SDF = 8; - public final int type; + public final int type; - /** Drawing order from bottom to top. */ - int level; + /** + * Drawing order from bottom to top. + */ + int level; - /** Number of vertices for this layer. */ - protected int numVertices; - protected int numIndices; + /** + * Number of vertices for this layer. + */ + protected int numVertices; + protected int numIndices; - /** Temporary list of vertex data. */ - protected final VertexData vertexItems; - protected final VertexData indiceItems; + /** + * Temporary list of vertex data. + */ + protected final VertexData vertexItems; + protected final VertexData indiceItems; - final static VertexData EMPTY = new VertexData(); - final boolean quads; + final static VertexData EMPTY = new VertexData(); + final boolean quads; - protected RenderBucket(int type, boolean indexed, boolean quads) { - this.type = type; - vertexItems = new VertexData(); - if (indexed) - indiceItems = new VertexData(); - else - indiceItems = EMPTY; + protected RenderBucket(int type, boolean indexed, boolean quads) { + this.type = type; + vertexItems = new VertexData(); + if (indexed) + indiceItems = new VertexData(); + else + indiceItems = EMPTY; - this.quads = quads; - } + this.quads = quads; + } - /** Clear all resources. */ - protected void clear() { - vertexItems.dispose(); - indiceItems.dispose(); - numVertices = 0; - numIndices = 0; - } + /** + * Clear all resources. + */ + protected void clear() { + vertexItems.dispose(); + indiceItems.dispose(); + numVertices = 0; + numIndices = 0; + } - /** - * Final preparation of content before compilation - * for stuff that should not be done on render-thread. - */ - protected void prepare() { + /** + * Final preparation of content before compilation + * for stuff that should not be done on render-thread. + */ + protected void prepare() { - } + } - /** - * For line- and polygon-buckets this is the offset - * of VERTICES in its bucket.vbo. - * For all other types it is the byte offset in vbo. - * FIXME - always use byte offset? - */ - public int getVertexOffset() { - return vertexOffset; - } + /** + * For line- and polygon-buckets this is the offset + * of VERTICES in its bucket.vbo. + * For all other types it is the byte offset in vbo. + * FIXME - always use byte offset? + */ + public int getVertexOffset() { + return vertexOffset; + } - /** - * Start position in ibo for this bucket - */ - public int getIndiceOffset() { - return indiceOffset; - } + /** + * Start position in ibo for this bucket + */ + public int getIndiceOffset() { + return indiceOffset; + } - public void setVertexOffset(int offset) { - this.vertexOffset = offset; - } + public void setVertexOffset(int offset) { + this.vertexOffset = offset; + } - protected int vertexOffset; + protected int vertexOffset; - protected int indiceOffset; + protected int indiceOffset; - protected void compile(ShortBuffer vboData, ShortBuffer iboData) { - compileVertexItems(vboData); - if (iboData != null) - compileIndiceItems(iboData); - } + protected void compile(ShortBuffer vboData, ShortBuffer iboData) { + compileVertexItems(vboData); + if (iboData != null) + compileIndiceItems(iboData); + } - protected void compileVertexItems(ShortBuffer vboData) { - /* keep offset of layer data in vbo */ - vertexOffset = vboData.position() * 2; // FIXME 2? - should be vertex stride / num shorts - vertexItems.compile(vboData); - } + protected void compileVertexItems(ShortBuffer vboData) { + /* keep offset of layer data in vbo */ + vertexOffset = vboData.position() * 2; // FIXME 2? - should be vertex stride / num shorts + vertexItems.compile(vboData); + } - protected void compileIndiceItems(ShortBuffer iboData) { - /* keep offset of layer data in vbo */ - if (indiceItems == null || indiceItems.empty()) - return; + protected void compileIndiceItems(ShortBuffer iboData) { + /* keep offset of layer data in vbo */ + if (indiceItems == null || indiceItems.empty()) + return; - indiceOffset = iboData.position() * 2; // needs byte offset... - indiceItems.compile(iboData); - } + indiceOffset = iboData.position() * 2; // needs byte offset... + indiceItems.compile(iboData); + } } diff --git a/vtm/src/org/oscim/renderer/bucket/RenderBuckets.java b/vtm/src/org/oscim/renderer/bucket/RenderBuckets.java index 8ced1c20..1165e953 100644 --- a/vtm/src/org/oscim/renderer/bucket/RenderBuckets.java +++ b/vtm/src/org/oscim/renderer/bucket/RenderBuckets.java @@ -16,14 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.renderer.bucket.RenderBucket.HAIRLINE; -import static org.oscim.renderer.bucket.RenderBucket.LINE; -import static org.oscim.renderer.bucket.RenderBucket.MESH; -import static org.oscim.renderer.bucket.RenderBucket.POLYGON; -import static org.oscim.renderer.bucket.RenderBucket.TEXLINE; - -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.core.Tile; import org.oscim.layers.tile.MapTile.TileData; @@ -34,6 +26,14 @@ import org.oscim.theme.styles.LineStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + +import static org.oscim.renderer.bucket.RenderBucket.HAIRLINE; +import static org.oscim.renderer.bucket.RenderBucket.LINE; +import static org.oscim.renderer.bucket.RenderBucket.MESH; +import static org.oscim.renderer.bucket.RenderBucket.POLYGON; +import static org.oscim.renderer.bucket.RenderBucket.TEXLINE; + /** * This class is primarily intended for rendering the vector elements of a * MapTile. It can be used for other purposes as well but some optimizations @@ -41,385 +41,389 @@ import org.slf4j.LoggerFactory; */ public class RenderBuckets extends TileData { - static final Logger log = LoggerFactory.getLogger(RenderBuckets.class); + static final Logger log = LoggerFactory.getLogger(RenderBuckets.class); - public final static int[] VERTEX_SHORT_CNT = { - 4, // LINE_VERTEX - 6, // TEXLINE_VERTEX - 2, // POLY_VERTEX - 2, // MESH_VERTEX - 4, // EXTRUSION_VERTEX - 2, // HAIRLINE_VERTEX - 6, // SYMBOL - 6, // BITMAP - }; + public final static int[] VERTEX_SHORT_CNT = { + 4, // LINE_VERTEX + 6, // TEXLINE_VERTEX + 2, // POLY_VERTEX + 2, // MESH_VERTEX + 4, // EXTRUSION_VERTEX + 2, // HAIRLINE_VERTEX + 6, // SYMBOL + 6, // BITMAP + }; - private final static int SHORT_BYTES = 2; + private final static int SHORT_BYTES = 2; - private RenderBucket buckets; + private RenderBucket buckets; - /** - * VBO holds all vertex data to draw lines and polygons after compilation. - * Layout: - * 16 bytes fill coordinates, - * n bytes polygon vertices, - * m bytes lines vertices - * ... - */ - public BufferObject vbo; - public BufferObject ibo; + /** + * VBO holds all vertex data to draw lines and polygons after compilation. + * Layout: + * 16 bytes fill coordinates, + * n bytes polygon vertices, + * m bytes lines vertices + * ... + */ + public BufferObject vbo; + public BufferObject ibo; - /** - * To not need to switch VertexAttribPointer positions all the time: - * 1. polygons are packed in VBO at offset 0 - * 2. lines afterwards at lineOffset - * 3. other buckets keep their byte offset in offset - */ - public int[] offset = { 0, 0 }; + /** + * To not need to switch VertexAttribPointer positions all the time: + * 1. polygons are packed in VBO at offset 0 + * 2. lines afterwards at lineOffset + * 3. other buckets keep their byte offset in offset + */ + public int[] offset = {0, 0}; - private RenderBucket mCurBucket; + private RenderBucket mCurBucket; - /** - * add the LineBucket for a level with a given Line style. Levels are - * ordered from bottom (0) to top - */ - public LineBucket addLineBucket(int level, LineStyle style) { - LineBucket l = (LineBucket) getBucket(level, LINE); - if (l == null) - return null; - // FIXME l.scale = style.width; - l.scale = 1; - l.line = style; - return l; - } + /** + * add the LineBucket for a level with a given Line style. Levels are + * ordered from bottom (0) to top + */ + public LineBucket addLineBucket(int level, LineStyle style) { + LineBucket l = (LineBucket) getBucket(level, LINE); + if (l == null) + return null; + // FIXME l.scale = style.width; + l.scale = 1; + l.line = style; + return l; + } - public PolygonBucket addPolygonBucket(int level, AreaStyle style) { - PolygonBucket l = (PolygonBucket) getBucket(level, POLYGON); - if (l == null) - return null; - l.area = style; - return l; - } + public PolygonBucket addPolygonBucket(int level, AreaStyle style) { + PolygonBucket l = (PolygonBucket) getBucket(level, POLYGON); + if (l == null) + return null; + l.area = style; + return l; + } - public MeshBucket addMeshBucket(int level, AreaStyle style) { - MeshBucket l = (MeshBucket) getBucket(level, MESH); - if (l == null) - return null; - l.area = style; - return l; - } + public MeshBucket addMeshBucket(int level, AreaStyle style) { + MeshBucket l = (MeshBucket) getBucket(level, MESH); + if (l == null) + return null; + l.area = style; + return l; + } - public HairLineBucket addHairLineBucket(int level, LineStyle style) { - HairLineBucket ll = getHairLineBucket(level); - if (ll == null) - return null; - ll.line = style; + public HairLineBucket addHairLineBucket(int level, LineStyle style) { + HairLineBucket ll = getHairLineBucket(level); + if (ll == null) + return null; + ll.line = style; - return ll; - } + return ll; + } - /** - * Get or add the LineBucket for a level. Levels are ordered from - * bottom (0) to top - */ - public LineBucket getLineBucket(int level) { - return (LineBucket) getBucket(level, LINE); - } + /** + * Get or add the LineBucket for a level. Levels are ordered from + * bottom (0) to top + */ + public LineBucket getLineBucket(int level) { + return (LineBucket) getBucket(level, LINE); + } - /** - * Get or add the MeshBucket for a level. Levels are ordered from - * bottom (0) to top - */ - public MeshBucket getMeshBucket(int level) { - return (MeshBucket) getBucket(level, MESH); - } + /** + * Get or add the MeshBucket for a level. Levels are ordered from + * bottom (0) to top + */ + public MeshBucket getMeshBucket(int level) { + return (MeshBucket) getBucket(level, MESH); + } - /** - * Get or add the PolygonBucket for a level. Levels are ordered from - * bottom (0) to top - */ - public PolygonBucket getPolygonBucket(int level) { - return (PolygonBucket) getBucket(level, POLYGON); - } + /** + * Get or add the PolygonBucket for a level. Levels are ordered from + * bottom (0) to top + */ + public PolygonBucket getPolygonBucket(int level) { + return (PolygonBucket) getBucket(level, POLYGON); + } - /** - * Get or add the TexLineBucket for a level. Levels are ordered from - * bottom (0) to top - */ - public LineTexBucket getLineTexBucket(int level) { - return (LineTexBucket) getBucket(level, TEXLINE); - } + /** + * Get or add the TexLineBucket for a level. Levels are ordered from + * bottom (0) to top + */ + public LineTexBucket getLineTexBucket(int level) { + return (LineTexBucket) getBucket(level, TEXLINE); + } - /** - * Get or add the TexLineBucket for a level. Levels are ordered from - * bottom (0) to top - */ - public HairLineBucket getHairLineBucket(int level) { - return (HairLineBucket) getBucket(level, HAIRLINE); - } + /** + * Get or add the TexLineBucket for a level. Levels are ordered from + * bottom (0) to top + */ + public HairLineBucket getHairLineBucket(int level) { + return (HairLineBucket) getBucket(level, HAIRLINE); + } - /** - * Set new bucket items and clear previous. - */ - public void set(RenderBucket buckets) { - for (RenderBucket l = this.buckets; l != null; l = l.next) - l.clear(); + /** + * Set new bucket items and clear previous. + */ + public void set(RenderBucket buckets) { + for (RenderBucket l = this.buckets; l != null; l = l.next) + l.clear(); - this.buckets = buckets; - } + this.buckets = buckets; + } - /** - * @return internal linked list of RenderBucket items - */ - public RenderBucket get() { - return buckets; - } + /** + * @return internal linked list of RenderBucket items + */ + public RenderBucket get() { + return buckets; + } - private RenderBucket getBucket(int level, int type) { - RenderBucket bucket = null; + private RenderBucket getBucket(int level, int type) { + RenderBucket bucket = null; - if (mCurBucket != null && mCurBucket.level == level) { - bucket = mCurBucket; - if (bucket.type != type) { - log.error("BUG wrong bucket {} {} on level {}", - Integer.valueOf(bucket.type), - Integer.valueOf(type), - Integer.valueOf(level)); + if (mCurBucket != null && mCurBucket.level == level) { + bucket = mCurBucket; + if (bucket.type != type) { + log.error("BUG wrong bucket {} {} on level {}", + Integer.valueOf(bucket.type), + Integer.valueOf(type), + Integer.valueOf(level)); - throw new IllegalArgumentException(); - } - return bucket; - } + throw new IllegalArgumentException(); + } + return bucket; + } - RenderBucket b = buckets; - if (b == null || b.level > level) { - /* insert new bucket at start */ - b = null; - } else { - if (mCurBucket != null && level > mCurBucket.level) - b = mCurBucket; + RenderBucket b = buckets; + if (b == null || b.level > level) { + /* insert new bucket at start */ + b = null; + } else { + if (mCurBucket != null && level > mCurBucket.level) + b = mCurBucket; - while (true) { - /* found bucket */ - if (b.level == level) { - bucket = b; - break; - } + while (true) { + /* found bucket */ + if (b.level == level) { + bucket = b; + break; + } /* insert bucket between current and next bucket */ - if (b.next == null || b.next.level > level) - break; + if (b.next == null || b.next.level > level) + break; - b = b.next; - } - } + b = b.next; + } + } - if (bucket == null) { + if (bucket == null) { /* add a new RenderElement */ - if (type == LINE) - bucket = new LineBucket(level); - else if (type == POLYGON) - bucket = new PolygonBucket(level); - else if (type == TEXLINE) - bucket = new LineTexBucket(level); - else if (type == MESH) - bucket = new MeshBucket(level); - else if (type == HAIRLINE) - bucket = new HairLineBucket(level); + if (type == LINE) + bucket = new LineBucket(level); + else if (type == POLYGON) + bucket = new PolygonBucket(level); + else if (type == TEXLINE) + bucket = new LineTexBucket(level); + else if (type == MESH) + bucket = new MeshBucket(level); + else if (type == HAIRLINE) + bucket = new HairLineBucket(level); - if (bucket == null) - throw new IllegalArgumentException(); + if (bucket == null) + throw new IllegalArgumentException(); - if (b == null) { - /** insert at start */ - bucket.next = buckets; - buckets = bucket; - } else { - bucket.next = b.next; - b.next = bucket; - } - } + if (b == null) { + /** insert at start */ + bucket.next = buckets; + buckets = bucket; + } else { + bucket.next = b.next; + b.next = bucket; + } + } /* check if found buckets matches requested type */ - if (bucket.type != type) { - log.error("BUG wrong bucket {} {} on level {}", - Integer.valueOf(bucket.type), - Integer.valueOf(type), - Integer.valueOf(level)); + if (bucket.type != type) { + log.error("BUG wrong bucket {} {} on level {}", + Integer.valueOf(bucket.type), + Integer.valueOf(type), + Integer.valueOf(level)); - throw new IllegalArgumentException(); - } + throw new IllegalArgumentException(); + } - mCurBucket = bucket; + mCurBucket = bucket; - return bucket; - } + return bucket; + } - private int countVboSize() { - int vboShorts = 0; + private int countVboSize() { + int vboShorts = 0; - for (RenderBucket l = buckets; l != null; l = l.next) - vboShorts += l.numVertices * VERTEX_SHORT_CNT[l.type]; + for (RenderBucket l = buckets; l != null; l = l.next) + vboShorts += l.numVertices * VERTEX_SHORT_CNT[l.type]; - return vboShorts; - } + return vboShorts; + } - private int countIboSize() { - int numIndices = 0; + private int countIboSize() { + int numIndices = 0; - for (RenderBucket l = buckets; l != null; l = l.next) - numIndices += l.numIndices; + for (RenderBucket l = buckets; l != null; l = l.next) + numIndices += l.numIndices; - return numIndices; - } + return numIndices; + } - public void setFrom(RenderBuckets buckets) { - if (buckets == this) - throw new IllegalArgumentException("Cannot set from oneself!"); + public void setFrom(RenderBuckets buckets) { + if (buckets == this) + throw new IllegalArgumentException("Cannot set from oneself!"); - set(buckets.buckets); + set(buckets.buckets); - mCurBucket = null; - buckets.buckets = null; - buckets.mCurBucket = null; - } + mCurBucket = null; + buckets.buckets = null; + buckets.mCurBucket = null; + } - /** cleanup only when buckets are not used by tile or bucket anymore! */ - public void clear() { + /** + * cleanup only when buckets are not used by tile or bucket anymore! + */ + public void clear() { /* NB: set null calls clear() on each bucket! */ - set(null); - mCurBucket = null; + set(null); + mCurBucket = null; - vbo = BufferObject.release(vbo); - ibo = BufferObject.release(ibo); - } + vbo = BufferObject.release(vbo); + ibo = BufferObject.release(ibo); + } - /** cleanup only when buckets are not used by tile or bucket anymore! */ - public void clearBuckets() { + /** + * cleanup only when buckets are not used by tile or bucket anymore! + */ + public void clearBuckets() { /* NB: set null calls clear() on each bucket! */ - for (RenderBucket l = buckets; l != null; l = l.next) - l.clear(); + for (RenderBucket l = buckets; l != null; l = l.next) + l.clear(); - mCurBucket = null; - } + mCurBucket = null; + } - @Override - protected void dispose() { - clear(); - } + @Override + protected void dispose() { + clear(); + } - public void prepare() { - for (RenderBucket l = buckets; l != null; l = l.next) - l.prepare(); - } + public void prepare() { + for (RenderBucket l = buckets; l != null; l = l.next) + l.prepare(); + } - public void bind() { - if (vbo != null) - vbo.bind(); + public void bind() { + if (vbo != null) + vbo.bind(); - if (ibo != null) - ibo.bind(); + if (ibo != null) + ibo.bind(); - } + } - public boolean compile(boolean addFill) { + public boolean compile(boolean addFill) { - int vboSize = countVboSize(); + int vboSize = countVboSize(); - if (vboSize <= 0) { - vbo = BufferObject.release(vbo); - ibo = BufferObject.release(ibo); - return false; - } + if (vboSize <= 0) { + vbo = BufferObject.release(vbo); + ibo = BufferObject.release(ibo); + return false; + } - if (addFill) - vboSize += 8; + if (addFill) + vboSize += 8; - ShortBuffer vboData = MapRenderer.getShortBuffer(vboSize); + ShortBuffer vboData = MapRenderer.getShortBuffer(vboSize); - if (addFill) - vboData.put(fillCoords, 0, 8); + if (addFill) + vboData.put(fillCoords, 0, 8); - ShortBuffer iboData = null; + ShortBuffer iboData = null; - int iboSize = countIboSize(); - if (iboSize > 0) { - iboData = MapRenderer.getShortBuffer(iboSize); - } + int iboSize = countIboSize(); + if (iboSize > 0) { + iboData = MapRenderer.getShortBuffer(iboSize); + } - int pos = addFill ? 4 : 0; + int pos = addFill ? 4 : 0; - for (RenderBucket l = buckets; l != null; l = l.next) { - if (l.type == POLYGON) { - l.compile(vboData, iboData); - l.vertexOffset = pos; - pos += l.numVertices; - } - } + for (RenderBucket l = buckets; l != null; l = l.next) { + if (l.type == POLYGON) { + l.compile(vboData, iboData); + l.vertexOffset = pos; + pos += l.numVertices; + } + } - offset[LINE] = vboData.position() * SHORT_BYTES; - pos = 0; - for (RenderBucket l = buckets; l != null; l = l.next) { - if (l.type == LINE) { - l.compile(vboData, iboData); + offset[LINE] = vboData.position() * SHORT_BYTES; + pos = 0; + for (RenderBucket l = buckets; l != null; l = l.next) { + if (l.type == LINE) { + l.compile(vboData, iboData); - l.vertexOffset = pos; - pos += l.numVertices; - } - } + l.vertexOffset = pos; + pos += l.numVertices; + } + } - for (RenderBucket l = buckets; l != null; l = l.next) { - if (l.type != LINE && l.type != POLYGON) { - l.compile(vboData, iboData); - } - } + for (RenderBucket l = buckets; l != null; l = l.next) { + if (l.type != LINE && l.type != POLYGON) { + l.compile(vboData, iboData); + } + } - if (vboSize != vboData.position()) { - log.debug("wrong vertex buffer size: " - + " new size: " + vboSize - + " buffer pos: " + vboData.position() - + " buffer limit: " + vboData.limit() - + " buffer fill: " + vboData.remaining()); - return false; - } + if (vboSize != vboData.position()) { + log.debug("wrong vertex buffer size: " + + " new size: " + vboSize + + " buffer pos: " + vboData.position() + + " buffer limit: " + vboData.limit() + + " buffer fill: " + vboData.remaining()); + return false; + } - if (iboSize > 0 && iboSize != iboData.position()) { - log.debug("wrong indice buffer size: " - + " new size: " + iboSize - + " buffer pos: " + iboData.position() - + " buffer limit: " + iboData.limit() - + " buffer fill: " + iboData.remaining()); - return false; - } + if (iboSize > 0 && iboSize != iboData.position()) { + log.debug("wrong indice buffer size: " + + " new size: " + iboSize + + " buffer pos: " + iboData.position() + + " buffer limit: " + iboData.limit() + + " buffer fill: " + iboData.remaining()); + return false; + } - if (vbo == null) - vbo = BufferObject.get(GL.ARRAY_BUFFER, vboSize); + if (vbo == null) + vbo = BufferObject.get(GL.ARRAY_BUFFER, vboSize); - vbo.loadBufferData(vboData.flip(), vboSize * 2); + vbo.loadBufferData(vboData.flip(), vboSize * 2); - if (iboSize > 0) { - if (ibo == null) - ibo = BufferObject.get(GL.ELEMENT_ARRAY_BUFFER, iboSize); + if (iboSize > 0) { + if (ibo == null) + ibo = BufferObject.get(GL.ELEMENT_ARRAY_BUFFER, iboSize); - ibo.loadBufferData(iboData.flip(), iboSize * 2); - } + ibo.loadBufferData(iboData.flip(), iboSize * 2); + } - return true; - } + return true; + } - private static short[] fillCoords; + private static short[] fillCoords; - static { - short s = (short) (Tile.SIZE * MapRenderer.COORD_SCALE); - fillCoords = new short[] { 0, s, s, s, 0, 0, s, 0 }; - } + static { + short s = (short) (Tile.SIZE * MapRenderer.COORD_SCALE); + fillCoords = new short[]{0, s, s, s, 0, 0, s, 0}; + } - public static void initRenderer() { - LineBucket.Renderer.init(); - LineTexBucket.Renderer.init(); - PolygonBucket.Renderer.init(); - TextureBucket.Renderer.init(); - BitmapBucket.Renderer.init(); - MeshBucket.Renderer.init(); - HairLineBucket.Renderer.init(); - } + public static void initRenderer() { + LineBucket.Renderer.init(); + LineTexBucket.Renderer.init(); + PolygonBucket.Renderer.init(); + TextureBucket.Renderer.init(); + BitmapBucket.Renderer.init(); + MeshBucket.Renderer.init(); + HairLineBucket.Renderer.init(); + } } diff --git a/vtm/src/org/oscim/renderer/bucket/SymbolBucket.java b/vtm/src/org/oscim/renderer/bucket/SymbolBucket.java index 870eaae8..61c849c5 100644 --- a/vtm/src/org/oscim/renderer/bucket/SymbolBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/SymbolBucket.java @@ -16,8 +16,6 @@ */ package org.oscim.renderer.bucket; -import java.nio.ShortBuffer; - import org.oscim.backend.canvas.Bitmap; import org.oscim.core.PointF; import org.oscim.renderer.atlas.TextureAtlas; @@ -25,175 +23,177 @@ import org.oscim.utils.pool.Inlist; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + public final class SymbolBucket extends TextureBucket { - static final Logger log = LoggerFactory.getLogger(SymbolBucket.class); + static final Logger log = LoggerFactory.getLogger(SymbolBucket.class); - private final static float SCALE = 8.0f; - private final static int VERTICES_PER_SPRITE = 4; - private final static int LBIT_MASK = 0xfffffffe; + private final static float SCALE = 8.0f; + private final static int VERTICES_PER_SPRITE = 4; + private final static int LBIT_MASK = 0xfffffffe; - private TextureItem prevTextures; - private List mSymbols = new List(); + private TextureItem prevTextures; + private List mSymbols = new List(); - public SymbolBucket() { - super(RenderBucket.SYMBOL); - fixed = true; - } + public SymbolBucket() { + super(RenderBucket.SYMBOL); + fixed = true; + } - /* TODO move sorting items to 'prepare' */ - public void addSymbol(SymbolItem item) { + /* TODO move sorting items to 'prepare' */ + public void addSymbol(SymbolItem item) { /* needed to calculate 'sbuf' size for compile */ - numVertices += VERTICES_PER_SPRITE; + numVertices += VERTICES_PER_SPRITE; - for (SymbolItem it : mSymbols) { - if (it.bitmap == item.bitmap) { - /* insert after same bitmap */ - item.next = it.next; - it.next = item; - return; - } - } - mSymbols.push(item); - } + for (SymbolItem it : mSymbols) { + if (it.bitmap == item.bitmap) { + /* insert after same bitmap */ + item.next = it.next; + it.next = item; + return; + } + } + mSymbols.push(item); + } - public void pushSymbol(SymbolItem item) { - /* needed to calculate 'sbuf' size for compile */ - numVertices += VERTICES_PER_SPRITE; - mSymbols.push(item); - } + public void pushSymbol(SymbolItem item) { + /* needed to calculate 'sbuf' size for compile */ + numVertices += VERTICES_PER_SPRITE; + mSymbols.push(item); + } - @Override - protected void compile(ShortBuffer vboData, ShortBuffer iboData) { + @Override + protected void compile(ShortBuffer vboData, ShortBuffer iboData) { /* offset of layer data in vbo */ - this.vertexOffset = vboData.position() * 2; //SHORT_BYTES; + this.vertexOffset = vboData.position() * 2; //SHORT_BYTES; - int numIndices = 0; + int numIndices = 0; - prevTextures = textures; - textures = null; - TextureItem t = null; + prevTextures = textures; + textures = null; + TextureItem t = null; - for (SymbolItem it = mSymbols.head(); it != null;) { - int width = 0, height = 0; - int x = 0; - int y = 0; + for (SymbolItem it = mSymbols.head(); it != null; ) { + int width = 0, height = 0; + int x = 0; + int y = 0; - if (it.texRegion != null) { + if (it.texRegion != null) { /* FIXME this work only with one TextureAtlas per SymbolLayer */ - if (textures == null) { + if (textures == null) { /* clone TextureItem to use same texID with * multiple TextureItem */ - t = TextureItem.clone(it.texRegion.texture); - textures = Inlist.appendItem(textures, t); - } + t = TextureItem.clone(it.texRegion.texture); + textures = Inlist.appendItem(textures, t); + } - TextureAtlas.Rect r = it.texRegion.rect; - x = r.x; - y = r.y; - width = r.w; - height = r.h; + TextureAtlas.Rect r = it.texRegion.rect; + x = r.x; + y = r.y; + width = r.w; + height = r.h; - } else if (it.bitmap != null) { - t = getTexture(it.bitmap); + } else if (it.bitmap != null) { + t = getTexture(it.bitmap); - if (t == null) { - t = new TextureItem(it.bitmap); - textures = Inlist.appendItem(textures, t); - t.offset = numIndices; - t.indices = 0; - } - width = t.width; - height = t.height; + if (t == null) { + t = new TextureItem(it.bitmap); + textures = Inlist.appendItem(textures, t); + t.offset = numIndices; + t.indices = 0; + } + width = t.width; + height = t.height; - } else { //if (to == null) { - log.debug("Bad SymbolItem"); - continue; - } + } else { //if (to == null) { + log.debug("Bad SymbolItem"); + continue; + } - short u1 = (short) (SCALE * x); - short v1 = (short) (SCALE * y); - short u2 = (short) (SCALE * (x + width)); - short v2 = (short) (SCALE * (y + height)); + short u1 = (short) (SCALE * x); + short v1 = (short) (SCALE * y); + short u2 = (short) (SCALE * (x + width)); + short v2 = (short) (SCALE * (y + height)); - PointF prevOffset = null; - short x1 = 0, y1 = 0, x2 = 0, y2 = 0; + PointF prevOffset = null; + short x1 = 0, y1 = 0, x2 = 0, y2 = 0; /* add symbol items referencing the same bitmap */ - for (SymbolItem prev = it; it != null; it = it.next) { + for (SymbolItem prev = it; it != null; it = it.next) { - if (prev.bitmap != null && prev.bitmap != it.bitmap) - break; + if (prev.bitmap != null && prev.bitmap != it.bitmap) + break; - if (prev.texRegion != null && prev.texRegion != it.texRegion) - break; + if (prev.texRegion != null && prev.texRegion != it.texRegion) + break; - if (it == prev || it.offset != prevOffset) { - prevOffset = it.offset; - if (it.offset == null) { - float hw = width / 2f; - float hh = height / 2f; + if (it == prev || it.offset != prevOffset) { + prevOffset = it.offset; + if (it.offset == null) { + float hw = width / 2f; + float hh = height / 2f; - x1 = (short) (SCALE * (-hw)); - x2 = (short) (SCALE * (hw)); - y1 = (short) (SCALE * (hh)); - y2 = (short) (SCALE * (-hh)); - } else { - float hw = (float) (it.offset.x * width); - float hh = (float) (it.offset.y * height); - x1 = (short) (SCALE * (-hw)); - x2 = (short) (SCALE * (width - hw)); - y1 = (short) (SCALE * (height - hh)); - y2 = (short) (SCALE * (-hh)); - } - } + x1 = (short) (SCALE * (-hw)); + x2 = (short) (SCALE * (hw)); + y1 = (short) (SCALE * (hh)); + y2 = (short) (SCALE * (-hh)); + } else { + float hw = (float) (it.offset.x * width); + float hh = (float) (it.offset.y * height); + x1 = (short) (SCALE * (-hw)); + x2 = (short) (SCALE * (width - hw)); + y1 = (short) (SCALE * (height - hh)); + y2 = (short) (SCALE * (-hh)); + } + } /* add vertices */ - short tx = (short) ((int) (SCALE * it.x) & LBIT_MASK - | (it.billboard ? 1 : 0)); + short tx = (short) ((int) (SCALE * it.x) & LBIT_MASK + | (it.billboard ? 1 : 0)); - short ty = (short) (SCALE * it.y); + short ty = (short) (SCALE * it.y); - vertexItems.add(tx, ty, x1, y1, u1, v2); - vertexItems.add(tx, ty, x1, y2, u1, v1); - vertexItems.add(tx, ty, x2, y1, u2, v2); - vertexItems.add(tx, ty, x2, y2, u2, v1); + vertexItems.add(tx, ty, x1, y1, u1, v2); + vertexItems.add(tx, ty, x1, y2, u1, v1); + vertexItems.add(tx, ty, x2, y1, u2, v2); + vertexItems.add(tx, ty, x2, y2, u2, v1); /* six elements used to draw the four vertices */ - t.indices += TextureBucket.INDICES_PER_SPRITE; - } - numIndices += t.indices; - } + t.indices += TextureBucket.INDICES_PER_SPRITE; + } + numIndices += t.indices; + } - vertexItems.compile(vboData); + vertexItems.compile(vboData); - for (t = prevTextures; t != null; t = t.dispose()); - prevTextures = null; - } + for (t = prevTextures; t != null; t = t.dispose()) ; + prevTextures = null; + } - private TextureItem getTexture(Bitmap bitmap) { - TextureItem t; + private TextureItem getTexture(Bitmap bitmap) { + TextureItem t; - for (t = prevTextures; t != null; t = t.next) { - if (t.bitmap == bitmap) { - prevTextures = Inlist.remove(prevTextures, t); - textures = Inlist.appendItem(textures, t); + for (t = prevTextures; t != null; t = t.next) { + if (t.bitmap == bitmap) { + prevTextures = Inlist.remove(prevTextures, t); + textures = Inlist.appendItem(textures, t); - t.offset = 0; - t.indices = 0; - return t; - } - } - return null; - } + t.offset = 0; + t.indices = 0; + return t; + } + } + return null; + } - public void clearItems() { - SymbolItem.pool.releaseAll(mSymbols.clear()); - } + public void clearItems() { + SymbolItem.pool.releaseAll(mSymbols.clear()); + } - @Override - public void clear() { - super.clear(); - clearItems(); - } + @Override + public void clear() { + super.clear(); + clearItems(); + } } diff --git a/vtm/src/org/oscim/renderer/bucket/SymbolItem.java b/vtm/src/org/oscim/renderer/bucket/SymbolItem.java index 42ae1508..f99d173e 100644 --- a/vtm/src/org/oscim/renderer/bucket/SymbolItem.java +++ b/vtm/src/org/oscim/renderer/bucket/SymbolItem.java @@ -24,43 +24,43 @@ import org.oscim.utils.pool.SyncPool; public class SymbolItem extends Inlist { - public final static SyncPool pool = new SyncPool(128) { + public final static SyncPool pool = new SyncPool(128) { - @Override - protected SymbolItem createItem() { - return new SymbolItem(); - } + @Override + protected SymbolItem createItem() { + return new SymbolItem(); + } - @Override - protected boolean clearItem(SymbolItem it) { - // drop references - it.bitmap = null; - it.texRegion = null; - it.offset = null; - return true; - } - }; + @Override + protected boolean clearItem(SymbolItem it) { + // drop references + it.bitmap = null; + it.texRegion = null; + it.offset = null; + return true; + } + }; - public boolean billboard; - public float x; - public float y; + public boolean billboard; + public float x; + public float y; - public TextureRegion texRegion; - public Bitmap bitmap; - public PointF offset; + public TextureRegion texRegion; + public Bitmap bitmap; + public PointF offset; - public void set(float x, float y, TextureRegion texture, boolean billboard) { - this.x = x; - this.y = y; - this.texRegion = texture; - this.billboard = billboard; - } + public void set(float x, float y, TextureRegion texture, boolean billboard) { + this.x = x; + this.y = y; + this.texRegion = texture; + this.billboard = billboard; + } - public void set(float x, float y, Bitmap bitmap, boolean billboard) { - this.x = x; - this.y = y; - this.bitmap = bitmap; - this.billboard = billboard; - } + public void set(float x, float y, Bitmap bitmap, boolean billboard) { + this.x = x; + this.y = y; + this.bitmap = bitmap; + this.billboard = billboard; + } } diff --git a/vtm/src/org/oscim/renderer/bucket/TextBucket.java b/vtm/src/org/oscim/renderer/bucket/TextBucket.java index f2b5048c..b7dd718a 100644 --- a/vtm/src/org/oscim/renderer/bucket/TextBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/TextBucket.java @@ -16,212 +16,212 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.renderer.MapRenderer.COORD_SCALE; - import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Canvas; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.renderer.MapRenderer.COORD_SCALE; + public class TextBucket extends TextureBucket { - static final Logger log = LoggerFactory.getLogger(TextBucket.class); + static final Logger log = LoggerFactory.getLogger(TextBucket.class); - protected final static int LBIT_MASK = 0xfffffffe; + protected final static int LBIT_MASK = 0xfffffffe; - protected static int mFontPadX = 1; - //private static int mFontPadY = 1; + protected static int mFontPadX = 1; + //private static int mFontPadY = 1; - public TextItem labels; - protected final Canvas mCanvas; + public TextItem labels; + protected final Canvas mCanvas; - public TextItem getLabels() { - return labels; - } + public TextItem getLabels() { + return labels; + } - public void setLabels(TextItem labels) { - this.labels = labels; - } + public void setLabels(TextItem labels) { + this.labels = labels; + } - public TextBucket() { - super(RenderBucket.SYMBOL); - mCanvas = CanvasAdapter.newCanvas(); - fixed = true; - level = -1; - } + public TextBucket() { + super(RenderBucket.SYMBOL); + mCanvas = CanvasAdapter.newCanvas(); + fixed = true; + level = -1; + } - public void addText(TextItem item) { - TextItem it = labels; + public void addText(TextItem item) { + TextItem it = labels; - for (; it != null; it = it.next) { + for (; it != null; it = it.next) { - if (item.text == it.text) { - while (it.next != null - /* break if next item uses different text style */ - && item.text == it.next.text - /* check same string instance */ - && item.string != it.string + if (item.text == it.text) { + while (it.next != null + /* break if next item uses different text style */ + && item.text == it.next.text + /* check same string instance */ + && item.string != it.string /* check same string */ - && !item.string.equals(it.string)) - it = it.next; + && !item.string.equals(it.string)) + it = it.next; /* unify duplicate string * // Note: this is required for 'packing test' in prepare to * work! */ - if (item.string != it.string && item.string.equals(it.string)) - item.string = it.string; + if (item.string != it.string && item.string.equals(it.string)) + item.string = it.string; /* insert after text of same type and/or before same string */ - item.next = it.next; - it.next = item; - return; - } - } + item.next = it.next; + it.next = item; + return; + } + } - item.next = labels; - labels = item; - } + item.next = labels; + labels = item; + } - @Override - public void prepare() { - int numIndices = 0; - int offsetIndices = 0; + @Override + public void prepare() { + int numIndices = 0; + int offsetIndices = 0; - int advanceY = 0; - float x = 0; - float y = 0; - float yy; + int advanceY = 0; + float x = 0; + float y = 0; + float yy; - TextureItem t = pool.get(); - textures = t; - mCanvas.setBitmap(t.bitmap); + TextureItem t = pool.get(); + textures = t; + mCanvas.setBitmap(t.bitmap); - for (TextItem it = labels; it != null;) { + for (TextItem it = labels; it != null; ) { - float width = it.width + 2 * mFontPadX; - float height = (int) (it.text.fontHeight) + 0.5f; + float width = it.width + 2 * mFontPadX; + float height = (int) (it.text.fontHeight) + 0.5f; - if (height > TEXTURE_HEIGHT) - height = TEXTURE_HEIGHT; + if (height > TEXTURE_HEIGHT) + height = TEXTURE_HEIGHT; - if (height > advanceY) - advanceY = (int) height; + if (height > advanceY) + advanceY = (int) height; - if (x + width > TEXTURE_WIDTH) { - x = 0; - y += advanceY; - advanceY = (int) (height + 0.5f); + if (x + width > TEXTURE_WIDTH) { + x = 0; + y += advanceY; + advanceY = (int) (height + 0.5f); - if (y + height > TEXTURE_HEIGHT) { - t.offset = offsetIndices; - t.indices = (numIndices - offsetIndices); - offsetIndices = numIndices; + if (y + height > TEXTURE_HEIGHT) { + t.offset = offsetIndices; + t.indices = (numIndices - offsetIndices); + offsetIndices = numIndices; - t.next = pool.get(); - t = t.next; + t.next = pool.get(); + t = t.next; - mCanvas.setBitmap(t.bitmap); + mCanvas.setBitmap(t.bitmap); - x = 0; - y = 0; - advanceY = (int) height; - } - } + x = 0; + y = 0; + advanceY = (int) height; + } + } - yy = y + height - it.text.fontDescent; + yy = y + height - it.text.fontDescent; - mCanvas.drawText(it.string, x, yy, it.text.paint, it.text.stroke); + mCanvas.drawText(it.string, x, yy, it.text.paint, it.text.stroke); - // FIXME !!! - if (width > TEXTURE_WIDTH) - width = TEXTURE_WIDTH; + // FIXME !!! + if (width > TEXTURE_WIDTH) + width = TEXTURE_WIDTH; - while (it != null) { - addItem(it, width, height, x, y); + while (it != null) { + addItem(it, width, height, x, y); /* six indices to draw the four vertices */ - numIndices += TextureBucket.INDICES_PER_SPRITE; - numVertices += 4; + numIndices += TextureBucket.INDICES_PER_SPRITE; + numVertices += 4; - if (it.next == null - || (it.next.text != it.text) - || (it.next.string != it.string)) { - it = it.next; - break; - } - it = it.next; + if (it.next == null + || (it.next.text != it.text) + || (it.next.string != it.string)) { + it = it.next; + break; + } + it = it.next; - } - x += width; - } + } + x += width; + } - t.offset = offsetIndices; - t.indices = (numIndices - offsetIndices); - } + t.offset = offsetIndices; + t.indices = (numIndices - offsetIndices); + } - protected void addItem(TextItem it, - float width, float height, float x, float y) { + protected void addItem(TextItem it, + float width, float height, float x, float y) { /* texture coordinates */ - short u1 = (short) (COORD_SCALE * x); - short v1 = (short) (COORD_SCALE * y); - short u2 = (short) (COORD_SCALE * (x + width)); - short v2 = (short) (COORD_SCALE * (y + height)); + short u1 = (short) (COORD_SCALE * x); + short v1 = (short) (COORD_SCALE * y); + short u2 = (short) (COORD_SCALE * (x + width)); + short v2 = (short) (COORD_SCALE * (y + height)); - short x1, x2, x3, x4, y1, y3, y2, y4; - float hw = width / 2.0f; - float hh = height / 2.0f; - if (it.text.caption) { - x1 = x3 = (short) (COORD_SCALE * -hw); - x2 = x4 = (short) (COORD_SCALE * hw); - y1 = y2 = (short) (COORD_SCALE * (it.text.dy + hh)); - y3 = y4 = (short) (COORD_SCALE * (it.text.dy - hh)); - } else { - float vx = it.x1 - it.x2; - float vy = it.y1 - it.y2; - float a = (float) Math.sqrt(vx * vx + vy * vy); - vx = vx / a; - vy = vy / a; + short x1, x2, x3, x4, y1, y3, y2, y4; + float hw = width / 2.0f; + float hh = height / 2.0f; + if (it.text.caption) { + x1 = x3 = (short) (COORD_SCALE * -hw); + x2 = x4 = (short) (COORD_SCALE * hw); + y1 = y2 = (short) (COORD_SCALE * (it.text.dy + hh)); + y3 = y4 = (short) (COORD_SCALE * (it.text.dy - hh)); + } else { + float vx = it.x1 - it.x2; + float vy = it.y1 - it.y2; + float a = (float) Math.sqrt(vx * vx + vy * vy); + vx = vx / a; + vy = vy / a; - float ux = -vy * hh; - float uy = vx * hh; + float ux = -vy * hh; + float uy = vx * hh; - float ux2 = -vy * hh; - float uy2 = vx * hh; + float ux2 = -vy * hh; + float uy2 = vx * hh; - vx *= hw; - vy *= hw; + vx *= hw; + vy *= hw; /* top-left */ - x1 = (short) (COORD_SCALE * (vx - ux)); - y1 = (short) (COORD_SCALE * (vy - uy)); + x1 = (short) (COORD_SCALE * (vx - ux)); + y1 = (short) (COORD_SCALE * (vy - uy)); /* top-right */ - x2 = (short) (COORD_SCALE * (-vx - ux)); - y2 = (short) (COORD_SCALE * (-vy - uy)); + x2 = (short) (COORD_SCALE * (-vx - ux)); + y2 = (short) (COORD_SCALE * (-vy - uy)); /* bot-right */ - x4 = (short) (COORD_SCALE * (-vx + ux2)); - y4 = (short) (COORD_SCALE * (-vy + uy2)); + x4 = (short) (COORD_SCALE * (-vx + ux2)); + y4 = (short) (COORD_SCALE * (-vy + uy2)); /* bot-left */ - x3 = (short) (COORD_SCALE * (vx + ux2)); - y3 = (short) (COORD_SCALE * (vy + uy2)); - } + x3 = (short) (COORD_SCALE * (vx + ux2)); + y3 = (short) (COORD_SCALE * (vy + uy2)); + } /* add vertices */ - int tmp = (int) (COORD_SCALE * it.x) & LBIT_MASK; - short tx = (short) (tmp | (it.text.caption ? 1 : 0)); - short ty = (short) (COORD_SCALE * it.y); + int tmp = (int) (COORD_SCALE * it.x) & LBIT_MASK; + short tx = (short) (tmp | (it.text.caption ? 1 : 0)); + short ty = (short) (COORD_SCALE * it.y); - vertexItems.add(tx, ty, x1, y1, u1, v2); - vertexItems.add(tx, ty, x3, y3, u1, v1); - vertexItems.add(tx, ty, x2, y2, u2, v2); - vertexItems.add(tx, ty, x4, y4, u2, v1); - } + vertexItems.add(tx, ty, x1, y1, u1, v2); + vertexItems.add(tx, ty, x3, y3, u1, v1); + vertexItems.add(tx, ty, x2, y2, u2, v2); + vertexItems.add(tx, ty, x4, y4, u2, v1); + } - @Override - public void clear() { - super.clear(); - clearLabels(); - } + @Override + public void clear() { + super.clear(); + clearLabels(); + } - public void clearLabels() { - labels = TextItem.pool.releaseAll(labels); - } + public void clearLabels() { + labels = TextItem.pool.releaseAll(labels); + } } diff --git a/vtm/src/org/oscim/renderer/bucket/TextItem.java b/vtm/src/org/oscim/renderer/bucket/TextItem.java index 30da7e21..717d746f 100644 --- a/vtm/src/org/oscim/renderer/bucket/TextItem.java +++ b/vtm/src/org/oscim/renderer/bucket/TextItem.java @@ -21,81 +21,81 @@ import org.oscim.utils.pool.Inlist; import org.oscim.utils.pool.SyncPool; public class TextItem extends Inlist { - //static final Logger log = LoggerFactory.getLogger(TextItem.class); - private final static int MAX_POOL = 250; + //static final Logger log = LoggerFactory.getLogger(TextItem.class); + private final static int MAX_POOL = 250; - public final static SyncPool pool = new SyncPool(MAX_POOL) { + public final static SyncPool pool = new SyncPool(MAX_POOL) { - @Override - protected TextItem createItem() { - return new TextItem(); - } + @Override + protected TextItem createItem() { + return new TextItem(); + } - @Override - protected boolean clearItem(TextItem ti) { - // drop references - ti.string = null; - ti.text = null; - //ti.n1 = null; - //ti.n2 = null; - return true; - } - }; + @Override + protected boolean clearItem(TextItem ti) { + // drop references + ti.string = null; + ti.text = null; + //ti.n1 = null; + //ti.n2 = null; + return true; + } + }; - public static TextItem copy(TextItem orig) { + public static TextItem copy(TextItem orig) { - TextItem ti = pool.get(); + TextItem ti = pool.get(); - ti.x = orig.x; - ti.y = orig.y; + ti.x = orig.x; + ti.y = orig.y; - ti.x1 = orig.x1; - ti.y1 = orig.y1; - ti.x2 = orig.x2; - ti.y2 = orig.y2; + ti.x1 = orig.x1; + ti.y1 = orig.y1; + ti.x2 = orig.x2; + ti.y2 = orig.y2; - return ti; - } + return ti; + } - public TextItem set(float x, float y, String string, TextStyle text) { - this.x = x; - this.y = y; - this.string = string; - this.text = text; - this.x1 = 0; - this.y1 = 0; - this.x2 = 1; - this.y2 = 0; - this.width = text.paint.measureText(string); - return this; - } + public TextItem set(float x, float y, String string, TextStyle text) { + this.x = x; + this.y = y; + this.string = string; + this.text = text; + this.x1 = 0; + this.y1 = 0; + this.x2 = 1; + this.y2 = 0; + this.width = text.paint.measureText(string); + return this; + } - // center - public float x, y; + // center + public float x, y; - // label text - public String string; + // label text + public String string; - // text style - public TextStyle text; + // text style + public TextStyle text; - // label width - public float width; + // label width + public float width; - // left and right corner of segment - public float x1, y1, x2, y2; + // left and right corner of segment + public float x1, y1, x2, y2; - // segment length - public short length; + // segment length + public short length; - // link to next/prev label of the way - //public TextItem n1; - //public TextItem n2; + // link to next/prev label of the way + //public TextItem n1; + //public TextItem n2; - public byte edges; + public byte edges; - @Override - public String toString() { - return x + " " + y + " " + string; - } + @Override + public String toString() { + return x + " " + y + " " + string; + } } diff --git a/vtm/src/org/oscim/renderer/bucket/TextureBucket.java b/vtm/src/org/oscim/renderer/bucket/TextureBucket.java index 5b4330da..fd5eab78 100644 --- a/vtm/src/org/oscim/renderer/bucket/TextureBucket.java +++ b/vtm/src/org/oscim/renderer/bucket/TextureBucket.java @@ -16,12 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; -import static org.oscim.renderer.MapRenderer.COORD_SCALE; -import static org.oscim.renderer.MapRenderer.MAX_INDICES; - -import java.nio.ShortBuffer; - import org.oscim.backend.GL; import org.oscim.renderer.GLShader; import org.oscim.renderer.GLState; @@ -31,136 +25,148 @@ import org.oscim.renderer.bucket.TextureItem.TexturePool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + +import static org.oscim.backend.GLAdapter.gl; +import static org.oscim.renderer.MapRenderer.COORD_SCALE; +import static org.oscim.renderer.MapRenderer.MAX_INDICES; + public class TextureBucket extends RenderBucket { - static final Logger log = LoggerFactory.getLogger(TextureBucket.class); + static final Logger log = LoggerFactory.getLogger(TextureBucket.class); - public final static int INDICES_PER_SPRITE = 6; - final static int VERTICES_PER_SPRITE = 4; - final static int SHORTS_PER_VERTICE = 6; + public final static int INDICES_PER_SPRITE = 6; + final static int VERTICES_PER_SPRITE = 4; + final static int SHORTS_PER_VERTICE = 6; - public final static int TEXTURE_HEIGHT = 256; - public final static int TEXTURE_WIDTH = 1024; - final static int POOL_FILL = 4; + public final static int TEXTURE_HEIGHT = 256; + public final static int TEXTURE_WIDTH = 1024; + final static int POOL_FILL = 4; - /** pool shared by TextLayers */ - public final static TexturePool pool = new TexturePool(POOL_FILL, - TEXTURE_WIDTH, - TEXTURE_HEIGHT); + /** + * pool shared by TextLayers + */ + public final static TexturePool pool = new TexturePool(POOL_FILL, + TEXTURE_WIDTH, + TEXTURE_HEIGHT); - public TextureBucket(int type) { - super(type, false, true); - } + public TextureBucket(int type) { + super(type, false, true); + } - /** holds textures and offset in vbo */ - public TextureItem textures; + /** + * holds textures and offset in vbo + */ + public TextureItem textures; - /** scale mode */ - public boolean fixed; + /** + * scale mode + */ + public boolean fixed; - @Override - protected void compile(ShortBuffer vboData, ShortBuffer iboData) { + @Override + protected void compile(ShortBuffer vboData, ShortBuffer iboData) { - for (TextureItem t = textures; t != null; t = t.next) - t.upload(); + for (TextureItem t = textures; t != null; t = t.next) + t.upload(); /* add vertices to vbo */ - compileVertexItems(vboData); - } + compileVertexItems(vboData); + } - protected void clear() { - while (textures != null) - textures = textures.dispose(); - super.clear(); - } + protected void clear() { + while (textures != null) + textures = textures.dispose(); + super.clear(); + } - static class Shader extends GLShader { - int uMV, uProj, uScale, uTexSize, aPos, aTexCoord; + static class Shader extends GLShader { + int uMV, uProj, uScale, uTexSize, aPos, aTexCoord; - Shader() { - if (!create("texture_layer")) - return; + Shader() { + if (!create("texture_layer")) + return; - uMV = getUniform("u_mv"); - uProj = getUniform("u_proj"); - uScale = getUniform("u_scale"); - uTexSize = getUniform("u_div"); - aPos = getAttrib("vertex"); - aTexCoord = getAttrib("tex_coord"); - } + uMV = getUniform("u_mv"); + uProj = getUniform("u_proj"); + uScale = getUniform("u_scale"); + uTexSize = getUniform("u_div"); + aPos = getAttrib("vertex"); + aTexCoord = getAttrib("tex_coord"); + } - @Override - public boolean useProgram() { - if (super.useProgram()) { - GLState.enableVertexArrays(aPos, aTexCoord); - return true; - } - return false; - } - } + @Override + public boolean useProgram() { + if (super.useProgram()) { + GLState.enableVertexArrays(aPos, aTexCoord); + return true; + } + return false; + } + } - static Shader shader; + static Shader shader; - public static final class Renderer { + public static final class Renderer { - static void init() { - shader = new Shader(); + static void init() { + shader = new Shader(); /* FIXME pool should be disposed on exit... */ - pool.init(0); - } + pool.init(0); + } - public static RenderBucket draw(RenderBucket b, GLViewport v, float scale) { + public static RenderBucket draw(RenderBucket b, GLViewport v, float scale) { - GLState.test(false, false); - GLState.blend(true); + GLState.test(false, false); + GLState.blend(true); - shader.useProgram(); + shader.useProgram(); - TextureBucket tb = (TextureBucket) b; - gl.uniform1f(shader.uScale, tb.fixed ? 1 / scale : 1); + TextureBucket tb = (TextureBucket) b; + gl.uniform1f(shader.uScale, tb.fixed ? 1 / scale : 1); - v.proj.setAsUniform(shader.uProj); - v.mvp.setAsUniform(shader.uMV); + v.proj.setAsUniform(shader.uProj); + v.mvp.setAsUniform(shader.uMV); - MapRenderer.bindQuadIndicesVBO(); + MapRenderer.bindQuadIndicesVBO(); - for (TextureItem t = tb.textures; t != null; t = t.next) { - gl.uniform2f(shader.uTexSize, - 1f / (t.width * COORD_SCALE), - 1f / (t.height * COORD_SCALE)); - t.bind(); + for (TextureItem t = tb.textures; t != null; t = t.next) { + gl.uniform2f(shader.uTexSize, + 1f / (t.width * COORD_SCALE), + 1f / (t.height * COORD_SCALE)); + t.bind(); /* draw up to maxVertices in each iteration */ - for (int i = 0; i < t.indices; i += MAX_INDICES) { - /* to.offset * (24(shorts) * 2(short-bytes) - * / 6(indices) == 8) */ - int off = (t.offset + i) * 8 + tb.vertexOffset; + for (int i = 0; i < t.indices; i += MAX_INDICES) { + /* to.offset * (24(shorts) * 2(short-bytes) + * / 6(indices) == 8) */ + int off = (t.offset + i) * 8 + tb.vertexOffset; - int numIndices = t.indices - i; - if (numIndices > MAX_INDICES) - numIndices = MAX_INDICES; + int numIndices = t.indices - i; + if (numIndices > MAX_INDICES) + numIndices = MAX_INDICES; - tb.render(off, numIndices); - } - } + tb.render(off, numIndices); + } + } - return b.next; - } - } + return b.next; + } + } - public TextureItem getTextures() { - return textures; - } + public TextureItem getTextures() { + return textures; + } - public void render(int offset, int numIndices) { - gl.vertexAttribPointer(shader.aPos, 4, GL.SHORT, - false, 12, offset); + public void render(int offset, int numIndices) { + gl.vertexAttribPointer(shader.aPos, 4, GL.SHORT, + false, 12, offset); - gl.vertexAttribPointer(shader.aTexCoord, 2, GL.SHORT, - false, 12, offset + 8); + gl.vertexAttribPointer(shader.aTexCoord, 2, GL.SHORT, + false, 12, offset + 8); - gl.drawElements(GL.TRIANGLES, numIndices, - GL.UNSIGNED_SHORT, 0); - } + gl.drawElements(GL.TRIANGLES, numIndices, + GL.UNSIGNED_SHORT, 0); + } } diff --git a/vtm/src/org/oscim/renderer/bucket/TextureItem.java b/vtm/src/org/oscim/renderer/bucket/TextureItem.java index 18d004d0..599feeb1 100644 --- a/vtm/src/org/oscim/renderer/bucket/TextureItem.java +++ b/vtm/src/org/oscim/renderer/bucket/TextureItem.java @@ -16,12 +16,6 @@ */ package org.oscim.renderer.bucket; -import static org.oscim.backend.GLAdapter.gl; - -import java.util.ArrayList; - -import javax.annotation.CheckReturnValue; - import org.oscim.backend.CanvasAdapter; import org.oscim.backend.GL; import org.oscim.backend.canvas.Bitmap; @@ -33,301 +27,321 @@ import org.oscim.utils.pool.SyncPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; + +import javax.annotation.CheckReturnValue; + +import static org.oscim.backend.GLAdapter.gl; + public class TextureItem extends Inlist { - static final Logger log = LoggerFactory.getLogger(TextureItem.class); + static final Logger log = LoggerFactory.getLogger(TextureItem.class); - static final boolean dbg = false; + static final boolean dbg = false; - /** texture ID */ - private int id; + /** + * texture ID + */ + private int id; - /** current settings */ - public final int width; - public final int height; - public final boolean repeat; + /** + * current settings + */ + public final int width; + public final int height; + public final boolean repeat; - /** vertex offset from which this texture is referenced */ - /* FIXME dont put this here! */ - public int offset; - public int indices; + /** + * vertex offset from which this texture is referenced + */ + /* FIXME dont put this here! */ + public int offset; + public int indices; - /** temporary Bitmap */ - public Bitmap bitmap; + /** + * temporary Bitmap + */ + public Bitmap bitmap; - /** do not release the texture when TextureItem is released. */ - private TextureItem ref; - private int used = 0; + /** + * do not release the texture when TextureItem is released. + */ + private TextureItem ref; + private int used = 0; - /** texture data is ready */ - boolean loaded; + /** + * texture data is ready + */ + boolean loaded; - final TexturePool pool; + final TexturePool pool; - private TextureItem(TexturePool pool, int id) { - this(pool, id, pool.mWidth, pool.mHeight, false); - } + private TextureItem(TexturePool pool, int id) { + this(pool, id, pool.mWidth, pool.mHeight, false); + } - public TextureItem(Bitmap bitmap) { - this(bitmap, false); - } + public TextureItem(Bitmap bitmap) { + this(bitmap, false); + } - public TextureItem(Bitmap bitmap, boolean repeat) { - this(NOPOOL, -1, bitmap.getWidth(), bitmap.getHeight(), repeat); - this.bitmap = bitmap; - } + public TextureItem(Bitmap bitmap, boolean repeat) { + this(NOPOOL, -1, bitmap.getWidth(), bitmap.getHeight(), repeat); + this.bitmap = bitmap; + } - private TextureItem(TexturePool pool, int id, int width, int height, boolean repeat) { - this.id = id; - this.width = width; - this.height = height; - this.pool = pool; - this.repeat = repeat; - } + private TextureItem(TexturePool pool, int id, int width, int height, boolean repeat) { + this.id = id; + this.width = width; + this.height = height; + this.pool = pool; + this.repeat = repeat; + } - public static TextureItem clone(TextureItem ti) { + public static TextureItem clone(TextureItem ti) { - TextureItem clone = new TextureItem(NOPOOL, ti.id, ti.width, ti.height, ti.repeat); - clone.id = ti.id; - clone.ref = (ti.ref == null) ? ti : ti.ref; - clone.loaded = ti.loaded; + TextureItem clone = new TextureItem(NOPOOL, ti.id, ti.width, ti.height, ti.repeat); + clone.id = ti.id; + clone.ref = (ti.ref == null) ? ti : ti.ref; + clone.loaded = ti.loaded; - clone.ref.used++; + clone.ref.used++; - return clone; - } + return clone; + } - /** - * Upload Image to Texture - * [on GL-Thread] - */ - public void upload() { - if (loaded) - return; + /** + * Upload Image to Texture + * [on GL-Thread] + */ + public void upload() { + if (loaded) + return; - if (ref == null) { - pool.uploadTexture(this); + if (ref == null) { + pool.uploadTexture(this); - } else { - /* load referenced texture */ - ref.upload(); - id = ref.id; + } else { + /* load referenced texture */ + ref.upload(); + id = ref.id; - } - loaded = true; - } + } + loaded = true; + } - /** - * Bind Texture for rendering - * [on GL-Thread] - */ - public void bind() { - if (loaded) - GLState.bindTex2D(id); - else - upload(); - } + /** + * Bind Texture for rendering + * [on GL-Thread] + */ + public void bind() { + if (loaded) + GLState.bindTex2D(id); + else + upload(); + } - /** - * Dispose TextureItem - * [Threadsafe] - * - * @return this.next - */ - @CheckReturnValue - public TextureItem dispose() { - TextureItem n = this.next; - this.next = null; - pool.release(this); - return n; - } + /** + * Dispose TextureItem + * [Threadsafe] + * + * @return this.next + */ + @CheckReturnValue + public TextureItem dispose() { + TextureItem n = this.next; + this.next = null; + pool.release(this); + return n; + } - public static class TexturePool extends SyncPool { - private final ArrayList mBitmaps = new ArrayList(10); + public static class TexturePool extends SyncPool { + private final ArrayList mBitmaps = new ArrayList(10); - private final int mHeight; - private final int mWidth; - private final boolean mUseBitmapPool; + private final int mHeight; + private final int mWidth; + private final boolean mUseBitmapPool; - //private final int mBitmapFormat; - //private final int mBitmapType; + //private final int mBitmapFormat; + //private final int mBitmapType; - protected int mTexCnt = 0; + protected int mTexCnt = 0; - public TexturePool(int maxFill, int width, int height) { - super(maxFill); - mWidth = width; - mHeight = height; - mUseBitmapPool = true; - } + public TexturePool(int maxFill, int width, int height) { + super(maxFill); + mWidth = width; + mHeight = height; + mUseBitmapPool = true; + } - public TexturePool(int maxFill) { - super(maxFill); - mWidth = 0; - mHeight = 0; - mUseBitmapPool = false; - } + public TexturePool(int maxFill) { + super(maxFill); + mWidth = 0; + mHeight = 0; + mUseBitmapPool = false; + } - @Override - public TextureItem releaseAll(TextureItem t) { - throw new RuntimeException("use TextureItem.dispose()"); - } + @Override + public TextureItem releaseAll(TextureItem t) { + throw new RuntimeException("use TextureItem.dispose()"); + } - /** - * Retrieve a TextureItem from pool. - */ - public synchronized TextureItem get() { - TextureItem t = super.get(); + /** + * Retrieve a TextureItem from pool. + */ + public synchronized TextureItem get() { + TextureItem t = super.get(); - if (!mUseBitmapPool) - return t; + if (!mUseBitmapPool) + return t; - synchronized (mBitmaps) { - int size = mBitmaps.size(); - if (size == 0) - t.bitmap = CanvasAdapter.newBitmap(mWidth, mHeight, 0); - else { - t.bitmap = mBitmaps.remove(size - 1); - t.bitmap.eraseColor(Color.TRANSPARENT); - } - } + synchronized (mBitmaps) { + int size = mBitmaps.size(); + if (size == 0) + t.bitmap = CanvasAdapter.newBitmap(mWidth, mHeight, 0); + else { + t.bitmap = mBitmaps.remove(size - 1); + t.bitmap.eraseColor(Color.TRANSPARENT); + } + } - return t; - } + return t; + } - public synchronized TextureItem get(Bitmap bitmap) { - TextureItem t = super.get(); - t.bitmap = bitmap; + public synchronized TextureItem get(Bitmap bitmap) { + TextureItem t = super.get(); + t.bitmap = bitmap; - return t; - } + return t; + } - @Override - protected TextureItem createItem() { - return new TextureItem(this, -1); - } + @Override + protected TextureItem createItem() { + return new TextureItem(this, -1); + } - @Override - protected boolean clearItem(TextureItem t) { + @Override + protected boolean clearItem(TextureItem t) { - if (t.used > 0) - return false; + if (t.used > 0) + return false; - if (t.ref != null) { + if (t.ref != null) { /* dispose texture if this clone holds the last handle */ - if (t.ref.used == 0) { - t.ref.dispose(); - return false; - } - t.ref.used--; - return false; - } + if (t.ref.used == 0) { + t.ref.dispose(); + return false; + } + t.ref.used--; + return false; + } - t.loaded = false; + t.loaded = false; - if (mUseBitmapPool) - releaseBitmap(t); + if (mUseBitmapPool) + releaseBitmap(t); - return t.id >= 0; - } + return t.id >= 0; + } - @Override - protected void freeItem(TextureItem t) { + @Override + protected void freeItem(TextureItem t) { - if (t.ref == null && t.used == 0 && t.id >= 0) { - mTexCnt--; - synchronized (disposedTextures) { - disposedTextures.add(Integer.valueOf(t.id)); - t.id = -1; - } - } - } + if (t.ref == null && t.used == 0 && t.id >= 0) { + mTexCnt--; + synchronized (disposedTextures) { + disposedTextures.add(Integer.valueOf(t.id)); + t.id = -1; + } + } + } - protected void releaseBitmap(TextureItem t) { + protected void releaseBitmap(TextureItem t) { - if (t.bitmap == null) - return; + if (t.bitmap == null) + return; - synchronized (mBitmaps) { - mBitmaps.add(t.bitmap); - t.bitmap = null; - } - } + synchronized (mBitmaps) { + mBitmaps.add(t.bitmap); + t.bitmap = null; + } + } - private void uploadTexture(TextureItem t) { + private void uploadTexture(TextureItem t) { - if (t.bitmap == null) - throw new RuntimeException("Missing bitmap for texture"); + if (t.bitmap == null) + throw new RuntimeException("Missing bitmap for texture"); - if (t.id < 0) { - int[] textureIds = GLUtils.glGenTextures(1); - t.id = textureIds[0]; + if (t.id < 0) { + int[] textureIds = GLUtils.glGenTextures(1); + t.id = textureIds[0]; - initTexture(t); + initTexture(t); - if (dbg) - log.debug("fill:" + getFill() - + " count:" + mTexCnt - + " new texture " + t.id); + if (dbg) + log.debug("fill:" + getFill() + + " count:" + mTexCnt + + " new texture " + t.id); - mTexCnt++; + mTexCnt++; - t.bitmap.uploadToTexture(false); - } else { - GLState.bindTex2D(t.id); + t.bitmap.uploadToTexture(false); + } else { + GLState.bindTex2D(t.id); /* use faster subimage upload */ - t.bitmap.uploadToTexture(true); - } + t.bitmap.uploadToTexture(true); + } - if (dbg) - GLUtils.checkGlError(TextureItem.class.getName()); + if (dbg) + GLUtils.checkGlError(TextureItem.class.getName()); - if (mUseBitmapPool) - releaseBitmap(t); - } + if (mUseBitmapPool) + releaseBitmap(t); + } - protected void initTexture(TextureItem t) { - GLState.bindTex2D(t.id); + protected void initTexture(TextureItem t) { + GLState.bindTex2D(t.id); - gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, - GL.LINEAR); - gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, - GL.LINEAR); + gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, + GL.LINEAR); + gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, + GL.LINEAR); - if (t.repeat) { - gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, - GL.REPEAT); - gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, - GL.REPEAT); - } else { - gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, - GL.CLAMP_TO_EDGE); - gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, - GL.CLAMP_TO_EDGE); - } - } - }; + if (t.repeat) { + gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, + GL.REPEAT); + gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, + GL.REPEAT); + } else { + gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, + GL.CLAMP_TO_EDGE); + gl.texParameterf(GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, + GL.CLAMP_TO_EDGE); + } + } + } - /* Pool for not-pooled textures. Disposed items will only be released - * on the GL-Thread and will not be put back in any pool. */ - final static TexturePool NOPOOL = new TexturePool(0); - final static ArrayList disposedTextures = new ArrayList(); + ; - /** - * Disposed textures are released by MapRenderer after each frame - */ - public static void disposeTextures() { - synchronized (disposedTextures) { + /* Pool for not-pooled textures. Disposed items will only be released + * on the GL-Thread and will not be put back in any pool. */ + final static TexturePool NOPOOL = new TexturePool(0); + final static ArrayList disposedTextures = new ArrayList(); - int size = disposedTextures.size(); - if (size > 0) { - int[] tmp = new int[size]; - for (int i = 0; i < size; i++) - tmp[i] = disposedTextures.get(i).intValue(); + /** + * Disposed textures are released by MapRenderer after each frame + */ + public static void disposeTextures() { + synchronized (disposedTextures) { - disposedTextures.clear(); - GLUtils.glDeleteTextures(size, tmp); - } - } - } + int size = disposedTextures.size(); + if (size > 0) { + int[] tmp = new int[size]; + for (int i = 0; i < size; i++) + tmp[i] = disposedTextures.get(i).intValue(); + + disposedTextures.clear(); + GLUtils.glDeleteTextures(size, tmp); + } + } + } } diff --git a/vtm/src/org/oscim/renderer/bucket/VertexData.java b/vtm/src/org/oscim/renderer/bucket/VertexData.java index 5227fdd2..495ff6ea 100644 --- a/vtm/src/org/oscim/renderer/bucket/VertexData.java +++ b/vtm/src/org/oscim/renderer/bucket/VertexData.java @@ -16,8 +16,6 @@ */ package org.oscim.renderer.bucket; -import java.nio.ShortBuffer; - import org.oscim.renderer.bucket.VertexData.Chunk; import org.oscim.utils.FastMath; import org.oscim.utils.pool.Inlist; @@ -25,228 +23,234 @@ import org.oscim.utils.pool.SyncPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.ShortBuffer; + /** * A linked list of array chunks to hold temporary vertex data. - * + *

* TODO override append() etc to update internal (cur) state. */ public class VertexData extends Inlist.List { - static final Logger log = LoggerFactory.getLogger(VertexData.class); + static final Logger log = LoggerFactory.getLogger(VertexData.class); - /** - * Size of array chunks. Must be multiple of: - * 4 (LineLayer/PolygonLayer), - * 24 (TexLineLayer - one block, i.e. two segments) - * 24 (TextureLayer) - */ - public static final int SIZE = 360; + /** + * Size of array chunks. Must be multiple of: + * 4 (LineLayer/PolygonLayer), + * 24 (TexLineLayer - one block, i.e. two segments) + * 24 (TextureLayer) + */ + public static final int SIZE = 360; - /** - * Shared chunk pool size. - */ - private static final int MAX_POOL = 500; + /** + * Shared chunk pool size. + */ + private static final int MAX_POOL = 500; - public static class Chunk extends Inlist { - public final short[] vertices = new short[SIZE]; - public int used; - }; + public static class Chunk extends Inlist { + public final short[] vertices = new short[SIZE]; + public int used; + } - private static class Pool extends SyncPool { - public Pool() { - super(MAX_POOL); - } + ; - @Override - protected Chunk createItem() { - return new Chunk(); - } + private static class Pool extends SyncPool { + public Pool() { + super(MAX_POOL); + } - @Override - protected boolean clearItem(Chunk it) { - it.used = 0; - return true; - } - } + @Override + protected Chunk createItem() { + return new Chunk(); + } - public int countSize() { - if (cur == null) - return 0; + @Override + protected boolean clearItem(Chunk it) { + it.used = 0; + return true; + } + } - cur.used = used; + public int countSize() { + if (cur == null) + return 0; - int size = 0; - for (Chunk it = head(); it != null; it = it.next) - size += it.used; + cur.used = used; - return size; - } + int size = 0; + for (Chunk it = head(); it != null; it = it.next) + size += it.used; - @Override - public Chunk clear() { - if (cur == null) - return null; + return size; + } - cur.used = used; - used = SIZE; /* set SIZE to get new item on add */ - cur = null; - vertices = null; + @Override + public Chunk clear() { + if (cur == null) + return null; - return super.clear(); - } + cur.used = used; + used = SIZE; /* set SIZE to get new item on add */ + cur = null; + vertices = null; - private final static Pool pool = new Pool(); + return super.clear(); + } - public void dispose() { - pool.releaseAll(super.clear()); - used = SIZE; /* set SIZE to get new item on add */ - cur = null; - vertices = null; - } + private final static Pool pool = new Pool(); - /** - * @return sum of elements added - */ - public int compile(ShortBuffer sbuf) { - if (cur == null) - return 0; + public void dispose() { + pool.releaseAll(super.clear()); + used = SIZE; /* set SIZE to get new item on add */ + cur = null; + vertices = null; + } - cur.used = used; + /** + * @return sum of elements added + */ + public int compile(ShortBuffer sbuf) { + if (cur == null) + return 0; - int size = 0; - for (Chunk it = head(); it != null; it = it.next) { - size += it.used; - sbuf.put(it.vertices, 0, it.used); - } - dispose(); - return size; - } + cur.used = used; - private Chunk cur; + int size = 0; + for (Chunk it = head(); it != null; it = it.next) { + size += it.used; + sbuf.put(it.vertices, 0, it.used); + } + dispose(); + return size; + } - /* set SIZE to get new item on add */ - private int used = SIZE; + private Chunk cur; - private short[] vertices; + /* set SIZE to get new item on add */ + private int used = SIZE; - private void getNext() { - if (cur == null) { - cur = pool.get(); - push(cur); - } else { - if (cur.next != null) - throw new IllegalStateException("seeeked..."); + private short[] vertices; - cur.used = SIZE; - cur.next = pool.get(); - cur = cur.next; - } - vertices = cur.vertices; - used = 0; - } + private void getNext() { + if (cur == null) { + cur = pool.get(); + push(cur); + } else { + if (cur.next != null) + throw new IllegalStateException("seeeked..."); - public void add(short a) { - if (used == SIZE) - getNext(); + cur.used = SIZE; + cur.next = pool.get(); + cur = cur.next; + } + vertices = cur.vertices; + used = 0; + } - vertices[used++] = a; - } + public void add(short a) { + if (used == SIZE) + getNext(); - static final short toShort(float v) { - return (short) FastMath.clamp(v, Short.MIN_VALUE, Short.MAX_VALUE); - } + vertices[used++] = a; + } - public void add(float a, float b) { - add(toShort(a), toShort(b)); - } + static final short toShort(float v) { + return (short) FastMath.clamp(v, Short.MIN_VALUE, Short.MAX_VALUE); + } - public void add(short a, short b) { - if (used == SIZE) - getNext(); + public void add(float a, float b) { + add(toShort(a), toShort(b)); + } - vertices[used + 0] = a; - vertices[used + 1] = b; - used += 2; - } + public void add(short a, short b) { + if (used == SIZE) + getNext(); - public void add(float a, float b, float c) { - add(toShort(a), toShort(b), toShort(c)); - } + vertices[used + 0] = a; + vertices[used + 1] = b; + used += 2; + } - public void add(short a, short b, short c) { - if (used == SIZE) - getNext(); + public void add(float a, float b, float c) { + add(toShort(a), toShort(b), toShort(c)); + } - vertices[used + 0] = a; - vertices[used + 1] = b; - vertices[used + 2] = c; - used += 3; - } + public void add(short a, short b, short c) { + if (used == SIZE) + getNext(); - public void add(float a, float b, float c, float d) { - add(toShort(a), toShort(b), toShort(c), toShort(d)); - } + vertices[used + 0] = a; + vertices[used + 1] = b; + vertices[used + 2] = c; + used += 3; + } - public void add(short a, short b, short c, short d) { - if (used == SIZE) - getNext(); + public void add(float a, float b, float c, float d) { + add(toShort(a), toShort(b), toShort(c), toShort(d)); + } - vertices[used + 0] = a; - vertices[used + 1] = b; - vertices[used + 2] = c; - vertices[used + 3] = d; - used += 4; - } + public void add(short a, short b, short c, short d) { + if (used == SIZE) + getNext(); - public void add(float a, float b, float c, float d, float e, float f) { - add(toShort(a), toShort(b), toShort(c), toShort(d), toShort(e), toShort(f)); - } + vertices[used + 0] = a; + vertices[used + 1] = b; + vertices[used + 2] = c; + vertices[used + 3] = d; + used += 4; + } - public void add(short a, short b, short c, short d, short e, short f) { - if (used == SIZE) - getNext(); + public void add(float a, float b, float c, float d, float e, float f) { + add(toShort(a), toShort(b), toShort(c), toShort(d), toShort(e), toShort(f)); + } - vertices[used + 0] = a; - vertices[used + 1] = b; - vertices[used + 2] = c; - vertices[used + 3] = d; - vertices[used + 4] = e; - vertices[used + 5] = f; - used += 6; - } + public void add(short a, short b, short c, short d, short e, short f) { + if (used == SIZE) + getNext(); - /** - * Direct access to the current chunk of VertexData. Use with care! - * - * When changing the position use releaseChunk to update internal state - */ - public Chunk obtainChunk() { - if (used == SIZE) - getNext(); + vertices[used + 0] = a; + vertices[used + 1] = b; + vertices[used + 2] = c; + vertices[used + 3] = d; + vertices[used + 4] = e; + vertices[used + 5] = f; + used += 6; + } - cur.used = used; + /** + * Direct access to the current chunk of VertexData. Use with care! + *

+ * When changing the position use releaseChunk to update internal state + */ + public Chunk obtainChunk() { + if (used == SIZE) + getNext(); - return cur; - } + cur.used = used; - public void releaseChunk() { - used = cur.used; - } + return cur; + } - public void releaseChunk(int size) { - cur.used = size; - used = size; - } + public void releaseChunk() { + used = cur.used; + } - /** Do not use! */ - public void seek(int offset) { - used += offset; - cur.used = used; + public void releaseChunk(int size) { + cur.used = size; + used = size; + } - if (used > SIZE || used < 0) - throw new IllegalStateException("seeked too far: " + offset + "/" + used); - } + /** + * Do not use! + */ + public void seek(int offset) { + used += offset; + cur.used = used; - public boolean empty() { - return cur == null; - } + if (used > SIZE || used < 0) + throw new IllegalStateException("seeked too far: " + offset + "/" + used); + } + + public boolean empty() { + return cur == null; + } } diff --git a/vtm/src/org/oscim/theme/DebugTheme.java b/vtm/src/org/oscim/theme/DebugTheme.java index 21b57447..5fe49bd6 100644 --- a/vtm/src/org/oscim/theme/DebugTheme.java +++ b/vtm/src/org/oscim/theme/DebugTheme.java @@ -9,40 +9,40 @@ import org.oscim.theme.styles.RenderStyle; public class DebugTheme implements IRenderTheme { - private final static LineStyle[] line = { new LineStyle(1, Color.MAGENTA, 2) }; - private final static AreaStyle[] area = { new AreaStyle(0, Color.CYAN) }; + private final static LineStyle[] line = {new LineStyle(1, Color.MAGENTA, 2)}; + private final static AreaStyle[] area = {new AreaStyle(0, Color.CYAN)}; - @Override - public RenderStyle[] matchElement(GeometryType type, TagSet tags, int zoomLevel) { - if (type == GeometryType.LINE) - return line; - if (type == GeometryType.POLY) - return area; + @Override + public RenderStyle[] matchElement(GeometryType type, TagSet tags, int zoomLevel) { + if (type == GeometryType.LINE) + return line; + if (type == GeometryType.POLY) + return area; - return null; - } + return null; + } - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public int getLevels() { - return 0; - } + @Override + public int getLevels() { + return 0; + } - @Override - public int getMapBackground() { - return 0; - } + @Override + public int getMapBackground() { + return 0; + } - @Override - public void scaleTextSize(float scaleFactor) { - } + @Override + public void scaleTextSize(float scaleFactor) { + } - @Override - public void updateStyles() { + @Override + public void updateStyles() { - } + } } diff --git a/vtm/src/org/oscim/theme/ExternalRenderTheme.java b/vtm/src/org/oscim/theme/ExternalRenderTheme.java index 6a7a08a0..6c0d1931 100644 --- a/vtm/src/org/oscim/theme/ExternalRenderTheme.java +++ b/vtm/src/org/oscim/theme/ExternalRenderTheme.java @@ -17,74 +17,72 @@ */ package org.oscim.theme; +import org.oscim.theme.IRenderTheme.ThemeException; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; -import org.oscim.theme.IRenderTheme.ThemeException; - /** * An ExternalRenderTheme allows for customizing the rendering style of the map * via an XML file. */ public class ExternalRenderTheme implements ThemeFile { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final long mFileModificationDate; - private final String mPath; + private final long mFileModificationDate; + private final String mPath; - /** - * @param fileName - * the path to the XML render theme file. - * @throws FileNotFoundException - * if the file does not exist or cannot be read. - */ - public ExternalRenderTheme(String fileName) { + /** + * @param fileName the path to the XML render theme file. + * @throws FileNotFoundException if the file does not exist or cannot be read. + */ + public ExternalRenderTheme(String fileName) { - File themeFile = new File(fileName); - if (!themeFile.exists()) { - throw new ThemeException("file does not exist: " + themeFile.getAbsolutePath()); - } else if (!themeFile.isFile()) { - throw new ThemeException("not a file: " + fileName); - } else if (!themeFile.canRead()) { - throw new ThemeException("cannot read file: " + fileName); - } + File themeFile = new File(fileName); + if (!themeFile.exists()) { + throw new ThemeException("file does not exist: " + themeFile.getAbsolutePath()); + } else if (!themeFile.isFile()) { + throw new ThemeException("not a file: " + fileName); + } else if (!themeFile.canRead()) { + throw new ThemeException("cannot read file: " + fileName); + } - mFileModificationDate = themeFile.lastModified(); - if (mFileModificationDate == 0L) { - throw new ThemeException("cannot read last modification time"); - } - mPath = fileName; - } + mFileModificationDate = themeFile.lastModified(); + if (mFileModificationDate == 0L) { + throw new ThemeException("cannot read last modification time"); + } + mPath = fileName; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (!(obj instanceof ExternalRenderTheme)) { - return false; - } - ExternalRenderTheme other = (ExternalRenderTheme) obj; - if (mFileModificationDate != other.mFileModificationDate) { - return false; - } else if (mPath == null && other.mPath != null) { - return false; - } else if (mPath != null && !mPath.equals(other.mPath)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof ExternalRenderTheme)) { + return false; + } + ExternalRenderTheme other = (ExternalRenderTheme) obj; + if (mFileModificationDate != other.mFileModificationDate) { + return false; + } else if (mPath == null && other.mPath != null) { + return false; + } else if (mPath != null && !mPath.equals(other.mPath)) { + return false; + } + return true; + } - @Override - public InputStream getRenderThemeAsStream() { - InputStream is; + @Override + public InputStream getRenderThemeAsStream() { + InputStream is; - try { - is = new FileInputStream(mPath); - } catch (FileNotFoundException e) { - throw new ThemeException(e.getMessage()); - } - return is; - } + try { + is = new FileInputStream(mPath); + } catch (FileNotFoundException e) { + throw new ThemeException(e.getMessage()); + } + return is; + } } diff --git a/vtm/src/org/oscim/theme/IRenderTheme.java b/vtm/src/org/oscim/theme/IRenderTheme.java index cff16996..134a4b29 100644 --- a/vtm/src/org/oscim/theme/IRenderTheme.java +++ b/vtm/src/org/oscim/theme/IRenderTheme.java @@ -23,47 +23,45 @@ import org.oscim.theme.styles.RenderStyle; public interface IRenderTheme { - /** - * Matches a MapElement with the given parameters against this RenderTheme. - * - * @param zoomLevel - * the zoom level at which the way should be matched. - * @return matching render instructions - */ - public abstract RenderStyle[] matchElement(GeometryType type, TagSet tags, int zoomLevel); + /** + * Matches a MapElement with the given parameters against this RenderTheme. + * + * @param zoomLevel the zoom level at which the way should be matched. + * @return matching render instructions + */ + public abstract RenderStyle[] matchElement(GeometryType type, TagSet tags, int zoomLevel); - /** - * Must be called when this RenderTheme gets destroyed to clean up and free - * resources. - */ - public abstract void dispose(); + /** + * Must be called when this RenderTheme gets destroyed to clean up and free + * resources. + */ + public abstract void dispose(); - /** - * @return the number of distinct drawing levels required by this - * RenderTheme. - */ - public abstract int getLevels(); + /** + * @return the number of distinct drawing levels required by this + * RenderTheme. + */ + public abstract int getLevels(); - /** - * @return the map background color of this RenderTheme. - */ - public abstract int getMapBackground(); + /** + * @return the map background color of this RenderTheme. + */ + public abstract int getMapBackground(); - public void updateStyles(); + public void updateStyles(); - /** - * Scales the text size of this RenderTheme by the given factor. - * - * @param scaleFactor - * the factor by which the text size should be scaled. - */ - public abstract void scaleTextSize(float scaleFactor); + /** + * Scales the text size of this RenderTheme by the given factor. + * + * @param scaleFactor the factor by which the text size should be scaled. + */ + public abstract void scaleTextSize(float scaleFactor); - public static class ThemeException extends IllegalArgumentException { - public ThemeException(String string) { - super(string); - } + public static class ThemeException extends IllegalArgumentException { + public ThemeException(String string) { + super(string); + } - private static final long serialVersionUID = 1L; - } + private static final long serialVersionUID = 1L; + } } diff --git a/vtm/src/org/oscim/theme/MatchingCacheKey.java b/vtm/src/org/oscim/theme/MatchingCacheKey.java index d9fadbb4..f04a446a 100644 --- a/vtm/src/org/oscim/theme/MatchingCacheKey.java +++ b/vtm/src/org/oscim/theme/MatchingCacheKey.java @@ -20,78 +20,80 @@ import org.oscim.core.Tag; import org.oscim.core.TagSet; class MatchingCacheKey { - int mHash; - Tag[] mTags; + int mHash; + Tag[] mTags; - MatchingCacheKey() { - } + MatchingCacheKey() { + } - MatchingCacheKey(MatchingCacheKey key) { - mTags = key.mTags; - mHash = key.mHash; - } + MatchingCacheKey(MatchingCacheKey key) { + mTags = key.mTags; + mHash = key.mHash; + } - /** set temporary values for comparison */ - boolean set(TagSet tags, MatchingCacheKey compare) { - int numTags = tags.numTags; + /** + * set temporary values for comparison + */ + boolean set(TagSet tags, MatchingCacheKey compare) { + int numTags = tags.numTags; /* Test if tags are equal to previous query */ - if (compare != null && numTags == compare.mTags.length) { - int i = 0; - for (; i < numTags; i++) { - Tag t1 = tags.tags[i]; - Tag t2 = compare.mTags[i]; + if (compare != null && numTags == compare.mTags.length) { + int i = 0; + for (; i < numTags; i++) { + Tag t1 = tags.tags[i]; + Tag t2 = compare.mTags[i]; - if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) - break; - } - if (i == numTags) - return true; - } + if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) + break; + } + if (i == numTags) + return true; + } /* Clone tags as they belong to TileDataSource. - * Also needed for comparison if previous tags + * Also needed for comparison if previous tags * were equal. */ - mTags = new Tag[numTags]; + mTags = new Tag[numTags]; - int result = 7; - for (int i = 0; i < numTags; i++) { - Tag t = tags.tags[i]; - result = 31 * result + t.hashCode(); - mTags[i] = t; - } + int result = 7; + for (int i = 0; i < numTags; i++) { + Tag t = tags.tags[i]; + result = 31 * result + t.hashCode(); + mTags[i] = t; + } - mHash = 31 * result; + mHash = 31 * result; - return false; - } + return false; + } - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; - if (this == obj) - return true; + if (this == obj) + return true; - MatchingCacheKey other = (MatchingCacheKey) obj; + MatchingCacheKey other = (MatchingCacheKey) obj; - int length = mTags.length; - if (length != other.mTags.length) - return false; + int length = mTags.length; + if (length != other.mTags.length) + return false; - for (int i = 0; i < length; i++) { - Tag t1 = mTags[i]; - Tag t2 = other.mTags[i]; + for (int i = 0; i < length; i++) { + Tag t1 = mTags[i]; + Tag t2 = other.mTags[i]; - if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) - return false; - } - return true; - } + if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) + return false; + } + return true; + } - @Override - public int hashCode() { - return mHash; - } + @Override + public int hashCode() { + return mHash; + } } diff --git a/vtm/src/org/oscim/theme/RenderTheme.java b/vtm/src/org/oscim/theme/RenderTheme.java index a7614547..4aa27986 100644 --- a/vtm/src/org/oscim/theme/RenderTheme.java +++ b/vtm/src/org/oscim/theme/RenderTheme.java @@ -16,10 +16,6 @@ */ package org.oscim.theme; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.TagSet; import org.oscim.theme.rule.Rule; @@ -30,240 +26,244 @@ import org.oscim.utils.LRUCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + public class RenderTheme implements IRenderTheme { - static final Logger log = LoggerFactory.getLogger(RenderTheme.class); + static final Logger log = LoggerFactory.getLogger(RenderTheme.class); - private static final int MATCHING_CACHE_SIZE = 512; + private static final int MATCHING_CACHE_SIZE = 512; - private final float mBaseTextSize; - private final int mMapBackground; + private final float mBaseTextSize; + private final int mMapBackground; - private final int mLevels; - private final Rule[] mRules; + private final int mLevels; + private final Rule[] mRules; - class RenderStyleCache { - final int matchType; - final LRUCache cache; - final MatchingCacheKey cacheKey; + class RenderStyleCache { + final int matchType; + final LRUCache cache; + final MatchingCacheKey cacheKey; - /* temporary matching instructions list */ - final ArrayList instructionList; + /* temporary matching instructions list */ + final ArrayList instructionList; - RenderStyleItem prevItem; + RenderStyleItem prevItem; - public RenderStyleCache(int type) { - cache = new LRUCache(MATCHING_CACHE_SIZE); - instructionList = new ArrayList(4); - cacheKey = new MatchingCacheKey(); - matchType = type; - } + public RenderStyleCache(int type) { + cache = new LRUCache(MATCHING_CACHE_SIZE); + instructionList = new ArrayList(4); + cacheKey = new MatchingCacheKey(); + matchType = type; + } - RenderStyleItem getRenderInstructions() { - return cache.get(cacheKey); - } - } + RenderStyleItem getRenderInstructions() { + return cache.get(cacheKey); + } + } - class RenderStyleItem { - RenderStyleItem next; - int zoom; - RenderStyle[] list; - MatchingCacheKey key; - } + class RenderStyleItem { + RenderStyleItem next; + int zoom; + RenderStyle[] list; + MatchingCacheKey key; + } - private final RenderStyleCache[] mStyleCache; + private final RenderStyleCache[] mStyleCache; - public RenderTheme(int mapBackground, float baseTextSize, Rule[] rules, int levels) { - if (rules == null) - throw new IllegalArgumentException("rules missing"); + public RenderTheme(int mapBackground, float baseTextSize, Rule[] rules, int levels) { + if (rules == null) + throw new IllegalArgumentException("rules missing"); - mMapBackground = mapBackground; - mBaseTextSize = baseTextSize; - mLevels = levels; - mRules = rules; + mMapBackground = mapBackground; + mBaseTextSize = baseTextSize; + mLevels = levels; + mRules = rules; - mStyleCache = new RenderStyleCache[3]; - mStyleCache[0] = new RenderStyleCache(Element.NODE); - mStyleCache[1] = new RenderStyleCache(Element.LINE); - mStyleCache[2] = new RenderStyleCache(Element.POLY); - } + mStyleCache = new RenderStyleCache[3]; + mStyleCache[0] = new RenderStyleCache(Element.NODE); + mStyleCache[1] = new RenderStyleCache(Element.LINE); + mStyleCache[2] = new RenderStyleCache(Element.POLY); + } - @Override - public void dispose() { + @Override + public void dispose() { - for (int i = 0; i < 3; i++) - mStyleCache[i].cache.clear(); + for (int i = 0; i < 3; i++) + mStyleCache[i].cache.clear(); - for (Rule rule : mRules) - rule.dispose(); - } + for (Rule rule : mRules) + rule.dispose(); + } - @Override - public int getLevels() { - return mLevels; - } + @Override + public int getLevels() { + return mLevels; + } - @Override - public int getMapBackground() { - return mMapBackground; - } + @Override + public int getMapBackground() { + return mMapBackground; + } - //AtomicInteger hitCount = new AtomicInteger(0); - //AtomicInteger missCount = new AtomicInteger(0); - //AtomicInteger sameCount = new AtomicInteger(0); + //AtomicInteger hitCount = new AtomicInteger(0); + //AtomicInteger missCount = new AtomicInteger(0); + //AtomicInteger sameCount = new AtomicInteger(0); - @Override - public RenderStyle[] matchElement(GeometryType geometryType, TagSet tags, int zoomLevel) { + @Override + public RenderStyle[] matchElement(GeometryType geometryType, TagSet tags, int zoomLevel) { /* list of items in cache */ - RenderStyleItem ris = null; + RenderStyleItem ris = null; /* the item matching tags and zoomlevel */ - RenderStyleItem ri = null; + RenderStyleItem ri = null; - int type = geometryType.nativeInt; - if (type < 1 || type > 3) { - log.debug("invalid geometry type for RenderTheme " + geometryType.name()); - return null; - } + int type = geometryType.nativeInt; + if (type < 1 || type > 3) { + log.debug("invalid geometry type for RenderTheme " + geometryType.name()); + return null; + } - RenderStyleCache cache = mStyleCache[type - 1]; + RenderStyleCache cache = mStyleCache[type - 1]; /* NOTE: maximum zoom level supported is 32 */ - int zoomMask = 1 << zoomLevel; + int zoomMask = 1 << zoomLevel; - synchronized (cache) { + synchronized (cache) { - if ((cache.prevItem == null) || (cache.prevItem.zoom & zoomMask) == 0) { - /* previous instructions zoom does not match */ - cache.cacheKey.set(tags, null); - } else { - /* compare if tags match previous instructions */ - if (cache.cacheKey.set(tags, cache.prevItem.key)) { - ri = cache.prevItem; - //log.debug(hitCount + "/" + sameCount.incrementAndGet() - // + "/" + missCount + "same hit " + tags); - } - } + if ((cache.prevItem == null) || (cache.prevItem.zoom & zoomMask) == 0) { + /* previous instructions zoom does not match */ + cache.cacheKey.set(tags, null); + } else { + /* compare if tags match previous instructions */ + if (cache.cacheKey.set(tags, cache.prevItem.key)) { + ri = cache.prevItem; + //log.debug(hitCount + "/" + sameCount.incrementAndGet() + // + "/" + missCount + "same hit " + tags); + } + } - if (ri == null) { + if (ri == null) { /* get instruction for current cacheKey */ - ris = cache.getRenderInstructions(); + ris = cache.getRenderInstructions(); - for (ri = ris; ri != null; ri = ri.next) { - if ((ri.zoom & zoomMask) != 0) { + for (ri = ris; ri != null; ri = ri.next) { + if ((ri.zoom & zoomMask) != 0) { /* cache hit */ - //log.debug(hitCount.incrementAndGet() - // + "/" + sameCount + "/" + missCount - // + " cache hit " + tags); - break; - } - } - } + //log.debug(hitCount.incrementAndGet() + // + "/" + sameCount + "/" + missCount + // + " cache hit " + tags); + break; + } + } + } - if (ri == null) { + if (ri == null) { /* cache miss */ - //missCount.incrementAndGet(); + //missCount.incrementAndGet(); - List matches = cache.instructionList; - matches.clear(); + List matches = cache.instructionList; + matches.clear(); - for (Rule rule : mRules) - rule.matchElement(cache.matchType, cache.cacheKey.mTags, zoomMask, matches); + for (Rule rule : mRules) + rule.matchElement(cache.matchType, cache.cacheKey.mTags, zoomMask, matches); - int size = matches.size(); - if (size > 1) { - for (int i = 0; i < size - 1; i++) { - RenderStyle r = matches.get(i); - for (int j = i + 1; j < size; j++) { - if (matches.get(j) == r) { - log.debug("fix duplicate instruction! " - + Arrays.deepToString(cache.cacheKey.mTags) - + " zoom:" + zoomLevel + " " - + r.getClass().getName()); - matches.remove(j--); - size--; - } - } - } - } + int size = matches.size(); + if (size > 1) { + for (int i = 0; i < size - 1; i++) { + RenderStyle r = matches.get(i); + for (int j = i + 1; j < size; j++) { + if (matches.get(j) == r) { + log.debug("fix duplicate instruction! " + + Arrays.deepToString(cache.cacheKey.mTags) + + " zoom:" + zoomLevel + " " + + r.getClass().getName()); + matches.remove(j--); + size--; + } + } + } + } /* check if same instructions are used in another level */ - for (ri = ris; ri != null; ri = ri.next) { - if (size == 0) { - if (ri.list != null) - continue; + for (ri = ris; ri != null; ri = ri.next) { + if (size == 0) { + if (ri.list != null) + continue; /* both matchinglists are empty */ - break; - } + break; + } - if (ri.list == null) - continue; + if (ri.list == null) + continue; - if (ri.list.length != size) - continue; + if (ri.list.length != size) + continue; - int i = 0; - for (RenderStyle r : ri.list) { - if (r != matches.get(i)) - break; - i++; - } - if (i == size) + int i = 0; + for (RenderStyle r : ri.list) { + if (r != matches.get(i)) + break; + i++; + } + if (i == size) /* both matching lists contain the same items */ - break; - } + break; + } - if (ri != null) { + if (ri != null) { /* we found a same matchting list on another zoomlevel add * this zoom level to the existing RenderInstructionItem. */ - ri.zoom |= zoomMask; + ri.zoom |= zoomMask; - //log.debug(zoomLevel + " same instructions " + size + " " - // + Arrays.deepToString(tags)); - } else { - //log.debug(zoomLevel + " new instructions " + size + " " - // + Arrays.deepToString(tags)); + //log.debug(zoomLevel + " same instructions " + size + " " + // + Arrays.deepToString(tags)); + } else { + //log.debug(zoomLevel + " new instructions " + size + " " + // + Arrays.deepToString(tags)); - ri = new RenderStyleItem(); - ri.zoom = zoomMask; + ri = new RenderStyleItem(); + ri.zoom = zoomMask; - if (size > 0) { - ri.list = new RenderStyle[size]; - matches.toArray(ri.list); - } + if (size > 0) { + ri.list = new RenderStyle[size]; + matches.toArray(ri.list); + } /* attach this list to the one found for MatchingKey */ - if (ris != null) { - ri.next = ris.next; - ri.key = ris.key; - ris.next = ri; - } else { - ri.key = new MatchingCacheKey(cache.cacheKey); - cache.cache.put(ri.key, ri); - } - } - } - cache.prevItem = ri; - } - return ri.list; - } + if (ris != null) { + ri.next = ris.next; + ri.key = ris.key; + ris.next = ri; + } else { + ri.key = new MatchingCacheKey(cache.cacheKey); + cache.cache.put(ri.key, ri); + } + } + } + cache.prevItem = ri; + } + return ri.list; + } - @Override - public void scaleTextSize(float scaleFactor) { - for (Rule rule : mRules) - rule.scaleTextSize(scaleFactor * mBaseTextSize); - } + @Override + public void scaleTextSize(float scaleFactor) { + for (Rule rule : mRules) + rule.scaleTextSize(scaleFactor * mBaseTextSize); + } - @Override - public void updateStyles() { - for (Rule rule : mRules) - rule.updateStyles(); - } + @Override + public void updateStyles() { + for (Rule rule : mRules) + rule.updateStyles(); + } - public void traverseRules(RuleVisitor visitor) { - for (Rule rule : mRules) - rule.apply(visitor); - } + public void traverseRules(RuleVisitor visitor) { + for (Rule rule : mRules) + rule.apply(visitor); + } } diff --git a/vtm/src/org/oscim/theme/ThemeFile.java b/vtm/src/org/oscim/theme/ThemeFile.java index 9b86b5e8..bbcfd830 100644 --- a/vtm/src/org/oscim/theme/ThemeFile.java +++ b/vtm/src/org/oscim/theme/ThemeFile.java @@ -22,10 +22,9 @@ import java.io.InputStream; import java.io.Serializable; public interface ThemeFile extends Serializable { - /** - * @return an InputStream to read the render theme data from. - * @throws FileNotFoundException - * if the render theme file cannot be found. - */ - InputStream getRenderThemeAsStream() throws FileNotFoundException; + /** + * @return an InputStream to read the render theme data from. + * @throws FileNotFoundException if the render theme file cannot be found. + */ + InputStream getRenderThemeAsStream() throws FileNotFoundException; } diff --git a/vtm/src/org/oscim/theme/ThemeLoader.java b/vtm/src/org/oscim/theme/ThemeLoader.java index c5eb03a4..5dce0557 100644 --- a/vtm/src/org/oscim/theme/ThemeLoader.java +++ b/vtm/src/org/oscim/theme/ThemeLoader.java @@ -17,50 +17,50 @@ package org.oscim.theme; -import java.io.FileNotFoundException; -import java.io.InputStream; - import org.oscim.backend.CanvasAdapter; import org.oscim.theme.IRenderTheme.ThemeException; import org.oscim.utils.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.FileNotFoundException; +import java.io.InputStream; + public class ThemeLoader { - static final Logger log = LoggerFactory.getLogger(ThemeLoader.class); + static final Logger log = LoggerFactory.getLogger(ThemeLoader.class); - /** - * Load theme from XML file. - * - * @throws FileNotFoundException - * @throws ThemeException - */ - public static IRenderTheme load(String renderThemePath) throws ThemeException, - FileNotFoundException { - return load(new ExternalRenderTheme(renderThemePath)); - } + /** + * Load theme from XML file. + * + * @throws FileNotFoundException + * @throws ThemeException + */ + public static IRenderTheme load(String renderThemePath) throws ThemeException, + FileNotFoundException { + return load(new ExternalRenderTheme(renderThemePath)); + } - public static IRenderTheme load(ThemeFile theme) throws ThemeException { + public static IRenderTheme load(ThemeFile theme) throws ThemeException { - try { - InputStream is = theme.getRenderThemeAsStream(); - return load(is); - } catch (FileNotFoundException e) { - log.error(e.getMessage()); - } + try { + InputStream is = theme.getRenderThemeAsStream(); + return load(is); + } catch (FileNotFoundException e) { + log.error(e.getMessage()); + } - return null; - } + return null; + } - public static IRenderTheme load(InputStream inputStream) throws ThemeException { + public static IRenderTheme load(InputStream inputStream) throws ThemeException { - try { - IRenderTheme t = XmlThemeBuilder.read(inputStream); - if (t != null) - t.scaleTextSize(CanvasAdapter.textScale + (CanvasAdapter.dpi / 240 - 1) * 0.5f); - return t; - } finally { - IOUtils.closeQuietly(inputStream); - } - } + try { + IRenderTheme t = XmlThemeBuilder.read(inputStream); + if (t != null) + t.scaleTextSize(CanvasAdapter.textScale + (CanvasAdapter.dpi / 240 - 1) * 0.5f); + return t; + } finally { + IOUtils.closeQuietly(inputStream); + } + } } diff --git a/vtm/src/org/oscim/theme/XmlThemeBuilder.java b/vtm/src/org/oscim/theme/XmlThemeBuilder.java index 95b36b01..1b8eab67 100644 --- a/vtm/src/org/oscim/theme/XmlThemeBuilder.java +++ b/vtm/src/org/oscim/theme/XmlThemeBuilder.java @@ -18,16 +18,6 @@ */ package org.oscim.theme; -import static java.lang.Boolean.parseBoolean; -import static java.lang.Float.parseFloat; -import static java.lang.Integer.parseInt; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Stack; - import org.oscim.backend.CanvasAdapter; import org.oscim.backend.XMLReaderAdapter; import org.oscim.backend.canvas.Bitmap; @@ -61,827 +51,824 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Stack; + +import static java.lang.Boolean.parseBoolean; +import static java.lang.Float.parseFloat; +import static java.lang.Integer.parseInt; + public class XmlThemeBuilder extends DefaultHandler { - static final Logger log = LoggerFactory.getLogger(XmlThemeBuilder.class); - - private static final int RENDER_THEME_VERSION = 1; - - private static enum Element { - RENDER_THEME, RENDERING_INSTRUCTION, RULE, STYLE, ATLAS; - } - - private static final String ELEMENT_NAME_RENDER_THEME = "rendertheme"; - private static final String ELEMENT_NAME_MATCH = "m"; - private static final String UNEXPECTED_ELEMENT = "unexpected element: "; - - //private static final String IMG_PATH = "styles/"; - private static final String IMG_PATH = ""; - - private static final String LINE_STYLE = "L"; - private static final String OUTLINE_STYLE = "O"; - private static final String AREA_STYLE = "A"; - - /** - * @param inputStream - * an input stream containing valid render theme XML data. - * @return a new RenderTheme which is created by parsing the XML data from - * the input stream. - * @throws ThemeException - * if an error occurs while parsing the render theme XML. - * @throws IOException - * if an I/O error occurs while reading from the input stream. - */ - public static IRenderTheme read(InputStream inputStream) - throws ThemeException { - - XmlThemeBuilder renderThemeHandler = new XmlThemeBuilder(); - - try { - new XMLReaderAdapter().parse(renderThemeHandler, inputStream); - } catch (IOException e) { - throw new ThemeException(e.getMessage()); - } - - return renderThemeHandler.mRenderTheme; - } - - /** - * Logs the given information about an unknown XML attribute. - * - * @param element - * the XML element name. - * @param name - * the XML attribute name. - * @param value - * the XML attribute value. - * @param attributeIndex - * the XML attribute index position. - */ - public static void logUnknownAttribute(String element, String name, - String value, int attributeIndex) { - log.debug("unknown attribute in element {} () : {} = {}", - element, attributeIndex, name, value); - } - - private final ArrayList mRulesList = new ArrayList(); - private final Stack mElementStack = new Stack(); - private final Stack mRuleStack = new Stack(); - private final HashMap mStyles = - new HashMap(10); - - private final HashMap> mTextStyles = - new HashMap>(10); - - private final TextBuilder mTextBuilder = TextStyle.builder(); - private final AreaBuilder mAreaBuilder = AreaStyle.builder(); - private final LineBuilder mLineBuilder = LineStyle.builder(); - - private RuleBuilder mCurrentRule; - private TextureAtlas mTextureAtlas; - - private int mLevels = 0; - private int mMapBackground = 0xffffffff; - private float mTextScale = 1; - - private RenderTheme mRenderTheme; - - @Override - public void endDocument() { - - Rule[] rules = new Rule[mRulesList.size()]; - for (int i = 0, n = rules.length; i < n; i++) - rules[i] = mRulesList.get(i).onComplete(null); - - mRenderTheme = new RenderTheme(mMapBackground, mTextScale, rules, mLevels); - - mRulesList.clear(); - mStyles.clear(); - mRuleStack.clear(); - mElementStack.clear(); - - mTextureAtlas = null; - } - - @Override - public void endElement(String uri, String localName, String qName) { - mElementStack.pop(); - - if (ELEMENT_NAME_MATCH.equals(localName)) { - mRuleStack.pop(); - if (mRuleStack.empty()) { - mRulesList.add(mCurrentRule); - } else { - mCurrentRule = mRuleStack.peek(); - } - } - } - - @Override - public void error(SAXParseException exception) { - log.debug(exception.getMessage()); - } - - @Override - public void warning(SAXParseException exception) { - log.debug(exception.getMessage()); - } - - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws ThemeException { - try { - if (ELEMENT_NAME_RENDER_THEME.equals(localName)) { - checkState(localName, Element.RENDER_THEME); - createRenderTheme(localName, attributes); - - } else if (ELEMENT_NAME_MATCH.equals(localName)) { - checkState(localName, Element.RULE); - RuleBuilder rule = createRule(localName, attributes, mRuleStack); - if (!mRuleStack.empty()) { - mCurrentRule.addSubRule(rule); - } - mCurrentRule = rule; - mRuleStack.push(mCurrentRule); - - } else if ("style-text".equals(localName)) { - checkState(localName, Element.STYLE); - handleTextElement(localName, attributes, true, false); - - } else if ("style-area".equals(localName)) { - checkState(localName, Element.STYLE); - handleAreaElement(localName, attributes, true); - - } else if ("style-line".equals(localName)) { - checkState(localName, Element.STYLE); - handleLineElement(localName, attributes, true); - - } else if ("outline-layer".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - LineStyle line = createLine(null, localName, attributes, mLevels++, true); - mStyles.put(OUTLINE_STYLE + line.style, line); - - } else if ("area".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - handleAreaElement(localName, attributes, false); - - } else if ("caption".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - handleTextElement(localName, attributes, false, true); - - } else if ("circle".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - CircleStyle circle = createCircle(localName, attributes, mLevels++); - mCurrentRule.addStyle(circle); - - } else if ("line".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - handleLineElement(localName, attributes, false); - - } else if ("text".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - handleTextElement(localName, attributes, false, false); - - } else if ("symbol".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - SymbolStyle symbol = createSymbol(localName, attributes); - mCurrentRule.addStyle(symbol); - - } else if ("outline".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - addOutline(attributes.getValue("use")); - - } else if ("extrusion".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - ExtrusionStyle extrusion = createExtrusion(localName, attributes, mLevels++); - mCurrentRule.addStyle(extrusion); - - } else if ("lineSymbol".equals(localName)) { - checkState(localName, Element.RENDERING_INSTRUCTION); - log.error("unknown element: {}", localName); - - } else if ("atlas".equals(localName)) { - checkState(localName, Element.ATLAS); - createAtlas(localName, attributes); - - } else if ("rect".equals(localName)) { - checkState(localName, Element.ATLAS); - createTextureRegion(localName, attributes); - - } else { - log.error("unknown element: {}", localName); - //throw new SAXException("unknown element: " + localName); - } - } catch (SAXException e) { - throw new ThemeException(e.getMessage()); - } catch (IOException e) { - throw new ThemeException(e.getMessage()); - } - } - - private RuleBuilder createRule(String localName, Attributes attributes, - Stack ruleStack) { - int element = Rule.Element.ANY; - int closed = Closed.ANY; - String keys = null; - String values = null; - byte zoomMin = 0; - byte zoomMax = Byte.MAX_VALUE; - int selector = 0; - - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("e".equals(name)) { - String val = value.toUpperCase(); - if ("WAY".equals(val)) - element = Rule.Element.WAY; - else if ("NODE".equals(val)) - element = Rule.Element.NODE; - } else if ("k".equals(name)) { - keys = value; - } else if ("v".equals(name)) { - values = value; - } else if ("closed".equals(name)) { - String val = value.toUpperCase(); - if ("YES".equals(val)) - closed = Closed.YES; - else if ("NO".equals(val)) - closed = Closed.NO; - } else if ("zoom-min".equals(name)) { - zoomMin = Byte.parseByte(value); - } else if ("zoom-max".equals(name)) { - zoomMax = Byte.parseByte(value); - } else if ("select".equals(name)) { - if ("first".equals(value)) - selector |= Selector.FIRST; - if ("when-matched".equals(value)) - selector |= Selector.WHEN_MATCHED; - } else { - XmlThemeBuilder.logUnknownAttribute(localName, name, value, i); - } - } - - if (closed == Closed.YES) - element = Rule.Element.POLY; - else if (closed == Closed.NO) - element = Rule.Element.LINE; - - XmlThemeBuilder.validateNonNegative("zoom-min", zoomMin); - XmlThemeBuilder.validateNonNegative("zoom-max", zoomMax); - if (zoomMin > zoomMax) - throw new ThemeException("zoom-min must be less or equal zoom-max: " + zoomMin); - - RuleBuilder b = RuleBuilder.create(keys, values); - b.setZoom(zoomMin, zoomMax); - b.element(element); - b.select(selector); - return b; - } - - private TextureRegion getAtlasRegion(String src) { - if (mTextureAtlas == null) - return null; - - TextureRegion texture = mTextureAtlas.getTextureRegion(src); - - if (texture == null) - log.debug("missing texture atlas item '" + src + "'"); - - return texture; - } - - private void handleLineElement(String localName, Attributes attributes, boolean isStyle) - throws SAXException { - - String use = attributes.getValue("use"); - LineStyle style = null; - - if (use != null) { - style = (LineStyle) mStyles.get(LINE_STYLE + use); - if (style == null) { - log.debug("missing line style 'use': " + use); - return; - } - } - - LineStyle line = createLine(style, localName, attributes, mLevels++, false); - - if (isStyle) { - mStyles.put(LINE_STYLE + line.style, line); - } else { - mCurrentRule.addStyle(line); - /* Note 'outline' will not be inherited, it's just a - * shorcut to add the outline RenderInstruction. */ - addOutline(attributes.getValue("outline")); - } - } - - /** - * @param line - * optional: line style defaults - * @param level - * the drawing level of this instruction. - * @param isOutline - * is outline layer - * @return a new Line with the given rendering attributes. - */ - private LineStyle createLine(LineStyle line, String elementName, Attributes attributes, - int level, boolean isOutline) { - LineBuilder b = mLineBuilder.set(line); - b.isOutline(isOutline); - b.level(level); - - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("id".equals(name)) - b.style = value; - - else if ("src".equals(name)) - ;// src = value; - - else if ("use".equals(name)) - ;// ignore - - else if ("outline".equals(name)) - ;// ignore - - else if ("stroke".equals(name)) - b.color(value); - - else if ("width".equals(name) || "stroke-width".equals(name)) { - b.strokeWidth = parseFloat(value); - if (line == null) { - if (!isOutline) - validateNonNegative("width", b.strokeWidth); - } else { + static final Logger log = LoggerFactory.getLogger(XmlThemeBuilder.class); + + private static final int RENDER_THEME_VERSION = 1; + + private static enum Element { + RENDER_THEME, RENDERING_INSTRUCTION, RULE, STYLE, ATLAS; + } + + private static final String ELEMENT_NAME_RENDER_THEME = "rendertheme"; + private static final String ELEMENT_NAME_MATCH = "m"; + private static final String UNEXPECTED_ELEMENT = "unexpected element: "; + + //private static final String IMG_PATH = "styles/"; + private static final String IMG_PATH = ""; + + private static final String LINE_STYLE = "L"; + private static final String OUTLINE_STYLE = "O"; + private static final String AREA_STYLE = "A"; + + /** + * @param inputStream an input stream containing valid render theme XML data. + * @return a new RenderTheme which is created by parsing the XML data from + * the input stream. + * @throws ThemeException if an error occurs while parsing the render theme XML. + * @throws IOException if an I/O error occurs while reading from the input stream. + */ + public static IRenderTheme read(InputStream inputStream) + throws ThemeException { + + XmlThemeBuilder renderThemeHandler = new XmlThemeBuilder(); + + try { + new XMLReaderAdapter().parse(renderThemeHandler, inputStream); + } catch (IOException e) { + throw new ThemeException(e.getMessage()); + } + + return renderThemeHandler.mRenderTheme; + } + + /** + * Logs the given information about an unknown XML attribute. + * + * @param element the XML element name. + * @param name the XML attribute name. + * @param value the XML attribute value. + * @param attributeIndex the XML attribute index position. + */ + public static void logUnknownAttribute(String element, String name, + String value, int attributeIndex) { + log.debug("unknown attribute in element {} () : {} = {}", + element, attributeIndex, name, value); + } + + private final ArrayList mRulesList = new ArrayList(); + private final Stack mElementStack = new Stack(); + private final Stack mRuleStack = new Stack(); + private final HashMap mStyles = + new HashMap(10); + + private final HashMap> mTextStyles = + new HashMap>(10); + + private final TextBuilder mTextBuilder = TextStyle.builder(); + private final AreaBuilder mAreaBuilder = AreaStyle.builder(); + private final LineBuilder mLineBuilder = LineStyle.builder(); + + private RuleBuilder mCurrentRule; + private TextureAtlas mTextureAtlas; + + private int mLevels = 0; + private int mMapBackground = 0xffffffff; + private float mTextScale = 1; + + private RenderTheme mRenderTheme; + + @Override + public void endDocument() { + + Rule[] rules = new Rule[mRulesList.size()]; + for (int i = 0, n = rules.length; i < n; i++) + rules[i] = mRulesList.get(i).onComplete(null); + + mRenderTheme = new RenderTheme(mMapBackground, mTextScale, rules, mLevels); + + mRulesList.clear(); + mStyles.clear(); + mRuleStack.clear(); + mElementStack.clear(); + + mTextureAtlas = null; + } + + @Override + public void endElement(String uri, String localName, String qName) { + mElementStack.pop(); + + if (ELEMENT_NAME_MATCH.equals(localName)) { + mRuleStack.pop(); + if (mRuleStack.empty()) { + mRulesList.add(mCurrentRule); + } else { + mCurrentRule = mRuleStack.peek(); + } + } + } + + @Override + public void error(SAXParseException exception) { + log.debug(exception.getMessage()); + } + + @Override + public void warning(SAXParseException exception) { + log.debug(exception.getMessage()); + } + + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws ThemeException { + try { + if (ELEMENT_NAME_RENDER_THEME.equals(localName)) { + checkState(localName, Element.RENDER_THEME); + createRenderTheme(localName, attributes); + + } else if (ELEMENT_NAME_MATCH.equals(localName)) { + checkState(localName, Element.RULE); + RuleBuilder rule = createRule(localName, attributes, mRuleStack); + if (!mRuleStack.empty()) { + mCurrentRule.addSubRule(rule); + } + mCurrentRule = rule; + mRuleStack.push(mCurrentRule); + + } else if ("style-text".equals(localName)) { + checkState(localName, Element.STYLE); + handleTextElement(localName, attributes, true, false); + + } else if ("style-area".equals(localName)) { + checkState(localName, Element.STYLE); + handleAreaElement(localName, attributes, true); + + } else if ("style-line".equals(localName)) { + checkState(localName, Element.STYLE); + handleLineElement(localName, attributes, true); + + } else if ("outline-layer".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + LineStyle line = createLine(null, localName, attributes, mLevels++, true); + mStyles.put(OUTLINE_STYLE + line.style, line); + + } else if ("area".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + handleAreaElement(localName, attributes, false); + + } else if ("caption".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + handleTextElement(localName, attributes, false, true); + + } else if ("circle".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + CircleStyle circle = createCircle(localName, attributes, mLevels++); + mCurrentRule.addStyle(circle); + + } else if ("line".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + handleLineElement(localName, attributes, false); + + } else if ("text".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + handleTextElement(localName, attributes, false, false); + + } else if ("symbol".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + SymbolStyle symbol = createSymbol(localName, attributes); + mCurrentRule.addStyle(symbol); + + } else if ("outline".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + addOutline(attributes.getValue("use")); + + } else if ("extrusion".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + ExtrusionStyle extrusion = createExtrusion(localName, attributes, mLevels++); + mCurrentRule.addStyle(extrusion); + + } else if ("lineSymbol".equals(localName)) { + checkState(localName, Element.RENDERING_INSTRUCTION); + log.error("unknown element: {}", localName); + + } else if ("atlas".equals(localName)) { + checkState(localName, Element.ATLAS); + createAtlas(localName, attributes); + + } else if ("rect".equals(localName)) { + checkState(localName, Element.ATLAS); + createTextureRegion(localName, attributes); + + } else { + log.error("unknown element: {}", localName); + //throw new SAXException("unknown element: " + localName); + } + } catch (SAXException e) { + throw new ThemeException(e.getMessage()); + } catch (IOException e) { + throw new ThemeException(e.getMessage()); + } + } + + private RuleBuilder createRule(String localName, Attributes attributes, + Stack ruleStack) { + int element = Rule.Element.ANY; + int closed = Closed.ANY; + String keys = null; + String values = null; + byte zoomMin = 0; + byte zoomMax = Byte.MAX_VALUE; + int selector = 0; + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("e".equals(name)) { + String val = value.toUpperCase(); + if ("WAY".equals(val)) + element = Rule.Element.WAY; + else if ("NODE".equals(val)) + element = Rule.Element.NODE; + } else if ("k".equals(name)) { + keys = value; + } else if ("v".equals(name)) { + values = value; + } else if ("closed".equals(name)) { + String val = value.toUpperCase(); + if ("YES".equals(val)) + closed = Closed.YES; + else if ("NO".equals(val)) + closed = Closed.NO; + } else if ("zoom-min".equals(name)) { + zoomMin = Byte.parseByte(value); + } else if ("zoom-max".equals(name)) { + zoomMax = Byte.parseByte(value); + } else if ("select".equals(name)) { + if ("first".equals(value)) + selector |= Selector.FIRST; + if ("when-matched".equals(value)) + selector |= Selector.WHEN_MATCHED; + } else { + XmlThemeBuilder.logUnknownAttribute(localName, name, value, i); + } + } + + if (closed == Closed.YES) + element = Rule.Element.POLY; + else if (closed == Closed.NO) + element = Rule.Element.LINE; + + XmlThemeBuilder.validateNonNegative("zoom-min", zoomMin); + XmlThemeBuilder.validateNonNegative("zoom-max", zoomMax); + if (zoomMin > zoomMax) + throw new ThemeException("zoom-min must be less or equal zoom-max: " + zoomMin); + + RuleBuilder b = RuleBuilder.create(keys, values); + b.setZoom(zoomMin, zoomMax); + b.element(element); + b.select(selector); + return b; + } + + private TextureRegion getAtlasRegion(String src) { + if (mTextureAtlas == null) + return null; + + TextureRegion texture = mTextureAtlas.getTextureRegion(src); + + if (texture == null) + log.debug("missing texture atlas item '" + src + "'"); + + return texture; + } + + private void handleLineElement(String localName, Attributes attributes, boolean isStyle) + throws SAXException { + + String use = attributes.getValue("use"); + LineStyle style = null; + + if (use != null) { + style = (LineStyle) mStyles.get(LINE_STYLE + use); + if (style == null) { + log.debug("missing line style 'use': " + use); + return; + } + } + + LineStyle line = createLine(style, localName, attributes, mLevels++, false); + + if (isStyle) { + mStyles.put(LINE_STYLE + line.style, line); + } else { + mCurrentRule.addStyle(line); + /* Note 'outline' will not be inherited, it's just a + * shorcut to add the outline RenderInstruction. */ + addOutline(attributes.getValue("outline")); + } + } + + /** + * @param line optional: line style defaults + * @param level the drawing level of this instruction. + * @param isOutline is outline layer + * @return a new Line with the given rendering attributes. + */ + private LineStyle createLine(LineStyle line, String elementName, Attributes attributes, + int level, boolean isOutline) { + LineBuilder b = mLineBuilder.set(line); + b.isOutline(isOutline); + b.level(level); + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("id".equals(name)) + b.style = value; + + else if ("src".equals(name)) + ;// src = value; + + else if ("use".equals(name)) + ;// ignore + + else if ("outline".equals(name)) + ;// ignore + + else if ("stroke".equals(name)) + b.color(value); + + else if ("width".equals(name) || "stroke-width".equals(name)) { + b.strokeWidth = parseFloat(value); + if (line == null) { + if (!isOutline) + validateNonNegative("width", b.strokeWidth); + } else { /* use stroke width relative to 'line' */ - b.strokeWidth += line.width; - if (b.strokeWidth <= 0) - b.strokeWidth = 1; - } - } - else if ("cap".equals(name) || "stroke-linecap".equals(name)) - b.cap = Cap.valueOf(value.toUpperCase()); + b.strokeWidth += line.width; + if (b.strokeWidth <= 0) + b.strokeWidth = 1; + } + } else if ("cap".equals(name) || "stroke-linecap".equals(name)) + b.cap = Cap.valueOf(value.toUpperCase()); - else if ("fix".equals(name)) - b.fixed = parseBoolean(value); + else if ("fix".equals(name)) + b.fixed = parseBoolean(value); - else if ("stipple".equals(name)) - b.stipple = parseInt(value); + else if ("stipple".equals(name)) + b.stipple = parseInt(value); - else if ("stipple-stroke".equals(name)) - b.stippleColor(value); + else if ("stipple-stroke".equals(name)) + b.stippleColor(value); - else if ("stipple-width".equals(name)) - b.stippleWidth = parseFloat(value); + else if ("stipple-width".equals(name)) + b.stippleWidth = parseFloat(value); - else if ("fade".equals(name)) - b.fadeScale = Integer.parseInt(value); + else if ("fade".equals(name)) + b.fadeScale = Integer.parseInt(value); - else if ("min".equals(name)) - ; //min = Float.parseFloat(value); + else if ("min".equals(name)) + ; //min = Float.parseFloat(value); - else if ("blur".equals(name)) - b.blur = parseFloat(value); - - else if ("style".equals(name)) - ; // ignore - - else if ("dasharray".equals(name)) - ; // TBD - - else - logUnknownAttribute(elementName, name, value, i); - } - return b.build(); - } - - private void handleAreaElement(String localName, Attributes attributes, boolean isStyle) - throws SAXException { - - String use = attributes.getValue("use"); - AreaStyle style = null; - - if (use != null) { - style = (AreaStyle) mStyles.get(AREA_STYLE + use); - if (style == null) { - log.debug("missing area style 'use': " + use); - return; - } - } - - AreaStyle area = createArea(style, localName, attributes, mLevels++); - - if (isStyle) { - mStyles.put(AREA_STYLE + area.style, area); - } else { - mCurrentRule.addStyle(area); - } - } - - /** - * @return a new Area with the given rendering attributes. - */ - private AreaStyle createArea(AreaStyle area, String elementName, Attributes attributes, - int level) { - AreaBuilder b = mAreaBuilder.set(area); - b.level(level); - - String src = null; - - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("id".equals(name)) - b.style = value; - - else if ("use".equals(name)) - ;// ignore - - else if ("src".equals(name)) - src = value; - - else if ("fill".equals(name)) - b.color(value); - - else if ("stroke".equals(name)) - b.strokeColor(value); - - else if ("stroke-width".equals(name)) { - float strokeWidth = Float.parseFloat(value); - validateNonNegative("stroke-width", strokeWidth); - b.strokeWidth = strokeWidth; - - } else if ("fade".equals(name)) - b.fadeScale = Integer.parseInt(value); - - else if ("blend".equals(name)) - b.blendScale = Integer.parseInt(value); - - else if ("blend-fill".equals(name)) - b.blendColor(value); - - else if ("mesh".equals(name)) - b.mesh(Boolean.parseBoolean(value)); - - else - logUnknownAttribute(elementName, name, value, i); - } - - if (src != null) { - try { - Bitmap bitmap = CanvasAdapter.getBitmapAsset(src); - if (bitmap != null) - b.texture = new TextureItem(bitmap, true); - } catch (Exception e) { - log.debug(e.getMessage()); - } - } - return b.build(); - } - - private void addOutline(String style) { - if (style != null) { - LineStyle line = (LineStyle) mStyles.get(OUTLINE_STYLE + style); - if (line != null && line.outline) - mCurrentRule.addStyle(line); - else - log.debug("BUG not an outline style: " + style); - } - } - - private void createAtlas(String elementName, Attributes attributes) throws IOException { - String img = null; - - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("img".equals(name)) { - img = value; - } else { - XmlThemeBuilder.logUnknownAttribute(elementName, name, value, i); - } - } - validateExists("img", img, elementName); - - Bitmap bitmap = CanvasAdapter.getBitmapAsset(IMG_PATH + img); - mTextureAtlas = new TextureAtlas(bitmap); - } - - private void createTextureRegion(String elementName, Attributes attributes) { - String regionName = null; - Rect r = null; - - for (int i = 0, n = attributes.getLength(); i < n; i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("id".equals(name)) { - regionName = value; - } else if ("pos".equals(name)) { - String[] pos = value.split(" "); - if (pos.length == 4) { - r = new Rect(Integer.parseInt(pos[0]), - Integer.parseInt(pos[1]), - Integer.parseInt(pos[2]), - Integer.parseInt(pos[3])); - } - } else { - XmlThemeBuilder.logUnknownAttribute(elementName, name, value, i); - } - } - validateExists("id", regionName, elementName); - validateExists("pos", r, elementName); - - mTextureAtlas.addTextureRegion(regionName.intern(), r); - } - - private void checkElement(String elementName, Element element) throws SAXException { - Element parentElement; - switch (element) { - case RENDER_THEME: - if (!mElementStack.empty()) { - throw new SAXException(UNEXPECTED_ELEMENT + elementName); - } - return; - - case RULE: - parentElement = mElementStack.peek(); - if (parentElement != Element.RENDER_THEME - && parentElement != Element.RULE) { - throw new SAXException(UNEXPECTED_ELEMENT + elementName); - } - return; - - case STYLE: - parentElement = mElementStack.peek(); - if (parentElement != Element.RENDER_THEME) { - throw new SAXException(UNEXPECTED_ELEMENT + elementName); - } - return; - - case RENDERING_INSTRUCTION: - if (mElementStack.peek() != Element.RULE) { - throw new SAXException(UNEXPECTED_ELEMENT + elementName); - } - return; - case ATLAS: - parentElement = mElementStack.peek(); - // FIXME - if (parentElement != Element.RENDER_THEME - && parentElement != Element.ATLAS) { - throw new SAXException(UNEXPECTED_ELEMENT + elementName); - } - return; - } - - throw new SAXException("unknown enum value: " + element); - } - - private void checkState(String elementName, Element element) throws SAXException { - checkElement(elementName, element); - mElementStack.push(element); - } - - private void createRenderTheme(String elementName, Attributes attributes) { - Integer version = null; - int mapBackground = Color.WHITE; - float baseStrokeWidth = 1; - float baseTextScale = 1; - - for (int i = 0; i < attributes.getLength(); ++i) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("schemaLocation".equals(name)) - continue; - - else if ("version".equals(name)) - version = Integer.valueOf(Integer.parseInt(value)); - - else if ("map-background".equals(name)) - mapBackground = Color.parseColor(value); - - else if ("base-stroke-width".equals(name)) - baseStrokeWidth = Float.parseFloat(value); - - else if ("base-text-scale".equals(name)) - baseTextScale = Float.parseFloat(value); - - else - XmlThemeBuilder.logUnknownAttribute(elementName, name, value, i); - - } - - validateExists("version", version, elementName); - - if (version.intValue() != RENDER_THEME_VERSION) - throw new ThemeException("invalid render theme version:" - + version); - - validateNonNegative("base-stroke-width", baseStrokeWidth); - validateNonNegative("base-text-scale", baseTextScale); - - mMapBackground = mapBackground; - mTextScale = baseTextScale; - } - - private void handleTextElement(String localName, Attributes attributes, boolean isStyle, - boolean isCaption) throws SAXException { - - String style = attributes.getValue("use"); - TextBuilder pt = null; - - if (style != null) { - pt = mTextStyles.get(style); - if (pt == null) { - log.debug("missing text style: " + style); - return; - } - } - - TextBuilder b = createText(localName, attributes, isCaption, pt); - if (isStyle) { - log.debug("put style {}", b.style); - mTextStyles.put(b.style, TextStyle.builder().from(b)); - } else { - mCurrentRule.addStyle(b.buildInternal()); - } - } - - /** - * @param caption - * ... - * @return a new Text with the given rendering attributes. - */ - private TextBuilder createText(String elementName, Attributes attributes, - boolean caption, TextBuilder style) { - TextBuilder b; - if (style == null) { - b = mTextBuilder.reset(); - b.caption = caption; - } else - b = mTextBuilder.from(style); - - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("id".equals(name)) - b.style = value; - - else if ("k".equals(name)) - b.textKey = value.intern(); - - else if ("font-family".equals(name)) - b.fontFamily = FontFamily.valueOf(value.toUpperCase()); - - else if ("style".equals(name)) - b.fontStyle = FontStyle.valueOf(value.toUpperCase()); - - else if ("size".equals(name)) - b.fontSize = Float.parseFloat(value); - - else if ("fill".equals(name)) - b.fillColor = Color.parseColor(value); - - else if ("stroke".equals(name)) - b.strokeColor = Color.parseColor(value); - - else if ("stroke-width".equals(name)) - b.strokeWidth = Float.parseFloat(value); - - else if ("caption".equals(name)) - b.caption = Boolean.parseBoolean(value); - - else if ("priority".equals(name)) - b.priority = Integer.parseInt(value); - - else if ("dy".equals(name)) - // NB: minus.. - b.dy = -Float.parseFloat(value); + else if ("blur".equals(name)) + b.blur = parseFloat(value); + + else if ("style".equals(name)) + ; // ignore + + else if ("dasharray".equals(name)) + ; // TBD + + else + logUnknownAttribute(elementName, name, value, i); + } + return b.build(); + } + + private void handleAreaElement(String localName, Attributes attributes, boolean isStyle) + throws SAXException { + + String use = attributes.getValue("use"); + AreaStyle style = null; + + if (use != null) { + style = (AreaStyle) mStyles.get(AREA_STYLE + use); + if (style == null) { + log.debug("missing area style 'use': " + use); + return; + } + } + + AreaStyle area = createArea(style, localName, attributes, mLevels++); + + if (isStyle) { + mStyles.put(AREA_STYLE + area.style, area); + } else { + mCurrentRule.addStyle(area); + } + } + + /** + * @return a new Area with the given rendering attributes. + */ + private AreaStyle createArea(AreaStyle area, String elementName, Attributes attributes, + int level) { + AreaBuilder b = mAreaBuilder.set(area); + b.level(level); + + String src = null; + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("id".equals(name)) + b.style = value; + + else if ("use".equals(name)) + ;// ignore + + else if ("src".equals(name)) + src = value; + + else if ("fill".equals(name)) + b.color(value); + + else if ("stroke".equals(name)) + b.strokeColor(value); + + else if ("stroke-width".equals(name)) { + float strokeWidth = Float.parseFloat(value); + validateNonNegative("stroke-width", strokeWidth); + b.strokeWidth = strokeWidth; + + } else if ("fade".equals(name)) + b.fadeScale = Integer.parseInt(value); + + else if ("blend".equals(name)) + b.blendScale = Integer.parseInt(value); + + else if ("blend-fill".equals(name)) + b.blendColor(value); + + else if ("mesh".equals(name)) + b.mesh(Boolean.parseBoolean(value)); + + else + logUnknownAttribute(elementName, name, value, i); + } + + if (src != null) { + try { + Bitmap bitmap = CanvasAdapter.getBitmapAsset(src); + if (bitmap != null) + b.texture = new TextureItem(bitmap, true); + } catch (Exception e) { + log.debug(e.getMessage()); + } + } + return b.build(); + } + + private void addOutline(String style) { + if (style != null) { + LineStyle line = (LineStyle) mStyles.get(OUTLINE_STYLE + style); + if (line != null && line.outline) + mCurrentRule.addStyle(line); + else + log.debug("BUG not an outline style: " + style); + } + } + + private void createAtlas(String elementName, Attributes attributes) throws IOException { + String img = null; + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("img".equals(name)) { + img = value; + } else { + XmlThemeBuilder.logUnknownAttribute(elementName, name, value, i); + } + } + validateExists("img", img, elementName); + + Bitmap bitmap = CanvasAdapter.getBitmapAsset(IMG_PATH + img); + mTextureAtlas = new TextureAtlas(bitmap); + } + + private void createTextureRegion(String elementName, Attributes attributes) { + String regionName = null; + Rect r = null; + + for (int i = 0, n = attributes.getLength(); i < n; i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("id".equals(name)) { + regionName = value; + } else if ("pos".equals(name)) { + String[] pos = value.split(" "); + if (pos.length == 4) { + r = new Rect(Integer.parseInt(pos[0]), + Integer.parseInt(pos[1]), + Integer.parseInt(pos[2]), + Integer.parseInt(pos[3])); + } + } else { + XmlThemeBuilder.logUnknownAttribute(elementName, name, value, i); + } + } + validateExists("id", regionName, elementName); + validateExists("pos", r, elementName); + + mTextureAtlas.addTextureRegion(regionName.intern(), r); + } + + private void checkElement(String elementName, Element element) throws SAXException { + Element parentElement; + switch (element) { + case RENDER_THEME: + if (!mElementStack.empty()) { + throw new SAXException(UNEXPECTED_ELEMENT + elementName); + } + return; + + case RULE: + parentElement = mElementStack.peek(); + if (parentElement != Element.RENDER_THEME + && parentElement != Element.RULE) { + throw new SAXException(UNEXPECTED_ELEMENT + elementName); + } + return; + + case STYLE: + parentElement = mElementStack.peek(); + if (parentElement != Element.RENDER_THEME) { + throw new SAXException(UNEXPECTED_ELEMENT + elementName); + } + return; + + case RENDERING_INSTRUCTION: + if (mElementStack.peek() != Element.RULE) { + throw new SAXException(UNEXPECTED_ELEMENT + elementName); + } + return; + case ATLAS: + parentElement = mElementStack.peek(); + // FIXME + if (parentElement != Element.RENDER_THEME + && parentElement != Element.ATLAS) { + throw new SAXException(UNEXPECTED_ELEMENT + elementName); + } + return; + } + + throw new SAXException("unknown enum value: " + element); + } + + private void checkState(String elementName, Element element) throws SAXException { + checkElement(elementName, element); + mElementStack.push(element); + } + + private void createRenderTheme(String elementName, Attributes attributes) { + Integer version = null; + int mapBackground = Color.WHITE; + float baseStrokeWidth = 1; + float baseTextScale = 1; + + for (int i = 0; i < attributes.getLength(); ++i) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("schemaLocation".equals(name)) + continue; + + else if ("version".equals(name)) + version = Integer.valueOf(Integer.parseInt(value)); + + else if ("map-background".equals(name)) + mapBackground = Color.parseColor(value); + + else if ("base-stroke-width".equals(name)) + baseStrokeWidth = Float.parseFloat(value); + + else if ("base-text-scale".equals(name)) + baseTextScale = Float.parseFloat(value); + + else + XmlThemeBuilder.logUnknownAttribute(elementName, name, value, i); + + } + + validateExists("version", version, elementName); + + if (version.intValue() != RENDER_THEME_VERSION) + throw new ThemeException("invalid render theme version:" + + version); + + validateNonNegative("base-stroke-width", baseStrokeWidth); + validateNonNegative("base-text-scale", baseTextScale); + + mMapBackground = mapBackground; + mTextScale = baseTextScale; + } + + private void handleTextElement(String localName, Attributes attributes, boolean isStyle, + boolean isCaption) throws SAXException { + + String style = attributes.getValue("use"); + TextBuilder pt = null; + + if (style != null) { + pt = mTextStyles.get(style); + if (pt == null) { + log.debug("missing text style: " + style); + return; + } + } + + TextBuilder b = createText(localName, attributes, isCaption, pt); + if (isStyle) { + log.debug("put style {}", b.style); + mTextStyles.put(b.style, TextStyle.builder().from(b)); + } else { + mCurrentRule.addStyle(b.buildInternal()); + } + } + + /** + * @param caption ... + * @return a new Text with the given rendering attributes. + */ + private TextBuilder createText(String elementName, Attributes attributes, + boolean caption, TextBuilder style) { + TextBuilder b; + if (style == null) { + b = mTextBuilder.reset(); + b.caption = caption; + } else + b = mTextBuilder.from(style); + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("id".equals(name)) + b.style = value; + + else if ("k".equals(name)) + b.textKey = value.intern(); + + else if ("font-family".equals(name)) + b.fontFamily = FontFamily.valueOf(value.toUpperCase()); - else if ("symbol".equals(name)) - b.texture = getAtlasRegion(value); - else if ("use".equals(name)) - ;/* ignore */ - else - logUnknownAttribute(elementName, name, value, i); - } - - validateExists("k", b.textKey, elementName); - validateNonNegative("size", b.fontSize); - validateNonNegative("stroke-width", b.strokeWidth); - - return b; - } - - /** - * @param level - * the drawing level of this instruction. - * @return a new Circle with the given rendering attributes. - */ - private static CircleStyle createCircle(String elementName, Attributes attributes, int level) { - Float radius = null; - boolean scaleRadius = false; - int fill = Color.TRANSPARENT; - int stroke = Color.TRANSPARENT; - float strokeWidth = 0; - - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("r".equals(name) || "radius".equals(name)) - radius = Float.valueOf(Float.parseFloat(value)); - - else if ("scale-radius".equals(name)) - scaleRadius = Boolean.parseBoolean(value); - - else if ("fill".equals(name)) - fill = Color.parseColor(value); - - else if ("stroke".equals(name)) - stroke = Color.parseColor(value); - - else if ("stroke-width".equals(name)) - strokeWidth = Float.parseFloat(value); - - else - logUnknownAttribute(elementName, name, value, i); - } - - validateExists("radius", radius, elementName); - validateNonNegative("radius", radius); - validateNonNegative("stroke-width", strokeWidth); - - return new CircleStyle(radius, scaleRadius, fill, stroke, strokeWidth, level); - } + else if ("style".equals(name)) + b.fontStyle = FontStyle.valueOf(value.toUpperCase()); - /** - * @return a new Symbol with the given rendering attributes. - */ - private SymbolStyle createSymbol(String elementName, Attributes attributes) { - String src = null; + else if ("size".equals(name)) + b.fontSize = Float.parseFloat(value); + + else if ("fill".equals(name)) + b.fillColor = Color.parseColor(value); + + else if ("stroke".equals(name)) + b.strokeColor = Color.parseColor(value); - for (int i = 0; i < attributes.getLength(); i++) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); + else if ("stroke-width".equals(name)) + b.strokeWidth = Float.parseFloat(value); - if ("src".equals(name)) - src = value; - else - logUnknownAttribute(elementName, name, value, i); - } + else if ("caption".equals(name)) + b.caption = Boolean.parseBoolean(value); - validateExists("src", src, elementName); + else if ("priority".equals(name)) + b.priority = Integer.parseInt(value); - return new SymbolStyle(getAtlasRegion(src)); - } + else if ("dy".equals(name)) + // NB: minus.. + b.dy = -Float.parseFloat(value); - private ExtrusionStyle createExtrusion(String elementName, Attributes attributes, int level) { - int colorSide = 0; - int colorTop = 0; - int colorLine = 0; - int defaultHeight = 0; + else if ("symbol".equals(name)) + b.texture = getAtlasRegion(value); + else if ("use".equals(name)) + ;/* ignore */ + else + logUnknownAttribute(elementName, name, value, i); + } - for (int i = 0; i < attributes.getLength(); ++i) { - String name = attributes.getLocalName(i); - String value = attributes.getValue(i); - - if ("side-color".equals(name)) - colorSide = Color.parseColor(value); - - else if ("top-color".equals(name)) - colorTop = Color.parseColor(value); - - else if ("line-color".equals(name)) - colorLine = Color.parseColor(value); - - else if ("default-height".equals(name)) - defaultHeight = Integer.parseInt(value); - - else - logUnknownAttribute(elementName, name, value, i); - } - - return new ExtrusionStyle(level, colorSide, colorTop, colorLine, defaultHeight); - } - - public static void validateNonNegative(String name, float value) { - if (value < 0) - throw new ThemeException(name + " must not be negative: " - + value); - } - - public static void validateExists(String name, Object obj, String elementName) { - if (obj == null) - throw new ThemeException("missing attribute " + name - + " for element: " + elementName); - } + validateExists("k", b.textKey, elementName); + validateNonNegative("size", b.fontSize); + validateNonNegative("stroke-width", b.strokeWidth); + + return b; + } + + /** + * @param level the drawing level of this instruction. + * @return a new Circle with the given rendering attributes. + */ + private static CircleStyle createCircle(String elementName, Attributes attributes, int level) { + Float radius = null; + boolean scaleRadius = false; + int fill = Color.TRANSPARENT; + int stroke = Color.TRANSPARENT; + float strokeWidth = 0; + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("r".equals(name) || "radius".equals(name)) + radius = Float.valueOf(Float.parseFloat(value)); + + else if ("scale-radius".equals(name)) + scaleRadius = Boolean.parseBoolean(value); + + else if ("fill".equals(name)) + fill = Color.parseColor(value); + + else if ("stroke".equals(name)) + stroke = Color.parseColor(value); + + else if ("stroke-width".equals(name)) + strokeWidth = Float.parseFloat(value); + + else + logUnknownAttribute(elementName, name, value, i); + } + + validateExists("radius", radius, elementName); + validateNonNegative("radius", radius); + validateNonNegative("stroke-width", strokeWidth); + + return new CircleStyle(radius, scaleRadius, fill, stroke, strokeWidth, level); + } + + /** + * @return a new Symbol with the given rendering attributes. + */ + private SymbolStyle createSymbol(String elementName, Attributes attributes) { + String src = null; + + for (int i = 0; i < attributes.getLength(); i++) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("src".equals(name)) + src = value; + else + logUnknownAttribute(elementName, name, value, i); + } + + validateExists("src", src, elementName); + + return new SymbolStyle(getAtlasRegion(src)); + } + + private ExtrusionStyle createExtrusion(String elementName, Attributes attributes, int level) { + int colorSide = 0; + int colorTop = 0; + int colorLine = 0; + int defaultHeight = 0; + + for (int i = 0; i < attributes.getLength(); ++i) { + String name = attributes.getLocalName(i); + String value = attributes.getValue(i); + + if ("side-color".equals(name)) + colorSide = Color.parseColor(value); + + else if ("top-color".equals(name)) + colorTop = Color.parseColor(value); + + else if ("line-color".equals(name)) + colorLine = Color.parseColor(value); + + else if ("default-height".equals(name)) + defaultHeight = Integer.parseInt(value); + + else + logUnknownAttribute(elementName, name, value, i); + } + + return new ExtrusionStyle(level, colorSide, colorTop, colorLine, defaultHeight); + } + + public static void validateNonNegative(String name, float value) { + if (value < 0) + throw new ThemeException(name + " must not be negative: " + + value); + } + + public static void validateExists(String name, Object obj, String elementName) { + if (obj == null) + throw new ThemeException("missing attribute " + name + + " for element: " + elementName); + } } diff --git a/vtm/src/org/oscim/theme/rule/Rule.java b/vtm/src/org/oscim/theme/rule/Rule.java index df1b37ad..68f2fdcc 100644 --- a/vtm/src/org/oscim/theme/rule/Rule.java +++ b/vtm/src/org/oscim/theme/rule/Rule.java @@ -16,272 +16,272 @@ */ package org.oscim.theme.rule; -import java.util.List; - import org.oscim.core.Tag; import org.oscim.theme.rule.RuleBuilder.RuleType; import org.oscim.theme.styles.RenderStyle; +import java.util.List; + public class Rule { - public final class Element { - public static final int NODE = 1 << 0; - public static final int LINE = 1 << 1; - public static final int POLY = 1 << 2; - public static final int WAY = LINE | POLY; - public static final int ANY = NODE | WAY; - } + public final class Element { + public static final int NODE = 1 << 0; + public static final int LINE = 1 << 1; + public static final int POLY = 1 << 2; + public static final int WAY = LINE | POLY; + public static final int ANY = NODE | WAY; + } - public final class Closed { - public static final int NO = 1 << 0; - public static final int YES = 1 << 1; - public static final int ANY = NO | YES; - } + public final class Closed { + public static final int NO = 1 << 0; + public static final int YES = 1 << 1; + public static final int ANY = NO | YES; + } - public final class Selector { - public static final int ANY = 0; - public static final int FIRST = 1 << 0; - public static final int WHEN_MATCHED = 1 << 1; - } + public final class Selector { + public static final int ANY = 0; + public static final int FIRST = 1 << 0; + public static final int WHEN_MATCHED = 1 << 1; + } - public final static RenderStyle[] EMPTY_STYLE = new RenderStyle[0]; - public final static Rule[] EMPTY_RULES = new Rule[0]; + public final static RenderStyle[] EMPTY_STYLE = new RenderStyle[0]; + public final static Rule[] EMPTY_RULES = new Rule[0]; - public final Rule[] subRules; - public final RenderStyle[] styles; + public final Rule[] subRules; + public final RenderStyle[] styles; - public final int zoom; - public final int element; - public final boolean selectFirstMatch; - public final boolean selectWhenMatched; + public final int zoom; + public final int element; + public final boolean selectFirstMatch; + public final boolean selectWhenMatched; - Rule(int element, int zoom, int selector, Rule[] subRules, RenderStyle[] styles) { - this.element = element; - this.zoom = zoom; + Rule(int element, int zoom, int selector, Rule[] subRules, RenderStyle[] styles) { + this.element = element; + this.zoom = zoom; - this.subRules = (subRules == null) ? EMPTY_RULES : subRules; - this.styles = (styles == null) ? EMPTY_STYLE : styles; + this.subRules = (subRules == null) ? EMPTY_RULES : subRules; + this.styles = (styles == null) ? EMPTY_STYLE : styles; - selectFirstMatch = (selector & Selector.FIRST) != 0; - selectWhenMatched = (selector & Selector.WHEN_MATCHED) != 0; - } + selectFirstMatch = (selector & Selector.FIRST) != 0; + selectWhenMatched = (selector & Selector.WHEN_MATCHED) != 0; + } - public boolean matchesTags(Tag[] tags) { - return true; - } + public boolean matchesTags(Tag[] tags) { + return true; + } - public boolean matchElement(int type, Tag[] tags, int zoomLevel, List result) { - if (((element & type) == 0) || ((zoom & zoomLevel) == 0) || !matchesTags(tags)) - return false; + public boolean matchElement(int type, Tag[] tags, int zoomLevel, List result) { + if (((element & type) == 0) || ((zoom & zoomLevel) == 0) || !matchesTags(tags)) + return false; - boolean matched = false; - if (subRules != EMPTY_RULES) { - if (selectFirstMatch) { - /* only add first matching rule and when-matched rules iff a - * previous rule matched */ - for (Rule r : subRules) { + boolean matched = false; + if (subRules != EMPTY_RULES) { + if (selectFirstMatch) { + /* only add first matching rule and when-matched rules iff a + * previous rule matched */ + for (Rule r : subRules) { /* continue if matched xor selectWhenMatch */ - if (matched ^ r.selectWhenMatched) - continue; + if (matched ^ r.selectWhenMatched) + continue; - if (r.matchElement(type, tags, zoomLevel, result)) - matched = true; - } - } else { + if (r.matchElement(type, tags, zoomLevel, result)) + matched = true; + } + } else { /* add all rules and when-matched rules iff a previous rule * matched */ - for (Rule r : subRules) { - if (r.selectWhenMatched && !matched) - continue; + for (Rule r : subRules) { + if (r.selectWhenMatched && !matched) + continue; - if (r.matchElement(type, tags, zoomLevel, result)) - matched = true; - } - } - } + if (r.matchElement(type, tags, zoomLevel, result)) + matched = true; + } + } + } - if (styles == EMPTY_STYLE) + if (styles == EMPTY_STYLE) /* matched if styles where added */ - return matched; + return matched; /* add instructions for this rule */ - for (RenderStyle ri : styles) - result.add(ri); + for (RenderStyle ri : styles) + result.add(ri); /* this rule did match */ - return true; - } + return true; + } - public void dispose() { - for (RenderStyle ri : styles) - ri.dispose(); + public void dispose() { + for (RenderStyle ri : styles) + ri.dispose(); - for (Rule subRule : subRules) - subRule.dispose(); - } + for (Rule subRule : subRules) + subRule.dispose(); + } - public void scaleTextSize(float scaleFactor) { - for (RenderStyle ri : styles) - ri.scaleTextSize(scaleFactor); + public void scaleTextSize(float scaleFactor) { + for (RenderStyle ri : styles) + ri.scaleTextSize(scaleFactor); - for (Rule subRule : subRules) - subRule.scaleTextSize(scaleFactor); - } + for (Rule subRule : subRules) + subRule.scaleTextSize(scaleFactor); + } - public void updateStyles() { - for (RenderStyle ri : styles) - ri.update(); + public void updateStyles() { + for (RenderStyle ri : styles) + ri.update(); - for (Rule subRule : subRules) - subRule.updateStyles(); - } + for (Rule subRule : subRules) + subRule.updateStyles(); + } - public static class RuleVisitor { - public void apply(Rule r) { - for (Rule subRule : r.subRules) - this.apply(subRule); - } - } + public static class RuleVisitor { + public void apply(Rule r) { + for (Rule subRule : r.subRules) + this.apply(subRule); + } + } - public static class TextSizeVisitor extends RuleVisitor { - float scaleFactor = 1; + public static class TextSizeVisitor extends RuleVisitor { + float scaleFactor = 1; - public void setScaleFactor(float scaleFactor) { - this.scaleFactor = scaleFactor; - } + public void setScaleFactor(float scaleFactor) { + this.scaleFactor = scaleFactor; + } - @Override - public void apply(Rule r) { - for (RenderStyle ri : r.styles) - ri.scaleTextSize(scaleFactor); - super.apply(r); - } - } + @Override + public void apply(Rule r) { + for (RenderStyle ri : r.styles) + ri.scaleTextSize(scaleFactor); + super.apply(r); + } + } - public static class UpdateVisitor extends RuleVisitor { - @Override - public void apply(Rule r) { - for (RenderStyle ri : r.styles) - ri.update(); - super.apply(r); - } - } + public static class UpdateVisitor extends RuleVisitor { + @Override + public void apply(Rule r) { + for (RenderStyle ri : r.styles) + ri.update(); + super.apply(r); + } + } - public void apply(RuleVisitor v) { - v.apply(this); - } + public void apply(RuleVisitor v) { + v.apply(this); + } - static class PositiveRuleK extends Rule { - private final String mKey; + static class PositiveRuleK extends Rule { + private final String mKey; - PositiveRuleK(int element, int zoom, int selector, String key, - Rule[] subRules, RenderStyle[] styles) { + PositiveRuleK(int element, int zoom, int selector, String key, + Rule[] subRules, RenderStyle[] styles) { - super(element, zoom, selector, subRules, styles); - mKey = key; - } + super(element, zoom, selector, subRules, styles); + mKey = key; + } - @Override - public boolean matchesTags(Tag[] tags) { - for (Tag tag : tags) - if (mKey == tag.key) - return true; + @Override + public boolean matchesTags(Tag[] tags) { + for (Tag tag : tags) + if (mKey == tag.key) + return true; - return false; - } - } + return false; + } + } - static class PositiveRuleV extends Rule { - private final String mValue; + static class PositiveRuleV extends Rule { + private final String mValue; - PositiveRuleV(int element, int zoom, int selector, String value, - Rule[] subRules, RenderStyle[] styles) { - super(element, zoom, selector, subRules, styles); - mValue = value; - } + PositiveRuleV(int element, int zoom, int selector, String value, + Rule[] subRules, RenderStyle[] styles) { + super(element, zoom, selector, subRules, styles); + mValue = value; + } - @Override - public boolean matchesTags(Tag[] tags) { - for (Tag tag : tags) - if (mValue == tag.value) - return true; + @Override + public boolean matchesTags(Tag[] tags) { + for (Tag tag : tags) + if (mValue == tag.value) + return true; - return false; - } - } + return false; + } + } - static class PositiveRuleKV extends Rule { - private final String mKey; - private final String mValue; + static class PositiveRuleKV extends Rule { + private final String mKey; + private final String mValue; - PositiveRuleKV(int element, int zoom, int selector, - String key, String value, - Rule[] subRules, RenderStyle[] styles) { - super(element, zoom, selector, subRules, styles); - mKey = key; - mValue = value; - } + PositiveRuleKV(int element, int zoom, int selector, + String key, String value, + Rule[] subRules, RenderStyle[] styles) { + super(element, zoom, selector, subRules, styles); + mKey = key; + mValue = value; + } - @Override - public boolean matchesTags(Tag[] tags) { - for (Tag tag : tags) - if (mKey == tag.key) - return (mValue == tag.value); + @Override + public boolean matchesTags(Tag[] tags) { + for (Tag tag : tags) + if (mKey == tag.key) + return (mValue == tag.value); - return false; - } - } + return false; + } + } - static class PositiveRuleMultiKV extends Rule { - private final String mKeys[]; - private final String mValues[]; + static class PositiveRuleMultiKV extends Rule { + private final String mKeys[]; + private final String mValues[]; - PositiveRuleMultiKV(int element, int zoom, int selector, - String keys[], String values[], - Rule[] subRules, RenderStyle[] styles) { + PositiveRuleMultiKV(int element, int zoom, int selector, + String keys[], String values[], + Rule[] subRules, RenderStyle[] styles) { - super(element, zoom, selector, subRules, styles); - if (keys.length == 0) - mKeys = null; - else - mKeys = keys; + super(element, zoom, selector, subRules, styles); + if (keys.length == 0) + mKeys = null; + else + mKeys = keys; - if (values.length == 0) - mValues = null; - else - mValues = values; - } + if (values.length == 0) + mValues = null; + else + mValues = values; + } - @Override - public boolean matchesTags(Tag[] tags) { - if (mKeys == null) { - for (Tag tag : tags) { - for (String value : mValues) { - if (value == tag.value) - return true; - } - } - return false; - } + @Override + public boolean matchesTags(Tag[] tags) { + if (mKeys == null) { + for (Tag tag : tags) { + for (String value : mValues) { + if (value == tag.value) + return true; + } + } + return false; + } - for (Tag tag : tags) - for (String key : mKeys) { - if (key == tag.key) { - if (mValues == null) - return true; + for (Tag tag : tags) + for (String key : mKeys) { + if (key == tag.key) { + if (mValues == null) + return true; - for (String value : mValues) { - if (value == tag.value) - return true; - } - } - } - return false; - } - } + for (String value : mValues) { + if (value == tag.value) + return true; + } + } + } + return false; + } + } - static class NegativeRule extends Rule { - public final String[] keys; - public final String[] values; + static class NegativeRule extends Rule { + public final String[] keys; + public final String[] values; /* (-) 'exclusive negation' matches when either KEY is not present * or KEY is present and any VALUE is NOT present @@ -293,42 +293,42 @@ public class Rule { * (~) 'non-exclusive negation' matches when either KEY is not present * or KEY is present and any VALUE is present */ - public final boolean exclusive; + public final boolean exclusive; - NegativeRule(RuleType type, int element, int zoom, int selector, - String[] keys, String[] values, - Rule[] subRules, RenderStyle[] styles) { - super(element, zoom, selector, subRules, styles); + NegativeRule(RuleType type, int element, int zoom, int selector, + String[] keys, String[] values, + Rule[] subRules, RenderStyle[] styles) { + super(element, zoom, selector, subRules, styles); - this.keys = keys; - this.values = values; - this.exclusive = type == RuleType.EXCLUDE; - } + this.keys = keys; + this.values = values; + this.exclusive = type == RuleType.EXCLUDE; + } - @Override - public boolean matchesTags(Tag[] tags) { - if (!containsKeys(tags)) - return true; + @Override + public boolean matchesTags(Tag[] tags) { + if (!containsKeys(tags)) + return true; - for (Tag tag : tags) - for (String value : values) - if (value == tag.value) - return !exclusive; + for (Tag tag : tags) + for (String value : values) + if (value == tag.value) + return !exclusive; - return exclusive; - } + return exclusive; + } - private boolean containsKeys(Tag[] tags) { - for (Tag tag : tags) - for (String key : keys) - if (key == tag.key) - return true; + private boolean containsKeys(Tag[] tags) { + for (Tag tag : tags) + for (String key : keys) + if (key == tag.key) + return true; - return false; - } - } + return false; + } + } - public static RuleBuilder builder() { - return new RuleBuilder(); - } + public static RuleBuilder builder() { + return new RuleBuilder(); + } } diff --git a/vtm/src/org/oscim/theme/rule/RuleBuilder.java b/vtm/src/org/oscim/theme/rule/RuleBuilder.java index 4e5c1cb8..d9ec7f2d 100644 --- a/vtm/src/org/oscim/theme/rule/RuleBuilder.java +++ b/vtm/src/org/oscim/theme/rule/RuleBuilder.java @@ -16,8 +16,6 @@ */ package org.oscim.theme.rule; -import java.util.ArrayList; - import org.oscim.theme.IRenderTheme.ThemeException; import org.oscim.theme.rule.Rule.Element; import org.oscim.theme.rule.Rule.NegativeRule; @@ -30,192 +28,194 @@ import org.oscim.theme.styles.RenderStyle.StyleBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; + public class RuleBuilder { - final static Logger log = LoggerFactory.getLogger(RuleBuilder.class); + final static Logger log = LoggerFactory.getLogger(RuleBuilder.class); - private final static String[] EMPTY_KV = {}; + private final static String[] EMPTY_KV = {}; - public enum RuleType { - POSITIVE, - NEGATIVE, - EXCLUDE - } + public enum RuleType { + POSITIVE, + NEGATIVE, + EXCLUDE + } - int zoom; - int element; - int selector; - RuleType type; + int zoom; + int element; + int selector; + RuleType type; - String keys[]; - String values[]; + String keys[]; + String values[]; - ArrayList renderStyles = new ArrayList(4); - ArrayList subRules = new ArrayList(4); - StyleBuilder[] styleBuilder; + ArrayList renderStyles = new ArrayList(4); + ArrayList subRules = new ArrayList(4); + StyleBuilder[] styleBuilder; - private static final String STRING_NEGATION = "~"; - private static final String STRING_EXCLUSIVE = "-"; - private static final String SEPARATOR = "\\|"; + private static final String STRING_NEGATION = "~"; + private static final String STRING_EXCLUSIVE = "-"; + private static final String SEPARATOR = "\\|"; - //private static final String STRING_WILDCARD = "*"; + //private static final String STRING_WILDCARD = "*"; - public RuleBuilder(RuleType type, int element, int zoom, int selector, - String[] keys, String[] values) { - this.type = type; - this.element = element; - this.zoom = zoom; - this.selector = selector; - this.keys = keys; - this.values = values; - } + public RuleBuilder(RuleType type, int element, int zoom, int selector, + String[] keys, String[] values) { + this.type = type; + this.element = element; + this.zoom = zoom; + this.selector = selector; + this.keys = keys; + this.values = values; + } - public RuleBuilder(RuleType type, String[] keys, String[] values) { - this.element = Element.ANY; - this.zoom = ~0; - this.type = type; - this.keys = keys; - this.values = values; - } + public RuleBuilder(RuleType type, String[] keys, String[] values) { + this.element = Element.ANY; + this.zoom = ~0; + this.type = type; + this.keys = keys; + this.values = values; + } - public RuleBuilder() { - this.type = RuleType.POSITIVE; - this.element = Element.ANY; - this.zoom = ~0; - this.keys = EMPTY_KV; - this.values = EMPTY_KV; - } + public RuleBuilder() { + this.type = RuleType.POSITIVE; + this.element = Element.ANY; + this.zoom = ~0; + this.keys = EMPTY_KV; + this.values = EMPTY_KV; + } - public static RuleBuilder create(String keys, String values) { + public static RuleBuilder create(String keys, String values) { - String[] keyList = EMPTY_KV; - String[] valueList = EMPTY_KV; - RuleType type = RuleType.POSITIVE; + String[] keyList = EMPTY_KV; + String[] valueList = EMPTY_KV; + RuleType type = RuleType.POSITIVE; - if (values != null) { - if (values.startsWith(STRING_NEGATION)) { - type = RuleType.NEGATIVE; - if (values.length() > 2) - valueList = values.substring(2) - .split(SEPARATOR); - } else if (values.startsWith(STRING_EXCLUSIVE)) { - type = RuleType.EXCLUDE; - if (values.length() > 2) - valueList = values.substring(2) - .split(SEPARATOR); - } else { - valueList = values.split(SEPARATOR); - } - } + if (values != null) { + if (values.startsWith(STRING_NEGATION)) { + type = RuleType.NEGATIVE; + if (values.length() > 2) + valueList = values.substring(2) + .split(SEPARATOR); + } else if (values.startsWith(STRING_EXCLUSIVE)) { + type = RuleType.EXCLUDE; + if (values.length() > 2) + valueList = values.substring(2) + .split(SEPARATOR); + } else { + valueList = values.split(SEPARATOR); + } + } - if (keys != null) { - keyList = keys.split(SEPARATOR); - } + if (keys != null) { + keyList = keys.split(SEPARATOR); + } - if (type != RuleType.POSITIVE) { - if (keyList == null || keyList.length == 0) - throw new ThemeException("negative rule requires key"); - } + if (type != RuleType.POSITIVE) { + if (keyList == null || keyList.length == 0) + throw new ThemeException("negative rule requires key"); + } - return new RuleBuilder(type, keyList, valueList); - } + return new RuleBuilder(type, keyList, valueList); + } - public RuleBuilder setZoom(byte zoomMin, byte zoomMax) { - // zoom-level bitmask - zoom = 0; - for (int z = zoomMin; z <= zoomMax && z < 32; z++) - zoom |= (1 << z); + public RuleBuilder setZoom(byte zoomMin, byte zoomMax) { + // zoom-level bitmask + zoom = 0; + for (int z = zoomMin; z <= zoomMax && z < 32; z++) + zoom |= (1 << z); - return this; - } + return this; + } - public Rule onComplete(int[] level) { + public Rule onComplete(int[] level) { - RenderStyle[] styles = null; - Rule[] rules = null; + RenderStyle[] styles = null; + Rule[] rules = null; - if (styleBuilder != null) - for (StyleBuilder style : styleBuilder) { - renderStyles.add(style.level(level[0]).build()); - level[0] += 2; - } + if (styleBuilder != null) + for (StyleBuilder style : styleBuilder) { + renderStyles.add(style.level(level[0]).build()); + level[0] += 2; + } - if (renderStyles.size() > 0) { - styles = new RenderStyle[renderStyles.size()]; - renderStyles.toArray(styles); - } + if (renderStyles.size() > 0) { + styles = new RenderStyle[renderStyles.size()]; + renderStyles.toArray(styles); + } - if (subRules.size() > 0) { - rules = new Rule[subRules.size()]; - for (int i = 0; i < rules.length; i++) - rules[i] = subRules.get(i).onComplete(level); - } + if (subRules.size() > 0) { + rules = new Rule[subRules.size()]; + for (int i = 0; i < rules.length; i++) + rules[i] = subRules.get(i).onComplete(level); + } - int numKeys = keys.length; - int numVals = values.length; + int numKeys = keys.length; + int numVals = values.length; - if (numKeys == 0 && numVals == 0) - return new Rule(element, zoom, selector, rules, styles); + if (numKeys == 0 && numVals == 0) + return new Rule(element, zoom, selector, rules, styles); - for (int i = 0; i < numVals; i++) - values[i] = values[i].intern(); + for (int i = 0; i < numVals; i++) + values[i] = values[i].intern(); - for (int i = 0; i < numKeys; i++) - keys[i] = keys[i].intern(); + for (int i = 0; i < numKeys; i++) + keys[i] = keys[i].intern(); - if (type != RuleType.POSITIVE) - return new NegativeRule(type, element, zoom, selector, - keys, values, rules, styles); + if (type != RuleType.POSITIVE) + return new NegativeRule(type, element, zoom, selector, + keys, values, rules, styles); - if (numKeys == 1 && numKeys == 0) - return new PositiveRuleK(element, zoom, selector, keys[0], - rules, styles); + if (numKeys == 1 && numKeys == 0) + return new PositiveRuleK(element, zoom, selector, keys[0], + rules, styles); - if (numKeys == 0 && numVals == 1) - return new PositiveRuleV(element, zoom, selector, values[0], - rules, styles); + if (numKeys == 0 && numVals == 1) + return new PositiveRuleV(element, zoom, selector, values[0], + rules, styles); - if (numKeys == 1 && numVals == 1) - return new PositiveRuleKV(element, zoom, selector, - keys[0], values[0], rules, styles); + if (numKeys == 1 && numVals == 1) + return new PositiveRuleKV(element, zoom, selector, + keys[0], values[0], rules, styles); - return new PositiveRuleMultiKV(element, zoom, selector, - keys, values, rules, styles); + return new PositiveRuleMultiKV(element, zoom, selector, + keys, values, rules, styles); - } + } - public RuleBuilder addStyle(RenderStyle style) { - renderStyles.add(style); - return this; - } + public RuleBuilder addStyle(RenderStyle style) { + renderStyles.add(style); + return this; + } - public RuleBuilder addSubRule(RuleBuilder rule) { - subRules.add(rule); - return this; - } + public RuleBuilder addSubRule(RuleBuilder rule) { + subRules.add(rule); + return this; + } - public RuleBuilder style(StyleBuilder... styles) { - styleBuilder = styles; - return this; - } + public RuleBuilder style(StyleBuilder... styles) { + styleBuilder = styles; + return this; + } - public RuleBuilder rules(RuleBuilder... rules) { - for (RuleBuilder rule : rules) - subRules.add(rule); - return this; - } + public RuleBuilder rules(RuleBuilder... rules) { + for (RuleBuilder rule : rules) + subRules.add(rule); + return this; + } - public RuleBuilder select(int selector) { - this.selector = selector; - return this; - } + public RuleBuilder select(int selector) { + this.selector = selector; + return this; + } - public RuleBuilder zoom(int zoom) { - this.zoom = zoom; - return this; - } + public RuleBuilder zoom(int zoom) { + this.zoom = zoom; + return this; + } - public RuleBuilder element(int element) { - this.element = element; - return this; - } + public RuleBuilder element(int element) { + this.element = element; + return this; + } } diff --git a/vtm/src/org/oscim/theme/styles/AreaStyle.java b/vtm/src/org/oscim/theme/styles/AreaStyle.java index 684a1715..ca719119 100644 --- a/vtm/src/org/oscim/theme/styles/AreaStyle.java +++ b/vtm/src/org/oscim/theme/styles/AreaStyle.java @@ -17,205 +17,223 @@ */ package org.oscim.theme.styles; -import static org.oscim.backend.canvas.Color.parseColor; - import org.oscim.backend.canvas.Color; import org.oscim.renderer.bucket.TextureItem; import org.oscim.utils.FastMath; +import static org.oscim.backend.canvas.Color.parseColor; + /*TODO * - add custom shaders * - create distance field per tile? */ public class AreaStyle extends RenderStyle { - private static final float FADE_START = 0.25f; + private static final float FADE_START = 0.25f; - /** Drawing order level */ - private final int level; + /** + * Drawing order level + */ + private final int level; - /** Style name */ - public final String style; + /** + * Style name + */ + public final String style; - /** Fill color */ - public final int color; + /** + * Fill color + */ + public final int color; - /** Fade-out zoom-level */ - public final int fadeScale; + /** + * Fade-out zoom-level + */ + public final int fadeScale; - /** Fade to blendColor zoom-level */ - public final int blendColor; + /** + * Fade to blendColor zoom-level + */ + public final int blendColor; - /** Blend fill color */ - public final int blendScale; + /** + * Blend fill color + */ + public final int blendScale; - /** Pattern texture */ - public final TextureItem texture; + /** + * Pattern texture + */ + public final TextureItem texture; - /** Outline */ - public final int strokeColor; - public final float strokeWidth; + /** + * Outline + */ + public final int strokeColor; + public final float strokeWidth; - /** Tessellation */ - public final boolean mesh; + /** + * Tessellation + */ + public final boolean mesh; - public AreaStyle(int color) { - this(0, color); - } + public AreaStyle(int color) { + this(0, color); + } - public AreaStyle(int level, int color) { - this.level = level; - this.style = ""; - this.fadeScale = -1; - this.blendColor = 0; - this.blendScale = -1; - this.color = color; - this.texture = null; - this.strokeColor = color; - this.strokeWidth = 1; - this.mesh = false; - } + public AreaStyle(int level, int color) { + this.level = level; + this.style = ""; + this.fadeScale = -1; + this.blendColor = 0; + this.blendScale = -1; + this.color = color; + this.texture = null; + this.strokeColor = color; + this.strokeWidth = 1; + this.mesh = false; + } - public AreaStyle(AreaBuilder b) { - this.level = b.level; - this.style = b.style; - this.fadeScale = b.fadeScale; - this.blendColor = b.blendColor; - this.blendScale = b.blendScale; - this.color = b.fillColor; - this.texture = b.texture; - this.strokeColor = b.strokeColor; - this.strokeWidth = b.strokeWidth; - this.mesh = b.mesh; - } + public AreaStyle(AreaBuilder b) { + this.level = b.level; + this.style = b.style; + this.fadeScale = b.fadeScale; + this.blendColor = b.blendColor; + this.blendScale = b.blendScale; + this.color = b.fillColor; + this.texture = b.texture; + this.strokeColor = b.strokeColor; + this.strokeWidth = b.strokeWidth; + this.mesh = b.mesh; + } - @Override - public AreaStyle current() { - return (AreaStyle) mCurrent; - } + @Override + public AreaStyle current() { + return (AreaStyle) mCurrent; + } - @Override - public void renderWay(Callback cb) { - cb.renderArea(this, level); - } + @Override + public void renderWay(Callback cb) { + cb.renderArea(this, level); + } - public boolean hasAlpha(int zoom) { - if (!Color.isOpaque(color)) - return true; + public boolean hasAlpha(int zoom) { + if (!Color.isOpaque(color)) + return true; - if (texture != null) - return true; + if (texture != null) + return true; - if (blendScale < 0 && fadeScale < 0) - return false; + if (blendScale < 0 && fadeScale < 0) + return false; - if (zoom >= blendScale) { - if (!Color.isOpaque(blendColor)) - return true; - } + if (zoom >= blendScale) { + if (!Color.isOpaque(blendColor)) + return true; + } - if (fadeScale <= zoom) - return true; + if (fadeScale <= zoom) + return true; - return false; - } + return false; + } - public float getFade(double scale) { - if (fadeScale < 0) - return 1; + public float getFade(double scale) { + if (fadeScale < 0) + return 1; - float f = (float) (scale / (1 << fadeScale)) - 1; - return FastMath.clamp(f, FADE_START, 1); - } + float f = (float) (scale / (1 << fadeScale)) - 1; + return FastMath.clamp(f, FADE_START, 1); + } - public float getBlend(double scale) { - if (blendScale < 0) - return 0; + public float getBlend(double scale) { + if (blendScale < 0) + return 0; - float f = (float) (scale / (1 << blendScale)) - 1; - return FastMath.clamp(f, 0, 1); - } + float f = (float) (scale / (1 << blendScale)) - 1; + return FastMath.clamp(f, 0, 1); + } - public static class AreaBuilder> extends StyleBuilder { + public static class AreaBuilder> extends StyleBuilder { - public int fadeScale; - public int blendColor; - public int blendScale; - public boolean mesh; + public int fadeScale; + public int blendColor; + public int blendScale; + public boolean mesh; - public TextureItem texture; + public TextureItem texture; - public AreaBuilder() { - } + public AreaBuilder() { + } - public T set(AreaStyle area) { - if (area == null) - return reset(); + public T set(AreaStyle area) { + if (area == null) + return reset(); - this.level = area.level; - this.style = area.style; - this.fadeScale = area.fadeScale; - this.blendColor = area.blendColor; - this.blendScale = area.blendScale; - this.fillColor = area.color; - this.texture = area.texture; - this.strokeColor = area.strokeColor; - this.strokeWidth = area.strokeWidth; - this.mesh = area.mesh; + this.level = area.level; + this.style = area.style; + this.fadeScale = area.fadeScale; + this.blendColor = area.blendColor; + this.blendScale = area.blendScale; + this.fillColor = area.color; + this.texture = area.texture; + this.strokeColor = area.strokeColor; + this.strokeWidth = area.strokeWidth; + this.mesh = area.mesh; - return self(); - } + return self(); + } - public T blendScale(int zoom) { - this.blendScale = zoom; - return self(); - } + public T blendScale(int zoom) { + this.blendScale = zoom; + return self(); + } - public T blendColor(int color) { - this.blendColor = color; - return self(); - } + public T blendColor(int color) { + this.blendColor = color; + return self(); + } - public T blendColor(String color) { - this.blendColor = parseColor(color); - return self(); - } + public T blendColor(String color) { + this.blendColor = parseColor(color); + return self(); + } - public T texture(TextureItem texture) { - this.texture = texture; - return self(); - } + public T texture(TextureItem texture) { + this.texture = texture; + return self(); + } - public T fadeScale(int zoom) { - this.fadeScale = zoom; - return self(); - } + public T fadeScale(int zoom) { + this.fadeScale = zoom; + return self(); + } - public T mesh(boolean mesh) { - this.mesh = mesh; - return self(); - } + public T mesh(boolean mesh) { + this.mesh = mesh; + return self(); + } - public T reset() { - fillColor = Color.WHITE; - strokeColor = Color.BLACK; - strokeWidth = 0; - fadeScale = -1; - blendScale = -1; - blendColor = Color.TRANSPARENT; - style = null; - texture = null; - mesh = false; - return self(); - } + public T reset() { + fillColor = Color.WHITE; + strokeColor = Color.BLACK; + strokeWidth = 0; + fadeScale = -1; + blendScale = -1; + blendColor = Color.TRANSPARENT; + style = null; + texture = null; + mesh = false; + return self(); + } - public AreaStyle build() { - return new AreaStyle(this); - } - } + public AreaStyle build() { + return new AreaStyle(this); + } + } - @SuppressWarnings("rawtypes") - public static AreaBuilder builder() { - return new AreaBuilder(); - } + @SuppressWarnings("rawtypes") + public static AreaBuilder builder() { + return new AreaBuilder(); + } } diff --git a/vtm/src/org/oscim/theme/styles/CircleStyle.java b/vtm/src/org/oscim/theme/styles/CircleStyle.java index c7dd8d10..e3d51ebc 100644 --- a/vtm/src/org/oscim/theme/styles/CircleStyle.java +++ b/vtm/src/org/oscim/theme/styles/CircleStyle.java @@ -22,36 +22,36 @@ package org.oscim.theme.styles; */ public final class CircleStyle extends RenderStyle { - public final int level; + public final int level; - public final int fill; - public final int outline; - public final float radius; - public float renderRadius; - public final boolean scaleRadius; - public final float strokeWidth; + public final int fill; + public final int outline; + public final float radius; + public float renderRadius; + public final boolean scaleRadius; + public final float strokeWidth; - public CircleStyle(Float radius, boolean scaleRadius, int fill, int stroke, - float strokeWidth, int level) { - super(); + public CircleStyle(Float radius, boolean scaleRadius, int fill, int stroke, + float strokeWidth, int level) { + super(); - this.radius = radius.floatValue(); - this.scaleRadius = scaleRadius; + this.radius = radius.floatValue(); + this.scaleRadius = scaleRadius; - this.fill = fill; - this.outline = stroke; + this.fill = fill; + this.outline = stroke; - this.strokeWidth = strokeWidth; - this.level = level; - } + this.strokeWidth = strokeWidth; + this.level = level; + } - @Override - public void renderNode(Callback cb) { - cb.renderCircle(this, this.level); - } + @Override + public void renderNode(Callback cb) { + cb.renderCircle(this, this.level); + } - @Override - public CircleStyle current() { - return (CircleStyle) mCurrent; - } + @Override + public CircleStyle current() { + return (CircleStyle) mCurrent; + } } diff --git a/vtm/src/org/oscim/theme/styles/ExtrusionStyle.java b/vtm/src/org/oscim/theme/styles/ExtrusionStyle.java index 75f44138..022729b7 100644 --- a/vtm/src/org/oscim/theme/styles/ExtrusionStyle.java +++ b/vtm/src/org/oscim/theme/styles/ExtrusionStyle.java @@ -20,52 +20,52 @@ import org.oscim.backend.canvas.Color; public class ExtrusionStyle extends RenderStyle { - public ExtrusionStyle(int level, int colorSides, int colorTop, int colorLine, int defaultHeight) { + public ExtrusionStyle(int level, int colorSides, int colorTop, int colorLine, int defaultHeight) { - this.colors = new float[16]; - fillColors(colorSides, colorTop, colorLine, colors); + this.colors = new float[16]; + fillColors(colorSides, colorTop, colorLine, colors); - this.defaultHeight = defaultHeight; - this.level = level; - } + this.defaultHeight = defaultHeight; + this.level = level; + } - public static void fillColors(int sides, int top, int lines, float[] colors) { - float a = Color.aToFloat(top); - colors[0] = a * Color.rToFloat(top); - colors[1] = a * Color.gToFloat(top); - colors[2] = a * Color.bToFloat(top); - colors[3] = a; + public static void fillColors(int sides, int top, int lines, float[] colors) { + float a = Color.aToFloat(top); + colors[0] = a * Color.rToFloat(top); + colors[1] = a * Color.gToFloat(top); + colors[2] = a * Color.bToFloat(top); + colors[3] = a; - a = Color.aToFloat(sides); - colors[4] = a * Color.rToFloat(sides); - colors[5] = a * Color.gToFloat(sides); - colors[6] = a * Color.bToFloat(sides); - colors[7] = a; + a = Color.aToFloat(sides); + colors[4] = a * Color.rToFloat(sides); + colors[5] = a * Color.gToFloat(sides); + colors[6] = a * Color.bToFloat(sides); + colors[7] = a; - a = Color.aToFloat(sides); - colors[8] = a * Color.rToFloat(sides); - colors[9] = a * Color.gToFloat(sides); - colors[10] = a * Color.bToFloat(sides); - colors[11] = a; + a = Color.aToFloat(sides); + colors[8] = a * Color.rToFloat(sides); + colors[9] = a * Color.gToFloat(sides); + colors[10] = a * Color.bToFloat(sides); + colors[11] = a; - a = Color.aToFloat(lines); - colors[12] = a * Color.rToFloat(lines); - colors[13] = a * Color.gToFloat(lines); - colors[14] = a * Color.bToFloat(lines); - colors[15] = a; - } + a = Color.aToFloat(lines); + colors[12] = a * Color.rToFloat(lines); + colors[13] = a * Color.gToFloat(lines); + colors[14] = a * Color.bToFloat(lines); + colors[15] = a; + } - @Override - public void renderWay(Callback cb) { - cb.renderExtrusion(this, this.level); - } + @Override + public void renderWay(Callback cb) { + cb.renderExtrusion(this, this.level); + } - @Override - public ExtrusionStyle current() { - return (ExtrusionStyle) mCurrent; - } + @Override + public ExtrusionStyle current() { + return (ExtrusionStyle) mCurrent; + } - private final int level; - public final float[] colors; - public final int defaultHeight; + private final int level; + public final float[] colors; + public final int defaultHeight; } diff --git a/vtm/src/org/oscim/theme/styles/LineStyle.java b/vtm/src/org/oscim/theme/styles/LineStyle.java index 5931e2ea..01dee2e8 100644 --- a/vtm/src/org/oscim/theme/styles/LineStyle.java +++ b/vtm/src/org/oscim/theme/styles/LineStyle.java @@ -17,182 +17,182 @@ */ package org.oscim.theme.styles; -import static org.oscim.backend.canvas.Color.parseColor; - import org.oscim.backend.canvas.Color; import org.oscim.backend.canvas.Paint.Cap; +import static org.oscim.backend.canvas.Color.parseColor; + public final class LineStyle extends RenderStyle { - final int level; - public final String style; - public final float width; - public final int color; - public final Cap cap; - public final boolean outline; - public final boolean fixed; - public final int fadeScale; - public final float blur; + final int level; + public final String style; + public final float width; + public final int color; + public final Cap cap; + public final boolean outline; + public final boolean fixed; + public final int fadeScale; + public final float blur; - public final int stipple; - public final int stippleColor; - public final float stippleWidth; + public final int stipple; + public final int stippleColor; + public final float stippleWidth; - private LineStyle(LineBuilder builer) { - this.level = builer.level; - this.style = builer.style; - this.width = builer.strokeWidth; - this.color = builer.fillColor; - this.cap = builer.cap; - this.outline = builer.outline; - this.fixed = builer.fixed; - this.fadeScale = builer.fadeScale; - this.blur = builer.blur; - this.stipple = builer.stipple; - this.stippleColor = builer.stippleColor; - this.stippleWidth = builer.stippleWidth; - } + private LineStyle(LineBuilder builer) { + this.level = builer.level; + this.style = builer.style; + this.width = builer.strokeWidth; + this.color = builer.fillColor; + this.cap = builer.cap; + this.outline = builer.outline; + this.fixed = builer.fixed; + this.fadeScale = builer.fadeScale; + this.blur = builer.blur; + this.stipple = builer.stipple; + this.stippleColor = builer.stippleColor; + this.stippleWidth = builer.stippleWidth; + } - public LineStyle(int level, String style, int color, float width, - Cap cap, boolean fixed, - int stipple, int stippleColor, float stippleWidth, - int fadeScale, float blur, boolean isOutline) { + public LineStyle(int level, String style, int color, float width, + Cap cap, boolean fixed, + int stipple, int stippleColor, float stippleWidth, + int fadeScale, float blur, boolean isOutline) { - this.level = level; - this.style = style; - this.outline = isOutline; + this.level = level; + this.style = style; + this.outline = isOutline; - this.cap = cap; - this.color = color; - this.width = width; - this.fixed = fixed; + this.cap = cap; + this.color = color; + this.width = width; + this.fixed = fixed; - this.stipple = stipple; - this.stippleColor = stippleColor; - this.stippleWidth = stippleWidth; + this.stipple = stipple; + this.stippleColor = stippleColor; + this.stippleWidth = stippleWidth; - this.blur = blur; - this.fadeScale = fadeScale; - } + this.blur = blur; + this.fadeScale = fadeScale; + } - public LineStyle(int stroke, float width) { - this(0, "", stroke, width, Cap.BUTT, true, 0, 0, 0, -1, 0, false); - } + public LineStyle(int stroke, float width) { + this(0, "", stroke, width, Cap.BUTT, true, 0, 0, 0, -1, 0, false); + } - public LineStyle(int level, int stroke, float width) { - this(level, "", stroke, width, Cap.BUTT, true, 0, 0, 0, -1, 0, false); - } + public LineStyle(int level, int stroke, float width) { + this(level, "", stroke, width, Cap.BUTT, true, 0, 0, 0, -1, 0, false); + } - public LineStyle(int stroke, float width, Cap cap) { - this(0, "", stroke, width, cap, true, 0, 0, 0, -1, 0, false); - } + public LineStyle(int stroke, float width, Cap cap) { + this(0, "", stroke, width, cap, true, 0, 0, 0, -1, 0, false); + } - @Override - public void renderWay(Callback cb) { - cb.renderWay(this, level); - } + @Override + public void renderWay(Callback cb) { + cb.renderWay(this, level); + } - @Override - public LineStyle current() { - return (LineStyle) mCurrent; - } + @Override + public LineStyle current() { + return (LineStyle) mCurrent; + } - public static class LineBuilder> extends StyleBuilder { + public static class LineBuilder> extends StyleBuilder { - public String style; - public Cap cap; - public boolean outline; - public boolean fixed; - public int fadeScale; - public float blur; + public String style; + public Cap cap; + public boolean outline; + public boolean fixed; + public int fadeScale; + public float blur; - public int stipple; - public int stippleColor; - public float stippleWidth; + public int stipple; + public int stippleColor; + public float stippleWidth; - public T set(LineStyle line) { - if (line == null) - return reset(); - this.level = line.level; - this.style = line.style; - this.strokeWidth = line.width; - this.fillColor = line.color; - this.cap = line.cap; - this.outline = line.outline; - this.fixed = line.fixed; - this.fadeScale = line.fadeScale; - this.blur = line.blur; - this.stipple = line.stipple; - this.stippleColor = line.stippleColor; - this.stippleWidth = line.stippleWidth; - return self(); - } + public T set(LineStyle line) { + if (line == null) + return reset(); + this.level = line.level; + this.style = line.style; + this.strokeWidth = line.width; + this.fillColor = line.color; + this.cap = line.cap; + this.outline = line.outline; + this.fixed = line.fixed; + this.fadeScale = line.fadeScale; + this.blur = line.blur; + this.stipple = line.stipple; + this.stippleColor = line.stippleColor; + this.stippleWidth = line.stippleWidth; + return self(); + } - public T reset() { - level = -1; - style = null; - fillColor = Color.BLACK; - cap = Cap.ROUND; - strokeWidth = 1; - fixed = false; + public T reset() { + level = -1; + style = null; + fillColor = Color.BLACK; + cap = Cap.ROUND; + strokeWidth = 1; + fixed = false; - fadeScale = -1; - blur = 0; + fadeScale = -1; + blur = 0; - stipple = 0; - stippleWidth = 1; - stippleColor = Color.BLACK; + stipple = 0; + stippleWidth = 1; + stippleColor = Color.BLACK; - return self(); - } + return self(); + } - public T style(String name) { - this.style = name; - return self(); - } + public T style(String name) { + this.style = name; + return self(); + } - public T blur(float blur) { - this.blur = blur; - return self(); - } + public T blur(float blur) { + this.blur = blur; + return self(); + } - public T fadeScale(int zoom) { - this.fadeScale = zoom; - return self(); - } + public T fadeScale(int zoom) { + this.fadeScale = zoom; + return self(); + } - public T stippleColor(int color) { - this.stippleColor = color; - return self(); - } + public T stippleColor(int color) { + this.stippleColor = color; + return self(); + } - public T stippleColor(String color) { - this.stippleColor = parseColor(color); - return self(); - } + public T stippleColor(String color) { + this.stippleColor = parseColor(color); + return self(); + } - public T isOutline(boolean outline) { - this.outline = outline; - return self(); - } + public T isOutline(boolean outline) { + this.outline = outline; + return self(); + } - public LineStyle build() { - return new LineStyle(this); - } + public LineStyle build() { + return new LineStyle(this); + } - public T cap(Cap cap) { - this.cap = cap; - return self(); - } + public T cap(Cap cap) { + this.cap = cap; + return self(); + } - public T fixed(boolean b) { - this.fixed = b; - return self(); - } - } + public T fixed(boolean b) { + this.fixed = b; + return self(); + } + } - @SuppressWarnings("rawtypes") - public static LineBuilder builder() { - return new LineBuilder(); - } + @SuppressWarnings("rawtypes") + public static LineBuilder builder() { + return new LineBuilder(); + } } diff --git a/vtm/src/org/oscim/theme/styles/RenderStyle.java b/vtm/src/org/oscim/theme/styles/RenderStyle.java index da5f3889..e01ad12d 100644 --- a/vtm/src/org/oscim/theme/styles/RenderStyle.java +++ b/vtm/src/org/oscim/theme/styles/RenderStyle.java @@ -24,170 +24,164 @@ import static org.oscim.backend.canvas.Color.parseColor; */ public abstract class RenderStyle { - public static abstract class StyleBuilder> { + public static abstract class StyleBuilder> { - public String style; + public String style; - public int level; + public int level; - public int fillColor; + public int fillColor; - public int strokeColor; - public float strokeWidth; + public int strokeColor; + public float strokeWidth; - public T setStyle(String style) { - this.style = style; - return self(); - } + public T setStyle(String style) { + this.style = style; + return self(); + } - public T level(int level) { - this.level = level; - return self(); - } + public T level(int level) { + this.level = level; + return self(); + } - public T outline(int color, float width) { - this.strokeColor = color; - this.strokeWidth = width; - return self(); - } + public T outline(int color, float width) { + this.strokeColor = color; + this.strokeWidth = width; + return self(); + } - public T strokeColor(int color) { - this.strokeColor = color; - return self(); - } + public T strokeColor(int color) { + this.strokeColor = color; + return self(); + } - public T strokeColor(String color) { - this.strokeColor = parseColor(color); - return self(); - } + public T strokeColor(String color) { + this.strokeColor = parseColor(color); + return self(); + } - public T strokeWidth(float width) { - this.strokeWidth = width; - return self(); - } + public T strokeWidth(float width) { + this.strokeWidth = width; + return self(); + } - public T color(int color) { - this.fillColor = color; - return self(); - } + public T color(int color) { + this.fillColor = color; + return self(); + } - public T color(String color) { - this.fillColor = parseColor(color); - return self(); - } + public T color(String color) { + this.fillColor = parseColor(color); + return self(); + } - @SuppressWarnings("unchecked") - protected T self() { - return (T) this; - } + @SuppressWarnings("unchecked") + protected T self() { + return (T) this; + } - public abstract RenderStyle build(); - } + public abstract RenderStyle build(); + } - /** - * Callback methods for rendering areas, ways and points of interest (POIs). - */ - public static interface Callback { - /** - * Renders an area with the given parameters. - * - * @param area - * @param level - */ - void renderArea(AreaStyle area, int level); + /** + * Callback methods for rendering areas, ways and points of interest (POIs). + */ + public static interface Callback { + /** + * Renders an area with the given parameters. + * + * @param area + * @param level + */ + void renderArea(AreaStyle area, int level); - /** - * Renders an extrusion with the given parameters. - * - * @param extrusion - * @param level - */ - void renderExtrusion(ExtrusionStyle extrusion, int level); + /** + * Renders an extrusion with the given parameters. + * + * @param extrusion + * @param level + */ + void renderExtrusion(ExtrusionStyle extrusion, int level); - /** - * Renders a point of interest circle with the given parameters. - * - * @param circle - * the circle. - * @param level - * the drawing level on which the circle should be rendered. - */ - void renderCircle(CircleStyle circle, int level); + /** + * Renders a point of interest circle with the given parameters. + * + * @param circle the circle. + * @param level the drawing level on which the circle should be rendered. + */ + void renderCircle(CircleStyle circle, int level); - /** - * Renders a point of interest symbol with the given bitmap. - * - * @param symbol - * the symbol to be rendered. - */ - void renderSymbol(SymbolStyle symbol); + /** + * Renders a point of interest symbol with the given bitmap. + * + * @param symbol the symbol to be rendered. + */ + void renderSymbol(SymbolStyle symbol); - /** - * Renders a way with the given parameters. - * - * @param line - * @param level - */ - void renderWay(LineStyle line, int level); + /** + * Renders a way with the given parameters. + * + * @param line + * @param level + */ + void renderWay(LineStyle line, int level); - /** - * Renders a way with the given text along the way path. - * - * @param text - */ - void renderText(TextStyle text); + /** + * Renders a way with the given text along the way path. + * + * @param text + */ + void renderText(TextStyle text); - } + } - RenderStyle mCurrent = this; - RenderStyle mNext; - boolean update; + RenderStyle mCurrent = this; + RenderStyle mNext; + boolean update; - public void set(RenderStyle next) { - update = true; - mNext = next; - } + public void set(RenderStyle next) { + update = true; + mNext = next; + } - public void unsetOverride() { - update = true; - mNext = null; - } + public void unsetOverride() { + update = true; + mNext = null; + } - /** - * Destroys this RenderInstruction and cleans up all its internal resources. - */ - public void dispose() { - } + /** + * Destroys this RenderInstruction and cleans up all its internal resources. + */ + public void dispose() { + } - /** - * @param renderCallback - * a reference to the receiver of all render callbacks. - */ - public void renderNode(Callback renderCallback) { - } + /** + * @param renderCallback a reference to the receiver of all render callbacks. + */ + public void renderNode(Callback renderCallback) { + } - /** - * @param renderCallback - * a reference to the receiver of all render callbacks. - */ - public void renderWay(Callback renderCallback) { - } + /** + * @param renderCallback a reference to the receiver of all render callbacks. + */ + public void renderWay(Callback renderCallback) { + } - /** - * Scales the text size of this RenderInstruction by the given factor. - * - * @param scaleFactor - * the factor by which the text size should be scaled. - */ - public void scaleTextSize(float scaleFactor) { - } + /** + * Scales the text size of this RenderInstruction by the given factor. + * + * @param scaleFactor the factor by which the text size should be scaled. + */ + public void scaleTextSize(float scaleFactor) { + } - public void update() { - if (update) { - update = false; - mCurrent = mNext; - } - } + public void update() { + if (update) { + update = false; + mCurrent = mNext; + } + } - public abstract RenderStyle current(); + public abstract RenderStyle current(); } diff --git a/vtm/src/org/oscim/theme/styles/SymbolStyle.java b/vtm/src/org/oscim/theme/styles/SymbolStyle.java index 77e49ba2..2fbe812c 100644 --- a/vtm/src/org/oscim/theme/styles/SymbolStyle.java +++ b/vtm/src/org/oscim/theme/styles/SymbolStyle.java @@ -24,28 +24,28 @@ import org.oscim.renderer.atlas.TextureRegion; */ public final class SymbolStyle extends RenderStyle { - public final TextureRegion texture; + public final TextureRegion texture; - public SymbolStyle(TextureRegion symbol) { - this.texture = symbol; - } + public SymbolStyle(TextureRegion symbol) { + this.texture = symbol; + } - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public void renderNode(Callback cb) { - cb.renderSymbol(this); - } + @Override + public void renderNode(Callback cb) { + cb.renderSymbol(this); + } - @Override - public void renderWay(Callback cb) { - cb.renderSymbol(this); - } + @Override + public void renderWay(Callback cb) { + cb.renderSymbol(this); + } - @Override - public SymbolStyle current() { - return (SymbolStyle) mCurrent; - } + @Override + public SymbolStyle current() { + return (SymbolStyle) mCurrent; + } } diff --git a/vtm/src/org/oscim/theme/styles/TextStyle.java b/vtm/src/org/oscim/theme/styles/TextStyle.java index 12998085..4ff14baa 100644 --- a/vtm/src/org/oscim/theme/styles/TextStyle.java +++ b/vtm/src/org/oscim/theme/styles/TextStyle.java @@ -26,194 +26,194 @@ import org.oscim.renderer.atlas.TextureRegion; public final class TextStyle extends RenderStyle { - public static class TextBuilder> extends StyleBuilder { + public static class TextBuilder> extends StyleBuilder { - public float fontSize; + public float fontSize; - public String textKey; - public boolean caption; - public float dy; - public int priority; - public TextureRegion texture; - public FontFamily fontFamily; - public FontStyle fontStyle; + public String textKey; + public boolean caption; + public float dy; + public int priority; + public TextureRegion texture; + public FontFamily fontFamily; + public FontStyle fontStyle; - public T reset() { - fontFamily = FontFamily.DEFAULT; - fontStyle = FontStyle.NORMAL; - style = null; - textKey = null; - fontSize = 0; - caption = false; - priority = Integer.MAX_VALUE; - texture = null; - fillColor = Color.BLACK; - strokeColor = Color.BLACK; - strokeWidth = 0; - dy = 0; - return self(); - } + public T reset() { + fontFamily = FontFamily.DEFAULT; + fontStyle = FontStyle.NORMAL; + style = null; + textKey = null; + fontSize = 0; + caption = false; + priority = Integer.MAX_VALUE; + texture = null; + fillColor = Color.BLACK; + strokeColor = Color.BLACK; + strokeWidth = 0; + dy = 0; + return self(); + } - public TextBuilder() { - reset(); - } + public TextBuilder() { + reset(); + } - public TextStyle build() { - TextStyle t = new TextStyle(this); - t.fontHeight = t.paint.getFontHeight(); - t.fontDescent = t.paint.getFontDescent(); - return t; - } + public TextStyle build() { + TextStyle t = new TextStyle(this); + t.fontHeight = t.paint.getFontHeight(); + t.fontDescent = t.paint.getFontDescent(); + return t; + } - public TextStyle buildInternal() { - return new TextStyle(this); - } + public TextStyle buildInternal() { + return new TextStyle(this); + } - public T fontSize(float fontSize) { - this.fontSize = fontSize; - return self(); - } + public T fontSize(float fontSize) { + this.fontSize = fontSize; + return self(); + } - public T textKey(String textKey) { - this.textKey = textKey; - return self(); - } + public T textKey(String textKey) { + this.textKey = textKey; + return self(); + } - public T isCaption(boolean caption) { - this.caption = caption; - return self(); - } + public T isCaption(boolean caption) { + this.caption = caption; + return self(); + } - public T offsetY(float dy) { - this.dy = dy; - return self(); - } + public T offsetY(float dy) { + this.dy = dy; + return self(); + } - public T priority(int priority) { - this.priority = priority; - return self(); - } + public T priority(int priority) { + this.priority = priority; + return self(); + } - public T texture(TextureRegion texture) { - this.texture = texture; - return self(); - } + public T texture(TextureRegion texture) { + this.texture = texture; + return self(); + } - public T fontFamily(FontFamily fontFamily) { - this.fontFamily = fontFamily; - return self(); - } + public T fontFamily(FontFamily fontFamily) { + this.fontFamily = fontFamily; + return self(); + } - public T fontStyle(FontStyle fontStyle) { - this.fontStyle = fontStyle; - return self(); - } + public T fontStyle(FontStyle fontStyle) { + this.fontStyle = fontStyle; + return self(); + } - public T from(TextBuilder other) { - fontFamily = other.fontFamily; - fontStyle = other.fontStyle; - style = other.style; - textKey = other.textKey; - fontSize = other.fontSize; - caption = other.caption; - priority = other.priority; - texture = other.texture; - fillColor = other.fillColor; - strokeColor = other.strokeColor; - strokeWidth = other.strokeWidth; - dy = other.dy; - return self(); - } + public T from(TextBuilder other) { + fontFamily = other.fontFamily; + fontStyle = other.fontStyle; + style = other.style; + textKey = other.textKey; + fontSize = other.fontSize; + caption = other.caption; + priority = other.priority; + texture = other.texture; + fillColor = other.fillColor; + strokeColor = other.strokeColor; + strokeWidth = other.strokeWidth; + dy = other.dy; + return self(); + } - public TextBuilder from(TextStyle style) { - this.style = style.style; - this.textKey = style.textKey; - this.caption = style.caption; - this.dy = style.dy; - this.priority = style.priority; - this.texture = style.texture; - this.fillColor = style.paint.getColor(); - this.fontFamily = FontFamily.DEFAULT; - this.fontStyle = FontStyle.NORMAL; - this.strokeColor = style.stroke.getColor(); - this.strokeWidth = 2; - this.fontSize = style.fontSize; - return self(); - } - } + public TextBuilder from(TextStyle style) { + this.style = style.style; + this.textKey = style.textKey; + this.caption = style.caption; + this.dy = style.dy; + this.priority = style.priority; + this.texture = style.texture; + this.fillColor = style.paint.getColor(); + this.fontFamily = FontFamily.DEFAULT; + this.fontStyle = FontStyle.NORMAL; + this.strokeColor = style.stroke.getColor(); + this.strokeWidth = 2; + this.fontSize = style.fontSize; + return self(); + } + } - TextStyle(TextBuilder tb) { - this.style = tb.style; - this.textKey = tb.textKey; - this.caption = tb.caption; - this.dy = tb.dy; - this.priority = tb.priority; - this.texture = tb.texture; + TextStyle(TextBuilder tb) { + this.style = tb.style; + this.textKey = tb.textKey; + this.caption = tb.caption; + this.dy = tb.dy; + this.priority = tb.priority; + this.texture = tb.texture; - paint = CanvasAdapter.newPaint(); - paint.setTextAlign(Align.CENTER); - paint.setTypeface(tb.fontFamily, tb.fontStyle); + paint = CanvasAdapter.newPaint(); + paint.setTextAlign(Align.CENTER); + paint.setTypeface(tb.fontFamily, tb.fontStyle); - paint.setColor(tb.fillColor); - paint.setTextSize(tb.fontSize); + paint.setColor(tb.fillColor); + paint.setTextSize(tb.fontSize); - if (tb.strokeWidth > 0) { - stroke = CanvasAdapter.newPaint(); - stroke.setStyle(Paint.Style.STROKE); - stroke.setTextAlign(Align.CENTER); - stroke.setTypeface(tb.fontFamily, tb.fontStyle); - stroke.setColor(tb.strokeColor); - stroke.setStrokeWidth(tb.strokeWidth); - stroke.setTextSize(tb.fontSize); - } else - stroke = null; + if (tb.strokeWidth > 0) { + stroke = CanvasAdapter.newPaint(); + stroke.setStyle(Paint.Style.STROKE); + stroke.setTextAlign(Align.CENTER); + stroke.setTypeface(tb.fontFamily, tb.fontStyle); + stroke.setColor(tb.strokeColor); + stroke.setStrokeWidth(tb.strokeWidth); + stroke.setTextSize(tb.fontSize); + } else + stroke = null; - this.fontSize = tb.fontSize; - } + this.fontSize = tb.fontSize; + } - public final String style; + public final String style; - public final float fontSize; - public final Paint paint; - public final Paint stroke; - public final String textKey; + public final float fontSize; + public final Paint paint; + public final Paint stroke; + public final String textKey; - public final boolean caption; - public final float dy; - public final int priority; + public final boolean caption; + public final float dy; + public final int priority; - public float fontHeight; - public float fontDescent; + public float fontHeight; + public float fontDescent; - public final TextureRegion texture; + public final TextureRegion texture; - @Override - public void renderNode(Callback cb) { - cb.renderText(this); - } + @Override + public void renderNode(Callback cb) { + cb.renderText(this); + } - @Override - public void renderWay(Callback cb) { - cb.renderText(this); - } + @Override + public void renderWay(Callback cb) { + cb.renderText(this); + } - @Override - public TextStyle current() { - return (TextStyle) mCurrent; - } + @Override + public TextStyle current() { + return (TextStyle) mCurrent; + } - @Override - public void scaleTextSize(float scaleFactor) { - paint.setTextSize(fontSize * scaleFactor); - if (stroke != null) - stroke.setTextSize(fontSize * scaleFactor); + @Override + public void scaleTextSize(float scaleFactor) { + paint.setTextSize(fontSize * scaleFactor); + if (stroke != null) + stroke.setTextSize(fontSize * scaleFactor); - fontHeight = paint.getFontHeight(); - fontDescent = paint.getFontDescent(); - } + fontHeight = paint.getFontHeight(); + fontDescent = paint.getFontDescent(); + } - @SuppressWarnings("rawtypes") - public static TextBuilder builder() { - return new TextBuilder(); - } + @SuppressWarnings("rawtypes") + public static TextBuilder builder() { + return new TextBuilder(); + } } diff --git a/vtm/src/org/oscim/tiling/ITileCache.java b/vtm/src/org/oscim/tiling/ITileCache.java index f27a69fc..7a4f163f 100644 --- a/vtm/src/org/oscim/tiling/ITileCache.java +++ b/vtm/src/org/oscim/tiling/ITileCache.java @@ -16,49 +16,44 @@ */ package org.oscim.tiling; +import org.oscim.core.Tile; + import java.io.InputStream; import java.io.OutputStream; -import org.oscim.core.Tile; - /* * Thie interface CacheManager defines the operation for the cache. */ public interface ITileCache { - /** - * @param tile - * The accessed tile. - * @return - * The CacheFile which contains the Fileoutputstream for the cache. - */ - TileWriter writeTile(Tile tile); + /** + * @param tile The accessed tile. + * @return The CacheFile which contains the Fileoutputstream for the cache. + */ + TileWriter writeTile(Tile tile); - /** - * @param tile - * The accessed tile. - * @return - * The stored file for this tile or null if tile is not stored. - */ - TileReader getTile(Tile tile); + /** + * @param tile The accessed tile. + * @return The stored file for this tile or null if tile is not stored. + */ + TileReader getTile(Tile tile); - /** - * @param size - * The size for the cache directionary. - */ - void setCacheSize(long size); + /** + * @param size The size for the cache directionary. + */ + void setCacheSize(long size); - public interface TileReader { - Tile getTile(); + public interface TileReader { + Tile getTile(); - InputStream getInputStream(); - } + InputStream getInputStream(); + } - public interface TileWriter { - Tile getTile(); + public interface TileWriter { + Tile getTile(); - OutputStream getOutputStream(); + OutputStream getOutputStream(); - void complete(boolean success); - } + void complete(boolean success); + } } diff --git a/vtm/src/org/oscim/tiling/ITileDataSink.java b/vtm/src/org/oscim/tiling/ITileDataSink.java index 7a597cd0..7386709b 100644 --- a/vtm/src/org/oscim/tiling/ITileDataSink.java +++ b/vtm/src/org/oscim/tiling/ITileDataSink.java @@ -23,21 +23,21 @@ import org.oscim.core.MapElement; * ITileDataSink callbacks (implemented by MapTileLoader) */ public interface ITileDataSink { - /** - * Pass read MapElement data to loader. - *

- * NOTE: MapElement passed belong to the caller! i.e. dont hold references - * to any of its data after callback function returns. - */ - void process(MapElement element); + /** + * Pass read MapElement data to loader. + *

+ * NOTE: MapElement passed belong to the caller! i.e. dont hold references + * to any of its data after callback function returns. + */ + void process(MapElement element); - /** - * Pass read Bitmap data to loader. - */ - void setTileImage(Bitmap bitmap); + /** + * Pass read Bitmap data to loader. + */ + void setTileImage(Bitmap bitmap); - /** - * Notify loader that tile loading is completed. - */ - void completed(QueryResult result); + /** + * Notify loader that tile loading is completed. + */ + void completed(QueryResult result); } diff --git a/vtm/src/org/oscim/tiling/ITileDataSource.java b/vtm/src/org/oscim/tiling/ITileDataSource.java index af513865..9a6fa77c 100644 --- a/vtm/src/org/oscim/tiling/ITileDataSource.java +++ b/vtm/src/org/oscim/tiling/ITileDataSource.java @@ -20,18 +20,20 @@ import org.oscim.layers.tile.MapTile; public interface ITileDataSource { - /** - * @param tile - * the tile to load. - * @param mapDataSink - * the callback to handle the extracted map elements. - */ - abstract void query(MapTile tile, ITileDataSink mapDataSink); + /** + * @param tile the tile to load. + * @param mapDataSink the callback to handle the extracted map elements. + */ + abstract void query(MapTile tile, ITileDataSink mapDataSink); - /** Implementations should cancel and release all resources */ - abstract void dispose(); + /** + * Implementations should cancel and release all resources + */ + abstract void dispose(); - /** Implementations should cancel their IO work and return */ - abstract void cancel(); + /** + * Implementations should cancel their IO work and return + */ + abstract void cancel(); } diff --git a/vtm/src/org/oscim/tiling/QueryResult.java b/vtm/src/org/oscim/tiling/QueryResult.java index efe83247..56c62ea7 100644 --- a/vtm/src/org/oscim/tiling/QueryResult.java +++ b/vtm/src/org/oscim/tiling/QueryResult.java @@ -1,8 +1,8 @@ package org.oscim.tiling; public enum QueryResult { - SUCCESS, - FAILED, - TILE_NOT_FOUND, - DELAYED, + SUCCESS, + FAILED, + TILE_NOT_FOUND, + DELAYED, } \ No newline at end of file diff --git a/vtm/src/org/oscim/tiling/TileSource.java b/vtm/src/org/oscim/tiling/TileSource.java index 5fd0ac90..b9099129 100644 --- a/vtm/src/org/oscim/tiling/TileSource.java +++ b/vtm/src/org/oscim/tiling/TileSource.java @@ -16,171 +16,170 @@ */ package org.oscim.tiling; -import java.util.HashMap; - import org.oscim.layers.tile.bitmap.BitmapTileLayer.FadeStep; +import java.util.HashMap; + public abstract class TileSource { - public abstract static class Builder> { - protected int zoomMin, zoomMax; - protected FadeStep[] fadeSteps; + public abstract static class Builder> { + protected int zoomMin, zoomMax; + protected FadeStep[] fadeSteps; - public T zoomMin(int zoom) { - zoomMin = zoom; - return self(); - } + public T zoomMin(int zoom) { + zoomMin = zoom; + return self(); + } - public T zoomMax(int zoom) { - zoomMax = zoom; - return self(); - } + public T zoomMax(int zoom) { + zoomMax = zoom; + return self(); + } - public T fadeSteps(FadeStep[] fadeSteps) { - this.fadeSteps = fadeSteps; - return self(); - } + public T fadeSteps(FadeStep[] fadeSteps) { + this.fadeSteps = fadeSteps; + return self(); + } - @SuppressWarnings("unchecked") - protected T self() { - return (T) this; - } + @SuppressWarnings("unchecked") + protected T self() { + return (T) this; + } - public abstract TileSource build(); - } + public abstract TileSource build(); + } - protected int mZoomMin = 0; - protected int mZoomMax = 20; + protected int mZoomMin = 0; + protected int mZoomMax = 20; - protected TileSource() { - } + protected TileSource() { + } - protected TileSource(int zoomMin, int zoomMax) { - mZoomMin = zoomMin; - mZoomMax = zoomMax; - } + protected TileSource(int zoomMin, int zoomMax) { + mZoomMin = zoomMin; + mZoomMax = zoomMax; + } - public TileSource(Builder builder) { - mZoomMin = builder.zoomMin; - mZoomMax = builder.zoomMax; - mFadeSteps = builder.fadeSteps; - } + public TileSource(Builder builder) { + mZoomMin = builder.zoomMin; + mZoomMax = builder.zoomMax; + mFadeSteps = builder.fadeSteps; + } - public abstract ITileDataSource getDataSource(); + public abstract ITileDataSource getDataSource(); - public abstract OpenResult open(); + public abstract OpenResult open(); - public abstract void close(); + public abstract void close(); - protected final Options options = new Options(); + protected final Options options = new Options(); - public ITileCache tileCache; + public ITileCache tileCache; - private FadeStep[] mFadeSteps; + private FadeStep[] mFadeSteps; - /** - * Cache MUST be set before TileSource is added to a TileLayer! - */ - public void setCache(ITileCache cache) { - tileCache = cache; - } + /** + * Cache MUST be set before TileSource is added to a TileLayer! + */ + public void setCache(ITileCache cache) { + tileCache = cache; + } - public int getZoomLevelMax() { - return mZoomMax; - } + public int getZoomLevelMax() { + return mZoomMax; + } - public int getZoomLevelMin() { - return mZoomMin; - } + public int getZoomLevelMin() { + return mZoomMin; + } - public FadeStep[] getFadeSteps() { - return mFadeSteps; - } + public FadeStep[] getFadeSteps() { + return mFadeSteps; + } - public TileSource setOption(String key, String value) { - options.put(key, value); - return this; - } + public TileSource setOption(String key, String value) { + options.put(key, value); + return this; + } - public String getOption(String key) { - return options.get(key); - } + public String getOption(String key) { + return options.get(key); + } - public static class Options extends HashMap { + public static class Options extends HashMap { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Override - public boolean equals(Object other) { - if (!(other instanceof Options)) - return false; + @Override + public boolean equals(Object other) { + if (!(other instanceof Options)) + return false; - //if (this.db != ((MapOptions) other).db) - // return false; + //if (this.db != ((MapOptions) other).db) + // return false; - // FIXME test if this is correct! - if (!this.entrySet().equals(((Options) other).entrySet())) - return false; + // FIXME test if this is correct! + if (!this.entrySet().equals(((Options) other).entrySet())) + return false; - return true; - } - } + return true; + } + } - /** - * A FileOpenResult is a simple DTO which is returned by - * IMapDatabase#open(). - */ - public static class OpenResult { - /** - * Singleton for a FileOpenResult instance with {@code success=true}. - */ - public static final OpenResult SUCCESS = new OpenResult(); + /** + * A FileOpenResult is a simple DTO which is returned by + * IMapDatabase#open(). + */ + public static class OpenResult { + /** + * Singleton for a FileOpenResult instance with {@code success=true}. + */ + public static final OpenResult SUCCESS = new OpenResult(); - private final String errorMessage; - private final boolean success; + private final String errorMessage; + private final boolean success; - /** - * @param errorMessage - * a textual message describing the error, must not be null. - */ - public OpenResult(String errorMessage) { - if (errorMessage == null) { - throw new IllegalArgumentException("error message must not be null"); - } + /** + * @param errorMessage a textual message describing the error, must not be null. + */ + public OpenResult(String errorMessage) { + if (errorMessage == null) { + throw new IllegalArgumentException("error message must not be null"); + } - this.success = false; - this.errorMessage = errorMessage; - } + this.success = false; + this.errorMessage = errorMessage; + } - public OpenResult() { - this.success = true; - this.errorMessage = null; - } + public OpenResult() { + this.success = true; + this.errorMessage = null; + } - /** - * @return a textual error description (might be null). - */ - public String getErrorMessage() { - return this.errorMessage; - } + /** + * @return a textual error description (might be null). + */ + public String getErrorMessage() { + return this.errorMessage; + } - /** - * @return true if the file could be opened successfully, false - * otherwise. - */ - public boolean isSuccess() { - return this.success; - } + /** + * @return true if the file could be opened successfully, false + * otherwise. + */ + public boolean isSuccess() { + return this.success; + } - @Override - public String toString() { - return new StringBuilder() - .append("FileOpenResult [success=") - .append(this.success) - .append(", errorMessage=") - .append(this.errorMessage) - .append("]") - .toString(); - } - } + @Override + public String toString() { + return new StringBuilder() + .append("FileOpenResult [success=") + .append(this.success) + .append(", errorMessage=") + .append(this.errorMessage) + .append("]") + .toString(); + } + } } diff --git a/vtm/src/org/oscim/tiling/source/HttpEngine.java b/vtm/src/org/oscim/tiling/source/HttpEngine.java index 7164eae0..a78ad420 100644 --- a/vtm/src/org/oscim/tiling/source/HttpEngine.java +++ b/vtm/src/org/oscim/tiling/source/HttpEngine.java @@ -16,32 +16,32 @@ */ package org.oscim.tiling.source; +import org.oscim.core.Tile; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import org.oscim.core.Tile; - public interface HttpEngine { - InputStream read() throws IOException; + InputStream read() throws IOException; - void sendRequest(Tile tile) throws IOException; + void sendRequest(Tile tile) throws IOException; - void close(); + void close(); - void setCache(OutputStream os); + void setCache(OutputStream os); - /** - * @param success maybe false when tile could not be decoded. - * Dont write cache in this case, close socket, etc - * at your option. - * @return true when everything went ok - */ - boolean requestCompleted(boolean success); + /** + * @param success maybe false when tile could not be decoded. + * Dont write cache in this case, close socket, etc + * at your option. + * @return true when everything went ok + */ + boolean requestCompleted(boolean success); - public interface Factory { - HttpEngine create(UrlTileSource tileSource); - } + public interface Factory { + HttpEngine create(UrlTileSource tileSource); + } } diff --git a/vtm/src/org/oscim/tiling/source/ITileDecoder.java b/vtm/src/org/oscim/tiling/source/ITileDecoder.java index 0412bb15..41eb7bc1 100644 --- a/vtm/src/org/oscim/tiling/source/ITileDecoder.java +++ b/vtm/src/org/oscim/tiling/source/ITileDecoder.java @@ -16,14 +16,14 @@ */ package org.oscim.tiling.source; -import java.io.IOException; -import java.io.InputStream; - import org.oscim.core.Tile; import org.oscim.tiling.ITileDataSink; +import java.io.IOException; +import java.io.InputStream; + public interface ITileDecoder { - boolean decode(Tile tile, ITileDataSink sink, InputStream is) - throws IOException; + boolean decode(Tile tile, ITileDataSink sink, InputStream is) + throws IOException; } diff --git a/vtm/src/org/oscim/tiling/source/LwHttp.java b/vtm/src/org/oscim/tiling/source/LwHttp.java index 52ae81a2..6a9066bb 100644 --- a/vtm/src/org/oscim/tiling/source/LwHttp.java +++ b/vtm/src/org/oscim/tiling/source/LwHttp.java @@ -16,6 +16,12 @@ */ package org.oscim.tiling.source; +import org.oscim.core.Tile; +import org.oscim.utils.ArrayUtils; +import org.oscim.utils.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; @@ -27,513 +33,513 @@ import java.net.UnknownHostException; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; -import org.oscim.core.Tile; -import org.oscim.utils.ArrayUtils; -import org.oscim.utils.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Lightweight HTTP connection for tile loading. Does not do redirects, * https, full header parsing or other stuff. */ public class LwHttp implements HttpEngine { - static final Logger log = LoggerFactory.getLogger(LwHttp.class); - static final boolean dbg = false; + static final Logger log = LoggerFactory.getLogger(LwHttp.class); + static final boolean dbg = false; - private final static byte[] HEADER_HTTP_OK = "200 OK".getBytes(); - private final static byte[] HEADER_CONTENT_LENGTH = "Content-Length".getBytes(); - private final static byte[] HEADER_CONNECTION_CLOSE = "Connection: close".getBytes(); - private final static byte[] HEADER_ENCODING_GZIP = "Content-Encoding: gzip".getBytes(); + private final static byte[] HEADER_HTTP_OK = "200 OK".getBytes(); + private final static byte[] HEADER_CONTENT_LENGTH = "Content-Length".getBytes(); + private final static byte[] HEADER_CONNECTION_CLOSE = "Connection: close".getBytes(); + private final static byte[] HEADER_ENCODING_GZIP = "Content-Encoding: gzip".getBytes(); - private final static int RESPONSE_EXPECTED_LIVES = 100; - private final static long RESPONSE_TIMEOUT = (long) 10E9; // 10 second in nanosecond + private final static int RESPONSE_EXPECTED_LIVES = 100; + private final static long RESPONSE_TIMEOUT = (long) 10E9; // 10 second in nanosecond - private final static int CONNECT_TIMEOUT = 15000; // 15 seconds - private final static int SOCKET_TIMEOUT = 8000; // 8 seconds + private final static int CONNECT_TIMEOUT = 15000; // 15 seconds + private final static int SOCKET_TIMEOUT = 8000; // 8 seconds - private final static int BUFFER_SIZE = 8192; - private final byte[] buffer = new byte[BUFFER_SIZE]; + private final static int BUFFER_SIZE = 8192; + private final byte[] buffer = new byte[BUFFER_SIZE]; - private final String mHost; - private final int mPort; + private final String mHost; + private final int mPort; - private int mMaxRequests = 0; - private Socket mSocket; - private OutputStream mCommandStream; - private Buffer mResponseStream; - private long mLastRequest = 0; - private InetSocketAddress mSockAddr; + private int mMaxRequests = 0; + private Socket mSocket; + private OutputStream mCommandStream; + private Buffer mResponseStream; + private long mLastRequest = 0; + private InetSocketAddress mSockAddr; - /** Server requested to close the connection */ - private boolean mMustCloseConnection; + /** + * Server requested to close the connection + */ + private boolean mMustCloseConnection; - private final byte[] REQUEST_GET_START; - private final byte[] REQUEST_GET_END; - private final byte[] mRequestBuffer; + private final byte[] REQUEST_GET_START; + private final byte[] REQUEST_GET_END; + private final byte[] mRequestBuffer; - private final byte[][] mTilePath; - private final UrlTileSource mTileSource; + private final byte[][] mTilePath; + private final UrlTileSource mTileSource; - //private boolean mUseGZIP; + //private boolean mUseGZIP; - private LwHttp(UrlTileSource tileSource, byte[][] tilePath) { - mTilePath = tilePath; - mTileSource = tileSource; + private LwHttp(UrlTileSource tileSource, byte[][] tilePath) { + mTilePath = tilePath; + mTileSource = tileSource; - URL url = tileSource.getUrl(); - int port = url.getPort(); - if (port < 0) - port = 80; + URL url = tileSource.getUrl(); + int port = url.getPort(); + if (port < 0) + port = 80; - mHost = url.getHost(); - mPort = port; + mHost = url.getHost(); + mPort = port; - String path = url.getPath(); + String path = url.getPath(); - REQUEST_GET_START = ("GET " + path).getBytes(); + REQUEST_GET_START = ("GET " + path).getBytes(); - StringBuilder sb = new StringBuilder() - .append(" HTTP/1.1") - .append("\nUser-Agent: vtm/0.5.9") - .append("\nHost: ") - .append(mHost) - .append("\nConnection: Keep-Alive"); + StringBuilder sb = new StringBuilder() + .append(" HTTP/1.1") + .append("\nUser-Agent: vtm/0.5.9") + .append("\nHost: ") + .append(mHost) + .append("\nConnection: Keep-Alive"); - for (Entry l : tileSource.getRequestHeader().entrySet()) { - String key = l.getKey(); - String val = l.getValue(); - //if ("Accept-Encoding".equals(key) && "gzip".equals(val)) - // mUseGZIP = true; - sb.append('\n').append(key).append(": ").append(val); - } - sb.append("\n\n"); + for (Entry l : tileSource.getRequestHeader().entrySet()) { + String key = l.getKey(); + String val = l.getValue(); + //if ("Accept-Encoding".equals(key) && "gzip".equals(val)) + // mUseGZIP = true; + sb.append('\n').append(key).append(": ").append(val); + } + sb.append("\n\n"); - REQUEST_GET_END = sb.toString().getBytes(); + REQUEST_GET_END = sb.toString().getBytes(); - mRequestBuffer = new byte[1024]; - System.arraycopy(REQUEST_GET_START, 0, - mRequestBuffer, 0, - REQUEST_GET_START.length); - } + mRequestBuffer = new byte[1024]; + System.arraycopy(REQUEST_GET_START, 0, + mRequestBuffer, 0, + REQUEST_GET_START.length); + } - static final class Buffer extends BufferedInputStream { - OutputStream cache; - int bytesRead = 0; - int bytesWrote; - int marked = -1; - int contentLength; + static final class Buffer extends BufferedInputStream { + OutputStream cache; + int bytesRead = 0; + int bytesWrote; + int marked = -1; + int contentLength; - public Buffer(InputStream is) { - super(is, BUFFER_SIZE); - } + public Buffer(InputStream is) { + super(is, BUFFER_SIZE); + } - public void setCache(OutputStream cache) { - this.cache = cache; - } + public void setCache(OutputStream cache) { + this.cache = cache; + } - public void start(int length) { - bytesRead = 0; - bytesWrote = 0; - contentLength = length; - } + public void start(int length) { + bytesRead = 0; + bytesWrote = 0; + contentLength = length; + } - public boolean finishedReading() { - try { - while (bytesRead < contentLength && read() >= 0); - } catch (IOException e) { - log.debug(e.getMessage()); - } + public boolean finishedReading() { + try { + while (bytesRead < contentLength && read() >= 0) ; + } catch (IOException e) { + log.debug(e.getMessage()); + } - return bytesRead == contentLength; - } + return bytesRead == contentLength; + } - @Override - public void close() throws IOException { - if (dbg) - log.debug("close()... ignored"); - } + @Override + public void close() throws IOException { + if (dbg) + log.debug("close()... ignored"); + } - @Override - public synchronized void mark(int readlimit) { - if (dbg) - log.debug("mark {}", readlimit); + @Override + public synchronized void mark(int readlimit) { + if (dbg) + log.debug("mark {}", readlimit); - marked = bytesRead; - super.mark(readlimit); - } + marked = bytesRead; + super.mark(readlimit); + } - @Override - public synchronized long skip(long n) throws IOException { - /* Android(4.1.2) image decoder *requires* skip to - * actually skip the requested amount. + @Override + public synchronized long skip(long n) throws IOException { + /* Android(4.1.2) image decoder *requires* skip to + * actually skip the requested amount. * https://code.google.com/p/android/issues/detail?id=6066 */ - long sumSkipped = 0L; - while (sumSkipped < n) { - long skipped = super.skip(n - sumSkipped); - if (skipped != 0) { - sumSkipped += skipped; - continue; - } - if (read() < 0) - break; // EOF + long sumSkipped = 0L; + while (sumSkipped < n) { + long skipped = super.skip(n - sumSkipped); + if (skipped != 0) { + sumSkipped += skipped; + continue; + } + if (read() < 0) + break; // EOF - sumSkipped += 1; + sumSkipped += 1; /* was incremented by read() */ - bytesRead -= 1; - } + bytesRead -= 1; + } - if (dbg) - log.debug("skip:{}/{} pos:{}", n, sumSkipped, bytesRead); + if (dbg) + log.debug("skip:{}/{} pos:{}", n, sumSkipped, bytesRead); - bytesRead += sumSkipped; - return sumSkipped; - } + bytesRead += sumSkipped; + return sumSkipped; + } - @Override - public synchronized void reset() throws IOException { - if (dbg) - log.debug("reset"); + @Override + public synchronized void reset() throws IOException { + if (dbg) + log.debug("reset"); - if (marked >= 0) - bytesRead = marked; + if (marked >= 0) + bytesRead = marked; /* TODO could check if the mark is already invalid */ - super.reset(); - } + super.reset(); + } - @Override - public int read() throws IOException { - if (bytesRead >= contentLength) - return -1; + @Override + public int read() throws IOException { + if (bytesRead >= contentLength) + return -1; - int data = super.read(); + int data = super.read(); - if (data >= 0) - bytesRead += 1; + if (data >= 0) + bytesRead += 1; - if (cache != null && bytesRead > bytesWrote) { - bytesWrote = bytesRead; - cache.write(data); - } + if (cache != null && bytesRead > bytesWrote) { + bytesWrote = bytesRead; + cache.write(data); + } - return data; - } + return data; + } - @Override - public int read(byte[] buffer, int offset, int byteCount) - throws IOException { + @Override + public int read(byte[] buffer, int offset, int byteCount) + throws IOException { - if (bytesRead >= contentLength) - return -1; + if (bytesRead >= contentLength) + return -1; - int len = super.read(buffer, offset, byteCount); + int len = super.read(buffer, offset, byteCount); - if (dbg) - log.debug("read {} {} {}", len, bytesRead, contentLength); + if (dbg) + log.debug("read {} {} {}", len, bytesRead, contentLength); - if (len <= 0) - return len; + if (len <= 0) + return len; - bytesRead += len; + bytesRead += len; - if (cache != null && bytesRead > bytesWrote) { - int add = bytesRead - bytesWrote; - bytesWrote = bytesRead; - cache.write(buffer, offset + (len - add), add); - } + if (cache != null && bytesRead > bytesWrote) { + int add = bytesRead - bytesWrote; + bytesWrote = bytesRead; + cache.write(buffer, offset + (len - add), add); + } - return len; - } - } + return len; + } + } - private void checkSocket() throws IOException { - if (mSocket == null) - throw new IOException("No Socket"); - } + private void checkSocket() throws IOException { + if (mSocket == null) + throw new IOException("No Socket"); + } - public synchronized InputStream read() throws IOException { - checkSocket(); + public synchronized InputStream read() throws IOException { + checkSocket(); - Buffer is = mResponseStream; - is.mark(BUFFER_SIZE); - is.start(BUFFER_SIZE); + Buffer is = mResponseStream; + is.mark(BUFFER_SIZE); + is.start(BUFFER_SIZE); - byte[] buf = buffer; - boolean first = true; - boolean gzip = false; + byte[] buf = buffer; + boolean first = true; + boolean gzip = false; - int read = 0; - int pos = 0; - int end = 0; - int len = 0; + int read = 0; + int pos = 0; + int end = 0; + int len = 0; - int contentLength = -1; + int contentLength = -1; /* header may not be larger than BUFFER_SIZE for this to work */ - for (; (pos < read) || ((read < BUFFER_SIZE) && - (len = is.read(buf, read, BUFFER_SIZE - read)) >= 0); len = 0) { + for (; (pos < read) || ((read < BUFFER_SIZE) && + (len = is.read(buf, read, BUFFER_SIZE - read)) >= 0); len = 0) { - read += len; + read += len; /* end of header lines */ - while (end < read && (buf[end] != '\n')) - end++; + while (end < read && (buf[end] != '\n')) + end++; - if (end == BUFFER_SIZE) { - throw new IOException("Header too large!"); - } + if (end == BUFFER_SIZE) { + throw new IOException("Header too large!"); + } - if (buf[end] != '\n') - continue; + if (buf[end] != '\n') + continue; /* empty line (header end) */ - if (end - pos == 1) { - end += 1; - break; - } + if (end - pos == 1) { + end += 1; + break; + } - if (first) { - first = false; + if (first) { + first = false; /* check only for OK ("HTTP/1.? ".length == 9) */ - if (!check(HEADER_HTTP_OK, buf, pos + 9, end)) { - throw new IOException("HTTP Error: " - + new String(buf, pos, end - pos - 1)); - } - } else if (check(HEADER_CONTENT_LENGTH, buf, pos, end)) { + if (!check(HEADER_HTTP_OK, buf, pos + 9, end)) { + throw new IOException("HTTP Error: " + + new String(buf, pos, end - pos - 1)); + } + } else if (check(HEADER_CONTENT_LENGTH, buf, pos, end)) { /* parse Content-Length */ - contentLength = parseInt(buf, pos + - HEADER_CONTENT_LENGTH.length + 2, end - 1); - } else if (check(HEADER_ENCODING_GZIP, buf, pos, end)) { - gzip = true; - } else if (check(HEADER_CONNECTION_CLOSE, buf, pos, end)) { - mMustCloseConnection = true; - } + contentLength = parseInt(buf, pos + + HEADER_CONTENT_LENGTH.length + 2, end - 1); + } else if (check(HEADER_ENCODING_GZIP, buf, pos, end)) { + gzip = true; + } else if (check(HEADER_CONNECTION_CLOSE, buf, pos, end)) { + mMustCloseConnection = true; + } - if (dbg) { - String line = new String(buf, pos, end - pos - 1); - log.debug("> {} <", line); - } + if (dbg) { + String line = new String(buf, pos, end - pos - 1); + log.debug("> {} <", line); + } - pos += (end - pos) + 1; - end = pos; - } + pos += (end - pos) + 1; + end = pos; + } /* back to start of content */ - is.reset(); - is.mark(0); - is.skip(end); - is.start(contentLength); + is.reset(); + is.mark(0); + is.skip(end); + is.start(contentLength); - if (gzip) { - return new GZIPInputStream(is); - } - return is; - } + if (gzip) { + return new GZIPInputStream(is); + } + return is; + } - @Override - public synchronized void sendRequest(Tile tile) throws IOException { + @Override + public synchronized void sendRequest(Tile tile) throws IOException { - if (mSocket != null) { - if (--mMaxRequests < 0) - close(); - else if (System.nanoTime() - mLastRequest > RESPONSE_TIMEOUT) - close(); - else { - try { - int n = mResponseStream.available(); - if (n > 0) { - log.debug("left over bytes {} ", n); - close(); - } - } catch (IOException e) { - log.debug(e.getMessage()); - close(); - } - } - } + if (mSocket != null) { + if (--mMaxRequests < 0) + close(); + else if (System.nanoTime() - mLastRequest > RESPONSE_TIMEOUT) + close(); + else { + try { + int n = mResponseStream.available(); + if (n > 0) { + log.debug("left over bytes {} ", n); + close(); + } + } catch (IOException e) { + log.debug(e.getMessage()); + close(); + } + } + } - if (mSocket == null) { + if (mSocket == null) { /* might throw IOException */ - lwHttpConnect(); + lwHttpConnect(); /* TODO parse from header */ - mMaxRequests = RESPONSE_EXPECTED_LIVES; - } + mMaxRequests = RESPONSE_EXPECTED_LIVES; + } - int pos = REQUEST_GET_START.length; - int len = REQUEST_GET_END.length; + int pos = REQUEST_GET_START.length; + int len = REQUEST_GET_END.length; - pos = formatTilePath(tile, mRequestBuffer, pos); - System.arraycopy(REQUEST_GET_END, 0, mRequestBuffer, pos, len); - len += pos; + pos = formatTilePath(tile, mRequestBuffer, pos); + System.arraycopy(REQUEST_GET_END, 0, mRequestBuffer, pos, len); + len += pos; - if (dbg) - log.debug("request: {}", new String(mRequestBuffer, 0, len)); + if (dbg) + log.debug("request: {}", new String(mRequestBuffer, 0, len)); - try { - writeRequest(len); - } catch (IOException e) { - log.debug("recreate connection"); - close(); + try { + writeRequest(len); + } catch (IOException e) { + log.debug("recreate connection"); + close(); - lwHttpConnect(); - writeRequest(len); - } - } + lwHttpConnect(); + writeRequest(len); + } + } - private void writeRequest(int length) throws IOException { - mCommandStream.write(mRequestBuffer, 0, length); - //mCommandStream.flush(); - } + private void writeRequest(int length) throws IOException { + mCommandStream.write(mRequestBuffer, 0, length); + //mCommandStream.flush(); + } - private synchronized void lwHttpConnect() throws IOException { - if (mSockAddr == null || mSockAddr.isUnresolved()) { - mSockAddr = new InetSocketAddress(mHost, mPort); - if (mSockAddr.isUnresolved()) - throw new UnknownHostException(mHost); - } + private synchronized void lwHttpConnect() throws IOException { + if (mSockAddr == null || mSockAddr.isUnresolved()) { + mSockAddr = new InetSocketAddress(mHost, mPort); + if (mSockAddr.isUnresolved()) + throw new UnknownHostException(mHost); + } - try { - mSocket = new Socket(); - mSocket.setTcpNoDelay(true); - mSocket.setSoTimeout(SOCKET_TIMEOUT); - mSocket.connect(mSockAddr, CONNECT_TIMEOUT); - mCommandStream = mSocket.getOutputStream(); - mResponseStream = new Buffer(mSocket.getInputStream()); + try { + mSocket = new Socket(); + mSocket.setTcpNoDelay(true); + mSocket.setSoTimeout(SOCKET_TIMEOUT); + mSocket.connect(mSockAddr, CONNECT_TIMEOUT); + mCommandStream = mSocket.getOutputStream(); + mResponseStream = new Buffer(mSocket.getInputStream()); - mMustCloseConnection = false; - } catch (IOException e) { - close(); - throw e; - } - } + mMustCloseConnection = false; + } catch (IOException e) { + close(); + throw e; + } + } - @Override - public void close() { - IOUtils.closeQuietly(mSocket); - synchronized (this) { - mSocket = null; - mCommandStream = null; - mResponseStream = null; - } - } + @Override + public void close() { + IOUtils.closeQuietly(mSocket); + synchronized (this) { + mSocket = null; + mCommandStream = null; + mResponseStream = null; + } + } - @Override - public synchronized void setCache(OutputStream os) { - if (mSocket == null) - return; + @Override + public synchronized void setCache(OutputStream os) { + if (mSocket == null) + return; - mResponseStream.setCache(os); - } + mResponseStream.setCache(os); + } - @Override - public synchronized boolean requestCompleted(boolean ok) { - if (mSocket == null) - return false; + @Override + public synchronized boolean requestCompleted(boolean ok) { + if (mSocket == null) + return false; - mLastRequest = System.nanoTime(); - mResponseStream.setCache(null); + mLastRequest = System.nanoTime(); + mResponseStream.setCache(null); - if (!ok || mMustCloseConnection || !mResponseStream.finishedReading()) - close(); + if (!ok || mMustCloseConnection || !mResponseStream.finishedReading()) + close(); - return ok; - } + return ok; + } - /** write (positive) integer to byte array */ - private static int writeInt(int val, int pos, byte[] buf) { - if (val == 0) { - buf[pos] = '0'; - return pos + 1; - } + /** + * write (positive) integer to byte array + */ + private static int writeInt(int val, int pos, byte[] buf) { + if (val == 0) { + buf[pos] = '0'; + return pos + 1; + } - int i = 0; - for (int n = val; n > 0; n = n / 10, i++) - buf[pos + i] = (byte) ('0' + n % 10); + int i = 0; + for (int n = val; n > 0; n = n / 10, i++) + buf[pos + i] = (byte) ('0' + n % 10); - ArrayUtils.reverse(buf, pos, pos + i); + ArrayUtils.reverse(buf, pos, pos + i); - return pos + i; - } + return pos + i; + } - /** parse (positive) integer from byte array */ - private static int parseInt(byte[] buf, int pos, int end) { - int val = 0; - for (; pos < end; pos++) - val = val * 10 + (buf[pos]) - '0'; + /** + * parse (positive) integer from byte array + */ + private static int parseInt(byte[] buf, int pos, int end) { + int val = 0; + for (; pos < end; pos++) + val = val * 10 + (buf[pos]) - '0'; - return val; - } + return val; + } - private static boolean check(byte[] string, byte[] buffer, - int position, int available) { + private static boolean check(byte[] string, byte[] buffer, + int position, int available) { - int length = string.length; + int length = string.length; - if (available - position < length) - return false; + if (available - position < length) + return false; - for (int i = 0; i < length; i++) - if (buffer[position + i] != string[i]) - return false; + for (int i = 0; i < length; i++) + if (buffer[position + i] != string[i]) + return false; - return true; - } + return true; + } - /** - * @param tile the Tile - * @param buf to write url string - * @param pos current position - * @return new position - */ - private int formatTilePath(Tile tile, byte[] buf, int pos) { - if (mTilePath == null) { - String url = mTileSource.getUrlFormatter() - .formatTilePath(mTileSource, tile); - byte[] b = url.getBytes(); - System.arraycopy(b, 0, buf, pos, b.length); - return pos + b.length; - } + /** + * @param tile the Tile + * @param buf to write url string + * @param pos current position + * @return new position + */ + private int formatTilePath(Tile tile, byte[] buf, int pos) { + if (mTilePath == null) { + String url = mTileSource.getUrlFormatter() + .formatTilePath(mTileSource, tile); + byte[] b = url.getBytes(); + System.arraycopy(b, 0, buf, pos, b.length); + return pos + b.length; + } - for (byte[] b : mTilePath) { - if (b.length == 1) { - if (b[0] == '/') { - buf[pos++] = '/'; - continue; - } else if (b[0] == 'X') { - pos = writeInt(tile.tileX, pos, buf); - continue; - } else if (b[0] == 'Y') { - pos = writeInt(tile.tileY, pos, buf); - continue; - } else if (b[0] == 'Z') { - pos = writeInt(tile.zoomLevel, pos, buf); - continue; - } - } - System.arraycopy(b, 0, buf, pos, b.length); - pos += b.length; - } - return pos; + for (byte[] b : mTilePath) { + if (b.length == 1) { + if (b[0] == '/') { + buf[pos++] = '/'; + continue; + } else if (b[0] == 'X') { + pos = writeInt(tile.tileX, pos, buf); + continue; + } else if (b[0] == 'Y') { + pos = writeInt(tile.tileY, pos, buf); + continue; + } else if (b[0] == 'Z') { + pos = writeInt(tile.zoomLevel, pos, buf); + continue; + } + } + System.arraycopy(b, 0, buf, pos, b.length); + pos += b.length; + } + return pos; - } + } - public static class LwHttpFactory implements HttpEngine.Factory { - private byte[][] mTilePath; + public static class LwHttpFactory implements HttpEngine.Factory { + private byte[][] mTilePath; - @Override - public HttpEngine create(UrlTileSource tileSource) { - if (tileSource.getUrlFormatter() != UrlTileSource.URL_FORMATTER) - return new LwHttp(tileSource, null); + @Override + public HttpEngine create(UrlTileSource tileSource) { + if (tileSource.getUrlFormatter() != UrlTileSource.URL_FORMATTER) + return new LwHttp(tileSource, null); /* use optimized formatter replacing the default */ - if (mTilePath == null) { - String[] path = tileSource.getTilePath(); - mTilePath = new byte[path.length][]; - for (int i = 0; i < path.length; i++) - mTilePath[i] = path[i].getBytes(); - } - return new LwHttp(tileSource, mTilePath); - } - } + if (mTilePath == null) { + String[] path = tileSource.getTilePath(); + mTilePath = new byte[path.length][]; + for (int i = 0; i < path.length; i++) + mTilePath[i] = path[i].getBytes(); + } + return new LwHttp(tileSource, mTilePath); + } + } } diff --git a/vtm/src/org/oscim/tiling/source/OkHttpEngine.java b/vtm/src/org/oscim/tiling/source/OkHttpEngine.java index a2783dbe..b2d20f5a 100644 --- a/vtm/src/org/oscim/tiling/source/OkHttpEngine.java +++ b/vtm/src/org/oscim/tiling/source/OkHttpEngine.java @@ -17,6 +17,14 @@ */ package org.oscim.tiling.source; +import com.squareup.okhttp.HttpResponseCache; +import com.squareup.okhttp.OkHttpClient; + +import org.oscim.core.Tile; +import org.oscim.utils.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -25,94 +33,86 @@ import java.net.HttpURLConnection; import java.net.URL; import java.util.Map.Entry; -import org.oscim.core.Tile; -import org.oscim.utils.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.squareup.okhttp.HttpResponseCache; -import com.squareup.okhttp.OkHttpClient; - public class OkHttpEngine implements HttpEngine { - static final Logger log = LoggerFactory.getLogger(OkHttpEngine.class); + static final Logger log = LoggerFactory.getLogger(OkHttpEngine.class); - private final OkHttpClient mClient; - private final UrlTileSource mTileSource; + private final OkHttpClient mClient; + private final UrlTileSource mTileSource; - public static class OkHttpFactory implements HttpEngine.Factory { - private final OkHttpClient mClient; + public static class OkHttpFactory implements HttpEngine.Factory { + private final OkHttpClient mClient; - public OkHttpFactory() { - mClient = new OkHttpClient(); - } + public OkHttpFactory() { + mClient = new OkHttpClient(); + } - public OkHttpFactory(HttpResponseCache responseCache) { - mClient = new OkHttpClient(); - mClient.setResponseCache(responseCache); - } + public OkHttpFactory(HttpResponseCache responseCache) { + mClient = new OkHttpClient(); + mClient.setResponseCache(responseCache); + } - @Override - public HttpEngine create(UrlTileSource tileSource) { - return new OkHttpEngine(mClient, tileSource); - } - } + @Override + public HttpEngine create(UrlTileSource tileSource) { + return new OkHttpEngine(mClient, tileSource); + } + } - private InputStream inputStream; + private InputStream inputStream; - public OkHttpEngine(OkHttpClient client, UrlTileSource tileSource) { - mClient = client; - mTileSource = tileSource; - } + public OkHttpEngine(OkHttpClient client, UrlTileSource tileSource) { + mClient = client; + mTileSource = tileSource; + } - @Override - public InputStream read() throws IOException { - return inputStream; - } + @Override + public InputStream read() throws IOException { + return inputStream; + } - @Override - public void sendRequest(Tile tile) throws IOException { - if (tile == null) { - throw new IllegalArgumentException("Tile cannot be null."); - } - URL url = new URL(mTileSource.getTileUrl(tile)); - HttpURLConnection conn = mClient.open(url); + @Override + public void sendRequest(Tile tile) throws IOException { + if (tile == null) { + throw new IllegalArgumentException("Tile cannot be null."); + } + URL url = new URL(mTileSource.getTileUrl(tile)); + HttpURLConnection conn = mClient.open(url); - for (Entry opt : mTileSource.getRequestHeader().entrySet()) - conn.addRequestProperty(opt.getKey(), opt.getValue()); + for (Entry opt : mTileSource.getRequestHeader().entrySet()) + conn.addRequestProperty(opt.getKey(), opt.getValue()); - try { - inputStream = conn.getInputStream(); - } catch (FileNotFoundException e) { - throw new IOException("ERROR " + conn.getResponseCode() - + ": " + conn.getResponseMessage()); - } - } + try { + inputStream = conn.getInputStream(); + } catch (FileNotFoundException e) { + throw new IOException("ERROR " + conn.getResponseCode() + + ": " + conn.getResponseMessage()); + } + } - @Override - public void close() { - if (inputStream == null) - return; + @Override + public void close() { + if (inputStream == null) + return; - final InputStream is = inputStream; - inputStream = null; - new Thread(new Runnable() { - @Override - public void run() { - IOUtils.closeQuietly(is); - } - }).start(); - } + final InputStream is = inputStream; + inputStream = null; + new Thread(new Runnable() { + @Override + public void run() { + IOUtils.closeQuietly(is); + } + }).start(); + } - @Override - public void setCache(OutputStream os) { - // OkHttp cache implented through tileSource setResponseCache - } + @Override + public void setCache(OutputStream os) { + // OkHttp cache implented through tileSource setResponseCache + } - @Override - public boolean requestCompleted(boolean success) { - IOUtils.closeQuietly(inputStream); - inputStream = null; + @Override + public boolean requestCompleted(boolean success) { + IOUtils.closeQuietly(inputStream); + inputStream = null; - return success; - } + return success; + } } diff --git a/vtm/src/org/oscim/tiling/source/PbfDecoder.java b/vtm/src/org/oscim/tiling/source/PbfDecoder.java index c7668a65..424f6ef0 100644 --- a/vtm/src/org/oscim/tiling/source/PbfDecoder.java +++ b/vtm/src/org/oscim/tiling/source/PbfDecoder.java @@ -16,546 +16,546 @@ */ package org.oscim.tiling.source; -import java.io.IOException; -import java.io.InputStream; - import org.oscim.core.GeometryBuffer; import org.oscim.utils.UTF8Decoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; + public abstract class PbfDecoder implements ITileDecoder { - static final Logger log = LoggerFactory.getLogger(PbfDecoder.class); + static final Logger log = LoggerFactory.getLogger(PbfDecoder.class); - private final static int S1 = 7; - private final static int S2 = 14; - private final static int S3 = 21; - private final static int S4 = 28; + private final static int S1 = 7; + private final static int S2 = 14; + private final static int S3 = 21; + private final static int S4 = 28; - private final static int M1 = (1 << S1) - 1; - private final static int M2 = (1 << S2) - 1; - private final static int M3 = (1 << S3) - 1; - private final static int M4 = (1 << S4) - 1; + private final static int M1 = (1 << S1) - 1; + private final static int M2 = (1 << S2) - 1; + private final static int M3 = (1 << S3) - 1; + private final static int M4 = (1 << S4) - 1; - protected static final boolean debug = false; + protected static final boolean debug = false; - static class ProtobufException extends IOException { - private static final long serialVersionUID = 1L; + static class ProtobufException extends IOException { + private static final long serialVersionUID = 1L; - public ProtobufException(String detailMessage) { - super(detailMessage); - } - } + public ProtobufException(String detailMessage) { + super(detailMessage); + } + } - final static ProtobufException TRUNCATED_MSG = - new ProtobufException("truncated msg"); + final static ProtobufException TRUNCATED_MSG = + new ProtobufException("truncated msg"); - protected final static ProtobufException INVALID_VARINT = - new ProtobufException("invalid varint"); + protected final static ProtobufException INVALID_VARINT = + new ProtobufException("invalid varint"); - protected final static ProtobufException INVALID_PACKED_SIZE = - new ProtobufException("invalid message size"); + protected final static ProtobufException INVALID_PACKED_SIZE = + new ProtobufException("invalid message size"); - protected void error(String msg) throws IOException { - throw new ProtobufException(msg); - } + protected void error(String msg) throws IOException { + throw new ProtobufException(msg); + } - private final static int BUFFER_SIZE = 1 << 15; // 32kb - protected byte[] buffer = new byte[BUFFER_SIZE]; + private final static int BUFFER_SIZE = 1 << 15; // 32kb + protected byte[] buffer = new byte[BUFFER_SIZE]; - // position in buffer - protected int bufferPos; + // position in buffer + protected int bufferPos; - // bytes available in buffer - protected int bufferFill; + // bytes available in buffer + protected int bufferFill; - // offset of buffer in message - private int mBufferOffset; + // offset of buffer in message + private int mBufferOffset; - // overall bytes of message read - private int mMsgPos; + // overall bytes of message read + private int mMsgPos; - private InputStream mInputStream; + private InputStream mInputStream; - private final UTF8Decoder mStringDecoder; + private final UTF8Decoder mStringDecoder; - public PbfDecoder() { - mStringDecoder = new UTF8Decoder(); - } + public PbfDecoder() { + mStringDecoder = new UTF8Decoder(); + } - public void setInputStream(InputStream is) { - mInputStream = is; + public void setInputStream(InputStream is) { + mInputStream = is; - bufferFill = 0; - bufferPos = 0; - mBufferOffset = 0; + bufferFill = 0; + bufferPos = 0; + mBufferOffset = 0; - mMsgPos = 0; - } + mMsgPos = 0; + } - protected int decodeVarint32() throws IOException { + protected int decodeVarint32() throws IOException { - int bytesLeft = 0; - int val = 0; + int bytesLeft = 0; + int val = 0; - for (int shift = 0; shift < 32; shift += 7) { - if (bytesLeft == 0) - bytesLeft = fillBuffer(1); + for (int shift = 0; shift < 32; shift += 7) { + if (bytesLeft == 0) + bytesLeft = fillBuffer(1); - byte b = buffer[bufferPos++]; - val |= (b & 0x7f) << shift; + byte b = buffer[bufferPos++]; + val |= (b & 0x7f) << shift; - if (b >= 0) - return val; + if (b >= 0) + return val; - bytesLeft--; - } + bytesLeft--; + } - throw INVALID_VARINT; - } + throw INVALID_VARINT; + } - protected long decodeVarint64() throws IOException { + protected long decodeVarint64() throws IOException { - int bytesLeft = 0; - long val = 0; + int bytesLeft = 0; + long val = 0; - for (int shift = 0; shift < 64; shift += 7) { - if (bytesLeft == 0) - bytesLeft = fillBuffer(1); + for (int shift = 0; shift < 64; shift += 7) { + if (bytesLeft == 0) + bytesLeft = fillBuffer(1); - byte b = buffer[bufferPos++]; - val |= (long) (b & 0x7f) << shift; + byte b = buffer[bufferPos++]; + val |= (long) (b & 0x7f) << shift; - if (b >= 0) - return val; + if (b >= 0) + return val; - bytesLeft--; - } + bytesLeft--; + } - throw INVALID_VARINT; - } + throw INVALID_VARINT; + } - protected String decodeString() throws IOException { - String result; + protected String decodeString() throws IOException { + String result; - final int size = decodeVarint32(); - fillBuffer(size); + final int size = decodeVarint32(); + fillBuffer(size); - if (mStringDecoder == null) - result = new String(buffer, bufferPos, size, "UTF-8"); - else - result = mStringDecoder.decode(buffer, bufferPos, size); + if (mStringDecoder == null) + result = new String(buffer, bufferPos, size, "UTF-8"); + else + result = mStringDecoder.decode(buffer, bufferPos, size); - bufferPos += size; + bufferPos += size; - return result; + return result; - } + } - protected float decodeFloat() throws IOException { - if (bufferPos + 4 > bufferFill) - fillBuffer(4); + protected float decodeFloat() throws IOException { + if (bufferPos + 4 > bufferFill) + fillBuffer(4); - int val = (buffer[bufferPos++] & 0xFF - | (buffer[bufferPos++] & 0xFF) << 8 - | (buffer[bufferPos++] & 0xFF) << 16 - | (buffer[bufferPos++] & 0xFF) << 24); + int val = (buffer[bufferPos++] & 0xFF + | (buffer[bufferPos++] & 0xFF) << 8 + | (buffer[bufferPos++] & 0xFF) << 16 + | (buffer[bufferPos++] & 0xFF) << 24); - return Float.intBitsToFloat(val); - } + return Float.intBitsToFloat(val); + } - protected double decodeDouble() throws IOException { - if (bufferPos + 8 > bufferFill) - fillBuffer(8); + protected double decodeDouble() throws IOException { + if (bufferPos + 8 > bufferFill) + fillBuffer(8); - long val = ((long) buffer[bufferPos++] & 0xFF - | ((long) buffer[bufferPos++] & 0xFF) << 8 - | ((long) buffer[bufferPos++] & 0xFF) << 16 - | ((long) buffer[bufferPos++] & 0xFF) << 24 - | ((long) buffer[bufferPos++] & 0xFF) << 32 - | ((long) buffer[bufferPos++] & 0xFF) << 40 - | ((long) buffer[bufferPos++] & 0xFF) << 48 - | ((long) buffer[bufferPos++] & 0xFF) << 56); + long val = ((long) buffer[bufferPos++] & 0xFF + | ((long) buffer[bufferPos++] & 0xFF) << 8 + | ((long) buffer[bufferPos++] & 0xFF) << 16 + | ((long) buffer[bufferPos++] & 0xFF) << 24 + | ((long) buffer[bufferPos++] & 0xFF) << 32 + | ((long) buffer[bufferPos++] & 0xFF) << 40 + | ((long) buffer[bufferPos++] & 0xFF) << 48 + | ((long) buffer[bufferPos++] & 0xFF) << 56); - return Double.longBitsToDouble(val); - } - - protected boolean decodeBool() throws IOException { - if (bufferPos + 1 > bufferFill) - fillBuffer(1); - - return buffer[bufferPos++] != 0; - } - - protected int decodeInterleavedPoints(GeometryBuffer geom, float scale) - throws IOException { - - float[] points = geom.points; - int bytes = decodeVarint32(); - fillBuffer(bytes); - - int cnt = 0; - int lastX = 0; - int lastY = 0; - boolean even = true; - - byte[] buf = buffer; - int pos = bufferPos; - int end = pos + bytes; - - while (pos < end) { - byte b = buf[pos++]; - int val = b; - - if (b < 0) { - b = buf[pos++]; - val = (val & M1) | (b << S1); - if (b < 0) { - b = buf[pos++]; - val = (val & M2) | (b << S2); - if (b < 0) { - b = buf[pos++]; - val = (val & M3) | (b << S3); - if (b < 0) { - b = buf[pos++]; - val = (val & M4) | (b << S4); - if (b < 0) - throw INVALID_VARINT; - } - } - } - } - // zigzag decoding - int s = ((val >>> 1) ^ -(val & 1)); - - if (even) { - lastX = lastX + s; - points[cnt++] = lastX / scale; - even = false; - } else { - lastY = lastY + s; - points[cnt++] = lastY / scale; - even = true; - } - } - - if (pos != bufferPos + bytes) - throw INVALID_PACKED_SIZE; - - bufferPos = pos; - - geom.pointPos = cnt; - - // return number of points read - return (cnt >> 1); - } - - protected int decodeInterleavedPoints3D(float[] coords, float scale) - throws IOException { - - int bytes = decodeVarint32(); - fillBuffer(bytes); - - int cnt = 0; - int lastX = 0; - int lastY = 0; - int lastZ = 0; - - int cur = 0; - - byte[] buf = buffer; - int pos = bufferPos; - int end = pos + bytes; - - while (pos < end) { - byte b = buf[pos++]; - int val = b; - - if (b < 0) { - b = buf[pos++]; - val = (val & M1) | (b << S1); - if (b < 0) { - b = buf[pos++]; - val = (val & M2) | (b << S2); - if (b < 0) { - b = buf[pos++]; - val = (val & M3) | (b << S3); - if (b < 0) { - b = buf[pos++]; - val = (val & M4) | (b << S4); - if (b < 0) - throw INVALID_VARINT; - } - } - } - } - // zigzag decoding - int s = ((val >>> 1) ^ -(val & 1)); - - if (cur == 0) { - lastX = lastX + s; - coords[cnt++] = lastX / scale; - } else if (cur == 1) { - lastY = lastY + s; - coords[cnt++] = lastY / scale; - } else { - lastZ = lastZ + s; - coords[cnt++] = lastZ / scale; - } - cur = (cur + 1) % 3; - } - - if (pos != bufferPos + bytes) - throw INVALID_PACKED_SIZE; - - bufferPos = pos; - - // return number of points read - //FIXME inconsitent with 3d version! - return cnt; - } - - protected static int deZigZag(int val) { - return ((val >>> 1) ^ -(val & 1)); - } - - public void decodeVarintArray(int num, int[] array) throws IOException { - int bytes = decodeVarint32(); - fillBuffer(bytes); - - final byte[] buf = buffer; - int pos = bufferPos; - int cnt = 0; - - for (int end = pos + bytes; pos < end; cnt++) { - if (cnt == num) - throw new ProtobufException("invalid array size " + num); - - byte b = buf[pos++]; - int val = b; - - if (b < 0) { - b = buf[pos++]; - val = (val & M1) | (b << S1); - if (b < 0) { - b = buf[pos++]; - val = (val & M2) | (b << S2); - if (b < 0) { - b = buf[pos++]; - val = (val & M3) | (b << S3); - if (b < 0) { - b = buf[pos++]; - val = (val & M4) | (b << S4); - if (b < 0) - throw INVALID_VARINT; - } - } - } - } - - array[cnt] = val; - } - - if (pos != bufferPos + bytes) - throw INVALID_PACKED_SIZE; - - bufferPos = pos; - } - - /** - * fill short array from packed uint32. Array values must be positive - * as the end will be marked by -1 if the resulting array is larger - * than the input! - */ - protected short[] decodeUnsignedVarintArray(short[] array) throws IOException { - int bytes = decodeVarint32(); - - int arrayLength = 0; - if (array == null) { - arrayLength = 32; - array = new short[32]; - } - - fillBuffer(bytes); - int cnt = 0; - - final byte[] buf = buffer; - int pos = bufferPos; - - for (int end = pos + bytes; pos < end; cnt++) { - - byte b = buf[pos++]; - int val = b; - - if (b < 0) { - b = buf[pos++]; - val = (val & M1) | (b << S1); - if (b < 0) { - b = buf[pos++]; - val = (val & M2) | (b << S2); - if (b < 0) { - b = buf[pos++]; - val = (val & M3) | (b << S3); - if (b < 0) { - b = buf[pos++]; - val = (val & M4) | (b << S4); - if (b < 0) - throw INVALID_VARINT; - } - } - } - } - - if (arrayLength <= cnt) { - arrayLength = cnt + 16; - short[] tmp = array; - array = new short[arrayLength]; - System.arraycopy(tmp, 0, array, 0, cnt); - } - - array[cnt] = (short) val; - } - - if (pos != bufferPos + bytes) - throw INVALID_PACKED_SIZE; - - bufferPos = pos; - - if (arrayLength > cnt) - array[cnt] = -1; - - return array; - } - - // for use int packed varint decoders - protected int decodeVarint32Filled() throws IOException { - - byte[] buf = buffer; - int pos = bufferPos; - - byte b = buf[pos++]; - int val = b; - - if (b < 0) { - b = buf[pos++]; - val = (val & M1) | (b << S1); - if (b < 0) { - b = buf[pos++]; - val = (val & M2) | (b << S2); - if (b < 0) { - b = buf[pos++]; - val = (val & M3) | (b << S3); - if (b < 0) { - b = buf[pos++]; - val = (val & M4) | (b << S4); - if (b < 0) - throw INVALID_VARINT; - } - } - } - } - - bufferPos = pos; - - return val; - } - - public boolean hasData() throws IOException { - //if (mBufferOffset + bufferPos >= mMsgEnd) - // return false; - - return fillBuffer(1) > 0; - } - - public int position() { - return mBufferOffset + bufferPos; - } - - public int fillBuffer(int size) throws IOException { - int bytesLeft = bufferFill - bufferPos; - - // check if buffer already contains the request bytes - if (bytesLeft >= size) - return bytesLeft; - - int maxSize = buffer.length; - - if (size > maxSize) { - - if (debug) - log.debug("increase read buffer to " + size + " bytes"); - - maxSize = size; - - byte[] tmp = buffer; - buffer = new byte[maxSize]; - System.arraycopy(tmp, bufferPos, buffer, 0, bytesLeft); - - mBufferOffset += bufferPos; - bufferPos = 0; - bufferFill = bytesLeft; - - } else if (bytesLeft == 0) { - // just advance buffer offset and reset buffer - mBufferOffset += bufferPos; - bufferPos = 0; - bufferFill = 0; - - } else if (bufferPos + size > maxSize) { - // copy bytes left to the beginning of buffer - if (debug) - log.debug("shift " + bufferFill + " " + bufferPos + " " + size); + return Double.longBitsToDouble(val); + } + + protected boolean decodeBool() throws IOException { + if (bufferPos + 1 > bufferFill) + fillBuffer(1); + + return buffer[bufferPos++] != 0; + } + + protected int decodeInterleavedPoints(GeometryBuffer geom, float scale) + throws IOException { + + float[] points = geom.points; + int bytes = decodeVarint32(); + fillBuffer(bytes); + + int cnt = 0; + int lastX = 0; + int lastY = 0; + boolean even = true; + + byte[] buf = buffer; + int pos = bufferPos; + int end = pos + bytes; + + while (pos < end) { + byte b = buf[pos++]; + int val = b; + + if (b < 0) { + b = buf[pos++]; + val = (val & M1) | (b << S1); + if (b < 0) { + b = buf[pos++]; + val = (val & M2) | (b << S2); + if (b < 0) { + b = buf[pos++]; + val = (val & M3) | (b << S3); + if (b < 0) { + b = buf[pos++]; + val = (val & M4) | (b << S4); + if (b < 0) + throw INVALID_VARINT; + } + } + } + } + // zigzag decoding + int s = ((val >>> 1) ^ -(val & 1)); + + if (even) { + lastX = lastX + s; + points[cnt++] = lastX / scale; + even = false; + } else { + lastY = lastY + s; + points[cnt++] = lastY / scale; + even = true; + } + } + + if (pos != bufferPos + bytes) + throw INVALID_PACKED_SIZE; + + bufferPos = pos; + + geom.pointPos = cnt; + + // return number of points read + return (cnt >> 1); + } + + protected int decodeInterleavedPoints3D(float[] coords, float scale) + throws IOException { + + int bytes = decodeVarint32(); + fillBuffer(bytes); + + int cnt = 0; + int lastX = 0; + int lastY = 0; + int lastZ = 0; + + int cur = 0; + + byte[] buf = buffer; + int pos = bufferPos; + int end = pos + bytes; + + while (pos < end) { + byte b = buf[pos++]; + int val = b; + + if (b < 0) { + b = buf[pos++]; + val = (val & M1) | (b << S1); + if (b < 0) { + b = buf[pos++]; + val = (val & M2) | (b << S2); + if (b < 0) { + b = buf[pos++]; + val = (val & M3) | (b << S3); + if (b < 0) { + b = buf[pos++]; + val = (val & M4) | (b << S4); + if (b < 0) + throw INVALID_VARINT; + } + } + } + } + // zigzag decoding + int s = ((val >>> 1) ^ -(val & 1)); + + if (cur == 0) { + lastX = lastX + s; + coords[cnt++] = lastX / scale; + } else if (cur == 1) { + lastY = lastY + s; + coords[cnt++] = lastY / scale; + } else { + lastZ = lastZ + s; + coords[cnt++] = lastZ / scale; + } + cur = (cur + 1) % 3; + } + + if (pos != bufferPos + bytes) + throw INVALID_PACKED_SIZE; + + bufferPos = pos; + + // return number of points read + //FIXME inconsitent with 3d version! + return cnt; + } + + protected static int deZigZag(int val) { + return ((val >>> 1) ^ -(val & 1)); + } + + public void decodeVarintArray(int num, int[] array) throws IOException { + int bytes = decodeVarint32(); + fillBuffer(bytes); + + final byte[] buf = buffer; + int pos = bufferPos; + int cnt = 0; + + for (int end = pos + bytes; pos < end; cnt++) { + if (cnt == num) + throw new ProtobufException("invalid array size " + num); + + byte b = buf[pos++]; + int val = b; + + if (b < 0) { + b = buf[pos++]; + val = (val & M1) | (b << S1); + if (b < 0) { + b = buf[pos++]; + val = (val & M2) | (b << S2); + if (b < 0) { + b = buf[pos++]; + val = (val & M3) | (b << S3); + if (b < 0) { + b = buf[pos++]; + val = (val & M4) | (b << S4); + if (b < 0) + throw INVALID_VARINT; + } + } + } + } + + array[cnt] = val; + } + + if (pos != bufferPos + bytes) + throw INVALID_PACKED_SIZE; + + bufferPos = pos; + } + + /** + * fill short array from packed uint32. Array values must be positive + * as the end will be marked by -1 if the resulting array is larger + * than the input! + */ + protected short[] decodeUnsignedVarintArray(short[] array) throws IOException { + int bytes = decodeVarint32(); + + int arrayLength = 0; + if (array == null) { + arrayLength = 32; + array = new short[32]; + } + + fillBuffer(bytes); + int cnt = 0; + + final byte[] buf = buffer; + int pos = bufferPos; + + for (int end = pos + bytes; pos < end; cnt++) { + + byte b = buf[pos++]; + int val = b; + + if (b < 0) { + b = buf[pos++]; + val = (val & M1) | (b << S1); + if (b < 0) { + b = buf[pos++]; + val = (val & M2) | (b << S2); + if (b < 0) { + b = buf[pos++]; + val = (val & M3) | (b << S3); + if (b < 0) { + b = buf[pos++]; + val = (val & M4) | (b << S4); + if (b < 0) + throw INVALID_VARINT; + } + } + } + } + + if (arrayLength <= cnt) { + arrayLength = cnt + 16; + short[] tmp = array; + array = new short[arrayLength]; + System.arraycopy(tmp, 0, array, 0, cnt); + } + + array[cnt] = (short) val; + } + + if (pos != bufferPos + bytes) + throw INVALID_PACKED_SIZE; + + bufferPos = pos; + + if (arrayLength > cnt) + array[cnt] = -1; + + return array; + } + + // for use int packed varint decoders + protected int decodeVarint32Filled() throws IOException { + + byte[] buf = buffer; + int pos = bufferPos; + + byte b = buf[pos++]; + int val = b; + + if (b < 0) { + b = buf[pos++]; + val = (val & M1) | (b << S1); + if (b < 0) { + b = buf[pos++]; + val = (val & M2) | (b << S2); + if (b < 0) { + b = buf[pos++]; + val = (val & M3) | (b << S3); + if (b < 0) { + b = buf[pos++]; + val = (val & M4) | (b << S4); + if (b < 0) + throw INVALID_VARINT; + } + } + } + } + + bufferPos = pos; + + return val; + } + + public boolean hasData() throws IOException { + //if (mBufferOffset + bufferPos >= mMsgEnd) + // return false; + + return fillBuffer(1) > 0; + } + + public int position() { + return mBufferOffset + bufferPos; + } + + public int fillBuffer(int size) throws IOException { + int bytesLeft = bufferFill - bufferPos; + + // check if buffer already contains the request bytes + if (bytesLeft >= size) + return bytesLeft; + + int maxSize = buffer.length; + + if (size > maxSize) { + + if (debug) + log.debug("increase read buffer to " + size + " bytes"); + + maxSize = size; + + byte[] tmp = buffer; + buffer = new byte[maxSize]; + System.arraycopy(tmp, bufferPos, buffer, 0, bytesLeft); + + mBufferOffset += bufferPos; + bufferPos = 0; + bufferFill = bytesLeft; + + } else if (bytesLeft == 0) { + // just advance buffer offset and reset buffer + mBufferOffset += bufferPos; + bufferPos = 0; + bufferFill = 0; + + } else if (bufferPos + size > maxSize) { + // copy bytes left to the beginning of buffer + if (debug) + log.debug("shift " + bufferFill + " " + bufferPos + " " + size); - System.arraycopy(buffer, bufferPos, buffer, 0, bytesLeft); + System.arraycopy(buffer, bufferPos, buffer, 0, bytesLeft); - mBufferOffset += bufferPos; - bufferPos = 0; - bufferFill = bytesLeft; - } + mBufferOffset += bufferPos; + bufferPos = 0; + bufferFill = bytesLeft; + } - while ((bufferFill - bufferPos) < size) { - int max = maxSize - bufferFill; + while ((bufferFill - bufferPos) < size) { + int max = maxSize - bufferFill; - if (max <= 0) { - // should not be possible - throw new IOException("burp"); - } + if (max <= 0) { + // should not be possible + throw new IOException("burp"); + } - // read until requested size is available in buffer - int len = mInputStream.read(buffer, bufferFill, max); + // read until requested size is available in buffer + int len = mInputStream.read(buffer, bufferFill, max); - if (len < 0) { - if (debug) - log.debug("finished reading {}", mMsgPos); - - // finished reading, mark end - buffer[bufferFill] = 0; - return bufferFill - bufferPos; - } - - mMsgPos += len; - bufferFill += len; - } - return bufferFill - bufferPos; - } - - protected static int readUnsignedInt(InputStream is, byte[] buf) throws IOException { - // check 4 bytes available.. - int read = 0; - int len = 0; + if (len < 0) { + if (debug) + log.debug("finished reading {}", mMsgPos); + + // finished reading, mark end + buffer[bufferFill] = 0; + return bufferFill - bufferPos; + } + + mMsgPos += len; + bufferFill += len; + } + return bufferFill - bufferPos; + } + + protected static int readUnsignedInt(InputStream is, byte[] buf) throws IOException { + // check 4 bytes available.. + int read = 0; + int len = 0; - while (read < 4 && (len = is.read(buf, read, 4 - read)) >= 0) - read += len; + while (read < 4 && (len = is.read(buf, read, 4 - read)) >= 0) + read += len; - if (read < 4) - return read < 0 ? (read * 10) : read; + if (read < 4) + return read < 0 ? (read * 10) : read; - return decodeInt(buf, 0); - } + return decodeInt(buf, 0); + } - static int decodeInt(byte[] buffer, int offset) { - return buffer[offset] << 24 | (buffer[offset + 1] & 0xff) << 16 - | (buffer[offset + 2] & 0xff) << 8 - | (buffer[offset + 3] & 0xff); - } + static int decodeInt(byte[] buffer, int offset) { + return buffer[offset] << 24 | (buffer[offset + 1] & 0xff) << 16 + | (buffer[offset + 2] & 0xff) << 8 + | (buffer[offset + 3] & 0xff); + } } diff --git a/vtm/src/org/oscim/tiling/source/UrlTileDataSource.java b/vtm/src/org/oscim/tiling/source/UrlTileDataSource.java index a808f290..5ca5ec3f 100644 --- a/vtm/src/org/oscim/tiling/source/UrlTileDataSource.java +++ b/vtm/src/org/oscim/tiling/source/UrlTileDataSource.java @@ -16,16 +16,6 @@ */ package org.oscim.tiling.source; -import static org.oscim.tiling.QueryResult.DELAYED; -import static org.oscim.tiling.QueryResult.FAILED; -import static org.oscim.tiling.QueryResult.SUCCESS; - -import java.io.IOException; -import java.io.InputStream; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; - import org.oscim.layers.tile.MapTile; import org.oscim.tiling.ITileCache; import org.oscim.tiling.ITileCache.TileReader; @@ -37,83 +27,93 @@ import org.oscim.utils.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; + +import static org.oscim.tiling.QueryResult.DELAYED; +import static org.oscim.tiling.QueryResult.FAILED; +import static org.oscim.tiling.QueryResult.SUCCESS; + public class UrlTileDataSource implements ITileDataSource { - static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class); + static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class); - protected final HttpEngine mConn; - protected final ITileDecoder mTileDecoder; - protected final UrlTileSource mTileSource; - protected final boolean mUseCache; + protected final HttpEngine mConn; + protected final ITileDecoder mTileDecoder; + protected final UrlTileSource mTileSource; + protected final boolean mUseCache; - public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) { - mTileDecoder = tileDecoder; - mTileSource = tileSource; - mUseCache = (tileSource.tileCache != null); - mConn = conn; - } + public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) { + mTileDecoder = tileDecoder; + mTileSource = tileSource; + mUseCache = (tileSource.tileCache != null); + mConn = conn; + } - @Override - public void query(MapTile tile, ITileDataSink sink) { - ITileCache cache = mTileSource.tileCache; + @Override + public void query(MapTile tile, ITileDataSink sink) { + ITileCache cache = mTileSource.tileCache; - if (mUseCache) { - TileReader c = cache.getTile(tile); - if (c != null) { - InputStream is = c.getInputStream(); - try { - if (mTileDecoder.decode(tile, sink, is)) { - sink.completed(SUCCESS); - return; - } - } catch (IOException e) { - log.debug("{} Cache read: {}", tile, e); - } finally { - IOUtils.closeQuietly(is); - } - } - } + if (mUseCache) { + TileReader c = cache.getTile(tile); + if (c != null) { + InputStream is = c.getInputStream(); + try { + if (mTileDecoder.decode(tile, sink, is)) { + sink.completed(SUCCESS); + return; + } + } catch (IOException e) { + log.debug("{} Cache read: {}", tile, e); + } finally { + IOUtils.closeQuietly(is); + } + } + } - QueryResult res = FAILED; + QueryResult res = FAILED; - TileWriter cacheWriter = null; - try { - mConn.sendRequest(tile); - InputStream is = mConn.read(); - if (mUseCache) { - cacheWriter = cache.writeTile(tile); - mConn.setCache(cacheWriter.getOutputStream()); - } - if (mTileDecoder.decode(tile, sink, is)) - res = SUCCESS; - } catch (SocketException e) { - log.debug("{} Socket Error: {}", tile, e.getMessage()); - } catch (SocketTimeoutException e) { - log.debug("{} Socket Timeout", tile); - res = DELAYED; - } catch (UnknownHostException e) { - log.debug("{} Unknown host: {}", tile, e.getMessage()); - } catch (IOException e) { - log.debug("{} Network Error: {}", tile, e.getMessage()); - } finally { - boolean ok = (res == SUCCESS); + TileWriter cacheWriter = null; + try { + mConn.sendRequest(tile); + InputStream is = mConn.read(); + if (mUseCache) { + cacheWriter = cache.writeTile(tile); + mConn.setCache(cacheWriter.getOutputStream()); + } + if (mTileDecoder.decode(tile, sink, is)) + res = SUCCESS; + } catch (SocketException e) { + log.debug("{} Socket Error: {}", tile, e.getMessage()); + } catch (SocketTimeoutException e) { + log.debug("{} Socket Timeout", tile); + res = DELAYED; + } catch (UnknownHostException e) { + log.debug("{} Unknown host: {}", tile, e.getMessage()); + } catch (IOException e) { + log.debug("{} Network Error: {}", tile, e.getMessage()); + } finally { + boolean ok = (res == SUCCESS); - if (!mConn.requestCompleted(ok) && ok) - res = FAILED; + if (!mConn.requestCompleted(ok) && ok) + res = FAILED; - if (cacheWriter != null) - cacheWriter.complete(ok); + if (cacheWriter != null) + cacheWriter.complete(ok); - sink.completed(res); - } - } + sink.completed(res); + } + } - @Override - public void dispose() { - mConn.close(); - } + @Override + public void dispose() { + mConn.close(); + } - @Override - public void cancel() { - mConn.close(); - } + @Override + public void cancel() { + mConn.close(); + } } diff --git a/vtm/src/org/oscim/tiling/source/UrlTileSource.java b/vtm/src/org/oscim/tiling/source/UrlTileSource.java index b35cb947..9484afaa 100644 --- a/vtm/src/org/oscim/tiling/source/UrlTileSource.java +++ b/vtm/src/org/oscim/tiling/source/UrlTileSource.java @@ -17,185 +17,185 @@ */ package org.oscim.tiling.source; +import org.oscim.core.Tile; +import org.oscim.tiling.TileSource; +import org.oscim.tiling.source.LwHttp.LwHttpFactory; + import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; -import org.oscim.core.Tile; -import org.oscim.tiling.TileSource; -import org.oscim.tiling.source.LwHttp.LwHttpFactory; - public abstract class UrlTileSource extends TileSource { - public abstract static class Builder> extends TileSource.Builder { - protected String tilePath; - protected String url; - private HttpEngine.Factory engineFactory; - private String apiKey; + public abstract static class Builder> extends TileSource.Builder { + protected String tilePath; + protected String url; + private HttpEngine.Factory engineFactory; + private String apiKey; - protected Builder() { + protected Builder() { - } + } - protected Builder(String url, String tilePath, int zoomMin, int zoomMax) { - this.url = url; - this.tilePath = tilePath; - this.zoomMin = zoomMin; - this.zoomMax = zoomMax; - } + protected Builder(String url, String tilePath, int zoomMin, int zoomMax) { + this.url = url; + this.tilePath = tilePath; + this.zoomMin = zoomMin; + this.zoomMax = zoomMax; + } - public T apiKey(String apiKey) { - this.apiKey = apiKey; - return self(); - } + public T apiKey(String apiKey) { + this.apiKey = apiKey; + return self(); + } - public T tilePath(String tilePath) { - this.tilePath = tilePath; - return self(); - } + public T tilePath(String tilePath) { + this.tilePath = tilePath; + return self(); + } - public T url(String url) { - this.url = url; - return self(); - } + public T url(String url) { + this.url = url; + return self(); + } - public T httpFactory(HttpEngine.Factory factory) { - this.engineFactory = factory; - return self(); - } + public T httpFactory(HttpEngine.Factory factory) { + this.engineFactory = factory; + return self(); + } - } + } - public final static TileUrlFormatter URL_FORMATTER = new DefaultTileUrlFormatter(); - private final URL mUrl; - private final String[] mTilePath; + public final static TileUrlFormatter URL_FORMATTER = new DefaultTileUrlFormatter(); + private final URL mUrl; + private final String[] mTilePath; - private HttpEngine.Factory mHttpFactory; - private Map mRequestHeaders = Collections.emptyMap(); - private TileUrlFormatter mTileUrlFormatter = URL_FORMATTER; - private String mApiKey; + private HttpEngine.Factory mHttpFactory; + private Map mRequestHeaders = Collections.emptyMap(); + private TileUrlFormatter mTileUrlFormatter = URL_FORMATTER; + private String mApiKey; - public interface TileUrlFormatter { - String formatTilePath(UrlTileSource tileSource, Tile tile); - } + public interface TileUrlFormatter { + String formatTilePath(UrlTileSource tileSource, Tile tile); + } - protected UrlTileSource(Builder builder) { - super(builder); - mApiKey = builder.apiKey; - mUrl = makeUrl(builder.url); - mTilePath = builder.tilePath.split("\\{|\\}"); - mHttpFactory = builder.engineFactory; - } + protected UrlTileSource(Builder builder) { + super(builder); + mApiKey = builder.apiKey; + mUrl = makeUrl(builder.url); + mTilePath = builder.tilePath.split("\\{|\\}"); + mHttpFactory = builder.engineFactory; + } - protected UrlTileSource(String urlString, String tilePath) { - this(urlString, tilePath, 0, 17); - } + protected UrlTileSource(String urlString, String tilePath) { + this(urlString, tilePath, 0, 17); + } - protected UrlTileSource(String urlString, String tilePath, int zoomMin, int zoomMax) { - super(zoomMin, zoomMax); - mUrl = makeUrl(urlString); - mTilePath = makeTilePath(tilePath); - } + protected UrlTileSource(String urlString, String tilePath, int zoomMin, int zoomMax) { + super(zoomMin, zoomMax); + mUrl = makeUrl(urlString); + mTilePath = makeTilePath(tilePath); + } - private String[] makeTilePath(String tilePath) { - if (tilePath == null) - throw new IllegalArgumentException("tilePath cannot be null."); + private String[] makeTilePath(String tilePath) { + if (tilePath == null) + throw new IllegalArgumentException("tilePath cannot be null."); - return tilePath.split("\\{|\\}"); - } + return tilePath.split("\\{|\\}"); + } - private URL makeUrl(String urlString) { - URL url; - try { - url = new URL(urlString); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - return url; - } + private URL makeUrl(String urlString) { + URL url; + try { + url = new URL(urlString); + } catch (MalformedURLException e) { + throw new IllegalArgumentException(e); + } + return url; + } - @Override - public OpenResult open() { - return OpenResult.SUCCESS; - } + @Override + public OpenResult open() { + return OpenResult.SUCCESS; + } - @Override - public void close() { + @Override + public void close() { - } + } - public void setApiKey(String apiKey) { - mApiKey = apiKey; - } + public void setApiKey(String apiKey) { + mApiKey = apiKey; + } - public URL getUrl() { - return mUrl; - } + public URL getUrl() { + return mUrl; + } - public String getTileUrl(Tile tile) { - String tileUrl = mUrl + mTileUrlFormatter.formatTilePath(this, tile); - if (mApiKey != null) { - tileUrl += String.format("?api_key=%s", mApiKey); - } - return tileUrl; - } + public String getTileUrl(Tile tile) { + String tileUrl = mUrl + mTileUrlFormatter.formatTilePath(this, tile); + if (mApiKey != null) { + tileUrl += String.format("?api_key=%s", mApiKey); + } + return tileUrl; + } - public void setHttpEngine(HttpEngine.Factory httpFactory) { - mHttpFactory = httpFactory; - } + public void setHttpEngine(HttpEngine.Factory httpFactory) { + mHttpFactory = httpFactory; + } - public void setHttpRequestHeaders(Map options) { - mRequestHeaders = options; - } + public void setHttpRequestHeaders(Map options) { + mRequestHeaders = options; + } - public Map getRequestHeader() { - return mRequestHeaders; - } + public Map getRequestHeader() { + return mRequestHeaders; + } - public String[] getTilePath() { - return mTilePath; - } + public String[] getTilePath() { + return mTilePath; + } - public void setUrlFormatter(TileUrlFormatter formatter) { - mTileUrlFormatter = formatter; - } + public void setUrlFormatter(TileUrlFormatter formatter) { + mTileUrlFormatter = formatter; + } - public TileUrlFormatter getUrlFormatter() { - return mTileUrlFormatter; - } + public TileUrlFormatter getUrlFormatter() { + return mTileUrlFormatter; + } - public HttpEngine getHttpEngine() { - if (mHttpFactory == null) { - mHttpFactory = new LwHttpFactory(); - } - return mHttpFactory.create(this); - } + public HttpEngine getHttpEngine() { + if (mHttpFactory == null) { + mHttpFactory = new LwHttpFactory(); + } + return mHttpFactory.create(this); + } - static class DefaultTileUrlFormatter implements TileUrlFormatter { - @Override - public String formatTilePath(UrlTileSource tileSource, Tile tile) { + static class DefaultTileUrlFormatter implements TileUrlFormatter { + @Override + public String formatTilePath(UrlTileSource tileSource, Tile tile) { - StringBuilder sb = new StringBuilder(); - for (String b : tileSource.getTilePath()) { - if (b.length() == 1) { - switch (b.charAt(0)) { - case 'X': - sb.append(tile.tileX); - continue; - case 'Y': - sb.append(tile.tileY); - continue; - case 'Z': - sb.append(tile.zoomLevel); - continue; - default: - break; - } - } - sb.append(b); - } - return sb.toString(); - } - } + StringBuilder sb = new StringBuilder(); + for (String b : tileSource.getTilePath()) { + if (b.length() == 1) { + switch (b.charAt(0)) { + case 'X': + sb.append(tile.tileX); + continue; + case 'Y': + sb.append(tile.tileY); + continue; + case 'Z': + sb.append(tile.zoomLevel); + continue; + default: + break; + } + } + sb.append(b); + } + return sb.toString(); + } + } } diff --git a/vtm/src/org/oscim/tiling/source/bitmap/BitmapTileSource.java b/vtm/src/org/oscim/tiling/source/bitmap/BitmapTileSource.java index 5fe51c1e..af5f878e 100644 --- a/vtm/src/org/oscim/tiling/source/bitmap/BitmapTileSource.java +++ b/vtm/src/org/oscim/tiling/source/bitmap/BitmapTileSource.java @@ -1,8 +1,5 @@ package org.oscim.tiling.source.bitmap; -import java.io.IOException; -import java.io.InputStream; - import org.oscim.backend.CanvasAdapter; import org.oscim.backend.canvas.Bitmap; import org.oscim.core.Tile; @@ -15,71 +12,74 @@ import org.oscim.tiling.source.UrlTileSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; + public class BitmapTileSource extends UrlTileSource { - static final Logger log = LoggerFactory.getLogger(LwHttp.class); + static final Logger log = LoggerFactory.getLogger(LwHttp.class); - public static class Builder> extends UrlTileSource.Builder { + public static class Builder> extends UrlTileSource.Builder { - public Builder() { - super(null, "/{Z}/{X}/{Y}.png", 0, 17); - } + public Builder() { + super(null, "/{Z}/{X}/{Y}.png", 0, 17); + } - public BitmapTileSource build() { - return new BitmapTileSource(this); - } - } + public BitmapTileSource build() { + return new BitmapTileSource(this); + } + } - protected BitmapTileSource(Builder builder) { - super(builder); - } + protected BitmapTileSource(Builder builder) { + super(builder); + } - @SuppressWarnings("rawtypes") - public static Builder builder() { - return new Builder(); - } + @SuppressWarnings("rawtypes") + public static Builder builder() { + return new Builder(); + } - /** - * Create BitmapTileSource for 'url' - * - * By default path will be formatted as: url/z/x/y.png - * Use e.g. setExtension(".jpg") to overide ending or - * implement getUrlString() for custom formatting. - */ - public BitmapTileSource(String url, int zoomMin, int zoomMax) { - this(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax); - } + /** + * Create BitmapTileSource for 'url' + *

+ * By default path will be formatted as: url/z/x/y.png + * Use e.g. setExtension(".jpg") to overide ending or + * implement getUrlString() for custom formatting. + */ + public BitmapTileSource(String url, int zoomMin, int zoomMax) { + this(url, "/{Z}/{X}/{Y}.png", zoomMin, zoomMax); + } - public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) { - this(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax); - } + public BitmapTileSource(String url, int zoomMin, int zoomMax, String extension) { + this(url, "/{Z}/{X}/{Y}" + extension, zoomMin, zoomMax); + } - public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) { - super(builder() - .url(url) - .tilePath(tilePath) - .zoomMin(zoomMin) - .zoomMax(zoomMax)); - } + public BitmapTileSource(String url, String tilePath, int zoomMin, int zoomMax) { + super(builder() + .url(url) + .tilePath(tilePath) + .zoomMin(zoomMin) + .zoomMax(zoomMax)); + } - @Override - public ITileDataSource getDataSource() { - return new UrlTileDataSource(this, new BitmapTileDecoder(), getHttpEngine()); - } + @Override + public ITileDataSource getDataSource() { + return new UrlTileDataSource(this, new BitmapTileDecoder(), getHttpEngine()); + } - public class BitmapTileDecoder implements ITileDecoder { + public class BitmapTileDecoder implements ITileDecoder { - @Override - public boolean decode(Tile tile, ITileDataSink sink, InputStream is) - throws IOException { + @Override + public boolean decode(Tile tile, ITileDataSink sink, InputStream is) + throws IOException { - Bitmap bitmap = CanvasAdapter.decodeBitmap(is); - if (!bitmap.isValid()) { - log.debug("{} invalid bitmap", tile); - return false; - } - sink.setTileImage(bitmap); + Bitmap bitmap = CanvasAdapter.decodeBitmap(is); + if (!bitmap.isValid()) { + log.debug("{} invalid bitmap", tile); + return false; + } + sink.setTileImage(bitmap); - return true; - } - } + return true; + } + } } diff --git a/vtm/src/org/oscim/tiling/source/bitmap/DefaultSources.java b/vtm/src/org/oscim/tiling/source/bitmap/DefaultSources.java index 2cf1845e..92b911d7 100644 --- a/vtm/src/org/oscim/tiling/source/bitmap/DefaultSources.java +++ b/vtm/src/org/oscim/tiling/source/bitmap/DefaultSources.java @@ -9,66 +9,66 @@ import org.oscim.tiling.source.bitmap.BitmapTileSource.Builder; */ public class DefaultSources { - public static Builder OPENSTREETMAP = BitmapTileSource.builder() - .url("http://tile.openstreetmap.org") - .zoomMax(18); + public static Builder OPENSTREETMAP = BitmapTileSource.builder() + .url("http://tile.openstreetmap.org") + .zoomMax(18); - public static Builder OSM_TRANSPORT = BitmapTileSource.builder() - .url("http://a.tile.thunderforest.com/transport") - .zoomMax(18); + public static Builder OSM_TRANSPORT = BitmapTileSource.builder() + .url("http://a.tile.thunderforest.com/transport") + .zoomMax(18); - public static Builder STAMEN_TONER = BitmapTileSource.builder() - .url("http://a.tile.stamen.com/toner") - .zoomMax(18); + public static Builder STAMEN_TONER = BitmapTileSource.builder() + .url("http://a.tile.stamen.com/toner") + .zoomMax(18); - public static Builder STAMEN_WATERCOLOR = BitmapTileSource.builder() - .url("http://a.tile.stamen.com/watercolor") - .tilePath("/{Z}/{X}/{Y}.jpg") - .zoomMax(18); + public static Builder STAMEN_WATERCOLOR = BitmapTileSource.builder() + .url("http://a.tile.stamen.com/watercolor") + .tilePath("/{Z}/{X}/{Y}.jpg") + .zoomMax(18); - public static Builder IMAGICO_LANDCOVER = BitmapTileSource.builder() - .url("http://www.imagico.de/map/tiles/landcover") - .tilePath("/{Z}/{X}/{Y}.jpg") - .zoomMax(6); + public static Builder IMAGICO_LANDCOVER = BitmapTileSource.builder() + .url("http://www.imagico.de/map/tiles/landcover") + .tilePath("/{Z}/{X}/{Y}.jpg") + .zoomMax(6); - final static FadeStep[] fadeSteps = new FadeStep[] { - new FadeStep(0, 8 - 1, 1, 0.7f), - // dont fade between zoom-min/max - // fade above zoom max + 2, interpolate 1 to 0 - new FadeStep(8 - 1, 8 + 1, 0.7f, 0) - }; + final static FadeStep[] fadeSteps = new FadeStep[]{ + new FadeStep(0, 8 - 1, 1, 0.7f), + // dont fade between zoom-min/max + // fade above zoom max + 2, interpolate 1 to 0 + new FadeStep(8 - 1, 8 + 1, 0.7f, 0) + }; - public static Builder MAPQUEST_AERIAL = BitmapTileSource.builder() - .url("http://otile1.mqcdn.com/tiles/1.0.0/sat") - .tilePath("/{Z}/{X}/{Y}.jpg") - .fadeSteps(fadeSteps) - .zoomMax(8); + public static Builder MAPQUEST_AERIAL = BitmapTileSource.builder() + .url("http://otile1.mqcdn.com/tiles/1.0.0/sat") + .tilePath("/{Z}/{X}/{Y}.jpg") + .fadeSteps(fadeSteps) + .zoomMax(8); - public static Builder NE_LANDCOVER = BitmapTileSource.builder() - .url("http://opensciencemap.org/tiles/ne") - .fadeSteps(fadeSteps) - .zoomMax(8); + public static Builder NE_LANDCOVER = BitmapTileSource.builder() + .url("http://opensciencemap.org/tiles/ne") + .fadeSteps(fadeSteps) + .zoomMax(8); - public static Builder ARCGIS_RELIEF = BitmapTileSource.builder() - .url("http://server.arcgisonline.com/ArcGIS/rest/services" + - "/World_Shaded_Relief/MapServer/tile/") - .tilePath("{Z}/{Y}/{X}") - .zoomMax(13); + public static Builder ARCGIS_RELIEF = BitmapTileSource.builder() + .url("http://server.arcgisonline.com/ArcGIS/rest/services" + + "/World_Shaded_Relief/MapServer/tile/") + .tilePath("{Z}/{Y}/{X}") + .zoomMax(13); - public static Builder HD_HILLSHADE = BitmapTileSource.builder() - .url("http://129.206.74.245:8004/tms_hs.ashx") - .tilePath("?x={X}&y={Y}&z={Z}") - .zoomMin(2) - .zoomMax(16); + public static Builder HD_HILLSHADE = BitmapTileSource.builder() + .url("http://129.206.74.245:8004/tms_hs.ashx") + .tilePath("?x={X}&y={Y}&z={Z}") + .zoomMin(2) + .zoomMax(16); - /** - * https://github.com/opensciencemap/vtm/issues/18 - * https://developers.google.com/maps/faq - */ + /** + * https://github.com/opensciencemap/vtm/issues/18 + * https://developers.google.com/maps/faq + */ - public static Builder GOOGLE_MAPS = BitmapTileSource.builder() - .url("INSERT URL") - .tilePath("/vt/x={X}&y={Y}&z={Z}&s=Galileo&scale=2") - .zoomMin(1) - .zoomMax(20); + public static Builder GOOGLE_MAPS = BitmapTileSource.builder() + .url("INSERT URL") + .tilePath("/vt/x={X}&y={Y}&z={Z}&s=Galileo&scale=2") + .zoomMin(1) + .zoomMax(20); } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/Deserializer.java b/vtm/src/org/oscim/tiling/source/mapfile/Deserializer.java index f0eaf180..1afb906c 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/Deserializer.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/Deserializer.java @@ -20,78 +20,70 @@ package org.oscim.tiling.source.mapfile; * This utility class contains methods to convert byte arrays to numbers. */ final class Deserializer { - /** - * Converts five bytes of a byte array to an unsigned long. - *

- * The byte order is big-endian. - * - * @param buffer - * the byte array. - * @param offset - * the offset in the array. - * @return the long value. - */ - static long getFiveBytesLong(byte[] buffer, int offset) { - return (buffer[offset] & 0xffL) << 32 | (buffer[offset + 1] & 0xffL) << 24 - | (buffer[offset + 2] & 0xffL) << 16 - | (buffer[offset + 3] & 0xffL) << 8 | (buffer[offset + 4] & 0xffL); - } + /** + * Converts five bytes of a byte array to an unsigned long. + *

+ * The byte order is big-endian. + * + * @param buffer the byte array. + * @param offset the offset in the array. + * @return the long value. + */ + static long getFiveBytesLong(byte[] buffer, int offset) { + return (buffer[offset] & 0xffL) << 32 | (buffer[offset + 1] & 0xffL) << 24 + | (buffer[offset + 2] & 0xffL) << 16 + | (buffer[offset + 3] & 0xffL) << 8 | (buffer[offset + 4] & 0xffL); + } - /** - * Converts four bytes of a byte array to a signed int. - *

- * The byte order is big-endian. - * - * @param buffer - * the byte array. - * @param offset - * the offset in the array. - * @return the int value. - */ - static int getInt(byte[] buffer, int offset) { - return buffer[offset] << 24 | (buffer[offset + 1] & 0xff) << 16 - | (buffer[offset + 2] & 0xff) << 8 - | (buffer[offset + 3] & 0xff); - } + /** + * Converts four bytes of a byte array to a signed int. + *

+ * The byte order is big-endian. + * + * @param buffer the byte array. + * @param offset the offset in the array. + * @return the int value. + */ + static int getInt(byte[] buffer, int offset) { + return buffer[offset] << 24 | (buffer[offset + 1] & 0xff) << 16 + | (buffer[offset + 2] & 0xff) << 8 + | (buffer[offset + 3] & 0xff); + } - /** - * Converts eight bytes of a byte array to a signed long. - *

- * The byte order is big-endian. - * - * @param buffer - * the byte array. - * @param offset - * the offset in the array. - * @return the long value. - */ - static long getLong(byte[] buffer, int offset) { - return (buffer[offset] & 0xffL) << 56 | (buffer[offset + 1] & 0xffL) << 48 - | (buffer[offset + 2] & 0xffL) << 40 - | (buffer[offset + 3] & 0xffL) << 32 | (buffer[offset + 4] & 0xffL) << 24 - | (buffer[offset + 5] & 0xffL) << 16 | (buffer[offset + 6] & 0xffL) << 8 - | (buffer[offset + 7] & 0xffL); - } + /** + * Converts eight bytes of a byte array to a signed long. + *

+ * The byte order is big-endian. + * + * @param buffer the byte array. + * @param offset the offset in the array. + * @return the long value. + */ + static long getLong(byte[] buffer, int offset) { + return (buffer[offset] & 0xffL) << 56 | (buffer[offset + 1] & 0xffL) << 48 + | (buffer[offset + 2] & 0xffL) << 40 + | (buffer[offset + 3] & 0xffL) << 32 | (buffer[offset + 4] & 0xffL) << 24 + | (buffer[offset + 5] & 0xffL) << 16 | (buffer[offset + 6] & 0xffL) << 8 + | (buffer[offset + 7] & 0xffL); + } - /** - * Converts two bytes of a byte array to a signed int. - *

- * The byte order is big-endian. - * - * @param buffer - * the byte array. - * @param offset - * the offset in the array. - * @return the int value. - */ - static int getShort(byte[] buffer, int offset) { - return buffer[offset] << 8 | (buffer[offset + 1] & 0xff); - } + /** + * Converts two bytes of a byte array to a signed int. + *

+ * The byte order is big-endian. + * + * @param buffer the byte array. + * @param offset the offset in the array. + * @return the int value. + */ + static int getShort(byte[] buffer, int offset) { + return buffer[offset] << 8 | (buffer[offset + 1] & 0xff); + } - /** - * Private constructor to prevent instantiation from other classes. - */ - private Deserializer() { - throw new IllegalStateException(); - } + /** + * Private constructor to prevent instantiation from other classes. + */ + private Deserializer() { + throw new IllegalStateException(); + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/IndexCache.java b/vtm/src/org/oscim/tiling/source/mapfile/IndexCache.java index 44fe636b..306f19fe 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/IndexCache.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/IndexCache.java @@ -16,6 +16,9 @@ */ package org.oscim.tiling.source.mapfile; +import org.oscim.tiling.source.mapfile.header.SubFileParameter; +import org.oscim.utils.LRUCache; + import java.io.IOException; import java.io.RandomAccessFile; import java.util.Collections; @@ -23,105 +26,97 @@ import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import org.oscim.tiling.source.mapfile.header.SubFileParameter; -import org.oscim.utils.LRUCache; - /** * A cache for database index blocks with a fixed size and LRU policy. */ class IndexCache { - /** - * Number of index entries that one index block consists of. - */ - private static final int INDEX_ENTRIES_PER_BLOCK = 128; + /** + * Number of index entries that one index block consists of. + */ + private static final int INDEX_ENTRIES_PER_BLOCK = 128; - private static final Logger LOG = Logger.getLogger(IndexCache.class.getName()); + private static final Logger LOG = Logger.getLogger(IndexCache.class.getName()); - /** - * Maximum size in bytes of one index block. - */ - private static final int SIZE_OF_INDEX_BLOCK = INDEX_ENTRIES_PER_BLOCK - * SubFileParameter.BYTES_PER_INDEX_ENTRY; + /** + * Maximum size in bytes of one index block. + */ + private static final int SIZE_OF_INDEX_BLOCK = INDEX_ENTRIES_PER_BLOCK + * SubFileParameter.BYTES_PER_INDEX_ENTRY; - private final Map map; - private final RandomAccessFile randomAccessFile; + private final Map map; + private final RandomAccessFile randomAccessFile; - /** - * @param randomAccessFile - * the map file from which the index should be read and cached. - * @param capacity - * the maximum number of entries in the cache. - * @throws IllegalArgumentException - * if the capacity is negative. - */ - IndexCache(RandomAccessFile randomAccessFile, int capacity) { - this.randomAccessFile = randomAccessFile; - this.map = Collections.synchronizedMap(new LRUCache(capacity)); - } + /** + * @param randomAccessFile the map file from which the index should be read and cached. + * @param capacity the maximum number of entries in the cache. + * @throws IllegalArgumentException if the capacity is negative. + */ + IndexCache(RandomAccessFile randomAccessFile, int capacity) { + this.randomAccessFile = randomAccessFile; + this.map = Collections.synchronizedMap(new LRUCache(capacity)); + } - /** - * Destroy the cache at the end of its lifetime. - */ - void destroy() { - this.map.clear(); - } + /** + * Destroy the cache at the end of its lifetime. + */ + void destroy() { + this.map.clear(); + } - /** - * Returns the index entry of a block in the given map file. If the required - * index entry is not cached, it will be - * read from the map file index and put in the cache. - * - * @param subFileParameter - * the parameters of the map file for which the index entry is - * needed. - * @param blockNumber - * the number of the block in the map file. - * @return the index entry or -1 if the block number is invalid. - */ - synchronized long getIndexEntry(SubFileParameter subFileParameter, long blockNumber) { - try { - // check if the block number is out of bounds - if (blockNumber >= subFileParameter.numberOfBlocks) { - return -1; - } + /** + * Returns the index entry of a block in the given map file. If the required + * index entry is not cached, it will be + * read from the map file index and put in the cache. + * + * @param subFileParameter the parameters of the map file for which the index entry is + * needed. + * @param blockNumber the number of the block in the map file. + * @return the index entry or -1 if the block number is invalid. + */ + synchronized long getIndexEntry(SubFileParameter subFileParameter, long blockNumber) { + try { + // check if the block number is out of bounds + if (blockNumber >= subFileParameter.numberOfBlocks) { + return -1; + } - // calculate the index block number - long indexBlockNumber = blockNumber / INDEX_ENTRIES_PER_BLOCK; + // calculate the index block number + long indexBlockNumber = blockNumber / INDEX_ENTRIES_PER_BLOCK; - // create the cache entry key for this request - IndexCacheEntryKey indexCacheEntryKey = new IndexCacheEntryKey(subFileParameter, - indexBlockNumber); + // create the cache entry key for this request + IndexCacheEntryKey indexCacheEntryKey = new IndexCacheEntryKey(subFileParameter, + indexBlockNumber); - // check for cached index block - byte[] indexBlock = this.map.get(indexCacheEntryKey); - if (indexBlock == null) { - // cache miss, seek to the correct index block in the file and read it - long indexBlockPosition = subFileParameter.indexStartAddress + indexBlockNumber - * SIZE_OF_INDEX_BLOCK; + // check for cached index block + byte[] indexBlock = this.map.get(indexCacheEntryKey); + if (indexBlock == null) { + // cache miss, seek to the correct index block in the file and read it + long indexBlockPosition = subFileParameter.indexStartAddress + indexBlockNumber + * SIZE_OF_INDEX_BLOCK; - int remainingIndexSize = (int) (subFileParameter.indexEndAddress - indexBlockPosition); - int indexBlockSize = Math.min(SIZE_OF_INDEX_BLOCK, remainingIndexSize); - indexBlock = new byte[indexBlockSize]; + int remainingIndexSize = (int) (subFileParameter.indexEndAddress - indexBlockPosition); + int indexBlockSize = Math.min(SIZE_OF_INDEX_BLOCK, remainingIndexSize); + indexBlock = new byte[indexBlockSize]; - this.randomAccessFile.seek(indexBlockPosition); - if (this.randomAccessFile.read(indexBlock, 0, indexBlockSize) != indexBlockSize) { - LOG.warning("reading the current index block has failed"); - return -1; - } + this.randomAccessFile.seek(indexBlockPosition); + if (this.randomAccessFile.read(indexBlock, 0, indexBlockSize) != indexBlockSize) { + LOG.warning("reading the current index block has failed"); + return -1; + } - // put the index block in the map - this.map.put(indexCacheEntryKey, indexBlock); - } + // put the index block in the map + this.map.put(indexCacheEntryKey, indexBlock); + } - // calculate the address of the index entry inside the index block - long indexEntryInBlock = blockNumber % INDEX_ENTRIES_PER_BLOCK; - int addressInIndexBlock = (int) (indexEntryInBlock * SubFileParameter.BYTES_PER_INDEX_ENTRY); + // calculate the address of the index entry inside the index block + long indexEntryInBlock = blockNumber % INDEX_ENTRIES_PER_BLOCK; + int addressInIndexBlock = (int) (indexEntryInBlock * SubFileParameter.BYTES_PER_INDEX_ENTRY); - // return the real index entry - return Deserializer.getFiveBytesLong(indexBlock, addressInIndexBlock); - } catch (IOException e) { - LOG.log(Level.SEVERE, null, e); - return -1; - } - } + // return the real index entry + return Deserializer.getFiveBytesLong(indexBlock, addressInIndexBlock); + } catch (IOException e) { + LOG.log(Level.SEVERE, null, e); + return -1; + } + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/IndexCacheEntryKey.java b/vtm/src/org/oscim/tiling/source/mapfile/IndexCacheEntryKey.java index 26c4330b..6769006b 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/IndexCacheEntryKey.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/IndexCacheEntryKey.java @@ -22,56 +22,54 @@ import org.oscim.tiling.source.mapfile.header.SubFileParameter; * An immutable container class which is the key for the index cache. */ class IndexCacheEntryKey { - private final int hashCodeValue; - private final long indexBlockNumber; - private final SubFileParameter subFileParameter; + private final int hashCodeValue; + private final long indexBlockNumber; + private final SubFileParameter subFileParameter; - /** - * Creates an immutable key to be stored in a map. - * - * @param subFileParameter - * the parameters of the map file. - * @param indexBlockNumber - * the number of the index block. - */ - IndexCacheEntryKey(SubFileParameter subFileParameter, long indexBlockNumber) { - this.subFileParameter = subFileParameter; - this.indexBlockNumber = indexBlockNumber; - this.hashCodeValue = calculateHashCode(); - } + /** + * Creates an immutable key to be stored in a map. + * + * @param subFileParameter the parameters of the map file. + * @param indexBlockNumber the number of the index block. + */ + IndexCacheEntryKey(SubFileParameter subFileParameter, long indexBlockNumber) { + this.subFileParameter = subFileParameter; + this.indexBlockNumber = indexBlockNumber; + this.hashCodeValue = calculateHashCode(); + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (!(obj instanceof IndexCacheEntryKey)) { - return false; - } - IndexCacheEntryKey other = (IndexCacheEntryKey) obj; - if (this.subFileParameter == null && other.subFileParameter != null) { - return false; - } else if (this.subFileParameter != null - && !this.subFileParameter.equals(other.subFileParameter)) { - return false; - } else if (this.indexBlockNumber != other.indexBlockNumber) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof IndexCacheEntryKey)) { + return false; + } + IndexCacheEntryKey other = (IndexCacheEntryKey) obj; + if (this.subFileParameter == null && other.subFileParameter != null) { + return false; + } else if (this.subFileParameter != null + && !this.subFileParameter.equals(other.subFileParameter)) { + return false; + } else if (this.indexBlockNumber != other.indexBlockNumber) { + return false; + } + return true; + } - @Override - public int hashCode() { - return this.hashCodeValue; - } + @Override + public int hashCode() { + return this.hashCodeValue; + } - /** - * @return the hash code of this object. - */ - private int calculateHashCode() { - int result = 7; - result = 31 * result - + ((this.subFileParameter == null) ? 0 : this.subFileParameter.hashCode()); - result = 31 * result + (int) (this.indexBlockNumber ^ (this.indexBlockNumber >>> 32)); - return result; - } + /** + * @return the hash code of this object. + */ + private int calculateHashCode() { + int result = 7; + result = 31 * result + + ((this.subFileParameter == null) ? 0 : this.subFileParameter.hashCode()); + result = 31 * result + (int) (this.indexBlockNumber ^ (this.indexBlockNumber >>> 32)); + return result; + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/MapDatabase.java b/vtm/src/org/oscim/tiling/source/mapfile/MapDatabase.java index e21c2e46..3fe25af2 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/MapDatabase.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/MapDatabase.java @@ -18,14 +18,6 @@ */ package org.oscim.tiling.source.mapfile; -import static org.oscim.core.GeometryBuffer.GeometryType.LINE; -import static org.oscim.core.GeometryBuffer.GeometryType.POLY; -import static org.oscim.tiling.QueryResult.FAILED; -import static org.oscim.tiling.QueryResult.SUCCESS; - -import java.io.IOException; -import java.io.RandomAccessFile; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.MercatorProjection; @@ -39,349 +31,402 @@ import org.oscim.utils.geom.TileClipper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.RandomAccessFile; + +import static org.oscim.core.GeometryBuffer.GeometryType.LINE; +import static org.oscim.core.GeometryBuffer.GeometryType.POLY; +import static org.oscim.tiling.QueryResult.FAILED; +import static org.oscim.tiling.QueryResult.SUCCESS; + /** * A class for reading binary map files. - * + * * @see Specification + * href="http://code.google.com/p/mapsforge/wiki/SpecificationBinaryMapFile">Specification */ public class MapDatabase implements ITileDataSource { - /** Bitmask to extract the block offset from an index entry. */ - private static final long BITMASK_INDEX_OFFSET = 0x7FFFFFFFFFL; + /** + * Bitmask to extract the block offset from an index entry. + */ + private static final long BITMASK_INDEX_OFFSET = 0x7FFFFFFFFFL; - /** Bitmask to extract the water information from an index entry. */ - private static final long BITMASK_INDEX_WATER = 0x8000000000L; + /** + * Bitmask to extract the water information from an index entry. + */ + private static final long BITMASK_INDEX_WATER = 0x8000000000L; - /** Debug message prefix for the block signature. */ - private static final String DEBUG_SIGNATURE_BLOCK = "block signature: "; + /** + * Debug message prefix for the block signature. + */ + private static final String DEBUG_SIGNATURE_BLOCK = "block signature: "; - /** Debug message prefix for the POI signature. */ - // private static final String DEBUG_SIGNATURE_POI = "POI signature: "; + /** Debug message prefix for the POI signature. */ + // private static final String DEBUG_SIGNATURE_POI = "POI signature: "; - /** Debug message prefix for the way signature. */ - private static final String DEBUG_SIGNATURE_WAY = "way signature: "; + /** + * Debug message prefix for the way signature. + */ + private static final String DEBUG_SIGNATURE_WAY = "way signature: "; - /** Error message for an invalid first way offset. */ - private static final String INVALID_FIRST_WAY_OFFSET = "invalid first way offset: "; + /** + * Error message for an invalid first way offset. + */ + private static final String INVALID_FIRST_WAY_OFFSET = "invalid first way offset: "; - static final Logger log = LoggerFactory.getLogger(MapDatabase.class); + static final Logger log = LoggerFactory.getLogger(MapDatabase.class); - /** Maximum way nodes sequence length which is considered as valid. */ - private static final int MAXIMUM_WAY_NODES_SEQUENCE_LENGTH = 8192; + /** + * Maximum way nodes sequence length which is considered as valid. + */ + private static final int MAXIMUM_WAY_NODES_SEQUENCE_LENGTH = 8192; - /** - * Maximum number of map objects in the zoom table which is considered as - * valid. - */ - private static final int MAXIMUM_ZOOM_TABLE_OBJECTS = 65536 * 2; + /** + * Maximum number of map objects in the zoom table which is considered as + * valid. + */ + private static final int MAXIMUM_ZOOM_TABLE_OBJECTS = 65536 * 2; - /** Bitmask for the optional POI feature "elevation". */ - private static final int POI_FEATURE_ELEVATION = 0x20; + /** + * Bitmask for the optional POI feature "elevation". + */ + private static final int POI_FEATURE_ELEVATION = 0x20; - /** Bitmask for the optional POI feature "house number". */ - private static final int POI_FEATURE_HOUSE_NUMBER = 0x40; + /** + * Bitmask for the optional POI feature "house number". + */ + private static final int POI_FEATURE_HOUSE_NUMBER = 0x40; - /** Bitmask for the optional POI feature "name". */ - private static final int POI_FEATURE_NAME = 0x80; + /** + * Bitmask for the optional POI feature "name". + */ + private static final int POI_FEATURE_NAME = 0x80; - /** Bitmask for the POI layer. */ - private static final int POI_LAYER_BITMASK = 0xf0; + /** + * Bitmask for the POI layer. + */ + private static final int POI_LAYER_BITMASK = 0xf0; - /** Bit shift for calculating the POI layer. */ - private static final int POI_LAYER_SHIFT = 4; + /** + * Bit shift for calculating the POI layer. + */ + private static final int POI_LAYER_SHIFT = 4; - /** Bitmask for the number of POI tags. */ - private static final int POI_NUMBER_OF_TAGS_BITMASK = 0x0f; + /** + * Bitmask for the number of POI tags. + */ + private static final int POI_NUMBER_OF_TAGS_BITMASK = 0x0f; - /** Length of the debug signature at the beginning of each block. */ - private static final byte SIGNATURE_LENGTH_BLOCK = 32; + /** + * Length of the debug signature at the beginning of each block. + */ + private static final byte SIGNATURE_LENGTH_BLOCK = 32; - /** Length of the debug signature at the beginning of each POI. */ - private static final byte SIGNATURE_LENGTH_POI = 32; + /** + * Length of the debug signature at the beginning of each POI. + */ + private static final byte SIGNATURE_LENGTH_POI = 32; - /** Length of the debug signature at the beginning of each way. */ - private static final byte SIGNATURE_LENGTH_WAY = 32; + /** + * Length of the debug signature at the beginning of each way. + */ + private static final byte SIGNATURE_LENGTH_WAY = 32; - /** Bitmask for the optional way data blocks byte. */ - private static final int WAY_FEATURE_DATA_BLOCKS_BYTE = 0x08; + /** + * Bitmask for the optional way data blocks byte. + */ + private static final int WAY_FEATURE_DATA_BLOCKS_BYTE = 0x08; - /** Bitmask for the optional way double delta encoding. */ - private static final int WAY_FEATURE_DOUBLE_DELTA_ENCODING = 0x04; + /** + * Bitmask for the optional way double delta encoding. + */ + private static final int WAY_FEATURE_DOUBLE_DELTA_ENCODING = 0x04; - /** Bitmask for the optional way feature "house number". */ - private static final int WAY_FEATURE_HOUSE_NUMBER = 0x40; + /** + * Bitmask for the optional way feature "house number". + */ + private static final int WAY_FEATURE_HOUSE_NUMBER = 0x40; - /** Bitmask for the optional way feature "label position". */ - private static final int WAY_FEATURE_LABEL_POSITION = 0x10; + /** + * Bitmask for the optional way feature "label position". + */ + private static final int WAY_FEATURE_LABEL_POSITION = 0x10; - /** Bitmask for the optional way feature "name". */ - private static final int WAY_FEATURE_NAME = 0x80; + /** + * Bitmask for the optional way feature "name". + */ + private static final int WAY_FEATURE_NAME = 0x80; - /** Bitmask for the optional way feature "reference". */ - private static final int WAY_FEATURE_REF = 0x20; + /** + * Bitmask for the optional way feature "reference". + */ + private static final int WAY_FEATURE_REF = 0x20; - /** Bitmask for the way layer. */ - private static final int WAY_LAYER_BITMASK = 0xf0; + /** + * Bitmask for the way layer. + */ + private static final int WAY_LAYER_BITMASK = 0xf0; - /** Bit shift for calculating the way layer. */ - private static final int WAY_LAYER_SHIFT = 4; + /** + * Bit shift for calculating the way layer. + */ + private static final int WAY_LAYER_SHIFT = 4; - /** Bitmask for the number of way tags. */ - private static final int WAY_NUMBER_OF_TAGS_BITMASK = 0x0f; + /** + * Bitmask for the number of way tags. + */ + private static final int WAY_NUMBER_OF_TAGS_BITMASK = 0x0f; - private long mFileSize; - private boolean mDebugFile; - private RandomAccessFile mInputFile; - private ReadBuffer mReadBuffer; - private String mSignatureBlock; - private String mSignaturePoi; - private String mSignatureWay; - private int mTileLatitude; - private int mTileLongitude; - private int[] mIntBuffer; + private long mFileSize; + private boolean mDebugFile; + private RandomAccessFile mInputFile; + private ReadBuffer mReadBuffer; + private String mSignatureBlock; + private String mSignaturePoi; + private String mSignatureWay; + private int mTileLatitude; + private int mTileLongitude; + private int[] mIntBuffer; - private final MapElement mElem = new MapElement(); + private final MapElement mElem = new MapElement(); - private int minDeltaLat, minDeltaLon; + private int minDeltaLat, minDeltaLon; - private final TileProjection mTileProjection; - private final TileClipper mTileClipper; + private final TileProjection mTileProjection; + private final TileClipper mTileClipper; - private final MapFileTileSource mTileSource; + private final MapFileTileSource mTileSource; - public MapDatabase(MapFileTileSource tileSource) throws IOException { - mTileSource = tileSource; - try { - /* open the file in read only mode */ - mInputFile = new RandomAccessFile(tileSource.mapFile, "r"); - mFileSize = mInputFile.length(); - mReadBuffer = new ReadBuffer(mInputFile); + public MapDatabase(MapFileTileSource tileSource) throws IOException { + mTileSource = tileSource; + try { + /* open the file in read only mode */ + mInputFile = new RandomAccessFile(tileSource.mapFile, "r"); + mFileSize = mInputFile.length(); + mReadBuffer = new ReadBuffer(mInputFile); - } catch (IOException e) { - log.error(e.getMessage()); - /* make sure that the file is closed */ - dispose(); - throw new IOException(); - } + } catch (IOException e) { + log.error(e.getMessage()); + /* make sure that the file is closed */ + dispose(); + throw new IOException(); + } - mTileProjection = new TileProjection(); - mTileClipper = new TileClipper(0, 0, 0, 0); - } + mTileProjection = new TileProjection(); + mTileClipper = new TileClipper(0, 0, 0, 0); + } - @Override - public void query(MapTile tile, ITileDataSink sink) { + @Override + public void query(MapTile tile, ITileDataSink sink) { - if (mTileSource.fileHeader == null) { - sink.completed(FAILED); - return; - } + if (mTileSource.fileHeader == null) { + sink.completed(FAILED); + return; + } - if (mIntBuffer == null) - mIntBuffer = new int[MAXIMUM_WAY_NODES_SEQUENCE_LENGTH * 2]; + if (mIntBuffer == null) + mIntBuffer = new int[MAXIMUM_WAY_NODES_SEQUENCE_LENGTH * 2]; - try { - mTileProjection.setTile(tile); - //mTile = tile; + try { + mTileProjection.setTile(tile); + //mTile = tile; /* size of tile in map coordinates; */ - double size = 1.0 / (1 << tile.zoomLevel); + double size = 1.0 / (1 << tile.zoomLevel); /* simplification tolerance */ - int pixel = (tile.zoomLevel > 11) ? 1 : 2; + int pixel = (tile.zoomLevel > 11) ? 1 : 2; - int simplify = Tile.SIZE / pixel; + int simplify = Tile.SIZE / pixel; /* translate screen pixel for tile to latitude and longitude * tolerance for point reduction before projection. */ - minDeltaLat = (int) (Math.abs(MercatorProjection.toLatitude(tile.y + size) - - MercatorProjection.toLatitude(tile.y)) * 1e6) / simplify; - minDeltaLon = (int) (Math.abs(MercatorProjection.toLongitude(tile.x + size) - - MercatorProjection.toLongitude(tile.x)) * 1e6) / simplify; + minDeltaLat = (int) (Math.abs(MercatorProjection.toLatitude(tile.y + size) + - MercatorProjection.toLatitude(tile.y)) * 1e6) / simplify; + minDeltaLon = (int) (Math.abs(MercatorProjection.toLongitude(tile.x + size) + - MercatorProjection.toLongitude(tile.x)) * 1e6) / simplify; - QueryParameters queryParameters = new QueryParameters(); - queryParameters.queryZoomLevel = - mTileSource.fileHeader.getQueryZoomLevel(tile.zoomLevel); + QueryParameters queryParameters = new QueryParameters(); + queryParameters.queryZoomLevel = + mTileSource.fileHeader.getQueryZoomLevel(tile.zoomLevel); /* get and check the sub-file for the query zoom level */ - SubFileParameter subFileParameter = - mTileSource.fileHeader.getSubFileParameter(queryParameters.queryZoomLevel); + SubFileParameter subFileParameter = + mTileSource.fileHeader.getSubFileParameter(queryParameters.queryZoomLevel); - if (subFileParameter == null) { - log.warn("no sub-file for zoom level: " - + queryParameters.queryZoomLevel); + if (subFileParameter == null) { + log.warn("no sub-file for zoom level: " + + queryParameters.queryZoomLevel); - sink.completed(FAILED); - return; - } + sink.completed(FAILED); + return; + } - QueryCalculations.calculateBaseTiles(queryParameters, tile, subFileParameter); - QueryCalculations.calculateBlocks(queryParameters, subFileParameter); - processBlocks(sink, queryParameters, subFileParameter); - } catch (IOException e) { - log.error(e.getMessage()); - sink.completed(FAILED); - return; - } + QueryCalculations.calculateBaseTiles(queryParameters, tile, subFileParameter); + QueryCalculations.calculateBlocks(queryParameters, subFileParameter); + processBlocks(sink, queryParameters, subFileParameter); + } catch (IOException e) { + log.error(e.getMessage()); + sink.completed(FAILED); + return; + } - sink.completed(SUCCESS); - } + sink.completed(SUCCESS); + } - @Override - public void dispose() { - mReadBuffer = null; - if (mInputFile != null) { + @Override + public void dispose() { + mReadBuffer = null; + if (mInputFile != null) { - try { - mInputFile.close(); - mInputFile = null; - } catch (IOException e) { - log.error(e.getMessage()); - } - } - } + try { + mInputFile.close(); + mInputFile = null; + } catch (IOException e) { + log.error(e.getMessage()); + } + } + } - @Override - public void cancel() { - } + @Override + public void cancel() { + } - /** - * Logs the debug signatures of the current way and block. - */ - private void logDebugSignatures() { - if (mDebugFile) { - log.warn(DEBUG_SIGNATURE_WAY + mSignatureWay); - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - } + /** + * Logs the debug signatures of the current way and block. + */ + private void logDebugSignatures() { + if (mDebugFile) { + log.warn(DEBUG_SIGNATURE_WAY + mSignatureWay); + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + } - /** - * Processes a single block and executes the callback functions on all map - * elements. - * - * @param queryParameters - * the parameters of the current query. - * @param subFileParameter - * the parameters of the current map file. - * @param mapDataSink - * the callback which handles the extracted map elements. - */ - private void processBlock(QueryParameters queryParameters, - SubFileParameter subFileParameter, ITileDataSink mapDataSink) { + /** + * Processes a single block and executes the callback functions on all map + * elements. + * + * @param queryParameters the parameters of the current query. + * @param subFileParameter the parameters of the current map file. + * @param mapDataSink the callback which handles the extracted map elements. + */ + private void processBlock(QueryParameters queryParameters, + SubFileParameter subFileParameter, ITileDataSink mapDataSink) { - if (!processBlockSignature()) { - return; - } + if (!processBlockSignature()) { + return; + } - int[][] zoomTable = readZoomTable(subFileParameter); - if (zoomTable == null) { - return; - } - int zoomTableRow = queryParameters.queryZoomLevel - subFileParameter.zoomLevelMin; - int poisOnQueryZoomLevel = zoomTable[zoomTableRow][0]; - int waysOnQueryZoomLevel = zoomTable[zoomTableRow][1]; + int[][] zoomTable = readZoomTable(subFileParameter); + if (zoomTable == null) { + return; + } + int zoomTableRow = queryParameters.queryZoomLevel - subFileParameter.zoomLevelMin; + int poisOnQueryZoomLevel = zoomTable[zoomTableRow][0]; + int waysOnQueryZoomLevel = zoomTable[zoomTableRow][1]; /* get the relative offset to the first stored way in the block */ - int firstWayOffset = mReadBuffer.readUnsignedInt(); - if (firstWayOffset < 0) { - log.warn(INVALID_FIRST_WAY_OFFSET + firstWayOffset); - if (mDebugFile) { - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - return; - } + int firstWayOffset = mReadBuffer.readUnsignedInt(); + if (firstWayOffset < 0) { + log.warn(INVALID_FIRST_WAY_OFFSET + firstWayOffset); + if (mDebugFile) { + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + return; + } /* add the current buffer position to the relative first way offset */ - firstWayOffset += mReadBuffer.getBufferPosition(); - if (firstWayOffset > mReadBuffer.getBufferSize()) { - log.warn(INVALID_FIRST_WAY_OFFSET + firstWayOffset); - if (mDebugFile) { - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - return; - } + firstWayOffset += mReadBuffer.getBufferPosition(); + if (firstWayOffset > mReadBuffer.getBufferSize()) { + log.warn(INVALID_FIRST_WAY_OFFSET + firstWayOffset); + if (mDebugFile) { + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + return; + } - if (!processPOIs(mapDataSink, poisOnQueryZoomLevel)) { - return; - } + if (!processPOIs(mapDataSink, poisOnQueryZoomLevel)) { + return; + } /* finished reading POIs, check if the current buffer position is valid */ - if (mReadBuffer.getBufferPosition() > firstWayOffset) { - log.warn("invalid buffer position: " + mReadBuffer.getBufferPosition()); - if (mDebugFile) { - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - return; - } + if (mReadBuffer.getBufferPosition() > firstWayOffset) { + log.warn("invalid buffer position: " + mReadBuffer.getBufferPosition()); + if (mDebugFile) { + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + return; + } /* move the pointer to the first way */ - mReadBuffer.setBufferPosition(firstWayOffset); + mReadBuffer.setBufferPosition(firstWayOffset); - if (!processWays(queryParameters, mapDataSink, waysOnQueryZoomLevel)) { - return; - } + if (!processWays(queryParameters, mapDataSink, waysOnQueryZoomLevel)) { + return; + } - } + } - // private long mCurrentRow; - // private long mCurrentCol; + // private long mCurrentRow; + // private long mCurrentCol; - private int xmin, ymin, xmax, ymax; + private int xmin, ymin, xmax, ymax; - private void setTileClipping(QueryParameters queryParameters, long mCurrentRow, long mCurrentCol) { - long numRows = queryParameters.toBlockY - queryParameters.fromBlockY; - long numCols = queryParameters.toBlockX - queryParameters.fromBlockX; + private void setTileClipping(QueryParameters queryParameters, long mCurrentRow, long mCurrentCol) { + long numRows = queryParameters.toBlockY - queryParameters.fromBlockY; + long numCols = queryParameters.toBlockX - queryParameters.fromBlockX; - //log.debug(numCols + "/" + numRows + " " + mCurrentCol + " " + mCurrentRow); - xmin = -16; - ymin = -16; - xmax = Tile.SIZE + 16; - ymax = Tile.SIZE + 16; + //log.debug(numCols + "/" + numRows + " " + mCurrentCol + " " + mCurrentRow); + xmin = -16; + ymin = -16; + xmax = Tile.SIZE + 16; + ymax = Tile.SIZE + 16; - if (numRows > 0) { - int w = (int) (Tile.SIZE / (numCols + 1)); - int h = (int) (Tile.SIZE / (numRows + 1)); + if (numRows > 0) { + int w = (int) (Tile.SIZE / (numCols + 1)); + int h = (int) (Tile.SIZE / (numRows + 1)); - if (mCurrentCol > 0) - xmin = (int) (mCurrentCol * w); + if (mCurrentCol > 0) + xmin = (int) (mCurrentCol * w); - if (mCurrentCol < numCols) - xmax = (int) (mCurrentCol * w + w); + if (mCurrentCol < numCols) + xmax = (int) (mCurrentCol * w + w); - if (mCurrentRow > 0) - ymin = (int) (mCurrentRow * h); + if (mCurrentRow > 0) + ymin = (int) (mCurrentRow * h); - if (mCurrentRow < numRows) - ymax = (int) (mCurrentRow * h + h); - } - mTileClipper.setRect(xmin, ymin, xmax, ymax); - } + if (mCurrentRow < numRows) + ymax = (int) (mCurrentRow * h + h); + } + mTileClipper.setRect(xmin, ymin, xmax, ymax); + } - //private final static Tag mWaterTag = new Tag("natural", "water"); + //private final static Tag mWaterTag = new Tag("natural", "water"); - private void processBlocks(ITileDataSink mapDataSink, QueryParameters queryParams, - SubFileParameter subFileParameter) throws IOException { + private void processBlocks(ITileDataSink mapDataSink, QueryParameters queryParams, + SubFileParameter subFileParameter) throws IOException { /* read and process all blocks from top to bottom and from left to right */ - for (long row = queryParams.fromBlockY; row <= queryParams.toBlockY; row++) { - for (long column = queryParams.fromBlockX; column <= queryParams.toBlockX; column++) { - //mCurrentCol = column - queryParameters.fromBlockX; - //mCurrentRow = row - queryParameters.fromBlockY; + for (long row = queryParams.fromBlockY; row <= queryParams.toBlockY; row++) { + for (long column = queryParams.fromBlockX; column <= queryParams.toBlockX; column++) { + //mCurrentCol = column - queryParameters.fromBlockX; + //mCurrentRow = row - queryParameters.fromBlockY; - setTileClipping(queryParams, - row - queryParams.fromBlockY, - column - queryParams.fromBlockX); + setTileClipping(queryParams, + row - queryParams.fromBlockY, + column - queryParams.fromBlockX); /* calculate the actual block number of the needed block in the * file */ - long blockNumber = row * subFileParameter.blocksWidth + column; + long blockNumber = row * subFileParameter.blocksWidth + column; /* get the current index entry */ - long blockIndexEntry = mTileSource.databaseIndexCache.getIndexEntry(subFileParameter, - blockNumber); + long blockIndexEntry = mTileSource.databaseIndexCache.getIndexEntry(subFileParameter, + blockNumber); /* check the water flag of the block in its index entry */ - if ((blockIndexEntry & BITMASK_INDEX_WATER) != 0) { - // Deprecate water tiles rendering + if ((blockIndexEntry & BITMASK_INDEX_WATER) != 0) { + // Deprecate water tiles rendering /*MapElement e = mElem; e.clear(); e.tags.clear(); @@ -392,593 +437,588 @@ public class MapDatabase implements ITileDataSource { e.addPoint(xmax, ymax); e.addPoint(xmin, ymax); mapDataSink.process(e);*/ - } + } /* get and check the current block pointer */ - long blockPointer = blockIndexEntry & BITMASK_INDEX_OFFSET; - if (blockPointer < 1 || blockPointer > subFileParameter.subFileSize) { - log.warn("invalid current block pointer: " + blockPointer); - log.warn("subFileSize: " + subFileParameter.subFileSize); - return; - } + long blockPointer = blockIndexEntry & BITMASK_INDEX_OFFSET; + if (blockPointer < 1 || blockPointer > subFileParameter.subFileSize) { + log.warn("invalid current block pointer: " + blockPointer); + log.warn("subFileSize: " + subFileParameter.subFileSize); + return; + } - long nextBlockPointer; + long nextBlockPointer; /* check if the current block is the last block in the file */ - if (blockNumber + 1 == subFileParameter.numberOfBlocks) { + if (blockNumber + 1 == subFileParameter.numberOfBlocks) { /* set the next block pointer to the end of the file */ - nextBlockPointer = subFileParameter.subFileSize; - } else { + nextBlockPointer = subFileParameter.subFileSize; + } else { /* get and check the next block pointer */ - nextBlockPointer = mTileSource.databaseIndexCache.getIndexEntry(subFileParameter, - blockNumber + 1); - nextBlockPointer &= BITMASK_INDEX_OFFSET; + nextBlockPointer = mTileSource.databaseIndexCache.getIndexEntry(subFileParameter, + blockNumber + 1); + nextBlockPointer &= BITMASK_INDEX_OFFSET; - if (nextBlockPointer < 1 || nextBlockPointer > subFileParameter.subFileSize) { - log.warn("invalid next block pointer: " + nextBlockPointer); - log.warn("sub-file size: " + subFileParameter.subFileSize); - return; - } - } + if (nextBlockPointer < 1 || nextBlockPointer > subFileParameter.subFileSize) { + log.warn("invalid next block pointer: " + nextBlockPointer); + log.warn("sub-file size: " + subFileParameter.subFileSize); + return; + } + } /* calculate the size of the current block */ - int blockSize = (int) (nextBlockPointer - blockPointer); - if (blockSize < 0) { - log.warn("current block size must not be negative: " - + blockSize); - return; - } else if (blockSize == 0) { + int blockSize = (int) (nextBlockPointer - blockPointer); + if (blockSize < 0) { + log.warn("current block size must not be negative: " + + blockSize); + return; + } else if (blockSize == 0) { /* the current block is empty, continue with the next block */ - continue; - } else if (blockSize > ReadBuffer.MAXIMUM_BUFFER_SIZE) { + continue; + } else if (blockSize > ReadBuffer.MAXIMUM_BUFFER_SIZE) { /* the current block is too large, continue with the next * block */ - log.warn("current block size too large: " + blockSize); - continue; - } else if (blockPointer + blockSize > mFileSize) { - log.warn("current block larger than file size: " - + blockSize); - return; - } + log.warn("current block size too large: " + blockSize); + continue; + } else if (blockPointer + blockSize > mFileSize) { + log.warn("current block larger than file size: " + + blockSize); + return; + } /* seek to the current block in the map file */ - mInputFile.seek(subFileParameter.startAddress + blockPointer); + mInputFile.seek(subFileParameter.startAddress + blockPointer); /* read the current block into the buffer */ - if (!mReadBuffer.readFromFile(blockSize)) { + if (!mReadBuffer.readFromFile(blockSize)) { /* skip the current block */ - log.warn("reading current block has failed: " + blockSize); - return; - } + log.warn("reading current block has failed: " + blockSize); + return; + } /* calculate the top-left coordinates of the underlying tile */ - double tileLatitudeDeg = - Projection.tileYToLatitude(subFileParameter.boundaryTileTop + row, - subFileParameter.baseZoomLevel); - double tileLongitudeDeg = - Projection.tileXToLongitude(subFileParameter.boundaryTileLeft + column, - subFileParameter.baseZoomLevel); + double tileLatitudeDeg = + Projection.tileYToLatitude(subFileParameter.boundaryTileTop + row, + subFileParameter.baseZoomLevel); + double tileLongitudeDeg = + Projection.tileXToLongitude(subFileParameter.boundaryTileLeft + column, + subFileParameter.baseZoomLevel); - mTileLatitude = (int) (tileLatitudeDeg * 1E6); - mTileLongitude = (int) (tileLongitudeDeg * 1E6); + mTileLatitude = (int) (tileLatitudeDeg * 1E6); + mTileLongitude = (int) (tileLongitudeDeg * 1E6); - processBlock(queryParams, subFileParameter, mapDataSink); - } - } - } + processBlock(queryParams, subFileParameter, mapDataSink); + } + } + } - /** - * Processes the block signature, if present. - * - * @return true if the block signature could be processed successfully, - * false otherwise. - */ - private boolean processBlockSignature() { - if (mDebugFile) { + /** + * Processes the block signature, if present. + * + * @return true if the block signature could be processed successfully, + * false otherwise. + */ + private boolean processBlockSignature() { + if (mDebugFile) { /* get and check the block signature */ - mSignatureBlock = mReadBuffer.readUTF8EncodedString(SIGNATURE_LENGTH_BLOCK); - if (!mSignatureBlock.startsWith("###TileStart")) { - log.warn("invalid block signature: " + mSignatureBlock); - return false; - } - } - return true; - } + mSignatureBlock = mReadBuffer.readUTF8EncodedString(SIGNATURE_LENGTH_BLOCK); + if (!mSignatureBlock.startsWith("###TileStart")) { + log.warn("invalid block signature: " + mSignatureBlock); + return false; + } + } + return true; + } - /** - * Processes the given number of POIs. - * - * @param mapDataSink - * the callback which handles the extracted POIs. - * @param numberOfPois - * how many POIs should be processed. - * @return true if the POIs could be processed successfully, false - * otherwise. - */ - private boolean processPOIs(ITileDataSink mapDataSink, int numberOfPois) { - Tag[] poiTags = mTileSource.fileInfo.poiTags; - MapElement e = mElem; + /** + * Processes the given number of POIs. + * + * @param mapDataSink the callback which handles the extracted POIs. + * @param numberOfPois how many POIs should be processed. + * @return true if the POIs could be processed successfully, false + * otherwise. + */ + private boolean processPOIs(ITileDataSink mapDataSink, int numberOfPois) { + Tag[] poiTags = mTileSource.fileInfo.poiTags; + MapElement e = mElem; - int numTags = 0; + int numTags = 0; - for (int elementCounter = numberOfPois; elementCounter != 0; --elementCounter) { - if (mDebugFile) { + for (int elementCounter = numberOfPois; elementCounter != 0; --elementCounter) { + if (mDebugFile) { /* get and check the POI signature */ - mSignaturePoi = mReadBuffer.readUTF8EncodedString(SIGNATURE_LENGTH_POI); - if (!mSignaturePoi.startsWith("***POIStart")) { - log.warn("invalid POI signature: " + mSignaturePoi); - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - return false; - } - } + mSignaturePoi = mReadBuffer.readUTF8EncodedString(SIGNATURE_LENGTH_POI); + if (!mSignaturePoi.startsWith("***POIStart")) { + log.warn("invalid POI signature: " + mSignaturePoi); + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + return false; + } + } /* get the POI latitude offset (VBE-S) */ - int latitude = mTileLatitude + mReadBuffer.readSignedInt(); + int latitude = mTileLatitude + mReadBuffer.readSignedInt(); /* get the POI longitude offset (VBE-S) */ - int longitude = mTileLongitude + mReadBuffer.readSignedInt(); + int longitude = mTileLongitude + mReadBuffer.readSignedInt(); /* get the special byte which encodes multiple flags */ - byte specialByte = mReadBuffer.readByte(); + byte specialByte = mReadBuffer.readByte(); /* bit 1-4 represent the layer */ - byte layer = (byte) ((specialByte & POI_LAYER_BITMASK) >>> POI_LAYER_SHIFT); + byte layer = (byte) ((specialByte & POI_LAYER_BITMASK) >>> POI_LAYER_SHIFT); /* bit 5-8 represent the number of tag IDs */ - byte numberOfTags = (byte) (specialByte & POI_NUMBER_OF_TAGS_BITMASK); + byte numberOfTags = (byte) (specialByte & POI_NUMBER_OF_TAGS_BITMASK); - if (numberOfTags != 0) { - if (!mReadBuffer.readTags(e.tags, poiTags, numberOfTags)) - return false; + if (numberOfTags != 0) { + if (!mReadBuffer.readTags(e.tags, poiTags, numberOfTags)) + return false; - numTags = numberOfTags; - } + numTags = numberOfTags; + } /* reset to common tag position */ - e.tags.numTags = numTags; + e.tags.numTags = numTags; /* get the feature bitmask (1 byte) */ - byte featureByte = mReadBuffer.readByte(); + byte featureByte = mReadBuffer.readByte(); /* bit 1-3 enable optional features * check if the POI has a name */ - if ((featureByte & POI_FEATURE_NAME) != 0) { - String str = mTileSource.extractLocalized(mReadBuffer.readUTF8EncodedString()); - e.tags.add(new Tag(Tag.KEY_NAME, str, false)); - } + if ((featureByte & POI_FEATURE_NAME) != 0) { + String str = mTileSource.extractLocalized(mReadBuffer.readUTF8EncodedString()); + e.tags.add(new Tag(Tag.KEY_NAME, str, false)); + } /* check if the POI has a house number */ - if ((featureByte & POI_FEATURE_HOUSE_NUMBER) != 0) { - String str = mReadBuffer.readUTF8EncodedString(); - e.tags.add(new Tag(Tag.KEY_HOUSE_NUMBER, str, false)); - } + if ((featureByte & POI_FEATURE_HOUSE_NUMBER) != 0) { + String str = mReadBuffer.readUTF8EncodedString(); + e.tags.add(new Tag(Tag.KEY_HOUSE_NUMBER, str, false)); + } /* check if the POI has an elevation */ - if ((featureByte & POI_FEATURE_ELEVATION) != 0) { - String str = Integer.toString(mReadBuffer.readSignedInt()); - e.tags.add(new Tag(Tag.KEY_ELE, str, false)); - } - mTileProjection.projectPoint(latitude, longitude, e); + if ((featureByte & POI_FEATURE_ELEVATION) != 0) { + String str = Integer.toString(mReadBuffer.readSignedInt()); + e.tags.add(new Tag(Tag.KEY_ELE, str, false)); + } + mTileProjection.projectPoint(latitude, longitude, e); - e.setLayer(layer); + e.setLayer(layer); - mapDataSink.process(e); - } + mapDataSink.process(e); + } - return true; - } + return true; + } - private boolean processWayDataBlock(MapElement e, boolean doubleDeltaEncoding, boolean isLine) { + private boolean processWayDataBlock(MapElement e, boolean doubleDeltaEncoding, boolean isLine) { /* get and check the number of way coordinate blocks (VBE-U) */ - int numBlocks = mReadBuffer.readUnsignedInt(); - if (numBlocks < 1 || numBlocks > Short.MAX_VALUE) { - log.warn("invalid number of way coordinate blocks: " + numBlocks); - return false; - } + int numBlocks = mReadBuffer.readUnsignedInt(); + if (numBlocks < 1 || numBlocks > Short.MAX_VALUE) { + log.warn("invalid number of way coordinate blocks: " + numBlocks); + return false; + } - int[] wayLengths = e.ensureIndexSize(numBlocks, false); - if (wayLengths.length > numBlocks) - wayLengths[numBlocks] = -1; + int[] wayLengths = e.ensureIndexSize(numBlocks, false); + if (wayLengths.length > numBlocks) + wayLengths[numBlocks] = -1; /* read the way coordinate blocks */ - for (int coordinateBlock = 0; coordinateBlock < numBlocks; ++coordinateBlock) { - int numWayNodes = mReadBuffer.readUnsignedInt(); + for (int coordinateBlock = 0; coordinateBlock < numBlocks; ++coordinateBlock) { + int numWayNodes = mReadBuffer.readUnsignedInt(); - if (numWayNodes < 2 || numWayNodes > MAXIMUM_WAY_NODES_SEQUENCE_LENGTH) { - log.warn("invalid number of way nodes: " + numWayNodes); - logDebugSignatures(); - return false; - } + if (numWayNodes < 2 || numWayNodes > MAXIMUM_WAY_NODES_SEQUENCE_LENGTH) { + log.warn("invalid number of way nodes: " + numWayNodes); + logDebugSignatures(); + return false; + } /* each way node consists of latitude and longitude */ - int len = numWayNodes * 2; + int len = numWayNodes * 2; - wayLengths[coordinateBlock] = decodeWayNodes(doubleDeltaEncoding, - e, len, isLine); - } + wayLengths[coordinateBlock] = decodeWayNodes(doubleDeltaEncoding, + e, len, isLine); + } - return true; - } + return true; + } - private int decodeWayNodes(boolean doubleDelta, MapElement e, int length, boolean isLine) { - int[] buffer = mIntBuffer; - mReadBuffer.readSignedInt(buffer, length); + private int decodeWayNodes(boolean doubleDelta, MapElement e, int length, boolean isLine) { + int[] buffer = mIntBuffer; + mReadBuffer.readSignedInt(buffer, length); - float[] outBuffer = e.ensurePointSize(e.pointPos + length, true); - int outPos = e.pointPos; - int lat, lon; + float[] outBuffer = e.ensurePointSize(e.pointPos + length, true); + int outPos = e.pointPos; + int lat, lon; /* first node latitude single-delta offset */ - int firstLat = lat = mTileLatitude + buffer[0]; - int firstLon = lon = mTileLongitude + buffer[1]; + int firstLat = lat = mTileLatitude + buffer[0]; + int firstLon = lon = mTileLongitude + buffer[1]; - outBuffer[outPos++] = lon; - outBuffer[outPos++] = lat; - int cnt = 2; + outBuffer[outPos++] = lon; + outBuffer[outPos++] = lat; + int cnt = 2; - int deltaLat = 0; - int deltaLon = 0; + int deltaLat = 0; + int deltaLon = 0; - for (int pos = 2; pos < length; pos += 2) { - if (doubleDelta) { - deltaLat = buffer[pos] + deltaLat; - deltaLon = buffer[pos + 1] + deltaLon; - } else { - deltaLat = buffer[pos]; - deltaLon = buffer[pos + 1]; - } - lat += deltaLat; - lon += deltaLon; + for (int pos = 2; pos < length; pos += 2) { + if (doubleDelta) { + deltaLat = buffer[pos] + deltaLat; + deltaLon = buffer[pos + 1] + deltaLon; + } else { + deltaLat = buffer[pos]; + deltaLon = buffer[pos + 1]; + } + lat += deltaLat; + lon += deltaLon; - if (pos == length - 2) { - boolean line = isLine || (lon != firstLon && lat != firstLat); + if (pos == length - 2) { + boolean line = isLine || (lon != firstLon && lat != firstLat); - if (line) { - outBuffer[outPos++] = lon; - outBuffer[outPos++] = lat; - cnt += 2; - } + if (line) { + outBuffer[outPos++] = lon; + outBuffer[outPos++] = lat; + cnt += 2; + } - if (e.type == GeometryType.NONE) - e.type = line ? LINE : POLY; + if (e.type == GeometryType.NONE) + e.type = line ? LINE : POLY; - } else if ((deltaLon > minDeltaLon || deltaLon < -minDeltaLon - || deltaLat > minDeltaLat || deltaLat < -minDeltaLat) - || e.tags.contains("natural", "nosea")) { - outBuffer[outPos++] = lon; - outBuffer[outPos++] = lat; - cnt += 2; - } - } + } else if ((deltaLon > minDeltaLon || deltaLon < -minDeltaLon + || deltaLat > minDeltaLat || deltaLat < -minDeltaLat) + || e.tags.contains("natural", "nosea")) { + outBuffer[outPos++] = lon; + outBuffer[outPos++] = lat; + cnt += 2; + } + } - e.pointPos = outPos; + e.pointPos = outPos; - return cnt; - } + return cnt; + } - private int stringOffset = -1; + private int stringOffset = -1; - /** - * Processes the given number of ways. - * - * @param queryParameters - * the parameters of the current query. - * @param mapDataSink - * the callback which handles the extracted ways. - * @param numberOfWays - * how many ways should be processed. - * @return true if the ways could be processed successfully, false - * otherwise. - */ - private boolean processWays(QueryParameters queryParameters, - ITileDataSink mapDataSink, int numberOfWays) { + /** + * Processes the given number of ways. + * + * @param queryParameters the parameters of the current query. + * @param mapDataSink the callback which handles the extracted ways. + * @param numberOfWays how many ways should be processed. + * @return true if the ways could be processed successfully, false + * otherwise. + */ + private boolean processWays(QueryParameters queryParameters, + ITileDataSink mapDataSink, int numberOfWays) { - Tag[] wayTags = mTileSource.fileInfo.wayTags; - MapElement e = mElem; + Tag[] wayTags = mTileSource.fileInfo.wayTags; + MapElement e = mElem; - int numTags = 0; + int numTags = 0; - int wayDataBlocks; + int wayDataBlocks; - // skip string block - int stringsSize = 0; - stringOffset = 0; + // skip string block + int stringsSize = 0; + stringOffset = 0; - if (mTileSource.experimental) { - stringsSize = mReadBuffer.readUnsignedInt(); - stringOffset = mReadBuffer.getBufferPosition(); - mReadBuffer.skipBytes(stringsSize); - } + if (mTileSource.experimental) { + stringsSize = mReadBuffer.readUnsignedInt(); + stringOffset = mReadBuffer.getBufferPosition(); + mReadBuffer.skipBytes(stringsSize); + } - //setTileClipping(queryParameters); + //setTileClipping(queryParameters); - for (int elementCounter = numberOfWays; elementCounter != 0; --elementCounter) { - if (mDebugFile) { - // get and check the way signature - mSignatureWay = mReadBuffer.readUTF8EncodedString(SIGNATURE_LENGTH_WAY); - if (!mSignatureWay.startsWith("---WayStart")) { - log.warn("invalid way signature: " + mSignatureWay); - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - return false; - } - } + for (int elementCounter = numberOfWays; elementCounter != 0; --elementCounter) { + if (mDebugFile) { + // get and check the way signature + mSignatureWay = mReadBuffer.readUTF8EncodedString(SIGNATURE_LENGTH_WAY); + if (!mSignatureWay.startsWith("---WayStart")) { + log.warn("invalid way signature: " + mSignatureWay); + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + return false; + } + } - if (queryParameters.useTileBitmask) { - elementCounter = mReadBuffer.skipWays(queryParameters.queryTileBitmask, - elementCounter); + if (queryParameters.useTileBitmask) { + elementCounter = mReadBuffer.skipWays(queryParameters.queryTileBitmask, + elementCounter); - if (elementCounter == 0) - return true; + if (elementCounter == 0) + return true; - if (elementCounter < 0) - return false; + if (elementCounter < 0) + return false; - if (mTileSource.experimental && mReadBuffer.lastTagPosition > 0) { - int pos = mReadBuffer.getBufferPosition(); - mReadBuffer.setBufferPosition(mReadBuffer.lastTagPosition); + if (mTileSource.experimental && mReadBuffer.lastTagPosition > 0) { + int pos = mReadBuffer.getBufferPosition(); + mReadBuffer.setBufferPosition(mReadBuffer.lastTagPosition); - byte numberOfTags = - (byte) (mReadBuffer.readByte() & WAY_NUMBER_OF_TAGS_BITMASK); - if (!mReadBuffer.readTags(e.tags, wayTags, numberOfTags)) - return false; + byte numberOfTags = + (byte) (mReadBuffer.readByte() & WAY_NUMBER_OF_TAGS_BITMASK); + if (!mReadBuffer.readTags(e.tags, wayTags, numberOfTags)) + return false; - numTags = numberOfTags; + numTags = numberOfTags; - mReadBuffer.setBufferPosition(pos); - } - } else { - int wayDataSize = mReadBuffer.readUnsignedInt(); - if (wayDataSize < 0) { - log.warn("invalid way data size: " + wayDataSize); - if (mDebugFile) { - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - log.error("BUG way 2"); - return false; - } + mReadBuffer.setBufferPosition(pos); + } + } else { + int wayDataSize = mReadBuffer.readUnsignedInt(); + if (wayDataSize < 0) { + log.warn("invalid way data size: " + wayDataSize); + if (mDebugFile) { + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + log.error("BUG way 2"); + return false; + } /* ignore the way tile bitmask (2 bytes) */ - mReadBuffer.skipBytes(2); - } + mReadBuffer.skipBytes(2); + } /* get the special byte which encodes multiple flags */ - byte specialByte = mReadBuffer.readByte(); + byte specialByte = mReadBuffer.readByte(); /* bit 1-4 represent the layer */ - byte layer = (byte) ((specialByte & WAY_LAYER_BITMASK) >>> WAY_LAYER_SHIFT); + byte layer = (byte) ((specialByte & WAY_LAYER_BITMASK) >>> WAY_LAYER_SHIFT); /* bit 5-8 represent the number of tag IDs */ - byte numberOfTags = (byte) (specialByte & WAY_NUMBER_OF_TAGS_BITMASK); + byte numberOfTags = (byte) (specialByte & WAY_NUMBER_OF_TAGS_BITMASK); - if (numberOfTags != 0) { + if (numberOfTags != 0) { - if (!mReadBuffer.readTags(e.tags, wayTags, numberOfTags)) - return false; + if (!mReadBuffer.readTags(e.tags, wayTags, numberOfTags)) + return false; - numTags = numberOfTags; - } + numTags = numberOfTags; + } /* get the feature bitmask (1 byte) */ - byte featureByte = mReadBuffer.readByte(); + byte featureByte = mReadBuffer.readByte(); /* bit 1-6 enable optional features */ - boolean featureWayDoubleDeltaEncoding = - (featureByte & WAY_FEATURE_DOUBLE_DELTA_ENCODING) != 0; + boolean featureWayDoubleDeltaEncoding = + (featureByte & WAY_FEATURE_DOUBLE_DELTA_ENCODING) != 0; - boolean hasName = (featureByte & WAY_FEATURE_NAME) != 0; - boolean hasHouseNr = (featureByte & WAY_FEATURE_HOUSE_NUMBER) != 0; - boolean hasRef = (featureByte & WAY_FEATURE_REF) != 0; + boolean hasName = (featureByte & WAY_FEATURE_NAME) != 0; + boolean hasHouseNr = (featureByte & WAY_FEATURE_HOUSE_NUMBER) != 0; + boolean hasRef = (featureByte & WAY_FEATURE_REF) != 0; - e.tags.numTags = numTags; + e.tags.numTags = numTags; - if (mTileSource.experimental) { - if (hasName) { - int textPos = mReadBuffer.readUnsignedInt(); - String str = mTileSource.extractLocalized(mReadBuffer.readUTF8EncodedStringAt(stringOffset + textPos)); - e.tags.add(new Tag(Tag.KEY_NAME, str, false)); - } - if (hasHouseNr) { - int textPos = mReadBuffer.readUnsignedInt(); - String str = mReadBuffer.readUTF8EncodedStringAt(stringOffset + textPos); - e.tags.add(new Tag(Tag.KEY_HOUSE_NUMBER, str, false)); - } - if (hasRef) { - int textPos = mReadBuffer.readUnsignedInt(); - String str = mReadBuffer.readUTF8EncodedStringAt(stringOffset + textPos); - e.tags.add(new Tag(Tag.KEY_REF, str, false)); - } - } else { - if (hasName) { - String str = mTileSource.extractLocalized(mReadBuffer.readUTF8EncodedString()); - e.tags.add(new Tag(Tag.KEY_NAME, str, false)); - } - if (hasHouseNr) { - String str = mReadBuffer.readUTF8EncodedString(); - e.tags.add(new Tag(Tag.KEY_HOUSE_NUMBER, str, false)); - } - if (hasRef) { - String str = mReadBuffer.readUTF8EncodedString(); - e.tags.add(new Tag(Tag.KEY_REF, str, false)); - } - } - if ((featureByte & WAY_FEATURE_LABEL_POSITION) != 0) - // labelPosition = - readOptionalLabelPosition(); + if (mTileSource.experimental) { + if (hasName) { + int textPos = mReadBuffer.readUnsignedInt(); + String str = mTileSource.extractLocalized(mReadBuffer.readUTF8EncodedStringAt(stringOffset + textPos)); + e.tags.add(new Tag(Tag.KEY_NAME, str, false)); + } + if (hasHouseNr) { + int textPos = mReadBuffer.readUnsignedInt(); + String str = mReadBuffer.readUTF8EncodedStringAt(stringOffset + textPos); + e.tags.add(new Tag(Tag.KEY_HOUSE_NUMBER, str, false)); + } + if (hasRef) { + int textPos = mReadBuffer.readUnsignedInt(); + String str = mReadBuffer.readUTF8EncodedStringAt(stringOffset + textPos); + e.tags.add(new Tag(Tag.KEY_REF, str, false)); + } + } else { + if (hasName) { + String str = mTileSource.extractLocalized(mReadBuffer.readUTF8EncodedString()); + e.tags.add(new Tag(Tag.KEY_NAME, str, false)); + } + if (hasHouseNr) { + String str = mReadBuffer.readUTF8EncodedString(); + e.tags.add(new Tag(Tag.KEY_HOUSE_NUMBER, str, false)); + } + if (hasRef) { + String str = mReadBuffer.readUTF8EncodedString(); + e.tags.add(new Tag(Tag.KEY_REF, str, false)); + } + } + if ((featureByte & WAY_FEATURE_LABEL_POSITION) != 0) + // labelPosition = + readOptionalLabelPosition(); - if ((featureByte & WAY_FEATURE_DATA_BLOCKS_BYTE) != 0) { - wayDataBlocks = mReadBuffer.readUnsignedInt(); + if ((featureByte & WAY_FEATURE_DATA_BLOCKS_BYTE) != 0) { + wayDataBlocks = mReadBuffer.readUnsignedInt(); - if (wayDataBlocks < 1) { - log.warn("invalid number of way data blocks: " + wayDataBlocks); - logDebugSignatures(); - return false; - } - } else { - wayDataBlocks = 1; - } + if (wayDataBlocks < 1) { + log.warn("invalid number of way data blocks: " + wayDataBlocks); + logDebugSignatures(); + return false; + } + } else { + wayDataBlocks = 1; + } /* some guessing if feature is a line or a polygon */ - boolean linearFeature = !OSMUtils.isArea(e); + boolean linearFeature = !OSMUtils.isArea(e); - for (int wayDataBlock = 0; wayDataBlock < wayDataBlocks; wayDataBlock++) { - e.clear(); + for (int wayDataBlock = 0; wayDataBlock < wayDataBlocks; wayDataBlock++) { + e.clear(); - if (!processWayDataBlock(e, featureWayDoubleDeltaEncoding, linearFeature)) - return false; + if (!processWayDataBlock(e, featureWayDoubleDeltaEncoding, linearFeature)) + return false; /* drop invalid outer ring */ - if (e.isPoly() && e.index[0] < 6) { - continue; - } + if (e.isPoly() && e.index[0] < 6) { + continue; + } - mTileProjection.project(e); + mTileProjection.project(e); - if (!e.tags.containsKey("building")) - if (!mTileClipper.clip(e)) { - continue; - } - e.simplify(1, true); + if (!e.tags.containsKey("building")) + if (!mTileClipper.clip(e)) { + continue; + } + e.simplify(1, true); - e.setLayer(layer); - mapDataSink.process(e); - } - } + e.setLayer(layer); + mapDataSink.process(e); + } + } - return true; - } + return true; + } - private float[] readOptionalLabelPosition() { - float[] labelPosition = new float[2]; + private float[] readOptionalLabelPosition() { + float[] labelPosition = new float[2]; /* get the label position latitude offset (VBE-S) */ - labelPosition[1] = mTileLatitude + mReadBuffer.readSignedInt(); + labelPosition[1] = mTileLatitude + mReadBuffer.readSignedInt(); /* get the label position longitude offset (VBE-S) */ - labelPosition[0] = mTileLongitude + mReadBuffer.readSignedInt(); + labelPosition[0] = mTileLongitude + mReadBuffer.readSignedInt(); - return labelPosition; - } + return labelPosition; + } - private int[][] readZoomTable(SubFileParameter subFileParameter) { - int rows = subFileParameter.zoomLevelMax - subFileParameter.zoomLevelMin + 1; - int[][] zoomTable = new int[rows][2]; + private int[][] readZoomTable(SubFileParameter subFileParameter) { + int rows = subFileParameter.zoomLevelMax - subFileParameter.zoomLevelMin + 1; + int[][] zoomTable = new int[rows][2]; - int cumulatedNumberOfPois = 0; - int cumulatedNumberOfWays = 0; + int cumulatedNumberOfPois = 0; + int cumulatedNumberOfWays = 0; - for (int row = 0; row < rows; row++) { - cumulatedNumberOfPois += mReadBuffer.readUnsignedInt(); - cumulatedNumberOfWays += mReadBuffer.readUnsignedInt(); + for (int row = 0; row < rows; row++) { + cumulatedNumberOfPois += mReadBuffer.readUnsignedInt(); + cumulatedNumberOfWays += mReadBuffer.readUnsignedInt(); - if (cumulatedNumberOfPois < 0 - || cumulatedNumberOfPois > MAXIMUM_ZOOM_TABLE_OBJECTS) { - log.warn("invalid cumulated number of POIs in row " + row + ' ' - + cumulatedNumberOfPois); - if (mDebugFile) { - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - return null; - } else if (cumulatedNumberOfWays < 0 - || cumulatedNumberOfWays > MAXIMUM_ZOOM_TABLE_OBJECTS) { - log.warn("invalid cumulated number of ways in row " + row + ' ' - + cumulatedNumberOfWays); - if (mTileSource.fileInfo.debugFile) { - log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); - } - return null; - } + if (cumulatedNumberOfPois < 0 + || cumulatedNumberOfPois > MAXIMUM_ZOOM_TABLE_OBJECTS) { + log.warn("invalid cumulated number of POIs in row " + row + ' ' + + cumulatedNumberOfPois); + if (mDebugFile) { + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + return null; + } else if (cumulatedNumberOfWays < 0 + || cumulatedNumberOfWays > MAXIMUM_ZOOM_TABLE_OBJECTS) { + log.warn("invalid cumulated number of ways in row " + row + ' ' + + cumulatedNumberOfWays); + if (mTileSource.fileInfo.debugFile) { + log.warn(DEBUG_SIGNATURE_BLOCK + mSignatureBlock); + } + return null; + } - zoomTable[row][0] = cumulatedNumberOfPois; - zoomTable[row][1] = cumulatedNumberOfWays; - } + zoomTable[row][0] = cumulatedNumberOfPois; + zoomTable[row][1] = cumulatedNumberOfWays; + } - return zoomTable; - } + return zoomTable; + } - static class TileProjection { - private static final double COORD_SCALE = 1000000.0; + static class TileProjection { + private static final double COORD_SCALE = 1000000.0; - long dx, dy; - double divx, divy; + long dx, dy; + double divx, divy; - void setTile(Tile tile) { + void setTile(Tile tile) { /* tile position in pixels at tile zoom */ - long x = tile.tileX * Tile.SIZE; - long y = tile.tileY * Tile.SIZE + Tile.SIZE; + long x = tile.tileX * Tile.SIZE; + long y = tile.tileY * Tile.SIZE + Tile.SIZE; /* size of the map in pixel at tile zoom */ - long mapExtents = Tile.SIZE << tile.zoomLevel; + long mapExtents = Tile.SIZE << tile.zoomLevel; /* offset relative to lat/lon == 0 */ - dx = (x - (mapExtents >> 1)); - dy = (y - (mapExtents >> 1)); + dx = (x - (mapExtents >> 1)); + dy = (y - (mapExtents >> 1)); /* scales longitude(1e6) to map-pixel */ - divx = (180.0 * COORD_SCALE) / (mapExtents >> 1); + divx = (180.0 * COORD_SCALE) / (mapExtents >> 1); /* scale latidute to map-pixel */ - divy = (Math.PI * 2.0) / (mapExtents >> 1); - } + divy = (Math.PI * 2.0) / (mapExtents >> 1); + } - public void projectPoint(int lat, int lon, MapElement out) { - out.clear(); - out.startPoints(); - out.addPoint(projectLon(lon), projectLat(lat)); - } + public void projectPoint(int lat, int lon, MapElement out) { + out.clear(); + out.startPoints(); + out.addPoint(projectLon(lon), projectLat(lat)); + } - public float projectLat(double lat) { - double s = Math.sin(lat * ((Math.PI / 180) / COORD_SCALE)); - double r = Math.log((1.0 + s) / (1.0 - s)); + public float projectLat(double lat) { + double s = Math.sin(lat * ((Math.PI / 180) / COORD_SCALE)); + double r = Math.log((1.0 + s) / (1.0 - s)); - return Tile.SIZE - (float) (r / divy + dy); - } + return Tile.SIZE - (float) (r / divy + dy); + } - public float projectLon(double lon) { - return (float) (lon / divx - dx); - } + public float projectLon(double lon) { + return (float) (lon / divx - dx); + } - void project(MapElement e) { + void project(MapElement e) { - float[] coords = e.points; - int[] indices = e.index; + float[] coords = e.points; + int[] indices = e.index; - int inPos = 0; - int outPos = 0; + int inPos = 0; + int outPos = 0; - boolean isPoly = e.isPoly(); + boolean isPoly = e.isPoly(); - for (int idx = 0, m = indices.length; idx < m; idx++) { - int len = indices[idx]; - if (len == 0) - continue; - if (len < 0) - break; + for (int idx = 0, m = indices.length; idx < m; idx++) { + int len = indices[idx]; + if (len == 0) + continue; + if (len < 0) + break; - float lat, lon, pLon = 0, pLat = 0; - int cnt = 0, first = outPos; + float lat, lon, pLon = 0, pLat = 0; + int cnt = 0, first = outPos; - for (int end = inPos + len; inPos < end; inPos += 2) { - lon = projectLon(coords[inPos]); - lat = projectLat(coords[inPos + 1]); + for (int end = inPos + len; inPos < end; inPos += 2) { + lon = projectLon(coords[inPos]); + lat = projectLat(coords[inPos + 1]); - if (cnt != 0) { + if (cnt != 0) { /* drop small distance intermediate nodes */ - if (lat == pLat && lon == pLon) { - //log.debug("drop zero delta "); - continue; - } - } - coords[outPos++] = pLon = lon; - coords[outPos++] = pLat = lat; - cnt += 2; - } + if (lat == pLat && lon == pLon) { + //log.debug("drop zero delta "); + continue; + } + } + coords[outPos++] = pLon = lon; + coords[outPos++] = pLat = lat; + cnt += 2; + } - if (isPoly && coords[first] == pLon && coords[first + 1] == pLat) { + if (isPoly && coords[first] == pLon && coords[first + 1] == pLat) { /* remove identical start/end point */ - //log.debug("drop closing point {}", e); - indices[idx] = (short) (cnt - 2); - outPos -= 2; - } else { - indices[idx] = (short) cnt; - } - } - } - } + //log.debug("drop closing point {}", e); + indices[idx] = (short) (cnt - 2); + outPos -= 2; + } else { + indices[idx] = (short) cnt; + } + } + } + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/MapFileTileSource.java b/vtm/src/org/oscim/tiling/source/mapfile/MapFileTileSource.java index 4e80c99c..f9b650f4 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/MapFileTileSource.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/MapFileTileSource.java @@ -18,10 +18,6 @@ */ package org.oscim.tiling.source.mapfile; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; - import org.oscim.tiling.ITileDataSource; import org.oscim.tiling.TileSource; import org.oscim.tiling.source.mapfile.header.MapFileHeader; @@ -30,147 +26,151 @@ import org.oscim.utils.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + public class MapFileTileSource extends TileSource { - static final Logger log = LoggerFactory.getLogger(MapFileTileSource.class); + static final Logger log = LoggerFactory.getLogger(MapFileTileSource.class); - /** - * Amount of cache blocks that the index cache should store. - */ - private static final int INDEX_CACHE_SIZE = 64; - private static final String READ_ONLY_MODE = "r"; + /** + * Amount of cache blocks that the index cache should store. + */ + private static final int INDEX_CACHE_SIZE = 64; + private static final String READ_ONLY_MODE = "r"; - MapFileHeader fileHeader; - MapFileInfo fileInfo; - IndexCache databaseIndexCache; - boolean experimental; - File mapFile; - RandomAccessFile mInputFile; + MapFileHeader fileHeader; + MapFileInfo fileInfo; + IndexCache databaseIndexCache; + boolean experimental; + File mapFile; + RandomAccessFile mInputFile; - /** - * The preferred language when extracting labels from this tile source. - */ - private String preferredLanguage; - private Callback callback; + /** + * The preferred language when extracting labels from this tile source. + */ + private String preferredLanguage; + private Callback callback; - public MapFileTileSource() { - super(0, 17); - } + public MapFileTileSource() { + super(0, 17); + } - /** - * Extracts substring of preferred language from multilingual string using - * the preferredLanguage setting. - */ - String extractLocalized(String s) { - if (callback != null) - return callback.extractLocalized(s); - return MapFileUtils.extract(s, preferredLanguage); - } + /** + * Extracts substring of preferred language from multilingual string using + * the preferredLanguage setting. + */ + String extractLocalized(String s) { + if (callback != null) + return callback.extractLocalized(s); + return MapFileUtils.extract(s, preferredLanguage); + } - public void setCallback(Callback callback) { - this.callback = callback; - } + public void setCallback(Callback callback) { + this.callback = callback; + } - public boolean setMapFile(String filename) { - setOption("file", filename); + public boolean setMapFile(String filename) { + setOption("file", filename); - File file = new File(filename); + File file = new File(filename); - if (!file.exists()) { - return false; - } else if (!file.isFile()) { - return false; - } else if (!file.canRead()) { - return false; - } + if (!file.exists()) { + return false; + } else if (!file.isFile()) { + return false; + } else if (!file.canRead()) { + return false; + } - return true; - } + return true; + } - public void setPreferredLanguage(String preferredLanguage) { - this.preferredLanguage = preferredLanguage; - } + public void setPreferredLanguage(String preferredLanguage) { + this.preferredLanguage = preferredLanguage; + } - @Override - public OpenResult open() { - if (!options.containsKey("file")) - return new OpenResult("no map file set"); + @Override + public OpenResult open() { + if (!options.containsKey("file")) + return new OpenResult("no map file set"); - try { - // make sure to close any previously opened file first - //close(); + try { + // make sure to close any previously opened file first + //close(); - File file = new File(options.get("file")); + File file = new File(options.get("file")); - // check if the file exists and is readable - if (!file.exists()) { - return new OpenResult("file does not exist: " + file); - } else if (!file.isFile()) { - return new OpenResult("not a file: " + file); - } else if (!file.canRead()) { - return new OpenResult("cannot read file: " + file); - } + // check if the file exists and is readable + if (!file.exists()) { + return new OpenResult("file does not exist: " + file); + } else if (!file.isFile()) { + return new OpenResult("not a file: " + file); + } else if (!file.canRead()) { + return new OpenResult("cannot read file: " + file); + } - // open the file in read only mode - mInputFile = new RandomAccessFile(file, READ_ONLY_MODE); - long mFileSize = mInputFile.length(); - ReadBuffer mReadBuffer = new ReadBuffer(mInputFile); + // open the file in read only mode + mInputFile = new RandomAccessFile(file, READ_ONLY_MODE); + long mFileSize = mInputFile.length(); + ReadBuffer mReadBuffer = new ReadBuffer(mInputFile); - fileHeader = new MapFileHeader(); - OpenResult openResult = fileHeader.readHeader(mReadBuffer, mFileSize); + fileHeader = new MapFileHeader(); + OpenResult openResult = fileHeader.readHeader(mReadBuffer, mFileSize); - if (!openResult.isSuccess()) { - close(); - return openResult; - } - fileInfo = fileHeader.getMapFileInfo(); - mapFile = file; - databaseIndexCache = new IndexCache(mInputFile, INDEX_CACHE_SIZE); + if (!openResult.isSuccess()) { + close(); + return openResult; + } + fileInfo = fileHeader.getMapFileInfo(); + mapFile = file; + databaseIndexCache = new IndexCache(mInputFile, INDEX_CACHE_SIZE); - // Experimental? - //experimental = fileInfo.fileVersion == 4; + // Experimental? + //experimental = fileInfo.fileVersion == 4; - log.debug("File version: " + fileInfo.fileVersion); - return OpenResult.SUCCESS; - } catch (IOException e) { - log.error(e.getMessage()); - // make sure that the file is closed - close(); - return new OpenResult(e.getMessage()); - } - } + log.debug("File version: " + fileInfo.fileVersion); + return OpenResult.SUCCESS; + } catch (IOException e) { + log.error(e.getMessage()); + // make sure that the file is closed + close(); + return new OpenResult(e.getMessage()); + } + } - @Override - public ITileDataSource getDataSource() { - try { - return new MapDatabase(this); - } catch (IOException e) { - log.debug(e.getMessage()); - } - return null; - } + @Override + public ITileDataSource getDataSource() { + try { + return new MapDatabase(this); + } catch (IOException e) { + log.debug(e.getMessage()); + } + return null; + } - @Override - public void close() { - IOUtils.closeQuietly(mInputFile); - mInputFile = null; - fileHeader = null; - fileInfo = null; - mapFile = null; + @Override + public void close() { + IOUtils.closeQuietly(mInputFile); + mInputFile = null; + fileHeader = null; + fileInfo = null; + mapFile = null; - if (databaseIndexCache != null) { - databaseIndexCache.destroy(); - databaseIndexCache = null; - } - } + if (databaseIndexCache != null) { + databaseIndexCache.destroy(); + databaseIndexCache = null; + } + } - public MapInfo getMapInfo() { - return fileInfo; - } + public MapInfo getMapInfo() { + return fileInfo; + } - public interface Callback { - /** - * Extracts substring of preferred language from multilingual string. - */ - String extractLocalized(String s); - } + public interface Callback { + /** + * Extracts substring of preferred language from multilingual string. + */ + String extractLocalized(String s); + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/MapInfo.java b/vtm/src/org/oscim/tiling/source/mapfile/MapInfo.java index e19cce8d..462c8ffd 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/MapInfo.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/MapInfo.java @@ -22,111 +22,99 @@ import org.oscim.core.GeoPoint; /** * Contains the immutable metadata of a map file. - * */ public class MapInfo { - /** - * The bounding box of the map file. - */ - public final BoundingBox boundingBox; + /** + * The bounding box of the map file. + */ + public final BoundingBox boundingBox; - /** - * The comment field of the map file (may be null). - */ - public final String comment; + /** + * The comment field of the map file (may be null). + */ + public final String comment; - /** - * The created by field of the map file (may be null). - */ - public final String createdBy; + /** + * The created by field of the map file (may be null). + */ + public final String createdBy; - /** - * The size of the map file, measured in bytes. - */ - public final long fileSize; + /** + * The size of the map file, measured in bytes. + */ + public final long fileSize; - /** - * The file version number of the map file. - */ - public final int fileVersion; + /** + * The file version number of the map file. + */ + public final int fileVersion; - /** - * The preferred language(s) separated with ',' for names as defined in ISO 639-1 or ISO 639-2 (may be null). - */ - public final String languagesPreference; + /** + * The preferred language(s) separated with ',' for names as defined in ISO 639-1 or ISO 639-2 (may be null). + */ + public final String languagesPreference; - /** - * The center point of the map file. - */ - public final GeoPoint mapCenter; + /** + * The center point of the map file. + */ + public final GeoPoint mapCenter; - /** - * The date of the map data in milliseconds since January 1, 1970. - */ - public final long mapDate; + /** + * The date of the map data in milliseconds since January 1, 1970. + */ + public final long mapDate; - /** - * The name of the projection used in the map file. - */ - public final String projectionName; + /** + * The name of the projection used in the map file. + */ + public final String projectionName; - /** - * The map start position from the file header (may be null). - */ - public final GeoPoint startPosition; + /** + * The map start position from the file header (may be null). + */ + public final GeoPoint startPosition; - /** - * The map start zoom level from the file header (may be null). - */ - public final Byte startZoomLevel; + /** + * The map start zoom level from the file header (may be null). + */ + public final Byte startZoomLevel; - /** - * Zoomlevels provided by this Database, if null then any zoomlevel can be - * queried. - */ - public final int[] zoomLevel; + /** + * Zoomlevels provided by this Database, if null then any zoomlevel can be + * queried. + */ + public final int[] zoomLevel; - /** - * @param bbox - * ... - * @param zoom - * ... - * @param start - * ... - * @param projection - * ... - * @param date - * ... - * @param size - * ... - * @param version - * ... - * @param language - * ... - * @param comment - * ... - * @param createdBy - * ... - * @param zoomLevel - * TODO - */ - public MapInfo(BoundingBox bbox, Byte zoom, GeoPoint start, String projection, - long date, long size, int version, String language, String comment, - String createdBy, int[] zoomLevel) { + /** + * @param bbox ... + * @param zoom ... + * @param start ... + * @param projection ... + * @param date ... + * @param size ... + * @param version ... + * @param language ... + * @param comment ... + * @param createdBy ... + * @param zoomLevel TODO + */ + public MapInfo(BoundingBox bbox, Byte zoom, GeoPoint start, String projection, + long date, long size, int version, String language, String comment, + String createdBy, int[] zoomLevel) { - this.startZoomLevel = zoom; - this.zoomLevel = zoomLevel; - this.startPosition = start; - this.projectionName = projection; - this.mapDate = date; - this.boundingBox = bbox; - this.mapCenter = bbox.getCenterPoint(); - this.languagesPreference = language; - this.fileSize = size; - this.fileVersion = version; + this.startZoomLevel = zoom; + this.zoomLevel = zoomLevel; + this.startPosition = start; + this.projectionName = projection; + this.mapDate = date; + this.boundingBox = bbox; + this.mapCenter = bbox.getCenterPoint(); + this.languagesPreference = language; + this.fileSize = size; + this.fileVersion = version; - this.comment = comment; - this.createdBy = createdBy; + this.comment = comment; + this.createdBy = createdBy; - } + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/Projection.java b/vtm/src/org/oscim/tiling/source/mapfile/Projection.java index 5b62f23a..b7ded649 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/Projection.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/Projection.java @@ -20,150 +20,130 @@ import org.oscim.core.Tile; public class Projection { - /** - * Converts a tile X number at a certain zoom level to a longitude - * coordinate. - * - * @param tileX - * the tile X number that should be converted. - * @param zoomLevel - * the zoom level at which the number should be converted. - * @return the longitude value of the tile X number. - */ - public static double tileXToLongitude(long tileX, int zoomLevel) { - return pixelXToLongitude(tileX * Tile.SIZE, zoomLevel); - } + /** + * Converts a tile X number at a certain zoom level to a longitude + * coordinate. + * + * @param tileX the tile X number that should be converted. + * @param zoomLevel the zoom level at which the number should be converted. + * @return the longitude value of the tile X number. + */ + public static double tileXToLongitude(long tileX, int zoomLevel) { + return pixelXToLongitude(tileX * Tile.SIZE, zoomLevel); + } - /** - * Converts a tile Y number at a certain zoom level to a latitude - * coordinate. - * - * @param tileY - * the tile Y number that should be converted. - * @param zoomLevel - * the zoom level at which the number should be converted. - * @return the latitude value of the tile Y number. - */ - public static double tileYToLatitude(long tileY, int zoomLevel) { - return pixelYToLatitude(tileY * Tile.SIZE, zoomLevel); - } + /** + * Converts a tile Y number at a certain zoom level to a latitude + * coordinate. + * + * @param tileY the tile Y number that should be converted. + * @param zoomLevel the zoom level at which the number should be converted. + * @return the latitude value of the tile Y number. + */ + public static double tileYToLatitude(long tileY, int zoomLevel) { + return pixelYToLatitude(tileY * Tile.SIZE, zoomLevel); + } - /** - * Converts a latitude coordinate (in degrees) to a tile Y number at a - * certain zoom level. - * - * @param latitude - * the latitude coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the tile Y number of the latitude value. - */ - public static long latitudeToTileY(double latitude, int zoomLevel) { - return pixelYToTileY(latitudeToPixelY(latitude, zoomLevel), zoomLevel); - } + /** + * Converts a latitude coordinate (in degrees) to a tile Y number at a + * certain zoom level. + * + * @param latitude the latitude coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the tile Y number of the latitude value. + */ + public static long latitudeToTileY(double latitude, int zoomLevel) { + return pixelYToTileY(latitudeToPixelY(latitude, zoomLevel), zoomLevel); + } - /** - * Converts a longitude coordinate (in degrees) to the tile X number at a - * certain zoom level. - * - * @param longitude - * the longitude coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the tile X number of the longitude value. - */ - public static long longitudeToTileX(double longitude, int zoomLevel) { - return pixelXToTileX(longitudeToPixelX(longitude, zoomLevel), zoomLevel); - } + /** + * Converts a longitude coordinate (in degrees) to the tile X number at a + * certain zoom level. + * + * @param longitude the longitude coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the tile X number of the longitude value. + */ + public static long longitudeToTileX(double longitude, int zoomLevel) { + return pixelXToTileX(longitudeToPixelX(longitude, zoomLevel), zoomLevel); + } - /** - * Converts a pixel X coordinate to the tile X number. - * - * @param pixelX - * the pixel X coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the tile X number. - */ - public static int pixelXToTileX(double pixelX, int zoomLevel) { - return (int) Math.min(Math.max(pixelX / Tile.SIZE, 0), - Math.pow(2, zoomLevel) - 1); - } + /** + * Converts a pixel X coordinate to the tile X number. + * + * @param pixelX the pixel X coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the tile X number. + */ + public static int pixelXToTileX(double pixelX, int zoomLevel) { + return (int) Math.min(Math.max(pixelX / Tile.SIZE, 0), + Math.pow(2, zoomLevel) - 1); + } - /** - * Converts a pixel Y coordinate to the tile Y number. - * - * @param pixelY - * the pixel Y coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the tile Y number. - */ - public static int pixelYToTileY(double pixelY, int zoomLevel) { - return (int) Math.min(Math.max(pixelY / Tile.SIZE, 0), - Math.pow(2, zoomLevel) - 1); - } + /** + * Converts a pixel Y coordinate to the tile Y number. + * + * @param pixelY the pixel Y coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the tile Y number. + */ + public static int pixelYToTileY(double pixelY, int zoomLevel) { + return (int) Math.min(Math.max(pixelY / Tile.SIZE, 0), + Math.pow(2, zoomLevel) - 1); + } - /** - * Converts a pixel X coordinate at a certain zoom level to a longitude - * coordinate. - * - * @param pixelX - * the pixel X coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the longitude value of the pixel X coordinate. - */ - public static double pixelXToLongitude(double pixelX, int zoomLevel) { - return 360 * ((pixelX / ((long) Tile.SIZE << zoomLevel)) - 0.5); - } + /** + * Converts a pixel X coordinate at a certain zoom level to a longitude + * coordinate. + * + * @param pixelX the pixel X coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the longitude value of the pixel X coordinate. + */ + public static double pixelXToLongitude(double pixelX, int zoomLevel) { + return 360 * ((pixelX / ((long) Tile.SIZE << zoomLevel)) - 0.5); + } - /** - * Converts a longitude coordinate (in degrees) to a pixel X coordinate at a - * certain zoom level. - * - * @param longitude - * the longitude coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the pixel X coordinate of the longitude value. - */ - public static double longitudeToPixelX(double longitude, int zoomLevel) { - return (longitude + 180) / 360 * ((long) Tile.SIZE << zoomLevel); - } + /** + * Converts a longitude coordinate (in degrees) to a pixel X coordinate at a + * certain zoom level. + * + * @param longitude the longitude coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the pixel X coordinate of the longitude value. + */ + public static double longitudeToPixelX(double longitude, int zoomLevel) { + return (longitude + 180) / 360 * ((long) Tile.SIZE << zoomLevel); + } - /** - * Converts a pixel Y coordinate at a certain zoom level to a latitude - * coordinate. - * - * @param pixelY - * the pixel Y coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the latitude value of the pixel Y coordinate. - */ - public static double pixelYToLatitude(double pixelY, int zoomLevel) { - double y = 0.5 - (pixelY / ((long) Tile.SIZE << zoomLevel)); - return 90 - 360 * Math.atan(Math.exp(-y * (2 * Math.PI))) / Math.PI; - } + /** + * Converts a pixel Y coordinate at a certain zoom level to a latitude + * coordinate. + * + * @param pixelY the pixel Y coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the latitude value of the pixel Y coordinate. + */ + public static double pixelYToLatitude(double pixelY, int zoomLevel) { + double y = 0.5 - (pixelY / ((long) Tile.SIZE << zoomLevel)); + return 90 - 360 * Math.atan(Math.exp(-y * (2 * Math.PI))) / Math.PI; + } - /** - * Converts a latitude coordinate (in degrees) to a pixel Y coordinate at a - * certain zoom level. - * - * @param latitude - * the latitude coordinate that should be converted. - * @param zoomLevel - * the zoom level at which the coordinate should be converted. - * @return the pixel Y coordinate of the latitude value. - */ - public static double latitudeToPixelY(double latitude, int zoomLevel) { - double sinLatitude = Math.sin(latitude * (Math.PI / 180)); - return (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) - * ((long) Tile.SIZE << zoomLevel); - } + /** + * Converts a latitude coordinate (in degrees) to a pixel Y coordinate at a + * certain zoom level. + * + * @param latitude the latitude coordinate that should be converted. + * @param zoomLevel the zoom level at which the coordinate should be converted. + * @return the pixel Y coordinate of the latitude value. + */ + public static double latitudeToPixelY(double latitude, int zoomLevel) { + double sinLatitude = Math.sin(latitude * (Math.PI / 180)); + return (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) + * ((long) Tile.SIZE << zoomLevel); + } - private Projection() { + private Projection() { - } + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/QueryCalculations.java b/vtm/src/org/oscim/tiling/source/mapfile/QueryCalculations.java index a0b73741..a3d4dd52 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/QueryCalculations.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/QueryCalculations.java @@ -20,158 +20,158 @@ import org.oscim.core.Tile; import org.oscim.tiling.source.mapfile.header.SubFileParameter; final class QueryCalculations { - private static int getFirstLevelTileBitmask(Tile tile) { - if (tile.tileX % 2 == 0 && tile.tileY % 2 == 0) { - // upper left quadrant - return 0xcc00; - } else if ((tile.tileX & 1) == 1 && tile.tileY % 2 == 0) { - // upper right quadrant - return 0x3300; - } else if (tile.tileX % 2 == 0 && (tile.tileY & 1) == 1) { - // lower left quadrant - return 0xcc; - } else { - // lower right quadrant - return 0x33; - } - } + private static int getFirstLevelTileBitmask(Tile tile) { + if (tile.tileX % 2 == 0 && tile.tileY % 2 == 0) { + // upper left quadrant + return 0xcc00; + } else if ((tile.tileX & 1) == 1 && tile.tileY % 2 == 0) { + // upper right quadrant + return 0x3300; + } else if (tile.tileX % 2 == 0 && (tile.tileY & 1) == 1) { + // lower left quadrant + return 0xcc; + } else { + // lower right quadrant + return 0x33; + } + } - private static int getSecondLevelTileBitmaskLowerLeft(long subtileX, long subtileY) { - if (subtileX % 2 == 0 && subtileY % 2 == 0) { - // upper left sub-tile - return 0x80; - } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { - // upper right sub-tile - return 0x40; - } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { - // lower left sub-tile - return 0x8; - } else { - // lower right sub-tile - return 0x4; - } - } + private static int getSecondLevelTileBitmaskLowerLeft(long subtileX, long subtileY) { + if (subtileX % 2 == 0 && subtileY % 2 == 0) { + // upper left sub-tile + return 0x80; + } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { + // upper right sub-tile + return 0x40; + } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { + // lower left sub-tile + return 0x8; + } else { + // lower right sub-tile + return 0x4; + } + } - private static int getSecondLevelTileBitmaskLowerRight(long subtileX, long subtileY) { - if (subtileX % 2 == 0 && subtileY % 2 == 0) { - // upper left sub-tile - return 0x20; - } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { - // upper right sub-tile - return 0x10; - } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { - // lower left sub-tile - return 0x2; - } else { - // lower right sub-tile - return 0x1; - } - } + private static int getSecondLevelTileBitmaskLowerRight(long subtileX, long subtileY) { + if (subtileX % 2 == 0 && subtileY % 2 == 0) { + // upper left sub-tile + return 0x20; + } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { + // upper right sub-tile + return 0x10; + } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { + // lower left sub-tile + return 0x2; + } else { + // lower right sub-tile + return 0x1; + } + } - private static int getSecondLevelTileBitmaskUpperLeft(long subtileX, long subtileY) { - if (subtileX % 2 == 0 && subtileY % 2 == 0) { - // upper left sub-tile - return 0x8000; - } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { - // upper right sub-tile - return 0x4000; - } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { - // lower left sub-tile - return 0x800; - } else { - // lower right sub-tile - return 0x400; - } - } + private static int getSecondLevelTileBitmaskUpperLeft(long subtileX, long subtileY) { + if (subtileX % 2 == 0 && subtileY % 2 == 0) { + // upper left sub-tile + return 0x8000; + } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { + // upper right sub-tile + return 0x4000; + } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { + // lower left sub-tile + return 0x800; + } else { + // lower right sub-tile + return 0x400; + } + } - private static int getSecondLevelTileBitmaskUpperRight(long subtileX, long subtileY) { - if (subtileX % 2 == 0 && subtileY % 2 == 0) { - // upper left sub-tile - return 0x2000; - } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { - // upper right sub-tile - return 0x1000; - } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { - // lower left sub-tile - return 0x200; - } else { - // lower right sub-tile - return 0x100; - } - } + private static int getSecondLevelTileBitmaskUpperRight(long subtileX, long subtileY) { + if (subtileX % 2 == 0 && subtileY % 2 == 0) { + // upper left sub-tile + return 0x2000; + } else if (subtileX % 2 == 1 && subtileY % 2 == 0) { + // upper right sub-tile + return 0x1000; + } else if (subtileX % 2 == 0 && subtileY % 2 == 1) { + // lower left sub-tile + return 0x200; + } else { + // lower right sub-tile + return 0x100; + } + } - static void calculateBaseTiles(QueryParameters queryParameters, Tile tile, - SubFileParameter subFileParameter) { - if (tile.zoomLevel < subFileParameter.baseZoomLevel) { - // calculate the XY numbers of the upper left and lower right - // sub-tiles - int zoomLevelDifference = subFileParameter.baseZoomLevel - tile.zoomLevel; - queryParameters.fromBaseTileX = tile.tileX << zoomLevelDifference; - queryParameters.fromBaseTileY = tile.tileY << zoomLevelDifference; - queryParameters.toBaseTileX = queryParameters.fromBaseTileX - + (1 << zoomLevelDifference) - 1; - queryParameters.toBaseTileY = queryParameters.fromBaseTileY - + (1 << zoomLevelDifference) - 1; - queryParameters.useTileBitmask = false; - } else if (tile.zoomLevel > subFileParameter.baseZoomLevel) { - // calculate the XY numbers of the parent base tile - int zoomLevelDifference = tile.zoomLevel - subFileParameter.baseZoomLevel; - queryParameters.fromBaseTileX = tile.tileX >>> zoomLevelDifference; - queryParameters.fromBaseTileY = tile.tileY >>> zoomLevelDifference; - queryParameters.toBaseTileX = queryParameters.fromBaseTileX; - queryParameters.toBaseTileY = queryParameters.fromBaseTileY; - queryParameters.useTileBitmask = true; - queryParameters.queryTileBitmask = calculateTileBitmask(tile, zoomLevelDifference); - } else { - // use the tile XY numbers of the requested tile - queryParameters.fromBaseTileX = tile.tileX; - queryParameters.fromBaseTileY = tile.tileY; - queryParameters.toBaseTileX = queryParameters.fromBaseTileX; - queryParameters.toBaseTileY = queryParameters.fromBaseTileY; - queryParameters.useTileBitmask = false; - } - } + static void calculateBaseTiles(QueryParameters queryParameters, Tile tile, + SubFileParameter subFileParameter) { + if (tile.zoomLevel < subFileParameter.baseZoomLevel) { + // calculate the XY numbers of the upper left and lower right + // sub-tiles + int zoomLevelDifference = subFileParameter.baseZoomLevel - tile.zoomLevel; + queryParameters.fromBaseTileX = tile.tileX << zoomLevelDifference; + queryParameters.fromBaseTileY = tile.tileY << zoomLevelDifference; + queryParameters.toBaseTileX = queryParameters.fromBaseTileX + + (1 << zoomLevelDifference) - 1; + queryParameters.toBaseTileY = queryParameters.fromBaseTileY + + (1 << zoomLevelDifference) - 1; + queryParameters.useTileBitmask = false; + } else if (tile.zoomLevel > subFileParameter.baseZoomLevel) { + // calculate the XY numbers of the parent base tile + int zoomLevelDifference = tile.zoomLevel - subFileParameter.baseZoomLevel; + queryParameters.fromBaseTileX = tile.tileX >>> zoomLevelDifference; + queryParameters.fromBaseTileY = tile.tileY >>> zoomLevelDifference; + queryParameters.toBaseTileX = queryParameters.fromBaseTileX; + queryParameters.toBaseTileY = queryParameters.fromBaseTileY; + queryParameters.useTileBitmask = true; + queryParameters.queryTileBitmask = calculateTileBitmask(tile, zoomLevelDifference); + } else { + // use the tile XY numbers of the requested tile + queryParameters.fromBaseTileX = tile.tileX; + queryParameters.fromBaseTileY = tile.tileY; + queryParameters.toBaseTileX = queryParameters.fromBaseTileX; + queryParameters.toBaseTileY = queryParameters.fromBaseTileY; + queryParameters.useTileBitmask = false; + } + } - static void calculateBlocks(QueryParameters queryParameters, SubFileParameter subFileParameter) { - // calculate the blocks in the file which need to be read - queryParameters.fromBlockX = Math.max(queryParameters.fromBaseTileX - - subFileParameter.boundaryTileLeft, 0); - queryParameters.fromBlockY = Math.max(queryParameters.fromBaseTileY - - subFileParameter.boundaryTileTop, 0); - queryParameters.toBlockX = Math.min(queryParameters.toBaseTileX - - subFileParameter.boundaryTileLeft, - subFileParameter.blocksWidth - 1); - queryParameters.toBlockY = Math.min(queryParameters.toBaseTileY - - subFileParameter.boundaryTileTop, - subFileParameter.blocksHeight - 1); - } + static void calculateBlocks(QueryParameters queryParameters, SubFileParameter subFileParameter) { + // calculate the blocks in the file which need to be read + queryParameters.fromBlockX = Math.max(queryParameters.fromBaseTileX + - subFileParameter.boundaryTileLeft, 0); + queryParameters.fromBlockY = Math.max(queryParameters.fromBaseTileY + - subFileParameter.boundaryTileTop, 0); + queryParameters.toBlockX = Math.min(queryParameters.toBaseTileX + - subFileParameter.boundaryTileLeft, + subFileParameter.blocksWidth - 1); + queryParameters.toBlockY = Math.min(queryParameters.toBaseTileY + - subFileParameter.boundaryTileTop, + subFileParameter.blocksHeight - 1); + } - static int calculateTileBitmask(Tile tile, int zoomLevelDifference) { - if (zoomLevelDifference == 1) { - return getFirstLevelTileBitmask(tile); - } + static int calculateTileBitmask(Tile tile, int zoomLevelDifference) { + if (zoomLevelDifference == 1) { + return getFirstLevelTileBitmask(tile); + } - // calculate the XY numbers of the second level sub-tile - long subtileX = tile.tileX >>> (zoomLevelDifference - 2); - long subtileY = tile.tileY >>> (zoomLevelDifference - 2); + // calculate the XY numbers of the second level sub-tile + long subtileX = tile.tileX >>> (zoomLevelDifference - 2); + long subtileY = tile.tileY >>> (zoomLevelDifference - 2); - // calculate the XY numbers of the parent tile - long parentTileX = subtileX >>> 1; - long parentTileY = subtileY >>> 1; + // calculate the XY numbers of the parent tile + long parentTileX = subtileX >>> 1; + long parentTileY = subtileY >>> 1; - // determine the correct bitmask for all 16 sub-tiles - if (parentTileX % 2 == 0 && parentTileY % 2 == 0) { - return getSecondLevelTileBitmaskUpperLeft(subtileX, subtileY); - } else if (parentTileX % 2 == 1 && parentTileY % 2 == 0) { - return getSecondLevelTileBitmaskUpperRight(subtileX, subtileY); - } else if (parentTileX % 2 == 0 && parentTileY % 2 == 1) { - return getSecondLevelTileBitmaskLowerLeft(subtileX, subtileY); - } else { - return getSecondLevelTileBitmaskLowerRight(subtileX, subtileY); - } - } + // determine the correct bitmask for all 16 sub-tiles + if (parentTileX % 2 == 0 && parentTileY % 2 == 0) { + return getSecondLevelTileBitmaskUpperLeft(subtileX, subtileY); + } else if (parentTileX % 2 == 1 && parentTileY % 2 == 0) { + return getSecondLevelTileBitmaskUpperRight(subtileX, subtileY); + } else if (parentTileX % 2 == 0 && parentTileY % 2 == 1) { + return getSecondLevelTileBitmaskLowerLeft(subtileX, subtileY); + } else { + return getSecondLevelTileBitmaskLowerRight(subtileX, subtileY); + } + } - private QueryCalculations() { - throw new IllegalStateException(); - } + private QueryCalculations() { + throw new IllegalStateException(); + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/QueryParameters.java b/vtm/src/org/oscim/tiling/source/mapfile/QueryParameters.java index 22a0813b..57de9270 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/QueryParameters.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/QueryParameters.java @@ -17,44 +17,44 @@ package org.oscim.tiling.source.mapfile; class QueryParameters { - long fromBaseTileX; - long fromBaseTileY; - long fromBlockX; - long fromBlockY; - int queryTileBitmask; - int queryZoomLevel; - long toBaseTileX; - long toBaseTileY; - long toBlockX; - long toBlockY; - boolean useTileBitmask; + long fromBaseTileX; + long fromBaseTileY; + long fromBlockX; + long fromBlockY; + int queryTileBitmask; + int queryZoomLevel; + long toBaseTileX; + long toBaseTileY; + long toBlockX; + long toBlockY; + boolean useTileBitmask; - @Override - public String toString() { - return new StringBuilder() - .append("QueryParameters [fromBaseTileX=") - .append(this.fromBaseTileX) - .append(", fromBaseTileY=") - .append(this.fromBaseTileY) - .append(", fromBlockX=") - .append(this.fromBlockX) - .append(", fromBlockY=") - .append(this.fromBlockY) - .append(", queryTileBitmask=") - .append(this.queryTileBitmask) - .append(", queryZoomLevel=") - .append(this.queryZoomLevel) - .append(", toBaseTileX=") - .append(this.toBaseTileX) - .append(", toBaseTileY=") - .append(this.toBaseTileY) - .append(", toBlockX=") - .append(this.toBlockX) - .append(", toBlockY=") - .append(this.toBlockY) - .append(", useTileBitmask=") - .append(this.useTileBitmask) - .append("]") - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("QueryParameters [fromBaseTileX=") + .append(this.fromBaseTileX) + .append(", fromBaseTileY=") + .append(this.fromBaseTileY) + .append(", fromBlockX=") + .append(this.fromBlockX) + .append(", fromBlockY=") + .append(this.fromBlockY) + .append(", queryTileBitmask=") + .append(this.queryTileBitmask) + .append(", queryZoomLevel=") + .append(this.queryZoomLevel) + .append(", toBaseTileX=") + .append(this.toBaseTileX) + .append(", toBaseTileY=") + .append(this.toBaseTileY) + .append(", toBlockX=") + .append(this.toBlockX) + .append(", toBlockY=") + .append(this.toBlockY) + .append(", useTileBitmask=") + .append(this.useTileBitmask) + .append("]") + .toString(); + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/ReadBuffer.java b/vtm/src/org/oscim/tiling/source/mapfile/ReadBuffer.java index fbbe1f21..18d2a2f3 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/ReadBuffer.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/ReadBuffer.java @@ -16,469 +16,461 @@ */ package org.oscim.tiling.source.mapfile; +import org.oscim.core.Tag; +import org.oscim.core.TagSet; + import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.util.logging.Logger; -import org.oscim.core.Tag; -import org.oscim.core.TagSet; - /** * Reads from a {@link RandomAccessFile} into a buffer and decodes the data. */ public class ReadBuffer { - private static final String CHARSET_UTF8 = "UTF-8"; - private static final Logger LOG = Logger.getLogger(ReadBuffer.class.getName()); - - /** - * Maximum buffer size which is supported by this implementation. - */ - static final int MAXIMUM_BUFFER_SIZE = 8000000; - - private byte[] mBufferData; - private int mBufferPosition; - private final RandomAccessFile mInputFile; - - ReadBuffer(RandomAccessFile inputFile) { - mInputFile = inputFile; - } - - /** - * Returns one signed byte from the read buffer. - * - * @return the byte value. - */ - public byte readByte() { - return mBufferData[mBufferPosition++]; - } - - /** - * Reads the given amount of bytes from the file into the read buffer and - * resets the internal buffer position. If - * the capacity of the read buffer is too small, a larger one is created - * automatically. - * - * @param length - * the amount of bytes to read from the file. - * @return true if the whole data was read successfully, false otherwise. - * @throws IOException - * if an error occurs while reading the file. - */ - public boolean readFromFile(int length) throws IOException { - // ensure that the read buffer is large enough - if (mBufferData == null || mBufferData.length < length) { - // ensure that the read buffer is not too large - if (length > MAXIMUM_BUFFER_SIZE) { - LOG.warning("invalid read length: " + length); - return false; - } - mBufferData = new byte[length]; - } - - mBufferPosition = 0; - - // reset the buffer position and read the data into the buffer - // bufferPosition = 0; - return mInputFile.read(mBufferData, 0, length) == length; - } - - /** - * Converts four bytes from the read buffer to a signed int. - *

- * The byte order is big-endian. - * - * @return the int value. - */ - public int readInt() { - int pos = mBufferPosition; - byte[] data = mBufferData; - mBufferPosition += 4; - - return data[pos] << 24 - | (data[pos + 1] & 0xff) << 16 - | (data[pos + 2] & 0xff) << 8 - | (data[pos + 3] & 0xff); - } - - /** - * Converts eight bytes from the read buffer to a signed long. - *

- * The byte order is big-endian. - * - * @return the long value. - */ - public long readLong() { - int pos = mBufferPosition; - byte[] data = mBufferData; - mBufferPosition += 8; - - return (data[pos] & 0xffL) << 56 - | (data[pos + 1] & 0xffL) << 48 - | (data[pos + 2] & 0xffL) << 40 - | (data[pos + 3] & 0xffL) << 32 - | (data[pos + 4] & 0xffL) << 24 - | (data[pos + 5] & 0xffL) << 16 - | (data[pos + 6] & 0xffL) << 8 - | (data[pos + 7] & 0xffL); - - } - - /** - * Converts two bytes from the read buffer to a signed int. - *

- * The byte order is big-endian. - * - * @return the int value. - */ - public int readShort() { - mBufferPosition += 2; - return mBufferData[mBufferPosition - 2] << 8 | (mBufferData[mBufferPosition - 1] & 0xff); - } - - /** - * Converts a variable amount of bytes from the read buffer to a signed int. - *

- * The first bit is for continuation info, the other six (last byte) or - * seven (all other bytes) bits are for data. The second bit in the last - * byte indicates the sign of the number. - * - * @return the value. - */ - public int readSignedInt() { - int pos = mBufferPosition; - byte[] data = mBufferData; - int flag; - - if ((data[pos] & 0x80) == 0) { - mBufferPosition += 1; - flag = ((data[pos] & 0x40) >> 6); - - return ((data[pos] & 0x3f) ^ -flag) + flag; - } - - if ((data[pos + 1] & 0x80) == 0) { - mBufferPosition += 2; - flag = ((data[pos + 1] & 0x40) >> 6); - - return (((data[pos] & 0x7f) - | (data[pos + 1] & 0x3f) << 7) ^ -flag) + flag; - - } - - if ((data[pos + 2] & 0x80) == 0) { - mBufferPosition += 3; - flag = ((data[pos + 2] & 0x40) >> 6); - - return (((data[pos] & 0x7f) - | (data[pos + 1] & 0x7f) << 7 - | (data[pos + 2] & 0x3f) << 14) ^ -flag) + flag; - - } - - if ((data[pos + 3] & 0x80) == 0) { - mBufferPosition += 4; - flag = ((data[pos + 3] & 0x40) >> 6); - - return (((data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x3f) << 21)) ^ -flag) + flag; - } - - mBufferPosition += 5; - flag = ((data[pos + 4] & 0x40) >> 6); - - return ((((data[pos] & 0x7f) - | (data[pos + 1] & 0x7f) << 7 - | (data[pos + 2] & 0x7f) << 14 - | (data[pos + 3] & 0x7f) << 21 - | (data[pos + 4] & 0x3f) << 28)) ^ -flag) + flag; - - } - - /** - * Converts a variable amount of bytes from the read buffer to a signed int - * array. - *

- * The first bit is for continuation info, the other six (last byte) or - * seven (all other bytes) bits are for data. The second bit in the last - * byte indicates the sign of the number. - * - * @param values - * result values - * @param length - * number of values to read - */ - public void readSignedInt(int[] values, int length) { - int pos = mBufferPosition; - byte[] data = mBufferData; - int flag; - - for (int i = 0; i < length; i++) { - - if ((data[pos] & 0x80) == 0) { - - flag = ((data[pos] & 0x40) >> 6); - - values[i] = ((data[pos] & 0x3f) ^ -flag) + flag; - pos += 1; - - } else if ((data[pos + 1] & 0x80) == 0) { - - flag = ((data[pos + 1] & 0x40) >> 6); - - values[i] = (((data[pos] & 0x7f) - | ((data[pos + 1] & 0x3f) << 7)) ^ -flag) + flag; - pos += 2; - - } else if ((data[pos + 2] & 0x80) == 0) { - - flag = ((data[pos + 2] & 0x40) >> 6); - - values[i] = (((data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x3f) << 14)) ^ -flag) + flag; - pos += 3; - - } else if ((data[pos + 3] & 0x80) == 0) { - - flag = ((data[pos + 3] & 0x40) >> 6); - - values[i] = (((data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x3f) << 21)) ^ -flag) + flag; - - pos += 4; - } else { - flag = ((data[pos + 4] & 0x40) >> 6); - - values[i] = ((((data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x7f) << 21) - | ((data[pos + 4] & 0x3f) << 28))) ^ -flag) + flag; - - pos += 5; - } - } - - mBufferPosition = pos; - } - - /** - * Converts a variable amount of bytes from the read buffer to an unsigned - * int. - *

- * The first bit is for continuation info, the other seven bits are for - * data. - * - * @return the int value. - */ - public int readUnsignedInt() { - int pos = mBufferPosition; - byte[] data = mBufferData; - - if ((data[pos] & 0x80) == 0) { - mBufferPosition += 1; - return (data[pos] & 0x7f); - } - - if ((data[pos + 1] & 0x80) == 0) { - mBufferPosition += 2; - return (data[pos] & 0x7f) - | (data[pos + 1] & 0x7f) << 7; - } - - if ((data[pos + 2] & 0x80) == 0) { - mBufferPosition += 3; - return (data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14); - } - - if ((data[pos + 3] & 0x80) == 0) { - mBufferPosition += 4; - return (data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x7f) << 21); - } - - mBufferPosition += 5; - return (data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x7f) << 21) - | ((data[pos + 4] & 0x7f) << 28); - } - - /** - * Decodes a variable amount of bytes from the read buffer to a string. - * - * @return the UTF-8 decoded string (may be null). - */ - public String readUTF8EncodedString() { - return readUTF8EncodedString(readUnsignedInt()); - } - - /** - * @return ... - */ - public int getPositionAndSkip() { - int pos = mBufferPosition; - int length = readUnsignedInt(); - skipBytes(length); - return pos; - } - - /** - * Decodes the given amount of bytes from the read buffer to a string. - * - * @param stringLength - * the length of the string in bytes. - * @return the UTF-8 decoded string (may be null). - */ - public String readUTF8EncodedString(int stringLength) { - if (stringLength > 0 && mBufferPosition + stringLength <= mBufferData.length) { - mBufferPosition += stringLength; - try { - return new String(mBufferData, mBufferPosition - stringLength, stringLength, - CHARSET_UTF8); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException(e); - } - } - LOG.warning("invalid string length: " + stringLength); - return null; - } - - /** - * Decodes a variable amount of bytes from the read buffer to a string. - * - * @param position - * buffer offset position of string - * @return the UTF-8 decoded string (may be null). - */ - public String readUTF8EncodedStringAt(int position) { - int curPosition = mBufferPosition; - mBufferPosition = position; - String result = readUTF8EncodedString(readUnsignedInt()); - mBufferPosition = curPosition; - return result; - } - - /** - * @return the current buffer position. - */ - int getBufferPosition() { - return mBufferPosition; - } - - /** - * @return the current size of the read buffer. - */ - int getBufferSize() { - return mBufferData.length; - } - - /** - * Sets the buffer position to the given offset. - * - * @param bufferPosition - * the buffer position. - */ - void setBufferPosition(int bufferPosition) { - mBufferPosition = bufferPosition; - } - - /** - * Skips the given number of bytes in the read buffer. - * - * @param bytes - * the number of bytes to skip. - */ - void skipBytes(int bytes) { - mBufferPosition += bytes; - } - - boolean readTags(TagSet tags, Tag[] wayTags, byte numberOfTags) { - tags.clear(); - - int maxTag = wayTags.length; - - for (byte i = 0; i < numberOfTags; i++) { - int tagId = readUnsignedInt(); - if (tagId < 0 || tagId >= maxTag) { - LOG.warning("invalid tag ID: " + tagId); - return true; - } - tags.add(wayTags[tagId]); - } - return true; - } - - private static final int WAY_NUMBER_OF_TAGS_BITMASK = 0x0f; - int lastTagPosition; - - int skipWays(int queryTileBitmask, int elements) { - int pos = mBufferPosition; - byte[] data = mBufferData; - int cnt = elements; - int skip; - - lastTagPosition = -1; - - while (cnt > 0) { - // read way size (unsigned int) - if ((data[pos] & 0x80) == 0) { - skip = (data[pos] & 0x7f); - pos += 1; - } else if ((data[pos + 1] & 0x80) == 0) { - skip = (data[pos] & 0x7f) - | (data[pos + 1] & 0x7f) << 7; - pos += 2; - } else if ((data[pos + 2] & 0x80) == 0) { - skip = (data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14); - pos += 3; - } else if ((data[pos + 3] & 0x80) == 0) { - skip = (data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x7f) << 21); - pos += 4; - } else { - skip = (data[pos] & 0x7f) - | ((data[pos + 1] & 0x7f) << 7) - | ((data[pos + 2] & 0x7f) << 14) - | ((data[pos + 3] & 0x7f) << 21) - | ((data[pos + 4] & 0x7f) << 28); - pos += 5; - } - // invalid way size - if (skip < 0) { - mBufferPosition = pos; - return -1; - } - - // check if way matches queryTileBitmask - if ((((data[pos] << 8) | (data[pos + 1] & 0xff)) & queryTileBitmask) == 0) { - - // remember last tags position - if ((data[pos + 2] & WAY_NUMBER_OF_TAGS_BITMASK) != 0) - lastTagPosition = pos + 2; - - pos += skip; - cnt--; - } else { - pos += 2; - break; - } - } - mBufferPosition = pos; - return cnt; - } + private static final String CHARSET_UTF8 = "UTF-8"; + private static final Logger LOG = Logger.getLogger(ReadBuffer.class.getName()); + + /** + * Maximum buffer size which is supported by this implementation. + */ + static final int MAXIMUM_BUFFER_SIZE = 8000000; + + private byte[] mBufferData; + private int mBufferPosition; + private final RandomAccessFile mInputFile; + + ReadBuffer(RandomAccessFile inputFile) { + mInputFile = inputFile; + } + + /** + * Returns one signed byte from the read buffer. + * + * @return the byte value. + */ + public byte readByte() { + return mBufferData[mBufferPosition++]; + } + + /** + * Reads the given amount of bytes from the file into the read buffer and + * resets the internal buffer position. If + * the capacity of the read buffer is too small, a larger one is created + * automatically. + * + * @param length the amount of bytes to read from the file. + * @return true if the whole data was read successfully, false otherwise. + * @throws IOException if an error occurs while reading the file. + */ + public boolean readFromFile(int length) throws IOException { + // ensure that the read buffer is large enough + if (mBufferData == null || mBufferData.length < length) { + // ensure that the read buffer is not too large + if (length > MAXIMUM_BUFFER_SIZE) { + LOG.warning("invalid read length: " + length); + return false; + } + mBufferData = new byte[length]; + } + + mBufferPosition = 0; + + // reset the buffer position and read the data into the buffer + // bufferPosition = 0; + return mInputFile.read(mBufferData, 0, length) == length; + } + + /** + * Converts four bytes from the read buffer to a signed int. + *

+ * The byte order is big-endian. + * + * @return the int value. + */ + public int readInt() { + int pos = mBufferPosition; + byte[] data = mBufferData; + mBufferPosition += 4; + + return data[pos] << 24 + | (data[pos + 1] & 0xff) << 16 + | (data[pos + 2] & 0xff) << 8 + | (data[pos + 3] & 0xff); + } + + /** + * Converts eight bytes from the read buffer to a signed long. + *

+ * The byte order is big-endian. + * + * @return the long value. + */ + public long readLong() { + int pos = mBufferPosition; + byte[] data = mBufferData; + mBufferPosition += 8; + + return (data[pos] & 0xffL) << 56 + | (data[pos + 1] & 0xffL) << 48 + | (data[pos + 2] & 0xffL) << 40 + | (data[pos + 3] & 0xffL) << 32 + | (data[pos + 4] & 0xffL) << 24 + | (data[pos + 5] & 0xffL) << 16 + | (data[pos + 6] & 0xffL) << 8 + | (data[pos + 7] & 0xffL); + + } + + /** + * Converts two bytes from the read buffer to a signed int. + *

+ * The byte order is big-endian. + * + * @return the int value. + */ + public int readShort() { + mBufferPosition += 2; + return mBufferData[mBufferPosition - 2] << 8 | (mBufferData[mBufferPosition - 1] & 0xff); + } + + /** + * Converts a variable amount of bytes from the read buffer to a signed int. + *

+ * The first bit is for continuation info, the other six (last byte) or + * seven (all other bytes) bits are for data. The second bit in the last + * byte indicates the sign of the number. + * + * @return the value. + */ + public int readSignedInt() { + int pos = mBufferPosition; + byte[] data = mBufferData; + int flag; + + if ((data[pos] & 0x80) == 0) { + mBufferPosition += 1; + flag = ((data[pos] & 0x40) >> 6); + + return ((data[pos] & 0x3f) ^ -flag) + flag; + } + + if ((data[pos + 1] & 0x80) == 0) { + mBufferPosition += 2; + flag = ((data[pos + 1] & 0x40) >> 6); + + return (((data[pos] & 0x7f) + | (data[pos + 1] & 0x3f) << 7) ^ -flag) + flag; + + } + + if ((data[pos + 2] & 0x80) == 0) { + mBufferPosition += 3; + flag = ((data[pos + 2] & 0x40) >> 6); + + return (((data[pos] & 0x7f) + | (data[pos + 1] & 0x7f) << 7 + | (data[pos + 2] & 0x3f) << 14) ^ -flag) + flag; + + } + + if ((data[pos + 3] & 0x80) == 0) { + mBufferPosition += 4; + flag = ((data[pos + 3] & 0x40) >> 6); + + return (((data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x3f) << 21)) ^ -flag) + flag; + } + + mBufferPosition += 5; + flag = ((data[pos + 4] & 0x40) >> 6); + + return ((((data[pos] & 0x7f) + | (data[pos + 1] & 0x7f) << 7 + | (data[pos + 2] & 0x7f) << 14 + | (data[pos + 3] & 0x7f) << 21 + | (data[pos + 4] & 0x3f) << 28)) ^ -flag) + flag; + + } + + /** + * Converts a variable amount of bytes from the read buffer to a signed int + * array. + *

+ * The first bit is for continuation info, the other six (last byte) or + * seven (all other bytes) bits are for data. The second bit in the last + * byte indicates the sign of the number. + * + * @param values result values + * @param length number of values to read + */ + public void readSignedInt(int[] values, int length) { + int pos = mBufferPosition; + byte[] data = mBufferData; + int flag; + + for (int i = 0; i < length; i++) { + + if ((data[pos] & 0x80) == 0) { + + flag = ((data[pos] & 0x40) >> 6); + + values[i] = ((data[pos] & 0x3f) ^ -flag) + flag; + pos += 1; + + } else if ((data[pos + 1] & 0x80) == 0) { + + flag = ((data[pos + 1] & 0x40) >> 6); + + values[i] = (((data[pos] & 0x7f) + | ((data[pos + 1] & 0x3f) << 7)) ^ -flag) + flag; + pos += 2; + + } else if ((data[pos + 2] & 0x80) == 0) { + + flag = ((data[pos + 2] & 0x40) >> 6); + + values[i] = (((data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x3f) << 14)) ^ -flag) + flag; + pos += 3; + + } else if ((data[pos + 3] & 0x80) == 0) { + + flag = ((data[pos + 3] & 0x40) >> 6); + + values[i] = (((data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x3f) << 21)) ^ -flag) + flag; + + pos += 4; + } else { + flag = ((data[pos + 4] & 0x40) >> 6); + + values[i] = ((((data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x7f) << 21) + | ((data[pos + 4] & 0x3f) << 28))) ^ -flag) + flag; + + pos += 5; + } + } + + mBufferPosition = pos; + } + + /** + * Converts a variable amount of bytes from the read buffer to an unsigned + * int. + *

+ * The first bit is for continuation info, the other seven bits are for + * data. + * + * @return the int value. + */ + public int readUnsignedInt() { + int pos = mBufferPosition; + byte[] data = mBufferData; + + if ((data[pos] & 0x80) == 0) { + mBufferPosition += 1; + return (data[pos] & 0x7f); + } + + if ((data[pos + 1] & 0x80) == 0) { + mBufferPosition += 2; + return (data[pos] & 0x7f) + | (data[pos + 1] & 0x7f) << 7; + } + + if ((data[pos + 2] & 0x80) == 0) { + mBufferPosition += 3; + return (data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14); + } + + if ((data[pos + 3] & 0x80) == 0) { + mBufferPosition += 4; + return (data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x7f) << 21); + } + + mBufferPosition += 5; + return (data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x7f) << 21) + | ((data[pos + 4] & 0x7f) << 28); + } + + /** + * Decodes a variable amount of bytes from the read buffer to a string. + * + * @return the UTF-8 decoded string (may be null). + */ + public String readUTF8EncodedString() { + return readUTF8EncodedString(readUnsignedInt()); + } + + /** + * @return ... + */ + public int getPositionAndSkip() { + int pos = mBufferPosition; + int length = readUnsignedInt(); + skipBytes(length); + return pos; + } + + /** + * Decodes the given amount of bytes from the read buffer to a string. + * + * @param stringLength the length of the string in bytes. + * @return the UTF-8 decoded string (may be null). + */ + public String readUTF8EncodedString(int stringLength) { + if (stringLength > 0 && mBufferPosition + stringLength <= mBufferData.length) { + mBufferPosition += stringLength; + try { + return new String(mBufferData, mBufferPosition - stringLength, stringLength, + CHARSET_UTF8); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } + LOG.warning("invalid string length: " + stringLength); + return null; + } + + /** + * Decodes a variable amount of bytes from the read buffer to a string. + * + * @param position buffer offset position of string + * @return the UTF-8 decoded string (may be null). + */ + public String readUTF8EncodedStringAt(int position) { + int curPosition = mBufferPosition; + mBufferPosition = position; + String result = readUTF8EncodedString(readUnsignedInt()); + mBufferPosition = curPosition; + return result; + } + + /** + * @return the current buffer position. + */ + int getBufferPosition() { + return mBufferPosition; + } + + /** + * @return the current size of the read buffer. + */ + int getBufferSize() { + return mBufferData.length; + } + + /** + * Sets the buffer position to the given offset. + * + * @param bufferPosition the buffer position. + */ + void setBufferPosition(int bufferPosition) { + mBufferPosition = bufferPosition; + } + + /** + * Skips the given number of bytes in the read buffer. + * + * @param bytes the number of bytes to skip. + */ + void skipBytes(int bytes) { + mBufferPosition += bytes; + } + + boolean readTags(TagSet tags, Tag[] wayTags, byte numberOfTags) { + tags.clear(); + + int maxTag = wayTags.length; + + for (byte i = 0; i < numberOfTags; i++) { + int tagId = readUnsignedInt(); + if (tagId < 0 || tagId >= maxTag) { + LOG.warning("invalid tag ID: " + tagId); + return true; + } + tags.add(wayTags[tagId]); + } + return true; + } + + private static final int WAY_NUMBER_OF_TAGS_BITMASK = 0x0f; + int lastTagPosition; + + int skipWays(int queryTileBitmask, int elements) { + int pos = mBufferPosition; + byte[] data = mBufferData; + int cnt = elements; + int skip; + + lastTagPosition = -1; + + while (cnt > 0) { + // read way size (unsigned int) + if ((data[pos] & 0x80) == 0) { + skip = (data[pos] & 0x7f); + pos += 1; + } else if ((data[pos + 1] & 0x80) == 0) { + skip = (data[pos] & 0x7f) + | (data[pos + 1] & 0x7f) << 7; + pos += 2; + } else if ((data[pos + 2] & 0x80) == 0) { + skip = (data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14); + pos += 3; + } else if ((data[pos + 3] & 0x80) == 0) { + skip = (data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x7f) << 21); + pos += 4; + } else { + skip = (data[pos] & 0x7f) + | ((data[pos + 1] & 0x7f) << 7) + | ((data[pos + 2] & 0x7f) << 14) + | ((data[pos + 3] & 0x7f) << 21) + | ((data[pos + 4] & 0x7f) << 28); + pos += 5; + } + // invalid way size + if (skip < 0) { + mBufferPosition = pos; + return -1; + } + + // check if way matches queryTileBitmask + if ((((data[pos] << 8) | (data[pos + 1] & 0xff)) & queryTileBitmask) == 0) { + + // remember last tags position + if ((data[pos + 2] & WAY_NUMBER_OF_TAGS_BITMASK) != 0) + lastTagPosition = pos + 2; + + pos += skip; + cnt--; + } else { + pos += 2; + break; + } + } + mBufferPosition = pos; + return cnt; + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileHeader.java b/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileHeader.java index f27a52fe..9dddd71f 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileHeader.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileHeader.java @@ -16,246 +16,241 @@ */ package org.oscim.tiling.source.mapfile.header; -import java.io.IOException; - import org.oscim.tiling.TileSource.OpenResult; import org.oscim.tiling.source.mapfile.ReadBuffer; +import java.io.IOException; + /** * Reads and validates the header data from a binary map file. */ public class MapFileHeader { - /** - * Maximum valid base zoom level of a sub-file. - */ - private static final int BASE_ZOOM_LEVEL_MAX = 20; + /** + * Maximum valid base zoom level of a sub-file. + */ + private static final int BASE_ZOOM_LEVEL_MAX = 20; - /** - * Minimum size of the file header in bytes. - */ - private static final int HEADER_SIZE_MIN = 70; + /** + * Minimum size of the file header in bytes. + */ + private static final int HEADER_SIZE_MIN = 70; - /** - * Length of the debug signature at the beginning of the index. - */ - private static final byte SIGNATURE_LENGTH_INDEX = 16; + /** + * Length of the debug signature at the beginning of the index. + */ + private static final byte SIGNATURE_LENGTH_INDEX = 16; - /** - * A single whitespace character. - */ - private static final char SPACE = ' '; + /** + * A single whitespace character. + */ + private static final char SPACE = ' '; - private MapFileInfo mapFileInfo; - private SubFileParameter[] subFileParameters; - private byte zoomLevelMaximum; - private byte zoomLevelMinimum; + private MapFileInfo mapFileInfo; + private SubFileParameter[] subFileParameters; + private byte zoomLevelMaximum; + private byte zoomLevelMinimum; - /** - * @return a MapFileInfo containing the header data. - */ - public MapFileInfo getMapFileInfo() { - return this.mapFileInfo; - } + /** + * @return a MapFileInfo containing the header data. + */ + public MapFileInfo getMapFileInfo() { + return this.mapFileInfo; + } - /** - * @param zoomLevel - * the originally requested zoom level. - * @return the closest possible zoom level which is covered by a sub-file. - */ - public byte getQueryZoomLevel(byte zoomLevel) { - if (zoomLevel > this.zoomLevelMaximum) { - return this.zoomLevelMaximum; - } else if (zoomLevel < this.zoomLevelMinimum) { - return this.zoomLevelMinimum; - } - return zoomLevel; - } + /** + * @param zoomLevel the originally requested zoom level. + * @return the closest possible zoom level which is covered by a sub-file. + */ + public byte getQueryZoomLevel(byte zoomLevel) { + if (zoomLevel > this.zoomLevelMaximum) { + return this.zoomLevelMaximum; + } else if (zoomLevel < this.zoomLevelMinimum) { + return this.zoomLevelMinimum; + } + return zoomLevel; + } - /** - * @param queryZoomLevel - * the zoom level for which the sub-file parameters are needed. - * @return the sub-file parameters for the given zoom level. - */ - public SubFileParameter getSubFileParameter(int queryZoomLevel) { - return this.subFileParameters[queryZoomLevel]; - } + /** + * @param queryZoomLevel the zoom level for which the sub-file parameters are needed. + * @return the sub-file parameters for the given zoom level. + */ + public SubFileParameter getSubFileParameter(int queryZoomLevel) { + return this.subFileParameters[queryZoomLevel]; + } - /** - * Reads and validates the header block from the map file. - * - * @param readBuffer - * the ReadBuffer for the file data. - * @param fileSize - * the size of the map file in bytes. - * @return a FileOpenResult containing an error message in case of a - * failure. - * @throws IOException - * if an error occurs while reading the file. - */ - public OpenResult readHeader(ReadBuffer readBuffer, long fileSize) throws IOException { - OpenResult openResult = RequiredFields.readMagicByte(readBuffer); - if (!openResult.isSuccess()) { - return openResult; - } + /** + * Reads and validates the header block from the map file. + * + * @param readBuffer the ReadBuffer for the file data. + * @param fileSize the size of the map file in bytes. + * @return a FileOpenResult containing an error message in case of a + * failure. + * @throws IOException if an error occurs while reading the file. + */ + public OpenResult readHeader(ReadBuffer readBuffer, long fileSize) throws IOException { + OpenResult openResult = RequiredFields.readMagicByte(readBuffer); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readRemainingHeader(readBuffer); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readRemainingHeader(readBuffer); + if (!openResult.isSuccess()) { + return openResult; + } - MapFileInfoBuilder mapFileInfoBuilder = new MapFileInfoBuilder(); + MapFileInfoBuilder mapFileInfoBuilder = new MapFileInfoBuilder(); - openResult = RequiredFields.readFileVersion(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readFileVersion(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readFileSize(readBuffer, fileSize, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readFileSize(readBuffer, fileSize, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readMapDate(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readMapDate(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readBoundingBox(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readBoundingBox(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readTilePixelSize(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readTilePixelSize(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readProjectionName(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readProjectionName(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = OptionalFields.readOptionalFields(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = OptionalFields.readOptionalFields(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readPoiTags(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readPoiTags(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = RequiredFields.readWayTags(readBuffer, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = RequiredFields.readWayTags(readBuffer, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = readSubFileParameters(readBuffer, fileSize, mapFileInfoBuilder); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = readSubFileParameters(readBuffer, fileSize, mapFileInfoBuilder); + if (!openResult.isSuccess()) { + return openResult; + } - this.mapFileInfo = mapFileInfoBuilder.build(); + this.mapFileInfo = mapFileInfoBuilder.build(); - return OpenResult.SUCCESS; - } + return OpenResult.SUCCESS; + } - private OpenResult readSubFileParameters(ReadBuffer readBuffer, long fileSize, - MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the number of sub-files (1 byte) - byte numberOfSubFiles = readBuffer.readByte(); - if (numberOfSubFiles < 1) { - return new OpenResult("invalid number of sub-files: " + numberOfSubFiles); - } - mapFileInfoBuilder.numberOfSubFiles = numberOfSubFiles; + private OpenResult readSubFileParameters(ReadBuffer readBuffer, long fileSize, + MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the number of sub-files (1 byte) + byte numberOfSubFiles = readBuffer.readByte(); + if (numberOfSubFiles < 1) { + return new OpenResult("invalid number of sub-files: " + numberOfSubFiles); + } + mapFileInfoBuilder.numberOfSubFiles = numberOfSubFiles; - SubFileParameter[] tempSubFileParameters = new SubFileParameter[numberOfSubFiles]; - this.zoomLevelMinimum = Byte.MAX_VALUE; - this.zoomLevelMaximum = Byte.MIN_VALUE; + SubFileParameter[] tempSubFileParameters = new SubFileParameter[numberOfSubFiles]; + this.zoomLevelMinimum = Byte.MAX_VALUE; + this.zoomLevelMaximum = Byte.MIN_VALUE; - // get and check the information for each sub-file - for (byte currentSubFile = 0; currentSubFile < numberOfSubFiles; ++currentSubFile) { - SubFileParameterBuilder subFileParameterBuilder = new SubFileParameterBuilder(); + // get and check the information for each sub-file + for (byte currentSubFile = 0; currentSubFile < numberOfSubFiles; ++currentSubFile) { + SubFileParameterBuilder subFileParameterBuilder = new SubFileParameterBuilder(); - // get and check the base zoom level (1 byte) - byte baseZoomLevel = readBuffer.readByte(); - if (baseZoomLevel < 0 || baseZoomLevel > BASE_ZOOM_LEVEL_MAX) { - return new OpenResult("invalid base zooom level: " + baseZoomLevel); - } - subFileParameterBuilder.baseZoomLevel = baseZoomLevel; + // get and check the base zoom level (1 byte) + byte baseZoomLevel = readBuffer.readByte(); + if (baseZoomLevel < 0 || baseZoomLevel > BASE_ZOOM_LEVEL_MAX) { + return new OpenResult("invalid base zooom level: " + baseZoomLevel); + } + subFileParameterBuilder.baseZoomLevel = baseZoomLevel; - // get and check the minimum zoom level (1 byte) - byte zoomLevelMin = readBuffer.readByte(); - if (zoomLevelMin < 0 || zoomLevelMin > 22) { - return new OpenResult("invalid minimum zoom level: " + zoomLevelMin); - } - subFileParameterBuilder.zoomLevelMin = zoomLevelMin; + // get and check the minimum zoom level (1 byte) + byte zoomLevelMin = readBuffer.readByte(); + if (zoomLevelMin < 0 || zoomLevelMin > 22) { + return new OpenResult("invalid minimum zoom level: " + zoomLevelMin); + } + subFileParameterBuilder.zoomLevelMin = zoomLevelMin; - // get and check the maximum zoom level (1 byte) - byte zoomLevelMax = readBuffer.readByte(); - if (zoomLevelMax < 0 || zoomLevelMax > 22) { - return new OpenResult("invalid maximum zoom level: " + zoomLevelMax); - } - subFileParameterBuilder.zoomLevelMax = zoomLevelMax; + // get and check the maximum zoom level (1 byte) + byte zoomLevelMax = readBuffer.readByte(); + if (zoomLevelMax < 0 || zoomLevelMax > 22) { + return new OpenResult("invalid maximum zoom level: " + zoomLevelMax); + } + subFileParameterBuilder.zoomLevelMax = zoomLevelMax; - // check for valid zoom level range - if (zoomLevelMin > zoomLevelMax) { - return new OpenResult("invalid zoom level range: " + zoomLevelMin + SPACE - + zoomLevelMax); - } + // check for valid zoom level range + if (zoomLevelMin > zoomLevelMax) { + return new OpenResult("invalid zoom level range: " + zoomLevelMin + SPACE + + zoomLevelMax); + } - // get and check the start address of the sub-file (8 bytes) - long startAddress = readBuffer.readLong(); - if (startAddress < HEADER_SIZE_MIN || startAddress >= fileSize) { - return new OpenResult("invalid start address: " + startAddress); - } - subFileParameterBuilder.startAddress = startAddress; + // get and check the start address of the sub-file (8 bytes) + long startAddress = readBuffer.readLong(); + if (startAddress < HEADER_SIZE_MIN || startAddress >= fileSize) { + return new OpenResult("invalid start address: " + startAddress); + } + subFileParameterBuilder.startAddress = startAddress; - long indexStartAddress = startAddress; - if (mapFileInfoBuilder.optionalFields.isDebugFile) { - // the sub-file has an index signature before the index - indexStartAddress += SIGNATURE_LENGTH_INDEX; - } - subFileParameterBuilder.indexStartAddress = indexStartAddress; + long indexStartAddress = startAddress; + if (mapFileInfoBuilder.optionalFields.isDebugFile) { + // the sub-file has an index signature before the index + indexStartAddress += SIGNATURE_LENGTH_INDEX; + } + subFileParameterBuilder.indexStartAddress = indexStartAddress; - // get and check the size of the sub-file (8 bytes) - long subFileSize = readBuffer.readLong(); - if (subFileSize < 1) { - return new OpenResult("invalid sub-file size: " + subFileSize); - } - subFileParameterBuilder.subFileSize = subFileSize; + // get and check the size of the sub-file (8 bytes) + long subFileSize = readBuffer.readLong(); + if (subFileSize < 1) { + return new OpenResult("invalid sub-file size: " + subFileSize); + } + subFileParameterBuilder.subFileSize = subFileSize; - subFileParameterBuilder.boundingBox = mapFileInfoBuilder.boundingBox; + subFileParameterBuilder.boundingBox = mapFileInfoBuilder.boundingBox; - // add the current sub-file to the list of sub-files - tempSubFileParameters[currentSubFile] = subFileParameterBuilder.build(); + // add the current sub-file to the list of sub-files + tempSubFileParameters[currentSubFile] = subFileParameterBuilder.build(); - updateZoomLevelInformation(tempSubFileParameters[currentSubFile]); - } + updateZoomLevelInformation(tempSubFileParameters[currentSubFile]); + } - mapFileInfoBuilder.zoomLevel = new int[numberOfSubFiles]; + mapFileInfoBuilder.zoomLevel = new int[numberOfSubFiles]; - // create and fill the lookup table for the sub-files - this.subFileParameters = new SubFileParameter[this.zoomLevelMaximum + 1]; - for (int currentMapFile = 0; currentMapFile < numberOfSubFiles; ++currentMapFile) { - SubFileParameter subFileParameter = tempSubFileParameters[currentMapFile]; + // create and fill the lookup table for the sub-files + this.subFileParameters = new SubFileParameter[this.zoomLevelMaximum + 1]; + for (int currentMapFile = 0; currentMapFile < numberOfSubFiles; ++currentMapFile) { + SubFileParameter subFileParameter = tempSubFileParameters[currentMapFile]; - mapFileInfoBuilder.zoomLevel[currentMapFile] = subFileParameter.baseZoomLevel; + mapFileInfoBuilder.zoomLevel[currentMapFile] = subFileParameter.baseZoomLevel; - for (byte zoomLevel = subFileParameter.zoomLevelMin; zoomLevel <= subFileParameter.zoomLevelMax; ++zoomLevel) { - this.subFileParameters[zoomLevel] = subFileParameter; - } - } - return OpenResult.SUCCESS; - } + for (byte zoomLevel = subFileParameter.zoomLevelMin; zoomLevel <= subFileParameter.zoomLevelMax; ++zoomLevel) { + this.subFileParameters[zoomLevel] = subFileParameter; + } + } + return OpenResult.SUCCESS; + } - private void updateZoomLevelInformation(SubFileParameter subFileParameter) { - // update the global minimum and maximum zoom level information - if (this.zoomLevelMinimum > subFileParameter.zoomLevelMin) { - this.zoomLevelMinimum = subFileParameter.zoomLevelMin; - } - if (this.zoomLevelMaximum < subFileParameter.zoomLevelMax) { - this.zoomLevelMaximum = subFileParameter.zoomLevelMax; - } - } + private void updateZoomLevelInformation(SubFileParameter subFileParameter) { + // update the global minimum and maximum zoom level information + if (this.zoomLevelMinimum > subFileParameter.zoomLevelMin) { + this.zoomLevelMinimum = subFileParameter.zoomLevelMin; + } + if (this.zoomLevelMaximum < subFileParameter.zoomLevelMax) { + this.zoomLevelMaximum = subFileParameter.zoomLevelMax; + } + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfo.java b/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfo.java index 0ba3649d..0239b4a7 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfo.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfo.java @@ -21,54 +21,53 @@ import org.oscim.core.Tag; /** * Contains the immutable metadata of a map file. - * */ public class MapFileInfo extends org.oscim.tiling.source.mapfile.MapInfo { - /** - * True if the map file includes debug information, false otherwise. - */ - public final boolean debugFile; + /** + * True if the map file includes debug information, false otherwise. + */ + public final boolean debugFile; - /** - * The number of sub-files in the map file. - */ - public final byte numberOfSubFiles; + /** + * The number of sub-files in the map file. + */ + public final byte numberOfSubFiles; - /** - * The POI tags. - */ - public final Tag[] poiTags; + /** + * The POI tags. + */ + public final Tag[] poiTags; - /** - * The way tags. - */ - public final Tag[] wayTags; + /** + * The way tags. + */ + public final Tag[] wayTags; - /** - * The size of the tiles in pixels. - */ - public final int tilePixelSize; + /** + * The size of the tiles in pixels. + */ + public final int tilePixelSize; - MapFileInfo(MapFileInfoBuilder mapFileInfoBuilder) { - super(mapFileInfoBuilder.boundingBox, - mapFileInfoBuilder.optionalFields.startZoomLevel, - mapFileInfoBuilder.optionalFields.startPosition, - mapFileInfoBuilder.projectionName, - mapFileInfoBuilder.mapDate, - mapFileInfoBuilder.fileSize, - mapFileInfoBuilder.fileVersion, - mapFileInfoBuilder.optionalFields.languagesPreference, - mapFileInfoBuilder.optionalFields.comment, - mapFileInfoBuilder.optionalFields.createdBy, - mapFileInfoBuilder.zoomLevel); + MapFileInfo(MapFileInfoBuilder mapFileInfoBuilder) { + super(mapFileInfoBuilder.boundingBox, + mapFileInfoBuilder.optionalFields.startZoomLevel, + mapFileInfoBuilder.optionalFields.startPosition, + mapFileInfoBuilder.projectionName, + mapFileInfoBuilder.mapDate, + mapFileInfoBuilder.fileSize, + mapFileInfoBuilder.fileVersion, + mapFileInfoBuilder.optionalFields.languagesPreference, + mapFileInfoBuilder.optionalFields.comment, + mapFileInfoBuilder.optionalFields.createdBy, + mapFileInfoBuilder.zoomLevel); - debugFile = mapFileInfoBuilder.optionalFields.isDebugFile; + debugFile = mapFileInfoBuilder.optionalFields.isDebugFile; - numberOfSubFiles = mapFileInfoBuilder.numberOfSubFiles; - poiTags = mapFileInfoBuilder.poiTags; + numberOfSubFiles = mapFileInfoBuilder.numberOfSubFiles; + poiTags = mapFileInfoBuilder.poiTags; - tilePixelSize = mapFileInfoBuilder.tilePixelSize; - wayTags = mapFileInfoBuilder.wayTags; - } + tilePixelSize = mapFileInfoBuilder.tilePixelSize; + wayTags = mapFileInfoBuilder.wayTags; + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfoBuilder.java b/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfoBuilder.java index 967d2c87..40417a1a 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfoBuilder.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/MapFileInfoBuilder.java @@ -20,19 +20,19 @@ import org.oscim.core.BoundingBox; import org.oscim.core.Tag; class MapFileInfoBuilder { - BoundingBox boundingBox; - long fileSize; - int fileVersion; - long mapDate; - byte numberOfSubFiles; - OptionalFields optionalFields; - Tag[] poiTags; - String projectionName; - int tilePixelSize; - Tag[] wayTags; - int[] zoomLevel; + BoundingBox boundingBox; + long fileSize; + int fileVersion; + long mapDate; + byte numberOfSubFiles; + OptionalFields optionalFields; + Tag[] poiTags; + String projectionName; + int tilePixelSize; + Tag[] wayTags; + int[] zoomLevel; - MapFileInfo build() { - return new MapFileInfo(this); - } + MapFileInfo build() { + return new MapFileInfo(this); + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/OptionalFields.java b/vtm/src/org/oscim/tiling/source/mapfile/header/OptionalFields.java index b7130870..597d7dae 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/OptionalFields.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/OptionalFields.java @@ -22,139 +22,139 @@ import org.oscim.tiling.TileSource.OpenResult; import org.oscim.tiling.source.mapfile.ReadBuffer; final class OptionalFields { - /** - * Bitmask for the comment field in the file header. - */ - private static final int HEADER_BITMASK_COMMENT = 0x08; + /** + * Bitmask for the comment field in the file header. + */ + private static final int HEADER_BITMASK_COMMENT = 0x08; - /** - * Bitmask for the created by field in the file header. - */ - private static final int HEADER_BITMASK_CREATED_BY = 0x04; + /** + * Bitmask for the created by field in the file header. + */ + private static final int HEADER_BITMASK_CREATED_BY = 0x04; - /** - * Bitmask for the debug flag in the file header. - */ - private static final int HEADER_BITMASK_DEBUG = 0x80; + /** + * Bitmask for the debug flag in the file header. + */ + private static final int HEADER_BITMASK_DEBUG = 0x80; - /** - * Bitmask for the language(s) preference field in the file header. - */ - private static final int HEADER_BITMASK_LANGUAGES_PREFERENCE = 0x10; + /** + * Bitmask for the language(s) preference field in the file header. + */ + private static final int HEADER_BITMASK_LANGUAGES_PREFERENCE = 0x10; - /** - * Bitmask for the start position field in the file header. - */ - private static final int HEADER_BITMASK_START_POSITION = 0x40; + /** + * Bitmask for the start position field in the file header. + */ + private static final int HEADER_BITMASK_START_POSITION = 0x40; - /** - * Bitmask for the start zoom level field in the file header. - */ - private static final int HEADER_BITMASK_START_ZOOM_LEVEL = 0x20; + /** + * Bitmask for the start zoom level field in the file header. + */ + private static final int HEADER_BITMASK_START_ZOOM_LEVEL = 0x20; - /** - * Maximum valid start zoom level. - */ - private static final int START_ZOOM_LEVEL_MAX = 22; + /** + * Maximum valid start zoom level. + */ + private static final int START_ZOOM_LEVEL_MAX = 22; - static OpenResult readOptionalFields(ReadBuffer readBuffer, - MapFileInfoBuilder mapFileInfoBuilder) { - OptionalFields optionalFields = new OptionalFields(readBuffer.readByte()); - mapFileInfoBuilder.optionalFields = optionalFields; + static OpenResult readOptionalFields(ReadBuffer readBuffer, + MapFileInfoBuilder mapFileInfoBuilder) { + OptionalFields optionalFields = new OptionalFields(readBuffer.readByte()); + mapFileInfoBuilder.optionalFields = optionalFields; - OpenResult openResult = optionalFields.readOptionalFields(readBuffer); - if (!openResult.isSuccess()) { - return openResult; - } - return OpenResult.SUCCESS; - } + OpenResult openResult = optionalFields.readOptionalFields(readBuffer); + if (!openResult.isSuccess()) { + return openResult; + } + return OpenResult.SUCCESS; + } - String comment; - String createdBy; - final boolean hasComment; - final boolean hasCreatedBy; - final boolean hasLanguagesPreference; - final boolean hasStartPosition; - final boolean hasStartZoomLevel; - final boolean isDebugFile; - String languagesPreference; - GeoPoint startPosition; - Byte startZoomLevel; + String comment; + String createdBy; + final boolean hasComment; + final boolean hasCreatedBy; + final boolean hasLanguagesPreference; + final boolean hasStartPosition; + final boolean hasStartZoomLevel; + final boolean isDebugFile; + String languagesPreference; + GeoPoint startPosition; + Byte startZoomLevel; - private OptionalFields(byte flags) { - this.isDebugFile = (flags & HEADER_BITMASK_DEBUG) != 0; - this.hasStartPosition = (flags & HEADER_BITMASK_START_POSITION) != 0; - this.hasStartZoomLevel = (flags & HEADER_BITMASK_START_ZOOM_LEVEL) != 0; - this.hasLanguagesPreference = (flags & HEADER_BITMASK_LANGUAGES_PREFERENCE) != 0; - this.hasComment = (flags & HEADER_BITMASK_COMMENT) != 0; - this.hasCreatedBy = (flags & HEADER_BITMASK_CREATED_BY) != 0; - } + private OptionalFields(byte flags) { + this.isDebugFile = (flags & HEADER_BITMASK_DEBUG) != 0; + this.hasStartPosition = (flags & HEADER_BITMASK_START_POSITION) != 0; + this.hasStartZoomLevel = (flags & HEADER_BITMASK_START_ZOOM_LEVEL) != 0; + this.hasLanguagesPreference = (flags & HEADER_BITMASK_LANGUAGES_PREFERENCE) != 0; + this.hasComment = (flags & HEADER_BITMASK_COMMENT) != 0; + this.hasCreatedBy = (flags & HEADER_BITMASK_CREATED_BY) != 0; + } - private OpenResult readLanguagesPreference(ReadBuffer readBuffer) { - if (this.hasLanguagesPreference) { - this.languagesPreference = readBuffer.readUTF8EncodedString(); - } - return OpenResult.SUCCESS; - } + private OpenResult readLanguagesPreference(ReadBuffer readBuffer) { + if (this.hasLanguagesPreference) { + this.languagesPreference = readBuffer.readUTF8EncodedString(); + } + return OpenResult.SUCCESS; + } - private OpenResult readMapStartPosition(ReadBuffer readBuffer) { - if (this.hasStartPosition) { - // get and check the start position latitude (4 byte) - int mapStartLatitude = readBuffer.readInt(); - if (mapStartLatitude < RequiredFields.LATITUDE_MIN - || mapStartLatitude > RequiredFields.LATITUDE_MAX) { - return new OpenResult("invalid map start latitude: " + mapStartLatitude); - } + private OpenResult readMapStartPosition(ReadBuffer readBuffer) { + if (this.hasStartPosition) { + // get and check the start position latitude (4 byte) + int mapStartLatitude = readBuffer.readInt(); + if (mapStartLatitude < RequiredFields.LATITUDE_MIN + || mapStartLatitude > RequiredFields.LATITUDE_MAX) { + return new OpenResult("invalid map start latitude: " + mapStartLatitude); + } - // get and check the start position longitude (4 byte) - int mapStartLongitude = readBuffer.readInt(); - if (mapStartLongitude < RequiredFields.LONGITUDE_MIN - || mapStartLongitude > RequiredFields.LONGITUDE_MAX) { - return new OpenResult("invalid map start longitude: " + mapStartLongitude); - } + // get and check the start position longitude (4 byte) + int mapStartLongitude = readBuffer.readInt(); + if (mapStartLongitude < RequiredFields.LONGITUDE_MIN + || mapStartLongitude > RequiredFields.LONGITUDE_MAX) { + return new OpenResult("invalid map start longitude: " + mapStartLongitude); + } - this.startPosition = new GeoPoint(mapStartLatitude, mapStartLongitude); - } - return OpenResult.SUCCESS; - } + this.startPosition = new GeoPoint(mapStartLatitude, mapStartLongitude); + } + return OpenResult.SUCCESS; + } - private OpenResult readMapStartZoomLevel(ReadBuffer readBuffer) { - if (this.hasStartZoomLevel) { - // get and check the start zoom level (1 byte) - byte mapStartZoomLevel = readBuffer.readByte(); - if (mapStartZoomLevel < 0 || mapStartZoomLevel > START_ZOOM_LEVEL_MAX) { - return new OpenResult("invalid map start zoom level: " + mapStartZoomLevel); - } + private OpenResult readMapStartZoomLevel(ReadBuffer readBuffer) { + if (this.hasStartZoomLevel) { + // get and check the start zoom level (1 byte) + byte mapStartZoomLevel = readBuffer.readByte(); + if (mapStartZoomLevel < 0 || mapStartZoomLevel > START_ZOOM_LEVEL_MAX) { + return new OpenResult("invalid map start zoom level: " + mapStartZoomLevel); + } - this.startZoomLevel = Byte.valueOf(mapStartZoomLevel); - } - return OpenResult.SUCCESS; - } + this.startZoomLevel = Byte.valueOf(mapStartZoomLevel); + } + return OpenResult.SUCCESS; + } - private OpenResult readOptionalFields(ReadBuffer readBuffer) { - OpenResult openResult = readMapStartPosition(readBuffer); - if (!openResult.isSuccess()) { - return openResult; - } + private OpenResult readOptionalFields(ReadBuffer readBuffer) { + OpenResult openResult = readMapStartPosition(readBuffer); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = readMapStartZoomLevel(readBuffer); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = readMapStartZoomLevel(readBuffer); + if (!openResult.isSuccess()) { + return openResult; + } - openResult = readLanguagesPreference(readBuffer); - if (!openResult.isSuccess()) { - return openResult; - } + openResult = readLanguagesPreference(readBuffer); + if (!openResult.isSuccess()) { + return openResult; + } - if (this.hasComment) { - this.comment = readBuffer.readUTF8EncodedString(); - } + if (this.hasComment) { + this.comment = readBuffer.readUTF8EncodedString(); + } - if (this.hasCreatedBy) { - this.createdBy = readBuffer.readUTF8EncodedString(); - } + if (this.hasCreatedBy) { + this.createdBy = readBuffer.readUTF8EncodedString(); + } - return OpenResult.SUCCESS; - } + return OpenResult.SUCCESS; + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/RequiredFields.java b/vtm/src/org/oscim/tiling/source/mapfile/header/RequiredFields.java index e4a80bec..84a060cd 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/RequiredFields.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/RequiredFields.java @@ -17,230 +17,230 @@ */ package org.oscim.tiling.source.mapfile.header; -import java.io.IOException; - import org.oscim.core.BoundingBox; import org.oscim.core.Tag; import org.oscim.tiling.TileSource.OpenResult; import org.oscim.tiling.source.mapfile.ReadBuffer; +import java.io.IOException; + final class RequiredFields { - /** - * Magic byte at the beginning of a valid binary map file. - */ - private static final String BINARY_OSM_MAGIC_BYTE = "mapsforge binary OSM"; + /** + * Magic byte at the beginning of a valid binary map file. + */ + private static final String BINARY_OSM_MAGIC_BYTE = "mapsforge binary OSM"; - /** - * Maximum size of the file header in bytes. - */ - private static final int HEADER_SIZE_MAX = 1000000; + /** + * Maximum size of the file header in bytes. + */ + private static final int HEADER_SIZE_MAX = 1000000; - /** - * Minimum size of the file header in bytes. - */ - private static final int HEADER_SIZE_MIN = 70; + /** + * Minimum size of the file header in bytes. + */ + private static final int HEADER_SIZE_MIN = 70; - /** - * The name of the Mercator projection as stored in the file header. - */ - private static final String MERCATOR = "Mercator"; + /** + * The name of the Mercator projection as stored in the file header. + */ + private static final String MERCATOR = "Mercator"; - /** - * A single whitespace character. - */ - private static final char SPACE = ' '; + /** + * A single whitespace character. + */ + private static final char SPACE = ' '; - /** - * Lowest version of the map file format supported by this implementation. - */ - private static final int SUPPORTED_FILE_VERSION_MIN = 3; + /** + * Lowest version of the map file format supported by this implementation. + */ + private static final int SUPPORTED_FILE_VERSION_MIN = 3; - /** - * Highest version of the map file format supported by this implementation. - */ - private static final int SUPPORTED_FILE_VERSION_MAX = 4; + /** + * Highest version of the map file format supported by this implementation. + */ + private static final int SUPPORTED_FILE_VERSION_MAX = 4; - /** - * The maximum latitude values in microdegrees. - */ - static final int LATITUDE_MAX = 90000000; + /** + * The maximum latitude values in microdegrees. + */ + static final int LATITUDE_MAX = 90000000; - /** - * The minimum latitude values in microdegrees. - */ - static final int LATITUDE_MIN = -90000000; + /** + * The minimum latitude values in microdegrees. + */ + static final int LATITUDE_MIN = -90000000; - /** - * The maximum longitude values in microdegrees. - */ - static final int LONGITUDE_MAX = 180000000; + /** + * The maximum longitude values in microdegrees. + */ + static final int LONGITUDE_MAX = 180000000; - /** - * The minimum longitude values in microdegrees. - */ - static final int LONGITUDE_MIN = -180000000; + /** + * The minimum longitude values in microdegrees. + */ + static final int LONGITUDE_MIN = -180000000; - static OpenResult readBoundingBox(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the minimum latitude (4 bytes) - int minLatitude = readBuffer.readInt(); - if (minLatitude < LATITUDE_MIN || minLatitude > LATITUDE_MAX) { - return new OpenResult("invalid minimum latitude: " + minLatitude); - } + static OpenResult readBoundingBox(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the minimum latitude (4 bytes) + int minLatitude = readBuffer.readInt(); + if (minLatitude < LATITUDE_MIN || minLatitude > LATITUDE_MAX) { + return new OpenResult("invalid minimum latitude: " + minLatitude); + } - // get and check the minimum longitude (4 bytes) - int minLongitude = readBuffer.readInt(); - if (minLongitude < LONGITUDE_MIN || minLongitude > LONGITUDE_MAX) { - return new OpenResult("invalid minimum longitude: " + minLongitude); - } + // get and check the minimum longitude (4 bytes) + int minLongitude = readBuffer.readInt(); + if (minLongitude < LONGITUDE_MIN || minLongitude > LONGITUDE_MAX) { + return new OpenResult("invalid minimum longitude: " + minLongitude); + } - // get and check the maximum latitude (4 bytes) - int maxLatitude = readBuffer.readInt(); - if (maxLatitude < LATITUDE_MIN || maxLatitude > LATITUDE_MAX) { - return new OpenResult("invalid maximum latitude: " + maxLatitude); - } + // get and check the maximum latitude (4 bytes) + int maxLatitude = readBuffer.readInt(); + if (maxLatitude < LATITUDE_MIN || maxLatitude > LATITUDE_MAX) { + return new OpenResult("invalid maximum latitude: " + maxLatitude); + } - // get and check the maximum longitude (4 bytes) - int maxLongitude = readBuffer.readInt(); - if (maxLongitude < LONGITUDE_MIN || maxLongitude > LONGITUDE_MAX) { - return new OpenResult("invalid maximum longitude: " + maxLongitude); - } + // get and check the maximum longitude (4 bytes) + int maxLongitude = readBuffer.readInt(); + if (maxLongitude < LONGITUDE_MIN || maxLongitude > LONGITUDE_MAX) { + return new OpenResult("invalid maximum longitude: " + maxLongitude); + } - // check latitude and longitude range - if (minLatitude > maxLatitude) { - return new OpenResult("invalid latitude range: " + minLatitude + SPACE + maxLatitude); - } else if (minLongitude > maxLongitude) { - return new OpenResult("invalid longitude range: " + minLongitude + SPACE + maxLongitude); - } + // check latitude and longitude range + if (minLatitude > maxLatitude) { + return new OpenResult("invalid latitude range: " + minLatitude + SPACE + maxLatitude); + } else if (minLongitude > maxLongitude) { + return new OpenResult("invalid longitude range: " + minLongitude + SPACE + maxLongitude); + } - mapFileInfoBuilder.boundingBox = new BoundingBox(minLatitude, minLongitude, maxLatitude, - maxLongitude); - return OpenResult.SUCCESS; - } + mapFileInfoBuilder.boundingBox = new BoundingBox(minLatitude, minLongitude, maxLatitude, + maxLongitude); + return OpenResult.SUCCESS; + } - static OpenResult readFileSize(ReadBuffer readBuffer, long fileSize, - MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the file size (8 bytes) - long headerFileSize = readBuffer.readLong(); - if (headerFileSize != fileSize) { - return new OpenResult("invalid file size: " + headerFileSize); - } - mapFileInfoBuilder.fileSize = fileSize; - return OpenResult.SUCCESS; - } + static OpenResult readFileSize(ReadBuffer readBuffer, long fileSize, + MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the file size (8 bytes) + long headerFileSize = readBuffer.readLong(); + if (headerFileSize != fileSize) { + return new OpenResult("invalid file size: " + headerFileSize); + } + mapFileInfoBuilder.fileSize = fileSize; + return OpenResult.SUCCESS; + } - static OpenResult readFileVersion(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the file version (4 bytes) - int fileVersion = readBuffer.readInt(); - if (fileVersion < SUPPORTED_FILE_VERSION_MIN || fileVersion > SUPPORTED_FILE_VERSION_MAX) { - return new OpenResult("unsupported file version: " + fileVersion); - } - mapFileInfoBuilder.fileVersion = fileVersion; - return OpenResult.SUCCESS; - } + static OpenResult readFileVersion(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the file version (4 bytes) + int fileVersion = readBuffer.readInt(); + if (fileVersion < SUPPORTED_FILE_VERSION_MIN || fileVersion > SUPPORTED_FILE_VERSION_MAX) { + return new OpenResult("unsupported file version: " + fileVersion); + } + mapFileInfoBuilder.fileVersion = fileVersion; + return OpenResult.SUCCESS; + } - static OpenResult readMagicByte(ReadBuffer readBuffer) throws IOException { - // read the the magic byte and the file header size into the buffer - int magicByteLength = BINARY_OSM_MAGIC_BYTE.length(); - if (!readBuffer.readFromFile(magicByteLength + 4)) { - return new OpenResult("reading magic byte has failed"); - } + static OpenResult readMagicByte(ReadBuffer readBuffer) throws IOException { + // read the the magic byte and the file header size into the buffer + int magicByteLength = BINARY_OSM_MAGIC_BYTE.length(); + if (!readBuffer.readFromFile(magicByteLength + 4)) { + return new OpenResult("reading magic byte has failed"); + } - // get and check the magic byte - String magicByte = readBuffer.readUTF8EncodedString(magicByteLength); - if (!BINARY_OSM_MAGIC_BYTE.equals(magicByte)) { - return new OpenResult("invalid magic byte: " + magicByte); - } - return OpenResult.SUCCESS; - } + // get and check the magic byte + String magicByte = readBuffer.readUTF8EncodedString(magicByteLength); + if (!BINARY_OSM_MAGIC_BYTE.equals(magicByte)) { + return new OpenResult("invalid magic byte: " + magicByte); + } + return OpenResult.SUCCESS; + } - static OpenResult readMapDate(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the the map date (8 bytes) - long mapDate = readBuffer.readLong(); - // is the map date before 2010-01-10 ? - if (mapDate < 1200000000000L) { - return new OpenResult("invalid map date: " + mapDate); - } - mapFileInfoBuilder.mapDate = mapDate; - return OpenResult.SUCCESS; - } + static OpenResult readMapDate(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the the map date (8 bytes) + long mapDate = readBuffer.readLong(); + // is the map date before 2010-01-10 ? + if (mapDate < 1200000000000L) { + return new OpenResult("invalid map date: " + mapDate); + } + mapFileInfoBuilder.mapDate = mapDate; + return OpenResult.SUCCESS; + } - static OpenResult readPoiTags(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the number of POI tags (2 bytes) - int numberOfPoiTags = readBuffer.readShort(); - if (numberOfPoiTags < 0) { - return new OpenResult("invalid number of POI tags: " + numberOfPoiTags); - } + static OpenResult readPoiTags(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the number of POI tags (2 bytes) + int numberOfPoiTags = readBuffer.readShort(); + if (numberOfPoiTags < 0) { + return new OpenResult("invalid number of POI tags: " + numberOfPoiTags); + } - Tag[] poiTags = new Tag[numberOfPoiTags]; - for (int currentTagId = 0; currentTagId < numberOfPoiTags; ++currentTagId) { - // get and check the POI tag - String tag = readBuffer.readUTF8EncodedString(); - if (tag == null) { - return new OpenResult("POI tag must not be null: " + currentTagId); - } - poiTags[currentTagId] = Tag.parse(tag); - } - mapFileInfoBuilder.poiTags = poiTags; - return OpenResult.SUCCESS; - } + Tag[] poiTags = new Tag[numberOfPoiTags]; + for (int currentTagId = 0; currentTagId < numberOfPoiTags; ++currentTagId) { + // get and check the POI tag + String tag = readBuffer.readUTF8EncodedString(); + if (tag == null) { + return new OpenResult("POI tag must not be null: " + currentTagId); + } + poiTags[currentTagId] = Tag.parse(tag); + } + mapFileInfoBuilder.poiTags = poiTags; + return OpenResult.SUCCESS; + } - static OpenResult readProjectionName(ReadBuffer readBuffer, - MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the projection name - String projectionName = readBuffer.readUTF8EncodedString(); - if (!MERCATOR.equals(projectionName)) { - return new OpenResult("unsupported projection: " + projectionName); - } - mapFileInfoBuilder.projectionName = projectionName; - return OpenResult.SUCCESS; - } + static OpenResult readProjectionName(ReadBuffer readBuffer, + MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the projection name + String projectionName = readBuffer.readUTF8EncodedString(); + if (!MERCATOR.equals(projectionName)) { + return new OpenResult("unsupported projection: " + projectionName); + } + mapFileInfoBuilder.projectionName = projectionName; + return OpenResult.SUCCESS; + } - static OpenResult readRemainingHeader(ReadBuffer readBuffer) throws IOException { - // get and check the size of the remaining file header (4 bytes) - int remainingHeaderSize = readBuffer.readInt(); - if (remainingHeaderSize < HEADER_SIZE_MIN || remainingHeaderSize > HEADER_SIZE_MAX) { - return new OpenResult("invalid remaining header size: " + remainingHeaderSize); - } + static OpenResult readRemainingHeader(ReadBuffer readBuffer) throws IOException { + // get and check the size of the remaining file header (4 bytes) + int remainingHeaderSize = readBuffer.readInt(); + if (remainingHeaderSize < HEADER_SIZE_MIN || remainingHeaderSize > HEADER_SIZE_MAX) { + return new OpenResult("invalid remaining header size: " + remainingHeaderSize); + } - // read the header data into the buffer - if (!readBuffer.readFromFile(remainingHeaderSize)) { - return new OpenResult("reading header data has failed: " + remainingHeaderSize); - } - return OpenResult.SUCCESS; - } + // read the header data into the buffer + if (!readBuffer.readFromFile(remainingHeaderSize)) { + return new OpenResult("reading header data has failed: " + remainingHeaderSize); + } + return OpenResult.SUCCESS; + } - static OpenResult readTilePixelSize(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the tile pixel size (2 bytes) - int tilePixelSize = readBuffer.readShort(); - // if (tilePixelSize != Tile.SIZE) { - // return new FileOpenResult("unsupported tile pixel size: " + tilePixelSize); - // } - mapFileInfoBuilder.tilePixelSize = tilePixelSize; - return OpenResult.SUCCESS; - } + static OpenResult readTilePixelSize(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the tile pixel size (2 bytes) + int tilePixelSize = readBuffer.readShort(); + // if (tilePixelSize != Tile.SIZE) { + // return new FileOpenResult("unsupported tile pixel size: " + tilePixelSize); + // } + mapFileInfoBuilder.tilePixelSize = tilePixelSize; + return OpenResult.SUCCESS; + } - static OpenResult readWayTags(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { - // get and check the number of way tags (2 bytes) - int numberOfWayTags = readBuffer.readShort(); - if (numberOfWayTags < 0) { - return new OpenResult("invalid number of way tags: " + numberOfWayTags); - } + static OpenResult readWayTags(ReadBuffer readBuffer, MapFileInfoBuilder mapFileInfoBuilder) { + // get and check the number of way tags (2 bytes) + int numberOfWayTags = readBuffer.readShort(); + if (numberOfWayTags < 0) { + return new OpenResult("invalid number of way tags: " + numberOfWayTags); + } - Tag[] wayTags = new Tag[numberOfWayTags]; + Tag[] wayTags = new Tag[numberOfWayTags]; - for (int currentTagId = 0; currentTagId < numberOfWayTags; ++currentTagId) { - // get and check the way tag - String tag = readBuffer.readUTF8EncodedString(); - if (tag == null) { - return new OpenResult("way tag must not be null: " + currentTagId); - } - wayTags[currentTagId] = Tag.parse(tag); - } - mapFileInfoBuilder.wayTags = wayTags; - return OpenResult.SUCCESS; - } + for (int currentTagId = 0; currentTagId < numberOfWayTags; ++currentTagId) { + // get and check the way tag + String tag = readBuffer.readUTF8EncodedString(); + if (tag == null) { + return new OpenResult("way tag must not be null: " + currentTagId); + } + wayTags[currentTagId] = Tag.parse(tag); + } + mapFileInfoBuilder.wayTags = wayTags; + return OpenResult.SUCCESS; + } - private RequiredFields() { - throw new IllegalStateException(); - } + private RequiredFields() { + throw new IllegalStateException(); + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameter.java b/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameter.java index bb975260..cc85df4e 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameter.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameter.java @@ -22,202 +22,202 @@ import org.oscim.tiling.source.mapfile.Projection; * Holds all parameters of a sub-file. */ public class SubFileParameter { - /** - * Number of bytes a single index entry consists of. - */ - public static final byte BYTES_PER_INDEX_ENTRY = 5; + /** + * Number of bytes a single index entry consists of. + */ + public static final byte BYTES_PER_INDEX_ENTRY = 5; - /** - * Divisor for converting coordinates stored as integers to double values. - */ - private static final double COORDINATES_DIVISOR = 1000000d; + /** + * Divisor for converting coordinates stored as integers to double values. + */ + private static final double COORDINATES_DIVISOR = 1000000d; - /** - * Base zoom level of the sub-file, which equals to one block. - */ - public final byte baseZoomLevel; + /** + * Base zoom level of the sub-file, which equals to one block. + */ + public final byte baseZoomLevel; - /** - * Size of the entries table at the beginning of each block in bytes. - */ - public final int blockEntriesTableSize; + /** + * Size of the entries table at the beginning of each block in bytes. + */ + public final int blockEntriesTableSize; - /** - * Vertical amount of blocks in the grid. - */ - public final long blocksHeight; + /** + * Vertical amount of blocks in the grid. + */ + public final long blocksHeight; - /** - * Horizontal amount of blocks in the grid. - */ - public final long blocksWidth; + /** + * Horizontal amount of blocks in the grid. + */ + public final long blocksWidth; - /** - * Y number of the tile at the bottom boundary in the grid. - */ - public final long boundaryTileBottom; + /** + * Y number of the tile at the bottom boundary in the grid. + */ + public final long boundaryTileBottom; - /** - * X number of the tile at the left boundary in the grid. - */ - public final long boundaryTileLeft; + /** + * X number of the tile at the left boundary in the grid. + */ + public final long boundaryTileLeft; - /** - * X number of the tile at the right boundary in the grid. - */ - public final long boundaryTileRight; + /** + * X number of the tile at the right boundary in the grid. + */ + public final long boundaryTileRight; - /** - * Y number of the tile at the top boundary in the grid. - */ - public final long boundaryTileTop; + /** + * Y number of the tile at the top boundary in the grid. + */ + public final long boundaryTileTop; - /** - * Absolute end address of the index in the enclosing file. - */ - public final long indexEndAddress; + /** + * Absolute end address of the index in the enclosing file. + */ + public final long indexEndAddress; - /** - * Absolute start address of the index in the enclosing file. - */ - public final long indexStartAddress; + /** + * Absolute start address of the index in the enclosing file. + */ + public final long indexStartAddress; - /** - * Total number of blocks in the grid. - */ - public final long numberOfBlocks; + /** + * Total number of blocks in the grid. + */ + public final long numberOfBlocks; - /** - * Absolute start address of the sub-file in the enclosing file. - */ - public final long startAddress; + /** + * Absolute start address of the sub-file in the enclosing file. + */ + public final long startAddress; - /** - * Size of the sub-file in bytes. - */ - public final long subFileSize; + /** + * Size of the sub-file in bytes. + */ + public final long subFileSize; - /** - * Maximum zoom level for which the block entries tables are made. - */ - public final byte zoomLevelMax; + /** + * Maximum zoom level for which the block entries tables are made. + */ + public final byte zoomLevelMax; - /** - * Minimum zoom level for which the block entries tables are made. - */ - public final byte zoomLevelMin; + /** + * Minimum zoom level for which the block entries tables are made. + */ + public final byte zoomLevelMin; - /** - * Stores the hash code of this object. - */ - private final int hashCodeValue; + /** + * Stores the hash code of this object. + */ + private final int hashCodeValue; - SubFileParameter(SubFileParameterBuilder subFileParameterBuilder) { - this.startAddress = subFileParameterBuilder.startAddress; - this.indexStartAddress = subFileParameterBuilder.indexStartAddress; - this.subFileSize = subFileParameterBuilder.subFileSize; - this.baseZoomLevel = subFileParameterBuilder.baseZoomLevel; - this.zoomLevelMin = subFileParameterBuilder.zoomLevelMin; - this.zoomLevelMax = subFileParameterBuilder.zoomLevelMax; - this.hashCodeValue = calculateHashCode(); + SubFileParameter(SubFileParameterBuilder subFileParameterBuilder) { + this.startAddress = subFileParameterBuilder.startAddress; + this.indexStartAddress = subFileParameterBuilder.indexStartAddress; + this.subFileSize = subFileParameterBuilder.subFileSize; + this.baseZoomLevel = subFileParameterBuilder.baseZoomLevel; + this.zoomLevelMin = subFileParameterBuilder.zoomLevelMin; + this.zoomLevelMax = subFileParameterBuilder.zoomLevelMax; + this.hashCodeValue = calculateHashCode(); - // calculate the XY numbers of the boundary tiles in this sub-file - this.boundaryTileBottom = Projection.latitudeToTileY( - subFileParameterBuilder.boundingBox.minLatitudeE6 - / COORDINATES_DIVISOR, - this.baseZoomLevel); - this.boundaryTileLeft = Projection.longitudeToTileX( - subFileParameterBuilder.boundingBox.minLongitudeE6 - / COORDINATES_DIVISOR, - this.baseZoomLevel); - this.boundaryTileTop = Projection.latitudeToTileY( - subFileParameterBuilder.boundingBox.maxLatitudeE6 - / COORDINATES_DIVISOR, - this.baseZoomLevel); - this.boundaryTileRight = Projection.longitudeToTileX( - subFileParameterBuilder.boundingBox.maxLongitudeE6 - / COORDINATES_DIVISOR, - this.baseZoomLevel); + // calculate the XY numbers of the boundary tiles in this sub-file + this.boundaryTileBottom = Projection.latitudeToTileY( + subFileParameterBuilder.boundingBox.minLatitudeE6 + / COORDINATES_DIVISOR, + this.baseZoomLevel); + this.boundaryTileLeft = Projection.longitudeToTileX( + subFileParameterBuilder.boundingBox.minLongitudeE6 + / COORDINATES_DIVISOR, + this.baseZoomLevel); + this.boundaryTileTop = Projection.latitudeToTileY( + subFileParameterBuilder.boundingBox.maxLatitudeE6 + / COORDINATES_DIVISOR, + this.baseZoomLevel); + this.boundaryTileRight = Projection.longitudeToTileX( + subFileParameterBuilder.boundingBox.maxLongitudeE6 + / COORDINATES_DIVISOR, + this.baseZoomLevel); - // calculate the horizontal and vertical amount of blocks in this sub-file - this.blocksWidth = this.boundaryTileRight - this.boundaryTileLeft + 1; - this.blocksHeight = this.boundaryTileBottom - this.boundaryTileTop + 1; + // calculate the horizontal and vertical amount of blocks in this sub-file + this.blocksWidth = this.boundaryTileRight - this.boundaryTileLeft + 1; + this.blocksHeight = this.boundaryTileBottom - this.boundaryTileTop + 1; - // calculate the total amount of blocks in this sub-file - this.numberOfBlocks = this.blocksWidth * this.blocksHeight; + // calculate the total amount of blocks in this sub-file + this.numberOfBlocks = this.blocksWidth * this.blocksHeight; - this.indexEndAddress = this.indexStartAddress + this.numberOfBlocks * BYTES_PER_INDEX_ENTRY; + this.indexEndAddress = this.indexStartAddress + this.numberOfBlocks * BYTES_PER_INDEX_ENTRY; - // calculate the size of the tile entries table - this.blockEntriesTableSize = 2 * (this.zoomLevelMax - this.zoomLevelMin + 1) * 2; - } + // calculate the size of the tile entries table + this.blockEntriesTableSize = 2 * (this.zoomLevelMax - this.zoomLevelMin + 1) * 2; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (!(obj instanceof SubFileParameter)) { - return false; - } - SubFileParameter other = (SubFileParameter) obj; - if (this.startAddress != other.startAddress) { - return false; - } else if (this.subFileSize != other.subFileSize) { - return false; - } else if (this.baseZoomLevel != other.baseZoomLevel) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof SubFileParameter)) { + return false; + } + SubFileParameter other = (SubFileParameter) obj; + if (this.startAddress != other.startAddress) { + return false; + } else if (this.subFileSize != other.subFileSize) { + return false; + } else if (this.baseZoomLevel != other.baseZoomLevel) { + return false; + } + return true; + } - @Override - public int hashCode() { - return this.hashCodeValue; - } + @Override + public int hashCode() { + return this.hashCodeValue; + } - @Override - public String toString() { - return new StringBuilder() - .append("SubFileParameter [baseZoomLevel=") - .append(this.baseZoomLevel) - .append(", blockEntriesTableSize=") - .append(this.blockEntriesTableSize) - .append(", blocksHeight=") - .append(this.blocksHeight) - .append(", blocksWidth=") - .append(this.blocksWidth) - .append(", boundaryTileBottom=") - .append(this.boundaryTileBottom) - .append(", boundaryTileLeft=") - .append(this.boundaryTileLeft) - .append(", boundaryTileRight=") - .append(this.boundaryTileRight) - .append(", boundaryTileTop=") - .append(this.boundaryTileTop) - .append(", indexStartAddress=") - .append(this.indexStartAddress) - .append(", numberOfBlocks=") - .append(this.numberOfBlocks) - .append(", startAddress=") - .append(this.startAddress) - .append(", subFileSize=") - .append(this.subFileSize) - .append(", zoomLevelMax=") - .append(this.zoomLevelMax) - .append(", zoomLevelMin=") - .append(this.zoomLevelMin) - .append("]") - .toString(); - } + @Override + public String toString() { + return new StringBuilder() + .append("SubFileParameter [baseZoomLevel=") + .append(this.baseZoomLevel) + .append(", blockEntriesTableSize=") + .append(this.blockEntriesTableSize) + .append(", blocksHeight=") + .append(this.blocksHeight) + .append(", blocksWidth=") + .append(this.blocksWidth) + .append(", boundaryTileBottom=") + .append(this.boundaryTileBottom) + .append(", boundaryTileLeft=") + .append(this.boundaryTileLeft) + .append(", boundaryTileRight=") + .append(this.boundaryTileRight) + .append(", boundaryTileTop=") + .append(this.boundaryTileTop) + .append(", indexStartAddress=") + .append(this.indexStartAddress) + .append(", numberOfBlocks=") + .append(this.numberOfBlocks) + .append(", startAddress=") + .append(this.startAddress) + .append(", subFileSize=") + .append(this.subFileSize) + .append(", zoomLevelMax=") + .append(this.zoomLevelMax) + .append(", zoomLevelMin=") + .append(this.zoomLevelMin) + .append("]") + .toString(); + } - /** - * @return the hash code of this object. - */ - private int calculateHashCode() { - int result = 7; - result = 31 * result + (int) (this.startAddress ^ (this.startAddress >>> 32)); - result = 31 * result + (int) (this.subFileSize ^ (this.subFileSize >>> 32)); - result = 31 * result + this.baseZoomLevel; - return result; - } + /** + * @return the hash code of this object. + */ + private int calculateHashCode() { + int result = 7; + result = 31 * result + (int) (this.startAddress ^ (this.startAddress >>> 32)); + result = 31 * result + (int) (this.subFileSize ^ (this.subFileSize >>> 32)); + result = 31 * result + this.baseZoomLevel; + return result; + } } diff --git a/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameterBuilder.java b/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameterBuilder.java index 4674789e..ec610418 100644 --- a/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameterBuilder.java +++ b/vtm/src/org/oscim/tiling/source/mapfile/header/SubFileParameterBuilder.java @@ -19,15 +19,15 @@ package org.oscim.tiling.source.mapfile.header; import org.oscim.core.BoundingBox; class SubFileParameterBuilder { - byte baseZoomLevel; - BoundingBox boundingBox; - long indexStartAddress; - long startAddress; - long subFileSize; - byte zoomLevelMax; - byte zoomLevelMin; + byte baseZoomLevel; + BoundingBox boundingBox; + long indexStartAddress; + long startAddress; + long subFileSize; + byte zoomLevelMax; + byte zoomLevelMin; - SubFileParameter build() { - return new SubFileParameter(this); - } + SubFileParameter build() { + return new SubFileParameter(this); + } } diff --git a/vtm/src/org/oscim/tiling/source/oscimap4/OSciMap4TileSource.java b/vtm/src/org/oscim/tiling/source/oscimap4/OSciMap4TileSource.java index c4870ee0..16976f37 100644 --- a/vtm/src/org/oscim/tiling/source/oscimap4/OSciMap4TileSource.java +++ b/vtm/src/org/oscim/tiling/source/oscimap4/OSciMap4TileSource.java @@ -22,39 +22,39 @@ import org.oscim.tiling.source.UrlTileSource; public class OSciMap4TileSource extends UrlTileSource { - private final static String DEFAULT_URL = "http://opensciencemap.org/tiles/vtm"; - private final static String DEFAULT_PATH = "/{Z}/{X}/{Y}.vtm"; + private final static String DEFAULT_URL = "http://opensciencemap.org/tiles/vtm"; + private final static String DEFAULT_PATH = "/{Z}/{X}/{Y}.vtm"; - public static class Builder> extends UrlTileSource.Builder { + public static class Builder> extends UrlTileSource.Builder { - public Builder() { - super(DEFAULT_URL, DEFAULT_PATH, 1, 17); - } + public Builder() { + super(DEFAULT_URL, DEFAULT_PATH, 1, 17); + } - public OSciMap4TileSource build() { - return new OSciMap4TileSource(this); - } - } + public OSciMap4TileSource build() { + return new OSciMap4TileSource(this); + } + } - @SuppressWarnings("rawtypes") - public static Builder builder() { - return new Builder(); - } + @SuppressWarnings("rawtypes") + public static Builder builder() { + return new Builder(); + } - protected OSciMap4TileSource(Builder builder) { - super(builder); - } + protected OSciMap4TileSource(Builder builder) { + super(builder); + } - public OSciMap4TileSource() { - this(builder()); - } + public OSciMap4TileSource() { + this(builder()); + } - public OSciMap4TileSource(String urlString) { - this(builder().url(urlString)); - } + public OSciMap4TileSource(String urlString) { + this(builder().url(urlString)); + } - @Override - public ITileDataSource getDataSource() { - return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); - } + @Override + public ITileDataSource getDataSource() { + return new UrlTileDataSource(this, new TileDecoder(), getHttpEngine()); + } } diff --git a/vtm/src/org/oscim/tiling/source/oscimap4/Tags.java b/vtm/src/org/oscim/tiling/source/oscimap4/Tags.java index 0e1a210d..dfe1b0ed 100644 --- a/vtm/src/org/oscim/tiling/source/oscimap4/Tags.java +++ b/vtm/src/org/oscim/tiling/source/oscimap4/Tags.java @@ -17,343 +17,343 @@ package org.oscim.tiling.source.oscimap4; public class Tags { - // TODO this should be retrieved from tile 0/0/0 + // TODO this should be retrieved from tile 0/0/0 - public final static int ATTRIB_OFFSET = 256; + public final static int ATTRIB_OFFSET = 256; - // the keys that were imported via osm2pgsql + some more - public final static String[] keys = { - "access", - "addr:housename", - "addr:housenumber", - "addr:interpolation", - "admin_level", - "aerialway", - "aeroway", - "amenity", - "area", - "barrier", - "bicycle", - "brand", - "bridge", - "boundary", - "building", - "construction", - "covered", - "culvert", - "cutting", - "denomination", - "disused", - "embankment", - "foot", - "generator:source", - "harbour", - "highway", - "historic", - "horse", - "intermittent", - "junction", - "landuse", - "layer", - "leisure", - "lock", - "man_made", - "military", - "motorcar", - "name", - "natural", - "oneway", - "operator", - "population", - "power", - "power_source", - "place", - "railway", - "ref", - "religion", - "route", - "service", - "shop", - "sport", - "surface", - "toll", - "tourism", - "tower:type", - "tracktype", - "tunnel", - "water", - "waterway", - "wetland", - "width", - "wood", + // the keys that were imported via osm2pgsql + some more + public final static String[] keys = { + "access", + "addr:housename", + "addr:housenumber", + "addr:interpolation", + "admin_level", + "aerialway", + "aeroway", + "amenity", + "area", + "barrier", + "bicycle", + "brand", + "bridge", + "boundary", + "building", + "construction", + "covered", + "culvert", + "cutting", + "denomination", + "disused", + "embankment", + "foot", + "generator:source", + "harbour", + "highway", + "historic", + "horse", + "intermittent", + "junction", + "landuse", + "layer", + "leisure", + "lock", + "man_made", + "military", + "motorcar", + "name", + "natural", + "oneway", + "operator", + "population", + "power", + "power_source", + "place", + "railway", + "ref", + "religion", + "route", + "service", + "shop", + "sport", + "surface", + "toll", + "tourism", + "tower:type", + "tracktype", + "tunnel", + "water", + "waterway", + "wetland", + "width", + "wood", - "height", - "min_height", - "roof:shape", - "roof:height", - "rank" - }; - public final static int MAX_KEY = keys.length - 1; + "height", + "min_height", + "roof:shape", + "roof:height", + "rank" + }; + public final static int MAX_KEY = keys.length - 1; - // most popular values for the selected key (created from taginfo db) - public final static String[] values = { - "yes", - "residential", - "service", - "unclassified", - "stream", - "track", - "water", - "footway", - "tertiary", - "private", - "tree", - "path", - "forest", - "secondary", - "house", - "no", - "asphalt", - "wood", - "grass", - "paved", - "primary", - "unpaved", - "bus_stop", - "parking", - "parking_aisle", - "rail", - "driveway", - "8", - "administrative", - "locality", - "turning_circle", - "crossing", - "village", - "fence", - "grade2", - "coastline", - "grade3", - "farmland", - "hamlet", - "hut", - "meadow", - "wetland", - "cycleway", - "river", - "school", - "trunk", - "gravel", - "place_of_worship", - "farm", - "grade1", - "traffic_signals", - "wall", - "garage", - "gate", - "motorway", - "living_street", - "pitch", - "grade4", - "industrial", - "road", - "ground", - "scrub", - "motorway_link", - "steps", - "ditch", - "swimming_pool", - "grade5", - "park", - "apartments", - "restaurant", - "designated", - "bench", - "survey_point", - "pedestrian", - "hedge", - "reservoir", - "riverbank", - "alley", - "farmyard", - "peak", - "level_crossing", - "roof", - "dirt", - "drain", - "garages", - "entrance", - "street_lamp", - "deciduous", - "fuel", - "trunk_link", - "information", - "playground", - "supermarket", - "primary_link", - "concrete", - "mixed", - "permissive", - "orchard", - "grave_yard", - "canal", - "garden", - "spur", - "paving_stones", - "rock", - "bollard", - "convenience", - "cemetery", - "post_box", - "commercial", - "pier", - "bank", - "hotel", - "cliff", - "retail", - "construction", - "-1", - "fast_food", - "coniferous", - "cafe", - "6", - "kindergarten", - "tower", - "hospital", - "yard", - "sand", - "public_building", - "cobblestone", - "destination", - "island", - "abandoned", - "vineyard", - "recycling", - "agricultural", - "isolated_dwelling", - "pharmacy", - "post_office", - "motorway_junction", - "pub", - "allotments", - "dam", - "secondary_link", - "lift_gate", - "siding", - "stop", - "main", - "farm_auxiliary", - "quarry", - "10", - "station", - "platform", - "taxiway", - "limited", - "sports_centre", - "cutline", - "detached", - "storage_tank", - "basin", - "bicycle_parking", - "telephone", - "terrace", - "town", - "suburb", - "bus", - "compacted", - "toilets", - "heath", - "works", - "tram", - "beach", - "culvert", - "fire_station", - "recreation_ground", - "bakery", - "police", - "atm", - "clothes", - "tertiary_link", - "waste_basket", - "attraction", - "viewpoint", - "bicycle", - "church", - "shelter", - "drinking_water", - "marsh", - "picnic_site", - "hairdresser", - "bridleway", - "retaining_wall", - "buffer_stop", - "nature_reserve", - "village_green", - "university", - "1", - "bar", - "townhall", - "mini_roundabout", - "camp_site", - "aerodrome", - "stile", - "9", - "car_repair", - "parking_space", - "library", - "pipeline", - "true", - "cycle_barrier", - "4", - "museum", - "spring", - "hunting_stand", - "disused", - "car", - "tram_stop", - "land", - "fountain", - "hiking", - "manufacture", - "vending_machine", - "kiosk", - "swamp", - "unknown", - "7", - "islet", - "shed", - "switch", - "rapids", - "office", - "bay", - "proposed", - "common", - "weir", - "grassland", - "customers", - "social_facility", - "hangar", - "doctors", - "stadium", - "give_way", - "greenhouse", - "guest_house", - "viaduct", - "doityourself", - "runway", - "bus_station", - "water_tower", - "golf_course", - "conservation", - "block", - "college", - "wastewater_plant", - "subway", - "halt", - "forestry", - "florist", - "butcher" - }; - public final static int MAX_VALUE = values.length - 1; + // most popular values for the selected key (created from taginfo db) + public final static String[] values = { + "yes", + "residential", + "service", + "unclassified", + "stream", + "track", + "water", + "footway", + "tertiary", + "private", + "tree", + "path", + "forest", + "secondary", + "house", + "no", + "asphalt", + "wood", + "grass", + "paved", + "primary", + "unpaved", + "bus_stop", + "parking", + "parking_aisle", + "rail", + "driveway", + "8", + "administrative", + "locality", + "turning_circle", + "crossing", + "village", + "fence", + "grade2", + "coastline", + "grade3", + "farmland", + "hamlet", + "hut", + "meadow", + "wetland", + "cycleway", + "river", + "school", + "trunk", + "gravel", + "place_of_worship", + "farm", + "grade1", + "traffic_signals", + "wall", + "garage", + "gate", + "motorway", + "living_street", + "pitch", + "grade4", + "industrial", + "road", + "ground", + "scrub", + "motorway_link", + "steps", + "ditch", + "swimming_pool", + "grade5", + "park", + "apartments", + "restaurant", + "designated", + "bench", + "survey_point", + "pedestrian", + "hedge", + "reservoir", + "riverbank", + "alley", + "farmyard", + "peak", + "level_crossing", + "roof", + "dirt", + "drain", + "garages", + "entrance", + "street_lamp", + "deciduous", + "fuel", + "trunk_link", + "information", + "playground", + "supermarket", + "primary_link", + "concrete", + "mixed", + "permissive", + "orchard", + "grave_yard", + "canal", + "garden", + "spur", + "paving_stones", + "rock", + "bollard", + "convenience", + "cemetery", + "post_box", + "commercial", + "pier", + "bank", + "hotel", + "cliff", + "retail", + "construction", + "-1", + "fast_food", + "coniferous", + "cafe", + "6", + "kindergarten", + "tower", + "hospital", + "yard", + "sand", + "public_building", + "cobblestone", + "destination", + "island", + "abandoned", + "vineyard", + "recycling", + "agricultural", + "isolated_dwelling", + "pharmacy", + "post_office", + "motorway_junction", + "pub", + "allotments", + "dam", + "secondary_link", + "lift_gate", + "siding", + "stop", + "main", + "farm_auxiliary", + "quarry", + "10", + "station", + "platform", + "taxiway", + "limited", + "sports_centre", + "cutline", + "detached", + "storage_tank", + "basin", + "bicycle_parking", + "telephone", + "terrace", + "town", + "suburb", + "bus", + "compacted", + "toilets", + "heath", + "works", + "tram", + "beach", + "culvert", + "fire_station", + "recreation_ground", + "bakery", + "police", + "atm", + "clothes", + "tertiary_link", + "waste_basket", + "attraction", + "viewpoint", + "bicycle", + "church", + "shelter", + "drinking_water", + "marsh", + "picnic_site", + "hairdresser", + "bridleway", + "retaining_wall", + "buffer_stop", + "nature_reserve", + "village_green", + "university", + "1", + "bar", + "townhall", + "mini_roundabout", + "camp_site", + "aerodrome", + "stile", + "9", + "car_repair", + "parking_space", + "library", + "pipeline", + "true", + "cycle_barrier", + "4", + "museum", + "spring", + "hunting_stand", + "disused", + "car", + "tram_stop", + "land", + "fountain", + "hiking", + "manufacture", + "vending_machine", + "kiosk", + "swamp", + "unknown", + "7", + "islet", + "shed", + "switch", + "rapids", + "office", + "bay", + "proposed", + "common", + "weir", + "grassland", + "customers", + "social_facility", + "hangar", + "doctors", + "stadium", + "give_way", + "greenhouse", + "guest_house", + "viaduct", + "doityourself", + "runway", + "bus_station", + "water_tower", + "golf_course", + "conservation", + "block", + "college", + "wastewater_plant", + "subway", + "halt", + "forestry", + "florist", + "butcher" + }; + public final static int MAX_VALUE = values.length - 1; } diff --git a/vtm/src/org/oscim/tiling/source/oscimap4/TileDecoder.java b/vtm/src/org/oscim/tiling/source/oscimap4/TileDecoder.java index 749d6656..325e6df8 100644 --- a/vtm/src/org/oscim/tiling/source/oscimap4/TileDecoder.java +++ b/vtm/src/org/oscim/tiling/source/oscimap4/TileDecoder.java @@ -16,9 +16,6 @@ */ package org.oscim.tiling.source.oscimap4; -import java.io.IOException; -import java.io.InputStream; - import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.Tag; @@ -29,371 +26,378 @@ import org.oscim.tiling.source.PbfDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; + public class TileDecoder extends PbfDecoder { - static final Logger log = LoggerFactory.getLogger(TileDecoder.class); - - private static final int TAG_TILE_VERSION = 1; - //private static final int TAG_TILE_TIMESTAMP = 2; - //private static final int TAG_TILE_ISWATER = 3; - - private static final int TAG_TILE_NUM_TAGS = 11; - private static final int TAG_TILE_NUM_KEYS = 12; - private static final int TAG_TILE_NUM_VALUES = 13; - - private static final int TAG_TILE_TAG_KEYS = 14; - private static final int TAG_TILE_TAG_VALUES = 15; - private static final int TAG_TILE_TAGS = 16; - - private static final int TAG_TILE_LINE = 21; - private static final int TAG_TILE_POLY = 22; - private static final int TAG_TILE_POINT = 23; - /** since version 5 */ - private static final int TAG_TILE_MESH = 24; - - private static final int TAG_ELEM_NUM_INDICES = 1; - private static final int TAG_ELEM_NUM_TAGS = 2; - /** since version 5 */ - private static final int TAG_ELEM_NUM_COORDINATES = 3; - private static final int TAG_ELEM_TAGS = 11; - private static final int TAG_ELEM_INDEX = 12; - private static final int TAG_ELEM_COORDS = 13; - private static final int TAG_ELEM_LAYER = 21; - - private int[] mSArray = new int[100]; - - private Tile mTile; - - private final MapElement mElem; - - private final TagSet mTileTags; - private ITileDataSink mMapDataSink; - - private int mVersion; - - // scale coordinates to tile size - private final static float REF_TILE_SIZE = 4096.0f; - private final float mScaleFactor = REF_TILE_SIZE / Tile.SIZE; - - TileDecoder() { - mElem = new MapElement(); - mTileTags = new TagSet(100); - } - - @Override - public boolean decode(Tile tile, ITileDataSink sink, InputStream is) - throws IOException { - - readUnsignedInt(is, buffer); - setInputStream(is); - - mTile = tile; - mMapDataSink = sink; - - mTileTags.clearAndNullTags(); - - int val; - int numTags = 0; - int numKeys = -1; - int numValues = -1; - - int curKey = 0; - int curValue = 0; - - String[] keys = null; - String[] values = null; - - while (hasData() && (val = decodeVarint32()) > 0) { - // read tag and wire type - int tag = (val >> 3); - //log.debug("tag: " + tag); - - switch (tag) { - case TAG_TILE_LINE: - case TAG_TILE_POLY: - case TAG_TILE_POINT: - case TAG_TILE_MESH: - decodeTileElement(tag); - break; - - case TAG_TILE_TAG_KEYS: - if (keys == null || curKey >= numKeys) { - log.debug("{} wrong number of keys {}", - mTile, numKeys); - return false; - } - keys[curKey++] = decodeString().intern(); - break; - - case TAG_TILE_TAG_VALUES: - if (values == null || curValue >= numValues) { - log.debug("{} wrong number of values {}", - mTile, numValues); - return false; - } - values[curValue++] = decodeString(); - break; - - case TAG_TILE_NUM_TAGS: - numTags = decodeVarint32(); - //log.debug("num tags " + numTags); - break; - - case TAG_TILE_NUM_KEYS: - numKeys = decodeVarint32(); - //log.debug("num keys " + numKeys); - keys = new String[numKeys]; - break; - - case TAG_TILE_NUM_VALUES: - numValues = decodeVarint32(); - //log.debug("num values " + numValues); - values = new String[numValues]; - break; - - case TAG_TILE_TAGS: - int len = numTags * 2; - if (mSArray.length < len) - mSArray = new int[len]; - - decodeVarintArray(len, mSArray); - if (!decodeTileTags(numTags, mSArray, keys, values)) { - log.debug("{} invalid tags", mTile); - return false; - } - break; - - case TAG_TILE_VERSION: - int version = decodeVarint32(); - if (version < 4 || mVersion > 5) { - log.debug("{} invalid version:{}", - mTile, version); - return false; - } - break; - - default: - log.debug("{} invalid type for tile:{}", - mTile, tag); - return false; - } - } - - return true; - } - - private boolean decodeTileTags(int numTags, int[] tagIdx, - String[] keys, String[] vals) { - - Tag tag; - for (int i = 0, n = (numTags << 1); i < n; i += 2) { - int k = tagIdx[i]; - int v = tagIdx[i + 1]; - String key, val; - - if (k < Tags.ATTRIB_OFFSET) { - if (k > Tags.MAX_KEY) - return false; - key = Tags.keys[k]; - } else { - k -= Tags.ATTRIB_OFFSET; - if (k >= keys.length) - return false; - key = keys[k]; - } - - if (v < Tags.ATTRIB_OFFSET) { - if (v > Tags.MAX_VALUE) - return false; - val = Tags.values[v]; - } else { - v -= Tags.ATTRIB_OFFSET; - if (v >= vals.length) - return false; - val = vals[v]; - } - - // FIXME filter out all variable tags - // might depend on theme though - if (key == Tag.KEY_NAME - || key == Tag.KEY_HEIGHT - || key == Tag.KEY_MIN_HEIGHT - || key == Tag.KEY_HOUSE_NUMBER - || key == Tag.KEY_REF - || key == Tag.KEY_ELE) - tag = new Tag(key, val, false); - else - tag = new Tag(key, val, false, true); - - mTileTags.add(tag); - } - - return true; - } - - private int decodeWayIndices(int indexCnt, boolean shift) throws IOException { - mElem.ensureIndexSize(indexCnt, false); - decodeVarintArray(indexCnt, mElem.index); - - int[] index = mElem.index; - int coordCnt = 0; - - if (shift) { - for (int i = 0; i < indexCnt; i++) { - coordCnt += index[i]; - index[i] *= 2; - } - } - // set end marker - if (indexCnt < index.length) - index[indexCnt] = -1; - - return coordCnt; - } - - private boolean decodeTileElement(int type) throws IOException { - - int bytes = decodeVarint32(); - - int end = position() + bytes; - int numIndices = 1; - int numTags = 1; - - //boolean skip = false; - boolean fail = false; - - int coordCnt = 0; - if (type == TAG_TILE_POINT) { - coordCnt = 1; - mElem.index[0] = 2; - } - - mElem.layer = 5; - - while (position() < end) { - // read tag and wire type - int val = decodeVarint32(); - if (val == 0) - break; - - int tag = (val >> 3); - - switch (tag) { - case TAG_ELEM_TAGS: - if (!decodeElementTags(numTags)) - return false; - break; - - case TAG_ELEM_NUM_INDICES: - numIndices = decodeVarint32(); - break; - - case TAG_ELEM_NUM_TAGS: - numTags = decodeVarint32(); - break; - - case TAG_ELEM_NUM_COORDINATES: - coordCnt = decodeVarint32(); - break; - - case TAG_ELEM_INDEX: - if (type == TAG_TILE_MESH) { - decodeWayIndices(numIndices, false); - } else { - coordCnt = decodeWayIndices(numIndices, true); - // otherwise using TAG_ELEM_NUM_COORDINATES - } - break; - - case TAG_ELEM_COORDS: - if (coordCnt == 0) { - log.debug("{} no coordinates", mTile); - } - - if (type == TAG_TILE_MESH) { - mElem.ensurePointSize((coordCnt * 3 / 2), false); - int cnt = decodeInterleavedPoints3D(mElem.points, 1); - - if (cnt != (3 * coordCnt)) { - log.debug("{} wrong number of coordintes {}/{}", mTile, - Integer.valueOf(coordCnt), - Integer.valueOf(cnt)); - fail = true; - } - mElem.pointPos = cnt; - } else { - mElem.ensurePointSize(coordCnt, false); - int cnt = decodeInterleavedPoints(mElem, mScaleFactor); - - if (cnt != coordCnt) { - log.debug("{} wrong number of coordintes {}/{}", mTile, - Integer.valueOf(coordCnt), - Integer.valueOf(cnt)); - fail = true; - } - } - break; - - case TAG_ELEM_LAYER: - mElem.layer = decodeVarint32(); - break; - - default: - log.debug("{} invalid type for way: {}", mTile, tag); - } - } - - if (fail || numTags == 0 || numIndices == 0) { - log.debug("{} failed: bytes:{} tags:{} ({},{})", - mTile, Integer.valueOf(bytes), - mElem.tags, - Integer.valueOf(numIndices), - Integer.valueOf(coordCnt)); - return false; - } - - switch (type) { - case TAG_TILE_LINE: - mElem.type = GeometryType.LINE; - break; - case TAG_TILE_POLY: - mElem.type = GeometryType.POLY; - break; - case TAG_TILE_POINT: - mElem.type = GeometryType.POINT; - break; - case TAG_TILE_MESH: - mElem.type = GeometryType.TRIS; - break; - } - - mMapDataSink.process(mElem); - - return true; - } - - private boolean decodeElementTags(int numTags) throws IOException { - if (mSArray.length < numTags) - mSArray = new int[numTags]; - int[] tagIds = mSArray; - - decodeVarintArray(numTags, tagIds); - - mElem.tags.clear(); - - int max = mTileTags.numTags - 1; - - for (int i = 0; i < numTags; i++) { - int idx = tagIds[i]; - - if (idx < 0 || idx > max) { - log.debug("{} invalid tag:{}", mTile, - Integer.valueOf(idx), - Integer.valueOf(i)); - return false; - } - mElem.tags.add(mTileTags.tags[idx]); - } - - return true; - } + static final Logger log = LoggerFactory.getLogger(TileDecoder.class); + + private static final int TAG_TILE_VERSION = 1; + //private static final int TAG_TILE_TIMESTAMP = 2; + //private static final int TAG_TILE_ISWATER = 3; + + private static final int TAG_TILE_NUM_TAGS = 11; + private static final int TAG_TILE_NUM_KEYS = 12; + private static final int TAG_TILE_NUM_VALUES = 13; + + private static final int TAG_TILE_TAG_KEYS = 14; + private static final int TAG_TILE_TAG_VALUES = 15; + private static final int TAG_TILE_TAGS = 16; + + private static final int TAG_TILE_LINE = 21; + private static final int TAG_TILE_POLY = 22; + private static final int TAG_TILE_POINT = 23; + /** + * since version 5 + */ + private static final int TAG_TILE_MESH = 24; + + private static final int TAG_ELEM_NUM_INDICES = 1; + private static final int TAG_ELEM_NUM_TAGS = 2; + /** + * since version 5 + */ + private static final int TAG_ELEM_NUM_COORDINATES = 3; + private static final int TAG_ELEM_TAGS = 11; + private static final int TAG_ELEM_INDEX = 12; + private static final int TAG_ELEM_COORDS = 13; + private static final int TAG_ELEM_LAYER = 21; + + private int[] mSArray = new int[100]; + + private Tile mTile; + + private final MapElement mElem; + + private final TagSet mTileTags; + private ITileDataSink mMapDataSink; + + private int mVersion; + + // scale coordinates to tile size + private final static float REF_TILE_SIZE = 4096.0f; + private final float mScaleFactor = REF_TILE_SIZE / Tile.SIZE; + + TileDecoder() { + mElem = new MapElement(); + mTileTags = new TagSet(100); + } + + @Override + public boolean decode(Tile tile, ITileDataSink sink, InputStream is) + throws IOException { + + readUnsignedInt(is, buffer); + setInputStream(is); + + mTile = tile; + mMapDataSink = sink; + + mTileTags.clearAndNullTags(); + + int val; + int numTags = 0; + int numKeys = -1; + int numValues = -1; + + int curKey = 0; + int curValue = 0; + + String[] keys = null; + String[] values = null; + + while (hasData() && (val = decodeVarint32()) > 0) { + // read tag and wire type + int tag = (val >> 3); + //log.debug("tag: " + tag); + + switch (tag) { + case TAG_TILE_LINE: + case TAG_TILE_POLY: + case TAG_TILE_POINT: + case TAG_TILE_MESH: + decodeTileElement(tag); + break; + + case TAG_TILE_TAG_KEYS: + if (keys == null || curKey >= numKeys) { + log.debug("{} wrong number of keys {}", + mTile, numKeys); + return false; + } + keys[curKey++] = decodeString().intern(); + break; + + case TAG_TILE_TAG_VALUES: + if (values == null || curValue >= numValues) { + log.debug("{} wrong number of values {}", + mTile, numValues); + return false; + } + values[curValue++] = decodeString(); + break; + + case TAG_TILE_NUM_TAGS: + numTags = decodeVarint32(); + //log.debug("num tags " + numTags); + break; + + case TAG_TILE_NUM_KEYS: + numKeys = decodeVarint32(); + //log.debug("num keys " + numKeys); + keys = new String[numKeys]; + break; + + case TAG_TILE_NUM_VALUES: + numValues = decodeVarint32(); + //log.debug("num values " + numValues); + values = new String[numValues]; + break; + + case TAG_TILE_TAGS: + int len = numTags * 2; + if (mSArray.length < len) + mSArray = new int[len]; + + decodeVarintArray(len, mSArray); + if (!decodeTileTags(numTags, mSArray, keys, values)) { + log.debug("{} invalid tags", mTile); + return false; + } + break; + + case TAG_TILE_VERSION: + int version = decodeVarint32(); + if (version < 4 || mVersion > 5) { + log.debug("{} invalid version:{}", + mTile, version); + return false; + } + break; + + default: + log.debug("{} invalid type for tile:{}", + mTile, tag); + return false; + } + } + + return true; + } + + private boolean decodeTileTags(int numTags, int[] tagIdx, + String[] keys, String[] vals) { + + Tag tag; + for (int i = 0, n = (numTags << 1); i < n; i += 2) { + int k = tagIdx[i]; + int v = tagIdx[i + 1]; + String key, val; + + if (k < Tags.ATTRIB_OFFSET) { + if (k > Tags.MAX_KEY) + return false; + key = Tags.keys[k]; + } else { + k -= Tags.ATTRIB_OFFSET; + if (k >= keys.length) + return false; + key = keys[k]; + } + + if (v < Tags.ATTRIB_OFFSET) { + if (v > Tags.MAX_VALUE) + return false; + val = Tags.values[v]; + } else { + v -= Tags.ATTRIB_OFFSET; + if (v >= vals.length) + return false; + val = vals[v]; + } + + // FIXME filter out all variable tags + // might depend on theme though + if (key == Tag.KEY_NAME + || key == Tag.KEY_HEIGHT + || key == Tag.KEY_MIN_HEIGHT + || key == Tag.KEY_HOUSE_NUMBER + || key == Tag.KEY_REF + || key == Tag.KEY_ELE) + tag = new Tag(key, val, false); + else + tag = new Tag(key, val, false, true); + + mTileTags.add(tag); + } + + return true; + } + + private int decodeWayIndices(int indexCnt, boolean shift) throws IOException { + mElem.ensureIndexSize(indexCnt, false); + decodeVarintArray(indexCnt, mElem.index); + + int[] index = mElem.index; + int coordCnt = 0; + + if (shift) { + for (int i = 0; i < indexCnt; i++) { + coordCnt += index[i]; + index[i] *= 2; + } + } + // set end marker + if (indexCnt < index.length) + index[indexCnt] = -1; + + return coordCnt; + } + + private boolean decodeTileElement(int type) throws IOException { + + int bytes = decodeVarint32(); + + int end = position() + bytes; + int numIndices = 1; + int numTags = 1; + + //boolean skip = false; + boolean fail = false; + + int coordCnt = 0; + if (type == TAG_TILE_POINT) { + coordCnt = 1; + mElem.index[0] = 2; + } + + mElem.layer = 5; + + while (position() < end) { + // read tag and wire type + int val = decodeVarint32(); + if (val == 0) + break; + + int tag = (val >> 3); + + switch (tag) { + case TAG_ELEM_TAGS: + if (!decodeElementTags(numTags)) + return false; + break; + + case TAG_ELEM_NUM_INDICES: + numIndices = decodeVarint32(); + break; + + case TAG_ELEM_NUM_TAGS: + numTags = decodeVarint32(); + break; + + case TAG_ELEM_NUM_COORDINATES: + coordCnt = decodeVarint32(); + break; + + case TAG_ELEM_INDEX: + if (type == TAG_TILE_MESH) { + decodeWayIndices(numIndices, false); + } else { + coordCnt = decodeWayIndices(numIndices, true); + // otherwise using TAG_ELEM_NUM_COORDINATES + } + break; + + case TAG_ELEM_COORDS: + if (coordCnt == 0) { + log.debug("{} no coordinates", mTile); + } + + if (type == TAG_TILE_MESH) { + mElem.ensurePointSize((coordCnt * 3 / 2), false); + int cnt = decodeInterleavedPoints3D(mElem.points, 1); + + if (cnt != (3 * coordCnt)) { + log.debug("{} wrong number of coordintes {}/{}", mTile, + Integer.valueOf(coordCnt), + Integer.valueOf(cnt)); + fail = true; + } + mElem.pointPos = cnt; + } else { + mElem.ensurePointSize(coordCnt, false); + int cnt = decodeInterleavedPoints(mElem, mScaleFactor); + + if (cnt != coordCnt) { + log.debug("{} wrong number of coordintes {}/{}", mTile, + Integer.valueOf(coordCnt), + Integer.valueOf(cnt)); + fail = true; + } + } + break; + + case TAG_ELEM_LAYER: + mElem.layer = decodeVarint32(); + break; + + default: + log.debug("{} invalid type for way: {}", mTile, tag); + } + } + + if (fail || numTags == 0 || numIndices == 0) { + log.debug("{} failed: bytes:{} tags:{} ({},{})", + mTile, Integer.valueOf(bytes), + mElem.tags, + Integer.valueOf(numIndices), + Integer.valueOf(coordCnt)); + return false; + } + + switch (type) { + case TAG_TILE_LINE: + mElem.type = GeometryType.LINE; + break; + case TAG_TILE_POLY: + mElem.type = GeometryType.POLY; + break; + case TAG_TILE_POINT: + mElem.type = GeometryType.POINT; + break; + case TAG_TILE_MESH: + mElem.type = GeometryType.TRIS; + break; + } + + mMapDataSink.process(mElem); + + return true; + } + + private boolean decodeElementTags(int numTags) throws IOException { + if (mSArray.length < numTags) + mSArray = new int[numTags]; + int[] tagIds = mSArray; + + decodeVarintArray(numTags, tagIds); + + mElem.tags.clear(); + + int max = mTileTags.numTags - 1; + + for (int i = 0; i < numTags; i++) { + int idx = tagIds[i]; + + if (idx < 0 || idx > max) { + log.debug("{} invalid tag:{}", mTile, + Integer.valueOf(idx), + Integer.valueOf(i)); + return false; + } + mElem.tags.add(mTileTags.tags[idx]); + } + + return true; + } } diff --git a/vtm/src/org/oscim/tiling/source/test/TestTileSource.java b/vtm/src/org/oscim/tiling/source/test/TestTileSource.java index b6404444..7ac2e719 100644 --- a/vtm/src/org/oscim/tiling/source/test/TestTileSource.java +++ b/vtm/src/org/oscim/tiling/source/test/TestTileSource.java @@ -16,8 +16,6 @@ */ package org.oscim.tiling.source.test; -import static org.oscim.tiling.QueryResult.SUCCESS; - import org.oscim.core.MapElement; import org.oscim.core.Tag; import org.oscim.core.Tile; @@ -26,170 +24,172 @@ import org.oscim.tiling.ITileDataSink; import org.oscim.tiling.ITileDataSource; import org.oscim.tiling.TileSource; +import static org.oscim.tiling.QueryResult.SUCCESS; + public class TestTileSource extends TileSource { - // private boolean mOpenFile = false; + // private boolean mOpenFile = false; - public TestTileSource() { - super(0, 18); - } + public TestTileSource() { + super(0, 18); + } - @Override - public ITileDataSource getDataSource() { - return new TileDataSource(); - } + @Override + public ITileDataSource getDataSource() { + return new TileDataSource(); + } - @Override - public OpenResult open() { - // mOpenFile =true; - return OpenResult.SUCCESS; - } + @Override + public OpenResult open() { + // mOpenFile =true; + return OpenResult.SUCCESS; + } - @Override - public void close() { - // mOpenFile = false; - } + @Override + public void close() { + // mOpenFile = false; + } - static class TileDataSource implements ITileDataSource { + static class TileDataSource implements ITileDataSource { - private static final Tag[] mTags = { - new Tag("natural", "water") - }; - private static final Tag[] mTagsWay = { - new Tag("highway", "primary"), - new Tag("name", "Highway Rd") - }; - private static final Tag[] mTagsBoundary = { - new Tag("boundary", "administrative"), - new Tag("admin_level", "2") - }; + private static final Tag[] mTags = { + new Tag("natural", "water") + }; + private static final Tag[] mTagsWay = { + new Tag("highway", "primary"), + new Tag("name", "Highway Rd") + }; + private static final Tag[] mTagsBoundary = { + new Tag("boundary", "administrative"), + new Tag("admin_level", "2") + }; - private static final Tag[] mTagsPlace = { - new Tag("place", "city"), - null - }; + private static final Tag[] mTagsPlace = { + new Tag("place", "city"), + null + }; - private final MapElement mElem; + private final MapElement mElem; - public TileDataSource() { - mElem = new MapElement(); - } + public TileDataSource() { + mElem = new MapElement(); + } - private boolean renderWays = true; - private boolean renderBoundary = true; - private boolean renderPlace = false; + private boolean renderWays = true; + private boolean renderBoundary = true; + private boolean renderPlace = false; - @Override - public void query(MapTile tile, ITileDataSink sink) { + @Override + public void query(MapTile tile, ITileDataSink sink) { - int size = Tile.SIZE; - MapElement e = mElem; + int size = Tile.SIZE; + MapElement e = mElem; - float x1 = -1; - float y1 = -1; - float x2 = size + 1; - float y2 = size + 1; + float x1 = -1; + float y1 = -1; + float x2 = size + 1; + float y2 = size + 1; - // always clear geometry before starting - // a different type. - e.clear(); - e.startPolygon(); - e.addPoint(x1, y1); - e.addPoint(x2, y1); - e.addPoint(x2, y2); - e.addPoint(x1, y2); + // always clear geometry before starting + // a different type. + e.clear(); + e.startPolygon(); + e.addPoint(x1, y1); + e.addPoint(x2, y1); + e.addPoint(x2, y2); + e.addPoint(x1, y2); - y1 = 5; - y2 = size - 5; - x1 = 5; - x2 = size - 5; + y1 = 5; + y2 = size - 5; + x1 = 5; + x2 = size - 5; - e.startHole(); - e.addPoint(x1, y1); - e.addPoint(x2, y1); - e.addPoint(x2, y2); - e.addPoint(x1, y2); + e.startHole(); + e.addPoint(x1, y1); + e.addPoint(x2, y1); + e.addPoint(x2, y2); + e.addPoint(x1, y2); - e.setLayer(0); - e.tags.set(mTags); - sink.process(e); + e.setLayer(0); + e.tags.set(mTags); + sink.process(e); - if (renderWays) { - e.clear(); + if (renderWays) { + e.clear(); - // middle horizontal - e.startLine(); - e.addPoint(0, size / 2); - e.addPoint(size, size / 2); + // middle horizontal + e.startLine(); + e.addPoint(0, size / 2); + e.addPoint(size, size / 2); - // center up - e.startLine(); - e.addPoint(size / 2, -size / 2); - e.addPoint(size / 2, size / 2); + // center up + e.startLine(); + e.addPoint(size / 2, -size / 2); + e.addPoint(size / 2, size / 2); - // center down - e.startLine(); - e.addPoint(size / 2, size / 2); - e.addPoint(size / 2, size / 2 + size); + // center down + e.startLine(); + e.addPoint(size / 2, size / 2); + e.addPoint(size / 2, size / 2 + size); - // //e.setLayer(mTagsWay, 0); - sink.process(e); + // //e.setLayer(mTagsWay, 0); + sink.process(e); - e.clear(); - // left-top to center - e.startLine(); - e.addPoint(size / 2, size / 2); - e.addPoint(10, 10); + e.clear(); + // left-top to center + e.startLine(); + e.addPoint(size / 2, size / 2); + e.addPoint(10, 10); - e.startLine(); - e.addPoint(0, 10); - e.addPoint(size, 10); + e.startLine(); + e.addPoint(0, 10); + e.addPoint(size, 10); - e.startLine(); - e.addPoint(10, 0); - e.addPoint(10, size); + e.startLine(); + e.addPoint(10, 0); + e.addPoint(10, size); - e.setLayer(1); - e.tags.set(mTagsWay); - sink.process(e); - } + e.setLayer(1); + e.tags.set(mTagsWay); + sink.process(e); + } - if (renderBoundary) { - e.clear(); - e.startPolygon(); - float r = size / 2; + if (renderBoundary) { + e.clear(); + e.startPolygon(); + float r = size / 2; - for (int i = 0; i < 360; i += 4) { - double d = Math.toRadians(i); - e.addPoint(r + (float) Math.cos(d) * (r - 40), - r + (float) Math.sin(d) * (r - 40)); - } + for (int i = 0; i < 360; i += 4) { + double d = Math.toRadians(i); + e.addPoint(r + (float) Math.cos(d) * (r - 40), + r + (float) Math.sin(d) * (r - 40)); + } - e.setLayer(1); - e.tags.set(mTagsBoundary); - sink.process(e); - } + e.setLayer(1); + e.tags.set(mTagsBoundary); + sink.process(e); + } - if (renderPlace) { - e.clear(); - e.startPoints(); - e.addPoint(size / 2, size / 2); + if (renderPlace) { + e.clear(); + e.startPoints(); + e.addPoint(size / 2, size / 2); - mTagsPlace[1] = new Tag("name", tile.toString()); - e.tags.set(mTagsPlace); - sink.process(e); - } + mTagsPlace[1] = new Tag("name", tile.toString()); + e.tags.set(mTagsPlace); + sink.process(e); + } - sink.completed(SUCCESS); - } + sink.completed(SUCCESS); + } - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public void cancel() { - } - } + @Override + public void cancel() { + } + } } diff --git a/vtm/src/org/oscim/utils/ArrayUtils.java b/vtm/src/org/oscim/utils/ArrayUtils.java index 937596b8..771d44d8 100644 --- a/vtm/src/org/oscim/utils/ArrayUtils.java +++ b/vtm/src/org/oscim/utils/ArrayUtils.java @@ -18,147 +18,147 @@ package org.oscim.utils; public class ArrayUtils { - public static void reverse(T[] data) { - reverse(data, 0, data.length); - } + public static void reverse(T[] data) { + reverse(data, 0, data.length); + } - public static void reverse(T[] data, int left, int right) { - right--; + public static void reverse(T[] data, int left, int right) { + right--; - while (left < right) { - T tmp = data[left]; - data[left] = data[right]; - data[right] = tmp; + while (left < right) { + T tmp = data[left]; + data[left] = data[right]; + data[right] = tmp; - left++; - right--; - } - } + left++; + right--; + } + } - public static void reverse(short[] data, int left, int right, int stride) { - right -= stride; + public static void reverse(short[] data, int left, int right, int stride) { + right -= stride; - while (left < right) { - for (int i = 0; i < stride; i++) { - short tmp = data[left + i]; - data[left + i] = data[right + i]; - data[right + i] = tmp; - } - left += stride; - right -= stride; - } - } + while (left < right) { + for (int i = 0; i < stride; i++) { + short tmp = data[left + i]; + data[left + i] = data[right + i]; + data[right + i] = tmp; + } + left += stride; + right -= stride; + } + } - public static void reverse(byte[] data, int left, int right) { - right -= 1; + public static void reverse(byte[] data, int left, int right) { + right -= 1; - while (left < right) { - byte tmp = data[left]; - data[left] = data[right]; - data[right] = tmp; + while (left < right) { + byte tmp = data[left]; + data[left] = data[right]; + data[right] = tmp; - left++; - right--; - } - } + left++; + right--; + } + } - public static double parseNumber(char[] str, int pos, int end) { + public static double parseNumber(char[] str, int pos, int end) { - boolean neg = false; - if (str[pos] == '-') { - neg = true; - pos++; - } + boolean neg = false; + if (str[pos] == '-') { + neg = true; + pos++; + } - double val = 0; - int pre = 0; - char c = 0; + double val = 0; + int pre = 0; + char c = 0; - for (; pos < end; pos++, pre++) { - c = str[pos]; - if (c < '0' || c > '9') { - if (pre == 0) - throw new NumberFormatException("s " + c); + for (; pos < end; pos++, pre++) { + c = str[pos]; + if (c < '0' || c > '9') { + if (pre == 0) + throw new NumberFormatException("s " + c); - break; - } - val = val * 10 + (int) (c - '0'); - } + break; + } + val = val * 10 + (int) (c - '0'); + } - if (pre == 0) - throw new NumberFormatException(); + if (pre == 0) + throw new NumberFormatException(); - if (c == '.') { - float div = 10; - for (pos++; pos < end; pos++) { - c = str[pos]; - if (c < '0' || c > '9') - break; - val = val + ((int) (c - '0')) / div; - div *= 10; - } - } + if (c == '.') { + float div = 10; + for (pos++; pos < end; pos++) { + c = str[pos]; + if (c < '0' || c > '9') + break; + val = val + ((int) (c - '0')) / div; + div *= 10; + } + } - if (c == 'e' || c == 'E') { - // advance 'e' - pos++; + if (c == 'e' || c == 'E') { + // advance 'e' + pos++; - // check direction - int dir = 1; - if (str[pos] == '-') { - dir = -1; - pos++; - } - // skip leading zeros - for (; pos < end; pos++) - if (str[pos] != '0') - break; + // check direction + int dir = 1; + if (str[pos] == '-') { + dir = -1; + pos++; + } + // skip leading zeros + for (; pos < end; pos++) + if (str[pos] != '0') + break; - int shift = 0; - for (pre = 0; pos < end; pos++, pre++) { - c = str[pos]; - if (c < '0' || c > '9') { - // nothing after 'e' - if (pre == 0) - throw new NumberFormatException("e " + c); - break; - } - shift = shift * 10 + (int) (c - '0'); - } + int shift = 0; + for (pre = 0; pos < end; pos++, pre++) { + c = str[pos]; + if (c < '0' || c > '9') { + // nothing after 'e' + if (pre == 0) + throw new NumberFormatException("e " + c); + break; + } + shift = shift * 10 + (int) (c - '0'); + } - // guess it's ok for sane values of E - if (dir > 0) { - while (shift-- > 0) - val *= 10; - } else { - while (shift-- > 0) - val /= 10; - } - } + // guess it's ok for sane values of E + if (dir > 0) { + while (shift-- > 0) + val *= 10; + } else { + while (shift-- > 0) + val /= 10; + } + } - return neg ? -val : val; - } + return neg ? -val : val; + } - public static boolean withinRange(float[] vec, float min, float max) { - for (int i = 0, n = vec.length; i < n; i++) { - float v = vec[i]; - if (v < min || v > max) - return false; - } - return true; - } + public static boolean withinRange(float[] vec, float min, float max) { + for (int i = 0, n = vec.length; i < n; i++) { + float v = vec[i]; + if (v < min || v > max) + return false; + } + return true; + } - /** - * Set bbox array to: - * xmin, ymin, - * xmin, ymax, - * xmax, ymax, - * xmax, ymin, - */ - public static void setBox2D(float[] bbox, float xmin, float ymin, float xmax, float ymax) { - bbox[0] = bbox[2] = xmin; - bbox[4] = bbox[6] = xmax; - bbox[1] = bbox[7] = ymin; - bbox[3] = bbox[5] = ymax; - } + /** + * Set bbox array to: + * xmin, ymin, + * xmin, ymax, + * xmax, ymax, + * xmax, ymin, + */ + public static void setBox2D(float[] bbox, float xmin, float ymin, float xmax, float ymax) { + bbox[0] = bbox[2] = xmin; + bbox[4] = bbox[6] = xmax; + bbox[1] = bbox[7] = ymin; + bbox[3] = bbox[5] = ymax; + } } diff --git a/vtm/src/org/oscim/utils/ColorUtil.java b/vtm/src/org/oscim/utils/ColorUtil.java index 26145e21..268cd9b6 100644 --- a/vtm/src/org/oscim/utils/ColorUtil.java +++ b/vtm/src/org/oscim/utils/ColorUtil.java @@ -1,256 +1,256 @@ package org.oscim.utils; +import org.oscim.backend.canvas.Color; +import org.oscim.utils.math.Vec3; + import static org.oscim.backend.canvas.Color.b; import static org.oscim.backend.canvas.Color.g; import static org.oscim.backend.canvas.Color.r; import static org.oscim.utils.FastMath.clamp; -import org.oscim.backend.canvas.Color; -import org.oscim.utils.math.Vec3; - public class ColorUtil { - private final static Vec3 TMP_VEC = new Vec3(); + private final static Vec3 TMP_VEC = new Vec3(); - public static synchronized int desaturate(int color) { - Vec3 hsl = TMP_VEC; - rgbToHsl(r(color), g(color), b(color), hsl); - return hslToRgb(hsl.x, 0, hsl.z); - } + public static synchronized int desaturate(int color) { + Vec3 hsl = TMP_VEC; + rgbToHsl(r(color), g(color), b(color), hsl); + return hslToRgb(hsl.x, 0, hsl.z); + } - public static synchronized int saturate(int color, double saturation) { - Vec3 hsl = TMP_VEC; - rgbToHsv(r(color), g(color), b(color), hsl); - return hsvToRgb(hsl.x, saturation, hsl.z); - } + public static synchronized int saturate(int color, double saturation) { + Vec3 hsl = TMP_VEC; + rgbToHsv(r(color), g(color), b(color), hsl); + return hsvToRgb(hsl.x, saturation, hsl.z); + } - public static synchronized int setHue(int color, double hue) { - Vec3 hsl = TMP_VEC; - rgbToHsv(r(color), g(color), b(color), hsl); - return hsvToRgb(hue, hsl.y, hsl.z, null); - } + public static synchronized int setHue(int color, double hue) { + Vec3 hsl = TMP_VEC; + rgbToHsv(r(color), g(color), b(color), hsl); + return hsvToRgb(hue, hsl.y, hsl.z, null); + } - public static synchronized int shiftHue(int color, double hue) { - Vec3 hsv = TMP_VEC; - rgbToHsv(r(color), g(color), b(color), hsv); - hsv.x += hue; - hsv.x -= Math.floor(hsv.x); + public static synchronized int shiftHue(int color, double hue) { + Vec3 hsv = TMP_VEC; + rgbToHsv(r(color), g(color), b(color), hsv); + hsv.x += hue; + hsv.x -= Math.floor(hsv.x); - return hsvToRgb(clamp(hsv.x, 0, 1), hsv.y, hsv.z, null); - } + return hsvToRgb(clamp(hsv.x, 0, 1), hsv.y, hsv.z, null); + } - public static synchronized int saturate(int color, double saturation, boolean relative) { - Vec3 hsl = TMP_VEC; - rgbToHsv(r(color), g(color), b(color), hsl); - return hsvToRgb(hsl.x, clamp(saturation * hsl.y, 0, 1), hsl.z); - } + public static synchronized int saturate(int color, double saturation, boolean relative) { + Vec3 hsl = TMP_VEC; + rgbToHsv(r(color), g(color), b(color), hsl); + return hsvToRgb(hsl.x, clamp(saturation * hsl.y, 0, 1), hsl.z); + } - public static synchronized int modHsv(int color, double hue, double saturation, double value, - boolean relative) { - Vec3 hsl = TMP_VEC; - rgbToHsv(r(color), g(color), b(color), hsl); - return hsvToRgb(clamp(hue * hsl.x, 0, 1), - clamp(saturation * hsl.y, 0, 1), - clamp(value * hsl.z, 0, 1)); - } + public static synchronized int modHsv(int color, double hue, double saturation, double value, + boolean relative) { + Vec3 hsl = TMP_VEC; + rgbToHsv(r(color), g(color), b(color), hsl); + return hsvToRgb(clamp(hue * hsl.x, 0, 1), + clamp(saturation * hsl.y, 0, 1), + clamp(value * hsl.z, 0, 1)); + } - // functions ported from http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c + // functions ported from http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c - /** - * Converts an RGB color value to HSL. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes r, g, and b are contained in the set [0, 255] and - * returns h, s, and l in the set [0, 1]. - * - * @param Number r The red color value - * @param Number g The green color value - * @param Number b The blue color value - * @return Array The HSL representation - */ - public static Vec3 rgbToHsl(double r, double g, double b, Vec3 out) { - r /= 255d; - g /= 255d; - b /= 255d; + /** + * Converts an RGB color value to HSL. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes r, g, and b are contained in the set [0, 255] and + * returns h, s, and l in the set [0, 1]. + * + * @param Number r The red color value + * @param Number g The green color value + * @param Number b The blue color value + * @return Array The HSL representation + */ + public static Vec3 rgbToHsl(double r, double g, double b, Vec3 out) { + r /= 255d; + g /= 255d; + b /= 255d; - double max = Math.max(r, Math.max(g, b)); - double min = Math.min(r, Math.min(g, b)); + double max = Math.max(r, Math.max(g, b)); + double min = Math.min(r, Math.min(g, b)); - double h = 0, s = 0, l = (max + min) / 2; + double h = 0, s = 0, l = (max + min) / 2; - if (max != min) { - double d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - if (max == r) - h = (g - b) / d + (g < b ? 6 : 0); - else if (max == g) - h = (b - r) / d + 2; - else - h = (r - g) / d + 4; + if (max != min) { + double d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + if (max == r) + h = (g - b) / d + (g < b ? 6 : 0); + else if (max == g) + h = (b - r) / d + 2; + else + h = (r - g) / d + 4; - h /= 6; - } + h /= 6; + } - out.set(h, s, l); + out.set(h, s, l); - return out; - } + return out; + } - public static Vec3 rgbToHsl(double r, double g, double b) { - return rgbToHsl(r, g, b, new Vec3()); - } + public static Vec3 rgbToHsl(double r, double g, double b) { + return rgbToHsl(r, g, b, new Vec3()); + } - /** - * Converts an HSL color value to RGB. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes h, s, and l are contained in the set [0, 1] and - * returns r, g, and b in the set [0, 255]. - * - * @param Number h The hue - * @param Number s The saturation - * @param Number l The lightness - * @return Array The RGB representation - */ - public static int hslToRgb(double h, double s, double l, Vec3 out) { - double r, g, b; + /** + * Converts an HSL color value to RGB. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes h, s, and l are contained in the set [0, 1] and + * returns r, g, and b in the set [0, 255]. + * + * @param Number h The hue + * @param Number s The saturation + * @param Number l The lightness + * @return Array The RGB representation + */ + public static int hslToRgb(double h, double s, double l, Vec3 out) { + double r, g, b; - if (s == 0) { - r = g = b = l; // achromatic - } else { - double q = l < 0.5 ? l * (1 + s) : l + s - l * s; - double p = 2 * l - q; - r = hue2rgb(p, q, h + 1 / 3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1 / 3); - } + if (s == 0) { + r = g = b = l; // achromatic + } else { + double q = l < 0.5 ? l * (1 + s) : l + s - l * s; + double p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } - if (out != null) - out.set(r, g, b); + if (out != null) + out.set(r, g, b); - return Color.get(r, g, b); - } + return Color.get(r, g, b); + } - static double hue2rgb(double p, double q, double t) { - if (t < 0) - t += 1; - if (t > 1) - t -= 1; - if (t < 1 / 6) - return p + (q - p) * 6 * t; - if (t < 1 / 2) - return q; - if (t < 2 / 3) - return p + (q - p) * (2 / 3 - t) * 6; - return p; - } + static double hue2rgb(double p, double q, double t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * (2 / 3 - t) * 6; + return p; + } - /** - * Converts an RGB color value to HSV. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSV_color_space. - * Assumes r, g, and b are contained in the set [0, 255] and - * returns h, s, and v in the set [0, 1]. - * - * @param Number r The red color value - * @param Number g The green color value - * @param Number b The blue color value - * @return Array The HSV representation - */ - public static Vec3 rgbToHsv(double r, double g, double b, Vec3 out) { - r /= 255d; - g /= 255d; - b /= 255d; + /** + * Converts an RGB color value to HSV. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSV_color_space. + * Assumes r, g, and b are contained in the set [0, 255] and + * returns h, s, and v in the set [0, 1]. + * + * @param Number r The red color value + * @param Number g The green color value + * @param Number b The blue color value + * @return Array The HSV representation + */ + public static Vec3 rgbToHsv(double r, double g, double b, Vec3 out) { + r /= 255d; + g /= 255d; + b /= 255d; - double max = Math.max(r, Math.max(g, b)); - double min = Math.min(r, Math.min(g, b)); + double max = Math.max(r, Math.max(g, b)); + double min = Math.min(r, Math.min(g, b)); - double h = 0, s, v = max; + double h = 0, s, v = max; - double d = max - min; - s = max == 0 ? 0 : d / max; + double d = max - min; + s = max == 0 ? 0 : d / max; - if (max != min) { - if (max == r) - h = (g - b) / d + (g < b ? 6 : 0); - else if (max == g) - h = (b - r) / d + 2; - else if (max == b) - h = (r - g) / d + 4; - h /= 6; - } + if (max != min) { + if (max == r) + h = (g - b) / d + (g < b ? 6 : 0); + else if (max == g) + h = (b - r) / d + 2; + else if (max == b) + h = (r - g) / d + 4; + h /= 6; + } - out.set(h, s, v); + out.set(h, s, v); - return out; - } + return out; + } - public static Vec3 rgbToHsv(double r, double g, double b) { - return rgbToHsv(r, g, b, new Vec3()); - } + public static Vec3 rgbToHsv(double r, double g, double b) { + return rgbToHsv(r, g, b, new Vec3()); + } - /** - * Converts an HSV color value to RGB. Conversion formula - * adapted from http://en.wikipedia.org/wiki/HSV_color_space. - * Assumes h, s, and v are contained in the set [0, 1] and - * returns r, g, and b in the set [0, 255]. - * - * @param h The hue - * @param s The saturation - * @param v The value - * @param out result rgb, may be ommited - * @return Array The RGB representation - */ - public static int hsvToRgb(double h, double s, double v, Vec3 out) { - double r = 0, g = 0, b = 0; + /** + * Converts an HSV color value to RGB. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSV_color_space. + * Assumes h, s, and v are contained in the set [0, 1] and + * returns r, g, and b in the set [0, 255]. + * + * @param h The hue + * @param s The saturation + * @param v The value + * @param out result rgb, may be ommited + * @return Array The RGB representation + */ + public static int hsvToRgb(double h, double s, double v, Vec3 out) { + double r = 0, g = 0, b = 0; - int i = (int) Math.floor(h * 6); - double f = h * 6 - i; - double p = v * (1 - s); - double q = v * (1 - f * s); - double t = v * (1 - (1 - f) * s); + int i = (int) Math.floor(h * 6); + double f = h * 6 - i; + double p = v * (1 - s); + double q = v * (1 - f * s); + double t = v * (1 - (1 - f) * s); - switch (i % 6) { - case 0: - r = v; - g = t; - b = p; - break; - case 1: - r = q; - g = v; - b = p; - break; - case 2: - r = p; - g = v; - b = t; - break; - case 3: - r = p; - g = q; - b = v; - break; - case 4: - r = t; - g = p; - b = v; - break; - case 5: - r = v; - g = p; - b = q; - break; - } + switch (i % 6) { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } - if (out != null) - out.set(r, g, b); + if (out != null) + out.set(r, g, b); - return Color.get(r, g, b); - } + return Color.get(r, g, b); + } - public static int hsvToRgb(double h, double s, double v) { - return hsvToRgb(h, s, v, null); - } + public static int hsvToRgb(double h, double s, double v) { + return hsvToRgb(h, s, v, null); + } - public static int hslToRgb(double h, double s, double l) { - return hslToRgb(h, s, l, null); - } + public static int hslToRgb(double h, double s, double l) { + return hslToRgb(h, s, l, null); + } } diff --git a/vtm/src/org/oscim/utils/ColorsCSS.java b/vtm/src/org/oscim/utils/ColorsCSS.java index e3b4cd81..832e22c7 100644 --- a/vtm/src/org/oscim/utils/ColorsCSS.java +++ b/vtm/src/org/oscim/utils/ColorsCSS.java @@ -7,164 +7,164 @@ import java.util.HashMap; */ public class ColorsCSS { - static HashMap sColors; + static HashMap sColors; - public static Integer get(String name) { - if (sColors == null) - init(); + public static Integer get(String name) { + if (sColors == null) + init(); - return sColors.get(name); - } + return sColors.get(name); + } - static void init() { - sColors = new HashMap(); + static void init() { + sColors = new HashMap(); - sColors.put("aliceblue", Integer.valueOf(0xFFF0F8FF)); - sColors.put("antiquewhite", Integer.valueOf(0xFFFAEBD7)); - sColors.put("aqua", Integer.valueOf(0xFF00FFFF)); - sColors.put("aquamarine", Integer.valueOf(0xFF7FFFD4)); - sColors.put("azure", Integer.valueOf(0xFFF0FFFF)); - sColors.put("beige", Integer.valueOf(0xFFF5F5DC)); - sColors.put("bisque", Integer.valueOf(0xFFFFE4C4)); - sColors.put("black", Integer.valueOf(0xFF000000)); - sColors.put("blanchedalmond", Integer.valueOf(0xFFFFEBCD)); - sColors.put("blue", Integer.valueOf(0xFF0000FF)); - sColors.put("blueviolet", Integer.valueOf(0xFF8A2BE2)); - sColors.put("brown", Integer.valueOf(0xFFA52A2A)); - sColors.put("burlywood", Integer.valueOf(0xFFDEB887)); - sColors.put("cadetblue", Integer.valueOf(0xFF5F9EA0)); - sColors.put("chartreuse", Integer.valueOf(0xFF7FFF00)); - sColors.put("chocolate", Integer.valueOf(0xFFD2691E)); - sColors.put("coral", Integer.valueOf(0xFFFF7F50)); - sColors.put("cornflowerblue", Integer.valueOf(0xFF6495ED)); - sColors.put("cornsilk", Integer.valueOf(0xFFFFF8DC)); - sColors.put("crimson", Integer.valueOf(0xFFDC143C)); - sColors.put("cyan", Integer.valueOf(0xFF00FFFF)); - sColors.put("darkblue", Integer.valueOf(0xFF00008B)); - sColors.put("darkcyan", Integer.valueOf(0xFF008B8B)); - sColors.put("darkgoldenrod", Integer.valueOf(0xFFB8860B)); - sColors.put("darkgray", Integer.valueOf(0xFFA9A9A9)); - sColors.put("darkgreen", Integer.valueOf(0xFF006400)); - sColors.put("darkgrey", Integer.valueOf(0xFFA9A9A9)); - sColors.put("darkkhaki", Integer.valueOf(0xFFBDB76B)); - sColors.put("darkmagenta", Integer.valueOf(0xFF8B008B)); - sColors.put("darkolivegreen", Integer.valueOf(0xFF556B2F)); - sColors.put("darkorange", Integer.valueOf(0xFFFF8C00)); - sColors.put("darkorchid", Integer.valueOf(0xFF9932CC)); - sColors.put("darkred", Integer.valueOf(0xFF8B0000)); - sColors.put("darksalmon", Integer.valueOf(0xFFE9967A)); - sColors.put("darkseagreen", Integer.valueOf(0xFF8FBC8F)); - sColors.put("darkslateblue", Integer.valueOf(0xFF483D8B)); - sColors.put("darkslategray", Integer.valueOf(0xFF2F4F4F)); - sColors.put("darkslategrey", Integer.valueOf(0xFF2F4F4F)); - sColors.put("darkturquoise", Integer.valueOf(0xFF00CED1)); - sColors.put("darkviolet", Integer.valueOf(0xFF9400D3)); - sColors.put("deeppink", Integer.valueOf(0xFFFF1493)); - sColors.put("deepskyblue", Integer.valueOf(0xFF00BFFF)); - sColors.put("dimgray", Integer.valueOf(0xFF696969)); - sColors.put("dimgrey", Integer.valueOf(0xFF696969)); - sColors.put("dodgerblue", Integer.valueOf(0xFF1E90FF)); - sColors.put("firebrick", Integer.valueOf(0xFFB22222)); - sColors.put("floralwhite", Integer.valueOf(0xFFFFFAF0)); - sColors.put("forestgreen", Integer.valueOf(0xFF228B22)); - sColors.put("fuchsia", Integer.valueOf(0xFFFF00FF)); - sColors.put("gainsboro", Integer.valueOf(0xFFDCDCDC)); - sColors.put("ghostwhite", Integer.valueOf(0xFFF8F8FF)); - sColors.put("gold", Integer.valueOf(0xFFFFD700)); - sColors.put("goldenrod", Integer.valueOf(0xFFDAA520)); - sColors.put("gray", Integer.valueOf(0xFF808080)); - sColors.put("green", Integer.valueOf(0xFF008000)); - sColors.put("greenyellow", Integer.valueOf(0xFFADFF2F)); - sColors.put("grey", Integer.valueOf(0xFF808080)); - sColors.put("honeydew", Integer.valueOf(0xFFF0FFF0)); - sColors.put("hotpink", Integer.valueOf(0xFFFF69B4)); - sColors.put("indianred", Integer.valueOf(0xFFCD5C5C)); - sColors.put("indigo", Integer.valueOf(0xFF4B0082)); - sColors.put("ivory", Integer.valueOf(0xFFFFFFF0)); - sColors.put("khaki", Integer.valueOf(0xFFF0E68C)); - sColors.put("lavender", Integer.valueOf(0xFFE6E6FA)); - sColors.put("lavenderblush", Integer.valueOf(0xFFFFF0F5)); - sColors.put("lawngreen", Integer.valueOf(0xFF7CFC00)); - sColors.put("lemonchiffon", Integer.valueOf(0xFFFFFACD)); - sColors.put("lightblue", Integer.valueOf(0xFFADD8E6)); - sColors.put("lightcoral", Integer.valueOf(0xFFF08080)); - sColors.put("lightcyan", Integer.valueOf(0xFFE0FFFF)); - sColors.put("lightgoldenrodyellow", Integer.valueOf(0xFFFAFAD2)); - sColors.put("lightgray", Integer.valueOf(0xFFD3D3D3)); - sColors.put("lightgreen", Integer.valueOf(0xFF90EE90)); - sColors.put("lightgrey", Integer.valueOf(0xFFD3D3D3)); - sColors.put("lightpink", Integer.valueOf(0xFFFFB6C1)); - sColors.put("lightsalmon", Integer.valueOf(0xFFFFA07A)); - sColors.put("lightseagreen", Integer.valueOf(0xFF20B2AA)); - sColors.put("lightskyblue", Integer.valueOf(0xFF87CEFA)); - sColors.put("lightslategray", Integer.valueOf(0xFF778899)); - sColors.put("lightslategrey", Integer.valueOf(0xFF778899)); - sColors.put("lightsteelblue", Integer.valueOf(0xFFB0C4DE)); - sColors.put("lightyellow", Integer.valueOf(0xFFFFFFE0)); - sColors.put("lime", Integer.valueOf(0xFF00FF00)); - sColors.put("limegreen", Integer.valueOf(0xFF32CD32)); - sColors.put("linen", Integer.valueOf(0xFFFAF0E6)); - sColors.put("magenta", Integer.valueOf(0xFFFF00FF)); - sColors.put("maroon", Integer.valueOf(0xFF800000)); - sColors.put("mediumaquamarine", Integer.valueOf(0xFF66CDAA)); - sColors.put("mediumblue", Integer.valueOf(0xFF0000CD)); - sColors.put("mediumorchid", Integer.valueOf(0xFFBA55D3)); - sColors.put("mediumpurple", Integer.valueOf(0xFF9370DB)); - sColors.put("mediumseagreen", Integer.valueOf(0xFF3CB371)); - sColors.put("mediumslateblue", Integer.valueOf(0xFF7B68EE)); - sColors.put("mediumspringgreen", Integer.valueOf(0xFF00FA9A)); - sColors.put("mediumturquoise", Integer.valueOf(0xFF48D1CC)); - sColors.put("mediumvioletred", Integer.valueOf(0xFFC71585)); - sColors.put("midnightblue", Integer.valueOf(0xFF191970)); - sColors.put("mintcream", Integer.valueOf(0xFFF5FFFA)); - sColors.put("mistyrose", Integer.valueOf(0xFFFFE4E1)); - sColors.put("moccasin", Integer.valueOf(0xFFFFE4B5)); - sColors.put("navajowhite", Integer.valueOf(0xFFFFDEAD)); - sColors.put("navy", Integer.valueOf(0xFF000080)); - sColors.put("oldlace", Integer.valueOf(0xFFFDF5E6)); - sColors.put("olive", Integer.valueOf(0xFF808000)); - sColors.put("olivedrab", Integer.valueOf(0xFF6B8E23)); - sColors.put("orange", Integer.valueOf(0xFFFFA500)); - sColors.put("orangered", Integer.valueOf(0xFFFF4500)); - sColors.put("orchid", Integer.valueOf(0xFFDA70D6)); - sColors.put("palegoldenrod", Integer.valueOf(0xFFEEE8AA)); - sColors.put("palegreen", Integer.valueOf(0xFF98FB98)); - sColors.put("paleturquoise", Integer.valueOf(0xFFAFEEEE)); - sColors.put("palevioletred", Integer.valueOf(0xFFDB7093)); - sColors.put("papayawhip", Integer.valueOf(0xFFFFEFD5)); - sColors.put("peachpuff", Integer.valueOf(0xFFFFDAB9)); - sColors.put("peru", Integer.valueOf(0xFFCD853F)); - sColors.put("pink", Integer.valueOf(0xFFFFC0CB)); - sColors.put("plum", Integer.valueOf(0xFFDDA0DD)); - sColors.put("powderblue", Integer.valueOf(0xFFB0E0E6)); - sColors.put("purple", Integer.valueOf(0xFF800080)); - sColors.put("red", Integer.valueOf(0xFFFF0000)); - sColors.put("rosybrown", Integer.valueOf(0xFFBC8F8F)); - sColors.put("royalblue", Integer.valueOf(0xFF4169E1)); - sColors.put("saddlebrown", Integer.valueOf(0xFF8B4513)); - sColors.put("salmon", Integer.valueOf(0xFFFA8072)); - sColors.put("sandybrown", Integer.valueOf(0xFFF4A460)); - sColors.put("seagreen", Integer.valueOf(0xFF2E8B57)); - sColors.put("seashell", Integer.valueOf(0xFFFFF5EE)); - sColors.put("sienna", Integer.valueOf(0xFFA0522D)); - sColors.put("silver", Integer.valueOf(0xFFC0C0C0)); - sColors.put("skyblue", Integer.valueOf(0xFF87CEEB)); - sColors.put("slateblue", Integer.valueOf(0xFF6A5ACD)); - sColors.put("slategray", Integer.valueOf(0xFF708090)); - sColors.put("slategrey", Integer.valueOf(0xFF708090)); - sColors.put("snow", Integer.valueOf(0xFFFFFAFA)); - sColors.put("springgreen", Integer.valueOf(0xFF00FF7F)); - sColors.put("steelblue", Integer.valueOf(0xFF4682B4)); - sColors.put("tan", Integer.valueOf(0xFFD2B48C)); - sColors.put("teal", Integer.valueOf(0xFF008080)); - sColors.put("thistle", Integer.valueOf(0xFFD8BFD8)); - sColors.put("tomato", Integer.valueOf(0xFFFF6347)); - sColors.put("turquoise", Integer.valueOf(0xFF40E0D0)); - sColors.put("violet", Integer.valueOf(0xFFEE82EE)); - sColors.put("wheat", Integer.valueOf(0xFFF5DEB3)); - sColors.put("white", Integer.valueOf(0xFFFFFFFF)); - sColors.put("whitesmoke", Integer.valueOf(0xFFF5F5F5)); - sColors.put("yellow", Integer.valueOf(0xFFFFFF00)); - sColors.put("yellowgreen", Integer.valueOf(0xFF9ACD32)); - } + sColors.put("aliceblue", Integer.valueOf(0xFFF0F8FF)); + sColors.put("antiquewhite", Integer.valueOf(0xFFFAEBD7)); + sColors.put("aqua", Integer.valueOf(0xFF00FFFF)); + sColors.put("aquamarine", Integer.valueOf(0xFF7FFFD4)); + sColors.put("azure", Integer.valueOf(0xFFF0FFFF)); + sColors.put("beige", Integer.valueOf(0xFFF5F5DC)); + sColors.put("bisque", Integer.valueOf(0xFFFFE4C4)); + sColors.put("black", Integer.valueOf(0xFF000000)); + sColors.put("blanchedalmond", Integer.valueOf(0xFFFFEBCD)); + sColors.put("blue", Integer.valueOf(0xFF0000FF)); + sColors.put("blueviolet", Integer.valueOf(0xFF8A2BE2)); + sColors.put("brown", Integer.valueOf(0xFFA52A2A)); + sColors.put("burlywood", Integer.valueOf(0xFFDEB887)); + sColors.put("cadetblue", Integer.valueOf(0xFF5F9EA0)); + sColors.put("chartreuse", Integer.valueOf(0xFF7FFF00)); + sColors.put("chocolate", Integer.valueOf(0xFFD2691E)); + sColors.put("coral", Integer.valueOf(0xFFFF7F50)); + sColors.put("cornflowerblue", Integer.valueOf(0xFF6495ED)); + sColors.put("cornsilk", Integer.valueOf(0xFFFFF8DC)); + sColors.put("crimson", Integer.valueOf(0xFFDC143C)); + sColors.put("cyan", Integer.valueOf(0xFF00FFFF)); + sColors.put("darkblue", Integer.valueOf(0xFF00008B)); + sColors.put("darkcyan", Integer.valueOf(0xFF008B8B)); + sColors.put("darkgoldenrod", Integer.valueOf(0xFFB8860B)); + sColors.put("darkgray", Integer.valueOf(0xFFA9A9A9)); + sColors.put("darkgreen", Integer.valueOf(0xFF006400)); + sColors.put("darkgrey", Integer.valueOf(0xFFA9A9A9)); + sColors.put("darkkhaki", Integer.valueOf(0xFFBDB76B)); + sColors.put("darkmagenta", Integer.valueOf(0xFF8B008B)); + sColors.put("darkolivegreen", Integer.valueOf(0xFF556B2F)); + sColors.put("darkorange", Integer.valueOf(0xFFFF8C00)); + sColors.put("darkorchid", Integer.valueOf(0xFF9932CC)); + sColors.put("darkred", Integer.valueOf(0xFF8B0000)); + sColors.put("darksalmon", Integer.valueOf(0xFFE9967A)); + sColors.put("darkseagreen", Integer.valueOf(0xFF8FBC8F)); + sColors.put("darkslateblue", Integer.valueOf(0xFF483D8B)); + sColors.put("darkslategray", Integer.valueOf(0xFF2F4F4F)); + sColors.put("darkslategrey", Integer.valueOf(0xFF2F4F4F)); + sColors.put("darkturquoise", Integer.valueOf(0xFF00CED1)); + sColors.put("darkviolet", Integer.valueOf(0xFF9400D3)); + sColors.put("deeppink", Integer.valueOf(0xFFFF1493)); + sColors.put("deepskyblue", Integer.valueOf(0xFF00BFFF)); + sColors.put("dimgray", Integer.valueOf(0xFF696969)); + sColors.put("dimgrey", Integer.valueOf(0xFF696969)); + sColors.put("dodgerblue", Integer.valueOf(0xFF1E90FF)); + sColors.put("firebrick", Integer.valueOf(0xFFB22222)); + sColors.put("floralwhite", Integer.valueOf(0xFFFFFAF0)); + sColors.put("forestgreen", Integer.valueOf(0xFF228B22)); + sColors.put("fuchsia", Integer.valueOf(0xFFFF00FF)); + sColors.put("gainsboro", Integer.valueOf(0xFFDCDCDC)); + sColors.put("ghostwhite", Integer.valueOf(0xFFF8F8FF)); + sColors.put("gold", Integer.valueOf(0xFFFFD700)); + sColors.put("goldenrod", Integer.valueOf(0xFFDAA520)); + sColors.put("gray", Integer.valueOf(0xFF808080)); + sColors.put("green", Integer.valueOf(0xFF008000)); + sColors.put("greenyellow", Integer.valueOf(0xFFADFF2F)); + sColors.put("grey", Integer.valueOf(0xFF808080)); + sColors.put("honeydew", Integer.valueOf(0xFFF0FFF0)); + sColors.put("hotpink", Integer.valueOf(0xFFFF69B4)); + sColors.put("indianred", Integer.valueOf(0xFFCD5C5C)); + sColors.put("indigo", Integer.valueOf(0xFF4B0082)); + sColors.put("ivory", Integer.valueOf(0xFFFFFFF0)); + sColors.put("khaki", Integer.valueOf(0xFFF0E68C)); + sColors.put("lavender", Integer.valueOf(0xFFE6E6FA)); + sColors.put("lavenderblush", Integer.valueOf(0xFFFFF0F5)); + sColors.put("lawngreen", Integer.valueOf(0xFF7CFC00)); + sColors.put("lemonchiffon", Integer.valueOf(0xFFFFFACD)); + sColors.put("lightblue", Integer.valueOf(0xFFADD8E6)); + sColors.put("lightcoral", Integer.valueOf(0xFFF08080)); + sColors.put("lightcyan", Integer.valueOf(0xFFE0FFFF)); + sColors.put("lightgoldenrodyellow", Integer.valueOf(0xFFFAFAD2)); + sColors.put("lightgray", Integer.valueOf(0xFFD3D3D3)); + sColors.put("lightgreen", Integer.valueOf(0xFF90EE90)); + sColors.put("lightgrey", Integer.valueOf(0xFFD3D3D3)); + sColors.put("lightpink", Integer.valueOf(0xFFFFB6C1)); + sColors.put("lightsalmon", Integer.valueOf(0xFFFFA07A)); + sColors.put("lightseagreen", Integer.valueOf(0xFF20B2AA)); + sColors.put("lightskyblue", Integer.valueOf(0xFF87CEFA)); + sColors.put("lightslategray", Integer.valueOf(0xFF778899)); + sColors.put("lightslategrey", Integer.valueOf(0xFF778899)); + sColors.put("lightsteelblue", Integer.valueOf(0xFFB0C4DE)); + sColors.put("lightyellow", Integer.valueOf(0xFFFFFFE0)); + sColors.put("lime", Integer.valueOf(0xFF00FF00)); + sColors.put("limegreen", Integer.valueOf(0xFF32CD32)); + sColors.put("linen", Integer.valueOf(0xFFFAF0E6)); + sColors.put("magenta", Integer.valueOf(0xFFFF00FF)); + sColors.put("maroon", Integer.valueOf(0xFF800000)); + sColors.put("mediumaquamarine", Integer.valueOf(0xFF66CDAA)); + sColors.put("mediumblue", Integer.valueOf(0xFF0000CD)); + sColors.put("mediumorchid", Integer.valueOf(0xFFBA55D3)); + sColors.put("mediumpurple", Integer.valueOf(0xFF9370DB)); + sColors.put("mediumseagreen", Integer.valueOf(0xFF3CB371)); + sColors.put("mediumslateblue", Integer.valueOf(0xFF7B68EE)); + sColors.put("mediumspringgreen", Integer.valueOf(0xFF00FA9A)); + sColors.put("mediumturquoise", Integer.valueOf(0xFF48D1CC)); + sColors.put("mediumvioletred", Integer.valueOf(0xFFC71585)); + sColors.put("midnightblue", Integer.valueOf(0xFF191970)); + sColors.put("mintcream", Integer.valueOf(0xFFF5FFFA)); + sColors.put("mistyrose", Integer.valueOf(0xFFFFE4E1)); + sColors.put("moccasin", Integer.valueOf(0xFFFFE4B5)); + sColors.put("navajowhite", Integer.valueOf(0xFFFFDEAD)); + sColors.put("navy", Integer.valueOf(0xFF000080)); + sColors.put("oldlace", Integer.valueOf(0xFFFDF5E6)); + sColors.put("olive", Integer.valueOf(0xFF808000)); + sColors.put("olivedrab", Integer.valueOf(0xFF6B8E23)); + sColors.put("orange", Integer.valueOf(0xFFFFA500)); + sColors.put("orangered", Integer.valueOf(0xFFFF4500)); + sColors.put("orchid", Integer.valueOf(0xFFDA70D6)); + sColors.put("palegoldenrod", Integer.valueOf(0xFFEEE8AA)); + sColors.put("palegreen", Integer.valueOf(0xFF98FB98)); + sColors.put("paleturquoise", Integer.valueOf(0xFFAFEEEE)); + sColors.put("palevioletred", Integer.valueOf(0xFFDB7093)); + sColors.put("papayawhip", Integer.valueOf(0xFFFFEFD5)); + sColors.put("peachpuff", Integer.valueOf(0xFFFFDAB9)); + sColors.put("peru", Integer.valueOf(0xFFCD853F)); + sColors.put("pink", Integer.valueOf(0xFFFFC0CB)); + sColors.put("plum", Integer.valueOf(0xFFDDA0DD)); + sColors.put("powderblue", Integer.valueOf(0xFFB0E0E6)); + sColors.put("purple", Integer.valueOf(0xFF800080)); + sColors.put("red", Integer.valueOf(0xFFFF0000)); + sColors.put("rosybrown", Integer.valueOf(0xFFBC8F8F)); + sColors.put("royalblue", Integer.valueOf(0xFF4169E1)); + sColors.put("saddlebrown", Integer.valueOf(0xFF8B4513)); + sColors.put("salmon", Integer.valueOf(0xFFFA8072)); + sColors.put("sandybrown", Integer.valueOf(0xFFF4A460)); + sColors.put("seagreen", Integer.valueOf(0xFF2E8B57)); + sColors.put("seashell", Integer.valueOf(0xFFFFF5EE)); + sColors.put("sienna", Integer.valueOf(0xFFA0522D)); + sColors.put("silver", Integer.valueOf(0xFFC0C0C0)); + sColors.put("skyblue", Integer.valueOf(0xFF87CEEB)); + sColors.put("slateblue", Integer.valueOf(0xFF6A5ACD)); + sColors.put("slategray", Integer.valueOf(0xFF708090)); + sColors.put("slategrey", Integer.valueOf(0xFF708090)); + sColors.put("snow", Integer.valueOf(0xFFFFFAFA)); + sColors.put("springgreen", Integer.valueOf(0xFF00FF7F)); + sColors.put("steelblue", Integer.valueOf(0xFF4682B4)); + sColors.put("tan", Integer.valueOf(0xFFD2B48C)); + sColors.put("teal", Integer.valueOf(0xFF008080)); + sColors.put("thistle", Integer.valueOf(0xFFD8BFD8)); + sColors.put("tomato", Integer.valueOf(0xFFFF6347)); + sColors.put("turquoise", Integer.valueOf(0xFF40E0D0)); + sColors.put("violet", Integer.valueOf(0xFFEE82EE)); + sColors.put("wheat", Integer.valueOf(0xFFF5DEB3)); + sColors.put("white", Integer.valueOf(0xFFFFFFFF)); + sColors.put("whitesmoke", Integer.valueOf(0xFFF5F5F5)); + sColors.put("yellow", Integer.valueOf(0xFFFFFF00)); + sColors.put("yellowgreen", Integer.valueOf(0xFF9ACD32)); + } } diff --git a/vtm/src/org/oscim/utils/FastMath.java b/vtm/src/org/oscim/utils/FastMath.java index 98b8e343..30cab595 100644 --- a/vtm/src/org/oscim/utils/FastMath.java +++ b/vtm/src/org/oscim/utils/FastMath.java @@ -17,90 +17,96 @@ package org.oscim.utils; public class FastMath { - /** - * Integer version of log2(x) - * - * from http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog - */ - public static int log2(int x) { + /** + * Integer version of log2(x) + *

+ * from http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog + */ + public static int log2(int x) { - int r = 0; // result of log2(v) will go here + int r = 0; // result of log2(v) will go here - if ((x & 0xFFFF0000) != 0) { - x >>= 16; - r |= 16; - } - if ((x & 0xFF00) != 0) { - x >>= 8; - r |= 8; - } - if ((x & 0xF0) != 0) { - x >>= 4; - r |= 4; - } - if ((x & 0xC) != 0) { - x >>= 2; - r |= 2; - } - if ((x & 0x2) != 0) { - r |= 1; - } - return r; - } + if ((x & 0xFFFF0000) != 0) { + x >>= 16; + r |= 16; + } + if ((x & 0xFF00) != 0) { + x >>= 8; + r |= 8; + } + if ((x & 0xF0) != 0) { + x >>= 4; + r |= 4; + } + if ((x & 0xC) != 0) { + x >>= 2; + r |= 2; + } + if ((x & 0x2) != 0) { + r |= 1; + } + return r; + } - /** Integer version of 2^x */ - public static float pow(int x) { - if (x == 0) - return 1; + /** + * Integer version of 2^x + */ + public static float pow(int x) { + if (x == 0) + return 1; - return (x > 0 ? (1 << x) : (1.0f / (1 << -x))); - } + return (x > 0 ? (1 << x) : (1.0f / (1 << -x))); + } - public static int clamp(int value, int min, int max) { - return (value < min ? min : (value > max ? max : value)); - } + public static int clamp(int value, int min, int max) { + return (value < min ? min : (value > max ? max : value)); + } - public static float clamp(float value, float min, float max) { - return (value < min ? min : (value > max ? max : value)); - } + public static float clamp(float value, float min, float max) { + return (value < min ? min : (value > max ? max : value)); + } - public static double clamp(double value, double min, double max) { - return (value < min ? min : (value > max ? max : value)); - } + public static double clamp(double value, double min, double max) { + return (value < min ? min : (value > max ? max : value)); + } - public static float clampN(float value) { - return (value < 0f ? 0f : (value > 1f ? 1f : value)); - } + public static float clampN(float value) { + return (value < 0f ? 0f : (value > 1f ? 1f : value)); + } - public static byte clampToByte(int value) { - return (byte) (value < 0 ? 0 : (value > 255 ? 255 : value)); - } + public static byte clampToByte(int value) { + return (byte) (value < 0 ? 0 : (value > 255 ? 255 : value)); + } - public static float abs(float value) { - return value < 0 ? -value : value; - } + public static float abs(float value) { + return value < 0 ? -value : value; + } - public static float absMax(float value1, float value2) { - float a1 = value1 < 0 ? -value1 : value1; - float a2 = value2 < 0 ? -value2 : value2; - return a2 < a1 ? a1 : a2; - } + public static float absMax(float value1, float value2) { + float a1 = value1 < 0 ? -value1 : value1; + float a2 = value2 < 0 ? -value2 : value2; + return a2 < a1 ? a1 : a2; + } - /** test if any absolute value is greater than 'cmp' */ - public static boolean absMaxCmp(float value1, float value2, float cmp) { - return value1 < -cmp || value1 > cmp || value2 < -cmp || value2 > cmp; - } + /** + * test if any absolute value is greater than 'cmp' + */ + public static boolean absMaxCmp(float value1, float value2, float cmp) { + return value1 < -cmp || value1 > cmp || value2 < -cmp || value2 > cmp; + } - /** test if any absolute value is greater than 'cmp' */ - public static boolean absMaxCmp(int value1, int value2, int cmp) { - return value1 < -cmp || value1 > cmp || value2 < -cmp || value2 > cmp; - } + /** + * test if any absolute value is greater than 'cmp' + */ + public static boolean absMaxCmp(int value1, int value2, int cmp) { + return value1 < -cmp || value1 > cmp || value2 < -cmp || value2 > cmp; + } - public static boolean withinSquaredDist(int dx, int dy, int distance) { - return dx * dx + dy * dy < distance; - } + public static boolean withinSquaredDist(int dx, int dy, int distance) { + return dx * dx + dy * dy < distance; + } - public static boolean withinSquaredDist(float dx, float dy, float distance) { - return dx * dx + dy * dy < distance; - } + public static boolean withinSquaredDist(float dx, float dy, float distance) { + return dx * dx + dy * dy < distance; + } } diff --git a/vtm/src/org/oscim/utils/IOUtils.java b/vtm/src/org/oscim/utils/IOUtils.java index 2dc59a4e..dd0496d9 100644 --- a/vtm/src/org/oscim/utils/IOUtils.java +++ b/vtm/src/org/oscim/utils/IOUtils.java @@ -16,50 +16,49 @@ */ package org.oscim.utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.Closeable; import java.io.IOException; import java.net.Socket; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * A utility class with IO-specific helper methods. */ public final class IOUtils { - final static Logger log = LoggerFactory.getLogger(IOUtils.class); + final static Logger log = LoggerFactory.getLogger(IOUtils.class); - /** - * Invokes the {@link Closeable#close()} method on the given object. If an - * {@link IOException} occurs during the - * method call, it will be caught and logged. - * - * @param closeable - * the data source which should be closed (may be null). - */ - public static void closeQuietly(Closeable closeable) { - if (closeable == null) - return; + /** + * Invokes the {@link Closeable#close()} method on the given object. If an + * {@link IOException} occurs during the + * method call, it will be caught and logged. + * + * @param closeable the data source which should be closed (may be null). + */ + public static void closeQuietly(Closeable closeable) { + if (closeable == null) + return; - try { - closeable.close(); - } catch (IOException e) { - log.debug(e.getMessage()); - } - } + try { + closeable.close(); + } catch (IOException e) { + log.debug(e.getMessage()); + } + } - /* for old java versions */ - public static void closeQuietly(Socket closeable) { - if (closeable == null) - return; + /* for old java versions */ + public static void closeQuietly(Socket closeable) { + if (closeable == null) + return; - try { - closeable.close(); - } catch (IOException e) { - log.debug(e.getMessage()); - } - } + try { + closeable.close(); + } catch (IOException e) { + log.debug(e.getMessage()); + } + } - private IOUtils() { - } + private IOUtils() { + } } diff --git a/vtm/src/org/oscim/utils/KeyMap.java b/vtm/src/org/oscim/utils/KeyMap.java index d5371b58..5bb28540 100644 --- a/vtm/src/org/oscim/utils/KeyMap.java +++ b/vtm/src/org/oscim/utils/KeyMap.java @@ -19,11 +19,11 @@ package org.oscim.utils; /** * Stripped down HashMap making HashItem entries public - So you have your custom - * 'Entry' holding key and value. HashItem must implement equals() and hashCode() + * 'Entry' holding key and value. HashItem must implement equals() and hashCode() * only for the 'key' part. Items may only be in one KeyMap at a time! - * + *

* KeyMap.put(HashItem, boolean replace) allows to get or add an item in one invocation. - * + *

* TODO add to NOTICE file * The VTM library includes software developed as part of the Apache * Harmony project which is copyright 2006, The Apache Software Foundation and @@ -46,594 +46,585 @@ package org.oscim.utils; * limitations under the License. */ -import java.util.Arrays; - import org.oscim.utils.KeyMap.HashItem; import org.oscim.utils.pool.Inlist; +import java.util.Arrays; + /** - *

+ *

* Note: the implementation of {@code KeyMap} is not synchronized. If one thread * of several threads accessing an instance modifies the map structurally, * access to the map needs to be synchronized. A structural modification is an * operation that adds or removes an entry. Changes in the value of an entry are * not structural changes. - * + * * @param the type of keys maintained by this map */ public class KeyMap extends Inlist> { - /** - * Min capacity (other than zero) for a HashMap. Must be a power of two - * greater than 1 (and less than 1 << 30). - */ - private static final int MINIMUM_CAPACITY = 4; + /** + * Min capacity (other than zero) for a HashMap. Must be a power of two + * greater than 1 (and less than 1 << 30). + */ + private static final int MINIMUM_CAPACITY = 4; - /** - * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY. - */ - private static final int MAXIMUM_CAPACITY = 1 << 30; + /** + * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY. + */ + private static final int MAXIMUM_CAPACITY = 1 << 30; - /** - * An empty table shared by all zero-capacity maps (typically from default - * constructor). It is never written to, and replaced on first put. Its size - * is set to half the minimum, so that the first resize will create a - * minimum-sized table. - */ - private static final HashItem[] EMPTY_TABLE = new HashItem[MINIMUM_CAPACITY >>> 1]; + /** + * An empty table shared by all zero-capacity maps (typically from default + * constructor). It is never written to, and replaced on first put. Its size + * is set to half the minimum, so that the first resize will create a + * minimum-sized table. + */ + private static final HashItem[] EMPTY_TABLE = new HashItem[MINIMUM_CAPACITY >>> 1]; - /** - * The default load factor. Note that this implementation ignores the - * load factor, but cannot do away with it entirely because it's - * mentioned in the API. - * - *

- * Note that this constant has no impact on the behavior of the program, but - * it is emitted as part of the serialized form. The load factor of .75 is - * hardwired into the program, which uses cheap shifts in place of expensive - * division. - */ - static final float DEFAULT_LOAD_FACTOR = .75F; + /** + * The default load factor. Note that this implementation ignores the + * load factor, but cannot do away with it entirely because it's + * mentioned in the API. + *

+ *

+ * Note that this constant has no impact on the behavior of the program, but + * it is emitted as part of the serialized form. The load factor of .75 is + * hardwired into the program, which uses cheap shifts in place of expensive + * division. + */ + static final float DEFAULT_LOAD_FACTOR = .75F; - /** - * The hash table. If this hash map contains a mapping for null, it is - * not represented this hash table. - */ - HashItem[] table; + /** + * The hash table. If this hash map contains a mapping for null, it is + * not represented this hash table. + */ + HashItem[] table; - /** - * The number of mappings in this hash map. - */ - int size; + /** + * The number of mappings in this hash map. + */ + int size; - /** - * The table is rehashed when its size exceeds this threshold. - * The value of this field is generally .75 * capacity, except when - * the capacity is zero, as described in the EMPTY_TABLE declaration - * above. - */ - private int threshold; + /** + * The table is rehashed when its size exceeds this threshold. + * The value of this field is generally .75 * capacity, except when + * the capacity is zero, as described in the EMPTY_TABLE declaration + * above. + */ + private int threshold; - /** - * Constructs a new empty {@code HashMap} instance. - */ - public KeyMap() { - table = (HashItem[]) EMPTY_TABLE; - threshold = -1; // Forces first put invocation to replace EMPTY_TABLE - } + /** + * Constructs a new empty {@code HashMap} instance. + */ + public KeyMap() { + table = (HashItem[]) EMPTY_TABLE; + threshold = -1; // Forces first put invocation to replace EMPTY_TABLE + } - /** - * Constructs a new {@code HashMap} instance with the specified capacity. - * - * @param capacity - * the initial capacity of this hash map. - * @throws IllegalArgumentException - * when the capacity is less than zero. - */ - public KeyMap(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException("Capacity: " + capacity); - } + /** + * Constructs a new {@code HashMap} instance with the specified capacity. + * + * @param capacity the initial capacity of this hash map. + * @throws IllegalArgumentException when the capacity is less than zero. + */ + public KeyMap(int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException("Capacity: " + capacity); + } - if (capacity == 0) { - HashItem[] tab = (HashItem[]) EMPTY_TABLE; - table = tab; - threshold = -1; // Forces first put() to replace EMPTY_TABLE - return; - } + if (capacity == 0) { + HashItem[] tab = (HashItem[]) EMPTY_TABLE; + table = tab; + threshold = -1; // Forces first put() to replace EMPTY_TABLE + return; + } - if (capacity < MINIMUM_CAPACITY) { - capacity = MINIMUM_CAPACITY; - } else if (capacity > MAXIMUM_CAPACITY) { - capacity = MAXIMUM_CAPACITY; - } else { - capacity = roundUpToPowerOfTwo(capacity); - } - makeTable(capacity); - } + if (capacity < MINIMUM_CAPACITY) { + capacity = MINIMUM_CAPACITY; + } else if (capacity > MAXIMUM_CAPACITY) { + capacity = MAXIMUM_CAPACITY; + } else { + capacity = roundUpToPowerOfTwo(capacity); + } + makeTable(capacity); + } - /** - * Constructs a new {@code HashMap} instance with the specified capacity and - * load factor. - * - * @param capacity - * the initial capacity of this hash map. - * @param loadFactor - * the initial load factor. - * @throws IllegalArgumentException - * when the capacity is less than zero or the load factor is - * less or equal to zero or NaN. - */ - public KeyMap(int capacity, float loadFactor) { - this(capacity); + /** + * Constructs a new {@code HashMap} instance with the specified capacity and + * load factor. + * + * @param capacity the initial capacity of this hash map. + * @param loadFactor the initial load factor. + * @throws IllegalArgumentException when the capacity is less than zero or the load factor is + * less or equal to zero or NaN. + */ + public KeyMap(int capacity, float loadFactor) { + this(capacity); - if (loadFactor <= 0 || Float.isNaN(loadFactor)) { - throw new IllegalArgumentException("Load factor: " + loadFactor); - } + if (loadFactor <= 0 || Float.isNaN(loadFactor)) { + throw new IllegalArgumentException("Load factor: " + loadFactor); + } /* Note that this implementation ignores loadFactor; it always uses - * a load factor of 3/4. This simplifies the code and generally + * a load factor of 3/4. This simplifies the code and generally * improves performance. */ - } + } - /** - * Returns an appropriate capacity for the specified initial size. Does - * not round the result up to a power of two; the caller must do this! - * The returned value will be between 0 and MAXIMUM_CAPACITY (inclusive). - */ - static int capacityForInitSize(int size) { - int result = (size >> 1) + size; // Multiply by 3/2 to allow for growth + /** + * Returns an appropriate capacity for the specified initial size. Does + * not round the result up to a power of two; the caller must do this! + * The returned value will be between 0 and MAXIMUM_CAPACITY (inclusive). + */ + static int capacityForInitSize(int size) { + int result = (size >> 1) + size; // Multiply by 3/2 to allow for growth - // boolean expr is equivalent to result >= 0 && result= 0 && result>> 20) ^ (hash >>> 12); - hash ^= (hash >>> 7) ^ (hash >>> 4); + // Doug Lea's supplemental secondaryHash function (inlined) + int hash = key.hashCode(); + hash ^= (hash >>> 20) ^ (hash >>> 12); + hash ^= (hash >>> 7) ^ (hash >>> 4); - HashItem[] tab = table; - for (HashItem e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { - HashItem eKey = e; - if (eKey == key || (e.hash == hash && key.equals(eKey))) { - return (K) e; - } - } - return null; - } + HashItem[] tab = table; + for (HashItem e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { + HashItem eKey = e; + if (eKey == key || (e.hash == hash && key.equals(eKey))) { + return (K) e; + } + } + return null; + } - /** - * Maps the specified key to the specified value. - * - * @param key - * the key. - * @param value - * the value. - * @return the value of any previous mapping with the specified key or - * {@code null} if there was no such mapping. - */ - public K put(K key) { - return put(key, true); - } + /** + * Maps the specified key to the specified value. + * + * @param key the key. + * @param value the value. + * @return the value of any previous mapping with the specified key or + * {@code null} if there was no such mapping. + */ + public K put(K key) { + return put(key, true); + } - @SuppressWarnings("unchecked") - public K put(K key, boolean replace) { - if (key.next != null) - throw new IllegalStateException("item not unhooked"); + @SuppressWarnings("unchecked") + public K put(K key, boolean replace) { + if (key.next != null) + throw new IllegalStateException("item not unhooked"); - int hash = secondaryHash(key.hashCode()); - HashItem[] tab = table; - int index = hash & (tab.length - 1); - for (HashItem e = tab[index]; e != null; e = e.next) { - if (e.hash == hash && key.equals(e)) { - if (replace) { - tab[index] = Inlist.remove(tab[index], e); - tab[index] = Inlist.push(tab[index], key); - } - //V oldValue = e.value; - //e.value = value; - return (K) e; //oldValue; - } - } + int hash = secondaryHash(key.hashCode()); + HashItem[] tab = table; + int index = hash & (tab.length - 1); + for (HashItem e = tab[index]; e != null; e = e.next) { + if (e.hash == hash && key.equals(e)) { + if (replace) { + tab[index] = Inlist.remove(tab[index], e); + tab[index] = Inlist.push(tab[index], key); + } + //V oldValue = e.value; + //e.value = value; + return (K) e; //oldValue; + } + } - // No entry key is present; create one - if (size++ > threshold) { - tab = doubleCapacity(); - index = hash & (tab.length - 1); - } - addNewEntry(key, hash, index); - return null; - } + // No entry key is present; create one + if (size++ > threshold) { + tab = doubleCapacity(); + index = hash & (tab.length - 1); + } + addNewEntry(key, hash, index); + return null; + } - /** - * Removes the mapping with the specified key from this map. - * - * @param key - * the key of the mapping to remove. - * @return the value of the removed mapping or {@code null} if no mapping - * for the specified key was found. - */ - @SuppressWarnings("unchecked") - public K remove(K key) { + /** + * Removes the mapping with the specified key from this map. + * + * @param key the key of the mapping to remove. + * @return the value of the removed mapping or {@code null} if no mapping + * for the specified key was found. + */ + @SuppressWarnings("unchecked") + public K remove(K key) { - int hash = secondaryHash(key.hashCode()); - HashItem[] tab = table; - int index = hash & (tab.length - 1); - for (HashItem e = tab[index], prev = null; e != null; prev = e, e = e.next) { - if (e.hash == hash && key.equals(e)) { - if (prev == null) { - tab[index] = e.next; - } else { - prev.next = e.next; - } - e.next = null; - //modCount++; - size--; - //postRemove(e); - return (K) e; - } - } - return null; - } + int hash = secondaryHash(key.hashCode()); + HashItem[] tab = table; + int index = hash & (tab.length - 1); + for (HashItem e = tab[index], prev = null; e != null; prev = e, e = e.next) { + if (e.hash == hash && key.equals(e)) { + if (prev == null) { + tab[index] = e.next; + } else { + prev.next = e.next; + } + e.next = null; + //modCount++; + size--; + //postRemove(e); + return (K) e; + } + } + return null; + } - /** - * Creates a new entry for the given key, value, hash, and index and - * inserts it into the hash table. This method is called by put - * (and indirectly, putAll), and overridden by LinkedHashMap. The hash - * must incorporate the secondary hash function. - */ - void addNewEntry(K key, int hash, int index) { - key.setIndex(hash, table[index]); - table[index] = key; - } + /** + * Creates a new entry for the given key, value, hash, and index and + * inserts it into the hash table. This method is called by put + * (and indirectly, putAll), and overridden by LinkedHashMap. The hash + * must incorporate the secondary hash function. + */ + void addNewEntry(K key, int hash, int index) { + key.setIndex(hash, table[index]); + table[index] = key; + } - /** - * Allocate a table of the given capacity and set the threshold accordingly. - * - * @param newCapacity must be a power of two - */ - private HashItem[] makeTable(int newCapacity) { - HashItem[] newTable = (HashItem[]) new HashItem[newCapacity]; - table = newTable; - threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity - return newTable; - } + /** + * Allocate a table of the given capacity and set the threshold accordingly. + * + * @param newCapacity must be a power of two + */ + private HashItem[] makeTable(int newCapacity) { + HashItem[] newTable = (HashItem[]) new HashItem[newCapacity]; + table = newTable; + threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity + return newTable; + } - /** - * Doubles the capacity of the hash table. Existing entries are placed in - * the correct bucket on the enlarged table. If the current capacity is, - * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which - * will be new unless we were already at MAXIMUM_CAPACITY. - */ - private HashItem[] doubleCapacity() { - HashItem[] oldTable = table; - int oldCapacity = oldTable.length; - if (oldCapacity == MAXIMUM_CAPACITY) { - return oldTable; - } - int newCapacity = oldCapacity * 2; - HashItem[] newTable = makeTable(newCapacity); - if (size == 0) { - return newTable; - } + /** + * Doubles the capacity of the hash table. Existing entries are placed in + * the correct bucket on the enlarged table. If the current capacity is, + * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which + * will be new unless we were already at MAXIMUM_CAPACITY. + */ + private HashItem[] doubleCapacity() { + HashItem[] oldTable = table; + int oldCapacity = oldTable.length; + if (oldCapacity == MAXIMUM_CAPACITY) { + return oldTable; + } + int newCapacity = oldCapacity * 2; + HashItem[] newTable = makeTable(newCapacity); + if (size == 0) { + return newTable; + } - for (int j = 0; j < oldCapacity; j++) { - /* Rehash the bucket using the minimum number of field writes. + for (int j = 0; j < oldCapacity; j++) { + /* Rehash the bucket using the minimum number of field writes. * This is the most subtle and delicate code in the class. */ - HashItem e = oldTable[j]; - if (e == null) { - continue; - } - int highBit = e.hash & oldCapacity; - HashItem broken = null; - newTable[j | highBit] = e; - for (HashItem n = e.next; n != null; e = n, n = n.next) { - int nextHighBit = n.hash & oldCapacity; - if (nextHighBit != highBit) { - if (broken == null) - newTable[j | nextHighBit] = n; - else - broken.next = n; - broken = e; - highBit = nextHighBit; - } - } - if (broken != null) - broken.next = null; - } - return newTable; - } + HashItem e = oldTable[j]; + if (e == null) { + continue; + } + int highBit = e.hash & oldCapacity; + HashItem broken = null; + newTable[j | highBit] = e; + for (HashItem n = e.next; n != null; e = n, n = n.next) { + int nextHighBit = n.hash & oldCapacity; + if (nextHighBit != highBit) { + if (broken == null) + newTable[j | nextHighBit] = n; + else + broken.next = n; + broken = e; + highBit = nextHighBit; + } + } + if (broken != null) + broken.next = null; + } + return newTable; + } - /** - * Subclass overrides this method to unlink entry. - */ - void postRemove(HashItem e) { - } + /** + * Subclass overrides this method to unlink entry. + */ + void postRemove(HashItem e) { + } - /** - * Removes all mappings from this hash map, leaving it empty. - * - * @see #isEmpty - * @see #size - */ - public void clear() { - if (size != 0) { - Arrays.fill(table, null); - size = 0; - } - } + /** + * Removes all mappings from this hash map, leaving it empty. + * + * @see #isEmpty + * @see #size + */ + public void clear() { + if (size != 0) { + Arrays.fill(table, null); + size = 0; + } + } - static final boolean STATS = false; + static final boolean STATS = false; - @SuppressWarnings("unchecked") - public K releaseItems() { - if (size == 0) - return null; + @SuppressWarnings("unchecked") + public K releaseItems() { + if (size == 0) + return null; - int collisions = 0; - int max = 0; - int sum = 0; + int collisions = 0; + int max = 0; + int sum = 0; - HashItem items = null; - HashItem last; - for (int i = 0, n = table.length; i < n; i++) { - HashItem item = table[i]; - if (item == null) - continue; - table[i] = null; - if (STATS) { - sum = 0; - last = item; - while (last != null) { - if (last.next == null) - break; + HashItem items = null; + HashItem last; + for (int i = 0, n = table.length; i < n; i++) { + HashItem item = table[i]; + if (item == null) + continue; + table[i] = null; + if (STATS) { + sum = 0; + last = item; + while (last != null) { + if (last.next == null) + break; - sum++; - last = last.next; - } - max = Math.max(max, sum); - collisions += sum; - } else { - last = Inlist.last(item); - } - last.next = items; - items = item; - } - if (STATS) - System.out.println("collisions: " + collisions + " " + max + " " + size); + sum++; + last = last.next; + } + max = Math.max(max, sum); + collisions += sum; + } else { + last = Inlist.last(item); + } + last.next = items; + items = item; + } + if (STATS) + System.out.println("collisions: " + collisions + " " + max + " " + size); - Arrays.fill(table, null); - size = 0; + Arrays.fill(table, null); + size = 0; - return (K) items; - } + return (K) items; + } - public static class HashItem extends Inlist { - int hash; + public static class HashItem extends Inlist { + int hash; - public void setIndex(int hash, HashItem next) { - this.hash = hash; - this.next = next; - } - } + public void setIndex(int hash, HashItem next) { + this.hash = hash; + this.next = next; + } + } - /** - * Applies a supplemental hash function to a given hashCode, which defends - * against poor quality hash functions. This is critical because HashMap - * uses power-of-two length hash tables, that otherwise encounter collisions - * for hashCodes that do not differ in lower or upper bits. - */ - private static int secondaryHash(int h) { - // Doug Lea's supplemental hash function - h ^= (h >>> 20) ^ (h >>> 12); - return h ^ (h >>> 7) ^ (h >>> 4); - } + /** + * Applies a supplemental hash function to a given hashCode, which defends + * against poor quality hash functions. This is critical because HashMap + * uses power-of-two length hash tables, that otherwise encounter collisions + * for hashCodes that do not differ in lower or upper bits. + */ + private static int secondaryHash(int h) { + // Doug Lea's supplemental hash function + h ^= (h >>> 20) ^ (h >>> 12); + return h ^ (h >>> 7) ^ (h >>> 4); + } - /** - * Returns the smallest power of two >= its argument, with several caveats: - * If the argument is negative but not Integer.MIN_VALUE, the method returns - * zero. If the argument is > 2^30 or equal to Integer.MIN_VALUE, the method - * returns Integer.MIN_VALUE. If the argument is zero, the method returns - * zero. - */ - private static int roundUpToPowerOfTwo(int i) { - i--; // If input is a power of two, shift its high-order bit right + /** + * Returns the smallest power of two >= its argument, with several caveats: + * If the argument is negative but not Integer.MIN_VALUE, the method returns + * zero. If the argument is > 2^30 or equal to Integer.MIN_VALUE, the method + * returns Integer.MIN_VALUE. If the argument is zero, the method returns + * zero. + */ + private static int roundUpToPowerOfTwo(int i) { + i--; // If input is a power of two, shift its high-order bit right - // "Smear" the high-order bit all the way to the right - i |= i >>> 1; - i |= i >>> 2; - i |= i >>> 4; - i |= i >>> 8; - i |= i >>> 16; + // "Smear" the high-order bit all the way to the right + i |= i >>> 1; + i |= i >>> 2; + i |= i >>> 4; + i |= i >>> 8; + i |= i >>> 16; - return i + 1; - } + return i + 1; + } - // public K put(K key) { - // // if (key == null) { - // // return putValueForNullKey(value); - // // } - // - // int hash = secondaryHash(key.hashCode()); - // HashItem[] tab = table; - // int index = hash & (tab.length - 1); - // for (HashItem e = tab[index]; e != null; e = e.next) { - // if (e.hash == hash && key.equals(e.key)) { - // preModify(e); - // //V oldValue = e.value; - // //e.value = value; - // return e.key; //oldValue; - // } - // } - // - // // No entry for (non-null) key is present; create one - // modCount++; - // if (size++ > threshold) { - // tab = doubleCapacity(); - // index = hash & (tab.length - 1); - // } - // addNewEntry(key, hash, index); - // return null; - // } + // public K put(K key) { + // // if (key == null) { + // // return putValueForNullKey(value); + // // } + // + // int hash = secondaryHash(key.hashCode()); + // HashItem[] tab = table; + // int index = hash & (tab.length - 1); + // for (HashItem e = tab[index]; e != null; e = e.next) { + // if (e.hash == hash && key.equals(e.key)) { + // preModify(e); + // //V oldValue = e.value; + // //e.value = value; + // return e.key; //oldValue; + // } + // } + // + // // No entry for (non-null) key is present; create one + // modCount++; + // if (size++ > threshold) { + // tab = doubleCapacity(); + // index = hash & (tab.length - 1); + // } + // addNewEntry(key, hash, index); + // return null; + // } - // private V putValueForNullKey(V value) { - // HashMapEntry entry = entryForNullKey; - // if (entry == null) { - // addNewEntryForNullKey(value); - // size++; - // modCount++; - // return null; - // } else { - // preModify(entry); - // V oldValue = entry.value; - // entry.value = value; - // return oldValue; - // } - // } + // private V putValueForNullKey(V value) { + // HashMapEntry entry = entryForNullKey; + // if (entry == null) { + // addNewEntryForNullKey(value); + // size++; + // modCount++; + // return null; + // } else { + // preModify(entry); + // V oldValue = entry.value; + // entry.value = value; + // return oldValue; + // } + // } - // /** - // * Returns whether this map contains the specified key. - // * - // * @param key - // * the key to search for. - // * @return {@code true} if this map contains the specified key, - // * {@code false} otherwise. - // */ - // //@Override - // public boolean containsKey(Object key) { - // if (key == null) { - // return entryForNullKey != null; - // } - // - // // Doug Lea's supplemental secondaryHash function (inlined) - // int hash = key.hashCode(); - // hash ^= (hash >>> 20) ^ (hash >>> 12); - // hash ^= (hash >>> 7) ^ (hash >>> 4); - // - // HashItem[] tab = table; - // for (HashItem e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { - // K eKey = e.key; - // if (eKey == key || (e.hash == hash && key.equals(eKey))) { - // return true; - // } - // } - // return false; - // } + // /** + // * Returns whether this map contains the specified key. + // * + // * @param key + // * the key to search for. + // * @return {@code true} if this map contains the specified key, + // * {@code false} otherwise. + // */ + // //@Override + // public boolean containsKey(Object key) { + // if (key == null) { + // return entryForNullKey != null; + // } + // + // // Doug Lea's supplemental secondaryHash function (inlined) + // int hash = key.hashCode(); + // hash ^= (hash >>> 20) ^ (hash >>> 12); + // hash ^= (hash >>> 7) ^ (hash >>> 4); + // + // HashItem[] tab = table; + // for (HashItem e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { + // K eKey = e.key; + // if (eKey == key || (e.hash == hash && key.equals(eKey))) { + // return true; + // } + // } + // return false; + // } - // /** - // * Returns whether this map contains the specified value. - // * - // * @param value - // * the value to search for. - // * @return {@code true} if this map contains the specified value, - // * {@code false} otherwise. - // */ - // @Override - // public boolean containsValue(Object value) { - // HashMapEntry[] tab = table; - // int len = tab.length; - // if (value == null) { - // for (int i = 0; i < len; i++) { - // for (HashMapEntry e = tab[i]; e != null; e = e.next) { - // if (e.value == null) { - // return true; - // } - // } - // } - // return entryForNullKey != null && entryForNullKey.value == null; - // } - // - // // value is non-null - // for (int i = 0; i < len; i++) { - // for (HashMapEntry e = tab[i]; e != null; e = e.next) { - // if (value.equals(e.value)) { - // return true; - // } - // } - // } - // return entryForNullKey != null && value.equals(entryForNullKey.value); - // } + // /** + // * Returns whether this map contains the specified value. + // * + // * @param value + // * the value to search for. + // * @return {@code true} if this map contains the specified value, + // * {@code false} otherwise. + // */ + // @Override + // public boolean containsValue(Object value) { + // HashMapEntry[] tab = table; + // int len = tab.length; + // if (value == null) { + // for (int i = 0; i < len; i++) { + // for (HashMapEntry e = tab[i]; e != null; e = e.next) { + // if (e.value == null) { + // return true; + // } + // } + // } + // return entryForNullKey != null && entryForNullKey.value == null; + // } + // + // // value is non-null + // for (int i = 0; i < len; i++) { + // for (HashMapEntry e = tab[i]; e != null; e = e.next) { + // if (value.equals(e.value)) { + // return true; + // } + // } + // } + // return entryForNullKey != null && value.equals(entryForNullKey.value); + // } - ///** - // * Ensures that the hash table has sufficient capacity to store the - // * specified number of mappings, with room to grow. If not, it increases the - // * capacity as appropriate. Like doubleCapacity, this method moves existing - // * entries to new buckets as appropriate. Unlike doubleCapacity, this method - // * can grow the table by factors of 2^n for n > 1. Hopefully, a single call - // * to this method will be faster than multiple calls to doubleCapacity. - // * - // *

- // * This method is called only by putAll. - // */ - //private void ensureCapacity(int numMappings) { - // int newCapacity = roundUpToPowerOfTwo(capacityForInitSize(numMappings)); - // HashItem[] oldTable = table; - // int oldCapacity = oldTable.length; - // if (newCapacity <= oldCapacity) { - // return; - // } - // if (newCapacity == oldCapacity * 2) { - // doubleCapacity(); - // return; - // } - // - // // We're growing by at least 4x, rehash in the obvious way - // HashItem[] newTable = makeTable(newCapacity); - // if (size != 0) { - // int newMask = newCapacity - 1; - // for (int i = 0; i < oldCapacity; i++) { - // for (HashItem e = oldTable[i]; e != null;) { - // HashItem oldNext = e.next; - // int newIndex = e.hash & newMask; - // HashItem newNext = newTable[newIndex]; - // newTable[newIndex] = e; - // e.next = newNext; - // e = oldNext; - // } - // } - // } - //} + ///** + // * Ensures that the hash table has sufficient capacity to store the + // * specified number of mappings, with room to grow. If not, it increases the + // * capacity as appropriate. Like doubleCapacity, this method moves existing + // * entries to new buckets as appropriate. Unlike doubleCapacity, this method + // * can grow the table by factors of 2^n for n > 1. Hopefully, a single call + // * to this method will be faster than multiple calls to doubleCapacity. + // * + // *

+ // * This method is called only by putAll. + // */ + //private void ensureCapacity(int numMappings) { + // int newCapacity = roundUpToPowerOfTwo(capacityForInitSize(numMappings)); + // HashItem[] oldTable = table; + // int oldCapacity = oldTable.length; + // if (newCapacity <= oldCapacity) { + // return; + // } + // if (newCapacity == oldCapacity * 2) { + // doubleCapacity(); + // return; + // } + // + // // We're growing by at least 4x, rehash in the obvious way + // HashItem[] newTable = makeTable(newCapacity); + // if (size != 0) { + // int newMask = newCapacity - 1; + // for (int i = 0; i < oldCapacity; i++) { + // for (HashItem e = oldTable[i]; e != null;) { + // HashItem oldNext = e.next; + // int newIndex = e.hash & newMask; + // HashItem newNext = newTable[newIndex]; + // newTable[newIndex] = e; + // e.next = newNext; + // e = oldNext; + // } + // } + // } + //} } diff --git a/vtm/src/org/oscim/utils/LRUCache.java b/vtm/src/org/oscim/utils/LRUCache.java index ce643ff1..32096a7d 100644 --- a/vtm/src/org/oscim/utils/LRUCache.java +++ b/vtm/src/org/oscim/utils/LRUCache.java @@ -24,38 +24,34 @@ import java.util.Map; * automatically removed from the cache when * new mappings are added. This implementation uses an {@link LinkedHashMap} * internally. - * - * @param - * the type of the map key, see {@link Map}. - * @param - * the type of the map value, see {@link Map}. + * + * @param the type of the map key, see {@link Map}. + * @param the type of the map value, see {@link Map}. */ public class LRUCache extends LinkedHashMap { - private static final float LOAD_FACTOR = 0.6f; - private static final long serialVersionUID = 1L; + private static final float LOAD_FACTOR = 0.6f; + private static final long serialVersionUID = 1L; - private static int calculateInitialCapacity(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException("capacity must not be negative: " + capacity); - } - return (int) (capacity / LOAD_FACTOR) + 2; - } + private static int calculateInitialCapacity(int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException("capacity must not be negative: " + capacity); + } + return (int) (capacity / LOAD_FACTOR) + 2; + } - private final int capacity; + private final int capacity; - /** - * @param capacity - * the maximum capacity of this cache. - * @throws IllegalArgumentException - * if the capacity is negative. - */ - public LRUCache(int capacity) { - super(calculateInitialCapacity(capacity), LOAD_FACTOR, true); - this.capacity = capacity; - } + /** + * @param capacity the maximum capacity of this cache. + * @throws IllegalArgumentException if the capacity is negative. + */ + public LRUCache(int capacity) { + super(calculateInitialCapacity(capacity), LOAD_FACTOR, true); + this.capacity = capacity; + } - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > this.capacity; - } + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > this.capacity; + } } diff --git a/vtm/src/org/oscim/utils/MinHeap.java b/vtm/src/org/oscim/utils/MinHeap.java index 3e3b83f7..695d2243 100644 --- a/vtm/src/org/oscim/utils/MinHeap.java +++ b/vtm/src/org/oscim/utils/MinHeap.java @@ -1,104 +1,104 @@ package org.oscim.utils; public class MinHeap { - private int[] data; - private float[] heap; + private int[] data; + private float[] heap; - public static final class Item { - public int pos; - public float prio; - public int index; - } + public static final class Item { + public int pos; + public float prio; + public int index; + } - int size; + int size; - private final Item it = new Item(); + private final Item it = new Item(); - public MinHeap(float[] heap, int[] data) { - this.heap = heap; - this.data = data; - size = 1; - } + public MinHeap(float[] heap, int[] data) { + this.heap = heap; + this.data = data; + size = 1; + } - public void push(float prio, int d) { - int idx = size++; - int n = idx >> 1; - while (idx > 1 && heap[n] > prio) { - heap[idx] = heap[n]; - data[idx] = data[n]; - idx = n; - n >>= 1; - } + public void push(float prio, int d) { + int idx = size++; + int n = idx >> 1; + while (idx > 1 && heap[n] > prio) { + heap[idx] = heap[n]; + data[idx] = data[n]; + idx = n; + n >>= 1; + } - heap[idx] = prio; - data[idx] = d; - } + heap[idx] = prio; + data[idx] = d; + } - public Item pop() { - if (size == 1) - return null; + public Item pop() { + if (size == 1) + return null; - it.pos = data[1]; - it.prio = heap[1]; + it.pos = data[1]; + it.prio = heap[1]; - int idx = --size; + int idx = --size; - if (idx > 1) { - heap[1] = heap[idx]; - data[1] = data[idx]; - heapify(); - } - return it; - } + if (idx > 1) { + heap[1] = heap[idx]; + data[1] = data[idx]; + heapify(); + } + return it; + } - public int peek() { - return data[1]; - } + public int peek() { + return data[1]; + } - private void heapify() { - float root = heap[1]; - int tmp = data[1]; + private void heapify() { + float root = heap[1]; + int tmp = data[1]; - int last = size; - int idx = 1; + int last = size; + int idx = 1; - while (true) { - // left child - int c = idx << 1; - if (c > last) - break; - // right child - if (c + 1 <= last && heap[c + 1] < heap[c]) - c++; + while (true) { + // left child + int c = idx << 1; + if (c > last) + break; + // right child + if (c + 1 <= last && heap[c + 1] < heap[c]) + c++; - float val = heap[c]; - if (val >= root) - break; + float val = heap[c]; + if (val >= root) + break; - heap[idx] = val; - data[idx] = data[c]; - idx = c; - } + heap[idx] = val; + data[idx] = data[c]; + idx = c; + } - heap[idx] = root; - data[idx] = tmp; - } + heap[idx] = root; + data[idx] = tmp; + } - public static void main(String[] args) { - MinHeap h = new MinHeap(new float[10], new int[10]); - h.push(10, 10); - h.push(12, 12); - h.push(21, 21); - h.push(31, 31); - h.push(14, 14); - h.push(2, 2); - Item it; - for (int i = 0; i < 10; i++) { + public static void main(String[] args) { + MinHeap h = new MinHeap(new float[10], new int[10]); + h.push(10, 10); + h.push(12, 12); + h.push(21, 21); + h.push(31, 31); + h.push(14, 14); + h.push(2, 2); + Item it; + for (int i = 0; i < 10; i++) { - it = h.pop(); - if (it != null) - System.out.println(it.pos + " " + it.prio); - } + it = h.pop(); + if (it != null) + System.out.println(it.pos + " " + it.prio); + } - } + } } diff --git a/vtm/src/org/oscim/utils/PausableThread.java b/vtm/src/org/oscim/utils/PausableThread.java index 9e43c762..247e834c 100644 --- a/vtm/src/org/oscim/utils/PausableThread.java +++ b/vtm/src/org/oscim/utils/PausableThread.java @@ -24,177 +24,177 @@ import org.slf4j.LoggerFactory; * An abstract base class for threads which support pausing and resuming. */ public abstract class PausableThread extends Thread { - private final static Logger log = LoggerFactory.getLogger(PausableThread.class); - private final static boolean dbg = false; + private final static Logger log = LoggerFactory.getLogger(PausableThread.class); + private final static boolean dbg = false; - private boolean mPausing = true; - private boolean mRunning = true; - private boolean mShouldPause = false; - private boolean mShouldStop = false; + private boolean mPausing = true; + private boolean mRunning = true; + private boolean mShouldPause = false; + private boolean mShouldStop = false; - /** - * Causes the current thread to wait until this thread is pausing. - */ - public final void awaitPausing() { - synchronized (this) { + /** + * Causes the current thread to wait until this thread is pausing. + */ + public final void awaitPausing() { + synchronized (this) { - while (!isPausing()) { + while (!isPausing()) { - if (dbg) - log.debug("Await Pause {}", getThreadName()); + if (dbg) + log.debug("Await Pause {}", getThreadName()); - try { - wait(100); - } catch (InterruptedException e) { - /* restore the interrupted status */ - this.interrupt(); - } - } - } - } + try { + wait(100); + } catch (InterruptedException e) { + /* restore the interrupted status */ + this.interrupt(); + } + } + } + } - public synchronized void finish() { - if (!mRunning) - return; + public synchronized void finish() { + if (!mRunning) + return; - log.debug("Finish {}", getThreadName()); + log.debug("Finish {}", getThreadName()); - mShouldStop = true; - this.interrupt(); - } + mShouldStop = true; + this.interrupt(); + } - /** - * @return true if this thread is currently pausing, false otherwise. - */ - public final synchronized boolean isPausing() { - return mPausing; - } + /** + * @return true if this thread is currently pausing, false otherwise. + */ + public final synchronized boolean isPausing() { + return mPausing; + } - /** - * The thread should stop its work temporarily. - */ - public final synchronized void pause() { - if (!mShouldPause) { - mShouldPause = true; - this.interrupt(); - } - } + /** + * The thread should stop its work temporarily. + */ + public final synchronized void pause() { + if (!mShouldPause) { + mShouldPause = true; + this.interrupt(); + } + } - /** - * The paused thread should continue with its work. - */ - public final synchronized void proceed() { - if (mShouldPause) { - mShouldPause = false; - notify(); - } - } + /** + * The paused thread should continue with its work. + */ + public final synchronized void proceed() { + if (mShouldPause) { + mShouldPause = false; + notify(); + } + } - public final synchronized boolean isCanceled() { - return mShouldPause; - } + public final synchronized boolean isCanceled() { + return mShouldPause; + } - @Override - public final void run() { - mRunning = true; - setName(getThreadName()); - setPriority(getThreadPriority()); + @Override + public final void run() { + mRunning = true; + setName(getThreadName()); + setPriority(getThreadPriority()); - O: while (!mShouldStop) { + O: + while (!mShouldStop) { - synchronized (this) { - if (mShouldStop) - break; + synchronized (this) { + if (mShouldStop) + break; - while ((mShouldPause || !hasWork())) { - try { - if (mShouldPause) { - mPausing = true; + while ((mShouldPause || !hasWork())) { + try { + if (mShouldPause) { + mPausing = true; - if (dbg) - log.debug("Pausing: {}", - getThreadName()); - } + if (dbg) + log.debug("Pausing: {}", + getThreadName()); + } - wait(); + wait(); - } catch (InterruptedException e) { - if (dbg) - log.debug("Interrupted {} {}:{}", - getThreadName(), - mShouldPause, - mShouldStop); + } catch (InterruptedException e) { + if (dbg) + log.debug("Interrupted {} {}:{}", + getThreadName(), + mShouldPause, + mShouldStop); - if (mShouldStop) - break O; - } - } + if (mShouldStop) + break O; + } + } - if (mPausing) { - mPausing = false; - afterPause(); - } - } + if (mPausing) { + mPausing = false; + afterPause(); + } + } - try { - doWork(); - } catch (InterruptedException e) { - if (dbg) - log.debug("Interrupted {} {}:{}", - getThreadName(), - mShouldPause, - mShouldStop); + try { + doWork(); + } catch (InterruptedException e) { + if (dbg) + log.debug("Interrupted {} {}:{}", + getThreadName(), + mShouldPause, + mShouldStop); - } - } + } + } - log.debug("Done {}", getThreadName()); + log.debug("Done {}", getThreadName()); - mPausing = true; - mRunning = false; + mPausing = true; + mRunning = false; - afterRun(); - } + afterRun(); + } - /** - * Called once when this thread continues to work after a pause. The default - * implementation is empty. - */ - protected void afterPause() { - // do nothing - } + /** + * Called once when this thread continues to work after a pause. The default + * implementation is empty. + */ + protected void afterPause() { + // do nothing + } - /** - * Called once at the end of the {@link #run()} method. The default - * implementation is empty. - */ - protected void afterRun() { - // do nothing - } + /** + * Called once at the end of the {@link #run()} method. The default + * implementation is empty. + */ + protected void afterRun() { + // do nothing + } - /** - * Called when this thread is not paused and should do its work. - * - * @throws InterruptedException - * if the thread has been interrupted. - */ - protected abstract void doWork() throws InterruptedException; + /** + * Called when this thread is not paused and should do its work. + * + * @throws InterruptedException if the thread has been interrupted. + */ + protected abstract void doWork() throws InterruptedException; - /** - * @return the name of this thread. - */ - protected abstract String getThreadName(); + /** + * @return the name of this thread. + */ + protected abstract String getThreadName(); - /** - * @return the priority of this thread. The default value is - * {@link Thread#NORM_PRIORITY}. - */ - protected int getThreadPriority() { - return Thread.NORM_PRIORITY; - } + /** + * @return the priority of this thread. The default value is + * {@link Thread#NORM_PRIORITY}. + */ + protected int getThreadPriority() { + return Thread.NORM_PRIORITY; + } - /** - * @return true if this thread has some work to do, false otherwise. - */ - protected abstract boolean hasWork(); + /** + * @return true if this thread has some work to do, false otherwise. + */ + protected abstract boolean hasWork(); } diff --git a/vtm/src/org/oscim/utils/QuadTree.java b/vtm/src/org/oscim/utils/QuadTree.java index 7002ca50..fc0db28f 100644 --- a/vtm/src/org/oscim/utils/QuadTree.java +++ b/vtm/src/org/oscim/utils/QuadTree.java @@ -1,7 +1,5 @@ package org.oscim.utils; -import java.util.List; - import org.oscim.core.Box; import org.oscim.utils.pool.Pool; import org.oscim.utils.quadtree.BoxTree; @@ -9,6 +7,8 @@ import org.oscim.utils.quadtree.BoxTree.BoxItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** * Quad-tree with fixed extents. * This implementation uses int bounding-boxes internally, @@ -16,66 +16,66 @@ import org.slf4j.LoggerFactory; */ public class QuadTree extends BoxTree, T> implements SpatialIndex { - static final Logger log = LoggerFactory.getLogger(QuadTree.class); + static final Logger log = LoggerFactory.getLogger(QuadTree.class); - public QuadTree(int extents, int maxDepth) { - super(extents, maxDepth); - } + public QuadTree(int extents, int maxDepth) { + super(extents, maxDepth); + } - final Pool> boxPool = new Pool>() { - @Override - protected BoxItem createItem() { - return new BoxItem(); - } - }; + final Pool> boxPool = new Pool>() { + @Override + protected BoxItem createItem() { + return new BoxItem(); + } + }; - private BoxItem getBox(Box box) { - BoxItem it = boxPool.get(); - it.x1 = (int) box.xmin; - it.y1 = (int) box.ymin; - it.x2 = (int) box.xmax; - it.y2 = (int) box.ymax; - return it; - } + private BoxItem getBox(Box box) { + BoxItem it = boxPool.get(); + it.x1 = (int) box.xmin; + it.y1 = (int) box.ymin; + it.x2 = (int) box.xmax; + it.y2 = (int) box.ymax; + return it; + } - @Override - public void insert(Box box, T item) { - insert(new BoxItem(box, item)); - } + @Override + public void insert(Box box, T item) { + insert(new BoxItem(box, item)); + } - @Override - public boolean remove(Box box, T item) { - BoxItem bbox = getBox(box); - boolean ok = remove(bbox, item); - boxPool.release(bbox); - return ok; - } + @Override + public boolean remove(Box box, T item) { + BoxItem bbox = getBox(box); + boolean ok = remove(bbox, item); + boxPool.release(bbox); + return ok; + } - static class CollectCb implements SearchCb { - @SuppressWarnings("unchecked") - @Override - public boolean call(T item, Object context) { - List l = (List) context; - l.add(item); - return true; - } - } + static class CollectCb implements SearchCb { + @SuppressWarnings("unchecked") + @Override + public boolean call(T item, Object context) { + List l = (List) context; + l.add(item); + return true; + } + } - final CollectCb collectCb = new CollectCb(); + final CollectCb collectCb = new CollectCb(); - @Override - public List search(Box bbox, List results) { - BoxItem box = getBox(bbox); - search(box, collectCb, results); - boxPool.release(box); - return results; - } + @Override + public List search(Box bbox, List results) { + BoxItem box = getBox(bbox); + search(box, collectCb, results); + boxPool.release(box); + return results; + } - @Override - public boolean search(Box bbox, SearchCb cb, Object context) { - BoxItem box = getBox(bbox); - boolean finished = search(box, cb, context); - boxPool.release(box); - return finished; - } + @Override + public boolean search(Box bbox, SearchCb cb, Object context) { + BoxItem box = getBox(bbox); + boolean finished = search(box, cb, context); + boxPool.release(box); + return finished; + } } diff --git a/vtm/src/org/oscim/utils/RTree.java b/vtm/src/org/oscim/utils/RTree.java index b7b18105..9137376b 100644 --- a/vtm/src/org/oscim/utils/RTree.java +++ b/vtm/src/org/oscim/utils/RTree.java @@ -16,10 +16,6 @@ */ package org.oscim.utils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import org.oscim.core.Box; import org.oscim.utils.RTree.Branch; import org.oscim.utils.RTree.Node; @@ -29,9 +25,13 @@ import org.oscim.utils.pool.SyncPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * Implementation of RTree, a multidimensional bounding rectangle tree. - * + * * @author 1983 Original algorithm and test code by Antonin Guttman and Michael * Stonebraker, UC Berkely * @author 1994 ANCI C ported from original test code by Melinda Green - @@ -43,1236 +43,1277 @@ import org.slf4j.LoggerFactory; */ public class RTree implements SpatialIndex, Iterable { - static final Logger log = LoggerFactory.getLogger(RTree.class); + static final Logger log = LoggerFactory.getLogger(RTree.class); - final static int MAXNODES = 8; - final static int MINNODES = 4; + final static int MAXNODES = 8; + final static int MINNODES = 4; - final static int NUMDIMS = 2; + final static int NUMDIMS = 2; - static final boolean DEBUG = true; + static final boolean DEBUG = true; - /** - * A Branch may be data or may be another subtree - * The parents level determines this. - * If the parents level is 0, then this is data - */ - final static class Branch extends Rect { - /** Child node or data item */ - E node; + /** + * A Branch may be data or may be another subtree + * The parents level determines this. + * If the parents level is 0, then this is data + */ + final static class Branch extends Rect { + /** + * Child node or data item + */ + E node; - @Override - public String toString() { - return node.toString(); - } - } + @Override + public String toString() { + return node.toString(); + } + } - /** - * Node for each branch level - */ - final static class Node { + /** + * Node for each branch level + */ + final static class Node { - /** Leaf is zero, others positive */ - int level = -1; + /** + * Leaf is zero, others positive + */ + int level = -1; - /** Fill count */ - int count; + /** + * Fill count + */ + int count; - /** Branches */ - final Branch branch[]; + /** + * Branches + */ + final Branch branch[]; - public Node(int maxnodes) { - branch = new Branch[maxnodes]; - } + public Node(int maxnodes) { + branch = new Branch[maxnodes]; + } - /** A leaf, contains data */ - boolean isLeaf() { - return (level == 0); - } + /** + * A leaf, contains data + */ + boolean isLeaf() { + return (level == 0); + } - @SuppressWarnings("unchecked") - Branch[] children() { - if (level == 0) - throw new IllegalStateException(); + @SuppressWarnings("unchecked") + Branch[] children() { + if (level == 0) + throw new IllegalStateException(); - return (Branch[]) branch; - } + return (Branch[]) branch; + } - /** - * Add a branch to a node. Split the node if necessary. - * - * @return false if node not split. Old node will be - * updated. - * Otherwise if node split, sets newNode to address of new node. - * Old node updated, becomes one of two. - */ - boolean addBranch(Branch branch) { - assert (branch != null); + /** + * Add a branch to a node. Split the node if necessary. + * + * @return false if node not split. Old node will be + * updated. + * Otherwise if node split, sets newNode to address of new node. + * Old node updated, becomes one of two. + */ + boolean addBranch(Branch branch) { + assert (branch != null); - if (count < MAXNODES) { - /* Split won't be necessary */ - this.branch[count] = branch; - count++; - return false; - } + if (count < MAXNODES) { + /* Split won't be necessary */ + this.branch[count] = branch; + count++; + return false; + } - return true; - } + return true; + } - @Override - public String toString() { - return count + "/" + Arrays.deepToString(branch) + '\n'; - } - } + @Override + public String toString() { + return count + "/" + Arrays.deepToString(branch) + '\n'; + } + } - /** Minimal bounding rectangle (n-dimensional) */ - static class Rect { + /** + * Minimal bounding rectangle (n-dimensional) + */ + static class Rect { - /** dimensions of bounding box */ - double xmin, ymin, xmax, ymax; + /** + * dimensions of bounding box + */ + double xmin, ymin, xmax, ymax; - public Rect() { - } + public Rect() { + } - public Rect(Box box) { - if (DEBUG) { - assert (xmin <= xmax); - assert (ymin <= ymax); - } + public Rect(Box box) { + if (DEBUG) { + assert (xmin <= xmax); + assert (ymin <= ymax); + } - xmin = box.xmin; - ymin = box.ymin; - xmax = box.xmax; - ymax = box.ymax; - } + xmin = box.xmin; + ymin = box.ymin; + xmax = box.xmax; + ymax = box.ymax; + } - public Rect(double[] min, double[] max) { + public Rect(double[] min, double[] max) { - if (DEBUG) { - for (int index = 0; index < NUMDIMS; index++) - assert (min[index] <= max[index]); - } + if (DEBUG) { + for (int index = 0; index < NUMDIMS; index++) + assert (min[index] <= max[index]); + } - xmin = min[0]; - ymin = min[1]; - xmax = max[0]; - ymax = max[1]; - } + xmin = min[0]; + ymin = min[1]; + xmax = max[0]; + ymax = max[1]; + } - /** - * Calculate the n-dimensional volume of a rectangle - */ - public double calcRectVolume() { - return (xmax - xmin) * (ymax - ymin); - } + /** + * Calculate the n-dimensional volume of a rectangle + */ + public double calcRectVolume() { + return (xmax - xmin) * (ymax - ymin); + } - /** - * Decide whether two rectangles overlap. - */ - public boolean overlap(Rect other) { - return !(xmin > other.xmax || xmax < other.xmin || ymin > other.ymax || ymax < other.ymin); - } + /** + * Decide whether two rectangles overlap. + */ + public boolean overlap(Rect other) { + return !(xmin > other.xmax || xmax < other.xmin || ymin > other.ymax || ymax < other.ymin); + } - /** - * Combine two rectangles into larger one containing both - */ - public void combine(Rect rectA, Rect rectB) { - xmin = Math.min(rectA.xmin, rectB.xmin); - ymin = Math.min(rectA.ymin, rectB.ymin); - xmax = Math.max(rectA.xmax, rectB.xmax); - ymax = Math.max(rectA.ymax, rectB.ymax); - } + /** + * Combine two rectangles into larger one containing both + */ + public void combine(Rect rectA, Rect rectB) { + xmin = Math.min(rectA.xmin, rectB.xmin); + ymin = Math.min(rectA.ymin, rectB.ymin); + xmax = Math.max(rectA.xmax, rectB.xmax); + ymax = Math.max(rectA.ymax, rectB.ymax); + } - public void add(Rect rect) { - xmin = Math.min(xmin, rect.xmin); - ymin = Math.min(ymin, rect.ymin); - xmax = Math.max(xmax, rect.xmax); - ymax = Math.max(ymax, rect.ymax); - } + public void add(Rect rect) { + xmin = Math.min(xmin, rect.xmin); + ymin = Math.min(ymin, rect.ymin); + xmax = Math.max(xmax, rect.xmax); + ymax = Math.max(ymax, rect.ymax); + } - public void set(Rect rect) { - xmin = rect.xmin; - ymin = rect.ymin; - xmax = rect.xmax; - ymax = rect.ymax; - } + public void set(Rect rect) { + xmin = rect.xmin; + ymin = rect.ymin; + xmax = rect.xmax; + ymax = rect.ymax; + } - public void set(double[] min, double[] max) { - if (DEBUG) { - for (int index = 0; index < NUMDIMS; index++) { - assert (min[index] <= max[index]); - } - } + public void set(double[] min, double[] max) { + if (DEBUG) { + for (int index = 0; index < NUMDIMS; index++) { + assert (min[index] <= max[index]); + } + } - xmin = min[0]; - ymin = min[1]; - xmax = max[0]; - ymax = max[1]; - } + xmin = min[0]; + ymin = min[1]; + xmax = max[0]; + ymax = max[1]; + } - public void set(Box box) { - if (DEBUG) { - assert (box.xmin <= box.xmax); - assert (box.ymin <= box.ymax); - } - xmin = box.xmin; - ymin = box.ymin; - xmax = box.xmax; - ymax = box.ymax; - } + public void set(Box box) { + if (DEBUG) { + assert (box.xmin <= box.xmax); + assert (box.ymin <= box.ymax); + } + xmin = box.xmin; + ymin = box.ymin; + xmax = box.xmax; + ymax = box.ymax; + } - /** - * Find the smallest rectangle that includes all rectangles in branches - * of a node. - */ - void setCover(Node node) { - assert (node != null); + /** + * Find the smallest rectangle that includes all rectangles in branches + * of a node. + */ + void setCover(Node node) { + assert (node != null); - set(node.branch[0]); - for (int idx = 1; idx < node.count; idx++) { - add(node.branch[idx]); - } - } - } + set(node.branch[0]); + for (int idx = 1; idx < node.count; idx++) { + add(node.branch[idx]); + } + } + } - /** Root of tree */ - protected Node mRoot; + /** + * Root of tree + */ + protected Node mRoot; - private final Partition mLocalVars = new Partition(MAXNODES, MINNODES); + private final Partition mLocalVars = new Partition(MAXNODES, MINNODES); - private Rect mTmpRect = new Rect(); + private Rect mTmpRect = new Rect(); - private Rect getRect() { - if (mTmpRect == null) { - return new Rect(); - } - Rect r = mTmpRect; - mTmpRect = null; - return r; - } + private Rect getRect() { + if (mTmpRect == null) { + return new Rect(); + } + Rect r = mTmpRect; + mTmpRect = null; + return r; + } - private void releaseRect(Rect r) { - mTmpRect = r; - } + private void releaseRect(Rect r) { + mTmpRect = r; + } - public RTree() { - mRoot = allocNode(); - mRoot.level = 0; - } + public RTree() { + mRoot = allocNode(); + mRoot.level = 0; + } - /** - * Insert item. - * - * @param min Min of bounding rect - * @param max Max of bounding rect - * @param item data. - */ - public void insert(double min[], double max[], T item) { - Rect r = getRect(); - r.set(min, max); - insertRect(r, item, 0); - releaseRect(r); - } + /** + * Insert item. + * + * @param min Min of bounding rect + * @param max Max of bounding rect + * @param item data. + */ + public void insert(double min[], double max[], T item) { + Rect r = getRect(); + r.set(min, max); + insertRect(r, item, 0); + releaseRect(r); + } - public void insert(Box box, T item) { - Rect r = getRect(); - r.set(box); - insertRect(r, item, 0); - releaseRect(r); - } + public void insert(Box box, T item) { + Rect r = getRect(); + r.set(box); + insertRect(r, item, 0); + releaseRect(r); + } - /** - * Remove item. - * - * @param min Min of bounding rect - * @param max Max of bounding rect - * @param item data. - */ - public boolean remove(double min[], double max[], T item) { - Rect r = getRect(); - r.set(min, max); - boolean removed = removeRect(r, item); - releaseRect(r); - return removed; - } + /** + * Remove item. + * + * @param min Min of bounding rect + * @param max Max of bounding rect + * @param item data. + */ + public boolean remove(double min[], double max[], T item) { + Rect r = getRect(); + r.set(min, max); + boolean removed = removeRect(r, item); + releaseRect(r); + return removed; + } - public boolean remove(Box box, T item) { - Rect r = getRect(); - r.set(box); - boolean removed = removeRect(r, item); - releaseRect(r); - return removed; - } + public boolean remove(Box box, T item) { + Rect r = getRect(); + r.set(box); + boolean removed = removeRect(r, item); + releaseRect(r); + return removed; + } - /** - * Find all items within search rectangle. - * - * @param a_min Min of search bounding rect - * @param a_max Max of search bounding rect - * @param a_searchResult Search result array. Caller should set grow size. - * Function will reset, not append to array. - * @param a_resultCallback Callback function to return result. Callback - * should return 'true' to continue searching - * @param a_context User context to pass as parameter to a_resultCallback - * @return Returns the number of entries found - */ - public boolean search(double min[], double max[], SearchCb cb, Object context) { - Rect r = getRect(); - r.set(min, max); + /** + * Find all items within search rectangle. + * + * @param a_min Min of search bounding rect + * @param a_max Max of search bounding rect + * @param a_searchResult Search result array. Caller should set grow size. + * Function will reset, not append to array. + * @param a_resultCallback Callback function to return result. Callback + * should return 'true' to continue searching + * @param a_context User context to pass as parameter to a_resultCallback + * @return Returns the number of entries found + */ + public boolean search(double min[], double max[], SearchCb cb, Object context) { + Rect r = getRect(); + r.set(min, max); - searchStack(r, cb, context); + searchStack(r, cb, context); - releaseRect(r); - return true; - } + releaseRect(r); + return true; + } - public boolean search(Box bbox, SearchCb cb, Object context) { - Rect r = getRect(); - r.set(bbox); + public boolean search(Box bbox, SearchCb cb, Object context) { + Rect r = getRect(); + r.set(bbox); - searchStack(r, cb, context); + searchStack(r, cb, context); - releaseRect(r); - return true; - } + releaseRect(r); + return true; + } - public List search(Box bbox, List results) { - if (results == null) - results = new ArrayList(16); + public List search(Box bbox, List results) { + if (results == null) + results = new ArrayList(16); - Rect r = getRect(); - r.set(bbox); + Rect r = getRect(); + r.set(bbox); - //search(mRoot, r, results); - searchStack(r, results); + //search(mRoot, r, results); + searchStack(r, results); - releaseRect(r); - return results; - } + releaseRect(r); + return results; + } - /** - * Count the data elements in this container. This is slow as no internal - * counter is maintained. - */ - public int size() { - int[] count = { 0 }; - countRec(mRoot, count); + /** + * Count the data elements in this container. This is slow as no internal + * counter is maintained. + */ + public int size() { + int[] count = {0}; + countRec(mRoot, count); - return count[0]; - } + return count[0]; + } - private void countRec(Node node, int[] count) { - if (node.isLeaf()) { - count[0] += node.count; - return; - } + private void countRec(Node node, int[] count) { + if (node.isLeaf()) { + count[0] += node.count; + return; + } /* not a leaf node */ - Branch[] children = node.children(); - for (int idx = 0; idx < node.count; idx++) { - countRec(children[idx].node, count); - } - } + Branch[] children = node.children(); + for (int idx = 0; idx < node.count; idx++) { + countRec(children[idx].node, count); + } + } - /** - * Remove all entries from tree. - */ - public void clear() { - /* Delete all existing nodes */ - reset(); + /** + * Remove all entries from tree. + */ + public void clear() { + /* Delete all existing nodes */ + reset(); - mRoot = allocNode(); - mRoot.level = 0; - } + mRoot = allocNode(); + mRoot.level = 0; + } - void reset() { - removeAllRec(mRoot); - } + void reset() { + removeAllRec(mRoot); + } - void removeAllRec(Node node) { - assert (node != null); - assert (node.level >= 0); + void removeAllRec(Node node) { + assert (node != null); + assert (node.level >= 0); - if (!node.isLeaf()) { - Branch[] children = node.children(); + if (!node.isLeaf()) { + Branch[] children = node.children(); /* This is an internal node in the tree */ - for (int idx = 0; idx < node.count; idx++) { - removeAllRec(children[idx].node); - } - } - freeNode(node); - } + for (int idx = 0; idx < node.count; idx++) { + removeAllRec(children[idx].node); + } + } + freeNode(node); + } - public int nodesAlloc; - public int nodesFree; + public int nodesAlloc; + public int nodesFree; - public void printStats() { - System.out.println("nodes alloc:\t" + nodesAlloc); - System.out.println("nodes free:\t" + nodesFree); + public void printStats() { + System.out.println("nodes alloc:\t" + nodesAlloc); + System.out.println("nodes free:\t" + nodesFree); - } + } - Node allocNode() { - nodesAlloc++; - Node newNode; - newNode = new Node(MAXNODES); - return newNode; - } + Node allocNode() { + nodesAlloc++; + Node newNode; + newNode = new Node(MAXNODES); + return newNode; + } - void freeNode(Node node) { - nodesFree++; - assert (node != null); - } + void freeNode(Node node) { + nodesFree++; + assert (node != null); + } - /** - * Inserts a new data rectangle into the index structure. - * Recursively descends tree, propagates splits back up. - * - * @param level The level argument specifies the number of steps up from the - * leaf level to insert; - * e.g. a data rectangle goes in at level = 0. - * - * @return false if node was not split, old node was updated. - * If node was split, returns true and sets the pointer - * pointed to by newNode to point to the new node. Old node is - * updated to become one of two. - */ - private Node insertRectRec(Rect rect, T item, Node node, int level) { - //assert (rect != null && node != null && newNode != null); - //assert (level >= 0 && level <= node.level); + /** + * Inserts a new data rectangle into the index structure. + * Recursively descends tree, propagates splits back up. + * + * @param level The level argument specifies the number of steps up from the + * leaf level to insert; + * e.g. a data rectangle goes in at level = 0. + * @return false if node was not split, old node was updated. + * If node was split, returns true and sets the pointer + * pointed to by newNode to point to the new node. Old node is + * updated to become one of two. + */ + private Node insertRectRec(Rect rect, T item, Node node, int level) { + //assert (rect != null && node != null && newNode != null); + //assert (level >= 0 && level <= node.level); - if (node.level > level) { + if (node.level > level) { /* Still above level for insertion, go down tree recursively */ - int idx = pickBranch(node, rect); - Branch[] children = node.children(); + int idx = pickBranch(node, rect); + Branch[] children = node.children(); - Node newNode = insertRectRec(rect, item, children[idx].node, level); - if (newNode != null) { + Node newNode = insertRectRec(rect, item, children[idx].node, level); + if (newNode != null) { /* Child was split */ - node.branch[idx].setCover(children[idx].node); - Branch branch = new Branch(); - branch.node = newNode; - branch.setCover(newNode); - if (node.addBranch(branch)) { - return splitNode(node, branch); - } - return null; - } else { + node.branch[idx].setCover(children[idx].node); + Branch branch = new Branch(); + branch.node = newNode; + branch.setCover(newNode); + if (node.addBranch(branch)) { + return splitNode(node, branch); + } + return null; + } else { /* Child was not split */ - node.branch[idx].add(rect); - return null; - } - } + node.branch[idx].add(rect); + return null; + } + } /* Have reached level for insertion. Add rect, split if necessary */ - assert (node.level == level); - Branch branch = new Branch(); - branch.set(rect); - branch.node = item; + assert (node.level == level); + Branch branch = new Branch(); + branch.set(rect); + branch.node = item; /* Child field of leaves contains id of data record */ - if (node.addBranch(branch)) { - return splitNode(node, branch); - } - return null; - } + if (node.addBranch(branch)) { + return splitNode(node, branch); + } + return null; + } - final static double mergedArea(Rect a, Rect b) { - return ((a.xmax > b.xmax ? a.xmax : b.xmax) - (a.xmin < b.xmin ? a.xmin : b.xmin) - * ((a.ymax > b.ymax ? a.ymax : b.ymax) - (a.ymin < b.ymin ? a.ymin : b.ymin))); - } + final static double mergedArea(Rect a, Rect b) { + return ((a.xmax > b.xmax ? a.xmax : b.xmax) - (a.xmin < b.xmin ? a.xmin : b.xmin) + * ((a.ymax > b.ymax ? a.ymax : b.ymax) - (a.ymin < b.ymin ? a.ymin : b.ymin))); + } - /** - * Pick a branch. Pick the one that will need the smallest increase - * in area to accomodate the new rectangle. This will result in the - * least total area for the covering rectangles in the current node. - * In case of a tie, pick the one which was smaller before, to get - * the best resolution when searching. - */ - int pickBranch(Node node, Rect rect) { - boolean firstTime = true; - double increase; - double bestIncr = (double) -1; - double area; - double bestArea = 0; - int best = 0; + /** + * Pick a branch. Pick the one that will need the smallest increase + * in area to accomodate the new rectangle. This will result in the + * least total area for the covering rectangles in the current node. + * In case of a tie, pick the one which was smaller before, to get + * the best resolution when searching. + */ + int pickBranch(Node node, Rect rect) { + boolean firstTime = true; + double increase; + double bestIncr = (double) -1; + double area; + double bestArea = 0; + int best = 0; - for (int idx = 0; idx < node.count; idx++) { - Rect curRect = node.branch[idx]; - area = curRect.calcRectVolume(); + for (int idx = 0; idx < node.count; idx++) { + Rect curRect = node.branch[idx]; + area = curRect.calcRectVolume(); - increase = mergedArea(rect, curRect) - area; + increase = mergedArea(rect, curRect) - area; - if ((increase < bestIncr) || firstTime) { - best = idx; - bestArea = area; - bestIncr = increase; - firstTime = false; - } else if ((increase == bestIncr) && (area < bestArea)) { - best = idx; - bestArea = area; - bestIncr = increase; - } - } - return best; - } + if ((increase < bestIncr) || firstTime) { + best = idx; + bestArea = area; + bestIncr = increase; + firstTime = false; + } else if ((increase == bestIncr) && (area < bestArea)) { + best = idx; + bestArea = area; + bestIncr = increase; + } + } + return best; + } - /** - * Insert a data rectangle into an index structure. - * InsertRect provides for splitting the root; - * returns 1 if root was split, 0 if it was not. - * The level argument specifies the number of steps up from the leaf - * level to insert; e.g. a data rectangle goes in at level = 0. - * InsertRect2 does the recursion. - */ - public boolean insertRect(Rect rect, T item, int level) { - // if (DEBUG) { - // assert (rect != null && root != null); - // assert (level >= 0 && level <= root.level); - // } + /** + * Insert a data rectangle into an index structure. + * InsertRect provides for splitting the root; + * returns 1 if root was split, 0 if it was not. + * The level argument specifies the number of steps up from the leaf + * level to insert; e.g. a data rectangle goes in at level = 0. + * InsertRect2 does the recursion. + */ + public boolean insertRect(Rect rect, T item, int level) { + // if (DEBUG) { + // assert (rect != null && root != null); + // assert (level >= 0 && level <= root.level); + // } - Node root = mRoot; - Node newNode = insertRectRec(rect, item, root, level); + Node root = mRoot; + Node newNode = insertRectRec(rect, item, root, level); - if (newNode != null) { + if (newNode != null) { /* Root split, Grow tree taller and new root */ - Node newRoot = allocNode(); - newRoot.level = root.level + 1; + Node newRoot = allocNode(); + newRoot.level = root.level + 1; - Branch branch = new Branch(); - branch.setCover(root); - branch.node = root; - newRoot.addBranch(branch); + Branch branch = new Branch(); + branch.setCover(root); + branch.node = root; + newRoot.addBranch(branch); - branch = new Branch(); - branch.setCover(newNode); - branch.node = newNode; - newRoot.addBranch(branch); + branch = new Branch(); + branch.setCover(newNode); + branch.node = newNode; + newRoot.addBranch(branch); - mRoot = newRoot; + mRoot = newRoot; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * Disconnect a dependent node. - * Caller must return (or stop using iteration index) after this as count - * has changed. - */ - void disconnectBranch(Node node, int idx) { - assert (node != null && (idx >= 0) && (idx < MAXNODES)); - assert (node.count > 0); + /** + * Disconnect a dependent node. + * Caller must return (or stop using iteration index) after this as count + * has changed. + */ + void disconnectBranch(Node node, int idx) { + assert (node != null && (idx >= 0) && (idx < MAXNODES)); + assert (node.count > 0); /* Remove element by swapping with the last element to * prevent gaps in array */ - node.count--; + node.count--; - if (node.count != idx) { - node.branch[idx] = node.branch[node.count]; - } - node.branch[node.count] = null; - } + if (node.count != idx) { + node.branch[idx] = node.branch[node.count]; + } + node.branch[node.count] = null; + } - /** - * Split a node. - * Divides the nodes branches and the extra one between two nodes. - * Old node is one of the new ones, and one really new one is created. - * Tries more than one method for choosing a partition, uses best result. - */ - Node splitNode(Node node, Branch branch) { - assert (node != null); - assert (branch != null); + /** + * Split a node. + * Divides the nodes branches and the extra one between two nodes. + * Old node is one of the new ones, and one really new one is created. + * Tries more than one method for choosing a partition, uses best result. + */ + Node splitNode(Node node, Branch branch) { + assert (node != null); + assert (branch != null); - Partition partition = mLocalVars.clear(); + Partition partition = mLocalVars.clear(); /* Load all the branches into a buffer, initialize old node */ - int level = node.level; - partition.getBranches(node, branch); + int level = node.level; + partition.getBranches(node, branch); /* Find partition */ - partition.choosePartition(); + partition.choosePartition(); /* Put branches from buffer into 2 nodes according to * chosen partition */ - Node newNode = allocNode(); - newNode.level = node.level = level; - partition.loadNodes(node, newNode); + Node newNode = allocNode(); + newNode.level = node.level = level; + partition.loadNodes(node, newNode); - assert ((node.count + newNode.count) == partition.total); + assert ((node.count + newNode.count) == partition.total); - for (int i = node.count; i < MAXNODES; i++) - node.branch[i] = null; + for (int i = node.count; i < MAXNODES; i++) + node.branch[i] = null; - return newNode; - } + return newNode; + } - private final ArrayList mReinsertNodes = new ArrayList(); + private final ArrayList mReinsertNodes = new ArrayList(); - /** - * Delete a data rectangle from an index structure. - * Pass in a pointer to a Rect, the tid of the record, ptr to ptr to root - * node. - * - * @return false if record not found, true if - * success. - * RemoveRect provides for eliminating the root. - */ - @SuppressWarnings("unchecked") - public boolean removeRect(Rect rect, T item) { - //assert (rect != null && root != null); - //assert (root != null); + /** + * Delete a data rectangle from an index structure. + * Pass in a pointer to a Rect, the tid of the record, ptr to ptr to root + * node. + * + * @return false if record not found, true if + * success. + * RemoveRect provides for eliminating the root. + */ + @SuppressWarnings("unchecked") + public boolean removeRect(Rect rect, T item) { + //assert (rect != null && root != null); + //assert (root != null); - Node root = mRoot; + Node root = mRoot; - ArrayList reInsertList = mReinsertNodes; + ArrayList reInsertList = mReinsertNodes; - if (removeRectRec(rect, item, root, reInsertList)) { + if (removeRectRec(rect, item, root, reInsertList)) { /* Found and deleted a data item * Reinsert any branches from eliminated nodes */ - for (Node node : reInsertList) { - for (int idx = 0; idx < node.count; idx++) { - insertRect((node.branch[idx]), - (T) node.branch[idx].node, - node.level); - } - freeNode(node); - } - reInsertList.clear(); + for (Node node : reInsertList) { + for (int idx = 0; idx < node.count; idx++) { + insertRect((node.branch[idx]), + (T) node.branch[idx].node, + node.level); + } + freeNode(node); + } + reInsertList.clear(); /* Check for redundant root (not leaf, 1 child) and eliminate */ - if (root.count == 1 && !root.isLeaf()) { + if (root.count == 1 && !root.isLeaf()) { - Node tempNode = root.children()[0].node; - assert (tempNode != null); + Node tempNode = root.children()[0].node; + assert (tempNode != null); - freeNode(root); - mRoot = tempNode; - } - return true; - } - return false; - } + freeNode(root); + mRoot = tempNode; + } + return true; + } + return false; + } - /** - * Delete a rectangle from non-root part of an index structure. - * Called by RemoveRect. Descends tree recursively, merges - * branches on the way back up. - * - * @return true iff record found. - */ - private boolean removeRectRec(Rect rect, T item, Node node, ArrayList removed) { - assert (rect != null && node != null && removed != null); - assert (node.level >= 0); + /** + * Delete a rectangle from non-root part of an index structure. + * Called by RemoveRect. Descends tree recursively, merges + * branches on the way back up. + * + * @return true iff record found. + */ + private boolean removeRectRec(Rect rect, T item, Node node, ArrayList removed) { + assert (rect != null && node != null && removed != null); + assert (node.level >= 0); - if (node.isLeaf()) { - for (int idx = 0; idx < node.count; idx++) { - if (node.branch[idx].node == item) { + if (node.isLeaf()) { + for (int idx = 0; idx < node.count; idx++) { + if (node.branch[idx].node == item) { /* Must return after this call as count has changed */ - disconnectBranch(node, idx); - return true; - } - } - return false; - } + disconnectBranch(node, idx); + return true; + } + } + return false; + } /* not a leaf node */ - for (int idx = 0; idx < node.count; idx++) { + for (int idx = 0; idx < node.count; idx++) { - if (!rect.overlap(node.branch[idx])) - continue; + if (!rect.overlap(node.branch[idx])) + continue; - Branch[] children = node.children(); - if (removeRectRec(rect, item, children[idx].node, removed)) { - if (children[idx].node.count >= MINNODES) { + Branch[] children = node.children(); + if (removeRectRec(rect, item, children[idx].node, removed)) { + if (children[idx].node.count >= MINNODES) { /* child removed, just resize parent rect */ - children[idx].setCover(children[idx].node); - } else { + children[idx].setCover(children[idx].node); + } else { /* child removed, not enough entries in node, * eliminate node */ - removed.add(children[idx].node); + removed.add(children[idx].node); /* Must return after this call as count has changed */ - disconnectBranch(node, idx); - } - return true; - } - } - return false; - } + disconnectBranch(node, idx); + } + return true; + } + } + return false; + } - // /** - // * Search in an index tree or subtree for all data retangles that overlap - // * the argument rectangle. - // */ - // public boolean search(Node node, Rect rect, int[] found, SearchCallback cb, - // Object context) { - // if (DEBUG) { - // assert (node != null); - // assert (node.level >= 0); - // assert (rect != null); - // } - // - // if (!node.isLeaf()) { - // Branch[] children = node.children(); - // /* This is an internal node in the tree */ - // for (int idx = 0; idx < node.count; idx++) { - // - // if (rect.overlap(children[idx])) { - // if (!search(children[idx].node, rect, found, cb, context)) { - // /* Stop searching */ - // return false; - // } - // } - // } - // /* Continue searching */ - // return true; - // } - // - // /* This is a leaf node */ - // for (int idx = 0; idx < node.count; idx++) { - // if (rect.overlap(node.branch[idx])) { - // @SuppressWarnings("unchecked") - // T item = (T) node.branch[idx].node; - // - // /* NOTE: There are different ways to return results. Here's - // * where to modify */ - // found[0]++; - // if (!cb.call(item, context)) { - // /* Stop searching */ - // return false; - // } - // } - // } - // - // /* Continue searching */ - // return true; - // } - // - // public boolean search(Node node, Rect rect, List results) { - // if (DEBUG) { - // assert (node != null); - // assert (node.level >= 0); - // assert (rect != null); - // } - // - // if (!node.isLeaf()) { - // Branch[] children = node.children(); - // /* This is an internal node in the tree */ - // for (int idx = 0; idx < node.count; idx++) { - // - // if (rect.overlap(children[idx])) { - // if (!search(children[idx].node, rect, results)) { - // /* Stop searching */ - // return false; - // } - // } - // } - // /* Continue searching */ - // return true; - // } - // - // /* This is a leaf node */ - // for (int idx = 0; idx < node.count; idx++) { - // if (rect.overlap(node.branch[idx])) { - // @SuppressWarnings("unchecked") - // T item = (T) node.branch[idx].node; - // - // results.add(item); - // } - // } - // - // /* Continue searching */ - // return true; - // } + // /** + // * Search in an index tree or subtree for all data retangles that overlap + // * the argument rectangle. + // */ + // public boolean search(Node node, Rect rect, int[] found, SearchCallback cb, + // Object context) { + // if (DEBUG) { + // assert (node != null); + // assert (node.level >= 0); + // assert (rect != null); + // } + // + // if (!node.isLeaf()) { + // Branch[] children = node.children(); + // /* This is an internal node in the tree */ + // for (int idx = 0; idx < node.count; idx++) { + // + // if (rect.overlap(children[idx])) { + // if (!search(children[idx].node, rect, found, cb, context)) { + // /* Stop searching */ + // return false; + // } + // } + // } + // /* Continue searching */ + // return true; + // } + // + // /* This is a leaf node */ + // for (int idx = 0; idx < node.count; idx++) { + // if (rect.overlap(node.branch[idx])) { + // @SuppressWarnings("unchecked") + // T item = (T) node.branch[idx].node; + // + // /* NOTE: There are different ways to return results. Here's + // * where to modify */ + // found[0]++; + // if (!cb.call(item, context)) { + // /* Stop searching */ + // return false; + // } + // } + // } + // + // /* Continue searching */ + // return true; + // } + // + // public boolean search(Node node, Rect rect, List results) { + // if (DEBUG) { + // assert (node != null); + // assert (node.level >= 0); + // assert (rect != null); + // } + // + // if (!node.isLeaf()) { + // Branch[] children = node.children(); + // /* This is an internal node in the tree */ + // for (int idx = 0; idx < node.count; idx++) { + // + // if (rect.overlap(children[idx])) { + // if (!search(children[idx].node, rect, results)) { + // /* Stop searching */ + // return false; + // } + // } + // } + // /* Continue searching */ + // return true; + // } + // + // /* This is a leaf node */ + // for (int idx = 0; idx < node.count; idx++) { + // if (rect.overlap(node.branch[idx])) { + // @SuppressWarnings("unchecked") + // T item = (T) node.branch[idx].node; + // + // results.add(item); + // } + // } + // + // /* Continue searching */ + // return true; + // } - public void searchStack(Rect rect, SearchCb cb, Object context) { - Stack stack = stackPool.get(); - stack.push(mRoot, 0); + public void searchStack(Rect rect, SearchCb cb, Object context) { + Stack stack = stackPool.get(); + stack.push(mRoot, 0); - O: while (!stack.empty()) { - stack.pop(); - Node node = stack.node(); + O: + while (!stack.empty()) { + stack.pop(); + Node node = stack.node(); - if (node.level == 0) { + if (node.level == 0) { /* is leaf node */ - for (int idx = 0; idx < node.count; idx++) { - @SuppressWarnings("unchecked") - Branch branch[] = (Branch[]) node.branch; + for (int idx = 0; idx < node.count; idx++) { + @SuppressWarnings("unchecked") + Branch branch[] = (Branch[]) node.branch; - if (rect.overlap(branch[idx])) { - if (!cb.call(branch[idx].node, context)) - break O; - } - } - } else { - int idx = stack.branchIndex(); + if (rect.overlap(branch[idx])) { + if (!cb.call(branch[idx].node, context)) + break O; + } + } + } else { + int idx = stack.branchIndex(); /* Push sibling on stack for future tree walk. * This is the 'fall back' node when we finish with * the current level */ - for (int i = idx + 1; i < node.count; i++) { - if (rect.overlap(node.branch[i])) { - stack.push(node, i); - break; - } - } + for (int i = idx + 1; i < node.count; i++) { + if (rect.overlap(node.branch[i])) { + stack.push(node, i); + break; + } + } /* Push first of next level to get deeper into * the tree */ - node = (Node) node.branch[idx].node; - for (int i = 0; i < node.count; i++) { - if (rect.overlap(node.branch[i])) { - stack.push(node, i); - break; - } - } - } - } - stackPool.release(stack); - } + node = (Node) node.branch[idx].node; + for (int i = 0; i < node.count; i++) { + if (rect.overlap(node.branch[i])) { + stack.push(node, i); + break; + } + } + } + } + stackPool.release(stack); + } - public boolean searchStack(Rect rect, List results) { + public boolean searchStack(Rect rect, List results) { - @SuppressWarnings("unchecked") - List out = (List) results; + @SuppressWarnings("unchecked") + List out = (List) results; - Stack stack = stackPool.get(); - stack.push(mRoot, 0); + Stack stack = stackPool.get(); + stack.push(mRoot, 0); - while (!stack.empty()) { - stack.pop(); - Node node = stack.node(); + while (!stack.empty()) { + stack.pop(); + Node node = stack.node(); - if (node.level == 0) { + if (node.level == 0) { /* is leaf node */ - for (int idx = 0; idx < node.count; idx++) { - if (rect.overlap(node.branch[idx])) { - out.add(node.branch[idx].node); - } - } - } else { - int idx = stack.branchIndex(); + for (int idx = 0; idx < node.count; idx++) { + if (rect.overlap(node.branch[idx])) { + out.add(node.branch[idx].node); + } + } + } else { + int idx = stack.branchIndex(); /* Push sibling on stack for future tree walk. * This is the 'fall back' node when we finish with * the current level */ - for (int i = idx + 1; i < node.count; i++) { - if (rect.overlap(node.branch[i])) { - stack.push(node, i); - break; - } - } + for (int i = idx + 1; i < node.count; i++) { + if (rect.overlap(node.branch[i])) { + stack.push(node, i); + break; + } + } /* Push first of next level* to get deeper into * the tree */ - node = (Node) node.branch[idx].node; - for (int i = 0; i < node.count; i++) { - if (rect.overlap(node.branch[i])) { - stack.push(node, i); - break; - } - } - } - } - stackPool.release(stack); - return true; - } + node = (Node) node.branch[idx].node; + for (int i = 0; i < node.count; i++) { + if (rect.overlap(node.branch[i])) { + stack.push(node, i); + break; + } + } + } + } + stackPool.release(stack); + return true; + } - /* Max stack size. Allows almost n^32 where n is number of branches in - * node */ - final static int MAX_STACK = 32; + /* Max stack size. Allows almost n^32 where n is number of branches in + * node */ + final static int MAX_STACK = 32; - static class StackElement { - Node node; - int branchIndex; - }; + static class StackElement { + Node node; + int branchIndex; + } - SyncPool stackPool = new SyncPool(10) { - @Override - protected Stack createItem() { - return new Stack(); - } + ; - protected boolean clearItem(Stack item) { - if (item.tos != 0) { - item.tos = 0; - Arrays.fill(item.nodes, null); - } - return true; - }; - }; + SyncPool stackPool = new SyncPool(10) { + @Override + protected Stack createItem() { + return new Stack(); + } - static class Stack extends Inlist { - /** Top Of Stack index */ - int tos; + protected boolean clearItem(Stack item) { + if (item.tos != 0) { + item.tos = 0; + Arrays.fill(item.nodes, null); + } + return true; + } - final Node[] nodes; - final int[] branchIndex; + ; + }; - Stack() { - nodes = new Node[MAX_STACK]; - branchIndex = new int[MAX_STACK]; - } + static class Stack extends Inlist { + /** + * Top Of Stack index + */ + int tos; - void push(Node node, int pos) { - nodes[tos] = node; - branchIndex[tos] = pos; - tos++; - assert (tos <= MAX_STACK); - } + final Node[] nodes; + final int[] branchIndex; - /** Pop element off iteration stack (For internal use only) */ - boolean pop() { - assert (tos > 0); - nodes[tos] = null; - tos--; - //return stack[tos]; - return tos >= 0; - } + Stack() { + nodes = new Node[MAX_STACK]; + branchIndex = new int[MAX_STACK]; + } - Node node() { - return nodes[tos]; - } + void push(Node node, int pos) { + nodes[tos] = node; + branchIndex[tos] = pos; + tos++; + assert (tos <= MAX_STACK); + } - int branchIndex() { - return branchIndex[tos]; - } + /** + * Pop element off iteration stack (For internal use only) + */ + boolean pop() { + assert (tos > 0); + nodes[tos] = null; + tos--; + //return stack[tos]; + return tos >= 0; + } - boolean empty() { - return tos <= 0; - } - } + Node node() { + return nodes[tos]; + } - /* Iterator is not remove safe. */ - public static class Iterator implements java.util.Iterator { + int branchIndex() { + return branchIndex[tos]; + } - /** Stack as we are doing iteration instead of recursion */ - final StackElement stack[] = new StackElement[MAX_STACK]; + boolean empty() { + return tos <= 0; + } + } - /** Top Of Stack index */ - int tos; + /* Iterator is not remove safe. */ + public static class Iterator implements java.util.Iterator { - Iterator(Node root) { - for (int i = 0; i < MAX_STACK; i++) - stack[i] = new StackElement(); + /** + * Stack as we are doing iteration instead of recursion + */ + final StackElement stack[] = new StackElement[MAX_STACK]; - push(root, 0); + /** + * Top Of Stack index + */ + int tos; - findNextData(); - } + Iterator(Node root) { + for (int i = 0; i < MAX_STACK; i++) + stack[i] = new StackElement(); - /** Is iterator invalid */ - boolean isNull() { - return (tos <= 0); - } + push(root, 0); - /** Is iterator pointing to valid data */ - boolean isNotNull() { - return (tos > 0); - } + findNextData(); + } - /* Find the next data element */ - @SuppressWarnings("unchecked") - public T next() { - assert (isNotNull()); - StackElement curTos = stack[tos - 1]; - T result = (T) curTos.node.branch[curTos.branchIndex].node; - curTos.branchIndex++; - findNextData(); - return result; - } + /** + * Is iterator invalid + */ + boolean isNull() { + return (tos <= 0); + } - /** Find the next data element in the tree (For internal use only) */ - boolean findNextData() { - for (;;) { - if (tos <= 0) - return false; + /** + * Is iterator pointing to valid data + */ + boolean isNotNull() { + return (tos > 0); + } + + /* Find the next data element */ + @SuppressWarnings("unchecked") + public T next() { + assert (isNotNull()); + StackElement curTos = stack[tos - 1]; + T result = (T) curTos.node.branch[curTos.branchIndex].node; + curTos.branchIndex++; + findNextData(); + return result; + } + + /** + * Find the next data element in the tree (For internal use only) + */ + boolean findNextData() { + for (; ; ) { + if (tos <= 0) + return false; /* Copy stack top cause it may change as we use it */ - StackElement curTos = pop(); + StackElement curTos = pop(); - if (curTos.node.isLeaf()) { + if (curTos.node.isLeaf()) { /* Keep walking through data while we can */ - if (curTos.branchIndex < curTos.node.count) { + if (curTos.branchIndex < curTos.node.count) { /* There is more data, just point to the next one */ - push(curTos.node, curTos.branchIndex); - return true; - } - continue; - } - int idx = curTos.branchIndex; + push(curTos.node, curTos.branchIndex); + return true; + } + continue; + } + int idx = curTos.branchIndex; /* No more data, so it will fall back to previous level */ - if (idx + 1 < curTos.node.count) { + if (idx + 1 < curTos.node.count) { /* Push sibling on stack for future tree walk. * This is the 'fall back' node when we finish with * the current level */ - push(curTos.node, idx + 1); - } + push(curTos.node, idx + 1); + } /* Since cur node is not a leaf, push first of next level * to get deeper into the tree */ - Node nextLevelnode = (Node) curTos.node.branch[idx].node; + Node nextLevelnode = (Node) curTos.node.branch[idx].node; - push(nextLevelnode, 0); + push(nextLevelnode, 0); /* If we pushed on a new leaf, exit as the data is ready * at TOS */ - if (nextLevelnode.isLeaf()) - return true; - } - } + if (nextLevelnode.isLeaf()) + return true; + } + } - /** Push node and branch onto iteration stack (For internal use only) */ - void push(Node node, int branchIndex) { - stack[tos].node = node; - stack[tos].branchIndex = branchIndex; - tos++; - assert (tos <= MAX_STACK); - } + /** + * Push node and branch onto iteration stack (For internal use only) + */ + void push(Node node, int branchIndex) { + stack[tos].node = node; + stack[tos].branchIndex = branchIndex; + tos++; + assert (tos <= MAX_STACK); + } - /** Pop element off iteration stack (For internal use only) */ - StackElement pop() { - assert (tos > 0); - tos--; - return stack[tos]; - } + /** + * Pop element off iteration stack (For internal use only) + */ + StackElement pop() { + assert (tos > 0); + tos--; + return stack[tos]; + } - @Override - public boolean hasNext() { - return isNotNull(); - } + @Override + public boolean hasNext() { + return isNotNull(); + } - @Override - public void remove() { + @Override + public void remove() { - } - } + } + } - @Override - public java.util.Iterator iterator() { - return new Iterator(mRoot); - } + @Override + public java.util.Iterator iterator() { + return new Iterator(mRoot); + } } -/** Temporary data and methods to split partition */ +/** + * Temporary data and methods to split partition + */ class Partition { - int total; - int minFill; + int total; + int minFill; - final int partition[]; - final boolean taken[]; - final int count[]; - final Rect cover[]; - final double area[]; + final int partition[]; + final boolean taken[]; + final int count[]; + final Rect cover[]; + final double area[]; - final Rect coverSplit; - double coverSplitArea; + final Rect coverSplit; + double coverSplitArea; - final Branch branchBuf[]; + final Branch branchBuf[]; - final double mTmpArea[]; + final double mTmpArea[]; - public Partition clear() { - int maxnodes = branchBuf.length; - for (int i = 0; i < maxnodes; i++) { - taken[i] = false; - partition[i] = -1; - } + public Partition clear() { + int maxnodes = branchBuf.length; + for (int i = 0; i < maxnodes; i++) { + taken[i] = false; + partition[i] = -1; + } - count[0] = count[1] = 0; - area[0] = area[1] = 0; + count[0] = count[1] = 0; + area[0] = area[1] = 0; - total = maxnodes; + total = maxnodes; - return this; - } + return this; + } - @SuppressWarnings("unchecked") - public Partition(int maxnodes, int minnodes) { - partition = new int[maxnodes + 1]; - taken = new boolean[maxnodes + 1]; - count = new int[2]; - area = new double[2]; - branchBuf = new Branch[maxnodes + 1]; - cover = new Rect[] { new Rect(), new Rect() }; - coverSplit = new Rect(); + @SuppressWarnings("unchecked") + public Partition(int maxnodes, int minnodes) { + partition = new int[maxnodes + 1]; + taken = new boolean[maxnodes + 1]; + count = new int[2]; + area = new double[2]; + branchBuf = new Branch[maxnodes + 1]; + cover = new Rect[]{new Rect(), new Rect()}; + coverSplit = new Rect(); - minFill = minnodes; + minFill = minnodes; - mTmpArea = new double[maxnodes + 1]; - } + mTmpArea = new double[maxnodes + 1]; + } - /** - * Copy branches from the buffer into two nodes according to the - * partition. - * - * FIXME this actually *moves* items from buffer! - */ - void loadNodes(Node nodeA, Node nodeB) { - assert (nodeA != null); - assert (nodeB != null); + /** + * Copy branches from the buffer into two nodes according to the + * partition. + *

+ * FIXME this actually *moves* items from buffer! + */ + void loadNodes(Node nodeA, Node nodeB) { + assert (nodeA != null); + assert (nodeB != null); - for (int idx = 0; idx < total; idx++) { - switch (partition[idx]) { - case 0: - nodeA.addBranch(branchBuf[idx]); - break; - case 1: - nodeB.addBranch(branchBuf[idx]); - break; - } - } - } + for (int idx = 0; idx < total; idx++) { + switch (partition[idx]) { + case 0: + nodeA.addBranch(branchBuf[idx]); + break; + case 1: + nodeB.addBranch(branchBuf[idx]); + break; + } + } + } - /** - * Load branch buffer with branches from full node plus the extra - * branch. - */ - @SuppressWarnings("unchecked") - void getBranches(Node node, Branch branch) { - assert (node != null); - assert (branch != null); - assert (node.count == node.branch.length); + /** + * Load branch buffer with branches from full node plus the extra + * branch. + */ + @SuppressWarnings("unchecked") + void getBranches(Node node, Branch branch) { + assert (node != null); + assert (branch != null); + assert (node.count == node.branch.length); /* Load the branch buffer */ - for (int idx = 0; idx < node.count; idx++) - branchBuf[idx] = (Branch) node.branch[idx]; + for (int idx = 0; idx < node.count; idx++) + branchBuf[idx] = (Branch) node.branch[idx]; - branchBuf[node.count] = (Branch) branch; + branchBuf[node.count] = (Branch) branch; /* Calculate rect containing all in the set */ - coverSplit.set(branchBuf[0]); - for (int idx = 1, n = branchBuf.length; idx < n; idx++) { - coverSplit.add(branchBuf[idx]); - } - coverSplitArea = coverSplit.calcRectVolume(); + coverSplit.set(branchBuf[0]); + for (int idx = 1, n = branchBuf.length; idx < n; idx++) { + coverSplit.add(branchBuf[idx]); + } + coverSplitArea = coverSplit.calcRectVolume(); /* init node - FIXME needed? */ - node.count = 0; - node.level = -1; - } + node.count = 0; + node.level = -1; + } - private void classify(int idx, int group) { - if (taken[idx]) - throw new IllegalStateException("Index already used!" - + idx + " " + Arrays.toString(taken)); + private void classify(int idx, int group) { + if (taken[idx]) + throw new IllegalStateException("Index already used!" + + idx + " " + Arrays.toString(taken)); - partition[idx] = group; - taken[idx] = true; + partition[idx] = group; + taken[idx] = true; - if (count[group] == 0) { - cover[group].set(branchBuf[idx]); - } else { - cover[group].add(branchBuf[idx]); - } + if (count[group] == 0) { + cover[group].set(branchBuf[idx]); + } else { + cover[group].add(branchBuf[idx]); + } - area[group] = cover[group].calcRectVolume(); - count[group]++; - } + area[group] = cover[group].calcRectVolume(); + count[group]++; + } - private void pickSeeds() { - int seed0 = 0, seed1 = 1; + private void pickSeeds() { + int seed0 = 0, seed1 = 1; - double tmpArea[] = mTmpArea;; + double tmpArea[] = mTmpArea; + ; - for (int idx = 0; idx < total; idx++) { - tmpArea[idx] = branchBuf[idx].calcRectVolume(); - } + for (int idx = 0; idx < total; idx++) { + tmpArea[idx] = branchBuf[idx].calcRectVolume(); + } - double worst = -coverSplitArea - 1; + double worst = -coverSplitArea - 1; - for (int idxA = 0; idxA < total - 1; idxA++) { - for (int idxB = idxA + 1; idxB < total; idxB++) { + for (int idxA = 0; idxA < total - 1; idxA++) { + for (int idxB = idxA + 1; idxB < total; idxB++) { - double waste = RTree.mergedArea(branchBuf[idxA], branchBuf[idxB]) - - (tmpArea[idxA] + tmpArea[idxB]); + double waste = RTree.mergedArea(branchBuf[idxA], branchBuf[idxB]) + - (tmpArea[idxA] + tmpArea[idxB]); - if (waste > worst) { - worst = waste; - seed0 = idxA; - seed1 = idxB; - } - } - } - classify(seed0, 0); - classify(seed1, 1); - } + if (waste > worst) { + worst = waste; + seed0 = idxA; + seed1 = idxB; + } + } + } + classify(seed0, 0); + classify(seed1, 1); + } - /** - * Method #0 for choosing a partition: - * As the seeds for the two groups, pick the two rects that would waste - * the most area if covered by a single rectangle, i.e. evidently the worst - * pair to have in the same group. - * Of the remaining, one at a time is chosen to be put in one of the two - * groups. - * The one chosen is the one with the greatest difference in area - * expansion - * depending on which group - the rect most strongly attracted to one - * group and repelled from the other. - * If one group gets too full (more would force other group to violate - * min fill requirement) then other group gets the rest. - * These last are the ones that can go in either group most easily. - */ - void choosePartition() { - double biggestDiff; - int group, chosen = 0, betterGroup = 0; + /** + * Method #0 for choosing a partition: + * As the seeds for the two groups, pick the two rects that would waste + * the most area if covered by a single rectangle, i.e. evidently the worst + * pair to have in the same group. + * Of the remaining, one at a time is chosen to be put in one of the two + * groups. + * The one chosen is the one with the greatest difference in area + * expansion + * depending on which group - the rect most strongly attracted to one + * group and repelled from the other. + * If one group gets too full (more would force other group to violate + * min fill requirement) then other group gets the rest. + * These last are the ones that can go in either group most easily. + */ + void choosePartition() { + double biggestDiff; + int group, chosen = 0, betterGroup = 0; - pickSeeds(); + pickSeeds(); - while (((count[0] + count[1]) < total) - && (count[0] < (total - minFill)) - && (count[1] < (total - minFill))) { + while (((count[0] + count[1]) < total) + && (count[0] < (total - minFill)) + && (count[1] < (total - minFill))) { - biggestDiff = (double) -1; - for (int idx = 0; idx < total; idx++) { - if (taken[idx]) - continue; + biggestDiff = (double) -1; + for (int idx = 0; idx < total; idx++) { + if (taken[idx]) + continue; - double growth0 = RTree.mergedArea(branchBuf[idx], cover[0]) - area[0]; - double growth1 = RTree.mergedArea(branchBuf[idx], cover[1]) - area[1]; + double growth0 = RTree.mergedArea(branchBuf[idx], cover[0]) - area[0]; + double growth1 = RTree.mergedArea(branchBuf[idx], cover[1]) - area[1]; - double diff = growth1 - growth0; - if (diff >= 0) { - group = 0; - } else { - group = 1; - diff = -diff; - } + double diff = growth1 - growth0; + if (diff >= 0) { + group = 0; + } else { + group = 1; + diff = -diff; + } - if (diff > biggestDiff) { - biggestDiff = diff; - chosen = idx; - betterGroup = group; - } else if ((diff == biggestDiff) - && (count[group] < count[betterGroup])) { - chosen = idx; - betterGroup = group; - } - } - classify(chosen, betterGroup); - } + if (diff > biggestDiff) { + biggestDiff = diff; + chosen = idx; + betterGroup = group; + } else if ((diff == biggestDiff) + && (count[group] < count[betterGroup])) { + chosen = idx; + betterGroup = group; + } + } + classify(chosen, betterGroup); + } /* If one group too full, put remaining rects in the other */ - if ((count[0] + count[1]) < total) { - if (count[0] >= total - minFill) { - group = 1; - } else { - group = 0; - } - for (int index = 0; index < total; index++) { - if (!taken[index]) { - classify(index, group); - } - } - } + if ((count[0] + count[1]) < total) { + if (count[0] >= total - minFill) { + group = 1; + } else { + group = 0; + } + for (int index = 0; index < total; index++) { + if (!taken[index]) { + classify(index, group); + } + } + } - assert ((count[0] + count[1]) == total); - assert ((count[0] >= minFill) && (count[1] >= minFill)); - } + assert ((count[0] + count[1]) == total); + assert ((count[0] >= minFill) && (count[1] >= minFill)); + } } diff --git a/vtm/src/org/oscim/utils/ScanBox.java b/vtm/src/org/oscim/utils/ScanBox.java index a229a7e9..3b998039 100644 --- a/vtm/src/org/oscim/utils/ScanBox.java +++ b/vtm/src/org/oscim/utils/ScanBox.java @@ -22,202 +22,202 @@ import org.oscim.core.Tile; /** * Scan-line fill algorithm to retrieve tile-coordinates from * Viewport. - *

+ *

* ScanBox is used to calculate tile coordinates that intersect the box (or * trapezoid) which is the projection of screen bounds to the map. Usage: - * + *

*

  * Viewport.getMapViewProjection(box)
  * 	ScanBox sb = new ScanBox(){
  *          protected void setVisible(int y, int x1, int x2) {
  *          }
- * 	};
+ *    };
  * sb.scan(pos.x, pos.y, pos.scale, * zoomLevel, coords);
  * 
- * + *

* where zoomLevel is the zoom-level for which tile coordinates should be * calculated. */ public abstract class ScanBox { - private final float[] mBox = new float[8]; + private final float[] mBox = new float[8]; - private float[] transScale(double x, double y, double scale, int zoom, float[] box) { - scale *= Tile.SIZE; + private float[] transScale(double x, double y, double scale, int zoom, float[] box) { + scale *= Tile.SIZE; - //double curScale = Tile.SIZE * scale; - double div = scale / (1 << zoom); + //double curScale = Tile.SIZE * scale; + double div = scale / (1 << zoom); - x *= scale; - y *= scale; + x *= scale; + y *= scale; - for (int i = 0; i < 8; i += 2) { - mBox[i + 0] = (float) ((x + box[i + 0]) / div); - mBox[i + 1] = (float) ((y + box[i + 1]) / div); - } - return mBox; - } + for (int i = 0; i < 8; i += 2) { + mBox[i + 0] = (float) ((x + box[i + 0]) / div); + mBox[i + 1] = (float) ((y + box[i + 1]) / div); + } + return mBox; + } /* ported from Polymaps: Layer.js */ - static class Edge { - float x0, y0, x1, y1, dx, dy; + static class Edge { + float x0, y0, x1, y1, dx, dy; - void set(float x0, float y0, float x1, float y1) { - if (y0 <= y1) { - this.x0 = x0; - this.y0 = y0; - this.x1 = x1; - this.y1 = y1; - } else { - this.x0 = x1; - this.y0 = y1; - this.x1 = x0; - this.y1 = y0; - } - this.dx = this.x1 - this.x0; - this.dy = this.y1 - this.y0; - } - } + void set(float x0, float y0, float x1, float y1) { + if (y0 <= y1) { + this.x0 = x0; + this.y0 = y0; + this.x1 = x1; + this.y1 = y1; + } else { + this.x0 = x1; + this.y0 = y1; + this.x1 = x0; + this.y1 = y0; + } + this.dx = this.x1 - this.x0; + this.dy = this.y1 - this.y0; + } + } - private Edge ab = new Edge(); - private Edge bc = new Edge(); - private Edge ca = new Edge(); + private Edge ab = new Edge(); + private Edge bc = new Edge(); + private Edge ca = new Edge(); - private int xmin, xmax; + private int xmin, xmax; - protected int mZoom; + protected int mZoom; - protected abstract void setVisible(int y, int x1, int x2); + protected abstract void setVisible(int y, int x1, int x2); - public void scan(double x, double y, double scale, int zoom, float[] box) { - mZoom = zoom; - // this does not modify 'box' parameter - box = transScale(x, y, scale, zoom, box); + public void scan(double x, double y, double scale, int zoom, float[] box) { + mZoom = zoom; + // this does not modify 'box' parameter + box = transScale(x, y, scale, zoom, box); - // clip result to min/max as steep angles - // cause overshooting in x direction. - float max = Float.MIN_VALUE; - float min = Float.MAX_VALUE; + // clip result to min/max as steep angles + // cause overshooting in x direction. + float max = Float.MIN_VALUE; + float min = Float.MAX_VALUE; - for (int i = 0; i < 8; i += 2) { - float xx = box[i]; - if (xx > max) - max = xx; - if (xx < min) - min = xx; - } + for (int i = 0; i < 8; i += 2) { + float xx = box[i]; + if (xx > max) + max = xx; + if (xx < min) + min = xx; + } - max = (float) Math.ceil(max); - min = (float) Math.floor(min); - if (min == max) - max++; + max = (float) Math.ceil(max); + min = (float) Math.floor(min); + if (min == max) + max++; - xmin = (int) min; - xmax = (int) max; + xmin = (int) min; + xmax = (int) max; - // top-left -> top-right - ab.set(box[0], box[1], box[2], box[3]); - // top-right -> bottom-right - bc.set(box[2], box[3], box[4], box[5]); - // bottom-right -> bottom-left - ca.set(box[4], box[5], box[0], box[1]); + // top-left -> top-right + ab.set(box[0], box[1], box[2], box[3]); + // top-right -> bottom-right + bc.set(box[2], box[3], box[4], box[5]); + // bottom-right -> bottom-left + ca.set(box[4], box[5], box[0], box[1]); - scanTriangle(); + scanTriangle(); - // top-left -> bottom-right - ab.set(box[0], box[1], box[4], box[5]); - // bottom-right -> bottom-left - bc.set(box[4], box[5], box[6], box[7]); - // bottom-left -> top-left - ca.set(box[6], box[7], box[0], box[1]); + // top-left -> bottom-right + ab.set(box[0], box[1], box[4], box[5]); + // bottom-right -> bottom-left + bc.set(box[4], box[5], box[6], box[7]); + // bottom-left -> top-left + ca.set(box[6], box[7], box[0], box[1]); - scanTriangle(); - } + scanTriangle(); + } - private void scanTriangle() { + private void scanTriangle() { - // sort so that ca.dy > bc.dy > ab.dy - if (ab.dy > bc.dy) { - Edge t = ab; - ab = bc; - bc = t; - } - if (ab.dy > ca.dy) { - Edge t = ab; - ab = ca; - ca = t; - } - if (bc.dy > ca.dy) { - Edge t = bc; - bc = ca; - ca = t; - } + // sort so that ca.dy > bc.dy > ab.dy + if (ab.dy > bc.dy) { + Edge t = ab; + ab = bc; + bc = t; + } + if (ab.dy > ca.dy) { + Edge t = ab; + ab = ca; + ca = t; + } + if (bc.dy > ca.dy) { + Edge t = bc; + bc = ca; + ca = t; + } - // shouldnt be possible, anyway - if (ca.dy == 0) - return; + // shouldnt be possible, anyway + if (ca.dy == 0) + return; - if (ab.dy > 0.0) - scanSpans(ca, ab); + if (ab.dy > 0.0) + scanSpans(ca, ab); - if (bc.dy > 0.0) - scanSpans(ca, bc); - } + if (bc.dy > 0.0) + scanSpans(ca, bc); + } - private void scanSpans(Edge e0, Edge e1) { + private void scanSpans(Edge e0, Edge e1) { - // scan the y-range of the edge with less dy - int y0 = (int) Math.max(0, Math.floor(e1.y0)); - int y1 = (int) Math.min((1 << mZoom), Math.ceil(e1.y1)); + // scan the y-range of the edge with less dy + int y0 = (int) Math.max(0, Math.floor(e1.y0)); + int y1 = (int) Math.min((1 << mZoom), Math.ceil(e1.y1)); - // sort edge by x-coordinate - if (e0.x0 == e1.x0 && e0.y0 == e1.y0) { - // bottom-flat - if (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) { - Edge t = e0; - e0 = e1; - e1 = t; - } - } else { - // top-flat - if (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0) { - Edge t = e0; - e0 = e1; - e1 = t; - } - } + // sort edge by x-coordinate + if (e0.x0 == e1.x0 && e0.y0 == e1.y0) { + // bottom-flat + if (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) { + Edge t = e0; + e0 = e1; + e1 = t; + } + } else { + // top-flat + if (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0) { + Edge t = e0; + e0 = e1; + e1 = t; + } + } - float m0 = e0.dx / e0.dy; - float m1 = e1.dx / e1.dy; + float m0 = e0.dx / e0.dy; + float m1 = e1.dx / e1.dy; - // e0 goes to the right, e1 to the left - int d0 = e0.dx > 0 ? 1 : 0; // use y + 1 to compute x0 - int d1 = e1.dx < 0 ? 1 : 0; // use y + 1 to compute x1 - float dy; + // e0 goes to the right, e1 to the left + int d0 = e0.dx > 0 ? 1 : 0; // use y + 1 to compute x0 + int d1 = e1.dx < 0 ? 1 : 0; // use y + 1 to compute x1 + float dy; - for (int y = y0; y < y1; y++) { + for (int y = y0; y < y1; y++) { - dy = d0 + y - e0.y0; - if (dy > e0.dy) - dy = e0.dy; + dy = d0 + y - e0.y0; + if (dy > e0.dy) + dy = e0.dy; - int x0 = (int) Math.ceil(e0.x0 + m0 * dy); + int x0 = (int) Math.ceil(e0.x0 + m0 * dy); - dy = d1 + y - e1.y0; - if (dy > e1.dy) - dy = e1.dy; + dy = d1 + y - e1.y0; + if (dy > e1.dy) + dy = e1.dy; - int x1 = (int) Math.floor(e1.x0 + m1 * dy); + int x1 = (int) Math.floor(e1.x0 + m1 * dy); - if (x1 < xmin) - x1 = xmin; + if (x1 < xmin) + x1 = xmin; - if (x0 > xmax) - x0 = xmax; + if (x0 > xmax) + x0 = xmax; - if (x1 < x0) - setVisible(y, x1, x0); - } - } + if (x1 < x0) + setVisible(y, x1, x0); + } + } } diff --git a/vtm/src/org/oscim/utils/SpatialIndex.java b/vtm/src/org/oscim/utils/SpatialIndex.java index fa195441..d3180a68 100644 --- a/vtm/src/org/oscim/utils/SpatialIndex.java +++ b/vtm/src/org/oscim/utils/SpatialIndex.java @@ -1,31 +1,30 @@ package org.oscim.utils; -import java.util.List; - import org.oscim.core.Box; +import java.util.List; + public interface SpatialIndex { - public interface SearchCb { - /** - * - * TODO should be able to return 'continue', 'stop', - * 'remove-current' - * - * @return false to stop search - */ + public interface SearchCb { + /** + * TODO should be able to return 'continue', 'stop', + * 'remove-current' + * + * @return false to stop search + */ - boolean call(T item, Object context); - } + boolean call(T item, Object context); + } - public void insert(Box box, T item); + public void insert(Box box, T item); - public boolean remove(Box box, T item); + public boolean remove(Box box, T item); - public List search(Box bbox, List results); + public List search(Box bbox, List results); - public boolean search(Box bbox, SearchCb cb, Object context); + public boolean search(Box bbox, SearchCb cb, Object context); - public int size(); + public int size(); - public void clear(); + public void clear(); } diff --git a/vtm/src/org/oscim/utils/TessJNI.java b/vtm/src/org/oscim/utils/TessJNI.java index 5d521775..9a081fe8 100644 --- a/vtm/src/org/oscim/utils/TessJNI.java +++ b/vtm/src/org/oscim/utils/TessJNI.java @@ -1,118 +1,118 @@ package org.oscim.utils; public class TessJNI { - private long inst; + private long inst; - public TessJNI() { - inst = newTess(0); - } + public TessJNI() { + inst = newTess(0); + } - public TessJNI(int bucketSize) { - inst = newTess(bucketSize); - } + public TessJNI(int bucketSize) { + inst = newTess(bucketSize); + } - @Override - protected void finalize() { - dispose(); - } + @Override + protected void finalize() { + dispose(); + } - public void dispose() { - if (inst != 0) { - freeTess(inst); - inst = 0; - } - } + public void dispose() { + if (inst != 0) { + freeTess(inst); + inst = 0; + } + } - protected long instance() { - return inst; - } + protected long instance() { + return inst; + } - /** - * See OpenGL Red Book for description of the winding rules - * http://www.glprogramming.com/red/chapter11.html - */ - public static final class WindingRule { - public static final int ODD = 0; - public static final int NONZERO = 1; - public static final int POSITIVE = 2; - public static final int NEGATIVE = 3; - public static final int ABS_GEQ_TWO = 4; - } + /** + * See OpenGL Red Book for description of the winding rules + * http://www.glprogramming.com/red/chapter11.html + */ + public static final class WindingRule { + public static final int ODD = 0; + public static final int NONZERO = 1; + public static final int POSITIVE = 2; + public static final int NEGATIVE = 3; + public static final int ABS_GEQ_TWO = 4; + } - public static final class ElementType { - public static final int POLYGONS = 0; - public static final int CONNECTED_POLYGONS = 1; - public static final int BOUNDARY_CONTOURS = 2; - } + public static final class ElementType { + public static final int POLYGONS = 0; + public static final int CONNECTED_POLYGONS = 1; + public static final int BOUNDARY_CONTOURS = 2; + } - public void addContour2D(float[] points) { - addContour2D(points, 0, points.length >> 1); - } + public void addContour2D(float[] points) { + addContour2D(points, 0, points.length >> 1); + } - public void addContour2D(float[] points, int offset, int length) { - if (length < 6) - return; - if ((length % 2 != 0) || (offset % 2 != 0) || (points.length >> 1) < (offset + length)) - throw new IllegalArgumentException("Invalid input: length:" + length - + ", offset:" + offset - + ", points.length:" + points.length); - addContour(inst, 2, points, 8, offset, length); - } + public void addContour2D(float[] points, int offset, int length) { + if (length < 6) + return; + if ((length % 2 != 0) || (offset % 2 != 0) || (points.length >> 1) < (offset + length)) + throw new IllegalArgumentException("Invalid input: length:" + length + + ", offset:" + offset + + ", points.length:" + points.length); + addContour(inst, 2, points, 8, offset, length); + } - public void addContour2D(int[] index, float[] contour) { - addMultiContour2D(inst, index, contour, 0, index.length); - } + public void addContour2D(int[] index, float[] contour) { + addMultiContour2D(inst, index, contour, 0, index.length); + } - public void addContour2D(int[] index, float[] contour, int idxStart, int idxEnd) { - addMultiContour2D(inst, index, contour, idxStart, idxEnd); - } + public void addContour2D(int[] index, float[] contour, int idxStart, int idxEnd) { + addMultiContour2D(inst, index, contour, idxStart, idxEnd); + } - public boolean tesselate() { - return tessContour2D(inst, - TessJNI.WindingRule.POSITIVE, - TessJNI.ElementType.POLYGONS, - 3, 2) == 1; - } + public boolean tesselate() { + return tessContour2D(inst, + TessJNI.WindingRule.POSITIVE, + TessJNI.ElementType.POLYGONS, + 3, 2) == 1; + } - public boolean tesselate(int windingRule, int elementType) { - return tessContour2D(inst, windingRule, elementType, 3, 2) == 1; - } + public boolean tesselate(int windingRule, int elementType) { + return tessContour2D(inst, windingRule, elementType, 3, 2) == 1; + } - public int getVertexCount() { - return getVertexCount(inst); - } + public int getVertexCount() { + return getVertexCount(inst); + } - public int getElementCount() { - return getElementCount(inst); - } + public int getElementCount() { + return getElementCount(inst); + } - public void getVertices(float[] out, int offset, int length) { - getVertices(inst, out, offset, length); - } + public void getVertices(float[] out, int offset, int length) { + getVertices(inst, out, offset, length); + } - public void getVertices(short[] out, int offset, int length, float scale) { - getVerticesS(inst, out, offset, length, scale); - } + public void getVertices(short[] out, int offset, int length, float scale) { + getVerticesS(inst, out, offset, length, scale); + } - public void getElements(int[] out, int offset, int length) { - getElements(inst, out, offset, length); - } + public void getElements(int[] out, int offset, int length) { + getElements(inst, out, offset, length); + } - public void getElements(short[] out, int offset, int length) { - getElementsS(inst, out, offset, length); - } + public void getElements(short[] out, int offset, int length) { + getElementsS(inst, out, offset, length); + } - public void getVertexIndices(int[] out, int offset, int length) { - getVertexIndices(inst, out, offset, length); - } + public void getVertexIndices(int[] out, int offset, int length) { + getVertexIndices(inst, out, offset, length); + } - public void getElementsWithInputVertexIds(short[] dst, int dstOffset, int offset, int length) { - getElementsWithInputVertexIds(inst, dst, dstOffset, offset, length); - } + public void getElementsWithInputVertexIds(short[] dst, int dstOffset, int offset, int length) { + getElementsWithInputVertexIds(inst, dst, dstOffset, offset, length); + } - // @formatter:off - /*JNI - #include + // @formatter:off + /*JNI + #include #include #include void* heapAlloc( void* userData, unsigned int size ){ @@ -128,7 +128,7 @@ public class TessJNI { free( ptr ); } */ - static native long newTess(int size); /* { + static native long newTess(int size); /* { if (size <= 0) return (long)tessNewTess(0); if (size > 10) @@ -148,23 +148,26 @@ public class TessJNI { //ma.extraVertices = 256; return (long)tessNewTess(&ma); } */ - static native void freeTess(long inst); /* { + + static native void freeTess(long inst); /* { tessDeleteTess((TESStesselator*) inst); } */ - /** - * Adds a contour to be tesselated. - * The type of the vertex coordinates is assumed to be TESSreal. - * - * @param tess - pointer to tesselator object. - * @param size - number of coordinates per vertex. Must be 2 or 3. - * @param pointer - pointer to the first coordinate of the first vertex in the array. - * @param stride - defines offset in bytes between consecutive vertices. - * @param count - number of vertices in contour. - */ - static native void addContour(long inst, int size, float[] contour, int stride, int offset, int count);/* { + + /** + * Adds a contour to be tesselated. + * The type of the vertex coordinates is assumed to be TESSreal. + * + * @param tess - pointer to tesselator object. + * @param size - number of coordinates per vertex. Must be 2 or 3. + * @param pointer - pointer to the first coordinate of the first vertex in the array. + * @param stride - defines offset in bytes between consecutive vertices. + * @param count - number of vertices in contour. + */ + static native void addContour(long inst, int size, float[] contour, int stride, int offset, int count);/* { tessAddContour((TESStesselator*) inst, size, contour + (offset * stride), stride, count); } */ - static native void addMultiContour2D(long inst, int[] index, float[] contour, int idxStart, int idxCount);/* { + + static native void addMultiContour2D(long inst, int[] index, float[] contour, int idxStart, int idxCount);/* { TESStesselator* tess = (TESStesselator*) inst; int offset = 0; // start at 0 to get the correct offset in contour.. @@ -180,83 +183,92 @@ public class TessJNI { offset += len; } } */ - /** - * Tesselate contours. - * - * @param tess - pointer to tesselator object. - * @param windingRule - winding rules used for tesselation, must be one of TessWindingRule. - * @param elementType - defines the tesselation result element type, must be one of TessElementType. - * @param polySize - defines maximum vertices per polygons if output is polygons. - * @param vertexSize - defines the number of coordinates in tesselation result vertex, must be 2 or 3. - * @param normal - defines the normal of the input contours, of null the normal is calculated automatically. - * @return 1 if succeed, 0 if failed. - */ - static native int tessContour2D(long inst, int windingRule, int elementType, int polySize, int vertexSize);/*{ + + /** + * Tesselate contours. + * + * @param tess - pointer to tesselator object. + * @param windingRule - winding rules used for tesselation, must be one of TessWindingRule. + * @param elementType - defines the tesselation result element type, must be one of TessElementType. + * @param polySize - defines maximum vertices per polygons if output is polygons. + * @param vertexSize - defines the number of coordinates in tesselation result vertex, must be 2 or 3. + * @param normal - defines the normal of the input contours, of null the normal is calculated automatically. + * @return 1 if succeed, 0 if failed. + */ + static native int tessContour2D(long inst, int windingRule, int elementType, int polySize, int vertexSize);/*{ return tessTesselate((TESStesselator*) inst, windingRule, elementType, polySize, vertexSize, 0); } */ - static native int getVertexCount(long inst); /*{ + + static native int getVertexCount(long inst); /*{ return tessGetVertexCount((TESStesselator*) inst); }*/ - /** - * Returns pointer to first coordinate of first vertex. - */ - static native boolean getVertices(long inst, float[] out, int offset, int length);/*{ + + /** + * Returns pointer to first coordinate of first vertex. + */ + static native boolean getVertices(long inst, float[] out, int offset, int length);/*{ const TESSreal* vertices = tessGetVertices((TESStesselator*) inst); if (!vertices) return 0; memcpy(out, vertices + offset, length * sizeof(TESSreal)); return 1; }*/ - /** - * Returns pointer to first coordinate of first vertex. - */ - static native void getVerticesS(long inst, short[] out, int offset, int length, float scale);/*{ + + /** + * Returns pointer to first coordinate of first vertex. + */ + static native void getVerticesS(long inst, short[] out, int offset, int length, float scale);/*{ const TESSreal* vertices = tessGetVertices((TESStesselator*) inst); for(int i = 0; i < length; i++) out[i] = (short)(vertices[offset++] * scale + 0.5f); }*/ - /** - * Returns pointer to first vertex index. - * - * Vertex indices can be used to map the generated vertices to the original vertices. - * Every point added using tessAddContour() will get a new index starting at 0. - * New vertices generated at the intersections of segments are assigned value TESS_UNDEF. - */ - static native boolean getVertexIndices(long inst, int[] out, int offset, int length);/* { + + /** + * Returns pointer to first vertex index. + *

+ * Vertex indices can be used to map the generated vertices to the original vertices. + * Every point added using tessAddContour() will get a new index starting at 0. + * New vertices generated at the intersections of segments are assigned value TESS_UNDEF. + */ + static native boolean getVertexIndices(long inst, int[] out, int offset, int length);/* { const TESSindex* indices = tessGetVertexIndices((TESStesselator*) inst); if (!indices) return 0; memcpy(out, indices + offset, length * sizeof(TESSindex)); return 1; } */ - /** - * Returns number of elements in the the tesselated output. - */ - static native int getElementCount(long inst);/*{ + + /** + * Returns number of elements in the the tesselated output. + */ + static native int getElementCount(long inst);/*{ return tessGetElementCount((TESStesselator*) inst); }*/ - /** - * Returns pointer to the first element. - */ - static native boolean getElements(long inst, int[] out, int offset, int length);/*{ + + /** + * Returns pointer to the first element. + */ + static native boolean getElements(long inst, int[] out, int offset, int length);/*{ const TESSindex* elements = tessGetElements((TESStesselator*) inst); if (!elements) return 0; memcpy(out, elements + offset, length * sizeof(TESSindex)); return 1; }*/ - /** - * Returns pointer to the first element. - */ - static native void getElementsS(long inst, short[] out, int offset, int length);/*{ + + /** + * Returns pointer to the first element. + */ + static native void getElementsS(long inst, short[] out, int offset, int length);/*{ const TESSindex* elements = tessGetElements((TESStesselator*) inst); for(int i = 0; i < length; i++) out[i] = (short)elements[offset++]; }*/ - /** - * Returns list of triangles indices (or to the first element of convex polygons). - */ - static native void getElementsWithInputVertexIds(long inst, short[] out, int dstOffset, int offset, int length);/*{ + + /** + * Returns list of triangles indices (or to the first element of convex polygons). + */ + static native void getElementsWithInputVertexIds(long inst, short[] out, int dstOffset, int offset, int length);/*{ const TESSindex* elements = tessGetElements((TESStesselator*) inst); const TESSindex* indices = tessGetVertexIndices((TESStesselator*) inst); for(int i = 0; i < length; i++) diff --git a/vtm/src/org/oscim/utils/Tessellator.java b/vtm/src/org/oscim/utils/Tessellator.java index af0a9d3c..2f516808 100644 --- a/vtm/src/org/oscim/utils/Tessellator.java +++ b/vtm/src/org/oscim/utils/Tessellator.java @@ -16,354 +16,354 @@ */ package org.oscim.utils; -import java.util.Arrays; - import org.oscim.renderer.bucket.VertexData; import org.oscim.utils.math.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Arrays; + public class Tessellator { - static final Logger log = LoggerFactory.getLogger(Tessellator.class); + static final Logger log = LoggerFactory.getLogger(Tessellator.class); - /** - * Special version for ExtrusionLayer to match indices with vertex - * positions. - */ - public static int tessellate(float[] points, int ppos, int numPoints, int[] index, - int ipos, int numRings, int vertexOffset, VertexData outTris) { + /** + * Special version for ExtrusionLayer to match indices with vertex + * positions. + */ + public static int tessellate(float[] points, int ppos, int numPoints, int[] index, + int ipos, int numRings, int vertexOffset, VertexData outTris) { - int buckets = FastMath.log2(MathUtils.nextPowerOfTwo(numPoints)); - buckets -= 2; - //log.debug("tess use {}", buckets); + int buckets = FastMath.log2(MathUtils.nextPowerOfTwo(numPoints)); + buckets -= 2; + //log.debug("tess use {}", buckets); - TessJNI tess = new TessJNI(buckets); + TessJNI tess = new TessJNI(buckets); - tess.addContour2D(index, points, ipos, numRings); - //log.debug("tess ipos:{} rings:{}", ipos, numRings); + tess.addContour2D(index, points, ipos, numRings); + //log.debug("tess ipos:{} rings:{}", ipos, numRings); - if (!tess.tesselate()) - return 0; + if (!tess.tesselate()) + return 0; - int nverts = tess.getVertexCount() * 2; - int nelems = tess.getElementCount() * 3; + int nverts = tess.getVertexCount() * 2; + int nelems = tess.getElementCount() * 3; - //log.debug("tess elems:{} verts:{} points:{}", nelems, nverts, numPoints); + //log.debug("tess elems:{} verts:{} points:{}", nelems, nverts, numPoints); - if (numPoints != nverts) { - log.debug("tess ----- skip poly: " + nverts + " " + numPoints); - tess.dispose(); - return 0; - } + if (numPoints != nverts) { + log.debug("tess ----- skip poly: " + nverts + " " + numPoints); + tess.dispose(); + return 0; + } - int sumIndices = 0; + int sumIndices = 0; - VertexData.Chunk vd = outTris.obtainChunk(); + VertexData.Chunk vd = outTris.obtainChunk(); - for (int offset = 0; offset < nelems;) { - int size = nelems - offset; + for (int offset = 0; offset < nelems; ) { + int size = nelems - offset; - if (VertexData.SIZE == vd.used) { - vd = outTris.obtainChunk(); - } + if (VertexData.SIZE == vd.used) { + vd = outTris.obtainChunk(); + } - if (size > VertexData.SIZE - vd.used) - size = VertexData.SIZE - vd.used; + if (size > VertexData.SIZE - vd.used) + size = VertexData.SIZE - vd.used; - tess.getElementsWithInputVertexIds(vd.vertices, vd.used, offset, size); + tess.getElementsWithInputVertexIds(vd.vertices, vd.used, offset, size); - int start = vd.used; - int end = start + size; - short[] indices = vd.vertices; + int start = vd.used; + int end = start + size; + short[] indices = vd.vertices; - for (int i = start; i < end; i++) { - if (indices[i] < 0) { - log.debug(">>>> eeek {} {} {}", - start, end, - Arrays.toString(Arrays.copyOfRange(indices, start, end))); - break; - } - indices[i] *= 2; - } - /* when a ring has an odd number of points one (or rather two) - * additional vertices will be added. so the following rings + for (int i = start; i < end; i++) { + if (indices[i] < 0) { + log.debug(">>>> eeek {} {} {}", + start, end, + Arrays.toString(Arrays.copyOfRange(indices, start, end))); + break; + } + indices[i] *= 2; + } + /* when a ring has an odd number of points one (or rather two) + * additional vertices will be added. so the following rings * needs extra offset */ - int shift = 0; - for (int i = 0, m = numRings - 1; i < m; i++) { - shift += (index[ipos + i]); + int shift = 0; + for (int i = 0, m = numRings - 1; i < m; i++) { + shift += (index[ipos + i]); /* even number of points? */ - if (((index[ipos + i] >> 1) & 1) == 0) - continue; + if (((index[ipos + i] >> 1) & 1) == 0) + continue; - for (int j = start; j < end; j++) - if (indices[j] >= shift) - indices[j] += 2; + for (int j = start; j < end; j++) + if (indices[j] >= shift) + indices[j] += 2; - shift += 2; - } + shift += 2; + } /* shift by vertexOffset */ - for (int i = start; i < end; i++) - indices[i] += vertexOffset; + for (int i = start; i < end; i++) + indices[i] += vertexOffset; - sumIndices += size; + sumIndices += size; - vd.used += size; - outTris.releaseChunk(); + vd.used += size; + outTris.releaseChunk(); - offset += size; - } + offset += size; + } - tess.dispose(); + tess.dispose(); - return sumIndices; - } - // private static final int RESULT_VERTICES = 0; - // private static final int RESULT_TRIANGLES = 1; - // - // /** - // * Special version for ExtrusionLayer to match indices with vertex - // * positions. - // */ - // public static int tessellate(float[] points, int ppos, int plen, int[] index, - // int ipos, int rings, int vertexOffset, VertexData outTris) { - // - // int[] result = new int[2]; - // - // int numPoints = 0; - // for (int i = 0; i < rings; i++) - // numPoints += index[ipos + i]; - // - // long ctx = Tessellator.tessellate(points, ppos, index, ipos, rings, result); - // if ((numPoints / 2) < result[RESULT_VERTICES]) { - // log.debug("skip poly: " + Arrays.toString(result) + " " + numPoints); - // Tessellator.tessFinish(ctx); - // return 0; - // } - // - // int cnt; - // int sumIndices = 0; - // - // VertexData.Chunk vd = outTris.obtainChunk(); - // - // while ((cnt = Tessellator.tessGetIndicesWO(ctx, vd.vertices, vd.used)) > 0) { - // int start = vd.used; - // int end = start + cnt; - // short[] v = vd.vertices; - // - // for (int i = start; i < end; i++) - // v[i] *= 2; - // - // /* when a ring has an odd number of points one (or rather two) - // * additional vertices will be added. so the following rings - // * needs extra offset */ - // int shift = 0; - // for (int i = 0, m = rings - 1; i < m; i++) { - // shift += (index[ipos + i]); - // - // /* even number of points? */ - // if (((index[ipos + i] >> 1) & 1) == 0) - // continue; - // - // for (int j = start; j < end; j++) - // if (v[j] >= shift) - // v[j] += 2; - // - // shift += 2; - // } - // - // /* shift by vertexOffset */ - // for (int i = start; i < end; i++) - // v[i] += vertexOffset; - // - // sumIndices += cnt; - // - // vd.used += cnt; - // outTris.releaseChunk(); - // - // if (vd.used == VertexData.SIZE) { - // /* gets next item since this one is full */ - // vd = outTris.obtainChunk(); - // continue; - // } - // /* no more indices to get. */ - // break; - // } - // - // Tessellator.tessFinish(ctx); - // - // return sumIndices; - // } - // - // /** - // * Untested! - // */ - // public static int tessellate(GeometryBuffer geom, GeometryBuffer out) { - // - // int[] result = new int[2]; - // - // int numRings = 0; - // int numPoints = 0; - // - // for (int i = 0; i < geom.indexPos; i++) { - // if (geom.index[i] > 0) { - // numRings++; - // numPoints += geom.index[i]; - // } else - // break; - // } - // - // long ctx = Tessellator.tessellate(geom.points, 0, - // geom.index, 0, - // numRings, result); - // - // boolean verticesAdded = false; - // if (numPoints < result[RESULT_VERTICES] * 2) { - // //log.debug("grow vertices" + geom.pointPos); - // verticesAdded = true; - // } - // - // if (out == null) { - // /* overwrite geom contents */ - // out = geom; - // if (verticesAdded) { - // out.ensurePointSize(result[RESULT_VERTICES], false); - // Tessellator.tessGetVerticesFloat(ctx, out.points); - // } - // } else { - // out.ensurePointSize(result[RESULT_VERTICES], false); - // - // if (verticesAdded) { - // Tessellator.tessGetVerticesFloat(ctx, out.points); - // } else { - // System.arraycopy(geom.points, 0, out.points, 0, numPoints); - // } - // } - // - // out.ensureIndexSize(result[RESULT_TRIANGLES * 3], false); - // Tessellator.tessGetIndices(ctx, out.index); - // - // Tessellator.tessFinish(ctx); - // - // return 1; - // } - // - // /* FIXME This modifies geom ?! */ - // public static int tessellate(GeometryBuffer geom, float scale, - // VertexData outPoints, VertexData outTris, int vertexOffset) { - // - // int numIndices = 0; - // int indexPos = 0; - // int pointPos = 0; - // int indexEnd = geom.index.length; - // - // int[] result = new int[2]; - // - // float s = scale; - // scale = 1; - // - // for (int idx = 0; idx < indexEnd && geom.index[idx] > 0; idx++) { - // indexPos = idx; - // - // int numRings = 1; - // int numPoints = geom.index[idx++]; - // - // for (; idx < indexEnd && geom.index[idx] > 0; idx++) { - // numRings++; - // numPoints += geom.index[idx]; - // } - // - // /* FIXME !!! */ - // for (int i = pointPos; i < pointPos + numPoints; i += 2) { - // geom.points[i + 0] = (int) (geom.points[i + 0] * s); - // geom.points[i + 1] = (int) (geom.points[i + 1] * s); - // } - // - // long ctx = Tessellator.tessellate(geom.points, pointPos, - // geom.index, indexPos, - // numRings, result); - // - // if (result[RESULT_VERTICES] == 0 || result[RESULT_TRIANGLES] == 0) { - // log.debug("ppos " + pointPos + " ipos:" + indexPos + - // " rings:" + numRings + " " + Arrays.toString(geom.index)); - // continue; - // } - // - // pointPos += numPoints; - // - // while (true) { - // VertexData.Chunk vd = outTris.obtainChunk(); - // - // int cnt = Tessellator.tessGetIndicesWO(ctx, vd.vertices, vd.used); - // if (cnt <= 0) - // break; - // - // /* shift by vertexOffset */ - // for (int pos = vd.used, end = pos + cnt; pos < end; pos++) - // vd.vertices[pos] += vertexOffset; - // - // numIndices += cnt; - // - // vd.used += cnt; - // outTris.releaseChunk(); - // - // if (vd.used < VertexData.SIZE) - // break; - // } - // - // while (true) { - // VertexData.Chunk vd = outPoints.obtainChunk(); - // - // int cnt = Tessellator.tessGetVerticesWO(ctx, vd.vertices, vd.used, scale); - // if (cnt <= 0) - // break; - // - // vertexOffset += cnt >> 1; - // - // vd.used += cnt; - // outPoints.releaseChunk(); - // - // if (vd.used < VertexData.SIZE) - // break; - // } - // - // Tessellator.tessFinish(ctx); - // - // if (idx >= indexEnd || geom.index[idx] < 0) - // break; - // } - // - // if (vertexOffset > Short.MAX_VALUE) { - // log.debug("too much !!!" + Arrays.toString(geom.index)); - // return 0; - // } - // - // return numIndices; - // } - // - // /** - // * @param points an array of x,y coordinates - // * @param pos position in points array - // * @param index geom indices - // * @param ipos position in index array - // * @param numRings number of rings in polygon == outer(1) + inner rings - // * @param result contains number of vertices and number of triangles - // * @return context - must be freed with tessFinish() - // */ - // protected static native long tessellate(float[] points, int pos, - // int[] index, int ipos, int numRings, int[] result); - // - // protected static native void tessFinish(long ctx); - // - // protected static native int tessGetVertices(long ctx, short[] coordinates, float scale); - // - // protected static native int tessGetVerticesWO(long ctx, short[] coordinates, - // int offset, float scale); - // - // protected static native int tessGetVerticesFloat(long ctx, float[] coordinates); - // - // protected static native int tessGetIndices(long ctx, int[] indices); - // - // protected static native int tessGetIndicesWO(long ctx, short[] indices, int offset); + return sumIndices; + } + // private static final int RESULT_VERTICES = 0; + // private static final int RESULT_TRIANGLES = 1; + // + // /** + // * Special version for ExtrusionLayer to match indices with vertex + // * positions. + // */ + // public static int tessellate(float[] points, int ppos, int plen, int[] index, + // int ipos, int rings, int vertexOffset, VertexData outTris) { + // + // int[] result = new int[2]; + // + // int numPoints = 0; + // for (int i = 0; i < rings; i++) + // numPoints += index[ipos + i]; + // + // long ctx = Tessellator.tessellate(points, ppos, index, ipos, rings, result); + // if ((numPoints / 2) < result[RESULT_VERTICES]) { + // log.debug("skip poly: " + Arrays.toString(result) + " " + numPoints); + // Tessellator.tessFinish(ctx); + // return 0; + // } + // + // int cnt; + // int sumIndices = 0; + // + // VertexData.Chunk vd = outTris.obtainChunk(); + // + // while ((cnt = Tessellator.tessGetIndicesWO(ctx, vd.vertices, vd.used)) > 0) { + // int start = vd.used; + // int end = start + cnt; + // short[] v = vd.vertices; + // + // for (int i = start; i < end; i++) + // v[i] *= 2; + // + // /* when a ring has an odd number of points one (or rather two) + // * additional vertices will be added. so the following rings + // * needs extra offset */ + // int shift = 0; + // for (int i = 0, m = rings - 1; i < m; i++) { + // shift += (index[ipos + i]); + // + // /* even number of points? */ + // if (((index[ipos + i] >> 1) & 1) == 0) + // continue; + // + // for (int j = start; j < end; j++) + // if (v[j] >= shift) + // v[j] += 2; + // + // shift += 2; + // } + // + // /* shift by vertexOffset */ + // for (int i = start; i < end; i++) + // v[i] += vertexOffset; + // + // sumIndices += cnt; + // + // vd.used += cnt; + // outTris.releaseChunk(); + // + // if (vd.used == VertexData.SIZE) { + // /* gets next item since this one is full */ + // vd = outTris.obtainChunk(); + // continue; + // } + // /* no more indices to get. */ + // break; + // } + // + // Tessellator.tessFinish(ctx); + // + // return sumIndices; + // } + // + // /** + // * Untested! + // */ + // public static int tessellate(GeometryBuffer geom, GeometryBuffer out) { + // + // int[] result = new int[2]; + // + // int numRings = 0; + // int numPoints = 0; + // + // for (int i = 0; i < geom.indexPos; i++) { + // if (geom.index[i] > 0) { + // numRings++; + // numPoints += geom.index[i]; + // } else + // break; + // } + // + // long ctx = Tessellator.tessellate(geom.points, 0, + // geom.index, 0, + // numRings, result); + // + // boolean verticesAdded = false; + // if (numPoints < result[RESULT_VERTICES] * 2) { + // //log.debug("grow vertices" + geom.pointPos); + // verticesAdded = true; + // } + // + // if (out == null) { + // /* overwrite geom contents */ + // out = geom; + // if (verticesAdded) { + // out.ensurePointSize(result[RESULT_VERTICES], false); + // Tessellator.tessGetVerticesFloat(ctx, out.points); + // } + // } else { + // out.ensurePointSize(result[RESULT_VERTICES], false); + // + // if (verticesAdded) { + // Tessellator.tessGetVerticesFloat(ctx, out.points); + // } else { + // System.arraycopy(geom.points, 0, out.points, 0, numPoints); + // } + // } + // + // out.ensureIndexSize(result[RESULT_TRIANGLES * 3], false); + // Tessellator.tessGetIndices(ctx, out.index); + // + // Tessellator.tessFinish(ctx); + // + // return 1; + // } + // + // /* FIXME This modifies geom ?! */ + // public static int tessellate(GeometryBuffer geom, float scale, + // VertexData outPoints, VertexData outTris, int vertexOffset) { + // + // int numIndices = 0; + // int indexPos = 0; + // int pointPos = 0; + // int indexEnd = geom.index.length; + // + // int[] result = new int[2]; + // + // float s = scale; + // scale = 1; + // + // for (int idx = 0; idx < indexEnd && geom.index[idx] > 0; idx++) { + // indexPos = idx; + // + // int numRings = 1; + // int numPoints = geom.index[idx++]; + // + // for (; idx < indexEnd && geom.index[idx] > 0; idx++) { + // numRings++; + // numPoints += geom.index[idx]; + // } + // + // /* FIXME !!! */ + // for (int i = pointPos; i < pointPos + numPoints; i += 2) { + // geom.points[i + 0] = (int) (geom.points[i + 0] * s); + // geom.points[i + 1] = (int) (geom.points[i + 1] * s); + // } + // + // long ctx = Tessellator.tessellate(geom.points, pointPos, + // geom.index, indexPos, + // numRings, result); + // + // if (result[RESULT_VERTICES] == 0 || result[RESULT_TRIANGLES] == 0) { + // log.debug("ppos " + pointPos + " ipos:" + indexPos + + // " rings:" + numRings + " " + Arrays.toString(geom.index)); + // continue; + // } + // + // pointPos += numPoints; + // + // while (true) { + // VertexData.Chunk vd = outTris.obtainChunk(); + // + // int cnt = Tessellator.tessGetIndicesWO(ctx, vd.vertices, vd.used); + // if (cnt <= 0) + // break; + // + // /* shift by vertexOffset */ + // for (int pos = vd.used, end = pos + cnt; pos < end; pos++) + // vd.vertices[pos] += vertexOffset; + // + // numIndices += cnt; + // + // vd.used += cnt; + // outTris.releaseChunk(); + // + // if (vd.used < VertexData.SIZE) + // break; + // } + // + // while (true) { + // VertexData.Chunk vd = outPoints.obtainChunk(); + // + // int cnt = Tessellator.tessGetVerticesWO(ctx, vd.vertices, vd.used, scale); + // if (cnt <= 0) + // break; + // + // vertexOffset += cnt >> 1; + // + // vd.used += cnt; + // outPoints.releaseChunk(); + // + // if (vd.used < VertexData.SIZE) + // break; + // } + // + // Tessellator.tessFinish(ctx); + // + // if (idx >= indexEnd || geom.index[idx] < 0) + // break; + // } + // + // if (vertexOffset > Short.MAX_VALUE) { + // log.debug("too much !!!" + Arrays.toString(geom.index)); + // return 0; + // } + // + // return numIndices; + // } + // + // /** + // * @param points an array of x,y coordinates + // * @param pos position in points array + // * @param index geom indices + // * @param ipos position in index array + // * @param numRings number of rings in polygon == outer(1) + inner rings + // * @param result contains number of vertices and number of triangles + // * @return context - must be freed with tessFinish() + // */ + // protected static native long tessellate(float[] points, int pos, + // int[] index, int ipos, int numRings, int[] result); + // + // protected static native void tessFinish(long ctx); + // + // protected static native int tessGetVertices(long ctx, short[] coordinates, float scale); + // + // protected static native int tessGetVerticesWO(long ctx, short[] coordinates, + // int offset, float scale); + // + // protected static native int tessGetVerticesFloat(long ctx, float[] coordinates); + // + // protected static native int tessGetIndices(long ctx, int[] indices); + // + // protected static native int tessGetIndicesWO(long ctx, short[] indices, int offset); } diff --git a/vtm/src/org/oscim/utils/ThreadUtils.java b/vtm/src/org/oscim/utils/ThreadUtils.java index 2f7d5344..aa4e9209 100644 --- a/vtm/src/org/oscim/utils/ThreadUtils.java +++ b/vtm/src/org/oscim/utils/ThreadUtils.java @@ -2,19 +2,19 @@ package org.oscim.utils; public class ThreadUtils { - private static Thread MAIN_THREAD; + private static Thread MAIN_THREAD; - public static void assertMainThread() { - if (MAIN_THREAD != Thread.currentThread()) - throw new RuntimeException("Access from non-main thread!"); - } + public static void assertMainThread() { + if (MAIN_THREAD != Thread.currentThread()) + throw new RuntimeException("Access from non-main thread!"); + } - public static boolean isMainThread() { - return MAIN_THREAD == Thread.currentThread(); - } + public static boolean isMainThread() { + return MAIN_THREAD == Thread.currentThread(); + } - public static void init() { - MAIN_THREAD = Thread.currentThread(); - } + public static void init() { + MAIN_THREAD = Thread.currentThread(); + } } diff --git a/vtm/src/org/oscim/utils/TimSort.java b/vtm/src/org/oscim/utils/TimSort.java index 9b8e0a68..bff942e9 100644 --- a/vtm/src/org/oscim/utils/TimSort.java +++ b/vtm/src/org/oscim/utils/TimSort.java @@ -25,23 +25,23 @@ import java.util.Comparator; * this sort requires temporary storage space for * n/2 object references; in the best case, it requires only a small constant * amount of space. - * + *

* This implementation was adapted from Tim Peters's list sort for Python, which * is described in detail here: - * + *

* http://svn.python.org/projects/python/trunk/Objects/listsort.txt - * + *

* Tim's C code may be found here: - * + *

* http://svn.python.org/projects/python/trunk/Objects/listobject.c - * + *

* The underlying techniques are described in this paper (and may have even * earlier origins): - * + *

* "Optimistic Sorting and Information Theoretic Complexity" Peter McIlroy SODA * (Fourth Annual ACM-SIAM Symposium on Discrete * Algorithms), pp 467-474, Austin, Texas, 25-27 January 1993. - * + *

* While the API to this class consists solely of static methods, it is * (privately) instantiable; a TimSort instance holds the * state of an ongoing sort, assuming the input array is large enough to warrant @@ -49,164 +49,170 @@ import java.util.Comparator; * in place, using a binary insertion sort. */ public class TimSort { - /** - * This is the minimum sized sequence that will be merged. Shorter sequences - * will be lengthened by calling binarySort. If the - * entire array is less than this length, no merges will be performed. - * - * This constant should be a power of two. It was 64 in Tim Peter's C - * implementation, but 32 was empirically determined to work - * better in this implementation. In the unlikely event that you set this - * constant to be a number that's not a power of two, - * you'll need to change the {@link #minRunLength} computation. - * - * If you decrease this constant, you must change the stackLen computation - * in the TimSort constructor, or you risk an - * ArrayOutOfBounds exception. See listsort.txt for a discussion of the - * minimum stack length required as a function of the - * length of the array being sorted and the minimum merge sequence length. - */ - private static final int MIN_MERGE = 32; + /** + * This is the minimum sized sequence that will be merged. Shorter sequences + * will be lengthened by calling binarySort. If the + * entire array is less than this length, no merges will be performed. + *

+ * This constant should be a power of two. It was 64 in Tim Peter's C + * implementation, but 32 was empirically determined to work + * better in this implementation. In the unlikely event that you set this + * constant to be a number that's not a power of two, + * you'll need to change the {@link #minRunLength} computation. + *

+ * If you decrease this constant, you must change the stackLen computation + * in the TimSort constructor, or you risk an + * ArrayOutOfBounds exception. See listsort.txt for a discussion of the + * minimum stack length required as a function of the + * length of the array being sorted and the minimum merge sequence length. + */ + private static final int MIN_MERGE = 32; - /** The array being sorted. */ - private T[] a; + /** + * The array being sorted. + */ + private T[] a; - /** The comparator for this sort. */ - private Comparator c; + /** + * The comparator for this sort. + */ + private Comparator c; - /** - * When we get into galloping mode, we stay there until both runs win less - * often than MIN_GALLOP consecutive times. - */ - private static final int MIN_GALLOP = 7; + /** + * When we get into galloping mode, we stay there until both runs win less + * often than MIN_GALLOP consecutive times. + */ + private static final int MIN_GALLOP = 7; - /** - * This controls when we get *into* galloping mode. It is initialized to - * MIN_GALLOP. The mergeLo and mergeHi methods nudge it - * higher for random data, and lower for highly structured data. - */ - private int minGallop = MIN_GALLOP; + /** + * This controls when we get *into* galloping mode. It is initialized to + * MIN_GALLOP. The mergeLo and mergeHi methods nudge it + * higher for random data, and lower for highly structured data. + */ + private int minGallop = MIN_GALLOP; - /** - * Maximum initial size of tmp array, which is used for merging. The array - * can grow to accommodate demand. - * - * Unlike Tim's original C version, we do not allocate this much storage - * when sorting smaller arrays. This change was required - * for performance. - */ - private static final int INITIAL_TMP_STORAGE_LENGTH = 256; + /** + * Maximum initial size of tmp array, which is used for merging. The array + * can grow to accommodate demand. + *

+ * Unlike Tim's original C version, we do not allocate this much storage + * when sorting smaller arrays. This change was required + * for performance. + */ + private static final int INITIAL_TMP_STORAGE_LENGTH = 256; - /** Temp storage for merges. */ - private T[] tmp; // Actual runtime type will be Object[], regardless of T - private int tmpCount; + /** + * Temp storage for merges. + */ + private T[] tmp; // Actual runtime type will be Object[], regardless of T + private int tmpCount; - /** - * A stack of pending runs yet to be merged. Run i starts at address base[i] - * and extends for len[i] elements. It's always true - * (so long as the indices are in bounds) that: - * - * runBase[i] + runLen[i] == runBase[i + 1] - * - * so we could cut the storage for this, but it's a minor amount, and - * keeping all the info explicit simplifies the code. - */ - private int stackSize = 0; // Number of pending runs on stack - private final int[] runBase; - private final int[] runLen; + /** + * A stack of pending runs yet to be merged. Run i starts at address base[i] + * and extends for len[i] elements. It's always true + * (so long as the indices are in bounds) that: + *

+ * runBase[i] + runLen[i] == runBase[i + 1] + *

+ * so we could cut the storage for this, but it's a minor amount, and + * keeping all the info explicit simplifies the code. + */ + private int stackSize = 0; // Number of pending runs on stack + private final int[] runBase; + private final int[] runLen; - /** - * Asserts have been placed in if-statements for performace. To enable them, - * set this field to true and enable them in VM with - * a command line flag. If you modify this class, please do test the - * asserts! - */ - private static final boolean DEBUG = false; + /** + * Asserts have been placed in if-statements for performace. To enable them, + * set this field to true and enable them in VM with + * a command line flag. If you modify this class, please do test the + * asserts! + */ + private static final boolean DEBUG = false; - @SuppressWarnings("unchecked") - public TimSort() { - tmp = (T[]) new Object[INITIAL_TMP_STORAGE_LENGTH]; - runBase = new int[40]; - runLen = new int[40]; - } + @SuppressWarnings("unchecked") + public TimSort() { + tmp = (T[]) new Object[INITIAL_TMP_STORAGE_LENGTH]; + runBase = new int[40]; + runLen = new int[40]; + } - public void doSort(T[] a, Comparator c, int lo, int hi) { - stackSize = 0; - rangeCheck(a.length, lo, hi); - int nRemaining = hi - lo; - if (nRemaining < 2) - return; // Arrays of size 0 and 1 are always sorted + public void doSort(T[] a, Comparator c, int lo, int hi) { + stackSize = 0; + rangeCheck(a.length, lo, hi); + int nRemaining = hi - lo; + if (nRemaining < 2) + return; // Arrays of size 0 and 1 are always sorted - // If array is small, do a "mini-TimSort" with no merges - if (nRemaining < MIN_MERGE) { - int initRunLen = countRunAndMakeAscending(a, lo, hi, c); - binarySort(a, lo, hi, lo + initRunLen, c); - return; - } + // If array is small, do a "mini-TimSort" with no merges + if (nRemaining < MIN_MERGE) { + int initRunLen = countRunAndMakeAscending(a, lo, hi, c); + binarySort(a, lo, hi, lo + initRunLen, c); + return; + } - this.a = a; - this.c = c; - tmpCount = 0; + this.a = a; + this.c = c; + tmpCount = 0; - /** - * March over the array once, left to right, finding natural runs, - * extending short natural runs to minRun elements, and - * merging runs to maintain stack invariant. - */ - int minRun = minRunLength(nRemaining); - do { - // Identify next run - int runLen = countRunAndMakeAscending(a, lo, hi, c); + /** + * March over the array once, left to right, finding natural runs, + * extending short natural runs to minRun elements, and + * merging runs to maintain stack invariant. + */ + int minRun = minRunLength(nRemaining); + do { + // Identify next run + int runLen = countRunAndMakeAscending(a, lo, hi, c); - // If run is short, extend to min(minRun, nRemaining) - if (runLen < minRun) { - int force = nRemaining <= minRun ? nRemaining : minRun; - binarySort(a, lo, lo + force, lo + runLen, c); - runLen = force; - } + // If run is short, extend to min(minRun, nRemaining) + if (runLen < minRun) { + int force = nRemaining <= minRun ? nRemaining : minRun; + binarySort(a, lo, lo + force, lo + runLen, c); + runLen = force; + } - // Push run onto pending-run stack, and maybe merge - pushRun(lo, runLen); - mergeCollapse(); + // Push run onto pending-run stack, and maybe merge + pushRun(lo, runLen); + mergeCollapse(); - // Advance to find next run - lo += runLen; - nRemaining -= runLen; - } while (nRemaining != 0); + // Advance to find next run + lo += runLen; + nRemaining -= runLen; + } while (nRemaining != 0); - // Merge all remaining runs to complete sort - if (DEBUG) - assert lo == hi; - mergeForceCollapse(); - if (DEBUG) - assert stackSize == 1; + // Merge all remaining runs to complete sort + if (DEBUG) + assert lo == hi; + mergeForceCollapse(); + if (DEBUG) + assert stackSize == 1; - this.a = null; - this.c = null; - T[] tmp = this.tmp; - for (int i = 0, n = tmpCount; i < n; i++) - tmp[i] = null; - } + this.a = null; + this.c = null; + T[] tmp = this.tmp; + for (int i = 0, n = tmpCount; i < n; i++) + tmp[i] = null; + } - /** - * Creates a TimSort instance to maintain the state of an ongoing sort. - * - * @param a the array to be sorted - * @param c the comparator to determine the order of the sort - */ - private TimSort(T[] a, Comparator c) { - this.a = a; - this.c = c; + /** + * Creates a TimSort instance to maintain the state of an ongoing sort. + * + * @param a the array to be sorted + * @param c the comparator to determine the order of the sort + */ + private TimSort(T[] a, Comparator c) { + this.a = a; + this.c = c; - // Allocate temp storage (which may be increased later if necessary) - int len = a.length; - @SuppressWarnings("unchecked") - T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len >>> 1 - : INITIAL_TMP_STORAGE_LENGTH]; - tmp = newArray; + // Allocate temp storage (which may be increased later if necessary) + int len = a.length; + @SuppressWarnings("unchecked") + T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len >>> 1 + : INITIAL_TMP_STORAGE_LENGTH]; + tmp = newArray; /* - * Allocate runs-to-be-merged stack (which cannot be expanded). The + * Allocate runs-to-be-merged stack (which cannot be expanded). The * stack length requirements are described in listsort.txt. * The C version always uses the same stack length (85), but this was * measured to be too expensive when sorting "mid-sized" @@ -216,121 +222,121 @@ public class TimSort { * MIN_MERGE is decreased. See the MIN_MERGE declaration * above for more information. */ - int stackLen = (len < 120 ? 5 : len < 1542 ? 10 : len < 119151 ? 19 : 40); - runBase = new int[stackLen]; - runLen = new int[stackLen]; - } + int stackLen = (len < 120 ? 5 : len < 1542 ? 10 : len < 119151 ? 19 : 40); + runBase = new int[stackLen]; + runLen = new int[stackLen]; + } /* - * The next two methods (which are package private and static) constitute + * The next two methods (which are package private and static) constitute * the entire API of this class. Each of these methods * obeys the contract of the public method with the same signature in * java.util.Arrays. */ - static void sort(T[] a, Comparator c) { - sort(a, 0, a.length, c); - } + static void sort(T[] a, Comparator c) { + sort(a, 0, a.length, c); + } - static void sort(T[] a, int lo, int hi, Comparator c) { - if (c == null) { - Arrays.sort(a, lo, hi); - return; - } + static void sort(T[] a, int lo, int hi, Comparator c) { + if (c == null) { + Arrays.sort(a, lo, hi); + return; + } - rangeCheck(a.length, lo, hi); - int nRemaining = hi - lo; - if (nRemaining < 2) - return; // Arrays of size 0 and 1 are always sorted + rangeCheck(a.length, lo, hi); + int nRemaining = hi - lo; + if (nRemaining < 2) + return; // Arrays of size 0 and 1 are always sorted - // If array is small, do a "mini-TimSort" with no merges - if (nRemaining < MIN_MERGE) { - int initRunLen = countRunAndMakeAscending(a, lo, hi, c); - binarySort(a, lo, hi, lo + initRunLen, c); - return; - } + // If array is small, do a "mini-TimSort" with no merges + if (nRemaining < MIN_MERGE) { + int initRunLen = countRunAndMakeAscending(a, lo, hi, c); + binarySort(a, lo, hi, lo + initRunLen, c); + return; + } - /** - * March over the array once, left to right, finding natural runs, - * extending short natural runs to minRun elements, and - * merging runs to maintain stack invariant. - */ - TimSort ts = new TimSort(a, c); - int minRun = minRunLength(nRemaining); - do { - // Identify next run - int runLen = countRunAndMakeAscending(a, lo, hi, c); + /** + * March over the array once, left to right, finding natural runs, + * extending short natural runs to minRun elements, and + * merging runs to maintain stack invariant. + */ + TimSort ts = new TimSort(a, c); + int minRun = minRunLength(nRemaining); + do { + // Identify next run + int runLen = countRunAndMakeAscending(a, lo, hi, c); - // If run is short, extend to min(minRun, nRemaining) - if (runLen < minRun) { - int force = nRemaining <= minRun ? nRemaining : minRun; - binarySort(a, lo, lo + force, lo + runLen, c); - runLen = force; - } + // If run is short, extend to min(minRun, nRemaining) + if (runLen < minRun) { + int force = nRemaining <= minRun ? nRemaining : minRun; + binarySort(a, lo, lo + force, lo + runLen, c); + runLen = force; + } - // Push run onto pending-run stack, and maybe merge - ts.pushRun(lo, runLen); - ts.mergeCollapse(); + // Push run onto pending-run stack, and maybe merge + ts.pushRun(lo, runLen); + ts.mergeCollapse(); - // Advance to find next run - lo += runLen; - nRemaining -= runLen; - } while (nRemaining != 0); + // Advance to find next run + lo += runLen; + nRemaining -= runLen; + } while (nRemaining != 0); - // Merge all remaining runs to complete sort - if (DEBUG) - assert lo == hi; - ts.mergeForceCollapse(); - if (DEBUG) - assert ts.stackSize == 1; - } + // Merge all remaining runs to complete sort + if (DEBUG) + assert lo == hi; + ts.mergeForceCollapse(); + if (DEBUG) + assert ts.stackSize == 1; + } - /** - * Sorts the specified portion of the specified array using a binary - * insertion sort. This is the best method for sorting small - * numbers of elements. It requires O(n log n) compares, but O(n^2) data - * movement (worst case). - * - * If the initial part of the specified range is already sorted, this method - * can take advantage of it: the method assumes that - * the elements from index {@code lo}, inclusive, to {@code start}, - * exclusive - * are already sorted. - * - * @param a the array in which a range is to be sorted - * @param lo the index of the first element in the range to be sorted - * @param hi the index after the last element in the range to be sorted - * @param start the index of the first element in the range that is not - * already known to be sorted (@code lo <= start <= hi} - * @param c comparator to used for the sort - */ - @SuppressWarnings("fallthrough") - private static void binarySort(T[] a, int lo, int hi, int start, Comparator c) { - if (DEBUG) - assert lo <= start && start <= hi; - if (start == lo) - start++; - for (; start < hi; start++) { - T pivot = a[start]; + /** + * Sorts the specified portion of the specified array using a binary + * insertion sort. This is the best method for sorting small + * numbers of elements. It requires O(n log n) compares, but O(n^2) data + * movement (worst case). + *

+ * If the initial part of the specified range is already sorted, this method + * can take advantage of it: the method assumes that + * the elements from index {@code lo}, inclusive, to {@code start}, + * exclusive + * are already sorted. + * + * @param a the array in which a range is to be sorted + * @param lo the index of the first element in the range to be sorted + * @param hi the index after the last element in the range to be sorted + * @param start the index of the first element in the range that is not + * already known to be sorted (@code lo <= start <= hi} + * @param c comparator to used for the sort + */ + @SuppressWarnings("fallthrough") + private static void binarySort(T[] a, int lo, int hi, int start, Comparator c) { + if (DEBUG) + assert lo <= start && start <= hi; + if (start == lo) + start++; + for (; start < hi; start++) { + T pivot = a[start]; - // Set left (and right) to the index where a[start] (pivot) belongs - int left = lo; - int right = start; - if (DEBUG) - assert left <= right; + // Set left (and right) to the index where a[start] (pivot) belongs + int left = lo; + int right = start; + if (DEBUG) + assert left <= right; /* * Invariants: pivot >= all in [lo, left). pivot < all in [right, * start). */ - while (left < right) { - int mid = (left + right) >>> 1; - if (c.compare(pivot, a[mid]) < 0) - right = mid; - else - left = mid + 1; - } - if (DEBUG) - assert left == right; + while (left < right) { + int mid = (left + right) >>> 1; + if (c.compare(pivot, a[mid]) < 0) + right = mid; + else + left = mid + 1; + } + if (DEBUG) + assert left == right; /* * The invariants still hold: pivot >= all in [lo, left) and pivot < @@ -339,289 +345,289 @@ public class TimSort { * first slot after them -- that's why this sort is stable. * Slide elements over to make room to make room for pivot. */ - int n = start - left; // The number of elements to move - // Switch is just an optimization for arraycopy in default case - switch (n) { - case 2: - a[left + 2] = a[left + 1]; - case 1: - a[left + 1] = a[left]; - break; - default: - System.arraycopy(a, left, a, left + 1, n); - } - a[left] = pivot; - } - } + int n = start - left; // The number of elements to move + // Switch is just an optimization for arraycopy in default case + switch (n) { + case 2: + a[left + 2] = a[left + 1]; + case 1: + a[left + 1] = a[left]; + break; + default: + System.arraycopy(a, left, a, left + 1, n); + } + a[left] = pivot; + } + } - /** - * Returns the length of the run beginning at the specified position in the - * specified array and reverses the run if it is - * descending (ensuring that the run will always be ascending when the - * method returns). - * - * A run is the longest ascending sequence with: - * - * a[lo] <= a[lo + 1] <= a[lo + 2] <= ... - * - * or the longest descending sequence with: - * - * a[lo] > a[lo + 1] > a[lo + 2] > ... - * - * For its intended use in a stable mergesort, the strictness of the - * definition of "descending" is needed so that the call can - * safely reverse a descending sequence without violating stability. - * - * @param a the array in which a run is to be counted and possibly reversed - * @param lo index of the first element in the run - * @param hi index after the last element that may be contained in the run. - * It is required that @code{lo < hi}. - * @param c the comparator to used for the sort - * @return the length of the run beginning at the specified position in the - * specified array - */ - private static int countRunAndMakeAscending(T[] a, int lo, int hi, Comparator c) { - if (DEBUG) - assert lo < hi; - int runHi = lo + 1; - if (runHi == hi) - return 1; + /** + * Returns the length of the run beginning at the specified position in the + * specified array and reverses the run if it is + * descending (ensuring that the run will always be ascending when the + * method returns). + *

+ * A run is the longest ascending sequence with: + *

+ * a[lo] <= a[lo + 1] <= a[lo + 2] <= ... + *

+ * or the longest descending sequence with: + *

+ * a[lo] > a[lo + 1] > a[lo + 2] > ... + *

+ * For its intended use in a stable mergesort, the strictness of the + * definition of "descending" is needed so that the call can + * safely reverse a descending sequence without violating stability. + * + * @param a the array in which a run is to be counted and possibly reversed + * @param lo index of the first element in the run + * @param hi index after the last element that may be contained in the run. + * It is required that @code{lo < hi}. + * @param c the comparator to used for the sort + * @return the length of the run beginning at the specified position in the + * specified array + */ + private static int countRunAndMakeAscending(T[] a, int lo, int hi, Comparator c) { + if (DEBUG) + assert lo < hi; + int runHi = lo + 1; + if (runHi == hi) + return 1; - // Find end of run, and reverse range if descending - if (c.compare(a[runHi++], a[lo]) < 0) { // Descending - while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0) - runHi++; - reverseRange(a, lo, runHi); - } else { // Ascending - while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0) - runHi++; - } + // Find end of run, and reverse range if descending + if (c.compare(a[runHi++], a[lo]) < 0) { // Descending + while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0) + runHi++; + reverseRange(a, lo, runHi); + } else { // Ascending + while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0) + runHi++; + } - return runHi - lo; - } + return runHi - lo; + } - /** - * Reverse the specified range of the specified array. - * - * @param a the array in which a range is to be reversed - * @param lo the index of the first element in the range to be reversed - * @param hi the index after the last element in the range to be reversed - */ - private static void reverseRange(Object[] a, int lo, int hi) { - hi--; - while (lo < hi) { - Object t = a[lo]; - a[lo++] = a[hi]; - a[hi--] = t; - } - } + /** + * Reverse the specified range of the specified array. + * + * @param a the array in which a range is to be reversed + * @param lo the index of the first element in the range to be reversed + * @param hi the index after the last element in the range to be reversed + */ + private static void reverseRange(Object[] a, int lo, int hi) { + hi--; + while (lo < hi) { + Object t = a[lo]; + a[lo++] = a[hi]; + a[hi--] = t; + } + } - /** - * Returns the minimum acceptable run length for an array of the specified - * length. Natural runs shorter than this will be - * extended with {@link #binarySort}. - * - * Roughly speaking, the computation is: - * - * If n < MIN_MERGE, return n (it's too small to bother with fancy stuff). - * Else if n is an exact power of 2, return - * MIN_MERGE/2. Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such - * that n/k is close to, but strictly less than, an - * exact power of 2. - * - * For the rationale, see listsort.txt. - * - * @param n the length of the array to be sorted - * @return the length of the minimum run to be merged - */ - private static int minRunLength(int n) { - if (DEBUG) - assert n >= 0; - int r = 0; // Becomes 1 if any 1 bits are shifted off - while (n >= MIN_MERGE) { - r |= (n & 1); - n >>= 1; - } - return n + r; - } + /** + * Returns the minimum acceptable run length for an array of the specified + * length. Natural runs shorter than this will be + * extended with {@link #binarySort}. + *

+ * Roughly speaking, the computation is: + *

+ * If n < MIN_MERGE, return n (it's too small to bother with fancy stuff). + * Else if n is an exact power of 2, return + * MIN_MERGE/2. Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such + * that n/k is close to, but strictly less than, an + * exact power of 2. + *

+ * For the rationale, see listsort.txt. + * + * @param n the length of the array to be sorted + * @return the length of the minimum run to be merged + */ + private static int minRunLength(int n) { + if (DEBUG) + assert n >= 0; + int r = 0; // Becomes 1 if any 1 bits are shifted off + while (n >= MIN_MERGE) { + r |= (n & 1); + n >>= 1; + } + return n + r; + } - /** - * Pushes the specified run onto the pending-run stack. - * - * @param runBase index of the first element in the run - * @param runLen the number of elements in the run - */ - private void pushRun(int runBase, int runLen) { - this.runBase[stackSize] = runBase; - this.runLen[stackSize] = runLen; - stackSize++; - } + /** + * Pushes the specified run onto the pending-run stack. + * + * @param runBase index of the first element in the run + * @param runLen the number of elements in the run + */ + private void pushRun(int runBase, int runLen) { + this.runBase[stackSize] = runBase; + this.runLen[stackSize] = runLen; + stackSize++; + } - /** - * Examines the stack of runs waiting to be merged and merges adjacent runs - * until the stack invariants are reestablished: - * - * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1] 2. runLen[i - 2] > - * runLen[i - 1] - * - * This method is called each time a new run is pushed onto the stack, so - * the invariants are guaranteed to hold for i < - * stackSize upon entry to the method. - */ - private void mergeCollapse() { - while (stackSize > 1) { - int n = stackSize - 2; - if (n > 0 && runLen[n - 1] <= runLen[n] + runLen[n + 1]) { - if (runLen[n - 1] < runLen[n + 1]) - n--; - mergeAt(n); - } else if (runLen[n] <= runLen[n + 1]) { - mergeAt(n); - } else { - break; // Invariant is established - } - } - } + /** + * Examines the stack of runs waiting to be merged and merges adjacent runs + * until the stack invariants are reestablished: + *

+ * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1] 2. runLen[i - 2] > + * runLen[i - 1] + *

+ * This method is called each time a new run is pushed onto the stack, so + * the invariants are guaranteed to hold for i < + * stackSize upon entry to the method. + */ + private void mergeCollapse() { + while (stackSize > 1) { + int n = stackSize - 2; + if (n > 0 && runLen[n - 1] <= runLen[n] + runLen[n + 1]) { + if (runLen[n - 1] < runLen[n + 1]) + n--; + mergeAt(n); + } else if (runLen[n] <= runLen[n + 1]) { + mergeAt(n); + } else { + break; // Invariant is established + } + } + } - /** - * Merges all runs on the stack until only one remains. This method is - * called once, to complete the sort. - */ - private void mergeForceCollapse() { - while (stackSize > 1) { - int n = stackSize - 2; - if (n > 0 && runLen[n - 1] < runLen[n + 1]) - n--; - mergeAt(n); - } - } + /** + * Merges all runs on the stack until only one remains. This method is + * called once, to complete the sort. + */ + private void mergeForceCollapse() { + while (stackSize > 1) { + int n = stackSize - 2; + if (n > 0 && runLen[n - 1] < runLen[n + 1]) + n--; + mergeAt(n); + } + } - /** - * Merges the two runs at stack indices i and i+1. Run i must be the - * penultimate or antepenultimate run on the stack. In other - * words, i must be equal to stackSize-2 or stackSize-3. - * - * @param i stack index of the first of the two runs to merge - */ - private void mergeAt(int i) { - if (DEBUG) - assert stackSize >= 2; - if (DEBUG) - assert i >= 0; - if (DEBUG) - assert i == stackSize - 2 || i == stackSize - 3; + /** + * Merges the two runs at stack indices i and i+1. Run i must be the + * penultimate or antepenultimate run on the stack. In other + * words, i must be equal to stackSize-2 or stackSize-3. + * + * @param i stack index of the first of the two runs to merge + */ + private void mergeAt(int i) { + if (DEBUG) + assert stackSize >= 2; + if (DEBUG) + assert i >= 0; + if (DEBUG) + assert i == stackSize - 2 || i == stackSize - 3; - int base1 = runBase[i]; - int len1 = runLen[i]; - int base2 = runBase[i + 1]; - int len2 = runLen[i + 1]; - if (DEBUG) - assert len1 > 0 && len2 > 0; - if (DEBUG) - assert base1 + len1 == base2; + int base1 = runBase[i]; + int len1 = runLen[i]; + int base2 = runBase[i + 1]; + int len2 = runLen[i + 1]; + if (DEBUG) + assert len1 > 0 && len2 > 0; + if (DEBUG) + assert base1 + len1 == base2; /* * Record the length of the combined runs; if i is the 3rd-last run now, * also slide over the last run (which isn't involved * in this merge). The current run (i+1) goes away in any case. */ - runLen[i] = len1 + len2; - if (i == stackSize - 3) { - runBase[i + 1] = runBase[i + 2]; - runLen[i + 1] = runLen[i + 2]; - } - stackSize--; + runLen[i] = len1 + len2; + if (i == stackSize - 3) { + runBase[i + 1] = runBase[i + 2]; + runLen[i + 1] = runLen[i + 2]; + } + stackSize--; /* * Find where the first element of run2 goes in run1. Prior elements in * run1 can be ignored (because they're already in * place). */ - int k = gallopRight(a[base2], a, base1, len1, 0, c); - if (DEBUG) - assert k >= 0; - base1 += k; - len1 -= k; - if (len1 == 0) - return; + int k = gallopRight(a[base2], a, base1, len1, 0, c); + if (DEBUG) + assert k >= 0; + base1 += k; + len1 -= k; + if (len1 == 0) + return; /* * Find where the last element of run1 goes in run2. Subsequent elements * in run2 can be ignored (because they're already in * place). */ - len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c); - if (DEBUG) - assert len2 >= 0; - if (len2 == 0) - return; + len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c); + if (DEBUG) + assert len2 >= 0; + if (len2 == 0) + return; - // Merge remaining runs, using tmp array with min(len1, len2) elements - if (len1 <= len2) - mergeLo(base1, len1, base2, len2); - else - mergeHi(base1, len1, base2, len2); - } + // Merge remaining runs, using tmp array with min(len1, len2) elements + if (len1 <= len2) + mergeLo(base1, len1, base2, len2); + else + mergeHi(base1, len1, base2, len2); + } - /** - * Locates the position at which to insert the specified key into the - * specified sorted range; if the range contains an element - * equal to key, returns the index of the leftmost equal element. - * - * @param key the key whose insertion point to search for - * @param a the array in which to search - * @param base the index of the first element in the range - * @param len the length of the range; must be > 0 - * @param hint the index at which to begin the search, 0 <= hint < n. The - * closer hint is to the result, the faster this method - * will run. - * @param c the comparator used to order the range, and to search - * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k], - * pretending that a[b - 1] is minus infinity and a[b - * + n] is infinity. In other words, key belongs at index b + k; or - * in other words, the first k elements of a should - * precede key, and the last n - k should follow it. - */ - private static int gallopLeft(T key, T[] a, int base, int len, int hint, - Comparator c) { - if (DEBUG) - assert len > 0 && hint >= 0 && hint < len; - int lastOfs = 0; - int ofs = 1; - if (c.compare(key, a[base + hint]) > 0) { - // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs] - int maxOfs = len - hint; - while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) { - lastOfs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) // int overflow - ofs = maxOfs; - } - if (ofs > maxOfs) - ofs = maxOfs; + /** + * Locates the position at which to insert the specified key into the + * specified sorted range; if the range contains an element + * equal to key, returns the index of the leftmost equal element. + * + * @param key the key whose insertion point to search for + * @param a the array in which to search + * @param base the index of the first element in the range + * @param len the length of the range; must be > 0 + * @param hint the index at which to begin the search, 0 <= hint < n. The + * closer hint is to the result, the faster this method + * will run. + * @param c the comparator used to order the range, and to search + * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k], + * pretending that a[b - 1] is minus infinity and a[b + * + n] is infinity. In other words, key belongs at index b + k; or + * in other words, the first k elements of a should + * precede key, and the last n - k should follow it. + */ + private static int gallopLeft(T key, T[] a, int base, int len, int hint, + Comparator c) { + if (DEBUG) + assert len > 0 && hint >= 0 && hint < len; + int lastOfs = 0; + int ofs = 1; + if (c.compare(key, a[base + hint]) > 0) { + // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs] + int maxOfs = len - hint; + while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) { + lastOfs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) // int overflow + ofs = maxOfs; + } + if (ofs > maxOfs) + ofs = maxOfs; - // Make offsets relative to base - lastOfs += hint; - ofs += hint; - } else { // key <= a[base + hint] - // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs] - final int maxOfs = hint + 1; - while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) { - lastOfs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) // int overflow - ofs = maxOfs; - } - if (ofs > maxOfs) - ofs = maxOfs; + // Make offsets relative to base + lastOfs += hint; + ofs += hint; + } else { // key <= a[base + hint] + // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs] + final int maxOfs = hint + 1; + while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) { + lastOfs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) // int overflow + ofs = maxOfs; + } + if (ofs > maxOfs) + ofs = maxOfs; - // Make offsets relative to base - int tmp = lastOfs; - lastOfs = hint - ofs; - ofs = hint - tmp; - } - if (DEBUG) - assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; + // Make offsets relative to base + int tmp = lastOfs; + lastOfs = hint - ofs; + ofs = hint - tmp; + } + if (DEBUG) + assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; /* * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere to @@ -629,76 +635,76 @@ public class TimSort { * Do a binary search, with invariant a[base + lastOfs - 1] < key <= * a[base + ofs]. */ - lastOfs++; - while (lastOfs < ofs) { - int m = lastOfs + ((ofs - lastOfs) >>> 1); + lastOfs++; + while (lastOfs < ofs) { + int m = lastOfs + ((ofs - lastOfs) >>> 1); - if (c.compare(key, a[base + m]) > 0) - lastOfs = m + 1; // a[base + m] < key - else - ofs = m; // key <= a[base + m] - } - if (DEBUG) - assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs] - return ofs; - } + if (c.compare(key, a[base + m]) > 0) + lastOfs = m + 1; // a[base + m] < key + else + ofs = m; // key <= a[base + m] + } + if (DEBUG) + assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs] + return ofs; + } - /** - * Like gallopLeft, except that if the range contains an element equal to - * key, gallopRight returns the index after the - * rightmost equal element. - * - * @param key the key whose insertion point to search for - * @param a the array in which to search - * @param base the index of the first element in the range - * @param len the length of the range; must be > 0 - * @param hint the index at which to begin the search, 0 <= hint < n. The - * closer hint is to the result, the faster this method - * will run. - * @param c the comparator used to order the range, and to search - * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] - */ - private static int gallopRight(T key, T[] a, int base, int len, int hint, - Comparator c) { - if (DEBUG) - assert len > 0 && hint >= 0 && hint < len; + /** + * Like gallopLeft, except that if the range contains an element equal to + * key, gallopRight returns the index after the + * rightmost equal element. + * + * @param key the key whose insertion point to search for + * @param a the array in which to search + * @param base the index of the first element in the range + * @param len the length of the range; must be > 0 + * @param hint the index at which to begin the search, 0 <= hint < n. The + * closer hint is to the result, the faster this method + * will run. + * @param c the comparator used to order the range, and to search + * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] + */ + private static int gallopRight(T key, T[] a, int base, int len, int hint, + Comparator c) { + if (DEBUG) + assert len > 0 && hint >= 0 && hint < len; - int ofs = 1; - int lastOfs = 0; - if (c.compare(key, a[base + hint]) < 0) { - // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs] - int maxOfs = hint + 1; - while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) { - lastOfs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) // int overflow - ofs = maxOfs; - } - if (ofs > maxOfs) - ofs = maxOfs; + int ofs = 1; + int lastOfs = 0; + if (c.compare(key, a[base + hint]) < 0) { + // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs] + int maxOfs = hint + 1; + while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) { + lastOfs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) // int overflow + ofs = maxOfs; + } + if (ofs > maxOfs) + ofs = maxOfs; - // Make offsets relative to b - int tmp = lastOfs; - lastOfs = hint - ofs; - ofs = hint - tmp; - } else { // a[b + hint] <= key - // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs] - int maxOfs = len - hint; - while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) { - lastOfs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) // int overflow - ofs = maxOfs; - } - if (ofs > maxOfs) - ofs = maxOfs; + // Make offsets relative to b + int tmp = lastOfs; + lastOfs = hint - ofs; + ofs = hint - tmp; + } else { // a[b + hint] <= key + // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs] + int maxOfs = len - hint; + while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) { + lastOfs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) // int overflow + ofs = maxOfs; + } + if (ofs > maxOfs) + ofs = maxOfs; - // Make offsets relative to b - lastOfs += hint; - ofs += hint; - } - if (DEBUG) - assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; + // Make offsets relative to b + lastOfs += hint; + ofs += hint; + } + if (DEBUG) + assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; /* * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to @@ -706,322 +712,324 @@ public class TimSort { * Do a binary search, with invariant a[b + lastOfs - 1] <= key < a[b + * ofs]. */ - lastOfs++; - while (lastOfs < ofs) { - int m = lastOfs + ((ofs - lastOfs) >>> 1); + lastOfs++; + while (lastOfs < ofs) { + int m = lastOfs + ((ofs - lastOfs) >>> 1); - if (c.compare(key, a[base + m]) < 0) - ofs = m; // key < a[b + m] - else - lastOfs = m + 1; // a[b + m] <= key - } - if (DEBUG) - assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs] - return ofs; - } + if (c.compare(key, a[base + m]) < 0) + ofs = m; // key < a[b + m] + else + lastOfs = m + 1; // a[b + m] <= key + } + if (DEBUG) + assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs] + return ofs; + } - /** - * Merges two adjacent runs in place, in a stable fashion. The first element - * of the first run must be greater than the first - * element of the second run (a[base1] > a[base2]), and the last element of - * the first run (a[base1 + len1-1]) must be greater - * than all elements of the second run. - * - * For performance, this method should be called only when len1 <= len2; its - * twin, mergeHi should be called if len1 >= len2. - * (Either method may be called if len1 == len2.) - * - * @param base1 index of first element in first run to be merged - * @param len1 length of first run to be merged (must be > 0) - * @param base2 index of first element in second run to be merged (must be - * aBase + aLen) - * @param len2 length of second run to be merged (must be > 0) - */ - private void mergeLo(int base1, int len1, int base2, int len2) { - if (DEBUG) - assert len1 > 0 && len2 > 0 && base1 + len1 == base2; + /** + * Merges two adjacent runs in place, in a stable fashion. The first element + * of the first run must be greater than the first + * element of the second run (a[base1] > a[base2]), and the last element of + * the first run (a[base1 + len1-1]) must be greater + * than all elements of the second run. + *

+ * For performance, this method should be called only when len1 <= len2; its + * twin, mergeHi should be called if len1 >= len2. + * (Either method may be called if len1 == len2.) + * + * @param base1 index of first element in first run to be merged + * @param len1 length of first run to be merged (must be > 0) + * @param base2 index of first element in second run to be merged (must be + * aBase + aLen) + * @param len2 length of second run to be merged (must be > 0) + */ + private void mergeLo(int base1, int len1, int base2, int len2) { + if (DEBUG) + assert len1 > 0 && len2 > 0 && base1 + len1 == base2; - // Copy first run into temp array - T[] a = this.a; // For performance - T[] tmp = ensureCapacity(len1); - System.arraycopy(a, base1, tmp, 0, len1); + // Copy first run into temp array + T[] a = this.a; // For performance + T[] tmp = ensureCapacity(len1); + System.arraycopy(a, base1, tmp, 0, len1); - int cursor1 = 0; // Indexes into tmp array - int cursor2 = base2; // Indexes int a - int dest = base1; // Indexes int a + int cursor1 = 0; // Indexes into tmp array + int cursor2 = base2; // Indexes int a + int dest = base1; // Indexes int a - // Move first element of second run and deal with degenerate cases - a[dest++] = a[cursor2++]; - if (--len2 == 0) { - System.arraycopy(tmp, cursor1, a, dest, len1); - return; - } - if (len1 == 1) { - System.arraycopy(a, cursor2, a, dest, len2); - a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge - return; - } + // Move first element of second run and deal with degenerate cases + a[dest++] = a[cursor2++]; + if (--len2 == 0) { + System.arraycopy(tmp, cursor1, a, dest, len1); + return; + } + if (len1 == 1) { + System.arraycopy(a, cursor2, a, dest, len2); + a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge + return; + } - Comparator c = this.c; // Use local variable for performance - int minGallop = this.minGallop; // " " " " " - outer: while (true) { - int count1 = 0; // Number of times in a row that first run won - int count2 = 0; // Number of times in a row that second run won + Comparator c = this.c; // Use local variable for performance + int minGallop = this.minGallop; // " " " " " + outer: + while (true) { + int count1 = 0; // Number of times in a row that first run won + int count2 = 0; // Number of times in a row that second run won /* * Do the straightforward thing until (if ever) one run starts * winning consistently. */ - do { - if (DEBUG) - assert len1 > 1 && len2 > 0; - if (c.compare(a[cursor2], tmp[cursor1]) < 0) { - a[dest++] = a[cursor2++]; - count2++; - count1 = 0; - if (--len2 == 0) - break outer; - } else { - a[dest++] = tmp[cursor1++]; - count1++; - count2 = 0; - if (--len1 == 1) - break outer; - } - } while ((count1 | count2) < minGallop); + do { + if (DEBUG) + assert len1 > 1 && len2 > 0; + if (c.compare(a[cursor2], tmp[cursor1]) < 0) { + a[dest++] = a[cursor2++]; + count2++; + count1 = 0; + if (--len2 == 0) + break outer; + } else { + a[dest++] = tmp[cursor1++]; + count1++; + count2 = 0; + if (--len1 == 1) + break outer; + } + } while ((count1 | count2) < minGallop); /* * One run is winning so consistently that galloping may be a huge * win. So try that, and continue galloping until (if * ever) neither run appears to be winning consistently anymore. */ - do { - if (DEBUG) - assert len1 > 1 && len2 > 0; - count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c); - if (count1 != 0) { - System.arraycopy(tmp, cursor1, a, dest, count1); - dest += count1; - cursor1 += count1; - len1 -= count1; - if (len1 <= 1) // len1 == 1 || len1 == 0 - break outer; - } - a[dest++] = a[cursor2++]; - if (--len2 == 0) - break outer; + do { + if (DEBUG) + assert len1 > 1 && len2 > 0; + count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c); + if (count1 != 0) { + System.arraycopy(tmp, cursor1, a, dest, count1); + dest += count1; + cursor1 += count1; + len1 -= count1; + if (len1 <= 1) // len1 == 1 || len1 == 0 + break outer; + } + a[dest++] = a[cursor2++]; + if (--len2 == 0) + break outer; - count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c); - if (count2 != 0) { - System.arraycopy(a, cursor2, a, dest, count2); - dest += count2; - cursor2 += count2; - len2 -= count2; - if (len2 == 0) - break outer; - } - a[dest++] = tmp[cursor1++]; - if (--len1 == 1) - break outer; - minGallop--; - } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); - if (minGallop < 0) - minGallop = 0; - minGallop += 2; // Penalize for leaving gallop mode - } // End of "outer" loop - this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field + count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c); + if (count2 != 0) { + System.arraycopy(a, cursor2, a, dest, count2); + dest += count2; + cursor2 += count2; + len2 -= count2; + if (len2 == 0) + break outer; + } + a[dest++] = tmp[cursor1++]; + if (--len1 == 1) + break outer; + minGallop--; + } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); + if (minGallop < 0) + minGallop = 0; + minGallop += 2; // Penalize for leaving gallop mode + } // End of "outer" loop + this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field - if (len1 == 1) { - if (DEBUG) - assert len2 > 0; - System.arraycopy(a, cursor2, a, dest, len2); - a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge - } else if (len1 == 0) { - throw new IllegalArgumentException("Comparison method violates its general contract!"); - } else { - if (DEBUG) - assert len2 == 0; - if (DEBUG) - assert len1 > 1; - System.arraycopy(tmp, cursor1, a, dest, len1); - } - } + if (len1 == 1) { + if (DEBUG) + assert len2 > 0; + System.arraycopy(a, cursor2, a, dest, len2); + a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge + } else if (len1 == 0) { + throw new IllegalArgumentException("Comparison method violates its general contract!"); + } else { + if (DEBUG) + assert len2 == 0; + if (DEBUG) + assert len1 > 1; + System.arraycopy(tmp, cursor1, a, dest, len1); + } + } - /** - * Like mergeLo, except that this method should be called only if len1 >= - * len2; mergeLo should be called if len1 <= len2. - * (Either method may be called if len1 == len2.) - * - * @param base1 index of first element in first run to be merged - * @param len1 length of first run to be merged (must be > 0) - * @param base2 index of first element in second run to be merged (must be - * aBase + aLen) - * @param len2 length of second run to be merged (must be > 0) - */ - private void mergeHi(int base1, int len1, int base2, int len2) { - if (DEBUG) - assert len1 > 0 && len2 > 0 && base1 + len1 == base2; + /** + * Like mergeLo, except that this method should be called only if len1 >= + * len2; mergeLo should be called if len1 <= len2. + * (Either method may be called if len1 == len2.) + * + * @param base1 index of first element in first run to be merged + * @param len1 length of first run to be merged (must be > 0) + * @param base2 index of first element in second run to be merged (must be + * aBase + aLen) + * @param len2 length of second run to be merged (must be > 0) + */ + private void mergeHi(int base1, int len1, int base2, int len2) { + if (DEBUG) + assert len1 > 0 && len2 > 0 && base1 + len1 == base2; - // Copy second run into temp array - T[] a = this.a; // For performance - T[] tmp = ensureCapacity(len2); - System.arraycopy(a, base2, tmp, 0, len2); + // Copy second run into temp array + T[] a = this.a; // For performance + T[] tmp = ensureCapacity(len2); + System.arraycopy(a, base2, tmp, 0, len2); - int cursor1 = base1 + len1 - 1; // Indexes into a - int cursor2 = len2 - 1; // Indexes into tmp array - int dest = base2 + len2 - 1; // Indexes into a + int cursor1 = base1 + len1 - 1; // Indexes into a + int cursor2 = len2 - 1; // Indexes into tmp array + int dest = base2 + len2 - 1; // Indexes into a - // Move last element of first run and deal with degenerate cases - a[dest--] = a[cursor1--]; - if (--len1 == 0) { - System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2); - return; - } - if (len2 == 1) { - dest -= len1; - cursor1 -= len1; - System.arraycopy(a, cursor1 + 1, a, dest + 1, len1); - a[dest] = tmp[cursor2]; - return; - } + // Move last element of first run and deal with degenerate cases + a[dest--] = a[cursor1--]; + if (--len1 == 0) { + System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2); + return; + } + if (len2 == 1) { + dest -= len1; + cursor1 -= len1; + System.arraycopy(a, cursor1 + 1, a, dest + 1, len1); + a[dest] = tmp[cursor2]; + return; + } - Comparator c = this.c; // Use local variable for performance - int minGallop = this.minGallop; // " " " " " - outer: while (true) { - int count1 = 0; // Number of times in a row that first run won - int count2 = 0; // Number of times in a row that second run won + Comparator c = this.c; // Use local variable for performance + int minGallop = this.minGallop; // " " " " " + outer: + while (true) { + int count1 = 0; // Number of times in a row that first run won + int count2 = 0; // Number of times in a row that second run won /* * Do the straightforward thing until (if ever) one run appears to * win consistently. */ - do { - if (DEBUG) - assert len1 > 0 && len2 > 1; - if (c.compare(tmp[cursor2], a[cursor1]) < 0) { - a[dest--] = a[cursor1--]; - count1++; - count2 = 0; - if (--len1 == 0) - break outer; - } else { - a[dest--] = tmp[cursor2--]; - count2++; - count1 = 0; - if (--len2 == 1) - break outer; - } - } while ((count1 | count2) < minGallop); + do { + if (DEBUG) + assert len1 > 0 && len2 > 1; + if (c.compare(tmp[cursor2], a[cursor1]) < 0) { + a[dest--] = a[cursor1--]; + count1++; + count2 = 0; + if (--len1 == 0) + break outer; + } else { + a[dest--] = tmp[cursor2--]; + count2++; + count1 = 0; + if (--len2 == 1) + break outer; + } + } while ((count1 | count2) < minGallop); /* * One run is winning so consistently that galloping may be a huge * win. So try that, and continue galloping until (if * ever) neither run appears to be winning consistently anymore. */ - do { - if (DEBUG) - assert len1 > 0 && len2 > 1; - count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c); - if (count1 != 0) { - dest -= count1; - cursor1 -= count1; - len1 -= count1; - System.arraycopy(a, cursor1 + 1, a, dest + 1, count1); - if (len1 == 0) - break outer; - } - a[dest--] = tmp[cursor2--]; - if (--len2 == 1) - break outer; + do { + if (DEBUG) + assert len1 > 0 && len2 > 1; + count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c); + if (count1 != 0) { + dest -= count1; + cursor1 -= count1; + len1 -= count1; + System.arraycopy(a, cursor1 + 1, a, dest + 1, count1); + if (len1 == 0) + break outer; + } + a[dest--] = tmp[cursor2--]; + if (--len2 == 1) + break outer; - count2 = len2 - gallopLeft(a[cursor1], tmp, 0, len2, len2 - 1, c); - if (count2 != 0) { - dest -= count2; - cursor2 -= count2; - len2 -= count2; - System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2); - if (len2 <= 1) // len2 == 1 || len2 == 0 - break outer; - } - a[dest--] = a[cursor1--]; - if (--len1 == 0) - break outer; - minGallop--; - } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); - if (minGallop < 0) - minGallop = 0; - minGallop += 2; // Penalize for leaving gallop mode - } // End of "outer" loop - this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field + count2 = len2 - gallopLeft(a[cursor1], tmp, 0, len2, len2 - 1, c); + if (count2 != 0) { + dest -= count2; + cursor2 -= count2; + len2 -= count2; + System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2); + if (len2 <= 1) // len2 == 1 || len2 == 0 + break outer; + } + a[dest--] = a[cursor1--]; + if (--len1 == 0) + break outer; + minGallop--; + } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); + if (minGallop < 0) + minGallop = 0; + minGallop += 2; // Penalize for leaving gallop mode + } // End of "outer" loop + this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field - if (len2 == 1) { - if (DEBUG) - assert len1 > 0; - dest -= len1; - cursor1 -= len1; - System.arraycopy(a, cursor1 + 1, a, dest + 1, len1); - a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge - } else if (len2 == 0) { - throw new IllegalArgumentException("Comparison method violates its general contract!"); - } else { - if (DEBUG) - assert len1 == 0; - if (DEBUG) - assert len2 > 0; - System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2); - } - } + if (len2 == 1) { + if (DEBUG) + assert len1 > 0; + dest -= len1; + cursor1 -= len1; + System.arraycopy(a, cursor1 + 1, a, dest + 1, len1); + a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge + } else if (len2 == 0) { + throw new IllegalArgumentException("Comparison method violates its general contract!"); + } else { + if (DEBUG) + assert len1 == 0; + if (DEBUG) + assert len2 > 0; + System.arraycopy(tmp, 0, a, dest - (len2 - 1), len2); + } + } - /** - * Ensures that the external array tmp has at least the specified number of - * elements, increasing its size if necessary. The - * size increases exponentially to ensure amortized linear time complexity. - * - * @param minCapacity the minimum required capacity of the tmp array - * @return tmp, whether or not it grew - */ - private T[] ensureCapacity(int minCapacity) { - tmpCount = Math.max(tmpCount, minCapacity); - if (tmp.length < minCapacity) { - // Compute smallest power of 2 > minCapacity - int newSize = minCapacity; - newSize |= newSize >> 1; - newSize |= newSize >> 2; - newSize |= newSize >> 4; - newSize |= newSize >> 8; - newSize |= newSize >> 16; - newSize++; + /** + * Ensures that the external array tmp has at least the specified number of + * elements, increasing its size if necessary. The + * size increases exponentially to ensure amortized linear time complexity. + * + * @param minCapacity the minimum required capacity of the tmp array + * @return tmp, whether or not it grew + */ + private T[] ensureCapacity(int minCapacity) { + tmpCount = Math.max(tmpCount, minCapacity); + if (tmp.length < minCapacity) { + // Compute smallest power of 2 > minCapacity + int newSize = minCapacity; + newSize |= newSize >> 1; + newSize |= newSize >> 2; + newSize |= newSize >> 4; + newSize |= newSize >> 8; + newSize |= newSize >> 16; + newSize++; - if (newSize < 0) // Not bloody likely! - newSize = minCapacity; - else - newSize = Math.min(newSize, a.length >>> 1); + if (newSize < 0) // Not bloody likely! + newSize = minCapacity; + else + newSize = Math.min(newSize, a.length >>> 1); - @SuppressWarnings("unchecked") - T[] newArray = (T[]) new Object[newSize]; - tmp = newArray; - } - return tmp; - } + @SuppressWarnings("unchecked") + T[] newArray = (T[]) new Object[newSize]; + tmp = newArray; + } + return tmp; + } - /** - * Checks that fromIndex and toIndex are in range, and throws an appropriate - * exception if they aren't. - * - * @param arrayLen the length of the array - * @param fromIndex the index of the first element of the range - * @param toIndex the index after the last element of the range - * @throws IllegalArgumentException if fromIndex > toIndex - * @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > - * arrayLen - */ - private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) { - if (fromIndex > toIndex) - throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex - + ")"); - if (fromIndex < 0) - throw new ArrayIndexOutOfBoundsException(fromIndex); - if (toIndex > arrayLen) - throw new ArrayIndexOutOfBoundsException(toIndex); - } + /** + * Checks that fromIndex and toIndex are in range, and throws an appropriate + * exception if they aren't. + * + * @param arrayLen the length of the array + * @param fromIndex the index of the first element of the range + * @param toIndex the index after the last element of the range + * @throws IllegalArgumentException if fromIndex > toIndex + * @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > + * arrayLen + */ + private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) { + if (fromIndex > toIndex) + throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + + ")"); + if (fromIndex < 0) + throw new ArrayIndexOutOfBoundsException(fromIndex); + if (toIndex > arrayLen) + throw new ArrayIndexOutOfBoundsException(toIndex); + } } diff --git a/vtm/src/org/oscim/utils/UTF8Decoder.java b/vtm/src/org/oscim/utils/UTF8Decoder.java index 59d9ff2e..9d7f0704 100644 --- a/vtm/src/org/oscim/utils/UTF8Decoder.java +++ b/vtm/src/org/oscim/utils/UTF8Decoder.java @@ -20,116 +20,117 @@ package org.oscim.utils; // modified new String so that it reuses temporary buffer instead of reallocation // when guess for size was incorrect. public class UTF8Decoder { - private static final char REPLACEMENT_CHAR = (char) 0xfffd; + private static final char REPLACEMENT_CHAR = (char) 0xfffd; - char[] mBuffer; - int mBufferSize = 0; + char[] mBuffer; + int mBufferSize = 0; - public String decode(byte[] data, int offset, int byteCount) { - if ((offset | byteCount) < 0 || byteCount > data.length - offset) { - throw new IllegalArgumentException("Brrr " + data.length - + " " + offset + " " + byteCount); - } + public String decode(byte[] data, int offset, int byteCount) { + if ((offset | byteCount) < 0 || byteCount > data.length - offset) { + throw new IllegalArgumentException("Brrr " + data.length + + " " + offset + " " + byteCount); + } - byte[] d = data; - char[] v; + byte[] d = data; + char[] v; - if (mBufferSize < byteCount) - v = mBuffer = new char[byteCount]; - else - v = mBuffer; + if (mBufferSize < byteCount) + v = mBuffer = new char[byteCount]; + else + v = mBuffer; - int idx = offset; - int last = offset + byteCount; - int s = 0; - outer: while (idx < last) { - byte b0 = d[idx++]; - if ((b0 & 0x80) == 0) { - // 0xxxxxxx - // Range: U-00000000 - U-0000007F - int val = b0 & 0xff; - v[s++] = (char) val; - } else if (((b0 & 0xe0) == 0xc0) || ((b0 & 0xf0) == 0xe0) || - ((b0 & 0xf8) == 0xf0) || ((b0 & 0xfc) == 0xf8) || ((b0 & 0xfe) == 0xfc)) { - int utfCount = 1; - if ((b0 & 0xf0) == 0xe0) - utfCount = 2; - else if ((b0 & 0xf8) == 0xf0) - utfCount = 3; - else if ((b0 & 0xfc) == 0xf8) - utfCount = 4; - else if ((b0 & 0xfe) == 0xfc) - utfCount = 5; + int idx = offset; + int last = offset + byteCount; + int s = 0; + outer: + while (idx < last) { + byte b0 = d[idx++]; + if ((b0 & 0x80) == 0) { + // 0xxxxxxx + // Range: U-00000000 - U-0000007F + int val = b0 & 0xff; + v[s++] = (char) val; + } else if (((b0 & 0xe0) == 0xc0) || ((b0 & 0xf0) == 0xe0) || + ((b0 & 0xf8) == 0xf0) || ((b0 & 0xfc) == 0xf8) || ((b0 & 0xfe) == 0xfc)) { + int utfCount = 1; + if ((b0 & 0xf0) == 0xe0) + utfCount = 2; + else if ((b0 & 0xf8) == 0xf0) + utfCount = 3; + else if ((b0 & 0xfc) == 0xf8) + utfCount = 4; + else if ((b0 & 0xfe) == 0xfc) + utfCount = 5; - // 110xxxxx (10xxxxxx)+ - // Range: U-00000080 - U-000007FF (count == 1) - // Range: U-00000800 - U-0000FFFF (count == 2) - // Range: U-00010000 - U-001FFFFF (count == 3) - // Range: U-00200000 - U-03FFFFFF (count == 4) - // Range: U-04000000 - U-7FFFFFFF (count == 5) + // 110xxxxx (10xxxxxx)+ + // Range: U-00000080 - U-000007FF (count == 1) + // Range: U-00000800 - U-0000FFFF (count == 2) + // Range: U-00010000 - U-001FFFFF (count == 3) + // Range: U-00200000 - U-03FFFFFF (count == 4) + // Range: U-04000000 - U-7FFFFFFF (count == 5) - if (idx + utfCount > last) { - v[s++] = REPLACEMENT_CHAR; - break; - } + if (idx + utfCount > last) { + v[s++] = REPLACEMENT_CHAR; + break; + } - // Extract usable bits from b0 - int val = b0 & (0x1f >> (utfCount - 1)); - for (int i = 0; i < utfCount; i++) { - byte b = d[idx++]; - if ((b & 0xC0) != 0x80) { - v[s++] = REPLACEMENT_CHAR; - idx--; // Put the input char back - continue outer; - } - // Push new bits in from the right side - val <<= 6; - val |= b & 0x3f; - } + // Extract usable bits from b0 + int val = b0 & (0x1f >> (utfCount - 1)); + for (int i = 0; i < utfCount; i++) { + byte b = d[idx++]; + if ((b & 0xC0) != 0x80) { + v[s++] = REPLACEMENT_CHAR; + idx--; // Put the input char back + continue outer; + } + // Push new bits in from the right side + val <<= 6; + val |= b & 0x3f; + } - // Note: Java allows overlong char - // specifications To disallow, check that val - // is greater than or equal to the minimum - // value for each count: - // - // count min value - // ----- ---------- - // 1 0x80 - // 2 0x800 - // 3 0x10000 - // 4 0x200000 - // 5 0x4000000 + // Note: Java allows overlong char + // specifications To disallow, check that val + // is greater than or equal to the minimum + // value for each count: + // + // count min value + // ----- ---------- + // 1 0x80 + // 2 0x800 + // 3 0x10000 + // 4 0x200000 + // 5 0x4000000 - // Allow surrogate values (0xD800 - 0xDFFF) to - // be specified using 3-byte UTF values only - if ((utfCount != 2) && (val >= 0xD800) && (val <= 0xDFFF)) { - v[s++] = REPLACEMENT_CHAR; - continue; - } + // Allow surrogate values (0xD800 - 0xDFFF) to + // be specified using 3-byte UTF values only + if ((utfCount != 2) && (val >= 0xD800) && (val <= 0xDFFF)) { + v[s++] = REPLACEMENT_CHAR; + continue; + } - // Reject chars greater than the Unicode maximum of U+10FFFF. - if (val > 0x10FFFF) { - v[s++] = REPLACEMENT_CHAR; - continue; - } + // Reject chars greater than the Unicode maximum of U+10FFFF. + if (val > 0x10FFFF) { + v[s++] = REPLACEMENT_CHAR; + continue; + } - // Encode chars from U+10000 up as surrogate pairs - if (val < 0x10000) { - v[s++] = (char) val; - } else { - int x = val & 0xffff; - int u = (val >> 16) & 0x1f; - int w = (u - 1) & 0xffff; - int hi = 0xd800 | (w << 6) | (x >> 10); - int lo = 0xdc00 | (x & 0x3ff); - v[s++] = (char) hi; - v[s++] = (char) lo; - } - } else { - // Illegal values 0x8*, 0x9*, 0xa*, 0xb*, 0xfd-0xff - v[s++] = REPLACEMENT_CHAR; - } - } - return new String(v, 0, s); - } + // Encode chars from U+10000 up as surrogate pairs + if (val < 0x10000) { + v[s++] = (char) val; + } else { + int x = val & 0xffff; + int u = (val >> 16) & 0x1f; + int w = (u - 1) & 0xffff; + int hi = 0xd800 | (w << 6) | (x >> 10); + int lo = 0xdc00 | (x & 0x3ff); + v[s++] = (char) hi; + v[s++] = (char) lo; + } + } else { + // Illegal values 0x8*, 0x9*, 0xa*, 0xb*, 0xfd-0xff + v[s++] = REPLACEMENT_CHAR; + } + } + return new String(v, 0, s); + } } diff --git a/vtm/src/org/oscim/utils/async/AsyncExecutor.java b/vtm/src/org/oscim/utils/async/AsyncExecutor.java index f05fde2b..224d4463 100644 --- a/vtm/src/org/oscim/utils/async/AsyncExecutor.java +++ b/vtm/src/org/oscim/utils/async/AsyncExecutor.java @@ -1,13 +1,13 @@ /******************************************************************************* * Copyright 2013 Mario Zechner * Copyright 2013 Nathan Sweet - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,64 +30,63 @@ import java.util.concurrent.TimeUnit; * which * case the executor waits for running tasks to finish. Scheduled but not yet * running tasks will not be executed. - * + * * @author badlogic - * */ public class AsyncExecutor { - private final ExecutorService executor; - private final TaskQueue mainloop; + private final ExecutorService executor; + private final TaskQueue mainloop; - /** - * Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable} - * instances to run in parallel. - * - * @param maxConcurrent number of threads. - */ - public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) { - this.mainloop = mainloop; - executor = Executors.newFixedThreadPool(maxConcurrent, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r, "VtmAsyncExecutor"); - thread.setDaemon(true); - thread.setPriority(Thread.NORM_PRIORITY - 1); - return thread; - } - }); - } + /** + * Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable} + * instances to run in parallel. + * + * @param maxConcurrent number of threads. + */ + public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) { + this.mainloop = mainloop; + executor = Executors.newFixedThreadPool(maxConcurrent, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r, "VtmAsyncExecutor"); + thread.setDaemon(true); + thread.setPriority(Thread.NORM_PRIORITY - 1); + return thread; + } + }); + } - /** - * Submits a {@link Runnable} to be executed asynchronously. If - * maxConcurrent runnables are already running, the runnable - * will be queued. - * - * @param task the task to execute asynchronously - */ - public boolean post(Runnable task) { - if (task instanceof AsyncTask) { - ((AsyncTask) task).setTaskQueue(mainloop); - } + /** + * Submits a {@link Runnable} to be executed asynchronously. If + * maxConcurrent runnables are already running, the runnable + * will be queued. + * + * @param task the task to execute asynchronously + */ + public boolean post(Runnable task) { + if (task instanceof AsyncTask) { + ((AsyncTask) task).setTaskQueue(mainloop); + } - try { - executor.execute(task); - } catch (RejectedExecutionException e) { - return false; - } - return true; - } + try { + executor.execute(task); + } catch (RejectedExecutionException e) { + return false; + } + return true; + } - /** - * Waits for running {@link AsyncTask} instances to finish, - * then destroys any resources like threads. Can not be used - * after this method is called. - */ - public void dispose() { - executor.shutdown(); - try { - executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); - } catch (InterruptedException e) { - throw new RuntimeException("Couldn't shutdown loading thread"); - } - } + /** + * Waits for running {@link AsyncTask} instances to finish, + * then destroys any resources like threads. Can not be used + * after this method is called. + */ + public void dispose() { + executor.shutdown(); + try { + executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); + } catch (InterruptedException e) { + throw new RuntimeException("Couldn't shutdown loading thread"); + } + } } diff --git a/vtm/src/org/oscim/utils/async/AsyncTask.java b/vtm/src/org/oscim/utils/async/AsyncTask.java index 562e6549..5362240a 100644 --- a/vtm/src/org/oscim/utils/async/AsyncTask.java +++ b/vtm/src/org/oscim/utils/async/AsyncTask.java @@ -17,42 +17,42 @@ package org.oscim.utils.async; public abstract class AsyncTask extends Task { - private TaskQueue mainloop; + private TaskQueue mainloop; - void setTaskQueue(TaskQueue mainloop) { - this.mainloop = mainloop; - } + void setTaskQueue(TaskQueue mainloop) { + this.mainloop = mainloop; + } - /** - * Do not override! Unless you have a reason, of course. - */ - @Override - public void run() { - if (state == GO) { - /* running on worker thread */ - state = go(false); + /** + * Do not override! Unless you have a reason, of course. + */ + @Override + public void run() { + if (state == GO) { + /* running on worker thread */ + state = go(false); - if (state == GO) - /* run on worker again */ - mainloop.addTask(this); - else - mainloop.post(this); - } else { + if (state == GO) + /* run on worker again */ + mainloop.addTask(this); + else + mainloop.post(this); + } else { /* post result on main-loop */ - onPostExecute(state); - } - } + onPostExecute(state); + } + } - /** - * Executed on worker thread. - * - * @return Task.DONE on success, Task.ERROR otherwise - */ - public abstract int go(boolean canceled); + /** + * Executed on worker thread. + * + * @return Task.DONE on success, Task.ERROR otherwise + */ + public abstract int go(boolean canceled); - /** - * Executed on mainloop thread. - */ - public abstract void onPostExecute(int state); + /** + * Executed on mainloop thread. + */ + public abstract void onPostExecute(int state); } diff --git a/vtm/src/org/oscim/utils/async/SimpleWorker.java b/vtm/src/org/oscim/utils/async/SimpleWorker.java index 8ae5af08..4947bb41 100644 --- a/vtm/src/org/oscim/utils/async/SimpleWorker.java +++ b/vtm/src/org/oscim/utils/async/SimpleWorker.java @@ -8,151 +8,159 @@ import org.oscim.map.Map; */ public abstract class SimpleWorker implements Runnable { - protected final Map mMap; + protected final Map mMap; - protected boolean mRunning; - protected boolean mWait; - protected boolean mCancel; - protected boolean mDelayed; + protected boolean mRunning; + protected boolean mWait; + protected boolean mCancel; + protected boolean mDelayed; - protected long mMinDelay; + protected long mMinDelay; - /** Stuff which can be processed on the worker thread. */ - protected T mTaskTodo; + /** + * Stuff which can be processed on the worker thread. + */ + protected T mTaskTodo; - /** Stuff that is done an ready for being fetched by poll(). */ - protected T mTaskDone; + /** + * Stuff that is done an ready for being fetched by poll(). + */ + protected T mTaskDone; - /** Stuff that is ready - will not be modified in the worker. */ - protected T mTaskLocked; + /** + * Stuff that is ready - will not be modified in the worker. + */ + protected T mTaskLocked; - public SimpleWorker(Map map, long minDelay, T t1, T t2) { - mMap = map; - mMinDelay = minDelay; + public SimpleWorker(Map map, long minDelay, T t1, T t2) { + mMap = map; + mMinDelay = minDelay; - mTaskTodo = t1; - mTaskLocked = t2; - } + mTaskTodo = t1; + mTaskLocked = t2; + } - @Override - public void run() { + @Override + public void run() { - synchronized (this) { - if (mCancel) { - mCancel = false; - mRunning = false; - mDelayed = false; - mWait = false; - if (mTaskTodo != null) - cleanup(mTaskTodo); - finish(); - return; - } + synchronized (this) { + if (mCancel) { + mCancel = false; + mRunning = false; + mDelayed = false; + mWait = false; + if (mTaskTodo != null) + cleanup(mTaskTodo); + finish(); + return; + } - // FIXME: mTaskTodo == null? - if (mDelayed || mTaskTodo == null) { + // FIXME: mTaskTodo == null? + if (mDelayed || mTaskTodo == null) { - if (mDelayed && mTaskTodo != null) - onMainLoop(mTaskTodo); + if (mDelayed && mTaskTodo != null) + onMainLoop(mTaskTodo); - // entered on main-loop - mDelayed = false; - // unset running temporarily - mRunning = false; - submit(0); - return; - } - } + // entered on main-loop + mDelayed = false; + // unset running temporarily + mRunning = false; + submit(0); + return; + } + } - boolean done = doWork(mTaskTodo); + boolean done = doWork(mTaskTodo); - synchronized (this) { - mRunning = false; + synchronized (this) { + mRunning = false; - if (mCancel) { - cleanup(mTaskTodo); - finish(); - mCancel = false; - } else if (done) { - mTaskDone = mTaskTodo; - mTaskTodo = null; - } else if (mWait) { - // only submit if not 'done' - // as otherwise there is no - // mStuffTodo - submit(mMinDelay); - mWait = false; - } - } - } + if (mCancel) { + cleanup(mTaskTodo); + finish(); + mCancel = false; + } else if (done) { + mTaskDone = mTaskTodo; + mTaskTodo = null; + } else if (mWait) { + // only submit if not 'done' + // as otherwise there is no + // mStuffTodo + submit(mMinDelay); + mWait = false; + } + } + } - public abstract boolean doWork(T task); + public abstract boolean doWork(T task); - public abstract void cleanup(T task); + public abstract void cleanup(T task); - public void finish() { + public void finish() { - } + } - /** do stuff on main-loop before executing the task */ - public void onMainLoop(T task) { + /** + * do stuff on main-loop before executing the task + */ + public void onMainLoop(T task) { - } + } - /** - * If delay > 0 onMainLoop will be called before Task - * is passed to worker-thread - */ - public synchronized void submit(long delay) { + /** + * If delay > 0 onMainLoop will be called before Task + * is passed to worker-thread + */ + public synchronized void submit(long delay) { - if (mRunning) { - mWait = true; - return; - } + if (mRunning) { + mWait = true; + return; + } - mRunning = true; - if (delay <= 0) { - mMap.addTask(this); - return; - } + mRunning = true; + if (delay <= 0) { + mMap.addTask(this); + return; + } - if (!mDelayed) { - mDelayed = true; - mMap.postDelayed(this, delay); - } - } + if (!mDelayed) { + mDelayed = true; + mMap.postDelayed(this, delay); + } + } - public synchronized T poll() { - if (mTaskDone == null) - return null; + public synchronized T poll() { + if (mTaskDone == null) + return null; - cleanup(mTaskLocked); - mTaskTodo = mTaskLocked; + cleanup(mTaskLocked); + mTaskTodo = mTaskLocked; - mTaskLocked = mTaskDone; - mTaskDone = null; + mTaskLocked = mTaskDone; + mTaskDone = null; - if (mWait) { - submit(mMinDelay); - mWait = false; - } + if (mWait) { + submit(mMinDelay); + mWait = false; + } - return mTaskLocked; - } + return mTaskLocked; + } - public synchronized void cancel(boolean clear) { - if (mRunning) { - mCancel = true; - return; - } + public synchronized void cancel(boolean clear) { + if (mRunning) { + mCancel = true; + return; + } - if (mTaskTodo != null) - cleanup(mTaskTodo); - finish(); - } + if (mTaskTodo != null) + cleanup(mTaskTodo); + finish(); + } - public synchronized boolean isRunning() { - return mRunning; - } + public synchronized boolean isRunning() { + return mRunning; + } } diff --git a/vtm/src/org/oscim/utils/async/Task.java b/vtm/src/org/oscim/utils/async/Task.java index 31c90306..9842fcf3 100644 --- a/vtm/src/org/oscim/utils/async/Task.java +++ b/vtm/src/org/oscim/utils/async/Task.java @@ -18,26 +18,26 @@ package org.oscim.utils.async; public abstract class Task implements Runnable { - public static final int ERROR = -1; - public static final int CANCEL = 0; - public static final int GO = 1; - public static final int DONE = 2; + public static final int ERROR = -1; + public static final int CANCEL = 0; + public static final int GO = 1; + public static final int DONE = 2; - protected int state = GO; + protected int state = GO; - boolean isCanceled; + boolean isCanceled; - @Override - public void run() { - go(state == CANCEL); - } + @Override + public void run() { + go(state == CANCEL); + } - /** - * @return ignored - */ - public abstract int go(boolean canceled); + /** + * @return ignored + */ + public abstract int go(boolean canceled); - public void cancel() { - state = CANCEL; - } + public void cancel() { + state = CANCEL; + } } diff --git a/vtm/src/org/oscim/utils/async/TaskQueue.java b/vtm/src/org/oscim/utils/async/TaskQueue.java index 57a228b4..818cd71f 100644 --- a/vtm/src/org/oscim/utils/async/TaskQueue.java +++ b/vtm/src/org/oscim/utils/async/TaskQueue.java @@ -18,13 +18,13 @@ package org.oscim.utils.async; public interface TaskQueue { - /** - * Add task to run on a main thread. - */ - boolean post(Runnable task); + /** + * Add task to run on a main thread. + */ + boolean post(Runnable task); - /** - * Add task to run on a worker thread. - */ - void addTask(Runnable task); + /** + * Add task to run on a worker thread. + */ + void addTask(Runnable task); } diff --git a/vtm/src/org/oscim/utils/geom/BezierPath.java b/vtm/src/org/oscim/utils/geom/BezierPath.java index 2ba32332..42405264 100644 --- a/vtm/src/org/oscim/utils/geom/BezierPath.java +++ b/vtm/src/org/oscim/utils/geom/BezierPath.java @@ -1,115 +1,115 @@ package org.oscim.utils.geom; +import org.oscim.core.Point; + import java.util.ArrayList; import java.util.List; -import org.oscim.core.Point; - public class BezierPath { - /** - * from http://paulbourke.net/geometry/bezier/index.html - * Three control point Bezier interpolation - * mu ranges from 0 to 1, start to end of the curve - */ - public static Point bezier3(Point p1, Point p2, Point p3, double mu) { - double mum1, mum12, mu2; - Point p = new Point(); + /** + * from http://paulbourke.net/geometry/bezier/index.html + * Three control point Bezier interpolation + * mu ranges from 0 to 1, start to end of the curve + */ + public static Point bezier3(Point p1, Point p2, Point p3, double mu) { + double mum1, mum12, mu2; + Point p = new Point(); - mu2 = mu * mu; - mum1 = 1 - mu; - mum12 = mum1 * mum1; - p.x = p1.x * mum12 + 2 * p2.x * mum1 * mu + p3.x * mu2; - p.y = p1.y * mum12 + 2 * p2.y * mum1 * mu + p3.y * mu2; - //p.z = p1.z * mum12 + 2 * p2.z * mum1 * mu + p3.z * mu2; + mu2 = mu * mu; + mum1 = 1 - mu; + mum12 = mum1 * mum1; + p.x = p1.x * mum12 + 2 * p2.x * mum1 * mu + p3.x * mu2; + p.y = p1.y * mum12 + 2 * p2.y * mum1 * mu + p3.y * mu2; + //p.z = p1.z * mum12 + 2 * p2.z * mum1 * mu + p3.z * mu2; - return (p); - } + return (p); + } - /** - * from http://paulbourke.net/geometry/bezier/index.html - * Four control point Bezier interpolation - * mu ranges from 0 to 1, start to end of curve - */ - public static Point cubicBezier(Point p1, Point p2, Point p3, Point p4, double mu) { - double mum1, mum13, mu3; - Point p = new Point(); + /** + * from http://paulbourke.net/geometry/bezier/index.html + * Four control point Bezier interpolation + * mu ranges from 0 to 1, start to end of curve + */ + public static Point cubicBezier(Point p1, Point p2, Point p3, Point p4, double mu) { + double mum1, mum13, mu3; + Point p = new Point(); - mum1 = 1 - mu; - mum13 = mum1 * mum1 * mum1; - mu3 = mu * mu * mu; + mum1 = 1 - mu; + mum13 = mum1 * mum1 * mum1; + mu3 = mu * mu * mu; - p.x = mum13 * p1.x + 3 * mu * mum1 * mum1 * p2.x + 3 * mu * mu * mum1 * p3.x + mu3 * p4.x; - p.y = mum13 * p1.y + 3 * mu * mum1 * mum1 * p2.y + 3 * mu * mu * mum1 * p3.y + mu3 * p4.y; - //p.z = mum13*p1.z + 3*mu*mum1*mum1*p2.z + 3*mu*mu*mum1*p3.z + mu3*p4.z; + p.x = mum13 * p1.x + 3 * mu * mum1 * mum1 * p2.x + 3 * mu * mu * mum1 * p3.x + mu3 * p4.x; + p.y = mum13 * p1.y + 3 * mu * mum1 * mum1 * p2.y + 3 * mu * mu * mum1 * p3.y + mu3 * p4.y; + //p.z = mum13*p1.z + 3*mu*mum1*mum1*p2.z + 3*mu*mu*mum1*p3.z + mu3*p4.z; - return (p); - } + return (p); + } - /** - * from geodroid - * FIXME - */ - public static List cubicSplineControlPoints(Point[] coords, float alpha) { + /** + * from geodroid + * FIXME + */ + public static List cubicSplineControlPoints(Point[] coords, float alpha) { - if (alpha < 0.0 || alpha > 1.0) { - throw new IllegalArgumentException("alpha must be between 0 and 1 inclusive"); - } + if (alpha < 0.0 || alpha > 1.0) { + throw new IllegalArgumentException("alpha must be between 0 and 1 inclusive"); + } - if (coords.length < 2) { - throw new IllegalArgumentException("number of Points must be >= 2"); - } + if (coords.length < 2) { + throw new IllegalArgumentException("number of Points must be >= 2"); + } - int n = coords.length; + int n = coords.length; - List ctrl = new ArrayList(); + List ctrl = new ArrayList(); - Point curr = new Point(2 * coords[0].x - coords[1].x, 2 * coords[0].y - coords[1].y); - Point next = coords[0]; + Point curr = new Point(2 * coords[0].x - coords[1].x, 2 * coords[0].y - coords[1].y); + Point next = coords[0]; - Point mid = new Point(); - mid.x = (curr.x + next.x) / 2.0; - mid.y = (curr.y + next.y) / 2.0; + Point mid = new Point(); + mid.x = (curr.x + next.x) / 2.0; + mid.y = (curr.y + next.y) / 2.0; - Point midPrev = new Point(); + Point midPrev = new Point(); - Point last = new Point(2 * coords[n - 1].x - coords[n - 2].x, - 2 * coords[n - 1].y - coords[n - 2].y); + Point last = new Point(2 * coords[n - 1].x - coords[n - 2].x, + 2 * coords[n - 1].y - coords[n - 2].y); - Point anchor = new Point(); - double dv = curr.distance(next); + Point anchor = new Point(); + double dv = curr.distance(next); - for (int i = 0; i < n; i++) { - curr = next; - next = i < n - 1 ? coords[i + 1] : last; + for (int i = 0; i < n; i++) { + curr = next; + next = i < n - 1 ? coords[i + 1] : last; - midPrev.x = mid.x; - midPrev.y = mid.y; + midPrev.x = mid.x; + midPrev.y = mid.y; - mid.x = (curr.x + next.x) / 2.0; - mid.y = (curr.y + next.y) / 2.0; + mid.x = (curr.x + next.x) / 2.0; + mid.y = (curr.y + next.y) / 2.0; - double dvPrev = dv; - dv = curr.distance(next); + double dvPrev = dv; + dv = curr.distance(next); - double p = dvPrev / (dvPrev + dv); + double p = dvPrev / (dvPrev + dv); - anchor.x = midPrev.x + p * (mid.x - midPrev.x); - anchor.y = midPrev.y + p * (mid.y - midPrev.y); + anchor.x = midPrev.x + p * (mid.x - midPrev.x); + anchor.y = midPrev.y + p * (mid.y - midPrev.y); - double dx = anchor.x - curr.x; - double dy = anchor.y - curr.y; + double dx = anchor.x - curr.x; + double dy = anchor.y - curr.y; - if (i > 0) { - ctrl.add(new Point(alpha * (curr.x - midPrev.x + dx) + midPrev.x - dx, - alpha * (curr.y - midPrev.y + dy) + midPrev.y - dy)); - } - if (i < n - 1) { - ctrl.add(new Point(alpha * (curr.x - mid.x + dx) + mid.x - dx, - alpha * (curr.y - mid.y + dy) + mid.y - dy)); - } - } + if (i > 0) { + ctrl.add(new Point(alpha * (curr.x - midPrev.x + dx) + midPrev.x - dx, + alpha * (curr.y - midPrev.y + dy) + midPrev.y - dy)); + } + if (i < n - 1) { + ctrl.add(new Point(alpha * (curr.x - mid.x + dx) + mid.x - dx, + alpha * (curr.y - mid.y + dy) + mid.y - dy)); + } + } - return ctrl; - } + return ctrl; + } } diff --git a/vtm/src/org/oscim/utils/geom/GeometryUtils.java b/vtm/src/org/oscim/utils/geom/GeometryUtils.java index 89d6a8da..30aa5e4f 100644 --- a/vtm/src/org/oscim/utils/geom/GeometryUtils.java +++ b/vtm/src/org/oscim/utils/geom/GeometryUtils.java @@ -18,134 +18,136 @@ package org.oscim.utils.geom; public final class GeometryUtils { - private GeometryUtils() { - } + private GeometryUtils() { + } - /** - * Test if point x/y is in polygon defined by vertices[offset ... - * offset+length] - *

- * -- from www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html - *

- * If there is only one connected component, then it is optional to repeat - * the first vertex at the end. It's also optional to surround the component - * with zero vertices. - *

- * The polygon may contain multiple separate components, and/or holes, - * provided that you separate the components and holes with a (0,0) vertex, - * as follows. - *

  • First, include a (0,0) vertex. - *
  • Then include the first component' vertices, repeating its first - * vertex after the last vertex. - *
  • Include another (0,0) vertex. - *
  • Include another component or hole, repeating its first vertex after - * the last vertex. - *
  • Repeat the above two steps for each component and hole. - *
  • Include a final (0,0) vertex. - *

    - * Each component or hole's vertices may be listed either clockwise or - * counter-clockwise. - */ - public static boolean pointInPoly(float x, float y, float[] vertices, - int length, int offset) { + /** + * Test if point x/y is in polygon defined by vertices[offset ... + * offset+length] + *

    + * -- from www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html + *

    + * If there is only one connected component, then it is optional to repeat + * the first vertex at the end. It's also optional to surround the component + * with zero vertices. + *

    + * The polygon may contain multiple separate components, and/or holes, + * provided that you separate the components and holes with a (0,0) vertex, + * as follows. + *

  • First, include a (0,0) vertex. + *
  • Then include the first component' vertices, repeating its first + * vertex after the last vertex. + *
  • Include another (0,0) vertex. + *
  • Include another component or hole, repeating its first vertex after + * the last vertex. + *
  • Repeat the above two steps for each component and hole. + *
  • Include a final (0,0) vertex. + *

    + * Each component or hole's vertices may be listed either clockwise or + * counter-clockwise. + */ + public static boolean pointInPoly(float x, float y, float[] vertices, + int length, int offset) { - int end = (offset + length); + int end = (offset + length); - boolean inside = false; - for (int i = offset, j = (end - 2); i < end; j = i, i += 2) { - if (((vertices[i + 1] > y) != (vertices[j + 1] > y)) && - (x < (vertices[j] - vertices[i]) * (y - vertices[i + 1]) - / (vertices[j + 1] - vertices[i + 1]) + vertices[i])) - inside = !inside; - } - return inside; - } + boolean inside = false; + for (int i = offset, j = (end - 2); i < end; j = i, i += 2) { + if (((vertices[i + 1] > y) != (vertices[j + 1] > y)) && + (x < (vertices[j] - vertices[i]) * (y - vertices[i + 1]) + / (vertices[j + 1] - vertices[i + 1]) + vertices[i])) + inside = !inside; + } + return inside; + } - public static float area(float ax, float ay, float bx, float by, float cx, float cy) { + public static float area(float ax, float ay, float bx, float by, float cx, float cy) { - float area = ((ax - cx) * (by - cy) - - (bx - cx) * (ay - cy)); + float area = ((ax - cx) * (by - cy) + - (bx - cx) * (ay - cy)); - return (area < 0 ? -area : area) * 0.5f; - } + return (area < 0 ? -area : area) * 0.5f; + } - public static float area(float[] a, int p1, int p2, int p3) { + public static float area(float[] a, int p1, int p2, int p3) { - float area = ((a[p1] - a[p3]) * (a[p2 + 1] - a[p3 + 1]) - - (a[p2] - a[p3]) * (a[p1 + 1] - a[p3 + 1])); + float area = ((a[p1] - a[p3]) * (a[p2 + 1] - a[p3 + 1]) + - (a[p2] - a[p3]) * (a[p1 + 1] - a[p3 + 1])); - return (area < 0 ? -area : area) * 0.5f; - } + return (area < 0 ? -area : area) * 0.5f; + } - public static float squaredDistance(float[] p, int a, int b) { - return (p[a] - p[b]) * (p[a] - p[b]) + (p[a + 1] - p[b + 1]) * (p[a + 1] - p[b + 1]); - } + public static float squaredDistance(float[] p, int a, int b) { + return (p[a] - p[b]) * (p[a] - p[b]) + (p[a + 1] - p[b + 1]) * (p[a + 1] - p[b + 1]); + } - /** square distance from a point a to a segment b,c */ - // modified from https://github.com/ekeneijeoma/simplify-java - public static float squareSegmentDistance(float[] p, int a, int b, int c) { - float x = p[b]; - float y = p[b + 1]; + /** + * square distance from a point a to a segment b,c + */ + // modified from https://github.com/ekeneijeoma/simplify-java + public static float squareSegmentDistance(float[] p, int a, int b, int c) { + float x = p[b]; + float y = p[b + 1]; - float dx = p[c] - x; - float dy = p[c + 1] - y; + float dx = p[c] - x; + float dy = p[c + 1] - y; - if (dx != 0 || dy != 0) { - float t = ((p[a] - x) * dx + (p[a + 1] - y) * dy) / (dx * dx + dy * dy); + if (dx != 0 || dy != 0) { + float t = ((p[a] - x) * dx + (p[a + 1] - y) * dy) / (dx * dx + dy * dy); - if (t > 1) { - x = p[c]; - y = p[c + 1]; - } else if (t > 0) { - x += dx * t; - y += dy * t; - } - } + if (t > 1) { + x = p[c]; + y = p[c + 1]; + } else if (t > 0) { + x += dx * t; + y += dy * t; + } + } - dx = p[a] - x; - dy = p[a + 1] - y; + dx = p[a] - x; + dy = p[a + 1] - y; - return dx * dx + dy * dy; - } + return dx * dx + dy * dy; + } - public static double distance(float[] p, int a, int b) { - float dx = p[a] - p[b]; - float dy = p[a + 1] - p[b + 1]; - return Math.sqrt(dx * dx + dy * dy); - } + public static double distance(float[] p, int a, int b) { + float dx = p[a] - p[b]; + float dy = p[a + 1] - p[b + 1]; + return Math.sqrt(dx * dx + dy * dy); + } - public static double dotProduct(float[] p, int a, int b, int c) { + public static double dotProduct(float[] p, int a, int b, int c) { - double ux = (p[b] - p[a]); - double uy = (p[b + 1] - p[a + 1]); - double ab = Math.sqrt(ux * ux + uy * uy); - double vx = (p[b] - p[c]); - double vy = (p[b + 1] - p[c + 1]); - double bc = Math.sqrt(vx * vx + vy * vy); + double ux = (p[b] - p[a]); + double uy = (p[b + 1] - p[a + 1]); + double ab = Math.sqrt(ux * ux + uy * uy); + double vx = (p[b] - p[c]); + double vy = (p[b + 1] - p[c + 1]); + double bc = Math.sqrt(vx * vx + vy * vy); - double d = ab * bc; + double d = ab * bc; - if (d <= 0) - return 0; + if (d <= 0) + return 0; - double dotp = (ux * -vx + uy * -vy) / d; + double dotp = (ux * -vx + uy * -vy) / d; - if (dotp > 1) - dotp = 1; - else if (dotp < -1) - dotp = -1; + if (dotp > 1) + dotp = 1; + else if (dotp < -1) + dotp = -1; - return dotp; - } + return dotp; + } - public static void main(String[] args) { - float[] p = { -1, 0, 0, 0, 0, 0 }; + public static void main(String[] args) { + float[] p = {-1, 0, 0, 0, 0, 0}; - for (int i = 0; i < 9; i++) { - p[4] = (float) Math.cos(Math.toRadians(i * 45)); - p[5] = (float) Math.sin(Math.toRadians(i * 45)); - System.out.println("\n> " + (i * 45) + " " + p[3] + ":" + p[4] + "\n=" - + dotProduct(p, 0, 2, 4)); - } - } + for (int i = 0; i < 9; i++) { + p[4] = (float) Math.cos(Math.toRadians(i * 45)); + p[5] = (float) Math.sin(Math.toRadians(i * 45)); + System.out.println("\n> " + (i * 45) + " " + p[3] + ":" + p[4] + "\n=" + + dotProduct(p, 0, 2, 4)); + } + } } diff --git a/vtm/src/org/oscim/utils/geom/LineClipper.java b/vtm/src/org/oscim/utils/geom/LineClipper.java index 4c8c3fed..2dba7645 100644 --- a/vtm/src/org/oscim/utils/geom/LineClipper.java +++ b/vtm/src/org/oscim/utils/geom/LineClipper.java @@ -25,256 +25,256 @@ import org.oscim.core.GeometryBuffer; public class LineClipper { - public static final int INSIDE = 0; // 0000 - public static final int LEFT = 1; // 0001 - public static final int RIGHT = 2; // 0010 - public static final int BOTTOM = 4; // 0100 - public static final int TOP = 8; // 1000 + public static final int INSIDE = 0; // 0000 + public static final int LEFT = 1; // 0001 + public static final int RIGHT = 2; // 0010 + public static final int BOTTOM = 4; // 0100 + public static final int TOP = 8; // 1000 - private float xmin, xmax, ymin, ymax; + private float xmin, xmax, ymin, ymax; - public LineClipper(float minx, float miny, float maxx, float maxy) { - this.xmin = minx; - this.ymin = miny; - this.xmax = maxx; - this.ymax = maxy; - } + public LineClipper(float minx, float miny, float maxx, float maxy) { + this.xmin = minx; + this.ymin = miny; + this.xmax = maxx; + this.ymax = maxy; + } - public void setRect(float minx, float miny, float maxx, float maxy) { - this.xmin = minx; - this.ymin = miny; - this.xmax = maxx; - this.ymax = maxy; - } + public void setRect(float minx, float miny, float maxx, float maxy) { + this.xmin = minx; + this.ymin = miny; + this.xmax = maxx; + this.ymax = maxy; + } - private int mPrevOutcode; - private float mPrevX; - private float mPrevY; + private int mPrevOutcode; + private float mPrevX; + private float mPrevY; - public float outX1; - public float outY1; - public float outX2; - public float outY2; + public float outX1; + public float outY1; + public float outX2; + public float outY2; - public boolean clipStart(float x0, float y0) { - mPrevX = x0; - mPrevY = y0; + public boolean clipStart(float x0, float y0) { + mPrevX = x0; + mPrevY = y0; - mPrevOutcode = INSIDE; - if (x0 < xmin) - mPrevOutcode |= LEFT; - else if (x0 > xmax) - mPrevOutcode |= RIGHT; - if (y0 < ymin) - mPrevOutcode |= BOTTOM; - else if (y0 > ymax) - mPrevOutcode |= TOP; + mPrevOutcode = INSIDE; + if (x0 < xmin) + mPrevOutcode |= LEFT; + else if (x0 > xmax) + mPrevOutcode |= RIGHT; + if (y0 < ymin) + mPrevOutcode |= BOTTOM; + else if (y0 > ymax) + mPrevOutcode |= TOP; - return mPrevOutcode == INSIDE; - } + return mPrevOutcode == INSIDE; + } - public int outcode(float x, float y) { + public int outcode(float x, float y) { - int outcode = INSIDE; - if (x < xmin) - outcode |= LEFT; - else if (x > xmax) - outcode |= RIGHT; - if (y < ymin) - outcode |= BOTTOM; - else if (y > ymax) - outcode |= TOP; + int outcode = INSIDE; + if (x < xmin) + outcode |= LEFT; + else if (x > xmax) + outcode |= RIGHT; + if (y < ymin) + outcode |= BOTTOM; + else if (y > ymax) + outcode |= TOP; - return outcode; - } + return outcode; + } - /** - * @return 0 if not intersection, 1 fully within, -1 clipped (and 'out' set - * to new points) - */ - public int clipNext(float x1, float y1) { - int accept; + /** + * @return 0 if not intersection, 1 fully within, -1 clipped (and 'out' set + * to new points) + */ + public int clipNext(float x1, float y1) { + int accept; - int outcode = INSIDE; - if (x1 < xmin) - outcode |= LEFT; - else if (x1 > xmax) - outcode |= RIGHT; + int outcode = INSIDE; + if (x1 < xmin) + outcode |= LEFT; + else if (x1 > xmax) + outcode |= RIGHT; - if (y1 < ymin) - outcode |= BOTTOM; - else if (y1 > ymax) - outcode |= TOP; + if (y1 < ymin) + outcode |= BOTTOM; + else if (y1 > ymax) + outcode |= TOP; - if ((mPrevOutcode | outcode) == 0) { - // Bitwise OR is 0. Trivially accept - accept = 1; - } else if ((mPrevOutcode & outcode) != 0) { - // Bitwise AND is not 0. Trivially reject - accept = 0; - } else { - accept = clip(mPrevX, mPrevY, x1, y1, mPrevOutcode, outcode) ? -1 : 0; - } - mPrevOutcode = outcode; - mPrevX = x1; - mPrevY = y1; + if ((mPrevOutcode | outcode) == 0) { + // Bitwise OR is 0. Trivially accept + accept = 1; + } else if ((mPrevOutcode & outcode) != 0) { + // Bitwise AND is not 0. Trivially reject + accept = 0; + } else { + accept = clip(mPrevX, mPrevY, x1, y1, mPrevOutcode, outcode) ? -1 : 0; + } + mPrevOutcode = outcode; + mPrevX = x1; + mPrevY = y1; - return accept; - } + return accept; + } - public int clipSegment(float x1, float y1, float x2, float y2) { - clipStart(x1, y1); - return clipNext(x2, y2); - } + public int clipSegment(float x1, float y1, float x2, float y2) { + clipStart(x1, y1); + return clipNext(x2, y2); + } - /* CohenSutherland clipping algorithm clips a line from - * P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with - * diagonal from (xmin, ymin) to (xmax, ymax). - * based on en.wikipedia.org/wiki/Cohen-Sutherland */ - private boolean clip(float x0, float y0, float x1, float y1, int outcode0, int outcode1) { - boolean accept = false; + /* CohenSutherland clipping algorithm clips a line from + * P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with + * diagonal from (xmin, ymin) to (xmax, ymax). + * based on en.wikipedia.org/wiki/Cohen-Sutherland */ + private boolean clip(float x0, float y0, float x1, float y1, int outcode0, int outcode1) { + boolean accept = false; - while (true) { - if ((outcode0 | outcode1) == 0) { - /* Bitwise OR is 0. Trivially accept and get out of loop */ - accept = true; - break; - } else if ((outcode0 & outcode1) != 0) { - /* Bitwise AND is not 0. Trivially reject and get out of loop */ - break; - } else { + while (true) { + if ((outcode0 | outcode1) == 0) { + /* Bitwise OR is 0. Trivially accept and get out of loop */ + accept = true; + break; + } else if ((outcode0 & outcode1) != 0) { + /* Bitwise AND is not 0. Trivially reject and get out of loop */ + break; + } else { /* failed both tests, so calculate the line segment to clip * from an outside point to an intersection with clip edge */ - float x = 0; - float y = 0; + float x = 0; + float y = 0; /* At least one endpoint is outside the clip rectangle; pick it. */ - int outcodeOut = (outcode0 == 0) ? outcode1 : outcode0; + int outcodeOut = (outcode0 == 0) ? outcode1 : outcode0; /* Now find the intersection point; * use formulas y = y0 + slope * (x - x0), x = x0 + (1 / slope) * * (y - y0) */ - if ((outcodeOut & TOP) != 0) { + if ((outcodeOut & TOP) != 0) { /* point is above the clip rectangle */ - x = x0 + (x1 - x0) * (ymax - y0) / (y1 - y0); - y = ymax; - } else if ((outcodeOut & BOTTOM) != 0) { + x = x0 + (x1 - x0) * (ymax - y0) / (y1 - y0); + y = ymax; + } else if ((outcodeOut & BOTTOM) != 0) { /* point is below the clip rectangle */ - x = x0 + (x1 - x0) * (ymin - y0) / (y1 - y0); - y = ymin; - } else if ((outcodeOut & RIGHT) != 0) { + x = x0 + (x1 - x0) * (ymin - y0) / (y1 - y0); + y = ymin; + } else if ((outcodeOut & RIGHT) != 0) { /* point is to the right of clip rectangle */ - y = y0 + (y1 - y0) * (xmax - x0) / (x1 - x0); - x = xmax; - } else if ((outcodeOut & LEFT) != 0) { + y = y0 + (y1 - y0) * (xmax - x0) / (x1 - x0); + x = xmax; + } else if ((outcodeOut & LEFT) != 0) { /* point is to the left of clip rectangle */ - y = y0 + (y1 - y0) * (xmin - x0) / (x1 - x0); - x = xmin; - } + y = y0 + (y1 - y0) * (xmin - x0) / (x1 - x0); + x = xmin; + } - int outcode = INSIDE; - if (x < xmin) - outcode |= LEFT; - else if (x > xmax) - outcode |= RIGHT; - if (y < ymin) - outcode |= BOTTOM; - else if (y > ymax) - outcode |= TOP; + int outcode = INSIDE; + if (x < xmin) + outcode |= LEFT; + else if (x > xmax) + outcode |= RIGHT; + if (y < ymin) + outcode |= BOTTOM; + else if (y > ymax) + outcode |= TOP; /* Now we move outside point to intersection point to clip * and get ready for next pass. */ - if (outcodeOut == outcode0) { - x0 = x; - y0 = y; - outcode0 = outcode; - } else { - x1 = x; - y1 = y; - outcode1 = outcode; - } - } - } - if (accept) { - outX1 = x0; - outY1 = y0; - outX2 = x1; - outY2 = y1; - } - return accept; - } + if (outcodeOut == outcode0) { + x0 = x; + y0 = y; + outcode0 = outcode; + } else { + x1 = x; + y1 = y; + outcode1 = outcode; + } + } + } + if (accept) { + outX1 = x0; + outY1 = y0; + outX2 = x1; + outY2 = y1; + } + return accept; + } - public float[] getLine(float out[], int offset) { - if (out == null) - return new float[] { outX1, outY1, outX2, outY2 }; + public float[] getLine(float out[], int offset) { + if (out == null) + return new float[]{outX1, outY1, outX2, outY2}; - out[offset + 0] = outX1; - out[offset + 1] = outY1; - out[offset + 2] = outX2; - out[offset + 3] = outY2; - return out; - } + out[offset + 0] = outX1; + out[offset + 1] = outY1; + out[offset + 2] = outX2; + out[offset + 3] = outY2; + return out; + } - public int clipLine(GeometryBuffer in, GeometryBuffer out) { - out.clear(); - int pointPos = 0; - int numLines = 0; + public int clipLine(GeometryBuffer in, GeometryBuffer out) { + out.clear(); + int pointPos = 0; + int numLines = 0; - for (int i = 0, n = in.index.length; i < n; i++) { - int len = in.index[i]; - if (len < 0) - break; + for (int i = 0, n = in.index.length; i < n; i++) { + int len = in.index[i]; + if (len < 0) + break; - if (len < 4) { - pointPos += len; - continue; - } + if (len < 4) { + pointPos += len; + continue; + } - if (len == 0) { - continue; - } + if (len == 0) { + continue; + } - int inPos = pointPos; - int end = inPos + len; + int inPos = pointPos; + int end = inPos + len; - float x = in.points[inPos++]; - float y = in.points[inPos++]; + float x = in.points[inPos++]; + float y = in.points[inPos++]; - boolean inside = clipStart(x, y); + boolean inside = clipStart(x, y); - if (inside) { - out.startLine(); - out.addPoint(x, y); - numLines++; - } + if (inside) { + out.startLine(); + out.addPoint(x, y); + numLines++; + } - while (inPos < end) { + while (inPos < end) { /* get the current way point coordinates */ - x = in.points[inPos++]; - y = in.points[inPos++]; + x = in.points[inPos++]; + y = in.points[inPos++]; - int clip = clipNext(x, y); - if (clip == 0) { + int clip = clipNext(x, y); + if (clip == 0) { /* current segment is fully outside */ - inside = false; // needed? - } else if (clip == 1) { + inside = false; // needed? + } else if (clip == 1) { /* current segment is fully within */ - out.addPoint(x, y); - } else { /* clip == -1 */ - if (inside) { + out.addPoint(x, y); + } else { /* clip == -1 */ + if (inside) { /* previous was inside */ - out.addPoint(outX2, outY2); - } else { + out.addPoint(outX2, outY2); + } else { /* previous was outside */ - out.startLine(); - numLines++; - out.addPoint(outX1, outY1); - out.addPoint(outX2, outY2); - } - inside = clipStart(x, y); - } - } - pointPos = end; - } - return numLines; - } + out.startLine(); + numLines++; + out.addPoint(outX1, outY1); + out.addPoint(outX2, outY2); + } + inside = clipStart(x, y); + } + } + pointPos = end; + } + return numLines; + } } diff --git a/vtm/src/org/oscim/utils/geom/OBB2D.java b/vtm/src/org/oscim/utils/geom/OBB2D.java index 71ffd6a2..5274e95d 100644 --- a/vtm/src/org/oscim/utils/geom/OBB2D.java +++ b/vtm/src/org/oscim/utils/geom/OBB2D.java @@ -22,327 +22,327 @@ package org.oscim.utils.geom; public class OBB2D { - /** - * Vector math for one array - */ - public static class Vec2 { - - public static void set(float[] v, int pos, float x, float y) { - v[pos + 0] = x; - v[pos + 1] = y; - } - - public static float dot(float[] v, int a, int b) { - return v[a] * v[b] + v[a + 1] * v[b + 1]; - } - - public final static float lengthSquared(float[] v, int pos) { - float x = v[pos + 0]; - float y = v[pos + 1]; - - return x * x + y * y; - } - - public final static void normalizeSquared(float[] v, int pos) { - float x = v[pos + 0]; - float y = v[pos + 1]; - - float length = x * x + y * y; - - v[pos + 0] = x / length; - v[pos + 1] = y / length; - } - - public final static void normalize(float[] v, int pos) { - float x = v[pos + 0]; - float y = v[pos + 1]; - - double length = Math.sqrt(x * x + y * y); - - v[pos + 0] = (float) (x / length); - v[pos + 1] = (float) (y / length); - } - - public final static float length(float[] v, int pos) { - float x = v[pos + 0]; - float y = v[pos + 1]; - - return (float) Math.sqrt(x * x + y * y); - } - - public final static void add(float[] v, int r, int a, int b) { - v[r + 0] = v[a + 0] + v[b + 0]; - v[r + 1] = v[a + 1] + v[b + 1]; - } - - public final static void sub(float[] v, int r, int a, int b) { - v[r + 0] = v[a + 0] - v[b + 0]; - v[r + 1] = v[a + 1] - v[b + 1]; - } - - public final static void mul(float[] v, int pos, float a) { - v[pos + 0] *= a; - v[pos + 1] *= a; - } - } - - float originX; - float originY; - - public final float[] vec = new float[4 * 2 + 2 * 2]; - - // Corners of the box, where 0 is the lower left. - //public final float[] corner = new float[ 4 * 2]; - private final static int CORNER_X = 0; - private final static int CORNER_Y = CORNER_X + 1; - private final static int CORNER_0 = CORNER_X; - private final static int CORNER_1 = CORNER_X + 2; - //private final static int CORNER_2 = CORNER_X + 4; - private final static int CORNER_3 = CORNER_X + 6; - - // Two edges of the box extended away from origin[CORNER_X + 0]. - //public final float[] axis = new float[2 * 2]; - private final static int AXIS_X = 2 * 4; - private final static int AXIS_Y = AXIS_X + 1; - - private final static int AXIS_1 = AXIS_X; - private final static int AXIS_2 = AXIS_X + 2; - - // Returns true if other overlaps one dimension of this. - private boolean overlaps1Way(OBB2D other) { - for (int a = 0; a <= 2; a += 2) { - float ax = vec[AXIS_X + a]; - float ay = vec[AXIS_Y + a]; - - // dot product - float t = ax * other.vec[CORNER_X] + ay * other.vec[CORNER_Y]; - - // Find the extent of box 2 on axis a - float tMin = t; - float tMax = t; - - for (int c = CORNER_X + 2; c < 8; c += 2) { - t = ax * other.vec[c] + ay * other.vec[c + 1]; - - if (t < tMin) - tMin = t; - else if (t > tMax) - tMax = t; - } - - // We have to subtract off the origin - // See if [tMin, tMax] intersects [0, 1] - if (a == 0) { - if ((tMin > 1 + originX) || (tMax < originX)) - // There was no intersection along this dimension; - // the boxes cannot possibly overlap. - return false; - } else { - if ((tMin > 1 + originY) || (tMax < originY)) - return false; - } - } - - // There was no dimension along which there is no intersection. - // Therefore the boxes overlap. - return true; - } - - // Updates the axes after the corners move. Assumes the - // corners actually form a rectangle. - private void computeAxes() { - Vec2.sub(vec, AXIS_1, CORNER_1, CORNER_0); - Vec2.sub(vec, AXIS_2, CORNER_3, CORNER_0); - - // Make the length of each axis 1/edge length so we know any - // dot product must be less than 1 to fall within the edge. - Vec2.normalizeSquared(vec, AXIS_1); - originX = Vec2.dot(vec, CORNER_0, AXIS_1); - - Vec2.normalizeSquared(vec, AXIS_2); - originY = Vec2.dot(vec, CORNER_0, AXIS_2); - } - - // public OBB2D(float cx, float cy, float w, float h, float angle) { - // float rcos = (float) Math.cos(angle); - // float rsin = (float) Math.sin(angle); - // - // float[] tmp = new float[4 * 2]; - // Vec2.set(tmp, 0, rcos, rsin); - // Vec2.set(tmp, 1, -rsin, rcos); - // - // Vec2.mul(tmp, 0, w / 2); - // Vec2.mul(tmp, 1, h / 2); - // - // Vec2.add(tmp, 2, tmp, 0, tmp, 1); - // Vec2.sub(tmp, 3, tmp, 0, tmp, 1); - // - // Vec2.set(tmp, 0, cx, cy); - // - // Vec2.sub(origin, CORNER_X + 0, tmp, 0, tmp, 3); - // Vec2.add(origin, CORNER_X + 2, tmp, 0, tmp, 3); - // Vec2.add(origin, CORNER_X + 4, tmp, 0, tmp, 2); - // Vec2.sub(origin, CORNER_X + 6, tmp, 0, tmp, 2); - // - // computeAxes(); - // } - // - public OBB2D() { - - } - - public OBB2D(float cx, float cy, float width, float height, double acos, double asin) { - - float vx = (float) acos * width / 2; - float vy = (float) asin * width / 2; - - float ux = (float) -asin * height / 2; - float uy = (float) acos * height / 2; - - vec[CORNER_X] = cx + (vx - ux); - vec[CORNER_Y] = cy + (vy - uy); - - vec[CORNER_X + 2] = cx + (-vx - ux); - vec[CORNER_Y + 2] = cy + (-vy - uy); + /** + * Vector math for one array + */ + public static class Vec2 { + + public static void set(float[] v, int pos, float x, float y) { + v[pos + 0] = x; + v[pos + 1] = y; + } + + public static float dot(float[] v, int a, int b) { + return v[a] * v[b] + v[a + 1] * v[b + 1]; + } + + public final static float lengthSquared(float[] v, int pos) { + float x = v[pos + 0]; + float y = v[pos + 1]; + + return x * x + y * y; + } + + public final static void normalizeSquared(float[] v, int pos) { + float x = v[pos + 0]; + float y = v[pos + 1]; + + float length = x * x + y * y; + + v[pos + 0] = x / length; + v[pos + 1] = y / length; + } + + public final static void normalize(float[] v, int pos) { + float x = v[pos + 0]; + float y = v[pos + 1]; + + double length = Math.sqrt(x * x + y * y); + + v[pos + 0] = (float) (x / length); + v[pos + 1] = (float) (y / length); + } + + public final static float length(float[] v, int pos) { + float x = v[pos + 0]; + float y = v[pos + 1]; + + return (float) Math.sqrt(x * x + y * y); + } + + public final static void add(float[] v, int r, int a, int b) { + v[r + 0] = v[a + 0] + v[b + 0]; + v[r + 1] = v[a + 1] + v[b + 1]; + } + + public final static void sub(float[] v, int r, int a, int b) { + v[r + 0] = v[a + 0] - v[b + 0]; + v[r + 1] = v[a + 1] - v[b + 1]; + } + + public final static void mul(float[] v, int pos, float a) { + v[pos + 0] *= a; + v[pos + 1] *= a; + } + } + + float originX; + float originY; + + public final float[] vec = new float[4 * 2 + 2 * 2]; + + // Corners of the box, where 0 is the lower left. + //public final float[] corner = new float[ 4 * 2]; + private final static int CORNER_X = 0; + private final static int CORNER_Y = CORNER_X + 1; + private final static int CORNER_0 = CORNER_X; + private final static int CORNER_1 = CORNER_X + 2; + //private final static int CORNER_2 = CORNER_X + 4; + private final static int CORNER_3 = CORNER_X + 6; + + // Two edges of the box extended away from origin[CORNER_X + 0]. + //public final float[] axis = new float[2 * 2]; + private final static int AXIS_X = 2 * 4; + private final static int AXIS_Y = AXIS_X + 1; + + private final static int AXIS_1 = AXIS_X; + private final static int AXIS_2 = AXIS_X + 2; + + // Returns true if other overlaps one dimension of this. + private boolean overlaps1Way(OBB2D other) { + for (int a = 0; a <= 2; a += 2) { + float ax = vec[AXIS_X + a]; + float ay = vec[AXIS_Y + a]; + + // dot product + float t = ax * other.vec[CORNER_X] + ay * other.vec[CORNER_Y]; + + // Find the extent of box 2 on axis a + float tMin = t; + float tMax = t; + + for (int c = CORNER_X + 2; c < 8; c += 2) { + t = ax * other.vec[c] + ay * other.vec[c + 1]; + + if (t < tMin) + tMin = t; + else if (t > tMax) + tMax = t; + } + + // We have to subtract off the origin + // See if [tMin, tMax] intersects [0, 1] + if (a == 0) { + if ((tMin > 1 + originX) || (tMax < originX)) + // There was no intersection along this dimension; + // the boxes cannot possibly overlap. + return false; + } else { + if ((tMin > 1 + originY) || (tMax < originY)) + return false; + } + } + + // There was no dimension along which there is no intersection. + // Therefore the boxes overlap. + return true; + } + + // Updates the axes after the corners move. Assumes the + // corners actually form a rectangle. + private void computeAxes() { + Vec2.sub(vec, AXIS_1, CORNER_1, CORNER_0); + Vec2.sub(vec, AXIS_2, CORNER_3, CORNER_0); + + // Make the length of each axis 1/edge length so we know any + // dot product must be less than 1 to fall within the edge. + Vec2.normalizeSquared(vec, AXIS_1); + originX = Vec2.dot(vec, CORNER_0, AXIS_1); + + Vec2.normalizeSquared(vec, AXIS_2); + originY = Vec2.dot(vec, CORNER_0, AXIS_2); + } + + // public OBB2D(float cx, float cy, float w, float h, float angle) { + // float rcos = (float) Math.cos(angle); + // float rsin = (float) Math.sin(angle); + // + // float[] tmp = new float[4 * 2]; + // Vec2.set(tmp, 0, rcos, rsin); + // Vec2.set(tmp, 1, -rsin, rcos); + // + // Vec2.mul(tmp, 0, w / 2); + // Vec2.mul(tmp, 1, h / 2); + // + // Vec2.add(tmp, 2, tmp, 0, tmp, 1); + // Vec2.sub(tmp, 3, tmp, 0, tmp, 1); + // + // Vec2.set(tmp, 0, cx, cy); + // + // Vec2.sub(origin, CORNER_X + 0, tmp, 0, tmp, 3); + // Vec2.add(origin, CORNER_X + 2, tmp, 0, tmp, 3); + // Vec2.add(origin, CORNER_X + 4, tmp, 0, tmp, 2); + // Vec2.sub(origin, CORNER_X + 6, tmp, 0, tmp, 2); + // + // computeAxes(); + // } + // + public OBB2D() { + + } + + public OBB2D(float cx, float cy, float width, float height, double acos, double asin) { + + float vx = (float) acos * width / 2; + float vy = (float) asin * width / 2; + + float ux = (float) -asin * height / 2; + float uy = (float) acos * height / 2; + + vec[CORNER_X] = cx + (vx - ux); + vec[CORNER_Y] = cy + (vy - uy); + + vec[CORNER_X + 2] = cx + (-vx - ux); + vec[CORNER_Y + 2] = cy + (-vy - uy); - vec[CORNER_X + 4] = cx + (-vx + ux); - vec[CORNER_Y + 4] = cy + (-vy + uy); + vec[CORNER_X + 4] = cx + (-vx + ux); + vec[CORNER_Y + 4] = cy + (-vy + uy); - vec[CORNER_X + 6] = cx + (vx + ux); - vec[CORNER_Y + 6] = cy + (vy + uy); + vec[CORNER_X + 6] = cx + (vx + ux); + vec[CORNER_Y + 6] = cy + (vy + uy); - computeAxes(); - } + computeAxes(); + } - public void setNormalized(float cx, float cy, float vx, float vy, float width, float height, - float dy) { - float ux = -vy; - float uy = vx; + public void setNormalized(float cx, float cy, float vx, float vy, float width, float height, + float dy) { + float ux = -vy; + float uy = vx; - float hw = width / 2; - float hh = height / 2; + float hw = width / 2; + float hh = height / 2; - if (dy != 0) { - cx += vx * dy + vy * dy; - cy += -vy * dy + vx * dy; - } + if (dy != 0) { + cx += vx * dy + vy * dy; + cy += -vy * dy + vx * dy; + } - vx *= hw; - vy *= hw; + vx *= hw; + vy *= hw; - ux *= hh; - uy *= hh; + ux *= hh; + uy *= hh; - vec[CORNER_X] = cx - (vx - ux); - vec[CORNER_Y] = cy - (vy - uy); + vec[CORNER_X] = cx - (vx - ux); + vec[CORNER_Y] = cy - (vy - uy); - vec[CORNER_X + 2] = cx + (vx - ux); - vec[CORNER_Y + 2] = cy + (vy - uy); + vec[CORNER_X + 2] = cx + (vx - ux); + vec[CORNER_Y + 2] = cy + (vy - uy); - vec[CORNER_X + 4] = cx + (vx + ux); - vec[CORNER_Y + 4] = cy + (vy + uy); + vec[CORNER_X + 4] = cx + (vx + ux); + vec[CORNER_Y + 4] = cy + (vy + uy); - vec[CORNER_X + 6] = cx - (vx + ux); - vec[CORNER_Y + 6] = cy - (vy + uy); + vec[CORNER_X + 6] = cx - (vx + ux); + vec[CORNER_Y + 6] = cy - (vy + uy); - computeAxes(); - } + computeAxes(); + } - public void set(float cx, float cy, float dx, float dy, float width, float height) { - float vx = cx - dx; - float vy = cy - dy; + public void set(float cx, float cy, float dx, float dy, float width, float height) { + float vx = cx - dx; + float vy = cy - dy; - float a = (float) Math.sqrt(vx * vx + vy * vy); - vx /= a; - vy /= a; + float a = (float) Math.sqrt(vx * vx + vy * vy); + vx /= a; + vy /= a; - float hw = width / 2; - float hh = height / 2; + float hw = width / 2; + float hh = height / 2; - float ux = vy * hh; - float uy = -vx * hh; + float ux = vy * hh; + float uy = -vx * hh; - vx *= hw; - vy *= hw; + vx *= hw; + vy *= hw; - vec[CORNER_X] = cx - vx - ux; - vec[CORNER_Y] = cy - vy - uy; + vec[CORNER_X] = cx - vx - ux; + vec[CORNER_Y] = cy - vy - uy; - vec[CORNER_X + 2] = cx + vx - ux; - vec[CORNER_Y + 2] = cy + vy - uy; + vec[CORNER_X + 2] = cx + vx - ux; + vec[CORNER_Y + 2] = cy + vy - uy; - vec[CORNER_X + 4] = cx + vx + ux; - vec[CORNER_Y + 4] = cy + vy + uy; + vec[CORNER_X + 4] = cx + vx + ux; + vec[CORNER_Y + 4] = cy + vy + uy; - vec[CORNER_X + 6] = cx - vx + ux; - vec[CORNER_Y + 6] = cy - vy + uy; + vec[CORNER_X + 6] = cx - vx + ux; + vec[CORNER_Y + 6] = cy - vy + uy; - computeAxes(); - } + computeAxes(); + } - public OBB2D(float cx, float cy, float dx, float dy, float width, float height) { + public OBB2D(float cx, float cy, float dx, float dy, float width, float height) { - float vx = cx - dx; - float vy = cy - dy; + float vx = cx - dx; + float vy = cy - dy; - float a = (float) Math.sqrt(vx * vx + vy * vy); - vx /= a; - vy /= a; + float a = (float) Math.sqrt(vx * vx + vy * vy); + vx /= a; + vy /= a; - float hw = width / 2; - float hh = height / 2; + float hw = width / 2; + float hh = height / 2; - float ux = vy * hh; - float uy = -vx * hh; + float ux = vy * hh; + float uy = -vx * hh; - vx *= hw; - vy *= hw; + vx *= hw; + vy *= hw; - vec[CORNER_X + 0] = cx - vx - ux; - vec[CORNER_Y + 0] = cy - vy - uy; + vec[CORNER_X + 0] = cx - vx - ux; + vec[CORNER_Y + 0] = cy - vy - uy; - vec[CORNER_X + 2] = cx + vx - ux; - vec[CORNER_Y + 2] = cy + vy - uy; + vec[CORNER_X + 2] = cx + vx - ux; + vec[CORNER_Y + 2] = cy + vy - uy; - vec[CORNER_X + 4] = cx + vx + ux; - vec[CORNER_Y + 4] = cy + vy + uy; + vec[CORNER_X + 4] = cx + vx + ux; + vec[CORNER_Y + 4] = cy + vy + uy; - vec[CORNER_X + 6] = cx - vx + ux; - vec[CORNER_Y + 6] = cy - vy + uy; + vec[CORNER_X + 6] = cx - vx + ux; + vec[CORNER_Y + 6] = cy - vy + uy; - computeAxes(); - } + computeAxes(); + } - // width and height must be > 1 I guess - public OBB2D(float cx, float cy, float width, float height) { + // width and height must be > 1 I guess + public OBB2D(float cx, float cy, float width, float height) { - float hw = width / 2; - float hh = height / 2; + float hw = width / 2; + float hh = height / 2; - vec[CORNER_X] = cx - hw; - vec[CORNER_Y] = cy - hh; + vec[CORNER_X] = cx - hw; + vec[CORNER_Y] = cy - hh; - vec[CORNER_X + 2] = cx - hw; - vec[CORNER_Y + 2] = cy + hh; + vec[CORNER_X + 2] = cx - hw; + vec[CORNER_Y + 2] = cy + hh; - vec[CORNER_X + 4] = cx + hw; - vec[CORNER_Y + 4] = cy + hh; + vec[CORNER_X + 4] = cx + hw; + vec[CORNER_Y + 4] = cy + hh; - vec[CORNER_X + 6] = cx + hw; - vec[CORNER_Y + 6] = cy - hh; + vec[CORNER_X + 6] = cx + hw; + vec[CORNER_Y + 6] = cy - hh; - vec[AXIS_X + 0] = 0; - vec[AXIS_X + 1] = 1 / height; + vec[AXIS_X + 0] = 0; + vec[AXIS_X + 1] = 1 / height; - vec[AXIS_X + 2] = 1 / width; - vec[AXIS_X + 3] = 0; + vec[AXIS_X + 2] = 1 / width; + vec[AXIS_X + 3] = 0; - vec[0] = vec[CORNER_Y] * vec[AXIS_Y]; - vec[1] = vec[CORNER_X + 2] * vec[AXIS_X + 2]; - } + vec[0] = vec[CORNER_Y] * vec[AXIS_Y]; + vec[1] = vec[CORNER_X + 2] * vec[AXIS_X + 2]; + } - // Returns true if the intersection of the boxes is non-empty. - public boolean overlaps(OBB2D other) { - return overlaps1Way(other) && other.overlaps1Way(this); - } + // Returns true if the intersection of the boxes is non-empty. + public boolean overlaps(OBB2D other) { + return overlaps1Way(other) && other.overlaps1Way(this); + } } diff --git a/vtm/src/org/oscim/utils/geom/SimplifyDP.java b/vtm/src/org/oscim/utils/geom/SimplifyDP.java index 70a6df9e..0e38d2cb 100644 --- a/vtm/src/org/oscim/utils/geom/SimplifyDP.java +++ b/vtm/src/org/oscim/utils/geom/SimplifyDP.java @@ -17,117 +17,117 @@ package org.oscim.utils.geom; -import static org.oscim.utils.geom.GeometryUtils.squareSegmentDistance; - import org.oscim.core.GeometryBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.oscim.utils.geom.GeometryUtils.squareSegmentDistance; + /** * Douglas-Peucker line simplification with stack and some bit twiddling. - * + *

    * based on: https://github.com/mourner/simplify-js, * https://github.com/ekeneijeoma/simplify-java */ public class SimplifyDP { - final static Logger log = LoggerFactory.getLogger(SimplifyDP.class); + final static Logger log = LoggerFactory.getLogger(SimplifyDP.class); - boolean[] markers = new boolean[128]; - int[] stack = new int[32]; + boolean[] markers = new boolean[128]; + int[] stack = new int[32]; - public void simplify(GeometryBuffer geom, float sqTolerance) { - int[] idx = geom.index; + public void simplify(GeometryBuffer geom, float sqTolerance) { + int[] idx = geom.index; - int inPos = 0; - int outPos = 0; + int inPos = 0; + int outPos = 0; - for (int i = 0, n = idx.length; i < n; i++) { - int len = idx[i]; - if (len < 0) - break; - if (len < 6) { - inPos += len; - outPos += len; - continue; - } + for (int i = 0, n = idx.length; i < n; i++) { + int len = idx[i]; + if (len < 0) + break; + if (len < 6) { + inPos += len; + outPos += len; + continue; + } - int end = simplify(geom.points, inPos, len, outPos, sqTolerance); - if (end > inPos + len) - log.error("out larger than cur: {} > {}", end, inPos + len); + int end = simplify(geom.points, inPos, len, outPos, sqTolerance); + if (end > inPos + len) + log.error("out larger than cur: {} > {}", end, inPos + len); - idx[i] = (short) (end - outPos); - outPos = end; - inPos += len; - } - } + idx[i] = (short) (end - outPos); + outPos = end; + inPos += len; + } + } - public int simplify(float[] points, int inPos, int length, int out, float sqTolerance) { + public int simplify(float[] points, int inPos, int length, int out, float sqTolerance) { - if ((length >> 1) >= markers.length) - markers = new boolean[length >> 1]; - //else - // Arrays.fill(markers, false); + if ((length >> 1) >= markers.length) + markers = new boolean[length >> 1]; + //else + // Arrays.fill(markers, false); - int first = inPos; - int last = inPos + length - 2; - int index = 0; + int first = inPos; + int last = inPos + length - 2; + int index = 0; - float maxSqDist; - float sqDist; - int sp = 0; + float maxSqDist; + float sqDist; + int sp = 0; - while (true) { - maxSqDist = 0; + while (true) { + maxSqDist = 0; - for (int i = first + 2; i < last; i += 2) { - sqDist = squareSegmentDistance(points, i, first, last); - if (sqDist > maxSqDist) { - index = i; - maxSqDist = sqDist; - } - } + for (int i = first + 2; i < last; i += 2) { + sqDist = squareSegmentDistance(points, i, first, last); + if (sqDist > maxSqDist) { + index = i; + maxSqDist = sqDist; + } + } - if (maxSqDist > sqTolerance) { - markers[(index - inPos) >> 1] = true; + if (maxSqDist > sqTolerance) { + markers[(index - inPos) >> 1] = true; - if (sp + 4 == stack.length) { - int tmp[] = new int[stack.length + 64]; - System.arraycopy(stack, 0, tmp, 0, stack.length); - stack = tmp; - } + if (sp + 4 == stack.length) { + int tmp[] = new int[stack.length + 64]; + System.arraycopy(stack, 0, tmp, 0, stack.length); + stack = tmp; + } - stack[sp++] = first; - stack[sp++] = index; + stack[sp++] = first; + stack[sp++] = index; - stack[sp++] = index; - stack[sp++] = last; - } + stack[sp++] = index; + stack[sp++] = last; + } - if (sp == 0) - break; + if (sp == 0) + break; - last = stack[--sp]; - first = stack[--sp]; - } + last = stack[--sp]; + first = stack[--sp]; + } - points[out++] = points[inPos]; - points[out++] = points[inPos + 1]; + points[out++] = points[inPos]; + points[out++] = points[inPos + 1]; - last = inPos + length - 2; + last = inPos + length - 2; - for (int i = 0; i < length / 2; i++) { - if (!markers[i]) - continue; - markers[i] = false; + for (int i = 0; i < length / 2; i++) { + if (!markers[i]) + continue; + markers[i] = false; - int pos = inPos + i * 2; + int pos = inPos + i * 2; - points[out++] = points[pos]; - points[out++] = points[pos + 1]; - } - points[out++] = points[last]; - points[out++] = points[last + 1]; + points[out++] = points[pos]; + points[out++] = points[pos + 1]; + } + points[out++] = points[last]; + points[out++] = points[last + 1]; - return out; - } + return out; + } } diff --git a/vtm/src/org/oscim/utils/geom/SimplifyVW.java b/vtm/src/org/oscim/utils/geom/SimplifyVW.java index da0b09f2..4dc4eeaa 100644 --- a/vtm/src/org/oscim/utils/geom/SimplifyVW.java +++ b/vtm/src/org/oscim/utils/geom/SimplifyVW.java @@ -23,222 +23,224 @@ import org.oscim.utils.pool.Pool; /** * Visvalingam-Wyatt simplification - * + *

    * based on: * https://github.com/mbloch/mapshaper/blob/master/src/mapshaper-visvalingam.js - * */ + */ public class SimplifyVW { - class Item extends Inlist { - int index; - int id; - float area; + class Item extends Inlist { + int index; + int id; + float area; - Item prev; - } + Item prev; + } - Pool pool = new Pool() { - @Override - protected Item createItem() { - return new Item(); - } - }; + Pool pool = new Pool() { + @Override + protected Item createItem() { + return new Item(); + } + }; - private Item[] heap = new Item[100]; - private int size = 0; + private Item[] heap = new Item[100]; + private int size = 0; - public void simplify(GeometryBuffer geom, float minArea) { - Item prev = null; - Item first = null; - Item it; + public void simplify(GeometryBuffer geom, float minArea) { + Item prev = null; + Item first = null; + Item it; - size = 0; + size = 0; - if (heap.length < geom.pointPos >> 1) - heap = new Item[geom.pointPos >> 1]; + if (heap.length < geom.pointPos >> 1) + heap = new Item[geom.pointPos >> 1]; - first = prev = push(0, Float.MAX_VALUE); + first = prev = push(0, Float.MAX_VALUE); - for (int i = 2; i < geom.pointPos - 2; i += 2) { - it = push(i, area(geom.points, i - 2, i, i + 2)); - prev.next = it; - it.prev = prev; + for (int i = 2; i < geom.pointPos - 2; i += 2) { + it = push(i, area(geom.points, i - 2, i, i + 2)); + prev.next = it; + it.prev = prev; - prev = it; - } + prev = it; + } - Item last = push(geom.pointPos - 2, Float.MAX_VALUE); + Item last = push(geom.pointPos - 2, Float.MAX_VALUE); - // sorter.doSort(heap, DistanceComparator, 0, size); - // for (int i = 0; i < size; i++) - // heap[i].index = i; + // sorter.doSort(heap, DistanceComparator, 0, size); + // for (int i = 0; i < size; i++) + // heap[i].index = i; - last.prev = prev; - prev.next = last; + last.prev = prev; + prev.next = last; - last.next = first; - first.prev = last; + last.next = first; + first.prev = last; - while ((it = pop()) != null) { - if (it.area > minArea) - break; + while ((it = pop()) != null) { + if (it.area > minArea) + break; - if (it.prev == it.next) - break; + if (it.prev == it.next) + break; - it.prev.next = it.next; - it.next.prev = it.prev; + it.prev.next = it.next; + it.next.prev = it.prev; - if (it.prev != first) - update(geom, it.prev); + if (it.prev != first) + update(geom, it.prev); - if (it.next != first) - update(geom, it.next); + if (it.next != first) + update(geom, it.next); - it = pool.release(it); - } + it = pool.release(it); + } - first.prev.next = null; - first.prev = null; - it = first; + first.prev.next = null; + first.prev = null; + it = first; - float[] points = new float[geom.pointPos]; - System.arraycopy(geom.points, 0, points, 0, geom.pointPos); + float[] points = new float[geom.pointPos]; + System.arraycopy(geom.points, 0, points, 0, geom.pointPos); - geom.clear(); - geom.startPolygon(); + geom.clear(); + geom.startPolygon(); - while (it != null) { - float x = points[it.id]; - float y = points[it.id + 1]; - geom.addPoint(x, y); - it = it.next; - } + while (it != null) { + float x = points[it.id]; + float y = points[it.id + 1]; + geom.addPoint(x, y); + it = it.next; + } - first = pool.release(first); - } + first = pool.release(first); + } - public static float area(float[] a, int p1, int p2, int p3) { + public static float area(float[] a, int p1, int p2, int p3) { - float area = GeometryUtils.area(a, p1, p2, p3); - double dotp = GeometryUtils.dotProduct(a, p1, p2, p3); - //return (float) (area * (0.5 + 0.5 * (1 - dotp * dotp))); + float area = GeometryUtils.area(a, p1, p2, p3); + double dotp = GeometryUtils.dotProduct(a, p1, p2, p3); + //return (float) (area * (0.5 + 0.5 * (1 - dotp * dotp))); - dotp = Math.abs(dotp); - double weight = dotp < 0.5 ? 0.1 : dotp < 1 ? 0.3 : 1; - return (float) (area * weight); - } + dotp = Math.abs(dotp); + double weight = dotp < 0.5 ? 0.1 : dotp < 1 ? 0.3 : 1; + return (float) (area * weight); + } - private void update(GeometryBuffer geom, Item it) { - float area = area(geom.points, it.prev.id, it.id, it.next.id); - update(it, area); - //remove(it); - //it.area = area(geom.points, it.prev.id, it.id, it.next.id); - //push(it); - } + private void update(GeometryBuffer geom, Item it) { + float area = area(geom.points, it.prev.id, it.id, it.next.id); + update(it, area); + //remove(it); + //it.area = area(geom.points, it.prev.id, it.id, it.next.id); + //push(it); + } - public void push(Item it) { - heap[size] = it; - it.index = size; - up(size++); - } + public void push(Item it) { + heap[size] = it; + it.index = size; + up(size++); + } - public Item push(int id, float area) { - Item it = pool.get(); - heap[size] = it; - it.index = size; - it.area = area; - it.id = id; - up(size++); - return it; - } + public Item push(int id, float area) { + Item it = pool.get(); + heap[size] = it; + it.index = size; + it.area = area; + it.id = id; + up(size++); + return it; + } - public Item pop() { - if (size == 0) - return null; + public Item pop() { + if (size == 0) + return null; - Item removed = heap[0]; - Item obj = heap[--size]; - heap[size] = null; + Item removed = heap[0]; + Item obj = heap[--size]; + heap[size] = null; - if (size > 0) { - heap[obj.index = 0] = obj; - down(0); - } - return removed; - } + if (size > 0) { + heap[obj.index = 0] = obj; + down(0); + } + return removed; + } - public void update(Item it, float area) { - if (area < it.area) { - it.area = area; - up(it.index); - } else { - it.area = area; - down(it.index); - } - } + public void update(Item it, float area) { + if (area < it.area) { + it.area = area; + up(it.index); + } else { + it.area = area; + down(it.index); + } + } - public int remove(Item removed) { - if (size == 0) - throw new IllegalStateException("size == 0"); + public int remove(Item removed) { + if (size == 0) + throw new IllegalStateException("size == 0"); - int i = removed.index; - Item obj = heap[--size]; - heap[size] = null; + int i = removed.index; + Item obj = heap[--size]; + heap[size] = null; /* if min obj was popped */ - if (i == size) - return i; + if (i == size) + return i; /* else put min obj in place of the removed item */ - obj.index = i; - heap[i] = obj; + obj.index = i; + heap[i] = obj; - if (obj.area < removed.area) { - up(i); - } else - down(i); + if (obj.area < removed.area) { + up(i); + } else + down(i); - return i; - }; + return i; + } - private void up(int i) { - Item it = heap[i]; - while (i > 0) { - int up = ((i + 1) >> 1) - 1; - Item parent = heap[up]; + ; - if (it.area >= parent.area) - break; + private void up(int i) { + Item it = heap[i]; + while (i > 0) { + int up = ((i + 1) >> 1) - 1; + Item parent = heap[up]; - parent.index = i; - heap[i] = parent; + if (it.area >= parent.area) + break; - it.index = i = up; - heap[i] = it; - } - } + parent.index = i; + heap[i] = parent; - private void down(int i) { - Item it = heap[i]; - while (true) { - int right = (i + 1) << 1; - int left = right - 1; - int down = i; + it.index = i = up; + heap[i] = it; + } + } - Item child = heap[down]; + private void down(int i) { + Item it = heap[i]; + while (true) { + int right = (i + 1) << 1; + int left = right - 1; + int down = i; - if (left < size && heap[left].area < child.area) - child = heap[down = left]; + Item child = heap[down]; - if (right < size && heap[right].area < child.area) - child = heap[down = right]; + if (left < size && heap[left].area < child.area) + child = heap[down = left]; - if (down == i) - break; + if (right < size && heap[right].area < child.area) + child = heap[down = right]; - heap[child.index = i] = child; - heap[it.index = i = down] = it; - } - } + if (down == i) + break; + + heap[child.index = i] = child; + heap[it.index = i = down] = it; + } + } } diff --git a/vtm/src/org/oscim/utils/geom/TileClipper.java b/vtm/src/org/oscim/utils/geom/TileClipper.java index 0a862fbd..f9dbae4b 100644 --- a/vtm/src/org/oscim/utils/geom/TileClipper.java +++ b/vtm/src/org/oscim/utils/geom/TileClipper.java @@ -22,237 +22,235 @@ import org.oscim.core.GeometryBuffer; * Clip polygons and lines to a rectangle. Output cannot expected to be valid * Simple-Feature geometry, i.e. all polygon rings are clipped independently * so that inner and outer rings might touch, etc. - * + *

    * based on http://www.cs.rit.edu/~icss571/clipTrans/PolyClipBack.html */ public class TileClipper { - private float xmin; - private float xmax; - private float ymin; - private float ymax; + private float xmin; + private float xmax; + private float ymin; + private float ymax; - public TileClipper(float xmin, float ymin, float xmax, float ymax) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - mLineClipper = new LineClipper(xmin, ymin, xmax, ymax); - } + public TileClipper(float xmin, float ymin, float xmax, float ymax) { + this.xmin = xmin; + this.ymin = ymin; + this.xmax = xmax; + this.ymax = ymax; + mLineClipper = new LineClipper(xmin, ymin, xmax, ymax); + } - public void setRect(float xmin, float ymin, float xmax, float ymax) { - this.xmin = xmin; - this.ymin = ymin; - this.xmax = xmax; - this.ymax = ymax; - mLineClipper.setRect(xmin, ymin, xmax, ymax); - } + public void setRect(float xmin, float ymin, float xmax, float ymax) { + this.xmin = xmin; + this.ymin = ymin; + this.xmax = xmax; + this.ymax = ymax; + mLineClipper.setRect(xmin, ymin, xmax, ymax); + } - private final LineClipper mLineClipper; + private final LineClipper mLineClipper; - private final GeometryBuffer mGeomOut = new GeometryBuffer(10, 1); + private final GeometryBuffer mGeomOut = new GeometryBuffer(10, 1); - public boolean clip(GeometryBuffer geom) { - if (geom.isPoly()) { + public boolean clip(GeometryBuffer geom) { + if (geom.isPoly()) { - GeometryBuffer out = mGeomOut; - out.clear(); + GeometryBuffer out = mGeomOut; + out.clear(); - clipEdge(geom, out, LineClipper.LEFT); - geom.clear(); + clipEdge(geom, out, LineClipper.LEFT); + geom.clear(); - clipEdge(out, geom, LineClipper.TOP); - out.clear(); + clipEdge(out, geom, LineClipper.TOP); + out.clear(); - clipEdge(geom, out, LineClipper.RIGHT); - geom.clear(); + clipEdge(geom, out, LineClipper.RIGHT); + geom.clear(); - clipEdge(out, geom, LineClipper.BOTTOM); + clipEdge(out, geom, LineClipper.BOTTOM); - if ((geom.indexPos == 0) && (geom.index[0] < 6)) - return false; - } + if ((geom.indexPos == 0) && (geom.index[0] < 6)) + return false; + } else if (geom.isLine()) { - else if (geom.isLine()) { + GeometryBuffer out = mGeomOut; + out.clear(); - GeometryBuffer out = mGeomOut; - out.clear(); + int numLines = mLineClipper.clipLine(geom, out); - int numLines = mLineClipper.clipLine(geom, out); + int idx[] = geom.ensureIndexSize(numLines + 1, false); + System.arraycopy(out.index, 0, idx, 0, numLines); + geom.index[numLines] = -1; - int idx[] = geom.ensureIndexSize(numLines + 1, false); - System.arraycopy(out.index, 0, idx, 0, numLines); - geom.index[numLines] = -1; + float pts[] = geom.ensurePointSize(out.pointPos >> 1, false); + System.arraycopy(out.points, 0, pts, 0, out.pointPos); + geom.indexPos = out.indexPos; + geom.pointPos = out.pointPos; - float pts[] = geom.ensurePointSize(out.pointPos >> 1, false); - System.arraycopy(out.points, 0, pts, 0, out.pointPos); - geom.indexPos = out.indexPos; - geom.pointPos = out.pointPos; + if ((geom.indexPos == 0) && (geom.index[0] < 4)) + return false; + } + return true; + } - if ((geom.indexPos == 0) && (geom.index[0] < 4)) - return false; - } - return true; - } + private boolean clipEdge(GeometryBuffer in, GeometryBuffer out, int edge) { - private boolean clipEdge(GeometryBuffer in, GeometryBuffer out, int edge) { + out.startPolygon(); + boolean outer = true; - out.startPolygon(); - boolean outer = true; + int pointPos = 0; - int pointPos = 0; + for (int indexPos = 0, n = in.index.length; indexPos < n; indexPos++) { + int len = in.index[indexPos]; + if (len < 0) + break; - for (int indexPos = 0, n = in.index.length; indexPos < n; indexPos++) { - int len = in.index[indexPos]; - if (len < 0) - break; + if (len == 0) { + out.startPolygon(); + outer = true; + continue; + } - if (len == 0) { - out.startPolygon(); - outer = true; - continue; - } + if (len < 6) { + pointPos += len; + continue; + } - if (len < 6) { - pointPos += len; - continue; - } + if (!outer) + out.startHole(); - if (!outer) - out.startHole(); + switch (edge) { + case LineClipper.LEFT: + clipRingLeft(indexPos, pointPos, in, out); + break; + case LineClipper.RIGHT: + clipRingRight(indexPos, pointPos, in, out); + break; + case LineClipper.TOP: + clipRingTop(indexPos, pointPos, in, out); + break; + case LineClipper.BOTTOM: + clipRingBottom(indexPos, pointPos, in, out); + break; + } - switch (edge) { - case LineClipper.LEFT: - clipRingLeft(indexPos, pointPos, in, out); - break; - case LineClipper.RIGHT: - clipRingRight(indexPos, pointPos, in, out); - break; - case LineClipper.TOP: - clipRingTop(indexPos, pointPos, in, out); - break; - case LineClipper.BOTTOM: - clipRingBottom(indexPos, pointPos, in, out); - break; - } + //if (out.index[i] < 6) { + // out.index[i] = 0; + // //if (out.indexPos > 0) + // // out.indexPos--; + // // TODO if outer skip holes + //} - //if (out.index[i] < 6) { - // out.index[i] = 0; - // //if (out.indexPos > 0) - // // out.indexPos--; - // // TODO if outer skip holes - //} + pointPos += len; - pointPos += len; + outer = false; + } + return true; + } - outer = false; - } - return true; - } + private void clipRingLeft(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { + int end = in.index[indexPos] + pointPos; + float px = in.points[end - 2]; + float py = in.points[end - 1]; - private void clipRingLeft(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { - int end = in.index[indexPos] + pointPos; - float px = in.points[end - 2]; - float py = in.points[end - 1]; - - for (int i = pointPos; i < end;) { - float cx = in.points[i++]; - float cy = in.points[i++]; - if (cx > xmin) { - /* current is inside */ - if (px > xmin) { - /* previous was inside */ - out.addPoint(cx, cy); - } else { + for (int i = pointPos; i < end; ) { + float cx = in.points[i++]; + float cy = in.points[i++]; + if (cx > xmin) { + /* current is inside */ + if (px > xmin) { + /* previous was inside */ + out.addPoint(cx, cy); + } else { /* previous was outside, add edge point */ - out.addPoint(xmin, py + (cy - py) * (xmin - px) / (cx - px)); - out.addPoint(cx, cy); - } - } else { - if (px > xmin) { + out.addPoint(xmin, py + (cy - py) * (xmin - px) / (cx - px)); + out.addPoint(cx, cy); + } + } else { + if (px > xmin) { /* previous was inside, add edge point */ - out.addPoint(xmin, py + (cy - py) * (xmin - px) / (cx - px)); - } + out.addPoint(xmin, py + (cy - py) * (xmin - px) / (cx - px)); + } /* else skip point */ - } - px = cx; - py = cy; - } - } + } + px = cx; + py = cy; + } + } - private void clipRingRight(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { - int len = in.index[indexPos] + pointPos; - float px = in.points[len - 2]; - float py = in.points[len - 1]; + private void clipRingRight(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { + int len = in.index[indexPos] + pointPos; + float px = in.points[len - 2]; + float py = in.points[len - 1]; - for (int i = pointPos; i < len;) { - float cx = in.points[i++]; - float cy = in.points[i++]; + for (int i = pointPos; i < len; ) { + float cx = in.points[i++]; + float cy = in.points[i++]; - if (cx < xmax) { - if (px < xmax) { - out.addPoint(cx, cy); - } else { - out.addPoint(xmax, py + (cy - py) * (xmax - px) / (cx - px)); - out.addPoint(cx, cy); - } - } else { - if (px < xmax) { - out.addPoint(xmax, py + (cy - py) * (xmax - px) / (cx - px)); - } - } - px = cx; - py = cy; - } - } + if (cx < xmax) { + if (px < xmax) { + out.addPoint(cx, cy); + } else { + out.addPoint(xmax, py + (cy - py) * (xmax - px) / (cx - px)); + out.addPoint(cx, cy); + } + } else { + if (px < xmax) { + out.addPoint(xmax, py + (cy - py) * (xmax - px) / (cx - px)); + } + } + px = cx; + py = cy; + } + } - private void clipRingTop(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { - int len = in.index[indexPos] + pointPos; - float px = in.points[len - 2]; - float py = in.points[len - 1]; + private void clipRingTop(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { + int len = in.index[indexPos] + pointPos; + float px = in.points[len - 2]; + float py = in.points[len - 1]; - for (int i = pointPos; i < len;) { - float cx = in.points[i++]; - float cy = in.points[i++]; + for (int i = pointPos; i < len; ) { + float cx = in.points[i++]; + float cy = in.points[i++]; - if (cy < ymax) { - if (py < ymax) { - out.addPoint(cx, cy); - } else { - out.addPoint(px + (cx - px) * (ymax - py) / (cy - py), ymax); - out.addPoint(cx, cy); - } - } else { - if (py < ymax) { - out.addPoint(px + (cx - px) * (ymax - py) / (cy - py), ymax); - } - } - px = cx; - py = cy; - } - } + if (cy < ymax) { + if (py < ymax) { + out.addPoint(cx, cy); + } else { + out.addPoint(px + (cx - px) * (ymax - py) / (cy - py), ymax); + out.addPoint(cx, cy); + } + } else { + if (py < ymax) { + out.addPoint(px + (cx - px) * (ymax - py) / (cy - py), ymax); + } + } + px = cx; + py = cy; + } + } - private void clipRingBottom(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { - int len = in.index[indexPos] + pointPos; - float px = in.points[len - 2]; - float py = in.points[len - 1]; + private void clipRingBottom(int indexPos, int pointPos, GeometryBuffer in, GeometryBuffer out) { + int len = in.index[indexPos] + pointPos; + float px = in.points[len - 2]; + float py = in.points[len - 1]; - for (int i = pointPos; i < len;) { - float cx = in.points[i++]; - float cy = in.points[i++]; - if (cy > ymin) { - if (py > ymin) { - out.addPoint(cx, cy); - } else { - out.addPoint(px + (cx - px) * (ymin - py) / (cy - py), ymin); - out.addPoint(cx, cy); - } - } else { - if (py > ymin) { - out.addPoint(px + (cx - px) * (ymin - py) / (cy - py), ymin); - } - } - px = cx; - py = cy; - } - } + for (int i = pointPos; i < len; ) { + float cx = in.points[i++]; + float cy = in.points[i++]; + if (cy > ymin) { + if (py > ymin) { + out.addPoint(cx, cy); + } else { + out.addPoint(px + (cx - px) * (ymin - py) / (cy - py), ymin); + out.addPoint(cx, cy); + } + } else { + if (py > ymin) { + out.addPoint(px + (cx - px) * (ymin - py) / (cy - py), ymin); + } + } + px = cx; + py = cy; + } + } } diff --git a/vtm/src/org/oscim/utils/math/Interpolation.java b/vtm/src/org/oscim/utils/math/Interpolation.java index 7faaf094..7a3a6ff0 100644 --- a/vtm/src/org/oscim/utils/math/Interpolation.java +++ b/vtm/src/org/oscim/utils/math/Interpolation.java @@ -1,13 +1,13 @@ /******************************************************************************* * Copyright 2011 Mario Zechner * Copyright 2011 Nathan Sweet - * + *

    * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

    + * http://www.apache.org/licenses/LICENSE-2.0 + *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,398 +23,402 @@ package org.oscim.utils.math; * interpolated value. */ public abstract class Interpolation { - /** @param a Alpha value between 0 and 1. */ - abstract public float apply(float a); + /** + * @param a Alpha value between 0 and 1. + */ + abstract public float apply(float a); - /** @param a Alpha value between 0 and 1. */ - public float apply(float start, float end, float a) { - return start + (end - start) * apply(a); - } + /** + * @param a Alpha value between 0 and 1. + */ + public float apply(float start, float end, float a) { + return start + (end - start) * apply(a); + } - static public final Interpolation linear = new Interpolation() { - @Override - public float apply(float a) { - return a; - } - }; + static public final Interpolation linear = new Interpolation() { + @Override + public float apply(float a) { + return a; + } + }; - static public final Interpolation fade = new Interpolation() { - @Override - public float apply(float a) { - return MathUtils.clamp(a * a * a * (a * (a * 6 - 15) + 10), 0, 1); - } - }; + static public final Interpolation fade = new Interpolation() { + @Override + public float apply(float a) { + return MathUtils.clamp(a * a * a * (a * (a * 6 - 15) + 10), 0, 1); + } + }; - static public final Pow pow2 = new Pow(2); - static public final PowIn pow2In = new PowIn(2); - static public final PowOut pow2Out = new PowOut(2); + static public final Pow pow2 = new Pow(2); + static public final PowIn pow2In = new PowIn(2); + static public final PowOut pow2Out = new PowOut(2); - static public final Pow pow3 = new Pow(3); - static public final PowIn pow3In = new PowIn(3); - static public final PowOut pow3Out = new PowOut(3); + static public final Pow pow3 = new Pow(3); + static public final PowIn pow3In = new PowIn(3); + static public final PowOut pow3Out = new PowOut(3); - static public final Pow pow4 = new Pow(4); - static public final PowIn pow4In = new PowIn(4); - static public final PowOut pow4Out = new PowOut(4); + static public final Pow pow4 = new Pow(4); + static public final PowIn pow4In = new PowIn(4); + static public final PowOut pow4Out = new PowOut(4); - static public final Pow pow5 = new Pow(5); - static public final PowIn pow5In = new PowIn(5); - static public final PowOut pow5Out = new PowOut(5); + static public final Pow pow5 = new Pow(5); + static public final PowIn pow5In = new PowIn(5); + static public final PowOut pow5Out = new PowOut(5); - static public final Interpolation sine = new Interpolation() { - @Override - public float apply(float a) { - return (1 - MathUtils.cos(a * MathUtils.PI)) / 2; - } - }; + static public final Interpolation sine = new Interpolation() { + @Override + public float apply(float a) { + return (1 - MathUtils.cos(a * MathUtils.PI)) / 2; + } + }; - static public final Interpolation sineIn = new Interpolation() { - @Override - public float apply(float a) { - return 1 - MathUtils.cos(a * MathUtils.PI / 2); - } - }; + static public final Interpolation sineIn = new Interpolation() { + @Override + public float apply(float a) { + return 1 - MathUtils.cos(a * MathUtils.PI / 2); + } + }; - static public final Interpolation sineOut = new Interpolation() { - @Override - public float apply(float a) { - return MathUtils.sin(a * MathUtils.PI / 2); - } - }; + static public final Interpolation sineOut = new Interpolation() { + @Override + public float apply(float a) { + return MathUtils.sin(a * MathUtils.PI / 2); + } + }; - static public final Interpolation exp10 = new Exp(2, 10); - static public final Interpolation exp10In = new ExpIn(2, 10); - static public final Interpolation exp10Out = new ExpOut(2, 10); + static public final Interpolation exp10 = new Exp(2, 10); + static public final Interpolation exp10In = new ExpIn(2, 10); + static public final Interpolation exp10Out = new ExpOut(2, 10); - static public final Interpolation exp5 = new Exp(2, 5); - static public final Interpolation exp5In = new ExpIn(2, 5); - static public final Interpolation exp5Out = new ExpOut(2, 5); + static public final Interpolation exp5 = new Exp(2, 5); + static public final Interpolation exp5In = new ExpIn(2, 5); + static public final Interpolation exp5Out = new ExpOut(2, 5); - static public final Interpolation circle = new Interpolation() { - @Override - public float apply(float a) { - if (a <= 0.5f) { - a *= 2; - return (1 - (float) Math.sqrt(1 - a * a)) / 2; - } - a--; - a *= 2; - return ((float) Math.sqrt(1 - a * a) + 1) / 2; - } - }; + static public final Interpolation circle = new Interpolation() { + @Override + public float apply(float a) { + if (a <= 0.5f) { + a *= 2; + return (1 - (float) Math.sqrt(1 - a * a)) / 2; + } + a--; + a *= 2; + return ((float) Math.sqrt(1 - a * a) + 1) / 2; + } + }; - static public final Interpolation circleIn = new Interpolation() { - @Override - public float apply(float a) { - return 1 - (float) Math.sqrt(1 - a * a); - } - }; + static public final Interpolation circleIn = new Interpolation() { + @Override + public float apply(float a) { + return 1 - (float) Math.sqrt(1 - a * a); + } + }; - static public final Interpolation circleOut = new Interpolation() { - @Override - public float apply(float a) { - a--; - return (float) Math.sqrt(1 - a * a); - } - }; + static public final Interpolation circleOut = new Interpolation() { + @Override + public float apply(float a) { + a--; + return (float) Math.sqrt(1 - a * a); + } + }; - static public final Elastic elastic = new Elastic(2, 10); - static public final Elastic elasticIn = new ElasticIn(2, 10); - static public final Elastic elasticOut = new ElasticOut(2, 10); + static public final Elastic elastic = new Elastic(2, 10); + static public final Elastic elasticIn = new ElasticIn(2, 10); + static public final Elastic elasticOut = new ElasticOut(2, 10); - static public final Interpolation swing = new Swing(1.5f); - static public final Interpolation swingIn = new SwingIn(2f); - static public final Interpolation swingOut = new SwingOut(2f); + static public final Interpolation swing = new Swing(1.5f); + static public final Interpolation swingIn = new SwingIn(2f); + static public final Interpolation swingOut = new SwingOut(2f); - static public final Interpolation bounce = new Bounce(4); - static public final Interpolation bounceIn = new BounceIn(4); - static public final Interpolation bounceOut = new BounceOut(4); + static public final Interpolation bounce = new Bounce(4); + static public final Interpolation bounceIn = new BounceIn(4); + static public final Interpolation bounceOut = new BounceOut(4); - // + // - static public class Pow extends Interpolation { - final int power; + static public class Pow extends Interpolation { + final int power; - public Pow(int power) { - this.power = power; - } + public Pow(int power) { + this.power = power; + } - @Override - public float apply(float a) { - if (a <= 0.5f) - return (float) Math.pow(a * 2, power) / 2; - return (float) Math.pow((a - 1) * 2, power) / (power % 2 == 0 ? -2 : 2) + 1; - } - } + @Override + public float apply(float a) { + if (a <= 0.5f) + return (float) Math.pow(a * 2, power) / 2; + return (float) Math.pow((a - 1) * 2, power) / (power % 2 == 0 ? -2 : 2) + 1; + } + } - static public class PowIn extends Pow { - public PowIn(int power) { - super(power); - } + static public class PowIn extends Pow { + public PowIn(int power) { + super(power); + } - @Override - public float apply(float a) { - return (float) Math.pow(a, power); - } - } + @Override + public float apply(float a) { + return (float) Math.pow(a, power); + } + } - static public class PowOut extends Pow { - public PowOut(int power) { - super(power); - } + static public class PowOut extends Pow { + public PowOut(int power) { + super(power); + } - @Override - public float apply(float a) { - return (float) Math.pow(a - 1, power) * (power % 2 == 0 ? -1 : 1) + 1; - } - } + @Override + public float apply(float a) { + return (float) Math.pow(a - 1, power) * (power % 2 == 0 ? -1 : 1) + 1; + } + } - // + // - static public class Exp extends Interpolation { - final float value, power, min, scale; + static public class Exp extends Interpolation { + final float value, power, min, scale; - public Exp(float value, float power) { - this.value = value; - this.power = power; - min = (float) Math.pow(value, -power); - scale = 1 / (1 - min); - } + public Exp(float value, float power) { + this.value = value; + this.power = power; + min = (float) Math.pow(value, -power); + scale = 1 / (1 - min); + } - @Override - public float apply(float a) { - if (a <= 0.5f) - return ((float) Math.pow(value, power * (a * 2 - 1)) - min) * scale / 2; - return (2 - ((float) Math.pow(value, -power * (a * 2 - 1)) - min) * scale) / 2; - } - } + @Override + public float apply(float a) { + if (a <= 0.5f) + return ((float) Math.pow(value, power * (a * 2 - 1)) - min) * scale / 2; + return (2 - ((float) Math.pow(value, -power * (a * 2 - 1)) - min) * scale) / 2; + } + } - static public class ExpIn extends Exp { - public ExpIn(float value, float power) { - super(value, power); - } + static public class ExpIn extends Exp { + public ExpIn(float value, float power) { + super(value, power); + } - @Override - public float apply(float a) { - return ((float) Math.pow(value, power * (a - 1)) - min) * scale; - } - } + @Override + public float apply(float a) { + return ((float) Math.pow(value, power * (a - 1)) - min) * scale; + } + } - static public class ExpOut extends Exp { - public ExpOut(float value, float power) { - super(value, power); - } + static public class ExpOut extends Exp { + public ExpOut(float value, float power) { + super(value, power); + } - @Override - public float apply(float a) { - return 1 - ((float) Math.pow(value, -power * a) - min) * scale; - } - } + @Override + public float apply(float a) { + return 1 - ((float) Math.pow(value, -power * a) - min) * scale; + } + } - // + // - static public class Elastic extends Interpolation { - final float value, power; + static public class Elastic extends Interpolation { + final float value, power; - public Elastic(float value, float power) { - this.value = value; - this.power = power; - } + public Elastic(float value, float power) { + this.value = value; + this.power = power; + } - @Override - public float apply(float a) { - if (a <= 0.5f) { - a *= 2; - return (float) Math.pow(value, power * (a - 1)) * MathUtils.sin(a * 20) * 1.0955f - / 2; - } - a = 1 - a; - a *= 2; - return 1 - (float) Math.pow(value, power * (a - 1)) * MathUtils.sin((a) * 20) * 1.0955f - / 2; - } - } + @Override + public float apply(float a) { + if (a <= 0.5f) { + a *= 2; + return (float) Math.pow(value, power * (a - 1)) * MathUtils.sin(a * 20) * 1.0955f + / 2; + } + a = 1 - a; + a *= 2; + return 1 - (float) Math.pow(value, power * (a - 1)) * MathUtils.sin((a) * 20) * 1.0955f + / 2; + } + } - static public class ElasticIn extends Elastic { - public ElasticIn(float value, float power) { - super(value, power); - } + static public class ElasticIn extends Elastic { + public ElasticIn(float value, float power) { + super(value, power); + } - @Override - public float apply(float a) { - return (float) Math.pow(value, power * (a - 1)) * MathUtils.sin(a * 20) * 1.0955f; - } - } + @Override + public float apply(float a) { + return (float) Math.pow(value, power * (a - 1)) * MathUtils.sin(a * 20) * 1.0955f; + } + } - static public class ElasticOut extends Elastic { - public ElasticOut(float value, float power) { - super(value, power); - } + static public class ElasticOut extends Elastic { + public ElasticOut(float value, float power) { + super(value, power); + } - @Override - public float apply(float a) { - a = 1 - a; - return (1 - (float) Math.pow(value, power * (a - 1)) * MathUtils.sin(a * 20) * 1.0955f); - } - } + @Override + public float apply(float a) { + a = 1 - a; + return (1 - (float) Math.pow(value, power * (a - 1)) * MathUtils.sin(a * 20) * 1.0955f); + } + } - // + // - static public class Bounce extends BounceOut { - public Bounce(float[] widths, float[] heights) { - super(widths, heights); - } + static public class Bounce extends BounceOut { + public Bounce(float[] widths, float[] heights) { + super(widths, heights); + } - public Bounce(int bounces) { - super(bounces); - } + public Bounce(int bounces) { + super(bounces); + } - private float out(float a) { - float test = a + widths[0] / 2; - if (test < widths[0]) - return test / (widths[0] / 2) - 1; - return super.apply(a); - } + private float out(float a) { + float test = a + widths[0] / 2; + if (test < widths[0]) + return test / (widths[0] / 2) - 1; + return super.apply(a); + } - @Override - public float apply(float a) { - if (a <= 0.5f) - return (1 - out(1 - a * 2)) / 2; - return out(a * 2 - 1) / 2 + 0.5f; - } - } + @Override + public float apply(float a) { + if (a <= 0.5f) + return (1 - out(1 - a * 2)) / 2; + return out(a * 2 - 1) / 2 + 0.5f; + } + } - static public class BounceOut extends Interpolation { - final float[] widths, heights; + static public class BounceOut extends Interpolation { + final float[] widths, heights; - public BounceOut(float[] widths, float[] heights) { - if (widths.length != heights.length) - throw new IllegalArgumentException("Must be the same number of widths and heights."); - this.widths = widths; - this.heights = heights; - } + public BounceOut(float[] widths, float[] heights) { + if (widths.length != heights.length) + throw new IllegalArgumentException("Must be the same number of widths and heights."); + this.widths = widths; + this.heights = heights; + } - public BounceOut(int bounces) { - if (bounces < 2 || bounces > 5) - throw new IllegalArgumentException("bounces cannot be < 2 or > 5: " + bounces); - widths = new float[bounces]; - heights = new float[bounces]; - heights[0] = 1; - switch (bounces) { - case 2: - widths[0] = 0.6f; - widths[1] = 0.4f; - heights[1] = 0.33f; - break; - case 3: - widths[0] = 0.4f; - widths[1] = 0.4f; - widths[2] = 0.2f; - heights[1] = 0.33f; - heights[2] = 0.1f; - break; - case 4: - widths[0] = 0.34f; - widths[1] = 0.34f; - widths[2] = 0.2f; - widths[3] = 0.15f; - heights[1] = 0.26f; - heights[2] = 0.11f; - heights[3] = 0.03f; - break; - case 5: - widths[0] = 0.3f; - widths[1] = 0.3f; - widths[2] = 0.2f; - widths[3] = 0.1f; - widths[4] = 0.1f; - heights[1] = 0.45f; - heights[2] = 0.3f; - heights[3] = 0.15f; - heights[4] = 0.06f; - break; - } - widths[0] *= 2; - } + public BounceOut(int bounces) { + if (bounces < 2 || bounces > 5) + throw new IllegalArgumentException("bounces cannot be < 2 or > 5: " + bounces); + widths = new float[bounces]; + heights = new float[bounces]; + heights[0] = 1; + switch (bounces) { + case 2: + widths[0] = 0.6f; + widths[1] = 0.4f; + heights[1] = 0.33f; + break; + case 3: + widths[0] = 0.4f; + widths[1] = 0.4f; + widths[2] = 0.2f; + heights[1] = 0.33f; + heights[2] = 0.1f; + break; + case 4: + widths[0] = 0.34f; + widths[1] = 0.34f; + widths[2] = 0.2f; + widths[3] = 0.15f; + heights[1] = 0.26f; + heights[2] = 0.11f; + heights[3] = 0.03f; + break; + case 5: + widths[0] = 0.3f; + widths[1] = 0.3f; + widths[2] = 0.2f; + widths[3] = 0.1f; + widths[4] = 0.1f; + heights[1] = 0.45f; + heights[2] = 0.3f; + heights[3] = 0.15f; + heights[4] = 0.06f; + break; + } + widths[0] *= 2; + } - @Override - public float apply(float a) { - a += widths[0] / 2; - float width = 0, height = 0; - for (int i = 0, n = widths.length; i < n; i++) { - width = widths[i]; - if (a <= width) { - height = heights[i]; - break; - } - a -= width; - } - a /= width; - float z = 4 / width * height * a; - return 1 - (z - z * a) * width; - } - } + @Override + public float apply(float a) { + a += widths[0] / 2; + float width = 0, height = 0; + for (int i = 0, n = widths.length; i < n; i++) { + width = widths[i]; + if (a <= width) { + height = heights[i]; + break; + } + a -= width; + } + a /= width; + float z = 4 / width * height * a; + return 1 - (z - z * a) * width; + } + } - static public class BounceIn extends BounceOut { - public BounceIn(float[] widths, float[] heights) { - super(widths, heights); - } + static public class BounceIn extends BounceOut { + public BounceIn(float[] widths, float[] heights) { + super(widths, heights); + } - public BounceIn(int bounces) { - super(bounces); - } + public BounceIn(int bounces) { + super(bounces); + } - @Override - public float apply(float a) { - return 1 - super.apply(1 - a); - } - } + @Override + public float apply(float a) { + return 1 - super.apply(1 - a); + } + } - // + // - static public class Swing extends Interpolation { - private final float scale; + static public class Swing extends Interpolation { + private final float scale; - public Swing(float scale) { - this.scale = scale * 2; - } + public Swing(float scale) { + this.scale = scale * 2; + } - @Override - public float apply(float a) { - if (a <= 0.5f) { - a *= 2; - return a * a * ((scale + 1) * a - scale) / 2; - } - a--; - a *= 2; - return a * a * ((scale + 1) * a + scale) / 2 + 1; - } - } + @Override + public float apply(float a) { + if (a <= 0.5f) { + a *= 2; + return a * a * ((scale + 1) * a - scale) / 2; + } + a--; + a *= 2; + return a * a * ((scale + 1) * a + scale) / 2 + 1; + } + } - static public class SwingOut extends Interpolation { - private final float scale; + static public class SwingOut extends Interpolation { + private final float scale; - public SwingOut(float scale) { - this.scale = scale; - } + public SwingOut(float scale) { + this.scale = scale; + } - @Override - public float apply(float a) { - a--; - return a * a * ((scale + 1) * a + scale) + 1; - } - } + @Override + public float apply(float a) { + a--; + return a * a * ((scale + 1) * a + scale) + 1; + } + } - static public class SwingIn extends Interpolation { - private final float scale; + static public class SwingIn extends Interpolation { + private final float scale; - public SwingIn(float scale) { - this.scale = scale; - } + public SwingIn(float scale) { + this.scale = scale; + } - @Override - public float apply(float a) { - return a * a * ((scale + 1) * a - scale); - } - } + @Override + public float apply(float a) { + return a * a * ((scale + 1) * a - scale); + } + } } diff --git a/vtm/src/org/oscim/utils/math/MathUtils.java b/vtm/src/org/oscim/utils/math/MathUtils.java index 4d1dd1fd..c50b450d 100644 --- a/vtm/src/org/oscim/utils/math/MathUtils.java +++ b/vtm/src/org/oscim/utils/math/MathUtils.java @@ -1,13 +1,13 @@ /******************************************************************************* * Copyright 2011 Mario Zechner * Copyright 2011 Nathan Sweet - * + *

    * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

    + * http://www.apache.org/licenses/LICENSE-2.0 + *

    * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,264 +21,285 @@ import java.util.Random; /** * Utility and fast math functions. - *

    + *

    * Thanks to Riven on JavaGaming.org for the basis of sin/cos/atan2/floor/ceil. - * + * * @author Nathan Sweet */ public class MathUtils { - static public final float nanoToSec = 1 / 1000000000f; + static public final float nanoToSec = 1 / 1000000000f; - static public final float PI = 3.1415927f; - public static final float PI2 = PI * 2; + static public final float PI = 3.1415927f; + public static final float PI2 = PI * 2; - static private final int SIN_BITS = 13; // Adjust for accuracy. - static private final int SIN_MASK = ~(-1 << SIN_BITS); - static private final int SIN_COUNT = SIN_MASK + 1; + static private final int SIN_BITS = 13; // Adjust for accuracy. + static private final int SIN_MASK = ~(-1 << SIN_BITS); + static private final int SIN_COUNT = SIN_MASK + 1; - static private final float radFull = PI * 2; - static private final float degFull = 360; - static private final float radToIndex = SIN_COUNT / radFull; - static private final float degToIndex = SIN_COUNT / degFull; + static private final float radFull = PI * 2; + static private final float degFull = 360; + static private final float radToIndex = SIN_COUNT / radFull; + static private final float degToIndex = SIN_COUNT / degFull; - static public final float radiansToDegrees = 180f / PI; - static public final float radDeg = radiansToDegrees; - static public final float degreesToRadians = PI / 180; - static public final float degRad = degreesToRadians; + static public final float radiansToDegrees = 180f / PI; + static public final float radDeg = radiansToDegrees; + static public final float degreesToRadians = PI / 180; + static public final float degRad = degreesToRadians; - static private class Sin { - static final float[] table = new float[SIN_COUNT]; - static { - for (int i = 0; i < SIN_COUNT; i++) - table[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull); - for (int i = 0; i < 360; i += 90) - table[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * degreesToRadians); - } - } + static private class Sin { + static final float[] table = new float[SIN_COUNT]; - static private class Cos { - static final float[] table = new float[SIN_COUNT]; - static { - for (int i = 0; i < SIN_COUNT; i++) - table[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull); - for (int i = 0; i < 360; i += 90) - table[(int) (i * degToIndex) & SIN_MASK] = (float) Math.cos(i * degreesToRadians); - } - } + static { + for (int i = 0; i < SIN_COUNT; i++) + table[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull); + for (int i = 0; i < 360; i += 90) + table[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * degreesToRadians); + } + } - /** Returns the sine in radians. */ - static public final float sin(float radians) { - return Sin.table[(int) (radians * radToIndex) & SIN_MASK]; - } + static private class Cos { + static final float[] table = new float[SIN_COUNT]; - /** Returns the cosine in radians. */ - static public final float cos(float radians) { - return Cos.table[(int) (radians * radToIndex) & SIN_MASK]; - } + static { + for (int i = 0; i < SIN_COUNT; i++) + table[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull); + for (int i = 0; i < 360; i += 90) + table[(int) (i * degToIndex) & SIN_MASK] = (float) Math.cos(i * degreesToRadians); + } + } - /** Returns the sine in radians. */ - static public final float sinDeg(float degrees) { - return Sin.table[(int) (degrees * degToIndex) & SIN_MASK]; - } + /** + * Returns the sine in radians. + */ + static public final float sin(float radians) { + return Sin.table[(int) (radians * radToIndex) & SIN_MASK]; + } - /** Returns the cosine in radians. */ - static public final float cosDeg(float degrees) { - return Cos.table[(int) (degrees * degToIndex) & SIN_MASK]; - } + /** + * Returns the cosine in radians. + */ + static public final float cos(float radians) { + return Cos.table[(int) (radians * radToIndex) & SIN_MASK]; + } - // --- + /** + * Returns the sine in radians. + */ + static public final float sinDeg(float degrees) { + return Sin.table[(int) (degrees * degToIndex) & SIN_MASK]; + } - static private final int ATAN2_BITS = 7; // Adjust for accuracy. - static private final int ATAN2_BITS2 = ATAN2_BITS << 1; - static private final int ATAN2_MASK = ~(-1 << ATAN2_BITS2); - static private final int ATAN2_COUNT = ATAN2_MASK + 1; - static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT); - static private final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1); + /** + * Returns the cosine in radians. + */ + static public final float cosDeg(float degrees) { + return Cos.table[(int) (degrees * degToIndex) & SIN_MASK]; + } - static private class Atan2 { - static final float[] table = new float[ATAN2_COUNT]; - static { - for (int i = 0; i < ATAN2_DIM; i++) { - for (int j = 0; j < ATAN2_DIM; j++) { - float x0 = (float) i / ATAN2_DIM; - float y0 = (float) j / ATAN2_DIM; - table[j * ATAN2_DIM + i] = (float) Math.atan2(y0, x0); - } - } - } - } + // --- - /** Returns atan2 in radians from a lookup table. */ - static public final float atan2(float y, float x) { - float add, mul; - if (x < 0) { - if (y < 0) { - y = -y; - mul = 1; - } else - mul = -1; - x = -x; - add = -PI; - } else { - if (y < 0) { - y = -y; - mul = -1; - } else - mul = 1; - add = 0; - } - float invDiv = 1 / ((x < y ? y : x) * INV_ATAN2_DIM_MINUS_1); - int xi = (int) (x * invDiv); - int yi = (int) (y * invDiv); - return (Atan2.table[yi * ATAN2_DIM + xi] + add) * mul; - } + static private final int ATAN2_BITS = 7; // Adjust for accuracy. + static private final int ATAN2_BITS2 = ATAN2_BITS << 1; + static private final int ATAN2_MASK = ~(-1 << ATAN2_BITS2); + static private final int ATAN2_COUNT = ATAN2_MASK + 1; + static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT); + static private final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1); - // --- + static private class Atan2 { + static final float[] table = new float[ATAN2_COUNT]; - static public Random random = new Random(); + static { + for (int i = 0; i < ATAN2_DIM; i++) { + for (int j = 0; j < ATAN2_DIM; j++) { + float x0 = (float) i / ATAN2_DIM; + float y0 = (float) j / ATAN2_DIM; + table[j * ATAN2_DIM + i] = (float) Math.atan2(y0, x0); + } + } + } + } - /** - * Returns a random number between 0 (inclusive) and the specified value - * (inclusive). - */ - static public final int random(int range) { - return random.nextInt(range + 1); - } + /** + * Returns atan2 in radians from a lookup table. + */ + static public final float atan2(float y, float x) { + float add, mul; + if (x < 0) { + if (y < 0) { + y = -y; + mul = 1; + } else + mul = -1; + x = -x; + add = -PI; + } else { + if (y < 0) { + y = -y; + mul = -1; + } else + mul = 1; + add = 0; + } + float invDiv = 1 / ((x < y ? y : x) * INV_ATAN2_DIM_MINUS_1); + int xi = (int) (x * invDiv); + int yi = (int) (y * invDiv); + return (Atan2.table[yi * ATAN2_DIM + xi] + add) * mul; + } - /** Returns a random number between start (inclusive) and end (inclusive). */ - static public final int random(int start, int end) { - return start + random.nextInt(end - start + 1); - } + // --- - /** Returns a random boolean value. */ - static public final boolean randomBoolean() { - return random.nextBoolean(); - } + static public Random random = new Random(); - /** Returns random number between 0.0 (inclusive) and 1.0 (exclusive). */ - static public final float random() { - return random.nextFloat(); - } + /** + * Returns a random number between 0 (inclusive) and the specified value + * (inclusive). + */ + static public final int random(int range) { + return random.nextInt(range + 1); + } - /** - * Returns a random number between 0 (inclusive) and the specified value - * (exclusive). - */ - static public final float random(float range) { - return random.nextFloat() * range; - } + /** + * Returns a random number between start (inclusive) and end (inclusive). + */ + static public final int random(int start, int end) { + return start + random.nextInt(end - start + 1); + } - /** Returns a random number between start (inclusive) and end (exclusive). */ - static public final float random(float start, float end) { - return start + random.nextFloat() * (end - start); - } + /** + * Returns a random boolean value. + */ + static public final boolean randomBoolean() { + return random.nextBoolean(); + } - // --- + /** + * Returns random number between 0.0 (inclusive) and 1.0 (exclusive). + */ + static public final float random() { + return random.nextFloat(); + } - /** - * Returns the next power of two. Returns the specified value if the value - * is already a power of two. - */ - static public int nextPowerOfTwo(int value) { - if (value == 0) - return 1; - value--; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - return value + 1; - } + /** + * Returns a random number between 0 (inclusive) and the specified value + * (exclusive). + */ + static public final float random(float range) { + return random.nextFloat() * range; + } - static public boolean isPowerOfTwo(int value) { - return value != 0 && (value & value - 1) == 0; - } + /** + * Returns a random number between start (inclusive) and end (exclusive). + */ + static public final float random(float start, float end) { + return start + random.nextFloat() * (end - start); + } - // --- + // --- - static public int clamp(int value, int min, int max) { - if (value < min) - return min; - if (value > max) - return max; - return value; - } + /** + * Returns the next power of two. Returns the specified value if the value + * is already a power of two. + */ + static public int nextPowerOfTwo(int value) { + if (value == 0) + return 1; + value--; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + return value + 1; + } - static public short clamp(short value, short min, short max) { - if (value < min) - return min; - if (value > max) - return max; - return value; - } + static public boolean isPowerOfTwo(int value) { + return value != 0 && (value & value - 1) == 0; + } - static public float clamp(float value, float min, float max) { - if (value < min) - return min; - if (value > max) - return max; - return value; - } + // --- - // --- + static public int clamp(int value, int min, int max) { + if (value < min) + return min; + if (value > max) + return max; + return value; + } - static private final int BIG_ENOUGH_INT = 16 * 1024; - static private final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT; - static private final double CEIL = 0.9999999; - static private final double BIG_ENOUGH_CEIL = Double.longBitsToDouble(Double.doubleToLongBits(BIG_ENOUGH_INT + 1) - 1); - static private final double BIG_ENOUGH_ROUND = BIG_ENOUGH_INT + 0.5f; + static public short clamp(short value, short min, short max) { + if (value < min) + return min; + if (value > max) + return max; + return value; + } - /** - * Returns the largest integer less than or equal to the specified float. - * This method will only properly floor floats from - * -(2^14) to (Float.MAX_VALUE - 2^14). - */ - static public int floor(float x) { - return (int) (x + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; - } + static public float clamp(float value, float min, float max) { + if (value < min) + return min; + if (value > max) + return max; + return value; + } - /** - * Returns the largest integer less than or equal to the specified float. - * This method will only properly floor floats that are - * positive. Note this method simply casts the float to int. - */ - static public int floorPositive(float x) { - return (int) x; - } + // --- - /** - * Returns the smallest integer greater than or equal to the specified - * float. This method will only properly ceil floats from - * -(2^14) to (Float.MAX_VALUE - 2^14). - */ - static public int ceil(float x) { - return (int) (x + BIG_ENOUGH_CEIL) - BIG_ENOUGH_INT; - } + static private final int BIG_ENOUGH_INT = 16 * 1024; + static private final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT; + static private final double CEIL = 0.9999999; + static private final double BIG_ENOUGH_CEIL = Double.longBitsToDouble(Double.doubleToLongBits(BIG_ENOUGH_INT + 1) - 1); + static private final double BIG_ENOUGH_ROUND = BIG_ENOUGH_INT + 0.5f; - /** - * Returns the smallest integer greater than or equal to the specified - * float. This method will only properly ceil floats that - * are positive. - */ - static public int ceilPositive(float x) { - return (int) (x + CEIL); - } + /** + * Returns the largest integer less than or equal to the specified float. + * This method will only properly floor floats from + * -(2^14) to (Float.MAX_VALUE - 2^14). + */ + static public int floor(float x) { + return (int) (x + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; + } - /** - * Returns the closest integer to the specified float. This method will only - * properly round floats from -(2^14) to - * (Float.MAX_VALUE - 2^14). - */ - static public int round(float x) { - return (int) (x + BIG_ENOUGH_ROUND) - BIG_ENOUGH_INT; - } + /** + * Returns the largest integer less than or equal to the specified float. + * This method will only properly floor floats that are + * positive. Note this method simply casts the float to int. + */ + static public int floorPositive(float x) { + return (int) x; + } - /** - * Returns the closest integer to the specified float. This method will only - * properly round floats that are positive. - */ - static public int roundPositive(float x) { - return (int) (x + 0.5f); - } + /** + * Returns the smallest integer greater than or equal to the specified + * float. This method will only properly ceil floats from + * -(2^14) to (Float.MAX_VALUE - 2^14). + */ + static public int ceil(float x) { + return (int) (x + BIG_ENOUGH_CEIL) - BIG_ENOUGH_INT; + } + + /** + * Returns the smallest integer greater than or equal to the specified + * float. This method will only properly ceil floats that + * are positive. + */ + static public int ceilPositive(float x) { + return (int) (x + CEIL); + } + + /** + * Returns the closest integer to the specified float. This method will only + * properly round floats from -(2^14) to + * (Float.MAX_VALUE - 2^14). + */ + static public int round(float x) { + return (int) (x + BIG_ENOUGH_ROUND) - BIG_ENOUGH_INT; + } + + /** + * Returns the closest integer to the specified float. This method will only + * properly round floats that are positive. + */ + static public int roundPositive(float x) { + return (int) (x + 0.5f); + } } diff --git a/vtm/src/org/oscim/utils/math/Vec3.java b/vtm/src/org/oscim/utils/math/Vec3.java index 0034568c..07016241 100644 --- a/vtm/src/org/oscim/utils/math/Vec3.java +++ b/vtm/src/org/oscim/utils/math/Vec3.java @@ -1,20 +1,20 @@ package org.oscim.utils.math; public class Vec3 { - public double x, y, z; + public double x, y, z; - public Vec3() { - } + public Vec3() { + } - public Vec3(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public Vec3(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public void set(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + public void set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } } diff --git a/vtm/src/org/oscim/utils/pool/Inlist.java b/vtm/src/org/oscim/utils/pool/Inlist.java index cc7ad07a..dcfb3fae 100644 --- a/vtm/src/org/oscim/utils/pool/Inlist.java +++ b/vtm/src/org/oscim/utils/pool/Inlist.java @@ -24,341 +24,351 @@ import javax.annotation.CheckReturnValue; * Utility class for making poolable objects. * Instead of using an additional list to hold pool items just extend this * class. - * + *

    * Also handy for objects that exist in only *one list* at a time, if you * are *REALLY* sure about it. Better do not use it! :) */ public class Inlist> { - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static class List> implements Iterable, Iterator { - private Inlist head; - private Inlist cur; + @SuppressWarnings({"rawtypes", "unchecked"}) + public static class List> implements Iterable, Iterator { + private Inlist head; + private Inlist cur; - /** - * Insert single item at start of list. - * item.next must be null. - */ - public void push(T it) { - if (it.next != null) - throw new IllegalArgumentException("item.next must be null"); + /** + * Insert single item at start of list. + * item.next must be null. + */ + public void push(T it) { + if (it.next != null) + throw new IllegalArgumentException("item.next must be null"); - ((Inlist) it).next = head; - head = it; - } + ((Inlist) it).next = head; + head = it; + } - /** - * Insert item at start of list. - */ - public T pop() { - if (head == null) - return null; + /** + * Insert item at start of list. + */ + public T pop() { + if (head == null) + return null; - Inlist it = head; - head = it.next; - it.next = null; - return (T) it; - } + Inlist it = head; + head = it.next; + it.next = null; + return (T) it; + } - /** - * Reverse list. - */ - public void reverse() { - Inlist tmp; - Inlist itr = head; - head = null; + /** + * Reverse list. + */ + public void reverse() { + Inlist tmp; + Inlist itr = head; + head = null; - while (itr != null) { - /* keep next */ - tmp = itr.next; + while (itr != null) { + /* keep next */ + tmp = itr.next; /* push itr onto new list */ - itr.next = head; - head = itr; + itr.next = head; + head = itr; - itr = tmp; - } - } + itr = tmp; + } + } - /** - * Append item, O(n) - use push() and - * reverse() to iterate in insertion order! - */ - public void append(T it) { - head = Inlist.appendItem(head, it); - } + /** + * Append item, O(n) - use push() and + * reverse() to iterate in insertion order! + */ + public void append(T it) { + head = Inlist.appendItem(head, it); + } - /** - * Append Inlist. - */ - public void appendList(T list) { - head = Inlist.appendList(head, list); - } + /** + * Append Inlist. + */ + public void appendList(T list) { + head = Inlist.appendList(head, list); + } - /** - * Remove item from list. - */ - public void remove(T it) { - cur = null; - head = Inlist.remove(head, it); - } + /** + * Remove item from list. + */ + public void remove(T it) { + cur = null; + head = Inlist.remove(head, it); + } - /** - * Clear list. - * - * @return head of list - */ - public T clear() { - Inlist ret = head; - head = null; - cur = null; - return (T) ret; - } + /** + * Clear list. + * + * @return head of list + */ + public T clear() { + Inlist ret = head; + head = null; + cur = null; + return (T) ret; + } - /** @return first node in list */ - public T head() { - return (T) head; - } + /** + * @return first node in list + */ + public T head() { + return (T) head; + } - /** Iterator: Has next item */ - @Override - public boolean hasNext() { - return cur != null; - } + /** + * Iterator: Has next item + */ + @Override + public boolean hasNext() { + return cur != null; + } - /** Iterator: Get next item */ - @Override - public T next() { - if (cur == null) - throw new IllegalStateException(); + /** + * Iterator: Get next item + */ + @Override + public T next() { + if (cur == null) + throw new IllegalStateException(); - Inlist tmp = cur; - cur = cur.next; - return (T) tmp; - } + Inlist tmp = cur; + cur = cur.next; + return (T) tmp; + } - /** Iterator: Remove current item */ - @Override - public void remove() { - /* iterator is at first position */ - if (head.next == cur) { - head = head.next; - return; - } + /** + * Iterator: Remove current item + */ + @Override + public void remove() { + /* iterator is at first position */ + if (head.next == cur) { + head = head.next; + return; + } - Inlist prev = head; - while (prev.next.next != cur) - prev = prev.next; + Inlist prev = head; + while (prev.next.next != cur) + prev = prev.next; - prev.next = cur; - } + prev.next = cur; + } - /** NB: Only one iterator at a time possible! */ - @Override - public Iterator iterator() { - cur = head; - return this; - } + /** + * NB: Only one iterator at a time possible! + */ + @Override + public Iterator iterator() { + cur = head; + return this; + } - public int size() { - return Inlist.size(head); - } - } + public int size() { + return Inlist.size(head); + } + } - public T next; + public T next; - public T next() { - return next; - } + public T next() { + return next; + } - /** - * Push 'item' onto 'list'. - * - * @param list the list - * @param item the item - * @return the new head of 'list' (item) - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @CheckReturnValue - public static > T push(T list, T item) { - if (item.next != null) - throw new IllegalArgumentException("'item' is a list"); + /** + * Push 'item' onto 'list'. + * + * @param list the list + * @param item the item + * @return the new head of 'list' (item) + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + @CheckReturnValue + public static > T push(T list, T item) { + if (item.next != null) + throw new IllegalArgumentException("'item' is a list"); - ((Inlist) (item)).next = list; - return item; - } + ((Inlist) (item)).next = list; + return item; + } - /** - * Get size of 'list'. - * - * @param list the list - * @return the number of items in 'list' - */ - public static > int size(T list) { - int count = 0; - for (Inlist l = list; l != null; l = l.next) - count++; - return count; - } + /** + * Get size of 'list'. + * + * @param list the list + * @return the number of items in 'list' + */ + public static > int size(T list) { + int count = 0; + for (Inlist l = list; l != null; l = l.next) + count++; + return count; + } - /** - * Removes the 'item' from 'list'. - * - * @param list the list - * @param item the item - * @return the new head of 'list' - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @CheckReturnValue - public static > T remove(T list, T item) { - if (item == list) { - Inlist head = item.next; - item.next = null; - return (T) head; - } + /** + * Removes the 'item' from 'list'. + * + * @param list the list + * @param item the item + * @return the new head of 'list' + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + @CheckReturnValue + public static > T remove(T list, T item) { + if (item == list) { + Inlist head = item.next; + item.next = null; + return (T) head; + } - for (Inlist prev = list, it = list.next; it != null; it = it.next) { - if (it == item) { - prev.next = item.next; - item.next = null; - return list; - } - prev = it; - } + for (Inlist prev = list, it = list.next; it != null; it = it.next) { + if (it == item) { + prev.next = item.next; + item.next = null; + return list; + } + prev = it; + } - return list; - } + return list; + } - /** - * Gets the 'item' with index 'i'. - * - * @param list the list - * @param i the index - * @return the item or null - */ - @SuppressWarnings({ "unchecked" }) - @CheckReturnValue - public static > T get(T list, int i) { - if (i < 0) - return null; + /** + * Gets the 'item' with index 'i'. + * + * @param list the list + * @param i the index + * @return the item or null + */ + @SuppressWarnings({"unchecked"}) + @CheckReturnValue + public static > T get(T list, int i) { + if (i < 0) + return null; - while (--i > 0 && list != null) - list = (T) list.next; + while (--i > 0 && list != null) + list = (T) list.next; - if (i == 0) - return list; + if (i == 0) + return list; - return null; - } + return null; + } - /** - * Append 'item' to 'list'. 'item' may not be in another list, - * i.e. item.next must be null - * - * @param list the list - * @param item the item - * @return the new head of 'list' - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @CheckReturnValue - public static > T appendItem(T list, T item) { + /** + * Append 'item' to 'list'. 'item' may not be in another list, + * i.e. item.next must be null + * + * @param list the list + * @param item the item + * @return the new head of 'list' + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + @CheckReturnValue + public static > T appendItem(T list, T item) { - if (item.next != null) - throw new IllegalArgumentException("'item' is list"); + if (item.next != null) + throw new IllegalArgumentException("'item' is list"); - if (list == null) - return item; + if (list == null) + return item; - Inlist it = list; - while (it.next != null) - it = it.next; + Inlist it = list; + while (it.next != null) + it = it.next; - ((Inlist) it).next = item; + ((Inlist) it).next = item; - return list; - } + return list; + } - /** - * Append list 'other' to 'list'. - * - * @param list the list - * @param other the other - * @return the head of 'list' - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @CheckReturnValue - public static T appendList(T list, T other) { + /** + * Append list 'other' to 'list'. + * + * @param list the list + * @param other the other + * @return the head of 'list' + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + @CheckReturnValue + public static T appendList(T list, T other) { - if (list == null) - return other; + if (list == null) + return other; - if (other == null) - return list; + if (other == null) + return list; - for (Inlist it = list;; it = it.next) { - if (it.next == null) { - ((Inlist) it).next = other; - break; - } - //else if (it.next == other) { - // throw new IllegalArgumentException("'other' already in 'list'"); - //} - } + for (Inlist it = list; ; it = it.next) { + if (it.next == null) { + ((Inlist) it).next = other; + break; + } + //else if (it.next == other) { + // throw new IllegalArgumentException("'other' already in 'list'"); + //} + } - return list; - } + return list; + } - /** - * Get last item in from list. - * - * @param list the list - * @return the last item - */ - @SuppressWarnings("unchecked") - @CheckReturnValue - public static > T last(T list) { - while (list != null) { - if (list.next == null) - return list; - list = (T) list.next; - } - return null; - } + /** + * Get last item in from list. + * + * @param list the list + * @return the last item + */ + @SuppressWarnings("unchecked") + @CheckReturnValue + public static > T last(T list) { + while (list != null) { + if (list.next == null) + return list; + list = (T) list.next; + } + return null; + } - /** - * Prepend 'item' relative to 'other'. - * - * @param list the list - * @param item the item - * @param other the other list - * @return the new head of list - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @CheckReturnValue - public static > T prependRelative(T list, T item, T other) { + /** + * Prepend 'item' relative to 'other'. + * + * @param list the list + * @param item the item + * @param other the other list + * @return the new head of list + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + @CheckReturnValue + public static > T prependRelative(T list, T item, T other) { - if (item.next != null) - throw new IllegalArgumentException("'item' is list"); + if (item.next != null) + throw new IllegalArgumentException("'item' is list"); - if (list == null) - throw new IllegalArgumentException("'list' is null"); + if (list == null) + throw new IllegalArgumentException("'list' is null"); - if (list == other) { - ((Inlist) item).next = list; - return item; - } + if (list == other) { + ((Inlist) item).next = list; + return item; + } - T it = list; + T it = list; - while (it != null && it.next != other) - it = (T) it.next; + while (it != null && it.next != other) + it = (T) it.next; - if (it == null) - throw new IllegalArgumentException("'other' not in 'list'"); + if (it == null) + throw new IllegalArgumentException("'other' not in 'list'"); - ((Inlist) item).next = it.next; - ((Inlist) it).next = item; + ((Inlist) item).next = it.next; + ((Inlist) it).next = item; - return list; - } + return list; + } } diff --git a/vtm/src/org/oscim/utils/pool/LList.java b/vtm/src/org/oscim/utils/pool/LList.java index 510a1e2e..94ead84a 100644 --- a/vtm/src/org/oscim/utils/pool/LList.java +++ b/vtm/src/org/oscim/utils/pool/LList.java @@ -17,37 +17,37 @@ package org.oscim.utils.pool; public class LList extends Inlist> { - public LList(T l) { - data = l; - } + public LList(T l) { + data = l; + } - public final T data; + public final T data; - public static , T> LList find(LList list, T item) { - for (LList l = list; l != null; l = l.next) - if (l.data == item) - return l; + public static , T> LList find(LList list, T item) { + for (LList l = list; l != null; l = l.next) + if (l.data == item) + return l; - return null; - } + return null; + } - public static , T> LList remove(LList list, T item) { - if (list.data == item) - return list.next; + public static , T> LList remove(LList list, T item) { + if (list.data == item) + return list.next; - LList prev = list; - for (LList l = list.next; l != null; l = l.next) - if (l.data == item) { - prev.next = l.next; - break; - } + LList prev = list; + for (LList l = list.next; l != null; l = l.next) + if (l.data == item) { + prev.next = l.next; + break; + } - return list; - } + return list; + } - public static > LList push(LList list, T item) { - item.next = list; - return item; - } + public static > LList push(LList list, T item) { + item.next = list; + return item; + } } diff --git a/vtm/src/org/oscim/utils/pool/Pool.java b/vtm/src/org/oscim/utils/pool/Pool.java index 7a9a529b..8022836f 100644 --- a/vtm/src/org/oscim/utils/pool/Pool.java +++ b/vtm/src/org/oscim/utils/pool/Pool.java @@ -18,87 +18,91 @@ package org.oscim.utils.pool; import javax.annotation.CheckReturnValue; -@SuppressWarnings({ "rawtypes", "unchecked" }) +@SuppressWarnings({"rawtypes", "unchecked"}) public abstract class Pool> { - protected T mPool; - protected int mLimit; - protected int mFill; + protected T mPool; + protected int mLimit; + protected int mFill; - /** - * @param item release resources - * @return whether item should be added to - * pool. use to manage pool size manually - */ - protected boolean clearItem(T item) { - return true; - } + /** + * @param item release resources + * @return whether item should be added to + * pool. use to manage pool size manually + */ + protected boolean clearItem(T item) { + return true; + } - /** - * Release 'item' to pool. - *

    - * Usage item = pool.release(item), to ensure to not keep a reference to - * item! - */ - @CheckReturnValue - public T release(T item) { - if (item == null) - return null; + /** + * Release 'item' to pool. + *

    + * Usage item = pool.release(item), to ensure to not keep a reference to + * item! + */ + @CheckReturnValue + public T release(T item) { + if (item == null) + return null; - if (!clearItem(item)) - return null; + if (!clearItem(item)) + return null; - ((Inlist) item).next = mPool; - mPool = item; + ((Inlist) item).next = mPool; + mPool = item; - return null; - } + return null; + } - /** - * Release 'list' to pool. - *

    - * Usage list = pool.releaseAll(list), to ensure to not keep a reference to - * list! - */ - @CheckReturnValue - public T releaseAll(T list) { - if (list == null) - return null; + /** + * Release 'list' to pool. + *

    + * Usage list = pool.releaseAll(list), to ensure to not keep a reference to + * list! + */ + @CheckReturnValue + public T releaseAll(T list) { + if (list == null) + return null; - while (list != null) { + while (list != null) { - T next = (T) list.next; + T next = (T) list.next; - clearItem(list); + clearItem(list); - ((Inlist) list).next = mPool; - mPool = list; + ((Inlist) list).next = mPool; + mPool = list; - list = next; - } - return null; - } + list = next; + } + return null; + } - /** remove 'item' from 'list' and add back to pool */ - public T release(T list, T item) { - if (item == null) - return list; + /** + * remove 'item' from 'list' and add back to pool + */ + public T release(T list, T item) { + if (item == null) + return list; - clearItem(item); + clearItem(item); - return (T) Inlist.remove((Inlist) list, item); - } + return (T) Inlist.remove((Inlist) list, item); + } - /** get an item from pool */ - public T get() { - if (mPool == null) - return createItem(); + /** + * get an item from pool + */ + public T get() { + if (mPool == null) + return createItem(); - Inlist ret = mPool; - mPool = (T) mPool.next; + Inlist ret = mPool; + mPool = (T) mPool.next; - ret.next = null; - return (T) ret; - } + ret.next = null; + return (T) ret; + } - protected abstract T createItem(); + protected abstract T createItem(); } diff --git a/vtm/src/org/oscim/utils/pool/SyncPool.java b/vtm/src/org/oscim/utils/pool/SyncPool.java index 56e69b60..89c3f423 100644 --- a/vtm/src/org/oscim/utils/pool/SyncPool.java +++ b/vtm/src/org/oscim/utils/pool/SyncPool.java @@ -18,164 +18,161 @@ package org.oscim.utils.pool; import javax.annotation.CheckReturnValue; -@SuppressWarnings({ "rawtypes", "unchecked" }) +@SuppressWarnings({"rawtypes", "unchecked"}) public abstract class SyncPool> { - protected final int mMaxFill; - protected final boolean mClearItems; + protected final int mMaxFill; + protected final boolean mClearItems; - protected int mFill; - protected T mPool; + protected int mFill; + protected T mPool; - public SyncPool(int maxItemsInPool) { - this(maxItemsInPool, true); - } + public SyncPool(int maxItemsInPool) { + this(maxItemsInPool, true); + } - public SyncPool(int maxItemsInPool, boolean clearItems) { - mMaxFill = maxItemsInPool; - mFill = 0; - mClearItems = clearItems; - } + public SyncPool(int maxItemsInPool, boolean clearItems) { + mMaxFill = maxItemsInPool; + mFill = 0; + mClearItems = clearItems; + } - public int getFill() { - return mFill; - } + public int getFill() { + return mFill; + } - /** - * To be implemented by subclass. - * - * @param items - * number of initial items - */ - public void init(int items) { - mFill = 0; - mPool = null; - } + /** + * To be implemented by subclass. + * + * @param items number of initial items + */ + public void init(int items) { + mFill = 0; + mPool = null; + } - public synchronized void clear() { - while (mPool != null) { - freeItem(mPool); - mPool = (T) mPool.next; - } - } + public synchronized void clear() { + while (mPool != null) { + freeItem(mPool); + mPool = (T) mPool.next; + } + } - /** - * @param item - * set initial state - * @return 'true' when item should be added back to pool, - * 'false' when freeItem should be called. - */ - protected boolean clearItem(T item) { - return true; - } + /** + * @param item set initial state + * @return 'true' when item should be added back to pool, + * 'false' when freeItem should be called. + */ + protected boolean clearItem(T item) { + return true; + } - /** - * @param item - * release resources - */ - protected void freeItem(T item) { + /** + * @param item release resources + */ + protected void freeItem(T item) { - } + } - /** - * Creates the item. To be implemented by subclass. - * - * @return the item - */ - protected abstract T createItem(); + /** + * Creates the item. To be implemented by subclass. + * + * @return the item + */ + protected abstract T createItem(); - /** - * Release 'item' to pool. - *

    - * Usage item = pool.release(item), to ensure to not keep a reference to - * item! - */ - @CheckReturnValue - public T release(T item) { - if (item == null) - return null; + /** + * Release 'item' to pool. + *

    + * Usage item = pool.release(item), to ensure to not keep a reference to + * item! + */ + @CheckReturnValue + public T release(T item) { + if (item == null) + return null; - if (mClearItems && !clearItem(item)) { - // dont add back to pool - freeItem(item); - return null; - } - if (mFill < mMaxFill) { - synchronized (this) { - mFill++; + if (mClearItems && !clearItem(item)) { + // dont add back to pool + freeItem(item); + return null; + } + if (mFill < mMaxFill) { + synchronized (this) { + mFill++; - ((Inlist) item).next = (T) mPool; - mPool = item; - } - } else if (mClearItems) { - freeItem(item); - } - return null; - } + ((Inlist) item).next = (T) mPool; + mPool = item; + } + } else if (mClearItems) { + freeItem(item); + } + return null; + } - /** - * Release 'list' to pool. - *

    - * Usage list = pool.releaseAll(list), to ensure to not keep a reference to - * list! - */ - @CheckReturnValue - public T releaseAll(T item) { - if (item == null) - return null; + /** + * Release 'list' to pool. + *

    + * Usage list = pool.releaseAll(list), to ensure to not keep a reference to + * list! + */ + @CheckReturnValue + public T releaseAll(T item) { + if (item == null) + return null; - if (mFill > mMaxFill) { - while (item != null) { - if (mClearItems) { - clearItem(item); - freeItem(item); - } - item = (T) item.next; - } - return null; - } + if (mFill > mMaxFill) { + while (item != null) { + if (mClearItems) { + clearItem(item); + freeItem(item); + } + item = (T) item.next; + } + return null; + } - synchronized (this) { - while (item != null) { - T next = (T) item.next; + synchronized (this) { + while (item != null) { + T next = (T) item.next; - if (mClearItems && !clearItem(item)) { - // dont add back to pool - freeItem(item); - item = next; - continue; - } + if (mClearItems && !clearItem(item)) { + // dont add back to pool + freeItem(item); + item = next; + continue; + } - mFill++; + mFill++; - ((Inlist) item).next = (T) mPool; - mPool = item; + ((Inlist) item).next = (T) mPool; + mPool = item; - item = next; - } - } - return null; - } + item = next; + } + } + return null; + } - /** - * Gets an 'item' from pool, if pool is empty a new - * item will be created by createItem(). - * - * @return the item - */ - public T get() { + /** + * Gets an 'item' from pool, if pool is empty a new + * item will be created by createItem(). + * + * @return the item + */ + public T get() { - synchronized (this) { - if (mPool == null) { - return createItem(); - } + synchronized (this) { + if (mPool == null) { + return createItem(); + } - mFill--; + mFill--; - T ret = mPool; - mPool = (T) mPool.next; + T ret = mPool; + mPool = (T) mPool.next; - ret.next = null; - return ret; - } - } + ret.next = null; + return ret; + } + } } diff --git a/vtm/src/org/oscim/utils/quadtree/BoxTree.java b/vtm/src/org/oscim/utils/quadtree/BoxTree.java index 3d49b406..b2c00ac9 100644 --- a/vtm/src/org/oscim/utils/quadtree/BoxTree.java +++ b/vtm/src/org/oscim/utils/quadtree/BoxTree.java @@ -1,7 +1,5 @@ package org.oscim.utils.quadtree; -import java.util.Arrays; - import org.oscim.utils.SpatialIndex.SearchCb; import org.oscim.utils.pool.Inlist; import org.oscim.utils.pool.Pool; @@ -10,669 +8,677 @@ import org.oscim.utils.quadtree.BoxTree.BoxNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Arrays; + /** * A BoxTree is made of BoxNodes which hold a list of * generic BoxItems which can hold a custom data item. - * + *

    * ... in case this generic isnt obvious at first sight. - * */ + */ public class BoxTree, E> extends TileIndex, T> { - final static Logger log = LoggerFactory.getLogger(BoxTree.class); - static boolean dbg = false; + final static Logger log = LoggerFactory.getLogger(BoxTree.class); + static boolean dbg = false; - protected final int extents; - protected final int maxDepth; - private final static int MAX_STACK = 32; + protected final int extents; + protected final int maxDepth; + private final static int MAX_STACK = 32; - static class Stack extends Inlist> { - /** Top of stack index */ - int tos; + static class Stack extends Inlist> { + /** + * Top of stack index + */ + int tos; - final E[] nodes; + final E[] nodes; - @SuppressWarnings("unchecked") - Stack() { - nodes = (E[]) new BoxNode[MAX_STACK]; - } + @SuppressWarnings("unchecked") + Stack() { + nodes = (E[]) new BoxNode[MAX_STACK]; + } - void push(E node) { - nodes[tos] = node; - tos++; - } + void push(E node) { + nodes[tos] = node; + tos++; + } - /** Pop element off iteration stack (For internal use only) */ - E pop() { - // assert (tos > 0); - nodes[tos--] = null; - return (E) nodes[tos]; - } + /** + * Pop element off iteration stack (For internal use only) + */ + E pop() { + // assert (tos > 0); + nodes[tos--] = null; + return (E) nodes[tos]; + } - E node() { - return (E) nodes[tos]; - } + E node() { + return (E) nodes[tos]; + } - boolean empty() { - return tos <= 0; - } - } + boolean empty() { + return tos <= 0; + } + } - public static class BoxNode> extends TreeNode, T> { - // TODO this is redundant - use tile ids - public int x1, x2, y1, y2; + public static class BoxNode> extends TreeNode, T> { + // TODO this is redundant - use tile ids + public int x1, x2, y1, y2; /* inherits BoxItem item; */ - @Override - public String toString() { - return x1 + ":" + y1 + ":" + (x2 - x1); - } - } + @Override + public String toString() { + return x1 + ":" + y1 + ":" + (x2 - x1); + } + } - public static class BoxItem extends Inlist> { - public int x1, x2, y1, y2; + public static class BoxItem extends Inlist> { + public int x1, x2, y1, y2; - public T item; + public T item; - public BoxItem() { - } + public BoxItem() { + } - public BoxItem(int x1, int y1, int x2, int y2) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - } + public BoxItem(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } - public BoxItem(float x1, float y1, float x2, float y2) { - this.x1 = (int) x1; - this.y1 = (int) y1; - this.x2 = (int) x2; - this.y2 = (int) y2; - } + public BoxItem(float x1, float y1, float x2, float y2) { + this.x1 = (int) x1; + this.y1 = (int) y1; + this.x2 = (int) x2; + this.y2 = (int) y2; + } - public BoxItem(org.oscim.core.Box box, T item) { - this.x1 = (int) box.xmin; - this.y1 = (int) box.ymin; - this.x2 = (int) box.xmax; - this.y2 = (int) box.ymax; - this.item = item; - } + public BoxItem(org.oscim.core.Box box, T item) { + this.x1 = (int) box.xmin; + this.y1 = (int) box.ymin; + this.x2 = (int) box.xmax; + this.y2 = (int) box.ymax; + this.item = item; + } - public boolean overlaps(BoxItem it) { - return !((x1 > it.x2) || (it.x1 > x2) || (y1 > it.y2) || (it.y1 > y2)); - } + public boolean overlaps(BoxItem it) { + return !((x1 > it.x2) || (it.x1 > x2) || (y1 > it.y2) || (it.y1 > y2)); + } - public void setExtents(float[] obb, float add) { - setExtents(obb, add, obb.length); - } + public void setExtents(float[] obb, float add) { + setExtents(obb, add, obb.length); + } - public void setExtents(float[] obb, float add, int length) { - float x1, y1, x2, y2; - x1 = x2 = obb[0]; - y1 = y2 = obb[1]; + public void setExtents(float[] obb, float add, int length) { + float x1, y1, x2, y2; + x1 = x2 = obb[0]; + y1 = y2 = obb[1]; - for (int i = 2, n = length; i < n; i += 2) { - float x = obb[i]; - if (x < x1) - x1 = x; - else if (x > x2) - x2 = x; + for (int i = 2, n = length; i < n; i += 2) { + float x = obb[i]; + if (x < x1) + x1 = x; + else if (x > x2) + x2 = x; - float y = obb[i + 1]; - if (y < y1) - y1 = y; - else if (y > y2) - y2 = y; - } - this.x1 = (int) (x1 - add); - this.y1 = (int) (y1 - add); - this.x2 = (int) (x2 + add); - this.y2 = (int) (y2 + add); - } + float y = obb[i + 1]; + if (y < y1) + y1 = y; + else if (y > y2) + y2 = y; + } + this.x1 = (int) (x1 - add); + this.y1 = (int) (y1 - add); + this.x2 = (int) (x2 + add); + this.y2 = (int) (y2 + add); + } - @Override - public String toString() { - return "[" + x1 + ',' + y1 + '/' + x2 + ',' + y2 + ']'; - } - } + @Override + public String toString() { + return "[" + x1 + ',' + y1 + '/' + x2 + ',' + y2 + ']'; + } + } - public interface Visitor { - boolean process(T item); - } + public interface Visitor { + boolean process(T item); + } - boolean isPowerOfTwo(int x) { - return ((x > 0) && (x & (x - 1)) == 0); - } + boolean isPowerOfTwo(int x) { + return ((x > 0) && (x & (x - 1)) == 0); + } - /** - * BoxTreee for the range [-extents, extents] - * - * @param extents must be power of two - * @param maxDepth must be <= 30 - */ - public BoxTree(int extents, int maxDepth) { - super(); - if (!isPowerOfTwo(extents)) - throw new IllegalArgumentException("Extents must be power of two!"); + /** + * BoxTreee for the range [-extents, extents] + * + * @param extents must be power of two + * @param maxDepth must be <= 30 + */ + public BoxTree(int extents, int maxDepth) { + super(); + if (!isPowerOfTwo(extents)) + throw new IllegalArgumentException("Extents must be power of two!"); /* size is -extents to +extents */ - this.root.x1 = -extents; - this.root.y1 = -extents; - this.root.x2 = extents; - this.root.y2 = extents; + this.root.x1 = -extents; + this.root.y1 = -extents; + this.root.x2 = extents; + this.root.y2 = extents; - this.extents = extents; - this.maxDepth = maxDepth; - } + this.extents = extents; + this.maxDepth = maxDepth; + } - @Override - public BoxNode create() { - return new BoxNode(); - } + @Override + public BoxNode create() { + return new BoxNode(); + } - @Override - public void removeItem(T item) { + @Override + public void removeItem(T item) { - } + } - Pool>> stackPool = new Pool>>() { - @Override - protected Stack> createItem() { - return new Stack>(); - } + Pool>> stackPool = new Pool>>() { + @Override + protected Stack> createItem() { + return new Stack>(); + } - protected boolean clearItem(Stack> item) { - if (item.tos != 0) { - item.tos = 0; - Arrays.fill(item.nodes, null); - } - return true; - }; - }; + protected boolean clearItem(Stack> item) { + if (item.tos != 0) { + item.tos = 0; + Arrays.fill(item.nodes, null); + } + return true; + } - /** - * @return false when search was aborted - */ - public boolean search(BoxItem box, SearchCb cb, Object ctxt) { - BoxNode n; + ; + }; - Stack> stack = stackPool.get(); - stack.push(root); + /** + * @return false when search was aborted + */ + public boolean search(BoxItem box, SearchCb cb, Object ctxt) { + BoxNode n; - while (!stack.empty()) { + Stack> stack = stackPool.get(); + stack.push(root); - n = stack.pop(); + while (!stack.empty()) { + + n = stack.pop(); /* process overlapping items from cur node */ - for (BoxItem it = n.item; it != null; it = it.next) { - if (it.overlaps(box)) { - if (!cb.call(it.item, ctxt)) { - stackPool.release(stack); - return false; - } - } - } + for (BoxItem it = n.item; it != null; it = it.next) { + if (it.overlaps(box)) { + if (!cb.call(it.item, ctxt)) { + stackPool.release(stack); + return false; + } + } + } - BoxNode p = n.parent; + BoxNode p = n.parent; /* push next node on same level onto stack */ - switch (n.id) { - case 0: - if (overlaps(p.child01, box)) { - stack.push(p.child01); - break; - } - case 1: - if (overlaps(p.child10, box)) { - stack.push(p.child10); - break; - } - case 2: - if (overlaps(p.child11, box)) { - stack.push(p.child11); - break; - } - default: - break; - } - /* push next level child onto stack */ - if (overlaps(n.child00, box)) - stack.push(n.child00); - else if (overlaps(n.child01, box)) - stack.push(n.child01); - else if (overlaps(n.child10, box)) - stack.push(n.child10); - else if (overlaps(n.child11, box)) - stack.push(n.child11); - } + switch (n.id) { + case 0: + if (overlaps(p.child01, box)) { + stack.push(p.child01); + break; + } + case 1: + if (overlaps(p.child10, box)) { + stack.push(p.child10); + break; + } + case 2: + if (overlaps(p.child11, box)) { + stack.push(p.child11); + break; + } + default: + break; + } + /* push next level child onto stack */ + if (overlaps(n.child00, box)) + stack.push(n.child00); + else if (overlaps(n.child01, box)) + stack.push(n.child01); + else if (overlaps(n.child10, box)) + stack.push(n.child10); + else if (overlaps(n.child11, box)) + stack.push(n.child11); + } - stackPool.release(stack); - return true; - } + stackPool.release(stack); + return true; + } - public interface SearchBoxCb> { - boolean call(T item); - } + public interface SearchBoxCb> { + boolean call(T item); + } - public boolean search(BoxItem box, SearchBoxCb cb) { - BoxNode n; + public boolean search(BoxItem box, SearchBoxCb cb) { + BoxNode n; - if (root.refs == 0) { - //log.debug("emtpy"); - return true; - } + if (root.refs == 0) { + //log.debug("emtpy"); + return true; + } - Stack> stack = stackPool.get(); - stack.push(root); + Stack> stack = stackPool.get(); + stack.push(root); - while (!stack.empty()) { - n = stack.pop(); + while (!stack.empty()) { + n = stack.pop(); /* process overlapping items from cur node */ - for (BoxItem it = n.item; it != null; it = it.next) { - if (it.overlaps(box)) { - @SuppressWarnings("unchecked") - T item = (T) it; - if (!cb.call(item)) { - stackPool.release(stack); - return false; - } - } - } + for (BoxItem it = n.item; it != null; it = it.next) { + if (it.overlaps(box)) { + @SuppressWarnings("unchecked") + T item = (T) it; + if (!cb.call(item)) { + stackPool.release(stack); + return false; + } + } + } - BoxNode p = n.parent; + BoxNode p = n.parent; /* push next node on same level onto stack */ - switch (n.id) { - case 0: - if (overlaps(p.child01, box)) { - stack.push(p.child01); - break; - } - case 1: - if (overlaps(p.child10, box)) { - stack.push(p.child10); - break; - } - case 2: - if (overlaps(p.child11, box)) { - stack.push(p.child11); - break; - } - default: - break; - } + switch (n.id) { + case 0: + if (overlaps(p.child01, box)) { + stack.push(p.child01); + break; + } + case 1: + if (overlaps(p.child10, box)) { + stack.push(p.child10); + break; + } + case 2: + if (overlaps(p.child11, box)) { + stack.push(p.child11); + break; + } + default: + break; + } /* push next level child onto stack */ - if (overlaps(n.child00, box)) - stack.push(n.child00); + if (overlaps(n.child00, box)) + stack.push(n.child00); - else if (overlaps(n.child01, box)) - stack.push(n.child01); + else if (overlaps(n.child01, box)) + stack.push(n.child01); - else if (overlaps(n.child10, box)) - stack.push(n.child10); + else if (overlaps(n.child10, box)) + stack.push(n.child10); - else if (overlaps(n.child11, box)) - stack.push(n.child11); - } - stackPool.release(stack); + else if (overlaps(n.child11, box)) + stack.push(n.child11); + } + stackPool.release(stack); - return true; - } + return true; + } - private static boolean overlaps(BoxNode a, BoxItem b) { - return a != null && !((a.x1 > b.x2) || (b.x1 > a.x2) || (a.y1 > b.y2) || (b.y1 > a.y2)); - } + private static boolean overlaps(BoxNode a, BoxItem b) { + return a != null && !((a.x1 > b.x2) || (b.x1 > a.x2) || (a.y1 > b.y2) || (b.y1 > a.y2)); + } - public interface SearchNodeCb> { - boolean call(E item); - } + public interface SearchNodeCb> { + boolean call(E item); + } - public void collect(SearchNodeCb> cb) { - BoxNode n; + public void collect(SearchNodeCb> cb) { + BoxNode n; - Stack> stack = stackPool.get(); + Stack> stack = stackPool.get(); - stack.push(root); + stack.push(root); - while (!stack.empty()) { - n = stack.pop(); + while (!stack.empty()) { + n = stack.pop(); /* process overlapping items from cur node */ - cb.call(n); + cb.call(n); - BoxNode p = n.parent; + BoxNode p = n.parent; /* push next node on same level onto stack */ - switch (n.id) { - case 0: - if (p.child01 != null) { - stack.push(p.child01); - break; - } - case 1: - if (p.child10 != null) { - stack.push(p.child10); - break; - } - case 2: - if (p.child11 != null) { - stack.push(p.child11); - break; - } - default: - break; - } + switch (n.id) { + case 0: + if (p.child01 != null) { + stack.push(p.child01); + break; + } + case 1: + if (p.child10 != null) { + stack.push(p.child10); + break; + } + case 2: + if (p.child11 != null) { + stack.push(p.child11); + break; + } + default: + break; + } /* push next level child onto stack */ - if (n.child00 != null) - stack.push(n.child00); - else if (n.child01 != null) - stack.push(n.child01); - else if (n.child10 != null) - stack.push(n.child10); - else if (n.child11 != null) - stack.push(n.child11); - } - stackPool.release(stack); - } + if (n.child00 != null) + stack.push(n.child00); + else if (n.child01 != null) + stack.push(n.child01); + else if (n.child10 != null) + stack.push(n.child10); + else if (n.child11 != null) + stack.push(n.child11); + } + stackPool.release(stack); + } - public BoxNode create(BoxNode parent, int i) { - BoxNode node; - if (pool != null) { - node = pool; - pool = pool.parent; - node.refs = 0; - } else - node = new BoxNode(); + public BoxNode create(BoxNode parent, int i) { + BoxNode node; + if (pool != null) { + node = pool; + pool = pool.parent; + node.refs = 0; + } else + node = new BoxNode(); - node.parent = parent; + node.parent = parent; - int size = (parent.x2 - parent.x1) >> 1; - node.x1 = parent.x1; - node.y1 = parent.y1; + int size = (parent.x2 - parent.x1) >> 1; + node.x1 = parent.x1; + node.y1 = parent.y1; - if (i == 0) { - parent.child00 = node; - } else if (i == 1) { - parent.child01 = node; - node.y1 += size; - } else if (i == 2) { - parent.child10 = node; - node.x1 += size; - } else { - parent.child11 = node; - node.x1 += size; - node.y1 += size; - } + if (i == 0) { + parent.child00 = node; + } else if (i == 1) { + parent.child01 = node; + node.y1 += size; + } else if (i == 2) { + parent.child10 = node; + node.x1 += size; + } else { + parent.child11 = node; + node.x1 += size; + node.y1 += size; + } - node.x2 = node.x1 + size; - node.y2 = node.y1 + size; - node.id = (byte) i; + node.x2 = node.x1 + size; + node.y2 = node.y1 + size; + node.id = (byte) i; - return node; - } + return node; + } - public void insert(T box) { - if (box.x1 > box.x2 || box.y1 > box.y2) - throw new IllegalArgumentException(); + public void insert(T box) { + if (box.x1 > box.x2 || box.y1 > box.y2) + throw new IllegalArgumentException(); - if (box.next != null) - throw new IllegalStateException("BoxItem is list"); + if (box.next != null) + throw new IllegalStateException("BoxItem is list"); - BoxNode cur = root; - BoxNode child = null; + BoxNode cur = root; + BoxNode child = null; - int x1 = box.x1; - int x2 = box.x2; - int y1 = box.y1; - int y2 = box.y2; + int x1 = box.x1; + int x2 = box.x2; + int y1 = box.y1; + int y2 = box.y2; - for (int level = 0; level <= maxDepth; level++) { - cur.refs++; + for (int level = 0; level <= maxDepth; level++) { + cur.refs++; /* half size of tile at current level */ - int hsize = (cur.x2 - cur.x1) >> 1; + int hsize = (cur.x2 - cur.x1) >> 1; /* center of tile */ - int cx = cur.x1 + hsize; - int cy = cur.y1 + hsize; + int cx = cur.x1 + hsize; + int cy = cur.y1 + hsize; - child = null; + child = null; - if (level < maxDepth) { - if (x2 < cx) { - if (y2 < cy) { - if ((child = cur.child00) == null) - child = create(cur, 0); - } else if (y1 >= cy) { - if ((child = cur.child01) == null) - child = create(cur, 1); - } - } - if (x1 >= cx) { - if (y2 < cy) { - if ((child = cur.child10) == null) - child = create(cur, 2); - } else if (y1 >= cy) { - if ((child = cur.child11) == null) - child = create(cur, 3); - } - } - } + if (level < maxDepth) { + if (x2 < cx) { + if (y2 < cy) { + if ((child = cur.child00) == null) + child = create(cur, 0); + } else if (y1 >= cy) { + if ((child = cur.child01) == null) + child = create(cur, 1); + } + } + if (x1 >= cx) { + if (y2 < cy) { + if ((child = cur.child10) == null) + child = create(cur, 2); + } else if (y1 >= cy) { + if ((child = cur.child11) == null) + child = create(cur, 3); + } + } + } - if (child == null) { - /* push item onto list of this node */ - box.next = cur.item; - cur.item = box; + if (child == null) { + /* push item onto list of this node */ + box.next = cur.item; + cur.item = box; - if (dbg) - log.debug("insert: " + level - + " cnt:" + Inlist.size(cur.item) + " " + x1 + ":" + y1 - + " /" + (x2) + "x" + (y2) + " " + box.item); - break; - } - cur = child; - } - } + if (dbg) + log.debug("insert: " + level + + " cnt:" + Inlist.size(cur.item) + " " + x1 + ":" + y1 + + " /" + (x2) + "x" + (y2) + " " + box.item); + break; + } + cur = child; + } + } - public boolean remove(T box, E item) { - if (box.x1 > box.x2 || box.y1 > box.y2) - throw new IllegalArgumentException(); + public boolean remove(T box, E item) { + if (box.x1 > box.x2 || box.y1 > box.y2) + throw new IllegalArgumentException(); - BoxNode cur = root; - BoxNode child = null; + BoxNode cur = root; + BoxNode child = null; - int x1 = box.x1; - int x2 = box.x2; - int y1 = box.y1; - int y2 = box.y2; + int x1 = box.x1; + int x2 = box.x2; + int y1 = box.y1; + int y2 = box.y2; - for (int level = 0; level <= maxDepth; level++) { + for (int level = 0; level <= maxDepth; level++) { /* half size of tile at current level */ - int hsize = (cur.x2 - cur.x1) >> 1; + int hsize = (cur.x2 - cur.x1) >> 1; /* center of tile */ - int cx = cur.x1 + hsize; - int cy = cur.y1 + hsize; + int cx = cur.x1 + hsize; + int cy = cur.y1 + hsize; - child = null; - if (level < maxDepth) { - if (x2 < cx) { - if (y2 < cy) { - child = cur.child00; - } else if (y1 >= cy) { - child = cur.child01; - } - } else if (x1 >= cx) { - if (y2 < cy) { - child = cur.child10; - } else if (y1 >= cy) { - child = cur.child11; - } - } - } - if (child == null) { + child = null; + if (level < maxDepth) { + if (x2 < cx) { + if (y2 < cy) { + child = cur.child00; + } else if (y1 >= cy) { + child = cur.child01; + } + } else if (x1 >= cx) { + if (y2 < cy) { + child = cur.child10; + } else if (y1 >= cy) { + child = cur.child11; + } + } + } + if (child == null) { - BoxItem prev = cur.item; + BoxItem prev = cur.item; - for (BoxItem it = cur.item; it != null; it = it.next) { - if (it.item == item) { - if (dbg) - log.debug("remove: " + level - + " cnt:" + Inlist.size(cur.item) + " " + x1 + ":" + y1 - + " /" + (x2) + "x" + (y2) + " " + item); + for (BoxItem it = cur.item; it != null; it = it.next) { + if (it.item == item) { + if (dbg) + log.debug("remove: " + level + + " cnt:" + Inlist.size(cur.item) + " " + x1 + ":" + y1 + + " /" + (x2) + "x" + (y2) + " " + item); - if (cur.item == it) { - // FUNKY GENERICS... - @SuppressWarnings("unchecked") - T b = (T) it.next; - cur.item = b; - } else - prev.next = it.next; + if (cur.item == it) { + // FUNKY GENERICS... + @SuppressWarnings("unchecked") + T b = (T) it.next; + cur.item = b; + } else + prev.next = it.next; - it.next = null; - remove(cur); + it.next = null; + remove(cur); - return true; - } - prev = it; - } - return false; - } + return true; + } + prev = it; + } + return false; + } - cur = child; - } - return false; - } + cur = child; + } + return false; + } - public BoxNode getNode(T box, boolean create) { - if (box.x1 > box.x2 || box.y1 > box.y2) - throw new IllegalArgumentException(); + public BoxNode getNode(T box, boolean create) { + if (box.x1 > box.x2 || box.y1 > box.y2) + throw new IllegalArgumentException(); - BoxNode cur = root; - BoxNode child = null; + BoxNode cur = root; + BoxNode child = null; - int x1 = box.x1; - int x2 = box.x2; - int y1 = box.y1; - int y2 = box.y2; + int x1 = box.x1; + int x2 = box.x2; + int y1 = box.y1; + int y2 = box.y2; - for (int level = 0; level <= maxDepth; level++) { - cur.refs++; + for (int level = 0; level <= maxDepth; level++) { + cur.refs++; /* half size of tile at current z */ - int hsize = (cur.x2 - cur.x1) >> 1; + int hsize = (cur.x2 - cur.x1) >> 1; /* center of tile (shift by -extents) */ - int cx = cur.x1 + hsize; - int cy = cur.y1 + hsize; + int cx = cur.x1 + hsize; + int cy = cur.y1 + hsize; - child = null; + child = null; - if (x2 < cx) { - if (y2 < cy) { - if ((child = cur.child00) == null && create) - child = create(cur, 0); - } else if (y1 >= cy) { - if ((child = cur.child01) == null && create) - child = create(cur, 1); - } - } - if (x1 >= cx) { - if (y2 < cy) { - if ((child = cur.child10) == null && create) - child = create(cur, 2); - } else if (y1 >= cy) { - if ((child = cur.child11) == null && create) - child = create(cur, 3); - } - } + if (x2 < cx) { + if (y2 < cy) { + if ((child = cur.child00) == null && create) + child = create(cur, 0); + } else if (y1 >= cy) { + if ((child = cur.child01) == null && create) + child = create(cur, 1); + } + } + if (x1 >= cx) { + if (y2 < cy) { + if ((child = cur.child10) == null && create) + child = create(cur, 2); + } else if (y1 >= cy) { + if ((child = cur.child11) == null && create) + child = create(cur, 3); + } + } - if (child == null || level == maxDepth) - return cur; + if (child == null || level == maxDepth) + return cur; - cur = child; - } - return null; - } + cur = child; + } + return null; + } - public void clear() { - root.child00 = null; - root.child01 = null; - root.child10 = null; - root.child11 = null; - root.item = null; - root.refs = 0; - } + public void clear() { + root.child00 = null; + root.child01 = null; + root.child10 = null; + root.child11 = null; + root.item = null; + root.refs = 0; + } - public void clearToPool() { - BoxNode node = root; + public void clearToPool() { + BoxNode node = root; - while (true) { + while (true) { /* traverse down */ - if (node.child00 != null) { - node = node.child00; - continue; - } - if (node.child01 != null) { - node = node.child01; - continue; - } - if (node.child10 != null) { - node = node.child10; - continue; - } - if (node.child11 != null) { - node = node.child11; - continue; - } + if (node.child00 != null) { + node = node.child00; + continue; + } + if (node.child01 != null) { + node = node.child01; + continue; + } + if (node.child10 != null) { + node = node.child10; + continue; + } + if (node.child11 != null) { + node = node.child11; + continue; + } - if (node == root) - break; + if (node == root) + break; /* traverse up */ - BoxNode parent = node.parent; + BoxNode parent = node.parent; /* unlink from parent */ - switch (node.id) { - case 0: - parent.child00 = null; - break; - case 1: - parent.child01 = null; - break; - case 2: - parent.child10 = null; - break; - case 3: - parent.child11 = null; - break; - } + switch (node.id) { + case 0: + parent.child00 = null; + break; + case 1: + parent.child01 = null; + break; + case 2: + parent.child10 = null; + break; + case 3: + parent.child11 = null; + break; + } /* release items */ - node.item = null; - node.refs = 0; + node.item = null; + node.refs = 0; /* add n back to pool */ - node.parent = pool; - pool = node; + node.parent = pool; + pool = node; /* continue with parent node */ - node = parent; - } + node = parent; + } - root.child00 = null; - root.child01 = null; - root.child10 = null; - root.child11 = null; - root.item = null; - root.refs = 0; - } + root.child00 = null; + root.child01 = null; + root.child10 = null; + root.child11 = null; + root.item = null; + root.refs = 0; + } - public int size() { - return root.refs; - } + public int size() { + return root.refs; + } } diff --git a/vtm/src/org/oscim/utils/quadtree/TileIndex.java b/vtm/src/org/oscim/utils/quadtree/TileIndex.java index d30bfedd..847fecbf 100644 --- a/vtm/src/org/oscim/utils/quadtree/TileIndex.java +++ b/vtm/src/org/oscim/utils/quadtree/TileIndex.java @@ -21,185 +21,185 @@ package org.oscim.utils.quadtree; */ public abstract class TileIndex, E> { - protected final T root; + protected final T root; - protected T pool; + protected T pool; - public TileIndex() { - root = create(); - root.id = -1; - root.parent = root; - } + public TileIndex() { + root = create(); + root.id = -1; + root.parent = root; + } - static void checkIndex(int x, int y, int max) { - if (x < 0 || x >= max || y < 0 || y >= max) { - throw new IllegalArgumentException("invalid position " - + x + '/' + y + '/' + (max >> 1)); - } - } + static void checkIndex(int x, int y, int max) { + if (x < 0 || x >= max || y < 0 || y >= max) { + throw new IllegalArgumentException("invalid position " + + x + '/' + y + '/' + (max >> 1)); + } + } - public abstract T create(); + public abstract T create(); - public abstract void removeItem(E item); + public abstract void removeItem(E item); - public T add(int x, int y, int z) { + public T add(int x, int y, int z) { - checkIndex(x, y, 1 << z); + checkIndex(x, y, 1 << z); - if (z == 0) - return root; + if (z == 0) + return root; - T leaf = root; + T leaf = root; - for (int level = z - 1; level >= 0; level--) { + for (int level = z - 1; level >= 0; level--) { - int id = ((x >> level) & 1) | ((y >> level) & 1) << 1; + int id = ((x >> level) & 1) | ((y >> level) & 1) << 1; - leaf.refs++; + leaf.refs++; - T cur = null; + T cur = null; - switch (id) { - case 0: - cur = leaf.child00; - break; - case 1: - cur = leaf.child01; - break; - case 2: - cur = leaf.child10; - break; - case 3: - cur = leaf.child11; - break; - } + switch (id) { + case 0: + cur = leaf.child00; + break; + case 1: + cur = leaf.child01; + break; + case 2: + cur = leaf.child10; + break; + case 3: + cur = leaf.child11; + break; + } - if (cur != null) { - leaf = cur; - continue; - } + if (cur != null) { + leaf = cur; + continue; + } - if (pool != null) { - cur = pool; - pool = pool.parent; - } else { - cur = create(); - } + if (pool != null) { + cur = pool; + pool = pool.parent; + } else { + cur = create(); + } - cur.refs = 0; - cur.id = (byte) id; - cur.parent = leaf; + cur.refs = 0; + cur.id = (byte) id; + cur.parent = leaf; - switch (id) { - case 0: - cur.parent.child00 = cur; - break; - case 1: - cur.parent.child01 = cur; - break; - case 2: - cur.parent.child10 = cur; - break; - case 3: - cur.parent.child11 = cur; - break; - } + switch (id) { + case 0: + cur.parent.child00 = cur; + break; + case 1: + cur.parent.child01 = cur; + break; + case 2: + cur.parent.child10 = cur; + break; + case 3: + cur.parent.child11 = cur; + break; + } - leaf = cur; - } + leaf = cur; + } - leaf.refs++; + leaf.refs++; - return leaf; - } + return leaf; + } - public E getTile(int x, int y, int z) { + public E getTile(int x, int y, int z) { - checkIndex(x, y, 1 << z); + checkIndex(x, y, 1 << z); - if (z == 0) - return root.item; + if (z == 0) + return root.item; - T leaf = root; - for (int level = z - 1; level >= 0; level--) { + T leaf = root; + for (int level = z - 1; level >= 0; level--) { - int id = ((x >> level) & 1) | ((y >> level) & 1) << 1; + int id = ((x >> level) & 1) | ((y >> level) & 1) << 1; - switch (id) { - case 0: - leaf = leaf.child00; - break; - case 1: - leaf = leaf.child01; - break; - case 2: - leaf = leaf.child10; - break; - case 3: - leaf = leaf.child11; - break; - } + switch (id) { + case 0: + leaf = leaf.child00; + break; + case 1: + leaf = leaf.child01; + break; + case 2: + leaf = leaf.child10; + break; + case 3: + leaf = leaf.child11; + break; + } - if (leaf == null) - return null; + if (leaf == null) + return null; - if (level == 0) { - return leaf.item; - } - } - return null; - } + if (level == 0) { + return leaf.item; + } + } + return null; + } - public boolean remove(T item) { - T cur = item; + public boolean remove(T item) { + T cur = item; - while (cur != root) { - if (cur == null) - throw new IllegalStateException("Item not in index"); + while (cur != root) { + if (cur == null) + throw new IllegalStateException("Item not in index"); /* keep pointer to parent */ - T next = cur.parent; - cur.refs--; + T next = cur.parent; + cur.refs--; /* if current node has no children */ - if (cur.refs == 0) { - /* unhook from parent */ - switch (cur.id) { - case 0: - next.child00 = null; - break; - case 1: - next.child01 = null; - break; - case 2: - next.child10 = null; - break; - case 3: - next.child11 = null; - break; - } + if (cur.refs == 0) { + /* unhook from parent */ + switch (cur.id) { + case 0: + next.child00 = null; + break; + case 1: + next.child01 = null; + break; + case 2: + next.child10 = null; + break; + case 3: + next.child11 = null; + break; + } /* add item back to pool */ - cur.parent = pool; - pool = cur; - } - cur = next; - } + cur.parent = pool; + pool = cur; + } + cur = next; + } - root.refs--; + root.refs--; - return true; - } + return true; + } - public int size() { - return root.refs; - } + public int size() { + return root.refs; + } - public void drop() { - root.item = null; - root.child00 = null; - root.child01 = null; - root.child10 = null; - root.child11 = null; - } + public void drop() { + root.item = null; + root.child00 = null; + root.child01 = null; + root.child10 = null; + root.child11 = null; + } } diff --git a/vtm/src/org/oscim/utils/quadtree/TreeNode.java b/vtm/src/org/oscim/utils/quadtree/TreeNode.java index 0e86e125..aea273c0 100644 --- a/vtm/src/org/oscim/utils/quadtree/TreeNode.java +++ b/vtm/src/org/oscim/utils/quadtree/TreeNode.java @@ -18,49 +18,63 @@ package org.oscim.utils.quadtree; public class TreeNode, E> { - public T parent; + public T parent; - /** top-left */ - public T child00; + /** + * top-left + */ + public T child00; - /** bottom-left */ - public T child01; + /** + * bottom-left + */ + public T child01; - /** top-right */ - public T child10; + /** + * top-right + */ + public T child10; - /** bottom-right */ - public T child11; + /** + * bottom-right + */ + public T child11; - /** payload */ - public E item; + /** + * payload + */ + public E item; - /** id of this child relative to parent */ - int id; + /** + * id of this child relative to parent + */ + int id; - /** number of children and grandchildren */ - int refs = 0; + /** + * number of children and grandchildren + */ + int refs = 0; - public E parent() { - return parent.item; - } + public E parent() { + return parent.item; + } - public E child(int i) { - switch (i) { - case 0: - return (child00 != null) ? child00.item : null; - case 1: - return (child01 != null) ? child01.item : null; - case 2: - return (child10 != null) ? child10.item : null; - case 3: - return (child11 != null) ? child11.item : null; - } - return null; - } + public E child(int i) { + switch (i) { + case 0: + return (child00 != null) ? child00.item : null; + case 1: + return (child01 != null) ? child01.item : null; + case 2: + return (child10 != null) ? child10.item : null; + case 3: + return (child11 != null) ? child11.item : null; + } + return null; + } - public boolean isRoot() { - return this == parent; - } + public boolean isRoot() { + return this == parent; + } }