diff options
119 files changed, 3340 insertions, 703 deletions
diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java index 1ef99a1e6845..09661a59334c 100644 --- a/core/java/android/appwidget/AppWidgetManager.java +++ b/core/java/android/appwidget/AppWidgetManager.java @@ -184,16 +184,6 @@ public class AppWidgetManager { */ public static final String META_DATA_APPWIDGET_PROVIDER = "android.appwidget.provider"; - /** - * Field for the manifest meta-data tag used to indicate any previous name for the - * app widget receiver. - * - * @see AppWidgetProviderInfo - * - * @hide Pending API approval - */ - public static final String META_DATA_APPWIDGET_OLD_NAME = "android.appwidget.oldName"; - static WeakHashMap<Context, WeakReference<AppWidgetManager>> sManagerCache = new WeakHashMap<Context, WeakReference<AppWidgetManager>>(); static IAppWidgetService sService; diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java index 9c352d58dfb2..c33681d65941 100644 --- a/core/java/android/appwidget/AppWidgetProviderInfo.java +++ b/core/java/android/appwidget/AppWidgetProviderInfo.java @@ -138,17 +138,6 @@ public class AppWidgetProviderInfo implements Parcelable { public int icon; /** - * The previous name, if any, of the app widget receiver. If not supplied, it will be - * ignored. - * - * <p>This field corresponds to the <code><meta-data /></code> with the name - * <code>android.appwidget.oldName</code>. - * - * @hide Pending API approval - */ - public String oldName; - - /** * The view id of the AppWidget subview which should be auto-advanced by the widget's host. * * <p>This field corresponds to the <code>android:autoAdvanceViewId</code> attribute in diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java index 5be6ec1fff86..496da41c8bc0 100644 --- a/core/java/android/content/SyncManager.java +++ b/core/java/android/content/SyncManager.java @@ -1573,8 +1573,11 @@ public class SyncManager implements OnAccountsUpdateListener { final Long periodInSeconds = info.periodicSyncs.get(i).second; // find when this periodic sync was last scheduled to run final long lastPollTimeAbsolute = status.getPeriodicSyncTime(i); - // compute when this periodic sync should next run - long nextPollTimeAbsolute = lastPollTimeAbsolute + periodInSeconds * 1000; + // compute when this periodic sync should next run - this can be in the future + // for example if the user changed the time, synced and changed back. + final long nextPollTimeAbsolute = lastPollTimeAbsolute > nowAbsolute + ? nowAbsolute + : lastPollTimeAbsolute + periodInSeconds * 1000; // if it is ready to run then schedule it and mark it as having been scheduled if (nextPollTimeAbsolute <= nowAbsolute) { final Pair<Long, Long> backoff = diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java index 6627bf63f333..886a47829816 100644 --- a/core/java/android/view/View.java +++ b/core/java/android/view/View.java @@ -12663,13 +12663,15 @@ public class View implements Drawable.Callback2, KeyEvent.Callback, Accessibilit * Request that the visibility of the status bar be changed. * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. + * + * This value will be re-applied immediately, even if the flags have not changed, so a view may + * easily reassert a particular SystemUiVisibility condition even if the system UI itself has + * since countermanded the original request. */ public void setSystemUiVisibility(int visibility) { - if (visibility != mSystemUiVisibility) { - mSystemUiVisibility = visibility; - if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { - mParent.recomputeViewAttributes(this); - } + mSystemUiVisibility = visibility; + if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { + mParent.recomputeViewAttributes(this); } } diff --git a/core/java/android/webkit/HTML5Audio.java b/core/java/android/webkit/HTML5Audio.java index 6fc0d119f9c9..1e958549809d 100644 --- a/core/java/android/webkit/HTML5Audio.java +++ b/core/java/android/webkit/HTML5Audio.java @@ -27,6 +27,8 @@ import android.os.Message; import android.util.Log; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Timer; import java.util.TimerTask; @@ -46,6 +48,8 @@ class HTML5Audio extends Handler // The C++ MediaPlayerPrivateAndroid object. private int mNativePointer; + // The private status of the view that created this player + private boolean mIsPrivate; private static int IDLE = 0; private static int INITIALIZED = 1; @@ -64,6 +68,9 @@ class HTML5Audio extends Handler // Timer thread -> UI thread private static final int TIMEUPDATE = 100; + private static final String COOKIE = "Cookie"; + private static final String HIDE_URL_LOGS = "x-hide-urls-from-log"; + // The spec says the timer should fire every 250 ms or less. private static final int TIMEUPDATE_PERIOD = 250; // ms // The timer for timeupate events. @@ -138,10 +145,11 @@ class HTML5Audio extends Handler /** * @param nativePtr is the C++ pointer to the MediaPlayerPrivate object. */ - public HTML5Audio(int nativePtr) { + public HTML5Audio(WebViewCore webViewCore, int nativePtr) { // Save the native ptr mNativePointer = nativePtr; resetMediaPlayer(); + mIsPrivate = webViewCore.getWebView().isPrivateBrowsingEnabled(); } private void resetMediaPlayer() { @@ -169,7 +177,17 @@ class HTML5Audio extends Handler if (mState != IDLE) { resetMediaPlayer(); } - mMediaPlayer.setDataSource(url); + String cookieValue = CookieManager.getInstance().getCookie(url, mIsPrivate); + Map<String, String> headers = new HashMap<String, String>(); + + if (cookieValue != null) { + headers.put(COOKIE, cookieValue); + } + if (mIsPrivate) { + headers.put(HIDE_URL_LOGS, "true"); + } + + mMediaPlayer.setDataSource(url, headers); mState = INITIALIZED; mMediaPlayer.prepareAsync(); } catch (IOException e) { diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java index 2bb9da157788..6374b471eadd 100644 --- a/core/java/android/webkit/WebView.java +++ b/core/java/android/webkit/WebView.java @@ -27,7 +27,6 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; -import android.content.res.AssetManager; import android.content.res.Configuration; import android.database.DataSetObserver; import android.graphics.Bitmap; @@ -8104,8 +8103,7 @@ public class WebView extends AbsoluteLayout // nativeCreate sets mNativeClass to a non-zero value String drawableDir = BrowserFrame.getRawResFilename( BrowserFrame.DRAWABLEDIR, mContext); - AssetManager am = mContext.getAssets(); - nativeCreate(msg.arg1, drawableDir, am); + nativeCreate(msg.arg1, drawableDir); if (mDelaySetPicture != null) { setNewPicture(mDelaySetPicture, true); mDelaySetPicture = null; @@ -9140,7 +9138,7 @@ public class WebView extends AbsoluteLayout private native Rect nativeCacheHitNodeBounds(); private native int nativeCacheHitNodePointer(); /* package */ native void nativeClearCursor(); - private native void nativeCreate(int ptr, String drawableDir, AssetManager am); + private native void nativeCreate(int ptr, String drawableDir); private native int nativeCursorFramePointer(); private native Rect nativeCursorNodeBounds(); private native int nativeCursorNodePointer(); diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java index db4df40a43b5..dae118e29f24 100644 --- a/core/java/android/widget/AbsListView.java +++ b/core/java/android/widget/AbsListView.java @@ -637,6 +637,11 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te private boolean mIsAttached; /** + * Track the item count from the last time we handled a data change. + */ + private int mLastHandledItemCount; + + /** * Interface definition for a callback to be invoked when the list or grid * has been scrolled. */ @@ -1829,10 +1834,10 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te // Check if our previous measured size was at a point where we should scroll later. if (mTranscriptMode == TRANSCRIPT_MODE_NORMAL) { final int childCount = getChildCount(); - final int listBottom = getBottom() - getPaddingBottom(); + final int listBottom = getHeight() - getPaddingBottom(); final View lastChild = getChildAt(childCount - 1); final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom; - mForceTranscriptScroll = mFirstPosition + childCount >= mOldItemCount && + mForceTranscriptScroll = mFirstPosition + childCount >= mLastHandledItemCount && lastBottom <= listBottom; } } @@ -4744,6 +4749,8 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te @Override protected void handleDataChanged() { int count = mItemCount; + int lastHandledItemCount = mLastHandledItemCount; + mLastHandledItemCount = mItemCount; if (count > 0) { int newPos; @@ -4765,10 +4772,11 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te return; } final int childCount = getChildCount(); - final int listBottom = getBottom() - getPaddingBottom(); + final int listBottom = getHeight() - getPaddingBottom(); final View lastChild = getChildAt(childCount - 1); final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom; - if (mFirstPosition + childCount >= mOldItemCount && lastBottom <= listBottom) { + if (mFirstPosition + childCount >= lastHandledItemCount && + lastBottom <= listBottom) { mLayoutMode = LAYOUT_FORCE_BOTTOM; return; } diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java index d6cb61dfa708..688d69bd924c 100644 --- a/core/java/android/widget/TextView.java +++ b/core/java/android/widget/TextView.java @@ -9499,8 +9499,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener public boolean isSuggestionsEnabled() { if (!mSuggestionsEnabled) return false; if ((mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) return false; - final int variation = - mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); + final int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT || variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE || diff --git a/core/java/com/android/internal/view/menu/ActionMenuPresenter.java b/core/java/com/android/internal/view/menu/ActionMenuPresenter.java index aaae691667b9..5c4257964403 100644 --- a/core/java/com/android/internal/view/menu/ActionMenuPresenter.java +++ b/core/java/com/android/internal/view/menu/ActionMenuPresenter.java @@ -173,7 +173,8 @@ public class ActionMenuPresenter extends BaseMenuPresenter { public void updateMenuView(boolean cleared) { super.updateMenuView(cleared); - final boolean hasOverflow = mReserveOverflow && mMenu.getNonActionItems().size() > 0; + final boolean hasOverflow = mReserveOverflow && mMenu != null && + mMenu.getNonActionItems().size() > 0; if (hasOverflow) { if (mOverflowButton == null) { mOverflowButton = new OverflowMenuButton(mContext); diff --git a/core/java/com/android/internal/view/menu/BaseMenuPresenter.java b/core/java/com/android/internal/view/menu/BaseMenuPresenter.java index ed9d34a25a90..bec437a744d6 100644 --- a/core/java/com/android/internal/view/menu/BaseMenuPresenter.java +++ b/core/java/com/android/internal/view/menu/BaseMenuPresenter.java @@ -74,20 +74,24 @@ public abstract class BaseMenuPresenter implements MenuPresenter { * Reuses item views when it can */ public void updateMenuView(boolean cleared) { - mMenu.flagActionItems(); - ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems(); - final int itemCount = visibleItems.size(); final ViewGroup parent = (ViewGroup) mMenuView; + if (parent == null) return; + int childIndex = 0; - for (int i = 0; i < itemCount; i++) { - MenuItemImpl item = visibleItems.get(i); - if (shouldIncludeItem(childIndex, item)) { - final View convertView = parent.getChildAt(childIndex); - final View itemView = getItemView(item, convertView, parent); - if (itemView != convertView) { - addItemView(itemView, childIndex); + if (mMenu != null) { + mMenu.flagActionItems(); + ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems(); + final int itemCount = visibleItems.size(); + for (int i = 0; i < itemCount; i++) { + MenuItemImpl item = visibleItems.get(i); + if (shouldIncludeItem(childIndex, item)) { + final View convertView = parent.getChildAt(childIndex); + final View itemView = getItemView(item, convertView, parent); + if (itemView != convertView) { + addItemView(itemView, childIndex); + } + childIndex++; } - childIndex++; } } diff --git a/core/java/com/android/internal/widget/ActionBarView.java b/core/java/com/android/internal/widget/ActionBarView.java index 6b5ea607aaae..78c9ee4bbea2 100644 --- a/core/java/com/android/internal/widget/ActionBarView.java +++ b/core/java/com/android/internal/widget/ActionBarView.java @@ -373,8 +373,7 @@ public class ActionBarView extends AbsActionBarView { mActionMenuPresenter.setExpandedActionViewsExclusive( getResources().getBoolean( com.android.internal.R.bool.action_bar_expanded_action_views_exclusive)); - builder.addMenuPresenter(mActionMenuPresenter); - builder.addMenuPresenter(mExpandedMenuPresenter); + configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != this) { @@ -390,8 +389,7 @@ public class ActionBarView extends AbsActionBarView { mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; - builder.addMenuPresenter(mActionMenuPresenter); - builder.addMenuPresenter(mExpandedMenuPresenter); + configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); if (mSplitView != null) { final ViewGroup oldParent = (ViewGroup) menuView.getParent(); @@ -407,6 +405,18 @@ public class ActionBarView extends AbsActionBarView { mMenuView = menuView; } + private void configPresenters(MenuBuilder builder) { + if (builder != null) { + builder.addMenuPresenter(mActionMenuPresenter); + builder.addMenuPresenter(mExpandedMenuPresenter); + } else { + mActionMenuPresenter.initForMenu(mContext, null); + mExpandedMenuPresenter.initForMenu(mContext, null); + mActionMenuPresenter.updateMenuView(true); + mExpandedMenuPresenter.updateMenuView(true); + } + } + public boolean hasExpandedActionView() { return mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null; @@ -1263,12 +1273,15 @@ public class ActionBarView extends AbsActionBarView { // Make sure the expanded item we have is still there. if (mCurrentExpandedItem != null) { boolean found = false; - final int count = mMenu.size(); - for (int i = 0; i < count; i++) { - final MenuItem item = mMenu.getItem(i); - if (item == mCurrentExpandedItem) { - found = true; - break; + + if (mMenu != null) { + final int count = mMenu.size(); + for (int i = 0; i < count; i++) { + final MenuItem item = mMenu.getItem(i); + if (item == mCurrentExpandedItem) { + found = true; + break; + } } } diff --git a/core/jni/android/graphics/TextLayoutCache.cpp b/core/jni/android/graphics/TextLayoutCache.cpp index 23a4ec741f99..89440c9dc0bd 100644 --- a/core/jni/android/graphics/TextLayoutCache.cpp +++ b/core/jni/android/graphics/TextLayoutCache.cpp @@ -360,31 +360,7 @@ void TextLayoutCacheValue::setupShaperItem(HB_ShaperItem* shaperItem, HB_FontRec shaperItem->item.length = count; shaperItem->item.bidiLevel = isRTL; - ssize_t nextCodePoint = 0; - uint32_t codePoint = utf16_to_code_point(chars, count, &nextCodePoint); - - HB_Script script = code_point_to_script(codePoint); - - if (script == HB_Script_Inherited) { -#if DEBUG_GLYPHS - LOGD("Cannot find a correct script for code point=%d " - " Need to look at the next code points.", codePoint); -#endif - while (script == HB_Script_Inherited && nextCodePoint < count) { - codePoint = utf16_to_code_point(chars, count, &nextCodePoint); - script = code_point_to_script(codePoint); - } - } - - if (script == HB_Script_Inherited) { -#if DEBUG_GLYPHS - LOGD("Cannot find a correct script from the text." - " Need to select a default script depending on the passed text direction."); -#endif - script = isRTL ? HB_Script_Arabic : HB_Script_Common; - } - - shaperItem->item.script = script; + shaperItem->item.script = isRTL ? HB_Script_Arabic : HB_Script_Common; shaperItem->string = chars; shaperItem->stringLength = contextCount; diff --git a/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png b/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png Binary files differindex 2edae8ff8382..1deaad714971 100644 --- a/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png +++ b/core/res/res/drawable-hdpi/day_picker_week_view_dayline_holo.9.png diff --git a/core/res/res/drawable-hdpi/ic_commit.png b/core/res/res/drawable-hdpi/ic_commit.png Binary files differdeleted file mode 100644 index 404051c55688..000000000000 --- a/core/res/res/drawable-hdpi/ic_commit.png +++ /dev/null diff --git a/core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.png b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.png Binary files differnew file mode 100644 index 000000000000..83f36a94cf14 --- /dev/null +++ b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_dark.png diff --git a/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png Binary files differindex b01688fa3225..a3cc21e6ba3d 100644 --- a/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png +++ b/core/res/res/drawable-hdpi/ic_commit_search_api_holo_light.png diff --git a/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png b/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png Binary files differindex a8cfd773cb34..7b750192462e 100644 --- a/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png +++ b/core/res/res/drawable-mdpi/day_picker_week_view_dayline_holo.9.png diff --git a/core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.png b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.png Binary files differnew file mode 100644 index 000000000000..844c99c22f9c --- /dev/null +++ b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_dark.png diff --git a/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png Binary files differindex c048f41ca290..86c170e97b10 100644 --- a/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png +++ b/core/res/res/drawable-mdpi/ic_commit_search_api_holo_light.png diff --git a/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png b/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png Binary files differindex bc6a6e47569b..701a1b24d042 100644 --- a/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png +++ b/core/res/res/drawable-xhdpi/day_picker_week_view_dayline_holo.9.png diff --git a/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.png b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.png Binary files differnew file mode 100644 index 000000000000..d8faf900ae77 --- /dev/null +++ b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_dark.png diff --git a/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png Binary files differindex 7b1054a50869..e7c7280add8f 100644 --- a/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png +++ b/core/res/res/drawable-xhdpi/ic_commit_search_api_holo_light.png diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml index feb78462dadb..9c774f8628e2 100755 --- a/core/res/res/values/strings.xml +++ b/core/res/res/values/strings.xml @@ -225,7 +225,7 @@ <!-- Displayed when a web request failed because there was a connection error. --> <string name="httpErrorConnect">The connection to the server was unsuccessful.</string> <!-- Displayed when a web request failed because there was an input or output error. --> - <string name="httpErrorIO">The server failed to communicate. Try again later.</string> + <string name="httpErrorIO">The server couldn\'t communicate. Try again later.</string> <!-- Displayed when a web request failed because the request timed out --> <string name="httpErrorTimeout">The connection to the server timed out.</string> <!-- Displayed when a web request failed because the site tried to redirect us one too many times --> @@ -2500,10 +2500,10 @@ <!-- Title of the alert when an application has crashed. --> <string name="aerr_title"></string> <!-- Text of the alert that is displayed when an application has crashed. --> - <string name="aerr_application"><xliff:g id="application">%1$s</xliff:g> has stopped by mistake.</string> + <string name="aerr_application">Unfortunately, <xliff:g id="application">%1$s</xliff:g> has stopped.</string> <!-- Text of the alert that is displayed when an application has crashed. --> - <string name="aerr_process">The process <xliff:g id="process">%1$s</xliff:g> has - stopped by mistake.</string> + <string name="aerr_process">Unfortunately, the process <xliff:g id="process">%1$s</xliff:g> has + stopped.</string> <!-- Title of the alert when an application is not responding. --> <string name="anr_title"></string> <!-- Text of the alert that is displayed when an application is not responding. --> @@ -2629,7 +2629,7 @@ <!-- Wi-Fi p2p dialog title--> <string name="wifi_p2p_dialog_title">Wi-Fi Direct</string> <string name="wifi_p2p_turnon_message">Start Wi-Fi Direct operation. This will turn off Wi-Fi client/hotspot operation.</string> - <string name="wifi_p2p_failed_message">Failed to start Wi-Fi Direct</string> + <string name="wifi_p2p_failed_message">Couldn\'t start Wi-Fi Direct</string> <string name="wifi_p2p_pbc_go_negotiation_request_message">Wi-Fi Direct connection setup request from <xliff:g id="p2p_device_address">%1$s</xliff:g>. Click OK to accept. </string> <string name="wifi_p2p_pin_go_negotiation_request_message">Wi-Fi Direct connection setup request from <xliff:g id="p2p_device_address">%1$s</xliff:g>. Enter pin to proceed. </string> <string name="wifi_p2p_pin_display_message">WPS pin <xliff:g id="p2p_wps_pin">%1$s</xliff:g> needs to be entered on the peer device <xliff:g id="p2p_client_address">%2$s</xliff:g> for connection setup to proceed </string> @@ -2728,7 +2728,7 @@ <!-- USB_STORAGE_KILL_STORAGE_USERS dialog message text --> <string name="dlg_confirm_kill_storage_users_text">If you turn on USB storage, some applications you are using will stop and may be unavailable until you turn off USB storage.</string> <!-- USB_STORAGE_ERROR dialog dialog--> - <string name="dlg_error_title">USB operation failed</string> + <string name="dlg_error_title">USB operation unsuccessful</string> <!-- USB_STORAGE_ERROR dialog ok button--> <string name="dlg_ok">OK</string> @@ -2982,9 +2982,9 @@ <!-- Text for progress dialog while erasing SD card [CHAR LIMIT=NONE] --> <string name="progress_erasing" product="default">Erasing SD card...</string> <!-- Text for message to user that an error happened when formatting USB storage [CHAR LIMIT=NONE] --> - <string name="format_error" product="nosdcard">Failed to erase USB storage.</string> + <string name="format_error" product="nosdcard">Couldn\'t erase USB storage.</string> <!-- Text for message to user that an error happened when formatting SD card [CHAR LIMIT=NONE] --> - <string name="format_error" product="default">Failed to erase SD card.</string> + <string name="format_error" product="default">Couldn\'t erase SD card.</string> <!-- Text for message to user that SD card has been removed while in use [CHAR LIMIT=NONE] --> <string name="media_bad_removal">SD card was removed before being unmounted.</string> <!-- Text for message to user USB storage is currently being checked [CHAR LIMIT=NONE] --> diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml index 6278c82d9906..786cdb544f94 100644 --- a/core/res/res/values/themes.xml +++ b/core/res/res/values/themes.xml @@ -329,7 +329,7 @@ please see themes_device_defaults.xml. <item name="searchViewSearchIcon">@android:drawable/ic_search</item> <item name="searchViewGoIcon">@android:drawable/ic_go</item> <item name="searchViewVoiceIcon">@android:drawable/ic_voice_search</item> - <item name="searchViewEditQuery">@android:drawable/ic_commit</item> + <item name="searchViewEditQuery">@android:drawable/ic_commit_search_api_holo_dark</item> <item name="searchViewEditQueryBackground">?attr/selectableItemBackground</item> <item name="searchDialogTheme">@style/Theme.SearchBar</item> diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs index 68c9a9161974..9c3a0bea18e8 100644 --- a/docs/html/guide/guide_toc.cs +++ b/docs/html/guide/guide_toc.cs @@ -244,7 +244,7 @@ </a></li> <li><a href="<?cs var:toroot ?>guide/topics/graphics/opengl.html"> <span class="en">3D with OpenGL</span> - </a></li> + </a><span class="new">updated</span></li> <li><a href="<?cs var:toroot ?>guide/topics/graphics/animation.html"> <span class="en">Property Animation</span> </a></li> diff --git a/docs/html/guide/topics/graphics/opengl.jd b/docs/html/guide/topics/graphics/opengl.jd index cc467f2ce8a1..2edc63d507b3 100644 --- a/docs/html/guide/topics/graphics/opengl.jd +++ b/docs/html/guide/topics/graphics/opengl.jd @@ -8,22 +8,37 @@ parent.link=index.html <h2>In this document</h2> <ol> - <li><a href="#basics">The Basics</a></li> + <li><a href="#basics">The Basics</a> + <ol> + <li><a href="#packages">OpenGL packages</a></li> + </ol> + <li><a href="#manifest">Declaring OpenGL Requirements</a></li> + </li> + <li><a href="#coordinate-mapping">Coordinate Mapping for Drawn Objects</a> + <ol> + <li><a href="#proj-es1">Projection and camera in ES 1.0</a></li> + <li><a href="#proj-es1">Projection and camera in ES 2.0</a></li> + </ol> + </li> <li><a href="#compatibility">OpenGL Versions and Device Compatibility</a> <ol> - <li><a href="#textures">Texture Compression Support</a></li> - <li><a href="#declare-compression">Declaring Use of Compressed Textures</a></li> + <li><a href="#textures">Texture compression support</a></li> + <li><a href="#gl-extension-query">Determining OpenGL Extensions</a></li> </ol> </li> + <li><a href="#choosing-version">Choosing an OpenGL API Version</a></li> </ol> <h2>Key classes</h2> <ol> <li>{@link android.opengl.GLSurfaceView}</li> <li>{@link android.opengl.GLSurfaceView.Renderer}</li> - <li>{@link javax.microedition.khronos.opengles}</li> - <li>{@link android.opengl}</li> </ol> - <h2>Related Samples</h2> + <h2>Related tutorials</h2> + <ol> + <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL ES 1.0</a></li> + <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL ES 2.0</a></li> + </ol> + <h2>Related samples</h2> <ol> <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ GLSurfaceViewActivity.html">GLSurfaceViewActivity</a></li> @@ -46,11 +61,11 @@ GLSurfaceView</a></li> </div> <p>Android includes support for high performance 2D and 3D graphics with the Open Graphics Library -(OpenGL) API—specifically, the OpenGL ES API. OpenGL is a cross-platform graphics API that -specifies a standard software interface for 3D graphics processing hardware. OpenGL ES is a flavor -of the OpenGL specification intended for embedded devices. The OpenGL ES 1.0 and 1.1 API -specifications have been supported since Android 1.0. Beginning with Android 2.2 (API -Level 8), the framework supports the OpenGL ES 2.0 API specification.</p> +(OpenGL), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics API that specifies a +standard software interface for 3D graphics processing hardware. OpenGL ES is a flavor of the OpenGL +specification intended for embedded devices. The OpenGL ES 1.0 and 1.1 API specifications have been +supported since Android 1.0. Beginning with Android 2.2 (API Level 8), the framework supports the +OpenGL ES 2.0 API specification.</p> <p class="note"><b>Note:</b> The specific API provided by the Android framework is similar to the J2ME JSR239 OpenGL ES API, but is not identical. If you are familiar with J2ME JSR239 @@ -71,18 +86,19 @@ understanding how to implement these classes in an activity should be your first </p> <dl> - <dt>{@link android.opengl.GLSurfaceView}</dt> - <dd>This class is a container on which you can draw and manipulate objects using OpenGL API calls. - This class is similar in function to a {@link android.view.SurfaceView}, except that it is - specifically for use with OpenGL. You can use this class by simply creating an instance of - {@link android.opengl.GLSurfaceView} and adding your + <dt><strong>{@link android.opengl.GLSurfaceView}</strong></dt> + <dd>This class is a {@link android.view.View} where you can draw and manipulate objects using + OpenGL API calls and is similar in function to a {@link android.view.SurfaceView}. You can use + this class by creating an instance of {@link android.opengl.GLSurfaceView} and adding your {@link android.opengl.GLSurfaceView.Renderer Renderer} to it. However, if you want to capture touch screen events, you should extend the {@link android.opengl.GLSurfaceView} class to - implement the touch listeners, as shown in the <a + implement the touch listeners, as shown in OpenGL Tutorials for + <a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html#touch">ES 1.0</a>, + <a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html#touch">ES 2.0</a> and the <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/TouchRotateActivity .html">TouchRotateActivity</a> sample.</dd> - <dt>{@link android.opengl.GLSurfaceView.Renderer}</dt> + <dt><strong>{@link android.opengl.GLSurfaceView.Renderer}</strong></dt> <dd>This interface defines the methods required for drawing graphics in an OpenGL {@link android.opengl.GLSurfaceView}. You must provide an implementation of this interface as a separate class and attach it to your {@link android.opengl.GLSurfaceView} instance using @@ -119,6 +135,7 @@ href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics </dd> </dl> +<h3 id="packages">OpenGL packages</h3> <p>Once you have established a container view for OpenGL using {@link android.opengl.GLSurfaceView} and {@link android.opengl.GLSurfaceView.Renderer}, you can begin calling OpenGL APIs using the following classes:</p> @@ -126,8 +143,17 @@ calling OpenGL APIs using the following classes:</p> <ul> <li>OpenGL ES 1.0/1.1 API Packages <ul> + <li>{@link android.opengl} - This package provides a static interface to the OpenGL ES +1.0/1.1 classes and better performance than the javax.microedition.khronos package interfaces. + <ul> + <li>{@link android.opengl.GLES10}</li> + <li>{@link android.opengl.GLES10Ext}</li> + <li>{@link android.opengl.GLES11}</li> + <li>{@link android.opengl.GLES10Ext}</li> + </ul> + </li> <li>{@link javax.microedition.khronos.opengles} - This package provides the standard -implementation of OpenGL ES 1.0 and 1.1. +implementation of OpenGL ES 1.0/1.1. <ul> <li>{@link javax.microedition.khronos.opengles.GL10}</li> <li>{@link javax.microedition.khronos.opengles.GL10Ext}</li> @@ -136,42 +162,243 @@ implementation of OpenGL ES 1.0 and 1.1. <li>{@link javax.microedition.khronos.opengles.GL11ExtensionPack}</li> </ul> </li> - <li>{@link android.opengl} - This package provides a static interface to the OpenGL classes - above. These interfaces were added with Android 1.6 (API Level 4). - <ul> - <li>{@link android.opengl.GLES10}</li> - <li>{@link android.opengl.GLES10Ext}</li> - <li>{@link android.opengl.GLES11}</li> - <li>{@link android.opengl.GLES10Ext}</li> - </ul> - </li> </ul> </li> <li>OpenGL ES 2.0 API Class <ul> - <li>{@link android.opengl.GLES20 android.opengl.GLES20}</li> + <li>{@link android.opengl.GLES20 android.opengl.GLES20} - This package provides the +interface to OpenGL ES 2.0 and is available starting with Android 2.2 (API Level 8).</li> </ul> </li> </ul> +<p>If you'd like to start building an app with OpenGL right away, have a look at the tutorials for +<a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL ES 1.0</a> or +<a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL ES 2.0</a>! +</p> + +<h2 id="manifest">Declaring OpenGL Requirements</h2> +<p>If your application uses OpenGL features that are not available on all devices, you must include +these requirements in your <a +href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a></code> file. +Here are the most common OpenGL manifest declarations:</p> + +<ul> + <li><strong>OpenGL ES version requirements</strong> - If your application only supports OpenGL ES +2.0, you must declare that requirement by adding the following settings to your manifest as +shown below. + +<pre> + <!-- Tell the system this app requires OpenGL ES 2.0. --> + <uses-feature android:glEsVersion="0x00020000" android:required="true" /> +</pre> + + <p>Adding this declaration causes the Android Market to restrict your application from being + installed on devices that do not support OpenGL ES 2.0.</p> + </li> + <li><strong>Texture compression requirements</strong> - If your application uses texture +compression formats that are not supported by all devices, you must declare them in your manifest +file using <a href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html"> +{@code <supports-gl-texture>}</a>. For more information about available texture compression +formats, see <a href="#textures">Texture compression support</a>. + +<p>Declaring texture compression requirements in your manifest hides your application from users +with devices that do not support at least one of your declared compression types. For more +information on how Android Market filtering works for texture compressions, see the <a +href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html#market-texture-filtering"> +Android Market and texture compression filtering</a> section of the {@code +<supports-gl-texture>} documentation.</p> + </li> +</ul> + + +<h2 id="coordinate-mapping">Coordinate Mapping for Drawn Objects</h2> + +<p>One of the basic problems in displaying graphics on Android devices is that their screens can +vary in size and shape. OpenGL assumes a square, uniform coordinate system and, by default, happily +draws those coordinates onto your typically non-square screen as if it is perfectly square.</p> + +<img src="{@docRoot}images/opengl/coordinates.png"> +<p class="img-caption"> + <strong>Figure 1.</strong> Default OpenGL coordinate system (left) mapped to a typical Android +device screen (right). +</p> + +<p>The illustration above shows the uniform coordinate system assumed for an OpenGL frame on the +left, and how these coordinates actually map to a typical device screen in landscape orientation +on the right. To solve this problem, you can apply OpenGL projection modes and camera views to +transform coordinates so your graphic objects have the correct proportions on any display.</p> + +<p>In order to apply projection and camera views, you create a projection matrix and a camera view +matrix and apply them to the OpenGL rendering pipeline. The projection matrix recalculates the +coordinates of your graphics so that they map correctly to Android device screens. The camera view +matrix creates a transformation that renders objects from a specific eye position.</p> + +<h3 id="proj-es1">Projection and camera view in OpenGL ES 1.0</h3> +<p>In the ES 1.0 API, you apply projection and camera view by creating each matrix and then +adding them to the OpenGL environment.</p> + +<ol> +<li><strong>Projection matrix</strong> - Create a projection matrix using the geometry of the +device screen in order to recalculate object coordinates so they are drawn with correct proportions. +The following example code demonstrates how to modify the {@code onSurfaceChanged()} method of a +{@link android.opengl.GLSurfaceView.Renderer} implementation to create a projection matrix based on +the screen's aspect ratio and apply it to the OpenGL rendering environment. + +<pre> + public void onSurfaceChanged(GL10 gl, int width, int height) { + gl.glViewport(0, 0, width, height); + + // make adjustments for screen ratio + float ratio = (float) width / height; + gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode + gl.glLoadIdentity(); // reset the matrix to its default state + gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix + } +</pre> +</li> + +<li><strong>Camera transformation matrix</strong> - Once you have adjusted the coordinate system +using a projection matrix, you must also apply a camera view. The following example code shows how +to modify the {@code onDrawFrame()} method of a {@link android.opengl.GLSurfaceView.Renderer} +implementation to apply a model view and use the {@link +android.opengl.GLU#gluLookAt(javax.microedition.khronos.opengles.GL10, float, float, float, float, +float, float, float, float, float) GLU.gluLookAt()} utility to create a viewing tranformation which +simulates a camera position. + +<pre> + public void onDrawFrame(GL10 gl) { + ... + // Set GL_MODELVIEW transformation mode + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); // reset the matrix to its default state + + // When using GL_MODELVIEW, you must set the camera view + GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); + ... + } +</pre> +</li> +</ol> + +<p>For a complete example of how to apply projection and camera views with OpenGL ES 1.0, see the <a +href="{@docRoot}resources/tutorials/opengl/opengl-es10.html#projection-and-views">OpenGL ES 1.0 +tutorial</a>.</p> + + +<h3 id="proj-es2">Projection and camera view in OpenGL ES 2.0</h3> +<p>In the ES 2.0 API, you apply projection and camera view by first adding a matrix member to +the vertex shaders of your graphics objects. With this matrix member added, you can then +generate and apply projection and camera viewing matrices to your objects.</p> + +<ol> +<li><strong>Add matrix to vertex shaders</strong> - Create a variable for the view projection matrix +and include it as a multiplier of the shader's position. In the following example vertex shader +code, the included {@code uMVPMatrix} member allows you to apply projection and camera viewing +matrices to the coordinates of objects that use this shader. + +<pre> + private final String vertexShaderCode = + + // This matrix member variable provides a hook to manipulate + // the coordinates of objects that use this vertex shader + "uniform mat4 uMVPMatrix; \n" + + + "attribute vec4 vPosition; \n" + + "void main(){ \n" + + + // the matrix must be included as part of gl_Position + " gl_Position = uMVPMatrix * vPosition; \n" + + + "} \n"; +</pre> + <p class="note"><strong>Note:</strong> The example above defines a single transformation matrix +member in the vertex shader into which you apply a combined projection matrix and camera view +matrix. Depending on your application requirements, you may want to define separate projection +matrix and camera viewing matrix members in your vertex shaders so you can change them +independently.</p> +</li> +<li><strong>Access the shader matrix</strong> - After creating a hook in your vertex shaders to +apply projection and camera view, you can then access that variable to apply projection and +camera viewing matrices. The following code shows how to modify the {@code onSurfaceCreated()} +method of a {@link android.opengl.GLSurfaceView.Renderer} implementation to access the matrix +variable defined in the vertex shader above. + +<pre> + public void onSurfaceCreated(GL10 unused, EGLConfig config) { + ... + muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); + ... + } +</pre> +</li> +<li><strong>Create projection and camera viewing matrices</strong> - Generate the projection and +viewing matrices to be applied the graphic objects. The following example code shows how to modify +the {@code onSurfaceCreated()} and {@code onSurfaceChanged()} methods of a {@link +android.opengl.GLSurfaceView.Renderer} implementation to create camera view matrix and a projection +matrix based on the screen aspect ratio of the device. + +<pre> + public void onSurfaceCreated(GL10 unused, EGLConfig config) { + ... + // Create a camera view matrix + Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); + } + + public void onSurfaceChanged(GL10 unused, int width, int height) { + GLES20.glViewport(0, 0, width, height); + + float ratio = (float) width / height; + + // create a projection matrix from device screen geometry + Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7); + } +</pre> +</li> + +<li><strong>Apply projection and camera viewing matrices</strong> - To apply the projection and +camera view transformations, multiply the matrices together and then set them into the vertex +shader. The following example code shows how modify the {@code onDrawFrame()} method of a {@link +android.opengl.GLSurfaceView.Renderer} implementation to combine the projection matrix and camera +view created in the code above and then apply it to the graphic objects to be rendered by OpenGL. + +<pre> + public void onDrawFrame(GL10 unused) { + ... + // Combine the projection and camera view matrices + Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0); + + // Apply the combined projection and camera view transformations + GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); + + // Draw objects + ... + } +</pre> +</li> +</ol> +<p>For a complete example of how to apply projection and camera view with OpenGL ES 2.0, see the <a +href="{@docRoot}resources/tutorials/opengl/opengl-es20.html#projection-and-views">OpenGL ES 2.0 +tutorial</a>.</p> + + <h2 id="compatibility">OpenGL Versions and Device Compatibility</h2> -<p> - The OpenGL ES 1.0 and 1.1 API specifications have been supported since Android 1.0. +<p>The OpenGL ES 1.0 and 1.1 API specifications have been supported since Android 1.0. Beginning with Android 2.2 (API Level 8), the framework supports the OpenGL ES 2.0 API specification. OpenGL ES 2.0 is supported by most Android devices and is recommended for new applications being developed with OpenGL. For information about the relative number of Android-powered devices that support a given version of OpenGL ES, see the <a href="{@docRoot}resources/dashboard/opengl.html">OpenGL ES Versions Dashboard</a>.</p> + <h3 id="textures">Texture compression support</h3> <p>Texture compression can significantly increase the performance of your OpenGL application by reducing memory requirements and making more efficient use of memory bandwidth. The Android framework provides support for the ETC1 compression format as a standard feature, including a {@link -android.opengl.ETC1Util} utility class and the {@code etc1tool} compression tool (located in your -Android SDK at {@code <sdk>/tools/}).</p> - -<p>For an example of an Android application that uses texture compression, see the <a +android.opengl.ETC1Util} utility class and the {@code etc1tool} compression tool (located in the +Android SDK at {@code <sdk>/tools/}). For an example of an Android application that uses +texture compression, see the <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ CompressedTextureActivity.html">CompressedTextureActivity</a> code sample. </p> @@ -184,34 +411,110 @@ alpha channel. If your application requires textures with an alpha channel, you investigate other texture compression formats available on your target devices.</p> <p>Beyond the ETC1 format, Android devices have varied support for texture compression based on -their GPU chipsets. You should investigate texture compression support on the the devices you are -are targeting to determine what compression types your application should support.</p> +their GPU chipsets and OpenGL implementations. You should investigate texture compression support on +the the devices you are are targeting to determine what compression types your application should +support. In order to determine what texture formats are supported on a given device, you must <a +href="#gl-extension-query">query the device</a> and review the <em>OpenGL extension names</em>, +which identify what texture compression formats (and other OpenGL features) are supported by the +device. Some commonly supported texture compression formats are as follows:</p> -<p>To determine if texture compression formats other than ETC1 are supported on a particular -device:</p> +<ul> + <li><strong>ATITC (ATC)</strong> - ATI texture compression (ATITC or ATC) is available on a +wide variety of devices and supports fixed rate compression for RGB textures with and without +an alpha channel. This format may be represented by several OpenGL extension names, for example: + <ul> + <li>{@code GL_AMD_compressed_ATC_texture}</li> + <li>{@code GL_ATI_texture_compression_atitc}</li> + </ul> + </li> + <li><strong>PVRTC</strong> - PowerVR texture compression (PVRTC) is available on a wide +variety of devices and supports 2-bit and 4-bit per pixel textures with or without an alpha channel. +This format is represented by the following OpenGL extension name: + <ul> + <li>{@code GL_IMG_texture_compression_pvrtc}</li> + </ul> + </li> + <li><strong>S3TC (DXT<em>n</em>/DXTC)</strong> - S3 texture compression (S3TC) has several +format variations (DXT1 to DXT5) and is less widely available. The format supports RGB textures with +4-bit alpha or 8-bit alpha channels. This format may be represented by several OpenGL extension +names, for example: + <ul> + <li>{@code GL_OES_texture_compression_S3TC}</li> + <li>{@code GL_EXT_texture_compression_s3tc}</li> + <li>{@code GL_EXT_texture_compression_dxt1}</li> + <li>{@code GL_EXT_texture_compression_dxt3}</li> + <li>{@code GL_EXT_texture_compression_dxt5}</li> + </ul> + </li> + <li><strong>3DC</strong> - 3DC texture compression (3DC) is a less widely available format that +supports RGB textures with an an alpha channel. This format is represented by the following OpenGL +extension name:</li> + <ul> + <li>{@code GL_AMD_compressed_3DC_texture}</li> + </ul> +</ul> + +<p class="warning"><strong>Warning:</strong> These texture compression formats are <em>not +supported</em> on all devices. Support for these formats can vary by manufacturer and device. For +information on how to determine what texture compression formats are on a particular device, see +the next section. +</p> + +<p class="note"><strong>Note:</strong> Once you decide which texture compression formats your +application will support, make sure you declare them in your manifest using <a +href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html"><supports-gl-texture> +</a>. Using this declaration enables filtering by external services such as Android Market, so that +your app is installed only on devices that support the formats your app requires. For details, see +<a +href="{@docRoot}guide/topics/graphics/opengl.html#manifest">OpenGL manifest declarations</a>.</p> + +<h3 id="gl-extension-query">Determining OpenGL extensions</h3> +<p>Implementations of OpenGL vary by Android device in terms of the extensions to the OpenGL ES API +that are supported. These extensions include texture compressions, but typically also include other +extensions to the OpenGL feature set.</p> + +<p>To determine what texture compression formats, and other OpenGL extensions, are supported on a +particular device:</p> <ol> <li>Run the following code on your target devices to determine what texture compression formats are supported: <pre> String extensions = javax.microedition.khronos.opengles.GL10.glGetString(GL10.GL_EXTENSIONS); </pre> - <p class="warning"><b>Warning:</b> The results of this call vary by device! You must run this -call on several target devices to determine what compression types are commonly supported on -your target devices.</p> + <p class="warning"><b>Warning:</b> The results of this call <em>vary by device!</em> You +must run this call on several target devices to determine what compression types are commonly +supported.</p> </li> - <li>Review the output of this method to determine what extensions are supported on the + <li>Review the output of this method to determine what OpenGL extensions are supported on the device.</li> </ol> -<h3 id="declare-compression">Declaring compressed textures</h3> -<p>Once you have decided which texture compression types your application will support, you -must declare them in your manifest file using <a -href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html"> -<supports-gl-texture></a>. Declaring this information in your manifest file hides your -application from users with devices that do not support at least one of your declared -compression types. For more information on how Android Market filtering works for texture -compressions, see the <a -href="{@docRoot}guide/topics/manifest/supports-gl-texture-element.html#market-texture-filtering"> -Android Market and texture compression filtering</a> section of the {@code -<supports-gl-texture>} documentation. +<h2 id="choosing-version">Choosing an OpenGL API Version</h2> + +<p>OpenGL ES API version 1.0 (and the 1.1 extensions) and version 2.0 both provide high +performance graphics interfaces for creating 3D games, visualizations and user interfaces. Graphics +programming for the OpenGL ES 1.0/1.1 API versus ES 2.0 differs significantly, and so developers +should carefully consider the following factors before starting development with either API:</p> + +<ul> + <li><strong>Performance</strong> - In general, OpenGL ES 2.0 provides faster graphics performance +than the ES 1.0/1.1 APIs. However, the performance difference can vary depending on the Android +device your OpenGL application is running on, due to differences in the implementation of the OpenGL +graphics pipeline.</li> + <li><strong>Device Compatibility</strong> - Developers should consider the types of devices, +Android versions and the OpenGL ES versions available to their customers. For more information +on OpenGL compatibility across devices, see the <a href="#compatibility">OpenGL Versions and Device +Compatibility</a> section.</li> + <li><strong>Coding Convenience</strong> - The OpenGL ES 1.0/1.1 API provides a fixed function +pipeline and convenience functions which are not available in the ES 2.0 API. Developers who are new +to OpenGL may find coding for OpenGL ES 1.0/1.1 faster and more convenient.</li> + <li><strong>Graphics Control</strong> - The OpenGL ES 2.0 API provides a higher degree +of control by providing a fully programmable pipeline through the use of shaders. With more +direct control of the graphics processing pipeline, developers can create effects that would be +very difficult to generate using the 1.0/1.1 API.</li> +</ul> + +<p>While performance, compatibility, convenience, control and other factors may influence your +decision, you should pick an OpenGL API version based on what you think provides the best experience +for your users.</p> diff --git a/docs/html/images/opengl/coordinates.png b/docs/html/images/opengl/coordinates.png Binary files differnew file mode 100644 index 000000000000..7180cd5cecf3 --- /dev/null +++ b/docs/html/images/opengl/coordinates.png diff --git a/docs/html/images/opengl/helloopengl-es10-1.png b/docs/html/images/opengl/helloopengl-es10-1.png Binary files differnew file mode 100644 index 000000000000..9aa2376ed720 --- /dev/null +++ b/docs/html/images/opengl/helloopengl-es10-1.png diff --git a/docs/html/images/opengl/helloopengl-es10-2.png b/docs/html/images/opengl/helloopengl-es10-2.png Binary files differnew file mode 100644 index 000000000000..cdfd9c70539a --- /dev/null +++ b/docs/html/images/opengl/helloopengl-es10-2.png diff --git a/docs/html/images/opengl/helloopengl-es20-1.png b/docs/html/images/opengl/helloopengl-es20-1.png Binary files differnew file mode 100644 index 000000000000..1f76c22cb23b --- /dev/null +++ b/docs/html/images/opengl/helloopengl-es20-1.png diff --git a/docs/html/images/opengl/helloopengl-es20-2.png b/docs/html/images/opengl/helloopengl-es20-2.png Binary files differnew file mode 100644 index 000000000000..0fbbe60010e3 --- /dev/null +++ b/docs/html/images/opengl/helloopengl-es20-2.png diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js index 0fc10bf746ce..720e14314c2a 100644 --- a/docs/html/resources/resources-data.js +++ b/docs/html/resources/resources-data.js @@ -782,6 +782,26 @@ var ANDROID_RESOURCES = [ } }, { + tags: ['tutorial', 'gl', 'new'], + path: 'tutorials/opengl/opengl-es10.html', + title: { + en: 'OpenGL ES 1.0' + }, + description: { + en: 'The basics of implementing an application using the OpenGL ES 1.0 APIs.' + } + }, + { + tags: ['tutorial', 'gl', 'new'], + path: 'tutorials/opengl/opengl-es20.html', + title: { + en: 'OpenGL ES 2.0' + }, + description: { + en: 'The basics of implementing an application using the OpenGL ES 2.0 APIs.' + } + }, + { tags: ['tutorial', 'testing'], path: 'tutorials/testing/helloandroid_test.html', title: { diff --git a/docs/html/resources/tutorials/opengl/opengl-es10.jd b/docs/html/resources/tutorials/opengl/opengl-es10.jd new file mode 100644 index 000000000000..40304fd41521 --- /dev/null +++ b/docs/html/resources/tutorials/opengl/opengl-es10.jd @@ -0,0 +1,532 @@ +page.title=OpenGL ES 1.0 +parent.title=Tutorials +parent.link=../../browser.html?tag=tutorial +@jd:body + + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#creating">Create an Activity with GLSurfaceView</a></li> + <li> + <a href="#drawing">Draw a Shape on GLSurfaceView</a> + <ol> + <li><a href="#define-triangle">Define a Triangle</a></li> + <li><a href="#draw-triangle">Draw the Triangle</a></li> + </ol> + </li> + <li><a href="#projection-and-views">Apply Projection and Camera Views</a></li> + <li><a href="#motion">Add Motion</a></li> + <li><a href="#touch">Respond to Touch Events</a></li> + </ol> + <h2 id="code-samples-list">Related Samples</h2> + <ol> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +index.html">API Demos - graphics</a></li> + <li><a + href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +GLSurfaceViewActivity.html">OpenGL ES 1.0 Sample</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +TouchRotateActivity.html">TouchRotateActivity</a></li> + </ol> + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a></li> + <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL +ES 2.0</a></li> + </ol> + </div> + </div> + +<p>This tutorial shows you how to create a simple Android application that uses the OpenGL ES 1.0 +API to perform some basic graphics operations. You'll learn how to:</p> + +<ul> + <li>Create an activity using {@link android.opengl.GLSurfaceView} and {@link +android.opengl.GLSurfaceView.Renderer}</li> + <li>Create and draw a graphic object</li> + <li>Define a projection to correct for screen geometry</li> + <li>Define a camera view</li> + <li>Rotate a graphic object</li> + <li>Make graphics touch-interactive</li> +</ul> + +<p>The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should +carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your +needs. For more information, see +<a href="{@docRoot}guide/topics/graphics/opengl.html#choosing-version">Choosing an OpenGL API +Version</a>. If you would prefer to use OpenGL ES 2.0, see the <a +href="{@docRoot}resources/tutorials/opengl/opengl-es20.jd">OpenGL ES 2.0 tutorial</a>.</p> + +<p>Before you start, you should understand how to create a basic Android application. If you do not +know how to create an app, follow the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello +World Tutorial</a> to familiarize yourself with the process.</p> + +<h2 id="creating">Create an Activity with GLSurfaceView</h2> + +<p>To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a +{@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main +view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer} +controls what is drawn within that view. (For more information about these classes, see the <a +href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.)</p> + +<p>To create an activity using {@code GLSurfaceView}:</p> + +<ol> + <li>Start a new Android project that targets Android 1.6 (API Level 4) or higher. + </li> + <li>Name the project <strong>HelloOpenGLES10</strong> and make sure it includes an activity called +{@code HelloOpenGLES10}. + </li> + <li>Modify the {@code HelloOpenGLES10} class as follows: +<pre> +package com.example.android.apis.graphics; + +import android.app.Activity; +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Bundle; + +public class HelloOpenGLES10 extends Activity { + + private GLSurfaceView mGLView; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Create a GLSurfaceView instance and set it + // as the ContentView for this Activity. + mGLView = new HelloOpenGLES10SurfaceView(this); + setContentView(mGLView); + } + + @Override + protected void onPause() { + super.onPause(); + // The following call pauses the rendering thread. + // If your OpenGL application is memory intensive, + // you should consider de-allocating objects that + // consume significant memory here. + mGLView.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + // The following call resumes a paused rendering thread. + // If you de-allocated graphic objects for onPause() + // this is a good place to re-allocate them. + mGLView.onResume(); + } +} + +class HelloOpenGLES10SurfaceView extends GLSurfaceView { + + public HelloOpenGLES10SurfaceView(Context context){ + super(context); + + // Set the Renderer for drawing on the GLSurfaceView + setRenderer(new HelloOpenGLES10Renderer()); + } +} +</pre> + <p class="note"><strong>Note:</strong> You will get a compile error for the {@code +HelloOpenGLES10Renderer} class reference. That's expected; you will fix this error in the next step. + </p> + + <p>As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its +view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its +work.</p> + + <p>The {@code HelloOpenGLES10SurfaceView} class in this example code above is just a thin wrapper +for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this +example. However, if you want your application to monitor and respond to touch screen +events—and we are guessing you do—you must extend {@link android.opengl.GLSurfaceView} +to add touch event listeners, which you will learn how to do in the <a href="#touch">Reponding to +Touch Events</a> section.</p> + + <p>In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an +implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create +a renderer class to complete this OpenGL application.</p> + </li> + + <li>Create a new file for the following class {@code HelloOpenGLES10Renderer}, which implements +the {@link android.opengl.GLSurfaceView.Renderer} interface: + +<pre> +package com.example.android.apis.graphics; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.opengl.GLSurfaceView; + +public class HelloOpenGLES10Renderer implements GLSurfaceView.Renderer { + + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + // Set the background frame color + gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + } + + public void onDrawFrame(GL10 gl) { + // Redraw background color + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + } + + public void onSurfaceChanged(GL10 gl, int width, int height) { + gl.glViewport(0, 0, width, height); + } + +} +</pre> + <p>This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the +code structure needed to use OpenGL drawing methods: +<ul> + <li>{@link + android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, + javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the +{@link android.opengl.GLSurfaceView} +environment.</li> + <li>{@link + android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10) + onDrawFrame()} is called for each redraw of the {@link +android.opengl.GLSurfaceView}.</li> + <li>{@link + android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10, + int, int) onSurfaceChanged()} is called if the geometry of the {@link +android.opengl.GLSurfaceView} changes, for example when the device's screen orientation +changes.</li> +</ul> + </p> + <p>For more information about these methods, see the <a +href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document. +</p> + </li> +</ol> + +<p>The code example above creates a simple Android application that displays a grey screen using +OpenGL ES 1.0 calls. While this application does not do anything very interesting, by creating these +classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES +1.0.</p> + +<p>If you are familiar with the OpenGL ES APIs, these classes should give you enough information +to use the OpenGL ES 1.0 API and create graphics. However, if you need a bit more help getting +started with OpenGL, head on to the next sections for a few more hints.</p> + +<h2 id="drawing">Draw a Shape on GLSurfaceView</h2> + +<p>Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to +draw something with it. This section shows you how to define and draw a triangle.</p> + +<h3 id="define-triangle">Define a Triangle</h3> + +<p>OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you + can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to + define a vertex array for the coordinates.</p> + +<p>By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of + the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top right corner of the frame and +[-1,-1,0] is bottom left corner of the frame.</p> + +<p>To define a vertex array for a triangle:</p> + +<ol> + <li>In your {@code HelloOpenGLES10Renderer} class, add new member variable to contain the +vertices of a triangle shape: +<pre> + private FloatBuffer triangleVB; +</pre> + </li> + + <li>Create a method, {@code initShapes()} which populates this member variable: +<pre> + private void initShapes(){ + + float triangleCoords[] = { + // X, Y, Z + -0.5f, -0.25f, 0, + 0.5f, -0.25f, 0, + 0.0f, 0.559016994f, 0 + }; + + // initialize vertex Buffer for triangle + ByteBuffer vbb = ByteBuffer.allocateDirect( + // (# of coordinate values * 4 bytes per float) + triangleCoords.length * 4); + vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order + triangleVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer + triangleVB.put(triangleCoords); // add the coordinates to the FloatBuffer + triangleVB.position(0); // set the buffer to read the first coordinate + + } +</pre> + <p>This method defines a two-dimensional triangle with three equal sides.</p> + </li> + <li>Modify your {@code onSurfaceCreated()} method to initialize your triangle: + <pre> + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + + // Set the background frame color + gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + + // initialize the triangle vertex array + initShapes(); + } +</pre> + <p class="caution"><strong>Caution:</strong> Shapes and other static objects should be initialized + once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the + new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects + for every frame redraw and slows down your application. + </p> + </li> + +</ol> + +<p>You have now defined a triangle shape, but if you run the application, nothing appears. What?! +You also have to tell OpenGL to draw the triangle, which you'll do in the next section. +</p> + + +<h3 id="draw-triangle">Draw the Triangle</h3> + +<p>Before you can draw your triangle, you must tell OpenGL that you are using vertex arrays. After +that setup step, you can call the drawing APIs to display the triangle.</p> + +<p>To draw the triangle:</p> + +<ol> + <li>Add the {@code glEnableClientState()} method to the end of {@code onSurfaceCreated()} to +enable vertex arrays. +<pre> + // Enable use of vertex arrays + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); +</pre> + <p>At this point, you are ready to draw the triangle object in the OpenGL view.</p> + </li> + + <li>Add the following code to the end of your {@code onDrawFrame()} method to draw the triangle. +<pre> + // Draw the triangle + gl.glColor4f(0.63671875f, 0.76953125f, 0.22265625f, 0.0f); + gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVB); + gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); +</pre> + </li> + <li id="squashed-triangle">Run the app! Your application should look something like this: + </li> +</ol> + +<img src="{@docRoot}images/opengl/helloopengl-es10-1.png"> +<p class="img-caption"> + <strong>Figure 1.</strong> Triangle drawn without a projection or camera view. +</p> + +<p>There are a few problems with this example. First of all, it is not going to impress your +friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen +orientation of the device. The reason the shape is skewed is due to the fact that the object is +being rendered in a frame which is not perfectly square. You'll fix that problem using a projection +and camera view in the next section.</p> + +<p>Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in +exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the +<a href="#motion">Add Motion</a> section, you'll make this shape rotate and justify +this use of processing power.</p> + +<h2 id="projection-and-views">Apply Projection and Camera View</h2> + +<p>One of the basic problems in displaying graphics is that Android device displays are typically +not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate +system onto your typically non-square screen. To solve this problem, you can apply an OpenGL +projection mode and camera view (eye point) to transform the coordinates of your graphic objects +so they have the correct proportions on any display. For more information about OpenGL coordinate +mapping, see <a href="{@docRoot}guide/topics/graphics/opengl.html#coordinate-mapping">Coordinate +Mapping for Drawn Objects</a>.</p> + +<p>To apply projection and camera view transformations to your triangle: +</p> +<ol> + <li>Modify your {@code onSurfaceChanged()} method to enable {@link + javax.microedition.khronos.opengles.GL10#GL_PROJECTION GL10.GL_PROJECTION} mode, calculate the + screen ratio and apply the ratio as a transformation of the object coordinates. +<pre> + public void onSurfaceChanged(GL10 gl, int width, int height) { + gl.glViewport(0, 0, width, height); + + // make adjustments for screen ratio + float ratio = (float) width / height; + gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode + gl.glLoadIdentity(); // reset the matrix to its default state + gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix + } +</pre> + </li> + + <li>Next, modify your {@code onDrawFrame()} method to apply the {@link +javax.microedition.khronos.opengles.GL10#GL_MODELVIEW GL_MODELVIEW} mode and set +a view point using {@link android.opengl.GLU#gluLookAt(javax.microedition.khronos.opengles.GL10, +float, float, float, float, float, float, float, float, float) GLU.gluLookAt()}. +<pre> + public void onDrawFrame(GL10 gl) { + // Redraw background color + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + + // Set GL_MODELVIEW transformation mode + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); // reset the matrix to its default state + + // When using GL_MODELVIEW, you must set the view point + GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); + + // Draw the triangle + ... + } +</pre> + </li> + <li>Run the updated application and you should see something like this:</li> +</ol> + +<img src="{@docRoot}images/opengl/helloopengl-es10-2.png"> +<p class="img-caption"> + <strong>Figure 2.</strong> Triangle drawn with a projection and camera view applied. +</p> + +<p>Now that you have applied this transformation, the triangle has three equal sides, instead of the +<a href="#squashed-triangle">squashed triangle</a> in the earlier version.</p> + +<h2 id="motion">Add Motion</h2> + +<p>While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances +are you want at least <em>some</em> of your objects to move. In this section, you'll add motion to +your triangle by rotating it.</p> + +<p>To add rotation to your triangle:</p> +<ol> + <li>Modify your {@code onDrawFrame()} method to rotate the triangle object: +<pre> + public void onDrawFrame(GL10 gl) { + ... + // When using GL_MODELVIEW, you must set the view point + GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); + + // Create a rotation for the triangle + long time = SystemClock.uptimeMillis() % 4000L; + float angle = 0.090f * ((int) time); + gl.glRotatef(angle, 0.0f, 0.0f, 1.0f); + + // Draw the triangle + ... + } +</pre> + </li> + <li>Run the application and your triangle should rotate around its center.</li> +</ol> + + +<h2 id="touch">Respond to Touch Events</h2> +<p>Making objects move according to a preset program like the rotating triangle is useful for +getting some attention, but what if you want to have users interact with your OpenGL graphics? In +this section, you'll learn how listen for touch events to let users interact with objects in your +{@code HelloOpenGLES10SurfaceView}.</p> + +<p>The key to making your OpenGL application touch interactive is expanding your implementation of +{@link android.opengl.GLSurfaceView} to override the {@link +android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events. +Before you do that, however, you'll modify the renderer class to expose the rotation angle of the +triangle. Afterwards, you'll modify the {@code HelloOpenGLES10SurfaceView} to process touch events +and pass that data to your renderer.</p> + +<p>To make your triangle rotate in response to touch events:</p> + +<ol> + <li>Modify your {@code HelloOpenGLES10Renderer} class to include a new, public member so that +your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer: +<pre> + public float mAngle; +</pre> + </li> + <li>In your {@code onDrawFrame()} method, comment out the code that generates an angle and +replace the {@code angle} variable with {@code mAngle}. +<pre> + // Create a rotation for the triangle (Boring! Comment this out:) + // long time = SystemClock.uptimeMillis() % 4000L; + // float angle = 0.090f * ((int) time); + + // Use the mAngle member as the rotation value + gl.glRotatef(mAngle, 0.0f, 0.0f, 1.0f); +</pre> + </li> + <li>In your {@code HelloOpenGLES10SurfaceView} class, add the following member variables. +<pre> + private final float TOUCH_SCALE_FACTOR = 180.0f / 320; + private HelloOpenGLES10Renderer mRenderer; + private float mPreviousX; + private float mPreviousY; +</pre> + </li> + <li>In the constructor method for {@code HelloOpenGLES10SurfaceView}, set the {@code mRenderer} +member so you have a handle to pass in rotation input and set the render mode to {@link +android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}. +<pre> + public HelloOpenGLES10SurfaceView(Context context){ + super(context); + // set the mRenderer member + mRenderer = new HelloOpenGLES10Renderer(); + setRenderer(mRenderer); + + // Render the view only when there is a change + setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); + } +</pre> + </li> + <li>In your {@code HelloOpenGLES10SurfaceView} class, override the {@link +android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch +events and pass them to your renderer. +<pre> + @Override + public boolean onTouchEvent(MotionEvent e) { + // MotionEvent reports input details from the touch screen + // and other input controls. In this case, you are only + // interested in events where the touch position changed. + + float x = e.getX(); + float y = e.getY(); + + switch (e.getAction()) { + case MotionEvent.ACTION_MOVE: + + float dx = x - mPreviousX; + float dy = y - mPreviousY; + + // reverse direction of rotation above the mid-line + if (y > getHeight() / 2) { + dx = dx * -1 ; + } + + // reverse direction of rotation to left of the mid-line + if (x < getWidth() / 2) { + dy = dy * -1 ; + } + + mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR; + requestRender(); + } + + mPreviousX = x; + mPreviousY = y; + return true; + } +</pre> + <p class="note"><strong>Note:</strong> Touch events return pixel coordinates which <em>are not the +same</em> as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the +highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL +graphic objects, you must translate touch coordinates into OpenGL coordinates.</p> + </li> + <li>Run the application and drag your finger or cursor around the screen to rotate the +triangle.</li> +</ol> +<p>For another example of OpenGL touch event functionality, see <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +TouchRotateActivity.html">TouchRotateActivity</a>.</p>
\ No newline at end of file diff --git a/docs/html/resources/tutorials/opengl/opengl-es20.jd b/docs/html/resources/tutorials/opengl/opengl-es20.jd new file mode 100644 index 000000000000..439f7d5b8631 --- /dev/null +++ b/docs/html/resources/tutorials/opengl/opengl-es20.jd @@ -0,0 +1,652 @@ +page.title=OpenGL ES 2.0 +parent.title=Tutorials +parent.link=../../browser.html?tag=tutorial +@jd:body + + +<div id="qv-wrapper"> + <div id="qv"> + <h2>In this document</h2> + + <ol> + <li><a href="#creating">Create an Activity with GLSurfaceView</a></li> + <li> + <a href="#drawing">Draw a Shape on GLSurfaceView</a> + <ol> + <li><a href="#define-triangle">Define a Triangle</a></li> + <li><a href="#draw-triangle">Draw the Triangle</a></li> + </ol> + </li> + <li><a href="#projection-and-views">Apply Projection and Camera Views</a></li> + <li><a href="#motion">Add Motion</a></li> + <li><a href="#touch">Respond to Touch Events</a></li> + </ol> + <h2 id="code-samples-list">Related Samples</h2> + <ol> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +index.html">API Demos - graphics</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +GLES20Activity.html">OpenGL ES 2.0 Sample</a></li> + <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +TouchRotateActivity.html">TouchRotateActivity</a></li> + </ol> + <h2>See also</h2> + <ol> + <li><a href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a></li> + <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es10.html">OpenGL +ES 1.0</a></li> + </ol> + </div> + </div> + +<p>This tutorial shows you how to create a simple Android application that uses the OpenGL ES 2.0 +API to perform some basic graphics operations. You'll learn how to:</p> + +<ul> + <li>Create an activity using {@link android.opengl.GLSurfaceView} and {@link +android.opengl.GLSurfaceView.Renderer}</li> + <li>Create and draw a graphic object</li> + <li>Define a projection to correct for screen geometry</li> + <li>Define a camera view</li> + <li>Rotate a graphic object</li> + <li>Make graphics touch interactive</li> +</ul> + +<p>The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should +carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your +needs. For more information, see +<a href="{@docRoot}guide/topics/graphics/opengl.html#choosing-version">Choosing an OpenGL API +Version</a>. If you would prefer to use OpenGL ES 1.0, see the <a +href="{@docRoot}resources/tutorials/opengl/opengl-es10.jd">OpenGL ES 1.0 tutorial</a>.</p> + +<p>Before you start, you should understand how to create a basic Android application. If you do not +know how to create an app, follow the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello +World Tutorial</a> to familiarize yourself with the process.</p> + +<p class="caution"><strong>Caution:</strong> OpenGL ES 2.0 <em>is currently not supported</em> by +the Android Emulator. You must have a physical test device running Android 2.2 (API Level 8) or +higher in order to run and test the example code in this tutorial.</p> + +<h2 id="creating">Create an Activity with GLSurfaceView</h2> + +<p>To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a +{@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main +view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer} +controls what is drawn within that view. (For more information about these classes, see the <a +href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.)</p> + +<p>To create an activity using {@code GLSurfaceView}:</p> + +<ol> + <li>Start a new Android project that targets Android 2.2 (API Level 8) or higher. + </li> + <li>Name the project <strong>HelloOpenGLES20</strong> and make sure it includes an activity called +{@code HelloOpenGLES20}. + </li> + <li>Modify the {@code HelloOpenGLES20} class as follows: +<pre> +package com.example.android.apis.graphics; + +import android.app.Activity; +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Bundle; + +public class HelloOpenGLES20 extends Activity { + + private GLSurfaceView mGLView; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Create a GLSurfaceView instance and set it + // as the ContentView for this Activity + mGLView = new HelloOpenGLES20SurfaceView(this); + setContentView(mGLView); + } + + @Override + protected void onPause() { + super.onPause(); + // The following call pauses the rendering thread. + // If your OpenGL application is memory intensive, + // you should consider de-allocating objects that + // consume significant memory here. + mGLView.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + // The following call resumes a paused rendering thread. + // If you de-allocated graphic objects for onPause() + // this is a good place to re-allocate them. + mGLView.onResume(); + } +} + +class HelloOpenGLES20SurfaceView extends GLSurfaceView { + + public HelloOpenGLES20SurfaceView(Context context){ + super(context); + + // Create an OpenGL ES 2.0 context. + setEGLContextClientVersion(2); + // Set the Renderer for drawing on the GLSurfaceView + setRenderer(new HelloOpenGLES20Renderer()); + } +} +</pre> + <p class="note"><strong>Note:</strong> You will get a compile error for the {@code +HelloOpenGLES20Renderer} class reference. That's expected; you will fix this error in the next step. + </p> + + <p>As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its +view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its +work.</p> + + <p>The {@code HelloOpenGLES20SurfaceView} class in this example code above is just a thin wrapper +for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this +example. However, if you want your application to monitor and respond to touch screen +events—and we are guessing you do—you must extend {@link android.opengl.GLSurfaceView} +to add touch event listeners, which you will learn how to do in the <a href="#touch">Reponding to +Touch Events</a> section.</p> + + <p>In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an +implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create +a renderer class to complete this OpenGL application.</p> + </li> + + <li>Create a new file for the following class {@code HelloOpenGLES20Renderer}, which implements +the {@link android.opengl.GLSurfaceView.Renderer} interface: + +<pre> +package com.example.android.apis.graphics; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.opengl.GLES20; +import android.opengl.GLSurfaceView; + +public class HelloOpenGLES20Renderer implements GLSurfaceView.Renderer { + + public void onSurfaceCreated(GL10 unused, EGLConfig config) { + + // Set the background frame color + GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + } + + public void onDrawFrame(GL10 unused) { + + // Redraw background color + GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); + } + + public void onSurfaceChanged(GL10 unused, int width, int height) { + GLES20.glViewport(0, 0, width, height); + } + +} +</pre> + <p>This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the +code structure needed to use OpenGL drawing methods: +<ul> + <li>{@link + android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, + javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the +{@link android.opengl.GLSurfaceView} +environment.</li> + <li>{@link + android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10) + onDrawFrame()} is called for each redraw of the {@link +android.opengl.GLSurfaceView}.</li> + <li>{@link + android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10, + int, int) onSurfaceChanged()} is called if the geometry of the {@link +android.opengl.GLSurfaceView} changes, for example when the device's screen orientation +changes.</li> +</ul> + </p> + <p>For more information about these methods, see the <a +href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document. +</p> + </li> +</ol> + +<p>The code example above creates a simple Android application that displays a grey screen using +OpenGL ES 2.0 calls. While this application does not do anything very interesting, by creating these +classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES +2.0.</p> + +<p>If you are familiar with the OpenGL ES APIs, these classes should give you enough information +to use the OpenGL ES 2.0 API and create graphics. However, if you need a bit more help getting +started with OpenGL, head on to the next sections for a few more hints.</p> + +<p class="note"><strong>Note:</strong> If your application requires OpenGL 2.0, make sure you +declare this in your manifest:</p> +<pre> + <!-- Tell the system this app requires OpenGL ES 2.0. --> + <uses-feature android:glEsVersion="0x00020000" android:required="true" /> +</pre> +<p>For more information, see <a +href="{@docRoot}guide/topics/graphics/opengl.html#manifest">OpenGL manifest declarations</a> in the +<em>3D with OpenGL</em> document.</p> + + +<h2 id="drawing">Draw a Shape on GLSurfaceView</h2> + +<p>Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to +draw something with it. This section shows you how to define and draw a triangle.</p> + +<h3 id="define-triangle">Define a Triangle</h3> + +<p>OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you + can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to + define a vertex array for the coordinates.</p> + +<p>By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of + the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top-right corner of the frame and +[-1,-1,0] is bottom-left corner of the frame.</p> + +<p>To define a vertex array for a triangle:</p> + +<ol> + <li>In your {@code HelloOpenGLES20Renderer} class, add new member variable to contain the +vertices of a triangle shape: +<pre> + private FloatBuffer triangleVB; +</pre> + </li> + + <li>Create a method, {@code initShapes()} which populates this member variable: +<pre> + private void initShapes(){ + + float triangleCoords[] = { + // X, Y, Z + -0.5f, -0.25f, 0, + 0.5f, -0.25f, 0, + 0.0f, 0.559016994f, 0 + }; + + // initialize vertex Buffer for triangle + ByteBuffer vbb = ByteBuffer.allocateDirect( + // (# of coordinate values * 4 bytes per float) + triangleCoords.length * 4); + vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order + triangleVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer + triangleVB.put(triangleCoords); // add the coordinates to the FloatBuffer + triangleVB.position(0); // set the buffer to read the first coordinate + + } +</pre> + <p>This method defines a two-dimensional triangle shape with three equal sides.</p> + </li> + <li>Modify your {@code onSurfaceCreated()} method to initialize your triangle: +<pre> + public void onSurfaceCreated(GL10 unused, EGLConfig config) { + + // Set the background frame color + GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + + // initialize the triangle vertex array + initShapes(); + } +</pre> + <p class="caution"><strong>Caution:</strong> Shapes and other static objects should be initialized + once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the + new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects + for every frame redraw and slows down your application. + </p> + </li> + +</ol> + +<p>You have now defined a triangle shape, but if you run the application, nothing appears. What?! +You also have to tell OpenGL to draw the triangle, which you'll do in the next section. +</p> + + +<h3 id="draw-triangle">Draw the Triangle</h3> + +<p>The OpenGL ES 2.0 requires a bit more code than OpenGL ES 1.0/1.1 in order to draw objects. In +this section, you'll create vertex and fragment shaders, a shader loader, apply the shaders, enable +the use of vertex arrays for your triangle and, finally, draw it on screen.</p> + +<p>To draw the triangle:</p> + +<ol> + <li>In your {@code HelloOpenGLES20Renderer} class, define a vertex shader and a fragment +shader. Shader code is defined as a string which is compiled and run by the OpenGL ES 2.0 rendering +engine. +<pre> + private final String vertexShaderCode = + "attribute vec4 vPosition; \n" + + "void main(){ \n" + + " gl_Position = vPosition; \n" + + "} \n"; + + private final String fragmentShaderCode = + "precision mediump float; \n" + + "void main(){ \n" + + " gl_FragColor = vec4 (0.63671875, 0.76953125, 0.22265625, 1.0); \n" + + "} \n"; +</pre> + <p>The vertex shader controls how OpenGL positions and draws the vertices of shapes in space. +The fragment shader controls what OpenGL draws <em>between</em> the vertices of shapes.</p> + </li> + <li>In your {@code HelloOpenGLES20Renderer} class, create a method for loading the shaders. +<pre> + private int loadShader(int type, String shaderCode){ + + // create a vertex shader type (GLES20.GL_VERTEX_SHADER) + // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) + int shader = GLES20.glCreateShader(type); + + // add the source code to the shader and compile it + GLES20.glShaderSource(shader, shaderCode); + GLES20.glCompileShader(shader); + + return shader; + } +</pre> + </li> + + <li>Add the following members to your {@code HelloOpenGLES20Renderer} class for an OpenGL +Program and the positioning control for your triangle. +<pre> + private int mProgram; + private int maPositionHandle; +</pre> + <p>In OpenGL ES 2.0, you attach vertex and fragment shaders to a <em>Program</em> and then +apply the program to the OpenGL graphics pipeline.</p> + </li> + + <li>Add the following code to the end of your {@code onSurfaceCreated()} method to load the +shaders and attach them to an OpenGL Program. +<pre> + int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode); + int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode); + + mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program + GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program + GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program + GLES20.glLinkProgram(mProgram); // creates OpenGL program executables + + // get handle to the vertex shader's vPosition member + maPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition"); +</pre> + <p>At this point, you are ready to draw the triangle object in the OpenGL view.</p> + </li> + + <li>Add the following code to the end of your {@code onDrawFrame()} method apply the OpenGL +program you created, load the triangle object and draw the triangle. +<pre> + // Add program to OpenGL environment + GLES20.glUseProgram(mProgram); + + // Prepare the triangle data + GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 12, triangleVB); + GLES20.glEnableVertexAttribArray(maPositionHandle); + + // Draw the triangle + GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); +</pre> + </li> + <li id="squashed-triangle">Run the app! Your application should look something like this: + </li> +</ol> + +<img src="{@docRoot}images/opengl/helloopengl-es20-1.png"> +<p class="img-caption"> + <strong>Figure 1.</strong> Triangle drawn without a projection or camera view. +</p> + +<p>There are a few problems with this example. First of all, it is not going to impress your +friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen +orientation of the device. The reason the shape is skewed is due to the fact that the object is +being rendered in a frame which is not perfectly square. You'll fix that problem using a projection +and camera view in the next section.</p> + +<p>Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in +exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the +<a href="#motion">Add Motion</a> section, you'll make this shape rotate and justify +this use of processing power.</p> + +<h2 id="projection-and-views">Apply Projection and Camera View</h2> + +<p>One of the basic problems in displaying graphics is that Android device displays are typically +not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate +system onto your typically non-square screen. To solve this problem, you can apply an OpenGL +projection mode and camera view (eye point) to transform the coordinates of your graphic objects +so they have the correct proportions on any display. For more information about OpenGL coordinate +mapping, see <a href="{@docRoot}guide/topics/graphics/opengl.html#coordinate-mapping">Coordinate +Mapping for Drawn Objects</a>.</p> + +<p>To apply projection and camera view transformations to your triangle: +</p> +<ol> + <li>Add the following members to your {@code HelloOpenGLES20Renderer} class. +<pre> + private int muMVPMatrixHandle; + private float[] mMVPMatrix = new float[16]; + private float[] mMMatrix = new float[16]; + private float[] mVMatrix = new float[16]; + private float[] mProjMatrix = new float[16]; +</pre> + </li> + <li>Modify your {@code vertexShaderCode} string to add a variable for a model view +projection matrix. +<pre> + private final String vertexShaderCode = + // This matrix member variable provides a hook to manipulate + // the coordinates of the objects that use this vertex shader + "uniform mat4 uMVPMatrix; \n" + + + "attribute vec4 vPosition; \n" + + "void main(){ \n" + + + // the matrix must be included as a modifier of gl_Position + " gl_Position = uMVPMatrix * vPosition; \n" + + + "} \n"; +</pre> + </li> + <li>Modify the {@code onSurfaceChanged()} method to calculate the device screen ratio and +create a projection matrix. +<pre> + public void onSurfaceChanged(GL10 unused, int width, int height) { + GLES20.glViewport(0, 0, width, height); + + float ratio = (float) width / height; + + // this projection matrix is applied to object coodinates + // in the onDrawFrame() method + Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7); + } +</pre> + </li> + <li>Add the following code to the end of your {@code onSurfaceChanged()} method to +reference the {@code uMVPMatrix} shader matrix variable you added in step 2. +<pre> + muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); +</pre> + </li> + <li>Add the following code to the end of your {@code onSurfaceChanged()} method to define +a camera view matrix. +<pre> + Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); +</pre> + </li> + <li>Finally, modify your {@code onDrawFrame()} method to combine the projection and +camera view matrices and then apply the combined transformation to the OpenGL rendering pipeline. +<pre> + public void onDrawFrame(GL10 unused) { + ... + // Apply a ModelView Projection transformation + Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0); + GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); + + // Draw the triangle + ... + } +</pre> + </li> + <li>Run the updated application and you should see something like this:</li> +</ol> + +<img src="{@docRoot}images/opengl/helloopengl-es20-2.png"> +<p class="img-caption"> + <strong>Figure 2.</strong> Triangle drawn with a projection and camera view applied. +</p> + +<p>Now that you have applied this transformation, the triangle has three equal sides, instead of the +<a href="#squashed-triangle">squashed triangle</a> in the earlier version.</p> + +<h2 id="motion">Add Motion</h2> + +<p>While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances +are you want at least <em>some</em> of your objects to move. In this section, you'll add motion to +your triangle by rotating it.</p> + +<p>To add rotation to your triangle:</p> +<ol> + <li>Add an additional tranformation matrix member to your {@code HelloOpenGLES20Renderer} +class. + <pre> + private float[] mMMatrix = new float[16]; + </pre> + </li> + <li>Modify your {@code onDrawFrame()} method to rotate the triangle object. +<pre> + public void onDrawFrame(GL10 gl) { + ... + + // Create a rotation for the triangle + long time = SystemClock.uptimeMillis() % 4000L; + float angle = 0.090f * ((int) time); + Matrix.setRotateM(mMMatrix, 0, angle, 0, 0, 1.0f); + Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0); + Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0); + + // Apply a ModelView Projection transformation + GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); + + // Draw the triangle + ... + } +</pre> + </li> + <li>Run the application and your triangle should rotate around its center.</li> +</ol> + + +<h2 id="touch">Respond to Touch Events</h2> +<p>Making objects move according to a preset program like the rotating triangle is useful for +getting some attention, but what if you want to have users interact with your OpenGL graphics? In +this section, you'll learn how listen for touch events to let users interact with objects in your +{@code HelloOpenGLES20SurfaceView}.</p> + +<p>The key to making your OpenGL application touch interactive is expanding your implementation of +{@link android.opengl.GLSurfaceView} to override the {@link +android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events. +Before you do that, however, you'll modify the renderer class to expose the rotation angle of the +triangle. Afterwards, you'll modify the {@code HelloOpenGLES20SurfaceView} to process touch events +and pass that data to your renderer.</p> + +<p>To make your triangle rotate in response to touch events:</p> + +<ol> + <li>Modify your {@code HelloOpenGLES20Renderer} class to include a new, public member so that +your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer: +<pre> + public float mAngle; +</pre> + </li> + <li>In your {@code onDrawFrame()} method, comment out the code that generates an angle and +replace the {@code angle} variable with {@code mAngle}. +<pre> + // Create a rotation for the triangle (Boring! Comment this out:) + // long time = SystemClock.uptimeMillis() % 4000L; + // float angle = 0.090f * ((int) time); + + // Use the mAngle member as the rotation value + Matrix.setRotateM(mMMatrix, 0, mAngle, 0, 0, 1.0f); +</pre> + </li> + <li>In your {@code HelloOpenGLES20SurfaceView} class, add the following member variables. +<pre> + private final float TOUCH_SCALE_FACTOR = 180.0f / 320; + private HelloOpenGLES20Renderer mRenderer; + private float mPreviousX; + private float mPreviousY; +</pre> + </li> + <li>In the constructor method for {@code HelloOpenGLES20SurfaceView}, set the {@code mRenderer} +member so you have a handle to pass in rotation input and set the render mode to {@link +android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}.<pre> + public HelloOpenGLES20SurfaceView(Context context){ + super(context); + // Create an OpenGL ES 2.0 context. + setEGLContextClientVersion(2); + + // set the mRenderer member + mRenderer = new HelloOpenGLES20Renderer(); + setRenderer(mRenderer); + + // Render the view only when there is a change + setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); + } +</pre> + </li> + <li>In your {@code HelloOpenGLES20SurfaceView} class, override the {@link +android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch +events and pass them to your renderer. +<pre> + @Override + public boolean onTouchEvent(MotionEvent e) { + // MotionEvent reports input details from the touch screen + // and other input controls. In this case, you are only + // interested in events where the touch position changed. + + float x = e.getX(); + float y = e.getY(); + + switch (e.getAction()) { + case MotionEvent.ACTION_MOVE: + + float dx = x - mPreviousX; + float dy = y - mPreviousY; + + // reverse direction of rotation above the mid-line + if (y > getHeight() / 2) { + dx = dx * -1 ; + } + + // reverse direction of rotation to left of the mid-line + if (x < getWidth() / 2) { + dy = dy * -1 ; + } + + mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR; + requestRender(); + } + + mPreviousX = x; + mPreviousY = y; + return true; + } +</pre> + <p class="note"><strong>Note:</strong> Touch events return pixel coordinates which <em>are not the +same</em> as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the +highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL +graphic objects, you must translate touch coordinates into OpenGL coordinates.</p> + </li> + <li>Run the application and drag your finger or cursor around the screen to rotate the +triangle.</li> +</ol> +<p>For another example of OpenGL touch event functionality, see <a +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ +TouchRotateActivity.html">TouchRotateActivity</a>.</p>
\ No newline at end of file diff --git a/docs/html/sdk/ndk/overview.jd b/docs/html/sdk/ndk/overview.jd index 93c664dac5a4..85599f76600d 100644 --- a/docs/html/sdk/ndk/overview.jd +++ b/docs/html/sdk/ndk/overview.jd @@ -457,7 +457,8 @@ adb install bin/NativeActivity-debug.apk <li>Mac OS X 10.4.8 or later (x86 only)</li> - <li>Linux (32- or 64-bit, tested on Linux Ubuntu Dapper Drake)</li> + <li>Linux (32 or 64-bit; Ubuntu 8.04, or other Linux distributions using GLibc 2.7 or +later)</li> </ul> <h4>Required development tools</h4> diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h index a6fb12e29638..493993d6d983 100644 --- a/include/gui/SurfaceTexture.h +++ b/include/gui/SurfaceTexture.h @@ -275,7 +275,7 @@ private: enum BufferState { // FREE indicates that the buffer is not currently being used and // will not be used in the future until it gets dequeued and - // subseqently queued by the client. + // subsequently queued by the client. FREE = 0, // DEQUEUED indicates that the buffer has been dequeued by the diff --git a/include/utils/String16.h b/include/utils/String16.h index 584f53f30065..360f407c36b5 100644 --- a/include/utils/String16.h +++ b/include/utils/String16.h @@ -156,7 +156,7 @@ inline String16& String16::operator+=(const String16& other) inline String16 String16::operator+(const String16& other) const { - String16 tmp; + String16 tmp(*this); tmp += other; return tmp; } diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp index 7ac43431f1d1..ac9b33b61cd8 100644 --- a/libs/gui/SurfaceTexture.cpp +++ b/libs/gui/SurfaceTexture.cpp @@ -36,6 +36,10 @@ #include <utils/Log.h> #include <utils/String8.h> + +#define ALLOW_DEQUEUE_CURRENT_BUFFER false + + namespace android { // Transform matrices @@ -294,9 +298,22 @@ status_t SurfaceTexture::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h, if (state == BufferSlot::DEQUEUED) { dequeuedCount++; } - if (state == BufferSlot::FREE /*|| i == mCurrentTexture*/) { - foundSync = i; - if (i != mCurrentTexture) { + + // if buffer is FREE it CANNOT be current + LOGW_IF((state == BufferSlot::FREE) && (mCurrentTexture==i), + "dequeueBuffer: buffer %d is both FREE and current!", i); + + if (ALLOW_DEQUEUE_CURRENT_BUFFER) { + if (state == BufferSlot::FREE || i == mCurrentTexture) { + foundSync = i; + if (i != mCurrentTexture) { + found = i; + break; + } + } + } else { + if (state == BufferSlot::FREE) { + foundSync = i; found = i; break; } @@ -325,7 +342,7 @@ status_t SurfaceTexture::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h, } // we're in synchronous mode and didn't find a buffer, we need to wait - // for for some buffers to be consumed + // for some buffers to be consumed tryAgain = mSynchronousMode && (foundSync == INVALID_BUFFER_SLOT); if (tryAgain) { mDequeueCondition.wait(mMutex); @@ -482,17 +499,16 @@ status_t SurfaceTexture::queueBuffer(int buf, int64_t timestamp, mSlots[buf].mScalingMode = mNextScalingMode; mSlots[buf].mTimestamp = timestamp; mDequeueCondition.signal(); + + *outWidth = mDefaultWidth; + *outHeight = mDefaultHeight; + *outTransform = 0; } // scope for the lock // call back without lock held if (listener != 0) { listener->onFrameAvailable(); } - - *outWidth = mDefaultWidth; - *outHeight = mDefaultHeight; - *outTransform = 0; - return OK; } @@ -847,6 +863,7 @@ void SurfaceTexture::freeBufferLocked(int i) { void SurfaceTexture::freeAllBuffersLocked() { LOGW_IF(!mQueue.isEmpty(), "freeAllBuffersLocked called but mQueue is not empty"); + mCurrentTexture = INVALID_BUFFER_SLOT; for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { freeBufferLocked(i); } @@ -860,6 +877,7 @@ void SurfaceTexture::freeAllBuffersExceptHeadLocked() { Fifo::iterator front(mQueue.begin()); head = *front; } + mCurrentTexture = INVALID_BUFFER_SLOT; for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { if (i != head) { freeBufferLocked(i); diff --git a/libs/rs/driver/rsdBcc.cpp b/libs/rs/driver/rsdBcc.cpp index fb2df3741c6a..176dd182b951 100644 --- a/libs/rs/driver/rsdBcc.cpp +++ b/libs/rs/driver/rsdBcc.cpp @@ -182,6 +182,7 @@ typedef struct { const Allocation * ain; Allocation * aout; const void * usr; + size_t usrLen; uint32_t mSliceSize; volatile int mSliceNum; @@ -209,6 +210,10 @@ typedef int (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint static void wc_xy(void *usr, uint32_t idx) { MTLaunchStruct *mtls = (MTLaunchStruct *)usr; + RsForEachStubParamStruct p; + memset(&p, 0, sizeof(p)); + p.usr = mtls->usr; + p.usr_len = mtls->usrLen; while (1) { uint32_t slice = (uint32_t)android_atomic_inc(&mtls->mSliceNum); @@ -221,13 +226,15 @@ static void wc_xy(void *usr, uint32_t idx) { //LOGE("usr idx %i, x %i,%i y %i,%i", idx, mtls->xStart, mtls->xEnd, yStart, yEnd); //LOGE("usr ptr in %p, out %p", mtls->ptrIn, mtls->ptrOut); - for (uint32_t y = yStart; y < yEnd; y++) { - uint32_t offset = mtls->dimX * y; + for (p.y = yStart; p.y < yEnd; p.y++) { + uint32_t offset = mtls->dimX * p.y; uint8_t *xPtrOut = mtls->ptrOut + (mtls->eStrideOut * offset); const uint8_t *xPtrIn = mtls->ptrIn + (mtls->eStrideIn * offset); - for (uint32_t x = mtls->xStart; x < mtls->xEnd; x++) { - ((rs_t)mtls->script->mHal.info.root) (xPtrIn, xPtrOut, mtls->usr, x, y, 0, 0); + for (p.x = mtls->xStart; p.x < mtls->xEnd; p.x++) { + p.in = xPtrIn; + p.out = xPtrOut; + ((rs_t)mtls->script->mHal.info.root) (p.in, p.out, p.usr, p.x, p.y, 0, 0); xPtrIn += mtls->eStrideIn; xPtrOut += mtls->eStrideOut; } @@ -237,6 +244,10 @@ static void wc_xy(void *usr, uint32_t idx) { static void wc_x(void *usr, uint32_t idx) { MTLaunchStruct *mtls = (MTLaunchStruct *)usr; + RsForEachStubParamStruct p; + memset(&p, 0, sizeof(p)); + p.usr = mtls->usr; + p.usr_len = mtls->usrLen; while (1) { uint32_t slice = (uint32_t)android_atomic_inc(&mtls->mSliceNum); @@ -251,8 +262,10 @@ static void wc_x(void *usr, uint32_t idx) { //LOGE("usr ptr in %p, out %p", mtls->ptrIn, mtls->ptrOut); uint8_t *xPtrOut = mtls->ptrOut + (mtls->eStrideOut * xStart); const uint8_t *xPtrIn = mtls->ptrIn + (mtls->eStrideIn * xStart); - for (uint32_t x = xStart; x < xEnd; x++) { - ((rs_t)mtls->script->mHal.info.root) (xPtrIn, xPtrOut, mtls->usr, x, 0, 0, 0); + for (p.x = xStart; p.x < xEnd; p.x++) { + p.in = xPtrIn; + p.out = xPtrOut; + ((rs_t)mtls->script->mHal.info.root) (p.in, p.out, p.usr, p.x, 0, 0, 0); xPtrIn += mtls->eStrideIn; xPtrOut += mtls->eStrideOut; } @@ -325,6 +338,7 @@ void rsdScriptInvokeForEach(const Context *rsc, mtls.aout = aout; mtls.script = s; mtls.usr = usr; + mtls.usrLen = usrLen; mtls.mSliceSize = 10; mtls.mSliceNum = 0; @@ -351,18 +365,25 @@ void rsdScriptInvokeForEach(const Context *rsc, //LOGE("launch 1"); } else { + RsForEachStubParamStruct p; + memset(&p, 0, sizeof(p)); + p.usr = mtls.usr; + p.usr_len = mtls.usrLen; + //LOGE("launch 3"); - for (uint32_t ar = mtls.arrayStart; ar < mtls.arrayEnd; ar++) { - for (uint32_t z = mtls.zStart; z < mtls.zEnd; z++) { - for (uint32_t y = mtls.yStart; y < mtls.yEnd; y++) { - uint32_t offset = mtls.dimX * mtls.dimY * mtls.dimZ * ar + - mtls.dimX * mtls.dimY * z + - mtls.dimX * y; + for (p.ar[0] = mtls.arrayStart; p.ar[0] < mtls.arrayEnd; p.ar[0]++) { + for (p.z = mtls.zStart; p.z < mtls.zEnd; p.z++) { + for (p.y = mtls.yStart; p.y < mtls.yEnd; p.y++) { + uint32_t offset = mtls.dimX * mtls.dimY * mtls.dimZ * p.ar[0] + + mtls.dimX * mtls.dimY * p.z + + mtls.dimX * p.y; uint8_t *xPtrOut = mtls.ptrOut + (mtls.eStrideOut * offset); const uint8_t *xPtrIn = mtls.ptrIn + (mtls.eStrideIn * offset); - for (uint32_t x = mtls.xStart; x < mtls.xEnd; x++) { - ((rs_t)s->mHal.info.root) (xPtrIn, xPtrOut, usr, x, y, z, ar); + for (p.x = mtls.xStart; p.x < mtls.xEnd; p.x++) { + p.in = xPtrIn; + p.out = xPtrOut; + ((rs_t)s->mHal.info.root) (p.in, p.out, p.usr, p.x, p.y, p.z, p.ar[0]); xPtrIn += mtls.eStrideIn; xPtrOut += mtls.eStrideOut; } diff --git a/libs/rs/rs.spec b/libs/rs/rs.spec index 0dea97100d35..f27758249a5d 100644 --- a/libs/rs/rs.spec +++ b/libs/rs/rs.spec @@ -127,6 +127,7 @@ ObjDestroy { } ElementCreate { + direct param RsDataType mType param RsDataKind mKind param bool mNormalized @@ -135,6 +136,7 @@ ElementCreate { } ElementCreate2 { + direct param const RsElement * elements param const char ** names param const uint32_t * arraySize @@ -226,6 +228,7 @@ AllocationCopy2DRange { } SamplerCreate { + direct param RsSamplerValue magFilter param RsSamplerValue minFilter param RsSamplerValue wrapS @@ -311,6 +314,7 @@ ScriptCCreate { ProgramStoreCreate { + direct param bool colorMaskR param bool colorMaskG param bool colorMaskB @@ -324,6 +328,7 @@ ProgramStoreCreate { } ProgramRasterCreate { + direct param bool pointSmooth param bool lineSmooth param bool pointSprite @@ -352,12 +357,14 @@ ProgramBindSampler { } ProgramFragmentCreate { + direct param const char * shaderText param const uint32_t * params ret RsProgramFragment } ProgramVertexCreate { + direct param const char * shaderText param const uint32_t * params ret RsProgramVertex diff --git a/libs/rs/rsAllocation.cpp b/libs/rs/rsAllocation.cpp index b59ade8d9fe9..a366d4985a48 100644 --- a/libs/rs/rsAllocation.cpp +++ b/libs/rs/rsAllocation.cpp @@ -252,6 +252,7 @@ Allocation *Allocation::createFromStream(Context *rsc, IStream *stream) { Allocation *alloc = Allocation::createAllocation(rsc, type, RS_ALLOCATION_USAGE_SCRIPT); alloc->setName(name.string(), name.size()); + type->decUserRef(); uint32_t count = dataSize / type->getElementSizeBytes(); @@ -307,12 +308,12 @@ void Allocation::resize1D(Context *rsc, uint32_t dimX) { return; } - Type *t = mHal.state.type->cloneAndResize1D(rsc, dimX); + ObjectBaseRef<Type> t = mHal.state.type->cloneAndResize1D(rsc, dimX); if (dimX < oldDimX) { decRefs(getPtr(), oldDimX - dimX, dimX); } - rsc->mHal.funcs.allocation.resize(rsc, this, t, mHal.state.hasReferences); - mHal.state.type.set(t); + rsc->mHal.funcs.allocation.resize(rsc, this, t.get(), mHal.state.hasReferences); + mHal.state.type.set(t.get()); updateCache(); } diff --git a/libs/rs/rsComponent.cpp b/libs/rs/rsComponent.cpp index e65febb4d464..ce06306a1ef0 100644 --- a/libs/rs/rsComponent.cpp +++ b/libs/rs/rsComponent.cpp @@ -176,36 +176,6 @@ bool Component::isReference() const { return (mType >= RS_TYPE_ELEMENT); } -String8 Component::getGLSLType() const { - if (mType == RS_TYPE_SIGNED_32) { - switch (mVectorSize) { - case 1: return String8("int"); - case 2: return String8("ivec2"); - case 3: return String8("ivec3"); - case 4: return String8("ivec4"); - } - } - if (mType == RS_TYPE_FLOAT_32) { - switch (mVectorSize) { - case 1: return String8("float"); - case 2: return String8("vec2"); - case 3: return String8("vec3"); - case 4: return String8("vec4"); - } - } - if ((mType == RS_TYPE_MATRIX_4X4) && (mVectorSize == 1)) { - return String8("mat4"); - } - if ((mType == RS_TYPE_MATRIX_3X3) && (mVectorSize == 1)) { - return String8("mat3"); - } - if ((mType == RS_TYPE_MATRIX_2X2) && (mVectorSize == 1)) { - return String8("mat2"); - } - return String8(); -} - - static const char * gTypeBasicStrings[] = { "NONE", "F16", diff --git a/libs/rs/rsComponent.h b/libs/rs/rsComponent.h index a448f0e8f495..6ddc990b2486 100644 --- a/libs/rs/rsComponent.h +++ b/libs/rs/rsComponent.h @@ -32,10 +32,8 @@ public: void set(RsDataType dt, RsDataKind dk, bool norm, uint32_t vecSize=1); - String8 getGLSLType() const; void dumpLOGV(const char *prefix) const; - RsDataType getType() const {return mType;} RsDataKind getKind() const {return mKind;} bool getIsNormalized() const {return mNormalized;} diff --git a/libs/rs/rsContext.cpp b/libs/rs/rsContext.cpp index bffe3c09c406..f65dd4723a81 100644 --- a/libs/rs/rsContext.cpp +++ b/libs/rs/rsContext.cpp @@ -240,6 +240,7 @@ void * Context::threadProc(void *vrsc) { rsc->setProgramStore(NULL); rsc->mStateFont.init(rsc); rsc->setFont(NULL); + rsc->mStateSampler.init(rsc); rsc->mFBOCache.init(rsc); } @@ -307,6 +308,7 @@ void Context::destroyWorkerThreadResources() { mStateFragment.deinit(this); mStateFragmentStore.deinit(this); mStateFont.deinit(this); + mStateSampler.deinit(this); mFBOCache.deinit(this); } //LOGV("destroyWorkerThreadResources 2"); diff --git a/libs/rs/rsElement.cpp b/libs/rs/rsElement.cpp index b77b18a0b686..36bbdf05a48c 100644 --- a/libs/rs/rsElement.cpp +++ b/libs/rs/rsElement.cpp @@ -29,13 +29,16 @@ Element::Element(Context *rsc) : ObjectBase(rsc) { } Element::~Element() { + clear(); +} + +void Element::preDestroy() const { for (uint32_t ct = 0; ct < mRSC->mStateElement.mElements.size(); ct++) { if (mRSC->mStateElement.mElements[ct] == this) { mRSC->mStateElement.mElements.removeAt(ct); break; } } - clear(); } void Element::clear() { @@ -60,6 +63,7 @@ size_t Element::getSizeBits() const { void Element::dumpLOGV(const char *prefix) const { ObjectBase::dumpLOGV(prefix); LOGV("%s Element: fieldCount: %zu, size bytes: %zu", prefix, mFieldCount, getSizeBytes()); + mComponent.dumpLOGV(prefix); for (uint32_t ct = 0; ct < mFieldCount; ct++) { LOGV("%s Element field index: %u ------------------", prefix, ct); LOGV("%s name: %s, offsetBits: %u, arraySize: %u", @@ -97,60 +101,46 @@ Element *Element::createFromStream(Context *rsc, IStream *stream) { String8 name; stream->loadString(&name); - Element *elem = new Element(rsc); - elem->mComponent.loadFromStream(stream); - - elem->mFieldCount = stream->loadU32(); - if (elem->mFieldCount) { - elem->mFields = new ElementField_t [elem->mFieldCount]; - for (uint32_t ct = 0; ct < elem->mFieldCount; ct ++) { - stream->loadString(&elem->mFields[ct].name); - elem->mFields[ct].arraySize = stream->loadU32(); - Element *fieldElem = Element::createFromStream(rsc, stream); - elem->mFields[ct].e.set(fieldElem); - } - } + Component component; + component.loadFromStream(stream); - // We need to check if this already exists - for (uint32_t ct=0; ct < rsc->mStateElement.mElements.size(); ct++) { - Element *ee = rsc->mStateElement.mElements[ct]; - if (ee->isEqual(elem)) { - ObjectBase::checkDelete(elem); - ee->incUserRef(); - return ee; - } + uint32_t fieldCount = stream->loadU32(); + if (!fieldCount) { + return (Element *)Element::create(rsc, + component.getType(), + component.getKind(), + component.getIsNormalized(), + component.getVectorSize());; } - elem->compute(); - rsc->mStateElement.mElements.push(elem); - return elem; -} - -bool Element::isEqual(const Element *other) const { - if (other == NULL) { - return false; + const Element **subElems = new const Element *[fieldCount]; + const char **subElemNames = new const char *[fieldCount]; + size_t *subElemNamesLengths = new size_t[fieldCount]; + uint32_t *arraySizes = new uint32_t[fieldCount]; + + String8 elemName; + for (uint32_t ct = 0; ct < fieldCount; ct ++) { + stream->loadString(&elemName); + subElemNamesLengths[ct] = elemName.length(); + char *tmpName = new char[subElemNamesLengths[ct]]; + memcpy(tmpName, elemName.string(), subElemNamesLengths[ct]); + subElemNames[ct] = tmpName; + arraySizes[ct] = stream->loadU32(); + subElems[ct] = Element::createFromStream(rsc, stream); } - if (!other->getFieldCount() && !mFieldCount) { - if ((other->getType() == getType()) && - (other->getKind() == getKind()) && - (other->getComponent().getIsNormalized() == getComponent().getIsNormalized()) && - (other->getComponent().getVectorSize() == getComponent().getVectorSize())) { - return true; - } - return false; - } - if (other->getFieldCount() == mFieldCount) { - for (uint32_t i=0; i < mFieldCount; i++) { - if ((!other->mFields[i].e->isEqual(mFields[i].e.get())) || - (other->mFields[i].name.length() != mFields[i].name.length()) || - (other->mFields[i].name != mFields[i].name) || - (other->mFields[i].arraySize != mFields[i].arraySize)) { - return false; - } - } - return true; + + const Element *elem = Element::create(rsc, fieldCount, subElems, subElemNames, + subElemNamesLengths, arraySizes); + for (uint32_t ct = 0; ct < fieldCount; ct ++) { + delete [] subElemNames[ct]; + subElems[ct]->decUserRef(); } - return false; + delete[] subElems; + delete[] subElemNames; + delete[] subElemNamesLengths; + delete[] arraySizes; + + return (Element *)elem; } void Element::compute() { @@ -172,9 +162,11 @@ void Element::compute() { } -const Element * Element::create(Context *rsc, RsDataType dt, RsDataKind dk, +ObjectBaseRef<const Element> Element::createRef(Context *rsc, RsDataType dt, RsDataKind dk, bool isNorm, uint32_t vecSize) { + ObjectBaseRef<const Element> returnRef; // Look for an existing match. + ObjectBase::asyncLock(); for (uint32_t ct=0; ct < rsc->mStateElement.mElements.size(); ct++) { const Element *ee = rsc->mStateElement.mElements[ct]; if (!ee->getFieldCount() && @@ -183,21 +175,31 @@ const Element * Element::create(Context *rsc, RsDataType dt, RsDataKind dk, (ee->getComponent().getIsNormalized() == isNorm) && (ee->getComponent().getVectorSize() == vecSize)) { // Match - ee->incUserRef(); + returnRef.set(ee); + ObjectBase::asyncUnlock(); return ee; } } + ObjectBase::asyncUnlock(); Element *e = new Element(rsc); + returnRef.set(e); e->mComponent.set(dt, dk, isNorm, vecSize); e->compute(); + + ObjectBase::asyncLock(); rsc->mStateElement.mElements.push(e); - return e; + ObjectBase::asyncUnlock(); + + return returnRef; } -const Element * Element::create(Context *rsc, size_t count, const Element **ein, +ObjectBaseRef<const Element> Element::createRef(Context *rsc, size_t count, const Element **ein, const char **nin, const size_t * lengths, const uint32_t *asin) { + + ObjectBaseRef<const Element> returnRef; // Look for an existing match. + ObjectBase::asyncLock(); for (uint32_t ct=0; ct < rsc->mStateElement.mElements.size(); ct++) { const Element *ee = rsc->mStateElement.mElements[ct]; if (ee->getFieldCount() == count) { @@ -212,13 +214,16 @@ const Element * Element::create(Context *rsc, size_t count, const Element **ein, } } if (match) { - ee->incUserRef(); - return ee; + returnRef.set(ee); + ObjectBase::asyncUnlock(); + return returnRef; } } } + ObjectBase::asyncUnlock(); Element *e = new Element(rsc); + returnRef.set(e); e->mFields = new ElementField_t [count]; e->mFieldCount = count; for (size_t ct=0; ct < count; ct++) { @@ -228,26 +233,11 @@ const Element * Element::create(Context *rsc, size_t count, const Element **ein, } e->compute(); + ObjectBase::asyncLock(); rsc->mStateElement.mElements.push(e); - return e; -} - -String8 Element::getGLSLType(uint32_t indent) const { - String8 s; - for (uint32_t ct=0; ct < indent; ct++) { - s.append(" "); - } + ObjectBase::asyncUnlock(); - if (!mFieldCount) { - // Basic component. - s.append(mComponent.getGLSLType()); - } else { - rsAssert(0); - //s.append("struct "); - //s.append(getCStructBody(indent)); - } - - return s; + return returnRef; } void Element::incRefs(const void *ptr) const { @@ -294,6 +284,23 @@ void Element::decRefs(const void *ptr) const { } } +void Element::Builder::add(const Element *e, const char *nameStr, uint32_t arraySize) { + mBuilderElementRefs.push(ObjectBaseRef<const Element>(e)); + mBuilderElements.push(e); + mBuilderNameStrings.push(nameStr); + mBuilderNameLengths.push(strlen(nameStr)); + mBuilderArrays.push(arraySize); + +} + +ObjectBaseRef<const Element> Element::Builder::create(Context *rsc) { + return Element::createRef(rsc, mBuilderElements.size(), + &(mBuilderElements.editArray()[0]), + &(mBuilderNameStrings.editArray()[0]), + mBuilderNameLengths.editArray(), + mBuilderArrays.editArray()); +} + ElementState::ElementState() { const uint32_t initialCapacity = 32; @@ -324,10 +331,10 @@ void ElementState::elementBuilderAdd(const Element *e, const char *nameStr, uint const Element *ElementState::elementBuilderCreate(Context *rsc) { return Element::create(rsc, mBuilderElements.size(), - &(mBuilderElements.editArray()[0]), - &(mBuilderNameStrings.editArray()[0]), - mBuilderNameLengths.editArray(), - mBuilderArrays.editArray()); + &(mBuilderElements.editArray()[0]), + &(mBuilderNameStrings.editArray()[0]), + mBuilderNameLengths.editArray(), + mBuilderArrays.editArray()); } @@ -342,9 +349,7 @@ RsElement rsi_ElementCreate(Context *rsc, RsDataKind dk, bool norm, uint32_t vecSize) { - const Element *e = Element::create(rsc, dt, dk, norm, vecSize); - e->incUserRef(); - return (RsElement)e; + return (RsElement)Element::create(rsc, dt, dk, norm, vecSize); } @@ -358,15 +363,15 @@ RsElement rsi_ElementCreate2(Context *rsc, const uint32_t * arraySizes, size_t arraySizes_length) { - const Element *e = Element::create(rsc, ein_length, (const Element **)ein, names, nameLengths, arraySizes); - e->incUserRef(); - return (RsElement)e; + return (RsElement)Element::create(rsc, ein_length, (const Element **)ein, + names, nameLengths, arraySizes); } } } -void rsaElementGetNativeData(RsContext con, RsElement elem, uint32_t *elemData, uint32_t elemDataSize) { +void rsaElementGetNativeData(RsContext con, RsElement elem, + uint32_t *elemData, uint32_t elemDataSize) { rsAssert(elemDataSize == 5); // we will pack mType; mKind; mNormalized; mVectorSize; NumSubElements Element *e = static_cast<Element *>(elem); @@ -378,7 +383,8 @@ void rsaElementGetNativeData(RsContext con, RsElement elem, uint32_t *elemData, (*elemData++) = e->getFieldCount(); } -void rsaElementGetSubElements(RsContext con, RsElement elem, uint32_t *ids, const char **names, uint32_t dataSize) { +void rsaElementGetSubElements(RsContext con, RsElement elem, uint32_t *ids, + const char **names, uint32_t dataSize) { Element *e = static_cast<Element *>(elem); rsAssert(e->getFieldCount() == dataSize); diff --git a/libs/rs/rsElement.h b/libs/rs/rsElement.h index 26e2760c124b..c3ef25038d33 100644 --- a/libs/rs/rsElement.h +++ b/libs/rs/rsElement.h @@ -28,8 +28,17 @@ namespace renderscript { // An element is a group of Components that occupies one cell in a structure. class Element : public ObjectBase { public: - ~Element(); - + class Builder { + public: + void add(const Element *e, const char *nameStr, uint32_t arraySize); + ObjectBaseRef<const Element> create(Context *rsc); + private: + Vector<ObjectBaseRef<const Element> > mBuilderElementRefs; + Vector<const Element *> mBuilderElements; + Vector<const char*> mBuilderNameStrings; + Vector<size_t> mBuilderNameLengths; + Vector<uint32_t> mBuilderArrays; + }; uint32_t getGLType() const; uint32_t getGLFormat() const; @@ -55,24 +64,45 @@ public: RsDataKind getKind() const {return mComponent.getKind();} uint32_t getBits() const {return mBits;} - String8 getGLSLType(uint32_t indent=0) const; - void dumpLOGV(const char *prefix) const; virtual void serialize(OStream *stream) const; virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_ELEMENT; } static Element *createFromStream(Context *rsc, IStream *stream); - static const Element * create(Context *rsc, RsDataType dt, RsDataKind dk, - bool isNorm, uint32_t vecSize); - static const Element * create(Context *rsc, size_t count, const Element **, - const char **, const size_t * lengths, const uint32_t *asin); + static ObjectBaseRef<const Element> createRef(Context *rsc, + RsDataType dt, + RsDataKind dk, + bool isNorm, + uint32_t vecSize); + static ObjectBaseRef<const Element> createRef(Context *rsc, size_t count, + const Element **, + const char **, + const size_t * lengths, + const uint32_t *asin); + + static const Element* create(Context *rsc, + RsDataType dt, + RsDataKind dk, + bool isNorm, + uint32_t vecSize) { + ObjectBaseRef<const Element> elem = createRef(rsc, dt, dk, isNorm, vecSize); + elem->incUserRef(); + return elem.get(); + } + static const Element* create(Context *rsc, size_t count, + const Element **ein, + const char **nin, + const size_t * lengths, + const uint32_t *asin) { + ObjectBaseRef<const Element> elem = createRef(rsc, count, ein, nin, lengths, asin); + elem->incUserRef(); + return elem.get(); + } void incRefs(const void *) const; void decRefs(const void *) const; bool getHasReferences() const {return mHasReference;} - bool isEqual(const Element *other) const; - protected: // deallocate any components that are part of this element. void clear(); @@ -88,12 +118,15 @@ protected: bool mHasReference; + virtual ~Element(); Element(Context *); Component mComponent; uint32_t mBits; void compute(); + + virtual void preDestroy() const; }; diff --git a/libs/rs/rsFileA3D.cpp b/libs/rs/rsFileA3D.cpp index cd02c24b981f..df5dc128061b 100644 --- a/libs/rs/rsFileA3D.cpp +++ b/libs/rs/rsFileA3D.cpp @@ -68,7 +68,7 @@ void FileA3D::parseHeader(IStream *headerStream) { for (uint32_t i = 0; i < numIndexEntries; i ++) { A3DIndexEntry *entry = new A3DIndexEntry(); headerStream->loadString(&entry->mObjectName); - LOGV("Header data, entry name = %s", entry->mObjectName.string()); + //LOGV("Header data, entry name = %s", entry->mObjectName.string()); entry->mType = (RsA3DClassID)headerStream->loadU32(); if (mUse64BitOffsets){ entry->mOffset = headerStream->loadOffset(); @@ -369,7 +369,7 @@ RsObjectBase rsaFileA3DGetEntryByIndex(RsContext con, uint32_t index, RsFile fil } ObjectBase *obj = fa3d->initializeFromEntry(index); - LOGV("Returning object with name %s", obj->getName()); + //LOGV("Returning object with name %s", obj->getName()); return obj; } diff --git a/libs/rs/rsFont.cpp b/libs/rs/rsFont.cpp index 3917ca19f80d..7efed9d9f948 100644 --- a/libs/rs/rsFont.cpp +++ b/libs/rs/rsFont.cpp @@ -490,49 +490,47 @@ void FontState::initRenderState() { shaderString.append(" gl_FragColor = col;\n"); shaderString.append("}\n"); - const Element *colorElem = Element::create(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 4); - const Element *gammaElem = Element::create(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 1); - mRSC->mStateElement.elementBuilderBegin(); - mRSC->mStateElement.elementBuilderAdd(colorElem, "Color", 1); - mRSC->mStateElement.elementBuilderAdd(gammaElem, "Gamma", 1); - const Element *constInput = mRSC->mStateElement.elementBuilderCreate(mRSC); + ObjectBaseRef<const Element> colorElem = Element::createRef(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 4); + ObjectBaseRef<const Element> gammaElem = Element::createRef(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 1); + Element::Builder builder; + builder.add(colorElem.get(), "Color", 1); + builder.add(gammaElem.get(), "Gamma", 1); + ObjectBaseRef<const Element> constInput = builder.create(mRSC); - Type *inputType = Type::getType(mRSC, constInput, 1, 0, 0, false, false); + ObjectBaseRef<Type> inputType = Type::getTypeRef(mRSC, constInput.get(), 1, 0, 0, false, false); uint32_t tmp[4]; tmp[0] = RS_PROGRAM_PARAM_CONSTANT; - tmp[1] = (uint32_t)inputType; + tmp[1] = (uint32_t)inputType.get(); tmp[2] = RS_PROGRAM_PARAM_TEXTURE_TYPE; tmp[3] = RS_TEXTURE_2D; - mFontShaderFConstant.set(Allocation::createAllocation(mRSC, inputType, + mFontShaderFConstant.set(Allocation::createAllocation(mRSC, inputType.get(), RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_GRAPHICS_CONSTANTS)); ProgramFragment *pf = new ProgramFragment(mRSC, shaderString.string(), shaderString.length(), tmp, 4); mFontShaderF.set(pf); mFontShaderF->bindAllocation(mRSC, mFontShaderFConstant.get(), 0); - Sampler *sampler = new Sampler(mRSC, RS_SAMPLER_NEAREST, RS_SAMPLER_NEAREST, - RS_SAMPLER_CLAMP, RS_SAMPLER_CLAMP, RS_SAMPLER_CLAMP); - mFontSampler.set(sampler); - mFontShaderF->bindSampler(mRSC, 0, sampler); - - ProgramStore *fontStore = new ProgramStore(mRSC, true, true, true, true, - false, false, - RS_BLEND_SRC_SRC_ALPHA, - RS_BLEND_DST_ONE_MINUS_SRC_ALPHA, - RS_DEPTH_FUNC_ALWAYS); - mFontProgramStore.set(fontStore); + mFontSampler.set(Sampler::getSampler(mRSC, RS_SAMPLER_NEAREST, RS_SAMPLER_NEAREST, + RS_SAMPLER_CLAMP, RS_SAMPLER_CLAMP, RS_SAMPLER_CLAMP).get()); + mFontShaderF->bindSampler(mRSC, 0, mFontSampler.get()); + + mFontProgramStore.set(ProgramStore::getProgramStore(mRSC, true, true, true, true, + false, false, + RS_BLEND_SRC_SRC_ALPHA, + RS_BLEND_DST_ONE_MINUS_SRC_ALPHA, + RS_DEPTH_FUNC_ALWAYS).get()); mFontProgramStore->init(); } void FontState::initTextTexture() { - const Element *alphaElem = Element::create(mRSC, RS_TYPE_UNSIGNED_8, RS_KIND_PIXEL_A, true, 1); + ObjectBaseRef<const Element> alphaElem = Element::createRef(mRSC, RS_TYPE_UNSIGNED_8, RS_KIND_PIXEL_A, true, 1); // We will allocate a texture to initially hold 32 character bitmaps - Type *texType = Type::getType(mRSC, alphaElem, 1024, 256, 0, false, false); + ObjectBaseRef<Type> texType = Type::getTypeRef(mRSC, alphaElem.get(), 1024, 256, 0, false, false); - Allocation *cacheAlloc = Allocation::createAllocation(mRSC, texType, + Allocation *cacheAlloc = Allocation::createAllocation(mRSC, texType.get(), RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_GRAPHICS_TEXTURE); mTextTexture.set(cacheAlloc); mTextTexture->syncAll(mRSC, RS_ALLOCATION_USAGE_SCRIPT); @@ -557,11 +555,11 @@ void FontState::initTextTexture() { // Avoid having to reallocate memory and render quad by quad void FontState::initVertexArrayBuffers() { // Now lets write index data - const Element *indexElem = Element::create(mRSC, RS_TYPE_UNSIGNED_16, RS_KIND_USER, false, 1); + ObjectBaseRef<const Element> indexElem = Element::createRef(mRSC, RS_TYPE_UNSIGNED_16, RS_KIND_USER, false, 1); uint32_t numIndicies = mMaxNumberOfQuads * 6; - Type *indexType = Type::getType(mRSC, indexElem, numIndicies, 0, 0, false, false); + ObjectBaseRef<Type> indexType = Type::getTypeRef(mRSC, indexElem.get(), numIndicies, 0, 0, false, false); - Allocation *indexAlloc = Allocation::createAllocation(mRSC, indexType, + Allocation *indexAlloc = Allocation::createAllocation(mRSC, indexType.get(), RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_GRAPHICS_VERTEX); uint16_t *indexPtr = (uint16_t*)indexAlloc->getPtr(); @@ -582,19 +580,19 @@ void FontState::initVertexArrayBuffers() { indexAlloc->sendDirty(mRSC); - const Element *posElem = Element::create(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 3); - const Element *texElem = Element::create(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 2); + ObjectBaseRef<const Element> posElem = Element::createRef(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 3); + ObjectBaseRef<const Element> texElem = Element::createRef(mRSC, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 2); - mRSC->mStateElement.elementBuilderBegin(); - mRSC->mStateElement.elementBuilderAdd(posElem, "position", 1); - mRSC->mStateElement.elementBuilderAdd(texElem, "texture0", 1); - const Element *vertexDataElem = mRSC->mStateElement.elementBuilderCreate(mRSC); + Element::Builder builder; + builder.add(posElem.get(), "position", 1); + builder.add(texElem.get(), "texture0", 1); + ObjectBaseRef<const Element> vertexDataElem = builder.create(mRSC); - Type *vertexDataType = Type::getType(mRSC, vertexDataElem, - mMaxNumberOfQuads * 4, - 0, 0, false, false); + ObjectBaseRef<Type> vertexDataType = Type::getTypeRef(mRSC, vertexDataElem.get(), + mMaxNumberOfQuads * 4, + 0, 0, false, false); - Allocation *vertexAlloc = Allocation::createAllocation(mRSC, vertexDataType, + Allocation *vertexAlloc = Allocation::createAllocation(mRSC, vertexDataType.get(), RS_ALLOCATION_USAGE_SCRIPT); mTextMeshPtr = (float*)vertexAlloc->getPtr(); diff --git a/libs/rs/rsFont.h b/libs/rs/rsFont.h index b0e1430e228b..679591ca434f 100644 --- a/libs/rs/rsFont.h +++ b/libs/rs/rsFont.h @@ -146,7 +146,6 @@ public: void deinit(Context *rsc); ObjectBaseRef<Font> mDefault; - ObjectBaseRef<Font> mLast; void renderText(const char *text, uint32_t len, int32_t x, int32_t y, uint32_t startIndex = 0, int numGlyphs = -1, diff --git a/libs/rs/rsObjectBase.h b/libs/rs/rsObjectBase.h index 01850f1e2511..c7cfb0e2e8b0 100644 --- a/libs/rs/rsObjectBase.h +++ b/libs/rs/rsObjectBase.h @@ -114,7 +114,10 @@ public: } ObjectBaseRef & operator= (const ObjectBaseRef &ref) { - return ObjectBaseRef(ref); + if (&ref != this) { + set(ref); + } + return *this; } ~ObjectBaseRef() { diff --git a/libs/rs/rsProgram.cpp b/libs/rs/rsProgram.cpp index b1d8f48b9ee3..33eb422e3354 100644 --- a/libs/rs/rsProgram.cpp +++ b/libs/rs/rsProgram.cpp @@ -116,7 +116,7 @@ void Program::bindAllocation(Context *rsc, Allocation *alloc, uint32_t slot) { rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind allocation"); return; } - if (!alloc->getType()->isEqual(mHal.state.constantTypes[slot].get())) { + if (alloc->getType() != mHal.state.constantTypes[slot].get()) { LOGE("Attempt to bind alloc at slot %u, on shader id %u, but types mismatch", slot, (uint32_t)this); rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind allocation"); diff --git a/libs/rs/rsProgramFragment.cpp b/libs/rs/rsProgramFragment.cpp index 356ff778f126..ff2952051162 100644 --- a/libs/rs/rsProgramFragment.cpp +++ b/libs/rs/rsProgramFragment.cpp @@ -97,18 +97,18 @@ void ProgramFragmentState::init(Context *rsc) { shaderString.append(" gl_FragColor = col;\n"); shaderString.append("}\n"); - const Element *colorElem = Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 4); - rsc->mStateElement.elementBuilderBegin(); - rsc->mStateElement.elementBuilderAdd(colorElem, "Color", 1); - const Element *constInput = rsc->mStateElement.elementBuilderCreate(rsc); + ObjectBaseRef<const Element> colorElem = Element::createRef(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 4); + Element::Builder builder; + builder.add(colorElem.get(), "Color", 1); + ObjectBaseRef<const Element> constInput = builder.create(rsc); - Type *inputType = Type::getType(rsc, constInput, 1, 0, 0, false, false); + ObjectBaseRef<Type> inputType = Type::getTypeRef(rsc, constInput.get(), 1, 0, 0, false, false); uint32_t tmp[2]; tmp[0] = RS_PROGRAM_PARAM_CONSTANT; - tmp[1] = (uint32_t)inputType; + tmp[1] = (uint32_t)inputType.get(); - Allocation *constAlloc = Allocation::createAllocation(rsc, inputType, + Allocation *constAlloc = Allocation::createAllocation(rsc, inputType.get(), RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_GRAPHICS_CONSTANTS); ProgramFragment *pf = new ProgramFragment(rsc, shaderString.string(), shaderString.length(), tmp, 2); diff --git a/libs/rs/rsProgramRaster.cpp b/libs/rs/rsProgramRaster.cpp index 435561d7308a..945b5eca68fd 100644 --- a/libs/rs/rsProgramRaster.cpp +++ b/libs/rs/rsProgramRaster.cpp @@ -37,6 +37,15 @@ ProgramRaster::ProgramRaster(Context *rsc, bool pointSmooth, rsc->mHal.funcs.raster.init(rsc, this); } +void ProgramRaster::preDestroy() const { + for (uint32_t ct = 0; ct < mRSC->mStateRaster.mRasterPrograms.size(); ct++) { + if (mRSC->mStateRaster.mRasterPrograms[ct] == this) { + mRSC->mStateRaster.mRasterPrograms.removeAt(ct); + break; + } + } +} + ProgramRaster::~ProgramRaster() { mRSC->mHal.funcs.raster.destroy(mRSC, this); } @@ -65,8 +74,8 @@ ProgramRasterState::~ProgramRasterState() { } void ProgramRasterState::init(Context *rsc) { - ProgramRaster *pr = new ProgramRaster(rsc, false, false, false, 1.f, RS_CULL_BACK); - mDefault.set(pr); + mDefault.set(ProgramRaster::getProgramRaster(rsc, false, false, + false, 1.f, RS_CULL_BACK).get()); } void ProgramRasterState::deinit(Context *rsc) { @@ -74,19 +83,47 @@ void ProgramRasterState::deinit(Context *rsc) { mLast.clear(); } -namespace android { -namespace renderscript { +ObjectBaseRef<ProgramRaster> ProgramRaster::getProgramRaster(Context *rsc, + bool pointSmooth, + bool lineSmooth, + bool pointSprite, + float lineWidth, + RsCullMode cull) { + ObjectBaseRef<ProgramRaster> returnRef; + ObjectBase::asyncLock(); + for (uint32_t ct = 0; ct < rsc->mStateRaster.mRasterPrograms.size(); ct++) { + ProgramRaster *existing = rsc->mStateRaster.mRasterPrograms[ct]; + if (existing->mHal.state.pointSmooth != pointSmooth) continue; + if (existing->mHal.state.lineSmooth != lineSmooth) continue; + if (existing->mHal.state.pointSprite != pointSprite) continue; + if (existing->mHal.state.lineWidth != lineWidth) continue; + if (existing->mHal.state.cull != cull) continue; + returnRef.set(existing); + ObjectBase::asyncUnlock(); + return returnRef; + } + ObjectBase::asyncUnlock(); -RsProgramRaster rsi_ProgramRasterCreate(Context * rsc, - bool pointSmooth, - bool lineSmooth, - bool pointSprite, - float lineWidth, - RsCullMode cull) { ProgramRaster *pr = new ProgramRaster(rsc, pointSmooth, lineSmooth, pointSprite, lineWidth, cull); + returnRef.set(pr); + + ObjectBase::asyncLock(); + rsc->mStateRaster.mRasterPrograms.push(pr); + ObjectBase::asyncUnlock(); + + return returnRef; +} + +namespace android { +namespace renderscript { + +RsProgramRaster rsi_ProgramRasterCreate(Context * rsc, bool pointSmooth, bool lineSmooth, + bool pointSprite, float lineWidth, RsCullMode cull) { + ObjectBaseRef<ProgramRaster> pr = ProgramRaster::getProgramRaster(rsc, pointSmooth, lineSmooth, + pointSprite, lineWidth, cull); pr->incUserRef(); - return pr; + return pr.get(); } } diff --git a/libs/rs/rsProgramRaster.h b/libs/rs/rsProgramRaster.h index efdb94874197..09d7d5432c9a 100644 --- a/libs/rs/rsProgramRaster.h +++ b/libs/rs/rsProgramRaster.h @@ -27,19 +27,17 @@ class ProgramRasterState; class ProgramRaster : public ProgramBase { public: - ProgramRaster(Context *rsc, - bool pointSmooth, - bool lineSmooth, - bool pointSprite, - float lineWidth, - RsCullMode cull); - virtual ~ProgramRaster(); - virtual void setup(const Context *, ProgramRasterState *); virtual void serialize(OStream *stream) const; virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_PROGRAM_RASTER; } static ProgramRaster *createFromStream(Context *rsc, IStream *stream); + static ObjectBaseRef<ProgramRaster> getProgramRaster(Context *rsc, + bool pointSmooth, + bool lineSmooth, + bool pointSprite, + float lineWidth, + RsCullMode cull); struct Hal { mutable void *drv; @@ -55,6 +53,17 @@ public: Hal mHal; protected: + virtual void preDestroy() const; + virtual ~ProgramRaster(); + +private: + ProgramRaster(Context *rsc, + bool pointSmooth, + bool lineSmooth, + bool pointSprite, + float lineWidth, + RsCullMode cull); + }; class ProgramRasterState { @@ -66,6 +75,9 @@ public: ObjectBaseRef<ProgramRaster> mDefault; ObjectBaseRef<ProgramRaster> mLast; + + // Cache of all existing raster programs. + Vector<ProgramRaster *> mRasterPrograms; }; diff --git a/libs/rs/rsProgramStore.cpp b/libs/rs/rsProgramStore.cpp index 8fe890becb72..7e25a226d8ae 100644 --- a/libs/rs/rsProgramStore.cpp +++ b/libs/rs/rsProgramStore.cpp @@ -41,6 +41,15 @@ ProgramStore::ProgramStore(Context *rsc, mHal.state.depthFunc = depthFunc; } +void ProgramStore::preDestroy() const { + for (uint32_t ct = 0; ct < mRSC->mStateFragmentStore.mStorePrograms.size(); ct++) { + if (mRSC->mStateFragmentStore.mStorePrograms[ct] == this) { + mRSC->mStateFragmentStore.mStorePrograms.removeAt(ct); + break; + } + } +} + ProgramStore::~ProgramStore() { mRSC->mHal.funcs.store.destroy(mRSC, this); } @@ -71,14 +80,58 @@ ProgramStoreState::ProgramStoreState() { ProgramStoreState::~ProgramStoreState() { } +ObjectBaseRef<ProgramStore> ProgramStore::getProgramStore(Context *rsc, + bool colorMaskR, + bool colorMaskG, + bool colorMaskB, + bool colorMaskA, + bool depthMask, bool ditherEnable, + RsBlendSrcFunc srcFunc, + RsBlendDstFunc destFunc, + RsDepthFunc depthFunc) { + ObjectBaseRef<ProgramStore> returnRef; + ObjectBase::asyncLock(); + for (uint32_t ct = 0; ct < rsc->mStateFragmentStore.mStorePrograms.size(); ct++) { + ProgramStore *existing = rsc->mStateFragmentStore.mStorePrograms[ct]; + if (existing->mHal.state.ditherEnable != ditherEnable) continue; + if (existing->mHal.state.colorRWriteEnable != colorMaskR) continue; + if (existing->mHal.state.colorGWriteEnable != colorMaskG) continue; + if (existing->mHal.state.colorBWriteEnable != colorMaskB) continue; + if (existing->mHal.state.colorAWriteEnable != colorMaskA) continue; + if (existing->mHal.state.blendSrc != srcFunc) continue; + if (existing->mHal.state.blendDst != destFunc) continue; + if (existing->mHal.state.depthWriteEnable != depthMask) continue; + if (existing->mHal.state.depthFunc != depthFunc) continue; + + returnRef.set(existing); + ObjectBase::asyncUnlock(); + return returnRef; + } + ObjectBase::asyncUnlock(); + + ProgramStore *pfs = new ProgramStore(rsc, + colorMaskR, colorMaskG, colorMaskB, colorMaskA, + depthMask, ditherEnable, + srcFunc, destFunc, depthFunc); + returnRef.set(pfs); + + pfs->init(); + + ObjectBase::asyncLock(); + rsc->mStateFragmentStore.mStorePrograms.push(pfs); + ObjectBase::asyncUnlock(); + + return returnRef; +} + + + void ProgramStoreState::init(Context *rsc) { - ProgramStore *ps = new ProgramStore(rsc, - true, true, true, true, - true, true, - RS_BLEND_SRC_ONE, RS_BLEND_DST_ZERO, - RS_DEPTH_FUNC_LESS); - ps->init(); - mDefault.set(ps); + mDefault.set(ProgramStore::getProgramStore(rsc, + true, true, true, true, + true, true, + RS_BLEND_SRC_ONE, RS_BLEND_DST_ZERO, + RS_DEPTH_FUNC_LESS).get()); } void ProgramStoreState::deinit(Context *rsc) { @@ -96,13 +149,14 @@ RsProgramStore rsi_ProgramStoreCreate(Context *rsc, RsBlendSrcFunc srcFunc, RsBlendDstFunc destFunc, RsDepthFunc depthFunc) { - ProgramStore *pfs = new ProgramStore(rsc, - colorMaskR, colorMaskG, colorMaskB, colorMaskA, - depthMask, ditherEnable, - srcFunc, destFunc, depthFunc); - pfs->init(); - pfs->incUserRef(); - return pfs; + + ObjectBaseRef<ProgramStore> ps = ProgramStore::getProgramStore(rsc, + colorMaskR, colorMaskG, + colorMaskB, colorMaskA, + depthMask, ditherEnable, + srcFunc, destFunc, depthFunc); + ps->incUserRef(); + return ps.get(); } } diff --git a/libs/rs/rsProgramStore.h b/libs/rs/rsProgramStore.h index 77b3881fc8ee..e21f039678b3 100644 --- a/libs/rs/rsProgramStore.h +++ b/libs/rs/rsProgramStore.h @@ -28,18 +28,17 @@ class ProgramStoreState; class ProgramStore : public ProgramBase { public: - ProgramStore(Context *, - bool colorMaskR, bool colorMaskG, bool colorMaskB, bool colorMaskA, - bool depthMask, bool ditherEnable, - RsBlendSrcFunc srcFunc, RsBlendDstFunc destFunc, - RsDepthFunc depthFunc); - virtual ~ProgramStore(); - virtual void setup(const Context *, ProgramStoreState *); virtual void serialize(OStream *stream) const; virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_PROGRAM_STORE; } static ProgramStore *createFromStream(Context *rsc, IStream *stream); + static ObjectBaseRef<ProgramStore> getProgramStore(Context *, + bool colorMaskR, bool colorMaskG, + bool colorMaskB, bool colorMaskA, + bool depthMask, bool ditherEnable, + RsBlendSrcFunc srcFunc, RsBlendDstFunc destFunc, + RsDepthFunc depthFunc); void init(); @@ -66,6 +65,15 @@ public: Hal mHal; protected: + virtual void preDestroy() const; + virtual ~ProgramStore(); + +private: + ProgramStore(Context *, + bool colorMaskR, bool colorMaskG, bool colorMaskB, bool colorMaskA, + bool depthMask, bool ditherEnable, + RsBlendSrcFunc srcFunc, RsBlendDstFunc destFunc, + RsDepthFunc depthFunc); }; class ProgramStoreState { @@ -77,6 +85,9 @@ public: ObjectBaseRef<ProgramStore> mDefault; ObjectBaseRef<ProgramStore> mLast; + + // Cache of all existing store programs. + Vector<ProgramStore *> mStorePrograms; }; } diff --git a/libs/rs/rsProgramVertex.cpp b/libs/rs/rsProgramVertex.cpp index 058a4564e03f..51cb2a8ad490 100644 --- a/libs/rs/rsProgramVertex.cpp +++ b/libs/rs/rsProgramVertex.cpp @@ -150,26 +150,30 @@ ProgramVertexState::~ProgramVertexState() { } void ProgramVertexState::init(Context *rsc) { - const Element *matrixElem = Element::create(rsc, RS_TYPE_MATRIX_4X4, RS_KIND_USER, false, 1); - const Element *f2Elem = Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 2); - const Element *f3Elem = Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 3); - const Element *f4Elem = Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 4); - - rsc->mStateElement.elementBuilderBegin(); - rsc->mStateElement.elementBuilderAdd(matrixElem, "MV", 1); - rsc->mStateElement.elementBuilderAdd(matrixElem, "P", 1); - rsc->mStateElement.elementBuilderAdd(matrixElem, "TexMatrix", 1); - rsc->mStateElement.elementBuilderAdd(matrixElem, "MVP", 1); - const Element *constInput = rsc->mStateElement.elementBuilderCreate(rsc); - - rsc->mStateElement.elementBuilderBegin(); - rsc->mStateElement.elementBuilderAdd(f4Elem, "position", 1); - rsc->mStateElement.elementBuilderAdd(f4Elem, "color", 1); - rsc->mStateElement.elementBuilderAdd(f3Elem, "normal", 1); - rsc->mStateElement.elementBuilderAdd(f2Elem, "texture0", 1); - const Element *attrElem = rsc->mStateElement.elementBuilderCreate(rsc); - - Type *inputType = Type::getType(rsc, constInput, 1, 0, 0, false, false); + ObjectBaseRef<const Element> matrixElem = Element::createRef(rsc, RS_TYPE_MATRIX_4X4, + RS_KIND_USER, false, 1); + ObjectBaseRef<const Element> f2Elem = Element::createRef(rsc, RS_TYPE_FLOAT_32, + RS_KIND_USER, false, 2); + ObjectBaseRef<const Element> f3Elem = Element::createRef(rsc, RS_TYPE_FLOAT_32, + RS_KIND_USER, false, 3); + ObjectBaseRef<const Element> f4Elem = Element::createRef(rsc, RS_TYPE_FLOAT_32, + RS_KIND_USER, false, 4); + + Element::Builder constBuilder; + constBuilder.add(matrixElem.get(), "MV", 1); + constBuilder.add(matrixElem.get(), "P", 1); + constBuilder.add(matrixElem.get(), "TexMatrix", 1); + constBuilder.add(matrixElem.get(), "MVP", 1); + ObjectBaseRef<const Element> constInput = constBuilder.create(rsc); + + Element::Builder inputBuilder; + inputBuilder.add(f4Elem.get(), "position", 1); + inputBuilder.add(f4Elem.get(), "color", 1); + inputBuilder.add(f3Elem.get(), "normal", 1); + inputBuilder.add(f2Elem.get(), "texture0", 1); + ObjectBaseRef<const Element> attrElem = inputBuilder.create(rsc); + + ObjectBaseRef<Type> inputType = Type::getTypeRef(rsc, constInput.get(), 1, 0, 0, false, false); String8 shaderString(RS_SHADER_INTERNAL); shaderString.append("varying vec4 varColor;\n"); @@ -183,13 +187,13 @@ void ProgramVertexState::init(Context *rsc) { uint32_t tmp[4]; tmp[0] = RS_PROGRAM_PARAM_CONSTANT; - tmp[1] = (uint32_t)inputType; + tmp[1] = (uint32_t)inputType.get(); tmp[2] = RS_PROGRAM_PARAM_INPUT; - tmp[3] = (uint32_t)attrElem; + tmp[3] = (uint32_t)attrElem.get(); ProgramVertex *pv = new ProgramVertex(rsc, shaderString.string(), shaderString.length(), tmp, 4); - Allocation *alloc = Allocation::createAllocation(rsc, inputType, + Allocation *alloc = Allocation::createAllocation(rsc, inputType.get(), RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_GRAPHICS_CONSTANTS); pv->bindAllocation(rsc, alloc, 0); diff --git a/libs/rs/rsSampler.cpp b/libs/rs/rsSampler.cpp index 2a05d16e9bbe..5fc64a42cd1f 100644 --- a/libs/rs/rsSampler.cpp +++ b/libs/rs/rsSampler.cpp @@ -48,6 +48,15 @@ Sampler::~Sampler() { mRSC->mHal.funcs.sampler.destroy(mRSC, this); } +void Sampler::preDestroy() const { + for (uint32_t ct = 0; ct < mRSC->mStateSampler.mAllSamplers.size(); ct++) { + if (mRSC->mStateSampler.mAllSamplers[ct] == this) { + mRSC->mStateSampler.mAllSamplers.removeAt(ct); + break; + } + } +} + void Sampler::bindToContext(SamplerState *ss, uint32_t slot) { ss->mSamplers[slot].set(this); mBoundSlot = slot; @@ -66,6 +75,39 @@ Sampler *Sampler::createFromStream(Context *rsc, IStream *stream) { return NULL; } +ObjectBaseRef<Sampler> Sampler::getSampler(Context *rsc, + RsSamplerValue magFilter, + RsSamplerValue minFilter, + RsSamplerValue wrapS, + RsSamplerValue wrapT, + RsSamplerValue wrapR, + float aniso) { + ObjectBaseRef<Sampler> returnRef; + ObjectBase::asyncLock(); + for (uint32_t ct = 0; ct < rsc->mStateSampler.mAllSamplers.size(); ct++) { + Sampler *existing = rsc->mStateSampler.mAllSamplers[ct]; + if (existing->mHal.state.magFilter != magFilter) continue; + if (existing->mHal.state.minFilter != minFilter ) continue; + if (existing->mHal.state.wrapS != wrapS) continue; + if (existing->mHal.state.wrapT != wrapT) continue; + if (existing->mHal.state.wrapR != wrapR) continue; + if (existing->mHal.state.aniso != aniso) continue; + returnRef.set(existing); + ObjectBase::asyncUnlock(); + return returnRef; + } + ObjectBase::asyncUnlock(); + + Sampler *s = new Sampler(rsc, magFilter, minFilter, wrapS, wrapT, wrapR, aniso); + returnRef.set(s); + + ObjectBase::asyncLock(); + rsc->mStateSampler.mAllSamplers.push(s); + ObjectBase::asyncUnlock(); + + return returnRef; +} + //////////////////////////////// namespace android { @@ -78,9 +120,10 @@ RsSampler rsi_SamplerCreate(Context * rsc, RsSamplerValue wrapT, RsSamplerValue wrapR, float aniso) { - Sampler * s = new Sampler(rsc, magFilter, minFilter, wrapS, wrapT, wrapR, aniso); + ObjectBaseRef<Sampler> s = Sampler::getSampler(rsc, magFilter, minFilter, + wrapS, wrapT, wrapR, aniso); s->incUserRef(); - return s; + return s.get(); } }} diff --git a/libs/rs/rsSampler.h b/libs/rs/rsSampler.h index 90b6082c139d..e698132d0f70 100644 --- a/libs/rs/rsSampler.h +++ b/libs/rs/rsSampler.h @@ -30,16 +30,13 @@ class SamplerState; class Sampler : public ObjectBase { public: - Sampler(Context *, - RsSamplerValue magFilter, - RsSamplerValue minFilter, - RsSamplerValue wrapS, - RsSamplerValue wrapT, - RsSamplerValue wrapR, - float aniso = 1.0f); - - virtual ~Sampler(); - + static ObjectBaseRef<Sampler> getSampler(Context *, + RsSamplerValue magFilter, + RsSamplerValue minFilter, + RsSamplerValue wrapS, + RsSamplerValue wrapT, + RsSamplerValue wrapR, + float aniso = 1.0f); void bindToContext(SamplerState *, uint32_t slot); void unbindFromContext(SamplerState *); @@ -65,14 +62,33 @@ public: protected: int32_t mBoundSlot; + virtual void preDestroy() const; + virtual ~Sampler(); + private: Sampler(Context *); + Sampler(Context *, + RsSamplerValue magFilter, + RsSamplerValue minFilter, + RsSamplerValue wrapS, + RsSamplerValue wrapT, + RsSamplerValue wrapR, + float aniso = 1.0f); }; class SamplerState { public: ObjectBaseRef<Sampler> mSamplers[RS_MAX_SAMPLER_SLOT]; + void init(Context *rsc) { + } + void deinit(Context *rsc) { + for (uint32_t i = 0; i < RS_MAX_SAMPLER_SLOT; i ++) { + mSamplers[i].clear(); + } + } + // Cache of all existing raster programs. + Vector<Sampler *> mAllSamplers; }; } diff --git a/libs/rs/rsType.cpp b/libs/rs/rsType.cpp index 10e3182c6389..9a6a31b4f89f 100644 --- a/libs/rs/rsType.cpp +++ b/libs/rs/rsType.cpp @@ -25,7 +25,7 @@ Type::Type(Context *rsc) : ObjectBase(rsc) { clear(); } -void Type::preDestroy() { +void Type::preDestroy() const { for (uint32_t ct = 0; ct < mRSC->mStateType.mTypes.size(); ct++) { if (mRSC->mStateType.mTypes[ct] == this) { mRSC->mStateType.mTypes.removeAt(ct); @@ -58,6 +58,7 @@ TypeState::TypeState() { } TypeState::~TypeState() { + rsAssert(!mTypes.size()); } size_t Type::getOffsetForFace(uint32_t face) const { @@ -183,7 +184,9 @@ Type *Type::createFromStream(Context *rsc, IStream *stream) { uint32_t z = stream->loadU32(); uint8_t lod = stream->loadU8(); uint8_t faces = stream->loadU8(); - return Type::getType(rsc, elem, x, y, z, lod != 0, faces !=0 ); + Type *type = Type::getType(rsc, elem, x, y, z, lod != 0, faces !=0 ); + elem->decUserRef(); + return type; } bool Type::getIsNp2() const { @@ -203,24 +206,11 @@ bool Type::getIsNp2() const { return false; } -bool Type::isEqual(const Type *other) const { - if (other == NULL) { - return false; - } - if (other->getElement()->isEqual(getElement()) && - other->getDimX() == mDimX && - other->getDimY() == mDimY && - other->getDimZ() == mDimZ && - other->getDimLOD() == mDimLOD && - other->getDimFaces() == mFaces) { - return true; - } - return false; -} +ObjectBaseRef<Type> Type::getTypeRef(Context *rsc, const Element *e, + uint32_t dimX, uint32_t dimY, uint32_t dimZ, + bool dimLOD, bool dimFaces) { + ObjectBaseRef<Type> returnRef; -Type * Type::getType(Context *rsc, const Element *e, - uint32_t dimX, uint32_t dimY, uint32_t dimZ, - bool dimLOD, bool dimFaces) { TypeState * stc = &rsc->mStateType; ObjectBase::asyncLock(); @@ -232,14 +222,15 @@ Type * Type::getType(Context *rsc, const Element *e, if (t->getDimZ() != dimZ) continue; if (t->getDimLOD() != dimLOD) continue; if (t->getDimFaces() != dimFaces) continue; - t->incUserRef(); + returnRef.set(t); ObjectBase::asyncUnlock(); - return t; + return returnRef; } ObjectBase::asyncUnlock(); Type *nt = new Type(rsc); + returnRef.set(nt); nt->mElement.set(e); nt->mDimX = dimX; nt->mDimY = dimY; @@ -247,25 +238,24 @@ Type * Type::getType(Context *rsc, const Element *e, nt->mDimLOD = dimLOD; nt->mFaces = dimFaces; nt->compute(); - nt->incUserRef(); ObjectBase::asyncLock(); stc->mTypes.push(nt); ObjectBase::asyncUnlock(); - return nt; + return returnRef; } -Type * Type::cloneAndResize1D(Context *rsc, uint32_t dimX) const { - return getType(rsc, mElement.get(), dimX, - mDimY, mDimZ, mDimLOD, mFaces); +ObjectBaseRef<Type> Type::cloneAndResize1D(Context *rsc, uint32_t dimX) const { + return getTypeRef(rsc, mElement.get(), dimX, + mDimY, mDimZ, mDimLOD, mFaces); } -Type * Type::cloneAndResize2D(Context *rsc, +ObjectBaseRef<Type> Type::cloneAndResize2D(Context *rsc, uint32_t dimX, uint32_t dimY) const { - return getType(rsc, mElement.get(), dimX, dimY, - mDimZ, mDimLOD, mFaces); + return getTypeRef(rsc, mElement.get(), dimX, dimY, + mDimZ, mDimLOD, mFaces); } diff --git a/libs/rs/rsType.h b/libs/rs/rsType.h index 086db337093b..bc0d9ffdbe46 100644 --- a/libs/rs/rsType.h +++ b/libs/rs/rsType.h @@ -62,14 +62,20 @@ public: virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_TYPE; } static Type *createFromStream(Context *rsc, IStream *stream); - bool isEqual(const Type *other) const; + ObjectBaseRef<Type> cloneAndResize1D(Context *rsc, uint32_t dimX) const; + ObjectBaseRef<Type> cloneAndResize2D(Context *rsc, uint32_t dimX, uint32_t dimY) const; - Type * cloneAndResize1D(Context *rsc, uint32_t dimX) const; - Type * cloneAndResize2D(Context *rsc, uint32_t dimX, uint32_t dimY) const; + static ObjectBaseRef<Type> getTypeRef(Context *rsc, const Element *e, + uint32_t dimX, uint32_t dimY, uint32_t dimZ, + bool dimLOD, bool dimFaces); - static Type * getType(Context *rsc, const Element *e, - uint32_t dimX, uint32_t dimY, uint32_t dimZ, - bool dimLOD, bool dimFaces); + static Type* getType(Context *rsc, const Element *e, + uint32_t dimX, uint32_t dimY, uint32_t dimZ, + bool dimLOD, bool dimFaces) { + ObjectBaseRef<Type> type = getTypeRef(rsc, e, dimX, dimY, dimZ, dimLOD, dimFaces); + type->incUserRef(); + return type.get(); + } protected: struct LOD { @@ -105,7 +111,7 @@ protected: uint32_t mLODCount; protected: - virtual void preDestroy(); + virtual void preDestroy() const; virtual ~Type(); private: diff --git a/libs/rs/rs_hal.h b/libs/rs/rs_hal.h index 6a4537b392a2..21dff218c868 100644 --- a/libs/rs/rs_hal.h +++ b/libs/rs/rs_hal.h @@ -40,6 +40,19 @@ class FBOCache; typedef void *(*RsHalSymbolLookupFunc)(void *usrptr, char const *symbolName); +typedef struct { + const void *in; + void *out; + const void *usr; + size_t usr_len; + uint32_t x; + uint32_t y; + uint32_t z; + uint32_t lod; + RsAllocationCubemapFace face; + uint32_t ar[16]; +} RsForEachStubParamStruct; + /** * Script management functions */ diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java index 92829caa8626..85c7dba423d0 100644 --- a/media/java/android/media/AudioService.java +++ b/media/java/android/media/AudioService.java @@ -522,6 +522,10 @@ public class AudioService extends IAudioService.Stub { (!mVoiceCapable && streamType != AudioSystem.STREAM_VOICE_CALL && streamType != AudioSystem.STREAM_BLUETOOTH_SCO) || (mVoiceCapable && streamType == AudioSystem.STREAM_RING)) { + // do not vibrate if already in silent mode + if (mRingerMode != AudioManager.RINGER_MODE_NORMAL) { + flags &= ~AudioManager.FLAG_VIBRATE; + } // Check if the ringer mode changes with this volume adjustment. If // it does, it will handle adjusting the volume, so we won't below adjustVolume = checkForRingerModeChange(oldIndex, direction); @@ -1553,14 +1557,17 @@ public class AudioService extends IAudioService.Stub { int newRingerMode = mRingerMode; if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) { - // audible mode, at the bottom of the scale - if ((direction == AudioManager.ADJUST_LOWER && - mPrevVolDirection != AudioManager.ADJUST_LOWER) && - ((oldIndex + 5) / 10 == 0)) { - // "silent mode", but which one? - newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1 - ? AudioManager.RINGER_MODE_VIBRATE - : AudioManager.RINGER_MODE_SILENT; + if ((direction == AudioManager.ADJUST_LOWER) && ((oldIndex + 5) / 10 <= 1)) { + // enter silent mode if current index is the last audible one and not repeating a + // volume key down + if (mPrevVolDirection != AudioManager.ADJUST_LOWER) { + // "silent mode", but which one? + newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1 + ? AudioManager.RINGER_MODE_VIBRATE + : AudioManager.RINGER_MODE_SILENT; + } else { + adjustVolumeIndex = false; + } } } else { if (direction == AudioManager.ADJUST_RAISE) { diff --git a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java index 5bfdcdbac2be..8caa04ce760f 100644 --- a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java +++ b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java @@ -3781,72 +3781,62 @@ class MediaArtistNativeHelper { * @param startMs The starting time in ms * @param endMs The end time in ms * @param thumbnailCount The number of frames to be extracted + * @param indices The indices of thumbnails wanted + * @param callback The callback used to pass back the bitmaps * from startMs to endMs * * @return The frames as bitmaps in bitmap array **/ - Bitmap[] getPixelsList(String filename, int width, int height, long startMs, long endMs, - int thumbnailCount) { - int[] rgb888 = null; - int thumbnailSize = 0; - Bitmap tempBitmap = null; - + void getPixelsList(String filename, final int width, final int height, + long startMs, long endMs, int thumbnailCount, int[] indices, + final MediaItem.GetThumbnailListCallback callback) { /* Make width and height as even */ final int newWidth = (width + 1) & 0xFFFFFFFE; final int newHeight = (height + 1) & 0xFFFFFFFE; - thumbnailSize = newWidth * newHeight * 4; + final int thumbnailSize = newWidth * newHeight; /* Create a temp bitmap for resized thumbnails */ - if ((newWidth != width) || (newHeight != height)) { - tempBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888); - } - int i = 0; - int deltaTime = (int)(endMs - startMs) / thumbnailCount; - Bitmap[] bitmaps = null; - - try { - // This may result in out of Memory Error - rgb888 = new int[thumbnailSize * thumbnailCount]; - bitmaps = new Bitmap[thumbnailCount]; - } catch (Throwable e) { - // Allocating to new size with Fixed count - try { - rgb888 = new int[thumbnailSize * MAX_THUMBNAIL_PERMITTED]; - bitmaps = new Bitmap[MAX_THUMBNAIL_PERMITTED]; - thumbnailCount = MAX_THUMBNAIL_PERMITTED; - } catch (Throwable ex) { - throw new RuntimeException("Memory allocation fails, thumbnail count too large: " - + thumbnailCount); - } - } - IntBuffer tmpBuffer = IntBuffer.allocate(thumbnailSize); - nativeGetPixelsList(filename, rgb888, newWidth, newHeight, deltaTime, thumbnailCount, - startMs, endMs); + final Bitmap tempBitmap = + (newWidth != width || newHeight != height) + ? Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888) + : null; + + final int[] rgb888 = new int[thumbnailSize]; + final IntBuffer tmpBuffer = IntBuffer.allocate(thumbnailSize); + nativeGetPixelsList(filename, rgb888, newWidth, newHeight, + thumbnailCount, startMs, endMs, indices, + new NativeGetPixelsListCallback() { + public void onThumbnail(int index) { + Bitmap bitmap = Bitmap.createBitmap( + width, height, Bitmap.Config.ARGB_8888); + tmpBuffer.put(rgb888, 0, thumbnailSize); + tmpBuffer.rewind(); + + if ((newWidth == width) && (newHeight == height)) { + bitmap.copyPixelsFromBuffer(tmpBuffer); + } else { + /* Copy the out rgb buffer to temp bitmap */ + tempBitmap.copyPixelsFromBuffer(tmpBuffer); - for (; i < thumbnailCount; i++) { - bitmaps[i] = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - tmpBuffer.put(rgb888, (i * thumbnailSize), thumbnailSize); - tmpBuffer.rewind(); + /* Create a canvas to resize */ + final Canvas canvas = new Canvas(bitmap); + canvas.drawBitmap(tempBitmap, + new Rect(0, 0, newWidth, newHeight), + new Rect(0, 0, width, height), sResizePaint); - if ((newWidth == width) && (newHeight == height)) { - bitmaps[i].copyPixelsFromBuffer(tmpBuffer); - } else { - /* Copy the out rgb buffer to temp bitmap */ - tempBitmap.copyPixelsFromBuffer(tmpBuffer); - - /* Create a canvas to resize */ - final Canvas canvas = new Canvas(bitmaps[i]); - canvas.drawBitmap(tempBitmap, new Rect(0, 0, newWidth, newHeight), - new Rect(0, 0, width, height), sResizePaint); - canvas.setBitmap(null); + canvas.setBitmap(null); + } + callback.onThumbnail(bitmap, index); } - } + }); if (tempBitmap != null) { tempBitmap.recycle(); } + } - return bitmaps; + interface NativeGetPixelsListCallback { + public void onThumbnail(int index); } /** @@ -3957,8 +3947,9 @@ class MediaArtistNativeHelper { private native int nativeGetPixels(String fileName, int[] pixelArray, int width, int height, long timeMS); - private native int nativeGetPixelsList(String fileName, int[] pixelArray, int width, int height, - int timeMS, int nosofTN, long startTimeMs, long endTimeMs); + private native int nativeGetPixelsList(String fileName, int[] pixelArray, + int width, int height, int nosofTN, long startTimeMs, long endTimeMs, + int[] indices, NativeGetPixelsListCallback callback); /** * Releases the JNI and cleans up the core native module.. Should be called diff --git a/media/java/android/media/videoeditor/MediaImageItem.java b/media/java/android/media/videoeditor/MediaImageItem.java index f0cc1fe945d4..4ca6fad2a69b 100755 --- a/media/java/android/media/videoeditor/MediaImageItem.java +++ b/media/java/android/media/videoeditor/MediaImageItem.java @@ -616,17 +616,18 @@ public class MediaImageItem extends MediaItem { * {@inheritDoc} */ @Override - public Bitmap[] getThumbnailList(int width, int height, long startMs, long endMs, - int thumbnailCount) throws IOException { + public void getThumbnailList(int width, int height, + long startMs, long endMs, + int thumbnailCount, + int[] indices, + GetThumbnailListCallback callback) + throws IOException { //KenBurns was not applied on this. if (getGeneratedImageClip() == null) { final Bitmap thumbnail = scaleImage(mFilename, width, height); - final Bitmap[] thumbnailArray = new Bitmap[thumbnailCount]; - for (int i = 0; i < thumbnailCount; i++) { - thumbnailArray[i] = thumbnail; + for (int i = 0; i < indices.length; i++) { + callback.onThumbnail(thumbnail, i); } - - return thumbnailArray; } else { if (startMs > endMs) { throw new IllegalArgumentException("Start time is greater than end time"); @@ -636,15 +637,8 @@ public class MediaImageItem extends MediaItem { throw new IllegalArgumentException("End time is greater than file duration"); } - if (startMs == endMs) { - Bitmap[] bitmap = new Bitmap[1]; - bitmap[0] = mMANativeHelper.getPixels(getGeneratedImageClip(), - width, height,startMs); - return bitmap; - } - - return mMANativeHelper.getPixelsList(getGeneratedImageClip(), width, - height,startMs,endMs,thumbnailCount); + mMANativeHelper.getPixelsList(getGeneratedImageClip(), width, + height, startMs, endMs, thumbnailCount, indices, callback); } } diff --git a/media/java/android/media/videoeditor/MediaItem.java b/media/java/android/media/videoeditor/MediaItem.java index 8c4841fc216d..4e9ea75a23a6 100755 --- a/media/java/android/media/videoeditor/MediaItem.java +++ b/media/java/android/media/videoeditor/MediaItem.java @@ -564,15 +564,41 @@ public abstract class MediaItem { * @param startMs The start of time range in milliseconds * @param endMs The end of the time range in milliseconds * @param thumbnailCount The thumbnail count - * - * @return The array of Bitmaps + * @param indices The indices of the thumbnails wanted + * @param callback The callback used to pass back the bitmaps * * @throws IOException if a file error occurs */ - public abstract Bitmap[] getThumbnailList(int width, int height, - long startMs, long endMs, - int thumbnailCount) - throws IOException; + public abstract void getThumbnailList(int width, int height, + long startMs, long endMs, + int thumbnailCount, + int[] indices, + GetThumbnailListCallback callback) + throws IOException; + + public interface GetThumbnailListCallback { + public void onThumbnail(Bitmap bitmap, int index); + } + + // This is for compatibility, only used in tests. + public Bitmap[] getThumbnailList(int width, int height, + long startMs, long endMs, + int thumbnailCount) + throws IOException { + final Bitmap[] bitmaps = new Bitmap[thumbnailCount]; + int[] indices = new int[thumbnailCount]; + for (int i = 0; i < thumbnailCount; i++) { + indices[i] = i; + } + getThumbnailList(width, height, startMs, endMs, + thumbnailCount, indices, new GetThumbnailListCallback() { + public void onThumbnail(Bitmap bitmap, int index) { + bitmaps[index] = bitmap; + } + }); + + return bitmaps; + } /* * {@inheritDoc} diff --git a/media/java/android/media/videoeditor/MediaVideoItem.java b/media/java/android/media/videoeditor/MediaVideoItem.java index 62486515548f..0ac354ba4846 100755 --- a/media/java/android/media/videoeditor/MediaVideoItem.java +++ b/media/java/android/media/videoeditor/MediaVideoItem.java @@ -293,8 +293,12 @@ public class MediaVideoItem extends MediaItem { * {@inheritDoc} */ @Override - public Bitmap[] getThumbnailList(int width, int height, long startMs, - long endMs, int thumbnailCount) throws IOException { + public void getThumbnailList(int width, int height, + long startMs, long endMs, + int thumbnailCount, + int[] indices, + GetThumbnailListCallback callback) + throws IOException { if (startMs > endMs) { throw new IllegalArgumentException("Start time is greater than end time"); } @@ -307,14 +311,8 @@ public class MediaVideoItem extends MediaItem { throw new IllegalArgumentException("Invalid dimension"); } - if (startMs == endMs) { - final Bitmap[] bitmap = new Bitmap[1]; - bitmap[0] = mMANativeHelper.getPixels(super.getFilename(), width, height,startMs); - return bitmap; - } - - return mMANativeHelper.getPixelsList(super.getFilename(), width, - height,startMs,endMs,thumbnailCount); + mMANativeHelper.getPixelsList(super.getFilename(), width, + height, startMs, endMs, thumbnailCount, indices, callback); } /* diff --git a/media/jni/mediaeditor/VideoBrowserInternal.h b/media/jni/mediaeditor/VideoBrowserInternal.h index 3cfb6b9270c1..f4eaab8a6df3 100755 --- a/media/jni/mediaeditor/VideoBrowserInternal.h +++ b/media/jni/mediaeditor/VideoBrowserInternal.h @@ -26,9 +26,6 @@ #define VIDEO_BROWSER_BGR565 - -#define VIDEO_BROWSER_PREDECODE_TIME 2000 /* In miliseconds */ - /*---------------------------- MACROS ----------------------------*/ #define CHECK_PTR(fct, p, err, errValue) \ { \ diff --git a/media/jni/mediaeditor/VideoBrowserMain.c b/media/jni/mediaeditor/VideoBrowserMain.c index 2de55e311422..c6c6000ce6bc 100755 --- a/media/jni/mediaeditor/VideoBrowserMain.c +++ b/media/jni/mediaeditor/VideoBrowserMain.c @@ -447,13 +447,9 @@ M4OSA_ERR videoBrowserPrepareFrame(M4OSA_Context pContext, M4OSA_UInt32* pTime, VideoBrowserContext* pC = (VideoBrowserContext*)pContext; M4OSA_ERR err = M4NO_ERROR; M4OSA_UInt32 targetTime = 0; - M4OSA_UInt32 jumpTime = 0; M4_MediaTime timeMS = 0; - M4OSA_Int32 rapTime = 0; - M4OSA_Bool isBackward = M4OSA_FALSE; M4OSA_Bool bJumpNeeded = M4OSA_FALSE; - /*--- Sanity checks ---*/ CHECK_PTR(videoBrowserPrepareFrame, pContext, err, M4ERR_PARAMETER); CHECK_PTR(videoBrowserPrepareFrame, pTime, err, M4ERR_PARAMETER); @@ -472,16 +468,11 @@ M4OSA_ERR videoBrowserPrepareFrame(M4OSA_Context pContext, M4OSA_UInt32* pTime, goto videoBrowserPrepareFrame_cleanUp; } - /*--- Check the duration ---*/ - /*--- If we jump backward, we need to jump ---*/ - if (targetTime < pC->m_currentCTS) - { - isBackward = M4OSA_TRUE; - bJumpNeeded = M4OSA_TRUE; - } - /*--- If we jumpt to a time greater than "currentTime" + "predecodeTime" - we need to jump ---*/ - else if (targetTime > (pC->m_currentCTS + VIDEO_BROWSER_PREDECODE_TIME)) + // If we jump backward or forward to a time greater than current position by + // 85ms (~ 2 frames), we want to jump. + if (pC->m_currentCTS == 0 || + targetTime < pC->m_currentCTS || + targetTime > (pC->m_currentCTS + 85)) { bJumpNeeded = M4OSA_TRUE; } diff --git a/media/jni/mediaeditor/VideoEditorMain.cpp b/media/jni/mediaeditor/VideoEditorMain.cpp index 14972a2f7623..7d0f56f51f4d 100755 --- a/media/jni/mediaeditor/VideoEditorMain.cpp +++ b/media/jni/mediaeditor/VideoEditorMain.cpp @@ -182,10 +182,11 @@ static int videoEditor_getPixelsList( jintArray pixelArray, M4OSA_UInt32 width, M4OSA_UInt32 height, - M4OSA_UInt32 deltatimeMS, M4OSA_UInt32 noOfThumbnails, - M4OSA_UInt32 startTime, - M4OSA_UInt32 endTime); + jlong startTime, + jlong endTime, + jintArray indexArray, + jobject callback); static void videoEditor_startPreview( @@ -288,7 +289,7 @@ static JNINativeMethod gManualEditMethods[] = { (void *)videoEditor_release }, {"nativeGetPixels", "(Ljava/lang/String;[IIIJ)I", (void*)videoEditor_getPixels }, - {"nativeGetPixelsList", "(Ljava/lang/String;[IIIIIJJ)I", + {"nativeGetPixelsList", "(Ljava/lang/String;[IIIIJJ[ILandroid/media/videoeditor/MediaArtistNativeHelper$NativeGetPixelsListCallback;)I", (void*)videoEditor_getPixelsList }, {"getMediaProperties", "(Ljava/lang/String;)Landroid/media/videoeditor/MediaArtistNativeHelper$Properties;", @@ -2150,75 +2151,72 @@ static int videoEditor_getPixels( } static int videoEditor_getPixelsList( - JNIEnv* env, - jobject thiz, - jstring path, - jintArray pixelArray, - M4OSA_UInt32 width, - M4OSA_UInt32 height, - M4OSA_UInt32 deltatimeMS, + JNIEnv* env, + jobject thiz, + jstring path, + jintArray pixelArray, + M4OSA_UInt32 width, + M4OSA_UInt32 height, M4OSA_UInt32 noOfThumbnails, - M4OSA_UInt32 startTime, - M4OSA_UInt32 endTime) + jlong startTime, + jlong endTime, + jintArray indexArray, + jobject callback) { - M4OSA_ERR err; + M4OSA_ERR err = M4NO_ERROR; M4OSA_Context mContext = M4OSA_NULL; - jint* m_dst32; - M4OSA_UInt32 timeMS = startTime; - int arrayOffset = 0; - - - - // Add a text marker (the condition must always be true). - ADD_TEXT_MARKER_FUN(NULL != env) const char *pString = env->GetStringUTFChars(path, NULL); if (pString == M4OSA_NULL) { - if (env != NULL) { - jniThrowException(env, "java/lang/RuntimeException", "Input string null"); - } + jniThrowException(env, "java/lang/RuntimeException", "Input string null"); return M4ERR_ALLOC; } err = ThumbnailOpen(&mContext,(const M4OSA_Char*)pString, M4OSA_FALSE); if (err != M4NO_ERROR || mContext == M4OSA_NULL) { - if (env != NULL) { - jniThrowException(env, "java/lang/RuntimeException", "ThumbnailOpen failed"); - } + jniThrowException(env, "java/lang/RuntimeException", "ThumbnailOpen failed"); if (pString != NULL) { env->ReleaseStringUTFChars(path, pString); } return err; } - m_dst32 = env->GetIntArrayElements(pixelArray, NULL); + jlong duration = (endTime - startTime); + M4OSA_UInt32 tolerance = duration / (2 * noOfThumbnails); + jint* m_dst32 = env->GetIntArrayElements(pixelArray, NULL); + jint* indices = env->GetIntArrayElements(indexArray, NULL); + jsize len = env->GetArrayLength(indexArray); - M4OSA_UInt32 tolerance = deltatimeMS / 2; - do { - err = ThumbnailGetPixels32(mContext, ((M4OSA_Int32 *)m_dst32 + arrayOffset), - width,height,&timeMS, tolerance); - if (err != M4NO_ERROR ) { - if (env != NULL) { - jniThrowException(env, "java/lang/RuntimeException",\ - "ThumbnailGetPixels32 failed"); - } - return err; + jclass cls = env->GetObjectClass(callback); + jmethodID mid = env->GetMethodID(cls, "onThumbnail", "(I)V"); + + for (int i = 0; i < len; i++) { + int k = indices[i]; + M4OSA_UInt32 timeMS = startTime; + timeMS += (2 * k + 1) * duration / (2 * noOfThumbnails); + err = ThumbnailGetPixels32(mContext, ((M4OSA_Int32 *)m_dst32), + width, height, &timeMS, tolerance); + if (err != M4NO_ERROR) { + break; } - timeMS += deltatimeMS; - arrayOffset += (width * height * 4); - noOfThumbnails--; - } while(noOfThumbnails > 0); + env->CallVoidMethod(callback, mid, (jint)k); + } env->ReleaseIntArrayElements(pixelArray, m_dst32, 0); + env->ReleaseIntArrayElements(indexArray, indices, 0); ThumbnailClose(mContext); if (pString != NULL) { env->ReleaseStringUTFChars(path, pString); } - return err; + if (err != M4NO_ERROR) { + jniThrowException(env, "java/lang/RuntimeException",\ + "ThumbnailGetPixels32 failed"); + } + return err; } static M4OSA_ERR diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk index b9e4f9fb1223..0b1a2af46bc5 100644 --- a/media/libstagefright/Android.mk +++ b/media/libstagefright/Android.mk @@ -131,11 +131,9 @@ LOCAL_SHARED_LIBRARIES += \ libdl \ LOCAL_STATIC_LIBRARIES += \ - libstagefright_chromium_http \ - libwebcore \ - libchromium_net \ + libstagefright_chromium_http -LOCAL_SHARED_LIBRARIES += libstlport +LOCAL_SHARED_LIBRARIES += libstlport libchromium_net include external/stlport/libstlport.mk LOCAL_CPPFLAGS += -DCHROMIUM_AVAILABLE=1 diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp index 73a05a5cec77..3b79f063c319 100644 --- a/media/libstagefright/MPEG4Extractor.cpp +++ b/media/libstagefright/MPEG4Extractor.cpp @@ -1687,6 +1687,11 @@ status_t MPEG4Extractor::verifyTrack(Track *track) { } } + if (!track->sampleTable->isValid()) { + // Make sure we have all the metadata we need. + return ERROR_MALFORMED; + } + return OK; } diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp index 644c413f6fee..27dfeab4cb6f 100755 --- a/media/libstagefright/OMXCodec.cpp +++ b/media/libstagefright/OMXCodec.cpp @@ -3199,9 +3199,16 @@ void OMXCodec::setState(State newState) { } status_t OMXCodec::waitForBufferFilled_l() { + + if (mIsEncoder) { + // For timelapse video recording, the timelapse video recording may + // not send an input frame for a _long_ time. Do not use timeout + // for video encoding. + return mBufferFilled.wait(mLock); + } status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutUs); if (err != OK) { - LOGE("Timed out waiting for buffers from video encoder: %d/%d", + CODEC_LOGE("Timed out waiting for output buffers: %d/%d", countBuffersWeOwn(mPortBuffers[kPortIndexInput]), countBuffersWeOwn(mPortBuffers[kPortIndexOutput])); } diff --git a/media/libstagefright/SampleTable.cpp b/media/libstagefright/SampleTable.cpp index a8a094e2bd5d..2b9d99bdf52d 100644 --- a/media/libstagefright/SampleTable.cpp +++ b/media/libstagefright/SampleTable.cpp @@ -84,6 +84,13 @@ SampleTable::~SampleTable() { mSampleIterator = NULL; } +bool SampleTable::isValid() const { + return mChunkOffsetOffset >= 0 + && mSampleToChunkOffset >= 0 + && mSampleSizeOffset >= 0 + && mTimeToSample != NULL; +} + status_t SampleTable::setChunkOffsetParams( uint32_t type, off64_t data_offset, size_t data_size) { if (mChunkOffsetOffset >= 0) { diff --git a/media/libstagefright/include/SampleTable.h b/media/libstagefright/include/SampleTable.h index f44e0a2495f7..a6a6524c06ad 100644 --- a/media/libstagefright/include/SampleTable.h +++ b/media/libstagefright/include/SampleTable.h @@ -34,6 +34,8 @@ class SampleTable : public RefBase { public: SampleTable(const sp<DataSource> &source); + bool isValid() const; + // type can be 'stco' or 'co64'. status_t setChunkOffsetParams( uint32_t type, off64_t data_offset, size_t data_size); diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java index 369a067165ce..e5ecd5cde2ee 100755 --- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java +++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java @@ -16,8 +16,7 @@ package com.android.mediaframeworktest; -import android.media.EncoderCapabilities.AudioEncoderCap; -import android.media.EncoderCapabilities.VideoEncoderCap; +import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.os.Bundle; import android.test.InstrumentationTestRunner; @@ -29,20 +28,21 @@ import junit.framework.TestSuite; public class MediaRecorderStressTestRunner extends InstrumentationTestRunner { - public static List<VideoEncoderCap> videoEncoders = MediaProfileReader.getVideoEncoders(); - public static List<AudioEncoderCap> audioEncoders = MediaProfileReader.getAudioEncoders(); - - //Get the first capability as the default - public static VideoEncoderCap videoEncoder = videoEncoders.get(0); - public static AudioEncoderCap audioEncoder = audioEncoders.get(0); + // MediaRecorder stress test sets one of the cameras as the video source. As + // a result, we should make sure that the encoding parameters as input to + // the test must be supported by the corresponding camera. + public static int mCameraId = 0; + public static int mProfileQuality = CamcorderProfile.QUALITY_HIGH; + public static CamcorderProfile profile = + CamcorderProfile.get(mCameraId, mProfileQuality); public static int mIterations = 100; - public static int mVideoEncoder = videoEncoder.mCodec; - public static int mAudioEncdoer = audioEncoder.mCodec; - public static int mFrameRate = videoEncoder.mMaxFrameRate; - public static int mVideoWidth = videoEncoder.mMaxFrameWidth; - public static int mVideoHeight = videoEncoder.mMaxFrameHeight; - public static int mBitRate = audioEncoder.mMaxBitRate; + public static int mVideoEncoder = profile.videoCodec; + public static int mAudioEncdoer = profile.audioCodec; + public static int mFrameRate = profile.videoFrameRate; + public static int mVideoWidth = profile.videoFrameWidth; + public static int mVideoHeight = profile.videoFrameHeight; + public static int mBitRate = profile.videoBitRate; public static boolean mRemoveVideo = true; public static int mDuration = 10000; diff --git a/packages/SystemUI/res/layout-sw600dp/status_bar.xml b/packages/SystemUI/res/layout-sw600dp/status_bar.xml index a204f17bc6e0..125c87e02795 100644 --- a/packages/SystemUI/res/layout-sw600dp/status_bar.xml +++ b/packages/SystemUI/res/layout-sw600dp/status_bar.xml @@ -44,24 +44,23 @@ /> <!-- navigation controls --> - <com.android.systemui.statusbar.policy.KeyButtonView android:id="@+id/back" - android:layout_width="80dip" - android:layout_height="match_parent" - android:src="@drawable/ic_sysbar_back" - android:layout_alignParentLeft="true" - systemui:keyCode="4" - android:contentDescription="@string/accessibility_back" - systemui:glowBackground="@drawable/ic_sysbar_highlight" - /> <LinearLayout android:id="@+id/navigationArea" android:layout_width="wrap_content" android:layout_height="match_parent" - android:layout_toRightOf="@+id/back" + android:layout_alignParentLeft="true" android:orientation="horizontal" android:clipChildren="false" android:clipToPadding="false" > + <com.android.systemui.statusbar.policy.KeyButtonView android:id="@+id/back" + android:layout_width="80dip" + android:layout_height="match_parent" + android:src="@drawable/ic_sysbar_back" + systemui:keyCode="4" + android:contentDescription="@string/accessibility_back" + systemui:glowBackground="@drawable/ic_sysbar_highlight" + /> <com.android.systemui.statusbar.policy.KeyButtonView android:id="@+id/home" android:layout_width="80dip" android:layout_height="match_parent" diff --git a/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml b/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml index 955d8aee1c0f..d2358592ca91 100644 --- a/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml +++ b/packages/SystemUI/res/layout-sw600dp/status_bar_notification_area.xml @@ -130,6 +130,7 @@ android:id="@+id/battery" android:layout_height="wrap_content" android:layout_width="wrap_content" + android:paddingLeft="6dip" /> </LinearLayout> </LinearLayout> diff --git a/packages/SystemUI/res/layout/navigation_bar.xml b/packages/SystemUI/res/layout/navigation_bar.xml index 6732feeb7a38..6c4c9c174914 100644 --- a/packages/SystemUI/res/layout/navigation_bar.xml +++ b/packages/SystemUI/res/layout/navigation_bar.xml @@ -37,6 +37,7 @@ android:orientation="horizontal" android:clipChildren="false" android:clipToPadding="false" + android:id="@+id/nav_buttons" > <!-- navigation controls --> @@ -66,6 +67,7 @@ android:layout_height="match_parent" android:src="@drawable/ic_sysbar_home" systemui:keyCode="3" + systemui:keyRepeat="false" android:layout_weight="0" systemui:glowBackground="@drawable/ic_sysbar_highlight" android:contentDescription="@string/accessibility_home" @@ -118,6 +120,7 @@ android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false" + android:id="@+id/nav_buttons" > <!-- navigation controls --> @@ -148,6 +151,7 @@ android:layout_width="match_parent" android:src="@drawable/ic_sysbar_home_land" systemui:keyCode="3" + systemui:keyRepeat="false" android:layout_weight="0" android:contentDescription="@string/accessibility_home" systemui:glowBackground="@drawable/ic_sysbar_highlight_land" diff --git a/packages/SystemUI/res/values-ca/strings.xml b/packages/SystemUI/res/values-ca/strings.xml index 529a5bc846d0..33eb223d5191 100644 --- a/packages/SystemUI/res/values-ca/strings.xml +++ b/packages/SystemUI/res/values-ca/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"No hi ha cap targeta SIM."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Connexió Bluetooth mitjançant dispositiu portàtil"</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Mode d\'avió."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Bateria: <xliff:g id="NUMBER">%d</xliff:g> %."</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Botó Configuració."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Botó de notificacions."</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Elimina la notificació."</string> diff --git a/packages/SystemUI/res/values-cs/strings.xml b/packages/SystemUI/res/values-cs/strings.xml index 8093de1eacaa..543bb9eca9b2 100644 --- a/packages/SystemUI/res/values-cs/strings.xml +++ b/packages/SystemUI/res/values-cs/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"Žádná karta SIM."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Tethering přes Bluetooth."</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Režim V letadle."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Stav baterie: <xliff:g id="NUMBER">%d</xliff:g> %."</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Tlačítko Nastavení."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Tlačítko upozornění."</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Odebrat oznámení"</string> diff --git a/packages/SystemUI/res/values-de/strings.xml b/packages/SystemUI/res/values-de/strings.xml index 8168f74f4419..ea9b8d26e5b8 100644 --- a/packages/SystemUI/res/values-de/strings.xml +++ b/packages/SystemUI/res/values-de/strings.xml @@ -60,8 +60,7 @@ <string name="compat_mode_help_header" msgid="7020175705401506719">"Kompatibilitätszoom"</string> <string name="compat_mode_help_body" msgid="4946726776359270040">"Wenn eine App für einen kleineren Bildschirm ausgelegt ist, wird ein Zoom-Steuerelement neben der Uhr angezeigt."</string> <string name="screenshot_saving_toast" msgid="8592630119048713208">"Screenshot in Galerie gespeichert"</string> - <!-- no translation found for screenshot_failed_toast (1990979819772906912) --> - <skip /> + <!-- outdated translation 655180965533683356 --> <string name="screenshot_failed_toast" msgid="1990979819772906912">"Screenshot konnte nicht gespeichert werden."</string> <string name="usb_preference_title" msgid="6551050377388882787">"USB-Dateiübertragungsoptionen"</string> <string name="use_mtp_button_title" msgid="4333504413563023626">"Als Medienplayer (MTP) bereitstellen"</string> <string name="use_ptp_button_title" msgid="7517127540301625751">"Als Kamera (PTP) bereitstellen"</string> diff --git a/packages/SystemUI/res/values-el/strings.xml b/packages/SystemUI/res/values-el/strings.xml index 76dadd4f7645..ee3e671c54f6 100644 --- a/packages/SystemUI/res/values-el/strings.xml +++ b/packages/SystemUI/res/values-el/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"Δεν υπάρχει SIM."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Σύνδεση Bluetooth"</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Λειτουργία πτήσης."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Μπαταρία <xliff:g id="NUMBER">%d</xliff:g> %."</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Κουμπί ρυθμίσεων."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Κουμπί ειδοοποιήσεων"</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Κατάργηση ειδοποίησης."</string> diff --git a/packages/SystemUI/res/values-es/strings.xml b/packages/SystemUI/res/values-es/strings.xml index 86470e4c9915..a8bbd9609b42 100644 --- a/packages/SystemUI/res/values-es/strings.xml +++ b/packages/SystemUI/res/values-es/strings.xml @@ -60,8 +60,7 @@ <string name="compat_mode_help_header" msgid="7020175705401506719">"Zoom de compatibilidad"</string> <string name="compat_mode_help_body" msgid="4946726776359270040">"Si la aplicación se ha diseñado para una pantalla más pequeña, aparecerá un control de zoom junto al reloj."</string> <string name="screenshot_saving_toast" msgid="8592630119048713208">"Captura de pantalla guardada en la galería"</string> - <!-- no translation found for screenshot_failed_toast (1990979819772906912) --> - <skip /> + <!-- outdated translation 655180965533683356 --> <string name="screenshot_failed_toast" msgid="1990979819772906912">"No se ha podido guardar la captura de pantalla."</string> <string name="usb_preference_title" msgid="6551050377388882787">"Opciones de transferencia de archivos por USB"</string> <string name="use_mtp_button_title" msgid="4333504413563023626">"Activar como reproductor de medios (MTP)"</string> <string name="use_ptp_button_title" msgid="7517127540301625751">"Activar como cámara (PTP)"</string> diff --git a/packages/SystemUI/res/values-fi/strings.xml b/packages/SystemUI/res/values-fi/strings.xml index c2098b12fbc2..aa0b48759433 100644 --- a/packages/SystemUI/res/values-fi/strings.xml +++ b/packages/SystemUI/res/values-fi/strings.xml @@ -60,8 +60,7 @@ <string name="compat_mode_help_header" msgid="7020175705401506719">"Yhteensopivuustilan zoomaus"</string> <string name="compat_mode_help_body" msgid="4946726776359270040">"Jos sovellus on suunniteltu pienemmälle näytölle, kellon viereen tulee näkyviin zoomaussäädin."</string> <string name="screenshot_saving_toast" msgid="8592630119048713208">"Kuvakaappaus on tallennettu galleriaan"</string> - <!-- no translation found for screenshot_failed_toast (1990979819772906912) --> - <skip /> + <!-- outdated translation 655180965533683356 --> <string name="screenshot_failed_toast" msgid="1990979819772906912">"Kuvakaappausta ei voitu tallentaa"</string> <string name="usb_preference_title" msgid="6551050377388882787">"USB-tiedostonsiirtoasetukset"</string> <string name="use_mtp_button_title" msgid="4333504413563023626">"Käytä mediasoittimena (MTP)"</string> <string name="use_ptp_button_title" msgid="7517127540301625751">"Käytä kamerana (PTP)"</string> diff --git a/packages/SystemUI/res/values-fr/strings.xml b/packages/SystemUI/res/values-fr/strings.xml index 858305f1eab2..b97ac2fbeeca 100644 --- a/packages/SystemUI/res/values-fr/strings.xml +++ b/packages/SystemUI/res/values-fr/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"Aucune carte SIM"</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Partage de connexion Bluetooth"</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Mode Avion"</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Batterie : <xliff:g id="NUMBER">%d</xliff:g> %"</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Bouton \"Paramètres\""</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Bouton \"Notifications\""</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Supprimer la notification"</string> diff --git a/packages/SystemUI/res/values-it/strings.xml b/packages/SystemUI/res/values-it/strings.xml index d4d5117c6c3e..c7ef3f6c94ad 100644 --- a/packages/SystemUI/res/values-it/strings.xml +++ b/packages/SystemUI/res/values-it/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"Nessuna SIM presente."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Tethering Bluetooth."</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Modalità aereo."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Batteria: <xliff:g id="NUMBER">%d</xliff:g>%."</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Pulsante Impostazioni."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Pulsante per le notifiche."</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Rimuovi la notifica."</string> diff --git a/packages/SystemUI/res/values-ja/strings.xml b/packages/SystemUI/res/values-ja/strings.xml index 2f3509a1fe2f..5ad4e2d5948b 100644 --- a/packages/SystemUI/res/values-ja/strings.xml +++ b/packages/SystemUI/res/values-ja/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"SIMがありません。"</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Bluetoothテザリング。"</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"機内モード。"</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"電池残量: <xliff:g id="NUMBER">%d</xliff:g>%"</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"設定ボタン。"</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"通知ボタン。"</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"通知を削除。"</string> diff --git a/packages/SystemUI/res/values-pt-rPT/strings.xml b/packages/SystemUI/res/values-pt-rPT/strings.xml index f264ef4c6b30..10d56113e3f1 100644 --- a/packages/SystemUI/res/values-pt-rPT/strings.xml +++ b/packages/SystemUI/res/values-pt-rPT/strings.xml @@ -60,8 +60,7 @@ <string name="compat_mode_help_header" msgid="7020175705401506719">"Compatibilidade de zoom"</string> <string name="compat_mode_help_body" msgid="4946726776359270040">"Sempre que uma aplicação tiver sido concebida para ecrãs mais pequenos, aparecerá um controlo de zoom junto ao relógio."</string> <string name="screenshot_saving_toast" msgid="8592630119048713208">"Captura de ecrã guardada na Galeria"</string> - <!-- no translation found for screenshot_failed_toast (1990979819772906912) --> - <skip /> + <!-- outdated translation 655180965533683356 --> <string name="screenshot_failed_toast" msgid="1990979819772906912">"Não foi possível guardar a captura de ecrã"</string> <string name="usb_preference_title" msgid="6551050377388882787">"Opções de transm. de fich. USB"</string> <string name="use_mtp_button_title" msgid="4333504413563023626">"Montar como leitor de multimédia (MTP)"</string> <string name="use_ptp_button_title" msgid="7517127540301625751">"Montar como câmara (PTP)"</string> diff --git a/packages/SystemUI/res/values-pt/strings.xml b/packages/SystemUI/res/values-pt/strings.xml index a6759fdf7540..07fb12b40a93 100644 --- a/packages/SystemUI/res/values-pt/strings.xml +++ b/packages/SystemUI/res/values-pt/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"Sem SIM."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Vínculo Bluetooth."</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Modo de avião."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Bateria em <xliff:g id="NUMBER">%d</xliff:g>%."</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Botão Configurações."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Botão de notificações."</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Remover notificação."</string> diff --git a/packages/SystemUI/res/values-ru/strings.xml b/packages/SystemUI/res/values-ru/strings.xml index 2dd0bd4a7cde..70a7c88eb660 100644 --- a/packages/SystemUI/res/values-ru/strings.xml +++ b/packages/SystemUI/res/values-ru/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"SIM-карта отсутствует."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Общий Bluetooth-модем."</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Режим полета."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Заряд батареи: <xliff:g id="NUMBER">%d</xliff:g>%"</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Кнопка вызова настроек."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Кнопка вызова панели уведомлений"</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Удалить уведомление."</string> diff --git a/packages/SystemUI/res/values-sk/strings.xml b/packages/SystemUI/res/values-sk/strings.xml index f6ab7e1348ce..b6a774cb7a69 100644 --- a/packages/SystemUI/res/values-sk/strings.xml +++ b/packages/SystemUI/res/values-sk/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"Žiadna karta SIM."</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"Zdieľanie dátového pripojenia cez Bluetooth."</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"Režim V lietadle."</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"Batéria <xliff:g id="NUMBER">%d</xliff:g> %"</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"Tlačidlo Nastavenia."</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"Tlačidlo upozornení."</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"Odstrániť upozornenie."</string> diff --git a/packages/SystemUI/res/values-zh-rCN/strings.xml b/packages/SystemUI/res/values-zh-rCN/strings.xml index 8aa9c62a9925..62e5a3eb696b 100644 --- a/packages/SystemUI/res/values-zh-rCN/strings.xml +++ b/packages/SystemUI/res/values-zh-rCN/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"无 SIM 卡。"</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"蓝牙绑定。"</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"飞行模式。"</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"电池电量为 <xliff:g id="NUMBER">%d</xliff:g>%。"</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"设置按钮。"</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"通知按钮。"</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"删除通知。"</string> diff --git a/packages/SystemUI/res/values-zh-rTW/strings.xml b/packages/SystemUI/res/values-zh-rTW/strings.xml index 17d082206359..54fbefb02e5a 100644 --- a/packages/SystemUI/res/values-zh-rTW/strings.xml +++ b/packages/SystemUI/res/values-zh-rTW/strings.xml @@ -104,7 +104,9 @@ <string name="accessibility_no_sim" msgid="8274017118472455155">"沒有 SIM 卡。"</string> <string name="accessibility_bluetooth_tether" msgid="4102784498140271969">"藍牙數據連線"</string> <string name="accessibility_airplane_mode" msgid="834748999790763092">"飛行模式。"</string> - <string name="accessibility_battery_level" msgid="7451474187113371965">"電池電量為 <xliff:g id="NUMBER">%d</xliff:g>%。"</string> + <!-- String.format failed for translation --> + <!-- no translation found for accessibility_battery_level (7451474187113371965) --> + <skip /> <string name="accessibility_settings_button" msgid="7913780116850379698">"設定按鈕。"</string> <string name="accessibility_notifications_button" msgid="2933903195211483438">"通知按鈕。"</string> <string name="accessibility_remove_notification" msgid="4883990503785778699">"移除通知。"</string> diff --git a/packages/SystemUI/res/values/attrs.xml b/packages/SystemUI/res/values/attrs.xml index b2b6d506b0ed..56d1295fc18e 100644 --- a/packages/SystemUI/res/values/attrs.xml +++ b/packages/SystemUI/res/values/attrs.xml @@ -16,7 +16,11 @@ <resources> <declare-styleable name="KeyButtonView"> + <!-- key code to send when pressed; if absent or 0, no key is sent --> <attr name="keyCode" format="integer" /> + <!-- does this button generate longpress / repeat events? --> + <attr name="keyRepeat" format="boolean" /> + <!-- drawable to use for a swelling, glowing background on press --> <attr name="glowBackground" format="reference" /> </declare-styleable> <declare-styleable name="ToggleSlider"> diff --git a/packages/SystemUI/src/com/android/systemui/SwipeHelper.java b/packages/SystemUI/src/com/android/systemui/SwipeHelper.java index 2818f875dcf0..e7ed0528a275 100644 --- a/packages/SystemUI/src/com/android/systemui/SwipeHelper.java +++ b/packages/SystemUI/src/com/android/systemui/SwipeHelper.java @@ -30,7 +30,7 @@ import android.view.View; public class SwipeHelper { static final String TAG = "com.android.systemui.SwipeHelper"; - private static final boolean DEBUG = true; + private static final boolean DEBUG = false; private static final boolean DEBUG_INVALIDATE = false; private static final boolean SLOW_ANIMATIONS = false; // DEBUG; @@ -142,7 +142,7 @@ public class SwipeHelper { // invalidate a rectangle relative to the view's coordinate system all the way up the view // hierarchy public static void invalidateGlobalRegion(View view, RectF childBounds) { - childBounds.offset(view.getX(), view.getY()); + //childBounds.offset(view.getTranslationX(), view.getTranslationY()); if (DEBUG_INVALIDATE) Log.v(TAG, "-------------"); while (view.getParent() != null && view.getParent() instanceof View) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java index abf505c5367c..c3f20bc3b313 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java @@ -29,6 +29,7 @@ import android.view.Display; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; +import android.view.ViewGroup; import android.view.Surface; import android.view.WindowManager; import android.widget.LinearLayout; @@ -67,6 +68,7 @@ public class NavigationBarView extends LinearLayout { public NavigationBarView(Context context, AttributeSet attrs) { super(context, attrs); + mHidden = false; mDisplay = ((WindowManager)context.getSystemService( @@ -129,6 +131,11 @@ public class NavigationBarView extends LinearLayout { ? findViewById(R.id.rot90) : findViewById(R.id.rot270); + for (View v : mRotatedViews) { + // this helps avoid drawing artifacts with glowing navigation keys + ViewGroup group = (ViewGroup) v.findViewById(R.id.nav_buttons); + group.setMotionEventSplittingEnabled(false); + } mCurrentView = mRotatedViews[Surface.ROTATION_0]; } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java index 38a10299fa12..6368d1d8549e 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java @@ -49,6 +49,8 @@ import com.android.systemui.R; public class KeyButtonView extends ImageView { private static final String TAG = "StatusBar.KeyButtonView"; + final float GLOW_MAX_SCALE_FACTOR = 1.8f; + IWindowManager mWindowManager; long mDownTime; boolean mSending; @@ -57,11 +59,12 @@ public class KeyButtonView extends ImageView { int mTouchSlop; Drawable mGlowBG; float mGlowAlpha = 0f, mGlowScale = 1f, mDrawingAlpha = 1f; + boolean mSupportsLongpress = true; Runnable mCheckLongPress = new Runnable() { public void run() { if (isPressed()) { - + // Slog.d("KeyButtonView", "longpressed: " + this); if (mCode != 0) { mRepeat++; sendEvent(KeyEvent.ACTION_DOWN, @@ -89,6 +92,8 @@ public class KeyButtonView extends ImageView { defStyle, 0); mCode = a.getInteger(R.styleable.KeyButtonView_keyCode, 0); + + mSupportsLongpress = a.getBoolean(R.styleable.KeyButtonView_keyRepeat, true); mGlowBG = a.getDrawable(R.styleable.KeyButtonView_glowBackground); if (mGlowBG != null) { @@ -156,17 +161,22 @@ public class KeyButtonView extends ImageView { mGlowScale = x; final float w = getWidth(); final float h = getHeight(); - if (x < 1.0f) { + if (GLOW_MAX_SCALE_FACTOR <= 1.0f) { + // this only works if we know the glow will never leave our bounds invalidate(); } else { - final float rx = (w * (x - 1.0f)) / 2.0f; - final float ry = (h * (x - 1.0f)) / 2.0f; + final float rx = (w * (GLOW_MAX_SCALE_FACTOR - 1.0f)) / 2.0f + 1.0f; + final float ry = (h * (GLOW_MAX_SCALE_FACTOR - 1.0f)) / 2.0f + 1.0f; com.android.systemui.SwipeHelper.invalidateGlobalRegion( this, new RectF(getLeft() - rx, getTop() - ry, getRight() + rx, getBottom() + ry)); + + // also invalidate our immediate parent to help avoid situations where nearby glows + // interfere + ((View)getParent()).invalidate(); } } @@ -180,7 +190,7 @@ public class KeyButtonView extends ImageView { setDrawingAlpha(1f); as.playTogether( ObjectAnimator.ofFloat(this, "glowAlpha", 1f), - ObjectAnimator.ofFloat(this, "glowScale", 1.8f) + ObjectAnimator.ofFloat(this, "glowScale", GLOW_MAX_SCALE_FACTOR) ); as.setDuration(50); } else { @@ -207,11 +217,19 @@ public class KeyButtonView extends ImageView { mDownTime = SystemClock.uptimeMillis(); mRepeat = 0; mSending = true; + setPressed(true); sendEvent(KeyEvent.ACTION_DOWN, KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, mDownTime); - setPressed(true); - removeCallbacks(mCheckLongPress); - postDelayed(mCheckLongPress, ViewConfiguration.getLongPressTimeout()); + if (mSupportsLongpress) { + removeCallbacks(mCheckLongPress); + postDelayed(mCheckLongPress, ViewConfiguration.getLongPressTimeout()); + } else { + mSending = false; + sendEvent(KeyEvent.ACTION_UP, + KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, mDownTime); + sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); + playSoundEffect(SoundEffectConstants.CLICK); + } break; case MotionEvent.ACTION_MOVE: if (mSending) { @@ -230,7 +248,9 @@ public class KeyButtonView extends ImageView { sendEvent(KeyEvent.ACTION_UP, KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY | KeyEvent.FLAG_CANCELED); - removeCallbacks(mCheckLongPress); + if (mSupportsLongpress) { + removeCallbacks(mCheckLongPress); + } } break; case MotionEvent.ACTION_UP: @@ -239,15 +259,15 @@ public class KeyButtonView extends ImageView { if (mSending) { mSending = false; final int flags = KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY; - removeCallbacks(mCheckLongPress); + if (mSupportsLongpress) { + removeCallbacks(mCheckLongPress); + } if (mCode != 0) { if (doIt) { sendEvent(KeyEvent.ACTION_UP, flags); sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); playSoundEffect(SoundEffectConstants.CLICK); - } else { - sendEvent(KeyEvent.ACTION_UP, flags | KeyEvent.FLAG_CANCELED); } } else { // no key code, just a regular ImageView diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java index e78711309bb3..201ff2d6c60f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java @@ -497,6 +497,8 @@ public class TabletStatusBar extends StatusBar implements mRecentButton = mNavigationArea.findViewById(R.id.recent_apps); mRecentButton.setOnClickListener(mOnClickListener); mNavigationArea.setLayoutTransition(mBarContentsLayoutTransition); + // no multi-touch on the nav buttons + mNavigationArea.setMotionEventSplittingEnabled(false); // The bar contents buttons mFeedbackIconArea = (ViewGroup)sb.findViewById(R.id.feedbackIconArea); @@ -966,11 +968,11 @@ public class TabletStatusBar extends StatusBar implements if ((diff & StatusBarManager.DISABLE_BACK) != 0) { if ((state & StatusBarManager.DISABLE_BACK) != 0) { Slog.i(TAG, "DISABLE_BACK: yes"); - mBackButton.setVisibility(View.INVISIBLE); + mBackButton.setEnabled(false); mInputMethodSwitchButton.setScreenLocked(true); } else { Slog.i(TAG, "DISABLE_BACK: no"); - mBackButton.setVisibility(View.VISIBLE); + mBackButton.setEnabled(true); mInputMethodSwitchButton.setScreenLocked(false); } } diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java index 0ee6488c1816..73e4338641fd 100644 --- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java +++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java @@ -386,6 +386,9 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback { // Ditch the menu created above st.menu = null; + // Don't show it in the action bar either + mActionBar.setMenu(null, mActionMenuPresenterCallback); + return false; } @@ -406,6 +409,9 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback { } if (!cb.onPreparePanel(st.featureId, st.createdPanelView, st.menu)) { + // The app didn't want to show the menu for now but it still exists. + // Clear it out of the action bar. + mActionBar.setMenu(null, mActionMenuPresenterCallback); st.menu.startDispatchingItemsChanged(); return false; } @@ -753,7 +759,7 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback { if (mPanelChordingKey != 0) { mPanelChordingKey = 0; - if (event.isCanceled()) { + if (event.isCanceled() || (mDecor != null && mDecor.mActionMode != null)) { return; } @@ -3139,6 +3145,7 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback { public boolean hasPanelItems() { if (shownPanelView == null) return false; + if (createdPanelView != null) return true; if (isCompact || isInExpandedMode) { return listMenuPresenter.getAdapter().getCount() > 0; diff --git a/services/input/InputDispatcher.cpp b/services/input/InputDispatcher.cpp index cbdfe8c4ac38..3cd3ac3c06e1 100644 --- a/services/input/InputDispatcher.cpp +++ b/services/input/InputDispatcher.cpp @@ -3196,10 +3196,12 @@ void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inpu LOGD("Focus left window: %s", mFocusedWindowHandle->name.string()); #endif - CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, - "focus left window"); - synthesizeCancelationEventsForInputChannelLocked( - mFocusedWindowHandle->inputChannel, options); + if (mFocusedWindowHandle->inputChannel != NULL) { + CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, + "focus left window"); + synthesizeCancelationEventsForInputChannelLocked( + mFocusedWindowHandle->inputChannel, options); + } } if (newFocusedWindowHandle != NULL) { #if DEBUG_FOCUS @@ -3216,10 +3218,12 @@ void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inpu #if DEBUG_FOCUS LOGD("Touched window was removed: %s", touchedWindow.windowHandle->name.string()); #endif - CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, - "touched window was removed"); - synthesizeCancelationEventsForInputChannelLocked( - touchedWindow.windowHandle->inputChannel, options); + if (touchedWindow.windowHandle->inputChannel != NULL) { + CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, + "touched window was removed"); + synthesizeCancelationEventsForInputChannelLocked( + touchedWindow.windowHandle->inputChannel, options); + } mTouchState.windows.removeAt(i--); } } diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java index a679ca72daa2..f5fd6bd866a5 100644 --- a/services/java/com/android/server/AppWidgetService.java +++ b/services/java/com/android/server/AppWidgetService.java @@ -817,11 +817,10 @@ class AppWidgetService extends IAppWidgetService.Stub } Provider lookupProviderLocked(ComponentName provider) { - final String className = provider.getClassName(); final int N = mInstalledProviders.size(); for (int i=0; i<N; i++) { Provider p = mInstalledProviders.get(i); - if (p.info.provider.equals(provider) || className.equals(p.info.oldName)) { + if (p.info.provider.equals(provider)) { return p; } } @@ -1006,11 +1005,6 @@ class AppWidgetService extends IAppWidgetService.Stub p = new Provider(); AppWidgetProviderInfo info = p.info = new AppWidgetProviderInfo(); - // If metaData was null, we would have returned earlier when getting - // the parser No need to do the check here - info.oldName = activityInfo.metaData.getString( - AppWidgetManager.META_DATA_APPWIDGET_OLD_NAME); - info.provider = component; p.uid = activityInfo.applicationInfo.uid; diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java index 33a4e51012d7..e9c91e6fbf25 100644 --- a/services/java/com/android/server/am/ActivityManagerService.java +++ b/services/java/com/android/server/am/ActivityManagerService.java @@ -10732,8 +10732,10 @@ public final class ActivityManagerService extends ActivityManagerNative if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r + " at " + b + ": apps=" + (b != null ? b.apps.size() : 0)); + + boolean inStopping = mStoppingServices.contains(r); if (b != null) { - if (b.apps.size() > 0) { + if (b.apps.size() > 0 && !inStopping) { // Applications have already bound since the last // unbind, so just rebind right here. requestServiceBindingLocked(r, b, true); @@ -10744,7 +10746,7 @@ public final class ActivityManagerService extends ActivityManagerNative } } - serviceDoneExecutingLocked(r, mStoppingServices.contains(r)); + serviceDoneExecutingLocked(r, inStopping); Binder.restoreCallingIdentity(origId); } diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java index 5967428a33b6..8fd4f9589df0 100644 --- a/services/java/com/android/server/wm/WindowManagerService.java +++ b/services/java/com/android/server/wm/WindowManagerService.java @@ -6573,8 +6573,10 @@ public class WindowManagerService extends IWindowManager.Stub } synchronized (mWindowMap) { // !!! TODO: ANR the drag-receiving app - mDragState.mDragResult = false; - mDragState.endDragLw(); + if (mDragState != null) { + mDragState.mDragResult = false; + mDragState.endDragLw(); + } } break; } diff --git a/services/surfaceflinger/Android.mk b/services/surfaceflinger/Android.mk index b178e4979b2c..51eb0a376d06 100644 --- a/services/surfaceflinger/Android.mk +++ b/services/surfaceflinger/Android.mk @@ -5,6 +5,7 @@ LOCAL_SRC_FILES:= \ Layer.cpp \ LayerBase.cpp \ LayerDim.cpp \ + DdmConnection.cpp \ DisplayHardware/DisplayHardware.cpp \ DisplayHardware/DisplayHardwareBase.cpp \ DisplayHardware/HWComposer.cpp \ @@ -36,6 +37,9 @@ LOCAL_SHARED_LIBRARIES := \ libui \ libgui +# this is only needed for DDMS debugging +LOCAL_SHARED_LIBRARIES += libdvm libandroid_runtime + LOCAL_C_INCLUDES := \ $(call include-path-for, corecg graphics) diff --git a/services/surfaceflinger/DdmConnection.cpp b/services/surfaceflinger/DdmConnection.cpp new file mode 100644 index 000000000000..467a915ed8b9 --- /dev/null +++ b/services/surfaceflinger/DdmConnection.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2011 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. + */ + +#include <android_runtime/AndroidRuntime.h> + +#include "jni.h" +#include "DdmConnection.h" + +extern "C" jint Java_com_android_internal_util_WithFramework_registerNatives( + JNIEnv* env, jclass clazz); + +namespace android { + +void DdmConnection::start(const char* name) { + JavaVM* vm; + JNIEnv* env; + + // start a VM + JavaVMInitArgs args; + JavaVMOption opt; + + opt.optionString = + "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y"; + + args.version = JNI_VERSION_1_4; + args.options = &opt; + args.nOptions = 1; + args.ignoreUnrecognized = JNI_FALSE; + + if (JNI_CreateJavaVM(&vm, &env, &args) == 0) { + jclass startClass; + jmethodID startMeth; + + // register native code + if (Java_com_android_internal_util_WithFramework_registerNatives(env, 0) == 0) { + // set our name by calling DdmHandleAppName.setAppName() + startClass = env->FindClass("android/ddm/DdmHandleAppName"); + if (startClass) { + startMeth = env->GetStaticMethodID(startClass, + "setAppName", "(Ljava/lang/String;)V"); + if (startMeth) { + jstring str = env->NewStringUTF(name); + env->CallStaticVoidMethod(startClass, startMeth, str); + env->DeleteLocalRef(str); + } + } + + // initialize DDMS communication by calling + // DdmRegister.registerHandlers() + startClass = env->FindClass("android/ddm/DdmRegister"); + if (startClass) { + startMeth = env->GetStaticMethodID(startClass, + "registerHandlers", "()V"); + if (startMeth) { + env->CallStaticVoidMethod(startClass, startMeth); + } + } + } + } +} + +}; // namespace android diff --git a/services/surfaceflinger/DdmConnection.h b/services/surfaceflinger/DdmConnection.h new file mode 100644 index 000000000000..91b737c92591 --- /dev/null +++ b/services/surfaceflinger/DdmConnection.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2011 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. + */ + +#ifndef ANDROID_SF_DDM_CONNECTION +#define ANDROID_SF_DDM_CONNECTION + +namespace android { + +class DdmConnection { +public: + static void start(const char* name); +}; + +}; // namespace android + +#endif /* ANDROID_SF_DDM_CONNECTION */ diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 082effe699f7..a68ab3055fe1 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -47,6 +47,7 @@ #include "clz.h" #include "GLExtensions.h" +#include "DdmConnection.h" #include "Layer.h" #include "LayerDim.h" #include "SurfaceFlinger.h" @@ -90,6 +91,7 @@ SurfaceFlinger::SurfaceFlinger() mFreezeDisplayTime(0), mDebugRegion(0), mDebugBackground(0), + mDebugDDMS(0), mDebugDisableHWC(0), mDebugInSwapBuffers(0), mLastSwapBufferTime(0), @@ -108,13 +110,22 @@ void SurfaceFlinger::init() // debugging stuff... char value[PROPERTY_VALUE_MAX]; + property_get("debug.sf.showupdates", value, "0"); mDebugRegion = atoi(value); + property_get("debug.sf.showbackground", value, "0"); mDebugBackground = atoi(value); + property_get("debug.sf.ddms", value, "0"); + mDebugDDMS = atoi(value); + if (mDebugDDMS) { + DdmConnection::start(getServiceName()); + } + LOGI_IF(mDebugRegion, "showupdates enabled"); LOGI_IF(mDebugBackground, "showbackground enabled"); + LOGI_IF(mDebugDDMS, "DDMS debugging enabled"); } SurfaceFlinger::~SurfaceFlinger() diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 6f93f5ba0ae5..89df0de55fd9 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -371,6 +371,7 @@ private: // don't use a lock for these, we don't care int mDebugRegion; int mDebugBackground; + int mDebugDDMS; int mDebugDisableHWC; volatile nsecs_t mDebugInSwapBuffers; nsecs_t mLastSwapBufferTime; diff --git a/tests/RenderScriptTests/ShadersTest/Android.mk b/tests/RenderScriptTests/ShadersTest/Android.mk new file mode 100644 index 000000000000..109b0a0e4bac --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/Android.mk @@ -0,0 +1,26 @@ +# +# Copyright (C) 2011 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. +# + +LOCAL_PATH := $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_MODULE_TAGS := optional + +LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src) + +LOCAL_PACKAGE_NAME := ShadersTest + +include $(BUILD_PACKAGE) diff --git a/tests/RenderScriptTests/ShadersTest/AndroidManifest.xml b/tests/RenderScriptTests/ShadersTest/AndroidManifest.xml new file mode 100644 index 000000000000..871200da6ad6 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/AndroidManifest.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2011 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. +--> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.shaderstest"> + + <uses-permission android:name="android.permission.INTERNET" /> + + <application android:label="_ShadersTest"> + <activity android:name="ShadersTest" + android:label="_ShadersTest" + android:theme="@android:style/Theme.Black.NoTitleBar"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + </application> +</manifest> diff --git a/tests/RenderScriptTests/ShadersTest/res/drawable-nodpi/robot.png b/tests/RenderScriptTests/ShadersTest/res/drawable-nodpi/robot.png Binary files differnew file mode 100644 index 000000000000..f7353fd61c5b --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/res/drawable-nodpi/robot.png diff --git a/tests/RenderScriptTests/ShadersTest/res/raw/depth_fs.glsl b/tests/RenderScriptTests/ShadersTest/res/raw/depth_fs.glsl new file mode 100644 index 000000000000..096843b1bb44 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/res/raw/depth_fs.glsl @@ -0,0 +1,13 @@ +void main() { + // Non-linear depth value + float z = gl_FragCoord.z; + // Near and far planes from the projection + // In practice, these values can be used to tweak + // the focus range + float n = UNI_near; + float f = UNI_far; + // Linear depth value + z = (2.0 * n) / (f + n - z * (f - n)); + + gl_FragColor = vec4(z, z, z, 1.0); +} diff --git a/tests/RenderScriptTests/ShadersTest/res/raw/robot.a3d b/tests/RenderScriptTests/ShadersTest/res/raw/robot.a3d Binary files differnew file mode 100644 index 000000000000..f48895cd8451 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/res/raw/robot.a3d diff --git a/tests/RenderScriptTests/ShadersTest/res/raw/vignette_fs.glsl b/tests/RenderScriptTests/ShadersTest/res/raw/vignette_fs.glsl new file mode 100644 index 000000000000..2dc1ea31b9d6 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/res/raw/vignette_fs.glsl @@ -0,0 +1,31 @@ +#define CRT_MASK + +varying vec2 varTex0; + +void main() { + lowp vec4 color = texture2D(UNI_Tex0, varTex0); + + vec2 powers = pow(abs((gl_FragCoord.xy / vec2(UNI_width, UNI_height)) - 0.5), vec2(2.0)); + float gradient = smoothstep(UNI_size - UNI_feather, UNI_size + UNI_feather, + powers.x + powers.y); + + color = vec4(mix(color.rgb, vec3(0.0), gradient), 1.0); + +#ifdef CRT_MASK + float vShift = gl_FragCoord.y; + if (mod(gl_FragCoord.x, 6.0) >= 3.0) { + vShift += 2.0; + } + + lowp vec3 r = vec3(0.95, 0.0, 0.2); + lowp vec3 g = vec3(0.2, 0.95, 0.0); + lowp vec3 b = vec3(0.0, 0.2, 0.95); + int channel = int(floor(mod(gl_FragCoord.x, 3.0))); + lowp vec4 crt = vec4(r[channel], g[channel], b[channel], 1.0); + crt *= clamp(floor(mod(vShift, 4.0)), 0.0, 1.0); + + color = (crt * color * 1.25) + 0.05; +#endif + + gl_FragColor = color; +} diff --git a/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTest.java b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTest.java new file mode 100644 index 000000000000..6803fbbf4016 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2011 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. + */ + +package com.android.shaderstest; + +import android.app.Activity; +import android.os.Bundle; + +@SuppressWarnings({"UnusedDeclaration"}) +public class ShadersTest extends Activity { + + private ShadersTestView mView; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + + mView = new ShadersTestView(this); + setContentView(mView); + } + + @Override + protected void onResume() { + super.onResume(); + mView.resume(); + } + + @Override + protected void onPause() { + super.onPause(); + mView.pause(); + } +} diff --git a/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTestRS.java b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTestRS.java new file mode 100644 index 000000000000..dad97e20417d --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTestRS.java @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2011 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. + */ + +package com.android.shaderstest; + +import android.content.res.Resources; +import android.renderscript.Allocation; +import android.renderscript.Element; +import android.renderscript.Element.DataKind; +import android.renderscript.Element.DataType; +import android.renderscript.FileA3D; +import android.renderscript.Mesh; +import android.renderscript.Program; +import android.renderscript.ProgramFragment; +import android.renderscript.ProgramFragmentFixedFunction; +import android.renderscript.ProgramStore; +import android.renderscript.ProgramStore.DepthFunc; +import android.renderscript.ProgramVertex; +import android.renderscript.ProgramVertexFixedFunction; +import android.renderscript.RSRuntimeException; +import android.renderscript.RenderScriptGL; +import android.renderscript.Sampler; +import android.renderscript.Type.Builder; + +@SuppressWarnings({"FieldCanBeLocal"}) +public class ShadersTestRS { + public ShadersTestRS() { + } + + public void init(RenderScriptGL rs, Resources res) { + mRS = rs; + mRes = res; + initRS(); + } + + public void surfaceChanged() { + initBuffers(mRS.getWidth(), mRS.getHeight()); + } + + private Resources mRes; + private RenderScriptGL mRS; + private Sampler mLinearClamp; + private Sampler mNearestClamp; + private ProgramStore mPSBackground; + private ProgramFragment mPFBackground; + private ProgramVertex mPVBackground; + private ProgramVertexFixedFunction.Constants mPVA; + + private ProgramFragment mPFVignette; + private ScriptField_VignetteConstants_s mFSVignetteConst; + + private Allocation mMeshTexture; + private Allocation mScreen; + private Allocation mScreenDepth; + + private ScriptField_MeshInfo mMeshes; + private ScriptC_shaderstest mScript; + + + public void onActionDown(float x, float y) { + mScript.invoke_onActionDown(x, y); + } + + public void onActionScale(float scale) { + mScript.invoke_onActionScale(scale); + } + + public void onActionMove(float x, float y) { + mScript.invoke_onActionMove(x, y); + } + + private void initPFS() { + ProgramStore.Builder b = new ProgramStore.Builder(mRS); + + b.setDepthFunc(DepthFunc.LESS); + b.setDitherEnabled(false); + b.setDepthMaskEnabled(true); + mPSBackground = b.create(); + + mScript.set_gPFSBackground(mPSBackground); + } + + private void initPF() { + mLinearClamp = Sampler.CLAMP_LINEAR(mRS); + mScript.set_gLinear(mLinearClamp); + + mNearestClamp = Sampler.CLAMP_NEAREST(mRS); + mScript.set_gNearest(mNearestClamp); + + ProgramFragmentFixedFunction.Builder b = new ProgramFragmentFixedFunction.Builder(mRS); + b.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.REPLACE, + ProgramFragmentFixedFunction.Builder.Format.RGBA, 0); + mPFBackground = b.create(); + mPFBackground.bindSampler(mLinearClamp, 0); + mScript.set_gPFBackground(mPFBackground); + + mFSVignetteConst = new ScriptField_VignetteConstants_s(mRS, 1); + mScript.bind_gFSVignetteConstants(mFSVignetteConst); + + ProgramFragment.Builder fs; + + fs = new ProgramFragment.Builder(mRS); + fs.setShader(mRes, R.raw.vignette_fs); + fs.addConstant(mFSVignetteConst.getAllocation().getType()); + fs.addTexture(Program.TextureType.TEXTURE_2D); + mPFVignette = fs.create(); + mPFVignette.bindConstants(mFSVignetteConst.getAllocation(), 0); + mScript.set_gPFVignette(mPFVignette); + } + + private void initPV() { + ProgramVertexFixedFunction.Builder pvb = new ProgramVertexFixedFunction.Builder(mRS); + mPVBackground = pvb.create(); + + mPVA = new ProgramVertexFixedFunction.Constants(mRS); + ((ProgramVertexFixedFunction) mPVBackground).bindConstants(mPVA); + + mScript.set_gPVBackground(mPVBackground); + } + + private void loadImage() { + mMeshTexture = Allocation.createFromBitmapResource(mRS, mRes, R.drawable.robot, + Allocation.MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE, + Allocation.USAGE_GRAPHICS_TEXTURE); + mScript.set_gTMesh(mMeshTexture); + } + + private void initMeshes(FileA3D model) { + int numEntries = model.getIndexEntryCount(); + int numMeshes = 0; + for (int i = 0; i < numEntries; i ++) { + FileA3D.IndexEntry entry = model.getIndexEntry(i); + if (entry != null && entry.getEntryType() == FileA3D.EntryType.MESH) { + numMeshes ++; + } + } + + if (numMeshes > 0) { + mMeshes = new ScriptField_MeshInfo(mRS, numMeshes); + + for (int i = 0; i < numEntries; i ++) { + FileA3D.IndexEntry entry = model.getIndexEntry(i); + if (entry != null && entry.getEntryType() == FileA3D.EntryType.MESH) { + Mesh mesh = entry.getMesh(); + mMeshes.set_mMesh(i, mesh, false); + mMeshes.set_mNumIndexSets(i, mesh.getPrimitiveCount(), false); + } + } + mMeshes.copyAll(); + } else { + throw new RSRuntimeException("No valid meshes in file"); + } + + mScript.bind_gMeshes(mMeshes); + mScript.invoke_updateMeshInfo(); + } + + private void initRS() { + mScript = new ScriptC_shaderstest(mRS, mRes, R.raw.shaderstest); + + initPFS(); + initPF(); + initPV(); + + loadImage(); + + initBuffers(1, 1); + + FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.robot); + initMeshes(model); + + mRS.bindRootScript(mScript); + } + + private void initBuffers(int width, int height) { + Builder b; + b = new Builder(mRS, Element.RGBA_8888(mRS)); + b.setX(width).setY(height); + mScreen = Allocation.createTyped(mRS, b.create(), + Allocation.USAGE_GRAPHICS_TEXTURE | Allocation.USAGE_GRAPHICS_RENDER_TARGET); + mScript.set_gScreen(mScreen); + + b = new Builder(mRS, Element.createPixel(mRS, DataType.UNSIGNED_16, DataKind.PIXEL_DEPTH)); + b.setX(width).setY(height); + mScreenDepth = Allocation.createTyped(mRS, b.create(), + Allocation.USAGE_GRAPHICS_RENDER_TARGET); + mScript.set_gScreenDepth(mScreenDepth); + } +} diff --git a/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTestView.java b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTestView.java new file mode 100644 index 000000000000..e0a540fb8c87 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/ShadersTestView.java @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2011 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. + */ + +package com.android.shaderstest; + +import android.content.Context; +import android.renderscript.RSSurfaceView; +import android.renderscript.RenderScriptGL; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.SurfaceHolder; + +public class ShadersTestView extends RSSurfaceView { + + private RenderScriptGL mRS; + private ShadersTestRS mRender; + + private ScaleGestureDetector mScaleDetector; + + private static final int INVALID_POINTER_ID = -1; + private int mActivePointerId = INVALID_POINTER_ID; + + public ShadersTestView(Context context) { + super(context); + ensureRenderScript(); + mScaleDetector = new ScaleGestureDetector(context, new ScaleListener()); + } + + private void ensureRenderScript() { + if (mRS == null) { + RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig(); + sc.setDepth(16, 24); + mRS = createRenderScriptGL(sc); + mRender = new ShadersTestRS(); + mRender.init(mRS, getResources()); + } + } + + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + ensureRenderScript(); + } + + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { + super.surfaceChanged(holder, format, w, h); + mRender.surfaceChanged(); + } + + @Override + protected void onDetachedFromWindow() { + mRender = null; + if (mRS != null) { + mRS = null; + destroyRenderScriptGL(); + } + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + mScaleDetector.onTouchEvent(ev); + + boolean ret = false; + float x = ev.getX(); + float y = ev.getY(); + + final int action = ev.getAction(); + + switch (action & MotionEvent.ACTION_MASK) { + case MotionEvent.ACTION_DOWN: { + mRender.onActionDown(x, y); + mActivePointerId = ev.getPointerId(0); + ret = true; + break; + } + case MotionEvent.ACTION_MOVE: { + if (!mScaleDetector.isInProgress()) { + mRender.onActionMove(x, y); + } + mRender.onActionDown(x, y); + ret = true; + break; + } + + case MotionEvent.ACTION_UP: { + mActivePointerId = INVALID_POINTER_ID; + break; + } + + case MotionEvent.ACTION_CANCEL: { + mActivePointerId = INVALID_POINTER_ID; + break; + } + + case MotionEvent.ACTION_POINTER_UP: { + final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) + >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; + final int pointerId = ev.getPointerId(pointerIndex); + if (pointerId == mActivePointerId) { + // This was our active pointer going up. Choose a new + // active pointer and adjust accordingly. + final int newPointerIndex = pointerIndex == 0 ? 1 : 0; + x = ev.getX(newPointerIndex); + y = ev.getY(newPointerIndex); + mRender.onActionDown(x, y); + mActivePointerId = ev.getPointerId(newPointerIndex); + } + break; + } + } + + return ret; + } + + private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { + @Override + public boolean onScale(ScaleGestureDetector detector) { + mRender.onActionScale(detector.getScaleFactor()); + return true; + } + } +} + + diff --git a/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/shaderstest.rs b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/shaderstest.rs new file mode 100644 index 000000000000..53f10f989319 --- /dev/null +++ b/tests/RenderScriptTests/ShadersTest/src/com/android/shaderstest/shaderstest.rs @@ -0,0 +1,193 @@ +// Copyright (C) 2011 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. + +#pragma version(1) + +#pragma rs java_package_name(com.android.shaderstest) + +#include "rs_graphics.rsh" + +rs_program_vertex gPVBackground; +rs_program_fragment gPFBackground; + +typedef struct VignetteConstants_s { + float size; + float feather; + float width; + float height; +} VignetteConstants; +VignetteConstants *gFSVignetteConstants; +rs_program_fragment gPFVignette; + +rs_allocation gTMesh; + +rs_sampler gLinear; +rs_sampler gNearest; + +rs_program_store gPFSBackground; + +rs_allocation gScreenDepth; +rs_allocation gScreen; + +typedef struct MeshInfo { + rs_mesh mMesh; + int mNumIndexSets; + float3 bBoxMin; + float3 bBoxMax; +} MeshInfo_t; +MeshInfo_t *gMeshes; + +static float3 gLookAt; + +static float gRotateX; +static float gRotateY; +static float gZoom; + +static float gLastX; +static float gLastY; + +void onActionDown(float x, float y) { + gLastX = x; + gLastY = y; +} + +void onActionScale(float scale) { + + gZoom *= 1.0f / scale; + gZoom = max(0.1f, min(gZoom, 500.0f)); +} + +void onActionMove(float x, float y) { + float dx = gLastX - x; + float dy = gLastY - y; + + if (fabs(dy) <= 2.0f) { + dy = 0.0f; + } + if (fabs(dx) <= 2.0f) { + dx = 0.0f; + } + + gRotateY -= dx; + if (gRotateY > 360) { + gRotateY -= 360; + } + if (gRotateY < 0) { + gRotateY += 360; + } + + gRotateX -= dy; + gRotateX = min(gRotateX, 80.0f); + gRotateX = max(gRotateX, -80.0f); + + gLastX = x; + gLastY = y; +} + +void init() { + gRotateX = 0.0f; + gRotateY = 0.0f; + gZoom = 50.0f; + gLookAt = 0.0f; +} + +void updateMeshInfo() { + rs_allocation allMeshes = rsGetAllocation(gMeshes); + int size = rsAllocationGetDimX(allMeshes); + gLookAt = 0.0f; + float minX, minY, minZ, maxX, maxY, maxZ; + for (int i = 0; i < size; i++) { + MeshInfo_t *info = (MeshInfo_t*)rsGetElementAt(allMeshes, i); + rsgMeshComputeBoundingBox(info->mMesh, + &minX, &minY, &minZ, + &maxX, &maxY, &maxZ); + info->bBoxMin = (minX, minY, minZ); + info->bBoxMax = (maxX, maxY, maxZ); + gLookAt += (info->bBoxMin + info->bBoxMax)*0.5f; + } + gLookAt = gLookAt / (float)size; +} + +static void renderAllMeshes() { + rs_allocation allMeshes = rsGetAllocation(gMeshes); + int size = rsAllocationGetDimX(allMeshes); + gLookAt = 0.0f; + float minX, minY, minZ, maxX, maxY, maxZ; + for (int i = 0; i < size; i++) { + MeshInfo_t *info = (MeshInfo_t*)rsGetElementAt(allMeshes, i); + rsgDrawMesh(info->mMesh); + } +} + +static void renderOffscreen() { + rsgBindProgramVertex(gPVBackground); + rs_matrix4x4 proj; + float aspect = (float) rsAllocationGetDimX(gScreen) / (float) rsAllocationGetDimY(gScreen); + rsMatrixLoadPerspective(&proj, 30.0f, aspect, 1.0f, 1000.0f); + rsgProgramVertexLoadProjectionMatrix(&proj); + + rsgBindProgramFragment(gPFBackground); + rsgBindTexture(gPFBackground, 0, gTMesh); + + rs_matrix4x4 matrix; + + rsMatrixLoadIdentity(&matrix); + rsMatrixTranslate(&matrix, gLookAt.x, gLookAt.y, gLookAt.z - gZoom); + rsMatrixRotate(&matrix, gRotateX, 1.0f, 0.0f, 0.0f); + rsMatrixRotate(&matrix, gRotateY, 0.0f, 1.0f, 0.0f); + rsgProgramVertexLoadModelMatrix(&matrix); + + renderAllMeshes(); +} + +static void drawOffscreenResult(int posX, int posY, float width, float height) { + // display the result d + rs_matrix4x4 proj, matrix; + rsMatrixLoadOrtho(&proj, 0, width, height, 0, -500, 500); + rsgProgramVertexLoadProjectionMatrix(&proj); + rsMatrixLoadIdentity(&matrix); + rsgProgramVertexLoadModelMatrix(&matrix); + float startX = posX, startY = posY; + rsgDrawQuadTexCoords(startX, startY, 0, 0, 1, + startX, startY + height, 0, 0, 0, + startX + width, startY + height, 0, 1, 0, + startX + width, startY, 0, 1, 1); +} + +int root(void) { + gFSVignetteConstants->size = 0.58f * 0.58f; + gFSVignetteConstants->feather = 0.2f; + gFSVignetteConstants->width = (float) rsAllocationGetDimX(gScreen); + gFSVignetteConstants->height = (float) rsAllocationGetDimY(gScreen); + + rsgBindProgramStore(gPFSBackground); + + // Render scene to fullscreenbuffer + rsgBindColorTarget(gScreen, 0); + rsgBindDepthTarget(gScreenDepth); + rsgClearDepth(1.0f); + rsgClearColor(1.0f, 1.0f, 1.0f, 0.0f); + renderOffscreen(); + + // Render on screen + rsgClearAllRenderTargets(); + rsgClearColor(1.0f, 1.0f, 1.0f, 1.0f); + rsgClearDepth(1.0f); + + rsgBindProgramFragment(gPFVignette); + rsgBindTexture(gPFVignette, 0, gScreen); + drawOffscreenResult(0, 0, rsgGetWidth(), rsgGetHeight()); + + return 0; +} |