diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..3a8b8b8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,62 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Overview + +StickerCamera is an Android app for taking/picking a photo, cropping it square, applying GPU filters, then overlaying movable/scalable/rotatable stickers and positional tags before saving locally. It started as a 2015-era project but the build toolchain and dependencies have since been **modernized** (AGP 8 / AndroidX / Java 17 — see below). The *app logic* is still legacy in places (e.g. legacy `android.hardware.Camera`, no runtime-permission handling), so watch for old patterns even though the toolchain is current. + +## Build & Run + +Gradle multi-module project driven by the wrapper. The toolchain is current: + +- Android Gradle Plugin **8.11.1**, Gradle **8.13**, `compileSdk 36`, `minSdk 26`, `targetSdk 36`. +- **Java 17** source/target. No Retrolambda (lambdas run natively). +- ButterKnife 10.x's annotation processor needs JDK-internal javac APIs; JDK 16+ encapsulates these, so `app/build.gradle` opens them via `--add-exports`/`--add-opens` on `JavaCompile` tasks. Keep that block if you touch the build script. + +```bash +./gradlew assembleDebug # build debug APK -> app/build/outputs/apk/ +./gradlew installDebug # build + install on a connected device/emulator +./gradlew :app:compileDebugJavaWithJavac # fast Java-only compile check +./gradlew clean +./gradlew lint # Android lint +./gradlew connectedAndroidTest # instrumentation tests (require a device/emulator) +``` + +There are effectively no real tests — `app/src/androidTest/.../ApplicationTest.java` is the empty Android Studio stub. Verify changes by running the app on a device. + +## Modules + +`settings.gradle` includes two modules: + +- **`:app`** — the application (package `com.github.skykai.stickercamera`; app classes live under `com.stickercamera`, `com.common`, `com.customview`). +- **`:ImageViewTouch`** — vendored zoomable/pannable image view, used as `com.imagezoom.ImageViewTouch`. The sticker overlay extends this. **Kept vendored on purpose**: the app's `MyImageViewDrawableOverlay`/`MyHighlightView` override many of `ImageViewTouchBase`'s protected methods, and this fork is repackaged to `com.imagezoom`, so it cannot be swapped for the upstream `it.sephiroth.android.library.imagezoom` Maven artifact without rewriting the overlay. + +GPU filters come from the **Maven dependency** `jp.co.cyberagent.android:gpuimage:2.1.0` (wasabeef fork), not a vendored module. Note its package layout: core classes (`GPUImageView`, `GPUImage`, `GPUImageRenderer`) are in `jp.co.cyberagent.android.gpuimage`, while all filter classes (`GPUImageFilter`, `GPUImageToneCurveFilter`, …) are in the **`jp.co.cyberagent.android.gpuimage.filter`** subpackage. + +## Architecture + +### Screen flow +`MainActivity` (gallery of saved creations; opens camera automatically when none exist) → `CameraActivity` (capture) or `AlbumActivity` (pick) → `CameraManager.processPhotoItem()` routes by aspect ratio: square images go straight to `PhotoProcessActivity`, others to `CropPhotoActivity` first. `PhotoProcessActivity` is the editor; `EditTextActivity` is a sub-screen for entering tag text. + +### Core singletons +- **`App`** (Application, registered in manifest) — initializes Universal Image Loader, caches `DisplayMetrics`, and exposes `dp2px`/`px2dp`, screen size, and `getApp()`. Reach global state through `App.getApp()`. +- **`CameraManager`** — opens the camera and keeps a `Stack` of camera-flow activities so the whole flow can be `close()`d at once. `CameraBaseActivity` auto-registers/unregisters with it; editor activities should extend it. +- **`EffectService`** — supplies the ordered list of `FilterEffect`s shown in the filter bar. + +### Photo editor (`PhotoProcessActivity`) — three independent overlay systems +1. **Filters**: a `GPUImageView` renders the bitmap. The app uses only the "原始" (NORMAL) pass and tone-curve `.acv` presets in `app/src/main/res/raw/`. `GPUImageFilterTools` is trimmed to exactly those (`FilterType` enum is NORMAL + `ACV_*`; each `ACV_*` maps to an `R.raw.*` curve via `GPUImageToneCurveFilter`). To add a filter: drop the `.acv`, add a `FilterType`, wire it in `GPUImageFilterTools`, and register it in `EffectService.getLocalFilters()`. +2. **Stickers**: `MyImageViewDrawableOverlay` (extends `ImageViewTouch`) hosts `MyHighlightView` handles drawing `StickerDrawable`s. `EffectUtil` adds/clears stickers and holds the static `addonList` (sticker drawables `R.drawable.sticker1..8`) plus the live overlay state. Add stickers by extending `addonList`. +3. **Tags**: `LabelView` (a positioned `TagItem`) placed via `LabelSelector`; tag text is edited in `EditTextActivity`. + +### Persistence +No database. Saved creations are a `List` serialized to JSON with **fastjson** and stored in SharedPreferences under `AppConstants.FEED_INFO` (via `DataUtils`). Output images are written through `FileUtils` (`getPhotoSavedPath()`), which uses **app-specific external storage** (`Context.getExternalFilesDir(...)`) — this works on all API levels without a storage permission, required because direct writes to public external storage fail under scoped storage / `targetSdk 36`. Universal Image Loader's disk cache uses `AppConstants.APP_IMAGE` and falls back to internal cache when external storage is unavailable. `largeHeap` is enabled because full-res bitmaps are processed in memory. + +### Cross-cutting conventions +- **AndroidX everywhere** — there are no `android.support.*` imports left. +- **`BaseActivity`** (extends `AppCompatActivity`) is the UI base: edge-to-edge via `WindowInsets` (the old SystemBarTint was removed), optional `CommonTitleBar` wiring, and dialog/toast/progress helpers delegated to `ActivityHelper` → `DialogHelper` (toasts are always posted via `runOnUiThread`). New activities should extend `BaseActivity` (or `CameraBaseActivity` inside the camera flow). +- **ButterKnife 10.x** for view injection — `@BindView`/`@OnClick` + `ButterKnife.bind(this)` (the modern API). +- **EventBus (greenrobot 3.x)** for loosely-coupled events between the editor and the main gallery — `@Subscribe`-annotated handlers (e.g. notifying that a new creation was saved). +- Lists use AndroidX **RecyclerView**; FABs use Material **FloatingActionButton**. +- The camera uses the legacy `android.hardware.Camera` API; `CameraHelper` selects `CameraHelperGB` vs `CameraHelperBase` by SDK level. **There is still no runtime-permission handling** (permissions are manifest-only) — a real gap under `targetSdk 36` for `CAMERA`; storage was sidestepped by writing to app-specific dirs instead of requesting `WRITE_EXTERNAL_STORAGE`. +- Reusable, app-agnostic helpers live in `com.common.util` (vendored Trinea android-common utils, pruned to only what the app uses); custom widgets/drawables live in `com.customview`. diff --git a/Gpu-Image/.gitignore b/Gpu-Image/.gitignore deleted file mode 100755 index 85e23b4..0000000 --- a/Gpu-Image/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -#Android generated -bin -gen -obj - -#Eclipse -#.project -#.classpath -.settings - -#IntelliJ IDEA -.idea -*.iml -*.ipr -*.iws -out - -#Checkstyle -.checkstyle - -#Maven -target -release.properties -pom.xml.* - -#Ant -build.xml -local.properties -proguard.cfg - -#OSX -.DS_Store diff --git a/Gpu-Image/AndroidManifest.xml b/Gpu-Image/AndroidManifest.xml deleted file mode 100755 index ee0e775..0000000 --- a/Gpu-Image/AndroidManifest.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/Gpu-Image/build.gradle b/Gpu-Image/build.gradle deleted file mode 100755 index fd9c608..0000000 --- a/Gpu-Image/build.gradle +++ /dev/null @@ -1,35 +0,0 @@ -apply plugin: 'com.android.library' - -android { - compileSdkVersion 22 - buildToolsVersion "22.0.1" - - defaultConfig { - minSdkVersion 15 - targetSdkVersion 22 - - versionCode = 1 - versionName = "1.0" - - } - - sourceSets { - main { - manifest.srcFile 'AndroidManifest.xml' - java.srcDirs = ['src'] - resources.srcDirs = ['src'] - aidl.srcDirs = ['src'] - renderscript.srcDirs = ['src'] - res.srcDirs = ['res'] - assets.srcDirs = ['assets'] - jni.srcDirs = ['jni'] - } - - instrumentTest.setRoot('tests') - } - - lintOptions { - abortOnError false - } - -} \ No newline at end of file diff --git a/Gpu-Image/gradle.properties b/Gpu-Image/gradle.properties deleted file mode 100755 index 9e16223..0000000 --- a/Gpu-Image/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -POM_NAME=GPUImage for Android Library -POM_ARTIFACT_ID=gpuimage-library -POM_PACKAGING=aar \ No newline at end of file diff --git a/Gpu-Image/libs/arm64-v8a/libgpuimage-library.so b/Gpu-Image/libs/arm64-v8a/libgpuimage-library.so deleted file mode 100755 index aeada07..0000000 Binary files a/Gpu-Image/libs/arm64-v8a/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/libs/armeabi-v7a/libgpuimage-library.so b/Gpu-Image/libs/armeabi-v7a/libgpuimage-library.so deleted file mode 100755 index 976a8e5..0000000 Binary files a/Gpu-Image/libs/armeabi-v7a/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/libs/armeabi/libgpuimage-library.so b/Gpu-Image/libs/armeabi/libgpuimage-library.so deleted file mode 100755 index 65a3f12..0000000 Binary files a/Gpu-Image/libs/armeabi/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/libs/mips/libgpuimage-library.so b/Gpu-Image/libs/mips/libgpuimage-library.so deleted file mode 100755 index 81c52ef..0000000 Binary files a/Gpu-Image/libs/mips/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/libs/mips64/libgpuimage-library.so b/Gpu-Image/libs/mips64/libgpuimage-library.so deleted file mode 100755 index 37590a2..0000000 Binary files a/Gpu-Image/libs/mips64/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/libs/x86/libgpuimage-library.so b/Gpu-Image/libs/x86/libgpuimage-library.so deleted file mode 100755 index 065a4fb..0000000 Binary files a/Gpu-Image/libs/x86/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/libs/x86_64/libgpuimage-library.so b/Gpu-Image/libs/x86_64/libgpuimage-library.so deleted file mode 100755 index 4ee7f58..0000000 Binary files a/Gpu-Image/libs/x86_64/libgpuimage-library.so and /dev/null differ diff --git a/Gpu-Image/proguard-project.txt b/Gpu-Image/proguard-project.txt deleted file mode 100755 index f2fe155..0000000 --- a/Gpu-Image/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/Gpu-Image/project.properties b/Gpu-Image/project.properties deleted file mode 100755 index 93c8c3c..0000000 --- a/Gpu-Image/project.properties +++ /dev/null @@ -1,15 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-21 -android.library=true diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage.java deleted file mode 100755 index e083917..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.annotation.TargetApi; -import android.app.ActivityManager; -import android.content.Context; -import android.content.pm.ConfigurationInfo; -import android.database.Cursor; -import android.graphics.Bitmap; -import android.graphics.Bitmap.CompressFormat; -import android.graphics.BitmapFactory; -import android.graphics.Matrix; -import android.graphics.PixelFormat; -import android.hardware.Camera; -import android.media.ExifInterface; -import android.media.MediaScannerConnection; -import android.net.Uri; -import android.opengl.GLSurfaceView; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Environment; -import android.os.Handler; -import android.provider.MediaStore; -import android.view.Display; -import android.view.WindowManager; - -import java.io.*; -import java.net.URL; -import java.util.List; -import java.util.concurrent.Semaphore; - -/** - * The main accessor for GPUImage functionality. This class helps to do common - * tasks through a simple interface. - */ -public class GPUImage { - private final Context mContext; - private final GPUImageRenderer mRenderer; - private GLSurfaceView mGlSurfaceView; - private GPUImageFilter mFilter; - private Bitmap mCurrentBitmap; - private ScaleType mScaleType = ScaleType.CENTER_CROP; - - /** - * Instantiates a new GPUImage object. - * - * @param context the context - */ - public GPUImage(final Context context) { - if (!supportsOpenGLES2(context)) { - throw new IllegalStateException("OpenGL ES 2.0 is not supported on this phone."); - } - - mContext = context; - mFilter = new GPUImageFilter(); - mRenderer = new GPUImageRenderer(mFilter); - } - - /** - * Checks if OpenGL ES 2.0 is supported on the current device. - * - * @param context the context - * @return true, if successful - */ - private boolean supportsOpenGLES2(final Context context) { - final ActivityManager activityManager = (ActivityManager) - context.getSystemService(Context.ACTIVITY_SERVICE); - final ConfigurationInfo configurationInfo = - activityManager.getDeviceConfigurationInfo(); - return configurationInfo.reqGlEsVersion >= 0x20000; - } - - /** - * Sets the GLSurfaceView which will display the preview. - * - * @param view the GLSurfaceView - */ - public void setGLSurfaceView(final GLSurfaceView view) { - mGlSurfaceView = view; - mGlSurfaceView.setEGLContextClientVersion(2); - mGlSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); - mGlSurfaceView.getHolder().setFormat(PixelFormat.RGBA_8888); - mGlSurfaceView.setRenderer(mRenderer); - mGlSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); - mGlSurfaceView.requestRender(); - } - - /** - * Request the preview to be rendered again. - */ - public void requestRender() { - if (mGlSurfaceView != null) { - mGlSurfaceView.requestRender(); - } - } - - /** - * Sets the up camera to be connected to GPUImage to get a filtered preview. - * - * @param camera the camera - */ - public void setUpCamera(final Camera camera) { - setUpCamera(camera, 0, false, false); - } - - /** - * Sets the up camera to be connected to GPUImage to get a filtered preview. - * - * @param camera the camera - * @param degrees by how many degrees the image should be rotated - * @param flipHorizontal if the image should be flipped horizontally - * @param flipVertical if the image should be flipped vertically - */ - public void setUpCamera(final Camera camera, final int degrees, final boolean flipHorizontal, - final boolean flipVertical) { - mGlSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) { - setUpCameraGingerbread(camera); - } else { - camera.setPreviewCallback(mRenderer); - camera.startPreview(); - } - Rotation rotation = Rotation.NORMAL; - switch (degrees) { - case 90: - rotation = Rotation.ROTATION_90; - break; - case 180: - rotation = Rotation.ROTATION_180; - break; - case 270: - rotation = Rotation.ROTATION_270; - break; - } - mRenderer.setRotationCamera(rotation, flipHorizontal, flipVertical); - } - - @TargetApi(11) - private void setUpCameraGingerbread(final Camera camera) { - mRenderer.setUpSurfaceTexture(camera); - } - - /** - * Sets the filter which should be applied to the image which was (or will - * be) set by setImage(...). - * - * @param filter the new filter - */ - public void setFilter(final GPUImageFilter filter) { - mFilter = filter; - mRenderer.setFilter(mFilter); - requestRender(); - } - - /** - * Sets the image on which the filter should be applied. - * - * @param bitmap the new image - */ - public void setImage(final Bitmap bitmap) { - mCurrentBitmap = bitmap; - mRenderer.setImageBitmap(bitmap, false); - requestRender(); - } - - /** - * This sets the scale type of GPUImage. This has to be run before setting the image. - * If image is set and scale type changed, image needs to be reset. - * - * @param scaleType The new ScaleType - */ - public void setScaleType(ScaleType scaleType) { - mScaleType = scaleType; - mRenderer.setScaleType(scaleType); - mRenderer.deleteImage(); - mCurrentBitmap = null; - requestRender(); - } - - /** - * Sets the rotation of the displayed image. - * - * @param rotation new rotation - */ - public void setRotation(Rotation rotation) { - mRenderer.setRotation(rotation); - } - - /** - * Deletes the current image. - */ - public void deleteImage() { - mRenderer.deleteImage(); - mCurrentBitmap = null; - requestRender(); - } - - /** - * Sets the image on which the filter should be applied from a Uri. - * - * @param uri the uri of the new image - */ - public void setImage(final Uri uri) { - new LoadImageUriTask(this, uri).execute(); - } - - /** - * Sets the image on which the filter should be applied from a File. - * - * @param file the file of the new image - */ - public void setImage(final File file) { - new LoadImageFileTask(this, file).execute(); - } - - private String getPath(final Uri uri) { - String[] projection = { - MediaStore.Images.Media.DATA, - }; - Cursor cursor = mContext.getContentResolver() - .query(uri, projection, null, null, null); - int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); - String path = null; - if (cursor.moveToFirst()) { - path = cursor.getString(pathIndex); - } - cursor.close(); - return path; - } - - /** - * Gets the current displayed image with applied filter as a Bitmap. - * - * @return the current image with filter applied - */ - public Bitmap getBitmapWithFilterApplied() { - return getBitmapWithFilterApplied(mCurrentBitmap); - } - - /** - * Gets the given bitmap with current filter applied as a Bitmap. - * - * @param bitmap the bitmap on which the current filter should be applied - * @return the bitmap with filter applied - */ - public Bitmap getBitmapWithFilterApplied(final Bitmap bitmap) { - if (mGlSurfaceView != null) { - mRenderer.deleteImage(); - mRenderer.runOnDraw(new Runnable() { - - @Override - public void run() { - synchronized(mFilter) { - mFilter.destroy(); - mFilter.notify(); - } - } - }); - synchronized(mFilter) { - requestRender(); - try { - mFilter.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - GPUImageRenderer renderer = new GPUImageRenderer(mFilter); - renderer.setRotation(Rotation.NORMAL, - mRenderer.isFlippedHorizontally(), mRenderer.isFlippedVertically()); - renderer.setScaleType(mScaleType); - PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight()); - buffer.setRenderer(renderer); - renderer.setImageBitmap(bitmap, false); - Bitmap result = buffer.getBitmap(); - mFilter.destroy(); - renderer.deleteImage(); - buffer.destroy(); - - mRenderer.setFilter(mFilter); - if (mCurrentBitmap != null) { - mRenderer.setImageBitmap(mCurrentBitmap, false); - } - requestRender(); - - return result; - } - - /** - * Gets the images for multiple filters on a image. This can be used to - * quickly get thumbnail images for filters.
- * Whenever a new Bitmap is ready, the listener will be called with the - * bitmap. The order of the calls to the listener will be the same as the - * filter order. - * - * @param bitmap the bitmap on which the filters will be applied - * @param filters the filters which will be applied on the bitmap - * @param listener the listener on which the results will be notified - */ - public static void getBitmapForMultipleFilters(final Bitmap bitmap, - final List filters, final ResponseListener listener) { - if (filters.isEmpty()) { - return; - } - GPUImageRenderer renderer = new GPUImageRenderer(filters.get(0)); - renderer.setImageBitmap(bitmap, false); - PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight()); - buffer.setRenderer(renderer); - - for (GPUImageFilter filter : filters) { - renderer.setFilter(filter); - listener.response(buffer.getBitmap()); - filter.destroy(); - } - renderer.deleteImage(); - buffer.destroy(); - } - - /** - * Deprecated: Please use - * {@link GPUImageView#saveToPictures(String, String, jp.co.cyberagent.android.gpuimage.GPUImageView.OnPictureSavedListener)} - * - * Save current image with applied filter to Pictures. It will be stored on - * the default Picture folder on the phone below the given folderName and - * fileName.
- * This method is async and will notify when the image was saved through the - * listener. - * - * @param folderName the folder name - * @param fileName the file name - * @param listener the listener - */ - @Deprecated - public void saveToPictures(final String folderName, final String fileName, - final OnPictureSavedListener listener) { - saveToPictures(mCurrentBitmap, folderName, fileName, listener); - } - - /** - * Deprecated: Please use - * {@link GPUImageView#saveToPictures(String, String, jp.co.cyberagent.android.gpuimage.GPUImageView.OnPictureSavedListener)} - * - * Apply and save the given bitmap with applied filter to Pictures. It will - * be stored on the default Picture folder on the phone below the given - * folerName and fileName.
- * This method is async and will notify when the image was saved through the - * listener. - * - * @param bitmap the bitmap - * @param folderName the folder name - * @param fileName the file name - * @param listener the listener - */ - @Deprecated - public void saveToPictures(final Bitmap bitmap, final String folderName, final String fileName, - final OnPictureSavedListener listener) { - new SaveTask(bitmap, folderName, fileName, listener).execute(); - } - - /** - * Runs the given Runnable on the OpenGL thread. - * - * @param runnable The runnable to be run on the OpenGL thread. - */ - void runOnGLThread(Runnable runnable) { - mRenderer.runOnDrawEnd(runnable); - } - - private int getOutputWidth() { - if (mRenderer != null && mRenderer.getFrameWidth() != 0) { - return mRenderer.getFrameWidth(); - } else if (mCurrentBitmap != null) { - return mCurrentBitmap.getWidth(); - } else { - WindowManager windowManager = - (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); - Display display = windowManager.getDefaultDisplay(); - return display.getWidth(); - } - } - - private int getOutputHeight() { - if (mRenderer != null && mRenderer.getFrameHeight() != 0) { - return mRenderer.getFrameHeight(); - } else if (mCurrentBitmap != null) { - return mCurrentBitmap.getHeight(); - } else { - WindowManager windowManager = - (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); - Display display = windowManager.getDefaultDisplay(); - return display.getHeight(); - } - } - - @Deprecated - private class SaveTask extends AsyncTask { - - private final Bitmap mBitmap; - private final String mFolderName; - private final String mFileName; - private final OnPictureSavedListener mListener; - private final Handler mHandler; - - public SaveTask(final Bitmap bitmap, final String folderName, final String fileName, - final OnPictureSavedListener listener) { - mBitmap = bitmap; - mFolderName = folderName; - mFileName = fileName; - mListener = listener; - mHandler = new Handler(); - } - - @Override - protected Void doInBackground(final Void... params) { - Bitmap result = getBitmapWithFilterApplied(mBitmap); - saveImage(mFolderName, mFileName, result); - return null; - } - - private void saveImage(final String folderName, final String fileName, final Bitmap image) { - File path = Environment - .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); - File file = new File(path, folderName + "/" + fileName); - try { - file.getParentFile().mkdirs(); - image.compress(CompressFormat.JPEG, 80, new FileOutputStream(file)); - MediaScannerConnection.scanFile(mContext, - new String[] { - file.toString() - }, null, - new MediaScannerConnection.OnScanCompletedListener() { - @Override - public void onScanCompleted(final String path, final Uri uri) { - if (mListener != null) { - mHandler.post(new Runnable() { - - @Override - public void run() { - mListener.onPictureSaved(uri); - } - }); - } - } - }); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - } - - public interface OnPictureSavedListener { - void onPictureSaved(Uri uri); - } - - private class LoadImageUriTask extends LoadImageTask { - - private final Uri mUri; - - public LoadImageUriTask(GPUImage gpuImage, Uri uri) { - super(gpuImage); - mUri = uri; - } - - @Override - protected Bitmap decode(BitmapFactory.Options options) { - try { - InputStream inputStream; - if (mUri.getScheme().startsWith("http") || mUri.getScheme().startsWith("https")) { - inputStream = new URL(mUri.toString()).openStream(); - } else { - inputStream = mContext.getContentResolver().openInputStream(mUri); - } - return BitmapFactory.decodeStream(inputStream, null, options); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - @Override - protected int getImageOrientation() throws IOException { - Cursor cursor = mContext.getContentResolver().query(mUri, - new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null); - - if (cursor == null || cursor.getCount() != 1) { - return 0; - } - - cursor.moveToFirst(); - int orientation = cursor.getInt(0); - cursor.close(); - return orientation; - } - } - - private class LoadImageFileTask extends LoadImageTask { - - private final File mImageFile; - - public LoadImageFileTask(GPUImage gpuImage, File file) { - super(gpuImage); - mImageFile = file; - } - - @Override - protected Bitmap decode(BitmapFactory.Options options) { - return BitmapFactory.decodeFile(mImageFile.getAbsolutePath(), options); - } - - @Override - protected int getImageOrientation() throws IOException { - ExifInterface exif = new ExifInterface(mImageFile.getAbsolutePath()); - int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); - switch (orientation) { - case ExifInterface.ORIENTATION_NORMAL: - return 0; - case ExifInterface.ORIENTATION_ROTATE_90: - return 90; - case ExifInterface.ORIENTATION_ROTATE_180: - return 180; - case ExifInterface.ORIENTATION_ROTATE_270: - return 270; - default: - return 0; - } - } - } - - private abstract class LoadImageTask extends AsyncTask { - - private final GPUImage mGPUImage; - private int mOutputWidth; - private int mOutputHeight; - - @SuppressWarnings("deprecation") - public LoadImageTask(final GPUImage gpuImage) { - mGPUImage = gpuImage; - } - - @Override - protected Bitmap doInBackground(Void... params) { - if (mRenderer != null && mRenderer.getFrameWidth() == 0) { - try { - synchronized (mRenderer.mSurfaceChangedWaiter) { - mRenderer.mSurfaceChangedWaiter.wait(3000); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - mOutputWidth = getOutputWidth(); - mOutputHeight = getOutputHeight(); - return loadResizedImage(); - } - - @Override - protected void onPostExecute(Bitmap bitmap) { - super.onPostExecute(bitmap); - mGPUImage.deleteImage(); - mGPUImage.setImage(bitmap); - } - - protected abstract Bitmap decode(BitmapFactory.Options options); - - private Bitmap loadResizedImage() { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - decode(options); - int scale = 1; - while (checkSize(options.outWidth / scale > mOutputWidth, options.outHeight / scale > mOutputHeight)) { - scale++; - } - - scale--; - if (scale < 1) { - scale = 1; - } - options = new BitmapFactory.Options(); - options.inSampleSize = scale; - options.inPreferredConfig = Bitmap.Config.RGB_565; - options.inPurgeable = true; - options.inTempStorage = new byte[32 * 1024]; - Bitmap bitmap = decode(options); - if (bitmap == null) { - return null; - } - bitmap = rotateImage(bitmap); - bitmap = scaleBitmap(bitmap); - return bitmap; - } - - private Bitmap scaleBitmap(Bitmap bitmap) { - // resize to desired dimensions - int width = bitmap.getWidth(); - int height = bitmap.getHeight(); - int[] newSize = getScaleSize(width, height); - Bitmap workBitmap = Bitmap.createScaledBitmap(bitmap, newSize[0], newSize[1], true); - if (workBitmap != bitmap) { - bitmap.recycle(); - bitmap = workBitmap; - System.gc(); - } - - if (mScaleType == ScaleType.CENTER_CROP) { - // Crop it - int diffWidth = newSize[0] - mOutputWidth; - int diffHeight = newSize[1] - mOutputHeight; - workBitmap = Bitmap.createBitmap(bitmap, diffWidth / 2, diffHeight / 2, - newSize[0] - diffWidth, newSize[1] - diffHeight); - if (workBitmap != bitmap) { - bitmap.recycle(); - bitmap = workBitmap; - } - } - - return bitmap; - } - - /** - * Retrieve the scaling size for the image dependent on the ScaleType.
- *
- * If CROP: sides are same size or bigger than output's sides
- * Else : sides are same size or smaller than output's sides - */ - private int[] getScaleSize(int width, int height) { - float newWidth; - float newHeight; - - float withRatio = (float) width / mOutputWidth; - float heightRatio = (float) height / mOutputHeight; - - boolean adjustWidth = mScaleType == ScaleType.CENTER_CROP - ? withRatio > heightRatio : withRatio < heightRatio; - - if (adjustWidth) { - newHeight = mOutputHeight; - newWidth = (newHeight / height) * width; - } else { - newWidth = mOutputWidth; - newHeight = (newWidth / width) * height; - } - return new int[]{Math.round(newWidth), Math.round(newHeight)}; - } - - private boolean checkSize(boolean widthBigger, boolean heightBigger) { - if (mScaleType == ScaleType.CENTER_CROP) { - return widthBigger && heightBigger; - } else { - return widthBigger || heightBigger; - } - } - - private Bitmap rotateImage(final Bitmap bitmap) { - if (bitmap == null) { - return null; - } - Bitmap rotatedBitmap = bitmap; - try { - int orientation = getImageOrientation(); - if (orientation != 0) { - Matrix matrix = new Matrix(); - matrix.postRotate(orientation); - rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), - bitmap.getHeight(), matrix, true); - bitmap.recycle(); - } - } catch (IOException e) { - e.printStackTrace(); - } - return rotatedBitmap; - } - - protected abstract int getImageOrientation() throws IOException; - } - - public interface ResponseListener { - void response(T item); - } - - public enum ScaleType { CENTER_INSIDE, CENTER_CROP } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage3x3ConvolutionFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage3x3ConvolutionFilter.java deleted file mode 100755 index 0c5e5a0..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage3x3ConvolutionFilter.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Runs a 3x3 convolution kernel against the image - */ -public class GPUImage3x3ConvolutionFilter extends GPUImage3x3TextureSamplingFilter { - public static final String THREE_X_THREE_TEXTURE_SAMPLING_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform mediump mat3 convolutionMatrix;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - " mediump vec4 bottomColor = texture2D(inputImageTexture, bottomTextureCoordinate);\n" + - " mediump vec4 bottomLeftColor = texture2D(inputImageTexture, bottomLeftTextureCoordinate);\n" + - " mediump vec4 bottomRightColor = texture2D(inputImageTexture, bottomRightTextureCoordinate);\n" + - " mediump vec4 centerColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 leftColor = texture2D(inputImageTexture, leftTextureCoordinate);\n" + - " mediump vec4 rightColor = texture2D(inputImageTexture, rightTextureCoordinate);\n" + - " mediump vec4 topColor = texture2D(inputImageTexture, topTextureCoordinate);\n" + - " mediump vec4 topRightColor = texture2D(inputImageTexture, topRightTextureCoordinate);\n" + - " mediump vec4 topLeftColor = texture2D(inputImageTexture, topLeftTextureCoordinate);\n" + - "\n" + - " mediump vec4 resultColor = topLeftColor * convolutionMatrix[0][0] + topColor * convolutionMatrix[0][1] + topRightColor * convolutionMatrix[0][2];\n" + - " resultColor += leftColor * convolutionMatrix[1][0] + centerColor * convolutionMatrix[1][1] + rightColor * convolutionMatrix[1][2];\n" + - " resultColor += bottomLeftColor * convolutionMatrix[2][0] + bottomColor * convolutionMatrix[2][1] + bottomRightColor * convolutionMatrix[2][2];\n" + - "\n" + - " gl_FragColor = resultColor;\n" + - "}"; - - private float[] mConvolutionKernel; - private int mUniformConvolutionMatrix; - - /** - * Instantiates a new GPUimage3x3ConvolutionFilter with default values, that - * will look like the original image. - */ - public GPUImage3x3ConvolutionFilter() { - this(new float[] { - 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f - }); - } - - /** - * Instantiates a new GPUimage3x3ConvolutionFilter with given convolution kernel. - * - * @param convolutionKernel the convolution kernel - */ - public GPUImage3x3ConvolutionFilter(final float[] convolutionKernel) { - super(THREE_X_THREE_TEXTURE_SAMPLING_FRAGMENT_SHADER); - mConvolutionKernel = convolutionKernel; - } - - @Override - public void onInit() { - super.onInit(); - mUniformConvolutionMatrix = GLES20.glGetUniformLocation(getProgram(), "convolutionMatrix"); - setConvolutionKernel(mConvolutionKernel); - } - - /** - * Sets the convolution kernel. - * - * @param convolutionKernel the new convolution kernel - */ - public void setConvolutionKernel(final float[] convolutionKernel) { - mConvolutionKernel = convolutionKernel; - setUniformMatrix3f(mUniformConvolutionMatrix, mConvolutionKernel); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage3x3TextureSamplingFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage3x3TextureSamplingFilter.java deleted file mode 100755 index 2e6820a..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImage3x3TextureSamplingFilter.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImage3x3TextureSamplingFilter extends GPUImageFilter { - public static final String THREE_X_THREE_TEXTURE_SAMPLING_VERTEX_SHADER = "" + - "attribute vec4 position;\n" + - "attribute vec4 inputTextureCoordinate;\n" + - "\n" + - "uniform highp float texelWidth; \n" + - "uniform highp float texelHeight; \n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - " gl_Position = position;\n" + - "\n" + - " vec2 widthStep = vec2(texelWidth, 0.0);\n" + - " vec2 heightStep = vec2(0.0, texelHeight);\n" + - " vec2 widthHeightStep = vec2(texelWidth, texelHeight);\n" + - " vec2 widthNegativeHeightStep = vec2(texelWidth, -texelHeight);\n" + - "\n" + - " textureCoordinate = inputTextureCoordinate.xy;\n" + - " leftTextureCoordinate = inputTextureCoordinate.xy - widthStep;\n" + - " rightTextureCoordinate = inputTextureCoordinate.xy + widthStep;\n" + - "\n" + - " topTextureCoordinate = inputTextureCoordinate.xy - heightStep;\n" + - " topLeftTextureCoordinate = inputTextureCoordinate.xy - widthHeightStep;\n" + - " topRightTextureCoordinate = inputTextureCoordinate.xy + widthNegativeHeightStep;\n" + - "\n" + - " bottomTextureCoordinate = inputTextureCoordinate.xy + heightStep;\n" + - " bottomLeftTextureCoordinate = inputTextureCoordinate.xy - widthNegativeHeightStep;\n" + - " bottomRightTextureCoordinate = inputTextureCoordinate.xy + widthHeightStep;\n" + - "}"; - - private int mUniformTexelWidthLocation; - private int mUniformTexelHeightLocation; - - private boolean mHasOverriddenImageSizeFactor = false; - private float mTexelWidth; - private float mTexelHeight; - private float mLineSize = 1.0f; - - public GPUImage3x3TextureSamplingFilter() { - this(NO_FILTER_VERTEX_SHADER); - } - - public GPUImage3x3TextureSamplingFilter(final String fragmentShader) { - super(THREE_X_THREE_TEXTURE_SAMPLING_VERTEX_SHADER, fragmentShader); - } - - @Override - public void onInit() { - super.onInit(); - mUniformTexelWidthLocation = GLES20.glGetUniformLocation(getProgram(), "texelWidth"); - mUniformTexelHeightLocation = GLES20.glGetUniformLocation(getProgram(), "texelHeight"); - if (mTexelWidth != 0) { - updateTexelValues(); - } - } - - @Override - public void onOutputSizeChanged(final int width, final int height) { - super.onOutputSizeChanged(width, height); - if (!mHasOverriddenImageSizeFactor) { - setLineSize(mLineSize); - } - } - - public void setTexelWidth(final float texelWidth) { - mHasOverriddenImageSizeFactor = true; - mTexelWidth = texelWidth; - setFloat(mUniformTexelWidthLocation, texelWidth); - } - - public void setTexelHeight(final float texelHeight) { - mHasOverriddenImageSizeFactor = true; - mTexelHeight = texelHeight; - setFloat(mUniformTexelHeightLocation, texelHeight); - } - - public void setLineSize(final float size) { - mLineSize = size; - mTexelWidth = size / getOutputWidth(); - mTexelHeight = size / getOutputHeight(); - updateTexelValues(); - } - - private void updateTexelValues() { - setFloat(mUniformTexelWidthLocation, mTexelWidth); - setFloat(mUniformTexelHeightLocation, mTexelHeight); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageAddBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageAddBlendFilter.java deleted file mode 100755 index 59dcb34..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageAddBlendFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageAddBlendFilter extends GPUImageTwoInputFilter { - public static final String ADD_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - "\n" + - " mediump float r;\n" + - " if (overlay.r * base.a + base.r * overlay.a >= overlay.a * base.a) {\n" + - " r = overlay.a * base.a + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " } else {\n" + - " r = overlay.r + base.r;\n" + - " }\n" + - "\n" + - " mediump float g;\n" + - " if (overlay.g * base.a + base.g * overlay.a >= overlay.a * base.a) {\n" + - " g = overlay.a * base.a + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - " } else {\n" + - " g = overlay.g + base.g;\n" + - " }\n" + - "\n" + - " mediump float b;\n" + - " if (overlay.b * base.a + base.b * overlay.a >= overlay.a * base.a) {\n" + - " b = overlay.a * base.a + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - " } else {\n" + - " b = overlay.b + base.b;\n" + - " }\n" + - "\n" + - " mediump float a = overlay.a + base.a - overlay.a * base.a;\n" + - " \n" + - " gl_FragColor = vec4(r, g, b, a);\n" + - " }"; - - public GPUImageAddBlendFilter() { - super(ADD_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageAlphaBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageAlphaBlendFilter.java deleted file mode 100755 index 753c24d..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageAlphaBlendFilter.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * Mix ranges from 0.0 (only image 1) to 1.0 (only image 2), with 0.5 (half of either) as the normal level - */ -public class GPUImageAlphaBlendFilter extends GPUImageMixBlendFilter{ - public static final String ALPHA_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " uniform lowp float mixturePercent;\n" + - "\n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - "\n" + - " gl_FragColor = vec4(mix(textureColor.rgb, textureColor2.rgb, textureColor2.a * mixturePercent), textureColor.a);\n" + - " }"; - - public GPUImageAlphaBlendFilter() { - super(ALPHA_BLEND_FRAGMENT_SHADER); - } - - public GPUImageAlphaBlendFilter(float mix) { - super(ALPHA_BLEND_FRAGMENT_SHADER, mix); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBoxBlurFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBoxBlurFilter.java deleted file mode 100755 index 4e681b3..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBoxBlurFilter.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * A hardware-accelerated 9-hit box blur of an image - * - * scaling: for the size of the applied blur, default of 1.0 - */ -public class GPUImageBoxBlurFilter extends GPUImageTwoPassTextureSamplingFilter { - public static final String VERTEX_SHADER = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset; \n" + - "uniform float texelHeightOffset; \n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepLeftTextureCoordinate;\n" + - "varying vec2 twoStepsLeftTextureCoordinate;\n" + - "varying vec2 oneStepRightTextureCoordinate;\n" + - "varying vec2 twoStepsRightTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 firstOffset = vec2(1.5 * texelWidthOffset, 1.5 * texelHeightOffset);\n" + - "vec2 secondOffset = vec2(3.5 * texelWidthOffset, 3.5 * texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepLeftTextureCoordinate = inputTextureCoordinate - firstOffset;\n" + - "twoStepsLeftTextureCoordinate = inputTextureCoordinate - secondOffset;\n" + - "oneStepRightTextureCoordinate = inputTextureCoordinate + firstOffset;\n" + - "twoStepsRightTextureCoordinate = inputTextureCoordinate + secondOffset;\n" + - "}\n"; - - public static final String FRAGMENT_SHADER = - "precision highp float;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepLeftTextureCoordinate;\n" + - "varying vec2 twoStepsLeftTextureCoordinate;\n" + - "varying vec2 oneStepRightTextureCoordinate;\n" + - "varying vec2 twoStepsRightTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp vec4 fragmentColor = texture2D(inputImageTexture, centerTextureCoordinate) * 0.2;\n" + - "fragmentColor += texture2D(inputImageTexture, oneStepLeftTextureCoordinate) * 0.2;\n" + - "fragmentColor += texture2D(inputImageTexture, oneStepRightTextureCoordinate) * 0.2;\n" + - "fragmentColor += texture2D(inputImageTexture, twoStepsLeftTextureCoordinate) * 0.2;\n" + - "fragmentColor += texture2D(inputImageTexture, twoStepsRightTextureCoordinate) * 0.2;\n" + - "\n" + - "gl_FragColor = fragmentColor;\n" + - "}\n"; - - private float blurSize = 1f; - - /** - * Construct new BoxBlurFilter with default blur size of 1.0. - */ - public GPUImageBoxBlurFilter() { - this(1f); - } - - - public GPUImageBoxBlurFilter(float blurSize) { - super(VERTEX_SHADER, FRAGMENT_SHADER, VERTEX_SHADER, FRAGMENT_SHADER); - this.blurSize = blurSize; - } - - /** - * A scaling for the size of the applied blur, default of 1.0 - * - * @param blurSize - */ - public void setBlurSize(float blurSize) { - this.blurSize = blurSize; - runOnDraw(new Runnable() { - @Override - public void run() { - initTexelOffsets(); - } - }); - } - - @Override - public float getVerticalTexelOffsetRatio() { - return blurSize; - } - - @Override - public float getHorizontalTexelOffsetRatio() { - return blurSize; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBrightnessFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBrightnessFilter.java deleted file mode 100755 index e528ee8..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBrightnessFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * brightness value ranges from -1.0 to 1.0, with 0.0 as the normal level - */ -public class GPUImageBrightnessFilter extends GPUImageFilter { - public static final String BRIGHTNESS_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform lowp float brightness;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4((textureColor.rgb + vec3(brightness)), textureColor.w);\n" + - " }"; - - private int mBrightnessLocation; - private float mBrightness; - - public GPUImageBrightnessFilter() { - this(0.0f); - } - - public GPUImageBrightnessFilter(final float brightness) { - super(NO_FILTER_VERTEX_SHADER, BRIGHTNESS_FRAGMENT_SHADER); - mBrightness = brightness; - } - - @Override - public void onInit() { - super.onInit(); - mBrightnessLocation = GLES20.glGetUniformLocation(getProgram(), "brightness"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setBrightness(mBrightness); - } - - public void setBrightness(final float brightness) { - mBrightness = brightness; - setFloat(mBrightnessLocation, mBrightness); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBulgeDistortionFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBulgeDistortionFilter.java deleted file mode 100755 index af49bed..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageBulgeDistortionFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.graphics.PointF; -import android.opengl.GLES20; - -public class GPUImageBulgeDistortionFilter extends GPUImageFilter { - public static final String BULGE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform highp float aspectRatio;\n" + - "uniform highp vec2 center;\n" + - "uniform highp float radius;\n" + - "uniform highp float scale;\n" + - "\n" + - "void main()\n" + - "{\n" + - "highp vec2 textureCoordinateToUse = vec2(textureCoordinate.x, (textureCoordinate.y * aspectRatio + 0.5 - 0.5 * aspectRatio));\n" + - "highp float dist = distance(center, textureCoordinateToUse);\n" + - "textureCoordinateToUse = textureCoordinate;\n" + - "\n" + - "if (dist < radius)\n" + - "{\n" + - "textureCoordinateToUse -= center;\n" + - "highp float percent = 1.0 - ((radius - dist) / radius) * scale;\n" + - "percent = percent * percent;\n" + - "\n" + - "textureCoordinateToUse = textureCoordinateToUse * percent;\n" + - "textureCoordinateToUse += center;\n" + - "}\n" + - "\n" + - "gl_FragColor = texture2D(inputImageTexture, textureCoordinateToUse ); \n" + - "}\n"; - - private float mScale; - private int mScaleLocation; - private float mRadius; - private int mRadiusLocation; - private PointF mCenter; - private int mCenterLocation; - private float mAspectRatio; - private int mAspectRatioLocation; - - public GPUImageBulgeDistortionFilter() { - this(0.25f, 0.5f, new PointF(0.5f, 0.5f)); - } - - public GPUImageBulgeDistortionFilter(float radius, float scale, PointF center) { - super(NO_FILTER_VERTEX_SHADER, BULGE_FRAGMENT_SHADER); - mRadius = radius; - mScale = scale; - mCenter = center; - } - - @Override - public void onInit() { - super.onInit(); - mScaleLocation = GLES20.glGetUniformLocation(getProgram(), "scale"); - mRadiusLocation = GLES20.glGetUniformLocation(getProgram(), "radius"); - mCenterLocation = GLES20.glGetUniformLocation(getProgram(), "center"); - mAspectRatioLocation = GLES20.glGetUniformLocation(getProgram(), "aspectRatio"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setRadius(mRadius); - setScale(mScale); - setCenter(mCenter); - } - - @Override - public void onOutputSizeChanged(int width, int height) { - mAspectRatio = (float) height / width; - setAspectRatio(mAspectRatio); - super.onOutputSizeChanged(width, height); - } - - private void setAspectRatio(float aspectRatio) { - mAspectRatio = aspectRatio; - setFloat(mAspectRatioLocation, aspectRatio); - } - - /** - * The radius of the distortion, ranging from 0.0 to 1.0, with a default of 0.25 - * - * @param radius from 0.0 to 1.0, default 0.25 - */ - public void setRadius(float radius) { - mRadius = radius; - setFloat(mRadiusLocation, radius); - } - - /** - * The amount of distortion to apply, from -1.0 to 1.0, with a default of 0.5 - * - * @param scale from -1.0 to 1.0, default 0.5 - */ - public void setScale(float scale) { - mScale = scale; - setFloat(mScaleLocation, scale); - } - - /** - * The center about which to apply the distortion, with a default of (0.5, 0.5) - * - * @param center default (0.5, 0.5) - */ - public void setCenter(PointF center) { - mCenter = center; - setPoint(mCenterLocation, center); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageCGAColorspaceFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageCGAColorspaceFilter.java deleted file mode 100755 index 5258595..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageCGAColorspaceFilter.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageCGAColorspaceFilter extends GPUImageFilter { - public static final String CGACOLORSPACE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "highp vec2 sampleDivisor = vec2(1.0 / 200.0, 1.0 / 320.0);\n" + - "//highp vec4 colorDivisor = vec4(colorDepth);\n" + - "\n" + - "highp vec2 samplePos = textureCoordinate - mod(textureCoordinate, sampleDivisor);\n" + - "highp vec4 color = texture2D(inputImageTexture, samplePos );\n" + - "\n" + - "//gl_FragColor = texture2D(inputImageTexture, samplePos );\n" + - "mediump vec4 colorCyan = vec4(85.0 / 255.0, 1.0, 1.0, 1.0);\n" + - "mediump vec4 colorMagenta = vec4(1.0, 85.0 / 255.0, 1.0, 1.0);\n" + - "mediump vec4 colorWhite = vec4(1.0, 1.0, 1.0, 1.0);\n" + - "mediump vec4 colorBlack = vec4(0.0, 0.0, 0.0, 1.0);\n" + - "\n" + - "mediump vec4 endColor;\n" + - "highp float blackDistance = distance(color, colorBlack);\n" + - "highp float whiteDistance = distance(color, colorWhite);\n" + - "highp float magentaDistance = distance(color, colorMagenta);\n" + - "highp float cyanDistance = distance(color, colorCyan);\n" + - "\n" + - "mediump vec4 finalColor;\n" + - "\n" + - "highp float colorDistance = min(magentaDistance, cyanDistance);\n" + - "colorDistance = min(colorDistance, whiteDistance);\n" + - "colorDistance = min(colorDistance, blackDistance); \n" + - "\n" + - "if (colorDistance == blackDistance) {\n" + - "finalColor = colorBlack;\n" + - "} else if (colorDistance == whiteDistance) {\n" + - "finalColor = colorWhite;\n" + - "} else if (colorDistance == cyanDistance) {\n" + - "finalColor = colorCyan;\n" + - "} else {\n" + - "finalColor = colorMagenta;\n" + - "}\n" + - "\n" + - "gl_FragColor = finalColor;\n" + - "}\n"; - - public GPUImageCGAColorspaceFilter() { - super(NO_FILTER_VERTEX_SHADER, CGACOLORSPACE_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageChromaKeyBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageChromaKeyBlendFilter.java deleted file mode 100755 index 7957b05..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageChromaKeyBlendFilter.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Selectively replaces a color in the first image with the second image - */ -public class GPUImageChromaKeyBlendFilter extends GPUImageTwoInputFilter { - public static final String CHROMA_KEY_BLEND_FRAGMENT_SHADER = " precision highp float;\n" + - " \n" + - " varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform float thresholdSensitivity;\n" + - " uniform float smoothing;\n" + - " uniform vec3 colorToReplace;\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " float maskY = 0.2989 * colorToReplace.r + 0.5866 * colorToReplace.g + 0.1145 * colorToReplace.b;\n" + - " float maskCr = 0.7132 * (colorToReplace.r - maskY);\n" + - " float maskCb = 0.5647 * (colorToReplace.b - maskY);\n" + - " \n" + - " float Y = 0.2989 * textureColor.r + 0.5866 * textureColor.g + 0.1145 * textureColor.b;\n" + - " float Cr = 0.7132 * (textureColor.r - Y);\n" + - " float Cb = 0.5647 * (textureColor.b - Y);\n" + - " \n" + - " float blendValue = 1.0 - smoothstep(thresholdSensitivity, thresholdSensitivity + smoothing, distance(vec2(Cr, Cb), vec2(maskCr, maskCb)));\n" + - " gl_FragColor = mix(textureColor, textureColor2, blendValue);\n" + - " }"; - - private int mThresholdSensitivityLocation; - private int mSmoothingLocation; - private int mColorToReplaceLocation; - private float mSmoothing = 0.1f; - private float mThresholdSensitivity = 0.3f; - private float[] mColorToReplace = new float[]{0.0f, 1.0f, 0.0f}; - - public GPUImageChromaKeyBlendFilter() { - super(CHROMA_KEY_BLEND_FRAGMENT_SHADER); - - } - - @Override - public void onInit() { - super.onInit(); - mThresholdSensitivityLocation = GLES20.glGetUniformLocation(getProgram(), "thresholdSensitivity"); - mSmoothingLocation = GLES20.glGetUniformLocation(getProgram(), "smoothing"); - mColorToReplaceLocation = GLES20.glGetUniformLocation(getProgram(), "colorToReplace"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setSmoothing(mSmoothing); - setThresholdSensitivity(mThresholdSensitivity); - setColorToReplace(mColorToReplace[0], mColorToReplace[1], mColorToReplace[2]); - } - - /** - * The degree of smoothing controls how gradually similar colors are replaced in the image - * The default value is 0.1 - */ - public void setSmoothing(final float smoothing) { - mSmoothing = smoothing; - setFloat(mSmoothingLocation, mSmoothing); - } - - /** - * The threshold sensitivity controls how similar pixels need to be colored to be replaced - * The default value is 0.3 - */ - public void setThresholdSensitivity(final float thresholdSensitivity) { - mThresholdSensitivity = thresholdSensitivity; - setFloat(mThresholdSensitivityLocation, mThresholdSensitivity); - } - - /** The color to be replaced is specified using individual red, green, and blue components (normalized to 1.0). - * The default is green: (0.0, 1.0, 0.0). - * - * @param redComponent Red component of color to be replaced - * @param greenComponent Green component of color to be replaced - * @param blueComponent Blue component of color to be replaced - */ - public void setColorToReplace(float redComponent, float greenComponent, float blueComponent) { - mColorToReplace = new float[]{redComponent, greenComponent, blueComponent}; - setFloatVec3(mColorToReplaceLocation, mColorToReplace); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBalanceFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBalanceFilter.java deleted file mode 100755 index 68c078a..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBalanceFilter.java +++ /dev/null @@ -1,197 +0,0 @@ -package jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Created by edward_chiang on 13/10/16. - */ -public class GPUImageColorBalanceFilter extends GPUImageFilter { - - public static final String GPU_IMAGE_COLOR_BALANCE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform lowp vec3 shadowsShift;\n" + - "uniform lowp vec3 midtonesShift;\n" + - "uniform lowp vec3 highlightsShift;\n" + - "uniform int preserveLuminosity;\n" + - "lowp vec3 RGBToHSL(lowp vec3 color)\n" + - - "{\n" + - "lowp vec3 hsl; // init to 0 to avoid warnings ? (and reverse if + remove first part)\n" + - - "lowp float fmin = min(min(color.r, color.g), color.b); //Min. value of RGB\n" + - "lowp float fmax = max(max(color.r, color.g), color.b); //Max. value of RGB\n" + - "lowp float delta = fmax - fmin; //Delta RGB value\n" + - - "hsl.z = (fmax + fmin) / 2.0; // Luminance\n" + - - "if (delta == 0.0) //This is a gray, no chroma...\n" + - "{\n" + - " hsl.x = 0.0; // Hue\n" + - " hsl.y = 0.0; // Saturation\n" + - "}\n" + - "else //Chromatic data...\n" + - "{\n" + - " if (hsl.z < 0.5)\n" + - " hsl.y = delta / (fmax + fmin); // Saturation\n" + - " else\n"+ - " hsl.y = delta / (2.0 - fmax - fmin); // Saturation\n" + - "\n" + - " lowp float deltaR = (((fmax - color.r) / 6.0) + (delta / 2.0)) / delta;\n" + - " lowp float deltaG = (((fmax - color.g) / 6.0) + (delta / 2.0)) / delta;\n" + - " lowp float deltaB = (((fmax - color.b) / 6.0) + (delta / 2.0)) / delta;\n" + - "\n" + - " if (color.r == fmax )\n" + - " hsl.x = deltaB - deltaG; // Hue\n" + - " else if (color.g == fmax)\n" + - " hsl.x = (1.0 / 3.0) + deltaR - deltaB; // Hue\n" + - " else if (color.b == fmax)\n" + - " hsl.x = (2.0 / 3.0) + deltaG - deltaR; // Hue\n" + - - " if (hsl.x < 0.0)\n" + - " hsl.x += 1.0; // Hue\n" + - " else if (hsl.x > 1.0)\n" + - " hsl.x -= 1.0; // Hue\n" + - "}\n" + - "\n" + - "return hsl;\n" + - "}\n" + - - "lowp float HueToRGB(lowp float f1, lowp float f2, lowp float hue)\n" + - "{\n"+ - " if (hue < 0.0)\n"+ - " hue += 1.0;\n"+ - " else if (hue > 1.0)\n"+ - " hue -= 1.0;\n"+ - " lowp float res;\n"+ - " if ((6.0 * hue) < 1.0)\n"+ - " res = f1 + (f2 - f1) * 6.0 * hue;\n"+ - " else if ((2.0 * hue) < 1.0)\n"+ - " res = f2;\n"+ - " else if ((3.0 * hue) < 2.0)\n"+ - " res = f1 + (f2 - f1) * ((2.0 / 3.0) - hue) * 6.0;\n"+ - " else\n"+ - " res = f1;\n"+ - " return res;\n"+ - "}\n"+ - - "lowp vec3 HSLToRGB(lowp vec3 hsl)\n"+ - "{\n" + - " lowp vec3 rgb;\n" + - - " if (hsl.y == 0.0)\n" + - " rgb = vec3(hsl.z); // Luminance\n" + - " else\n" + - " {\n" + - " lowp float f2;\n" + - - " if (hsl.z < 0.5)\n" + - " f2 = hsl.z * (1.0 + hsl.y);\n" + - " else\n" + - " f2 = (hsl.z + hsl.y) - (hsl.y * hsl.z);\n" + - - " lowp float f1 = 2.0 * hsl.z - f2;\n" + - - " rgb.r = HueToRGB(f1, f2, hsl.x + (1.0/3.0));\n" + - " rgb.g = HueToRGB(f1, f2, hsl.x);\n" + - " rgb.b= HueToRGB(f1, f2, hsl.x - (1.0/3.0));\n" + - " }\n" + - - " return rgb;\n "+ - "}\n" + - - "lowp float RGBToL(lowp vec3 color)\n" + - "{\n" + - " lowp float fmin = min(min(color.r, color.g), color.b); //Min. value of RGB\n" + - " lowp float fmax = max(max(color.r, color.g), color.b); //Max. value of RGB\n" + - - " return (fmax + fmin) / 2.0; // Luminance\n" + - "}\n" + - - "void main()\n"+ - "{\n"+ - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - - " // Alternative way:\n" + - " //lowp vec3 lightness = RGBToL(textureColor.rgb);\n" + - " lowp vec3 lightness = textureColor.rgb;\n" + - - " const lowp float a = 0.25;\n" + - " const lowp float b = 0.333;\n" + - " const lowp float scale = 0.7;\n" + - - " lowp vec3 shadows = shadowsShift * (clamp((lightness - b) / -a + 0.5, 0.0, 1.0) * scale);\n" + - " lowp vec3 midtones = midtonesShift * (clamp((lightness - b) / a + 0.5, 0.0, 1.0) *\n" + - " clamp((lightness + b - 1.0) / -a + 0.5, 0.0, 1.0) * scale);\n" + - " lowp vec3 highlights = highlightsShift * (clamp((lightness + b - 1.0) / a + 0.5, 0.0, 1.0) * scale);\n" + - - " mediump vec3 newColor = textureColor.rgb + shadows + midtones + highlights;\n"+ - " newColor = clamp(newColor, 0.0, 1.0);\n "+ - - " if (preserveLuminosity != 0) {\n "+ - " lowp vec3 newHSL = RGBToHSL(newColor);\n" + - " lowp float oldLum = RGBToL(textureColor.rgb);\n" + - " textureColor.rgb = HSLToRGB(vec3(newHSL.x, newHSL.y, oldLum));\n" + - " gl_FragColor = textureColor;\n" + - " } else {\n" + - " gl_FragColor = vec4(newColor.rgb, textureColor.w);\n" + - " }\n" + - "}\n"; - - private int mShadowsLocation; - private int mMidtonesLocation; - private int mHighlightsLocation; - private int mPreserveLuminosityLocation; - - private float[] showdows; - private float[] midtones; - private float[] highlights; - private boolean preserveLuminosity; - - - public GPUImageColorBalanceFilter() { - super(NO_FILTER_VERTEX_SHADER, GPU_IMAGE_COLOR_BALANCE_FRAGMENT_SHADER); - this.showdows = new float[]{0.0f, 0.0f, 0.0f}; - this.midtones = new float[]{0.0f, 0.0f, 0.0f}; - this.highlights = new float[]{0.0f, 0.0f, 0.0f}; - this.preserveLuminosity = true; - } - - @Override - public void onInit() { - super.onInit(); - mShadowsLocation = GLES20.glGetUniformLocation(getProgram(), "shadowsShift"); - mMidtonesLocation = GLES20.glGetUniformLocation(getProgram(), "midtonesShift"); - mHighlightsLocation = GLES20.glGetUniformLocation(getProgram(), "highlightsShift"); - mPreserveLuminosityLocation = GLES20.glGetUniformLocation(getProgram(), "preserveLuminosity"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setMidtones(this.midtones); - setShowdows(this.showdows); - setHighlights(this.highlights); - setPreserveLuminosity(this.preserveLuminosity); - } - - public void setShowdows(float[] showdows) { - this.showdows = showdows; - setFloatVec3(mShadowsLocation, showdows); - } - - public void setMidtones(float[] midtones) { - this.midtones = midtones; - setFloatVec3(mMidtonesLocation, midtones); - } - - public void setHighlights(float[] highlights) { - this.highlights = highlights; - setFloatVec3(mHighlightsLocation, highlights); - } - - public void setPreserveLuminosity(boolean preserveLuminosity) { - this.preserveLuminosity = preserveLuminosity; - setInteger(mPreserveLuminosityLocation, preserveLuminosity ? 1: 0); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBlendFilter.java deleted file mode 100755 index 0f5de14..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBlendFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageColorBlendFilter extends GPUImageTwoInputFilter { - public static final String COLOR_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " highp float lum(lowp vec3 c) {\n" + - " return dot(c, vec3(0.3, 0.59, 0.11));\n" + - " }\n" + - " \n" + - " lowp vec3 clipcolor(lowp vec3 c) {\n" + - " highp float l = lum(c);\n" + - " lowp float n = min(min(c.r, c.g), c.b);\n" + - " lowp float x = max(max(c.r, c.g), c.b);\n" + - " \n" + - " if (n < 0.0) {\n" + - " c.r = l + ((c.r - l) * l) / (l - n);\n" + - " c.g = l + ((c.g - l) * l) / (l - n);\n" + - " c.b = l + ((c.b - l) * l) / (l - n);\n" + - " }\n" + - " if (x > 1.0) {\n" + - " c.r = l + ((c.r - l) * (1.0 - l)) / (x - l);\n" + - " c.g = l + ((c.g - l) * (1.0 - l)) / (x - l);\n" + - " c.b = l + ((c.b - l) * (1.0 - l)) / (x - l);\n" + - " }\n" + - " \n" + - " return c;\n" + - " }\n" + - "\n" + - " lowp vec3 setlum(lowp vec3 c, highp float l) {\n" + - " highp float d = l - lum(c);\n" + - " c = c + vec3(d);\n" + - " return clipcolor(c);\n" + - " }\n" + - " \n" + - " void main()\n" + - " {\n" + - " highp vec4 baseColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " highp vec4 overlayColor = texture2D(inputImageTexture2, textureCoordinate2);\n" + - "\n" + - " gl_FragColor = vec4(baseColor.rgb * (1.0 - overlayColor.a) + setlum(overlayColor.rgb, lum(baseColor.rgb)) * overlayColor.a, baseColor.a);\n" + - " }"; - - public GPUImageColorBlendFilter() { - super(COLOR_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBurnBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBurnBlendFilter.java deleted file mode 100755 index e3b5c42..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorBurnBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageColorBurnBlendFilter extends GPUImageTwoInputFilter { - public static final String COLOR_BURN_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " mediump vec4 whiteColor = vec4(1.0);\n" + - " gl_FragColor = whiteColor - (whiteColor - textureColor) / textureColor2;\n" + - " }"; - - public GPUImageColorBurnBlendFilter() { - super(COLOR_BURN_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorDodgeBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorDodgeBlendFilter.java deleted file mode 100755 index 702a3a9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorDodgeBlendFilter.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageColorDodgeBlendFilter extends GPUImageTwoInputFilter { - public static final String COLOR_DODGE_BLEND_FRAGMENT_SHADER = "precision mediump float;\n" + - " \n" + - " varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " vec3 baseOverlayAlphaProduct = vec3(overlay.a * base.a);\n" + - " vec3 rightHandProduct = overlay.rgb * (1.0 - base.a) + base.rgb * (1.0 - overlay.a);\n" + - " \n" + - " vec3 firstBlendColor = baseOverlayAlphaProduct + rightHandProduct;\n" + - " vec3 overlayRGB = clamp((overlay.rgb / clamp(overlay.a, 0.01, 1.0)) * step(0.0, overlay.a), 0.0, 0.99);\n" + - " \n" + - " vec3 secondBlendColor = (base.rgb * overlay.a) / (1.0 - overlayRGB) + rightHandProduct;\n" + - " \n" + - " vec3 colorChoice = step((overlay.rgb * base.a + base.rgb * overlay.a), baseOverlayAlphaProduct);\n" + - " \n" + - " gl_FragColor = vec4(mix(firstBlendColor, secondBlendColor, colorChoice), 1.0);\n" + - " }"; - - public GPUImageColorDodgeBlendFilter() { - super(COLOR_DODGE_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorInvertFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorInvertFilter.java deleted file mode 100755 index 2d8df9b..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorInvertFilter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * Invert all the colors in the image. - */ -public class GPUImageColorInvertFilter extends GPUImageFilter { - public static final String COLOR_INVERT_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4((1.0 - textureColor.rgb), textureColor.w);\n" + - "}"; - - public GPUImageColorInvertFilter() { - super(NO_FILTER_VERTEX_SHADER, COLOR_INVERT_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorMatrixFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorMatrixFilter.java deleted file mode 100755 index 59203c4..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageColorMatrixFilter.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Applies a ColorMatrix to the image. - */ -public class GPUImageColorMatrixFilter extends GPUImageFilter { - public static final String COLOR_MATRIX_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform lowp mat4 colorMatrix;\n" + - "uniform lowp float intensity;\n" + - "\n" + - "void main()\n" + - "{\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 outputColor = textureColor * colorMatrix;\n" + - " \n" + - " gl_FragColor = (intensity * outputColor) + ((1.0 - intensity) * textureColor);\n" + - "}"; - - private float mIntensity; - private float[] mColorMatrix; - private int mColorMatrixLocation; - private int mIntensityLocation; - - public GPUImageColorMatrixFilter() { - this(1.0f, new float[] { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }); - } - - public GPUImageColorMatrixFilter(final float intensity, final float[] colorMatrix) { - super(NO_FILTER_VERTEX_SHADER, COLOR_MATRIX_FRAGMENT_SHADER); - mIntensity = intensity; - mColorMatrix = colorMatrix; - } - - @Override - public void onInit() { - super.onInit(); - mColorMatrixLocation = GLES20.glGetUniformLocation(getProgram(), "colorMatrix"); - mIntensityLocation = GLES20.glGetUniformLocation(getProgram(), "intensity"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setIntensity(mIntensity); - setColorMatrix(mColorMatrix); - } - - public void setIntensity(final float intensity) { - mIntensity = intensity; - setFloat(mIntensityLocation, intensity); - } - - public void setColorMatrix(final float[] colorMatrix) { - mColorMatrix = colorMatrix; - setUniformMatrix4f(mColorMatrixLocation, colorMatrix); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageContrastFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageContrastFilter.java deleted file mode 100755 index 1d2b910..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageContrastFilter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Changes the contrast of the image.
- *
- * contrast value ranges from 0.0 to 4.0, with 1.0 as the normal level - */ -public class GPUImageContrastFilter extends GPUImageFilter { - public static final String CONTRAST_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform lowp float contrast;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4(((textureColor.rgb - vec3(0.5)) * contrast + vec3(0.5)), textureColor.w);\n" + - " }"; - - private int mContrastLocation; - private float mContrast; - - public GPUImageContrastFilter() { - this(1.2f); - } - - public GPUImageContrastFilter(float contrast) { - super(NO_FILTER_VERTEX_SHADER, CONTRAST_FRAGMENT_SHADER); - mContrast = contrast; - } - - @Override - public void onInit() { - super.onInit(); - mContrastLocation = GLES20.glGetUniformLocation(getProgram(), "contrast"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setContrast(mContrast); - } - - public void setContrast(final float contrast) { - mContrast = contrast; - setFloat(mContrastLocation, mContrast); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageCrosshatchFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageCrosshatchFilter.java deleted file mode 100755 index 04a3d4c..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageCrosshatchFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * crossHatchSpacing: The fractional width of the image to use as the spacing for the crosshatch. The default is 0.03. - * lineWidth: A relative width for the crosshatch lines. The default is 0.003. - */ -public class GPUImageCrosshatchFilter extends GPUImageFilter { - public static final String CROSSHATCH_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform highp float crossHatchSpacing;\n" + - "uniform highp float lineWidth;\n" + - "const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" + - "void main()\n" + - "{\n" + - "highp float luminance = dot(texture2D(inputImageTexture, textureCoordinate).rgb, W);\n" + - "lowp vec4 colorToDisplay = vec4(1.0, 1.0, 1.0, 1.0);\n" + - "if (luminance < 1.00)\n" + - "{\n" + - "if (mod(textureCoordinate.x + textureCoordinate.y, crossHatchSpacing) <= lineWidth)\n" + - "{\n" + - "colorToDisplay = vec4(0.0, 0.0, 0.0, 1.0);\n" + - "}\n" + - "}\n" + - "if (luminance < 0.75)\n" + - "{\n" + - "if (mod(textureCoordinate.x - textureCoordinate.y, crossHatchSpacing) <= lineWidth)\n" + - "{\n" + - "colorToDisplay = vec4(0.0, 0.0, 0.0, 1.0);\n" + - "}\n" + - "}\n" + - "if (luminance < 0.50)\n" + - "{\n" + - "if (mod(textureCoordinate.x + textureCoordinate.y - (crossHatchSpacing / 2.0), crossHatchSpacing) <= lineWidth)\n" + - "{\n" + - "colorToDisplay = vec4(0.0, 0.0, 0.0, 1.0);\n" + - "}\n" + - "}\n" + - "if (luminance < 0.3)\n" + - "{\n" + - "if (mod(textureCoordinate.x - textureCoordinate.y - (crossHatchSpacing / 2.0), crossHatchSpacing) <= lineWidth)\n" + - "{\n" + - "colorToDisplay = vec4(0.0, 0.0, 0.0, 1.0);\n" + - "}\n" + - "}\n" + - "gl_FragColor = colorToDisplay;\n" + - "}\n"; - - private float mCrossHatchSpacing; - private int mCrossHatchSpacingLocation; - private float mLineWidth; - private int mLineWidthLocation; - - /** - * Using default values of crossHatchSpacing: 0.03f and lineWidth: 0.003f. - */ - public GPUImageCrosshatchFilter() { - this(0.03f, 0.003f); - } - - public GPUImageCrosshatchFilter(float crossHatchSpacing, float lineWidth) { - super(NO_FILTER_VERTEX_SHADER, CROSSHATCH_FRAGMENT_SHADER); - mCrossHatchSpacing = crossHatchSpacing; - mLineWidth = lineWidth; - } - - @Override - public void onInit() { - super.onInit(); - mCrossHatchSpacingLocation = GLES20.glGetUniformLocation(getProgram(), "crossHatchSpacing"); - mLineWidthLocation = GLES20.glGetUniformLocation(getProgram(), "lineWidth"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setCrossHatchSpacing(mCrossHatchSpacing); - setLineWidth(mLineWidth); - } - - /** - * The fractional width of the image to use as the spacing for the crosshatch. The default is 0.03. - * - * @param crossHatchSpacing default 0.03 - */ - public void setCrossHatchSpacing(final float crossHatchSpacing) { - float singlePixelSpacing; - if (getOutputWidth() != 0) { - singlePixelSpacing = 1.0f / (float) getOutputWidth(); - } else { - singlePixelSpacing = 1.0f / 2048.0f; - } - - if (crossHatchSpacing < singlePixelSpacing) { - mCrossHatchSpacing = singlePixelSpacing; - } else { - mCrossHatchSpacing = crossHatchSpacing; - } - - setFloat(mCrossHatchSpacingLocation, mCrossHatchSpacing); - } - - /** - * A relative width for the crosshatch lines. The default is 0.003. - * - * @param lineWidth default 0.003 - */ - public void setLineWidth(final float lineWidth) { - mLineWidth = lineWidth; - setFloat(mLineWidthLocation, mLineWidth); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDarkenBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDarkenBlendFilter.java deleted file mode 100755 index 385e8e3..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDarkenBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageDarkenBlendFilter extends GPUImageTwoInputFilter { - public static final String DARKEN_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 overlayer = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = vec4(min(overlayer.rgb * base.a, base.rgb * overlayer.a) + overlayer.rgb * (1.0 - base.a) + base.rgb * (1.0 - overlayer.a), 1.0);\n" + - " }"; - - public GPUImageDarkenBlendFilter() { - super(DARKEN_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDifferenceBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDifferenceBlendFilter.java deleted file mode 100755 index 1a32cd0..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDifferenceBlendFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageDifferenceBlendFilter extends GPUImageTwoInputFilter { - public static final String DIFFERENCE_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " gl_FragColor = vec4(abs(textureColor2.rgb - textureColor.rgb), textureColor.a);\n" + - " }"; - - public GPUImageDifferenceBlendFilter() { - super(DIFFERENCE_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDilationFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDilationFilter.java deleted file mode 100755 index f6ce4e2..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDilationFilter.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * For each pixel, this sets it to the maximum value of the red channel in a rectangular neighborhood extending - * out dilationRadius pixels from the center. - * This extends out bright features, and is most commonly used with black-and-white thresholded images. - */ -public class GPUImageDilationFilter extends GPUImageTwoPassTextureSamplingFilter { - public static final String VERTEX_SHADER_1 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset; \n" + - "uniform float texelHeightOffset; \n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "}\n"; - - public static final String VERTEX_SHADER_2 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "twoStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 2.0);\n" + - "twoStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 2.0);\n" + - "}\n"; - - public static final String VERTEX_SHADER_3 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "twoStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 2.0);\n" + - "twoStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 2.0);\n" + - "threeStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 3.0);\n" + - "threeStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 3.0);\n" + - "}\n"; - - public static final String VERTEX_SHADER_4 = - - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "varying vec2 fourStepsPositiveTextureCoordinate;\n" + - "varying vec2 fourStepsNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "twoStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 2.0);\n" + - "twoStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 2.0);\n" + - "threeStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 3.0);\n" + - "threeStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 3.0);\n" + - "fourStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 4.0);\n" + - "fourStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 4.0);\n" + - "}\n"; - - - public static final String FRAGMENT_SHADER_1 = - "precision lowp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "float centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate).r;\n" + - "float oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate).r;\n" + - "float oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate).r;\n" + - "\n" + - "lowp float maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "\n" + - "gl_FragColor = vec4(vec3(maxValue), 1.0);\n" + - "}\n"; - - public static final String FRAGMENT_SHADER_2 = - "precision lowp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "float centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate).r;\n" + - "float oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate).r;\n" + - "float oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate).r;\n" + - "float twoStepsPositiveIntensity = texture2D(inputImageTexture, twoStepsPositiveTextureCoordinate).r;\n" + - "float twoStepsNegativeIntensity = texture2D(inputImageTexture, twoStepsNegativeTextureCoordinate).r;\n" + - "\n" + - "lowp float maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "maxValue = max(maxValue, twoStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, twoStepsNegativeIntensity);\n" + - "\n" + - "gl_FragColor = vec4(vec3(maxValue), 1.0);\n" + - "}\n"; - - public static final String FRAGMENT_SHADER_3 = - "precision lowp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "float centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate).r;\n" + - "float oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate).r;\n" + - "float oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate).r;\n" + - "float twoStepsPositiveIntensity = texture2D(inputImageTexture, twoStepsPositiveTextureCoordinate).r;\n" + - "float twoStepsNegativeIntensity = texture2D(inputImageTexture, twoStepsNegativeTextureCoordinate).r;\n" + - "float threeStepsPositiveIntensity = texture2D(inputImageTexture, threeStepsPositiveTextureCoordinate).r;\n" + - "float threeStepsNegativeIntensity = texture2D(inputImageTexture, threeStepsNegativeTextureCoordinate).r;\n" + - "\n" + - "lowp float maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "maxValue = max(maxValue, twoStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, twoStepsNegativeIntensity);\n" + - "maxValue = max(maxValue, threeStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, threeStepsNegativeIntensity);\n" + - "\n" + - "gl_FragColor = vec4(vec3(maxValue), 1.0);\n" + - "}\n"; - - public static final String FRAGMENT_SHADER_4 = - "precision lowp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "varying vec2 fourStepsPositiveTextureCoordinate;\n" + - "varying vec2 fourStepsNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "float centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate).r;\n" + - "float oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate).r;\n" + - "float oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate).r;\n" + - "float twoStepsPositiveIntensity = texture2D(inputImageTexture, twoStepsPositiveTextureCoordinate).r;\n" + - "float twoStepsNegativeIntensity = texture2D(inputImageTexture, twoStepsNegativeTextureCoordinate).r;\n" + - "float threeStepsPositiveIntensity = texture2D(inputImageTexture, threeStepsPositiveTextureCoordinate).r;\n" + - "float threeStepsNegativeIntensity = texture2D(inputImageTexture, threeStepsNegativeTextureCoordinate).r;\n" + - "float fourStepsPositiveIntensity = texture2D(inputImageTexture, fourStepsPositiveTextureCoordinate).r;\n" + - "float fourStepsNegativeIntensity = texture2D(inputImageTexture, fourStepsNegativeTextureCoordinate).r;\n" + - "\n" + - "lowp float maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "maxValue = max(maxValue, twoStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, twoStepsNegativeIntensity);\n" + - "maxValue = max(maxValue, threeStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, threeStepsNegativeIntensity);\n" + - "maxValue = max(maxValue, fourStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, fourStepsNegativeIntensity);\n" + - "\n" + - "gl_FragColor = vec4(vec3(maxValue), 1.0);\n" + - "}\n"; - - - public GPUImageDilationFilter() { - this(1); - } - - /** - * Acceptable values for dilationRadius, which sets the distance in pixels to sample out from the center, - * are 1, 2, 3, and 4. - * - * @param radius 1, 2, 3 or 4 - */ - public GPUImageDilationFilter(int radius) { - this(getVertexShader(radius), getFragmentShader(radius)); - } - - private GPUImageDilationFilter(String vertexShader, String fragmentShader) { - super(vertexShader, fragmentShader, vertexShader, fragmentShader); - } - - private static String getVertexShader(int radius) { - switch (radius) { - case 0: - case 1: - return VERTEX_SHADER_1; - case 2: - return VERTEX_SHADER_2; - case 3: - return VERTEX_SHADER_3; - default: - return VERTEX_SHADER_4; - } - } - - private static String getFragmentShader(int radius) { - switch (radius) { - case 0: - case 1: - return FRAGMENT_SHADER_1; - case 2: - return FRAGMENT_SHADER_2; - case 3: - return FRAGMENT_SHADER_3; - default: - return FRAGMENT_SHADER_4; - } - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDirectionalSobelEdgeDetectionFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDirectionalSobelEdgeDetectionFilter.java deleted file mode 100755 index a5884a1..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDirectionalSobelEdgeDetectionFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - - -public class GPUImageDirectionalSobelEdgeDetectionFilter extends GPUImage3x3TextureSamplingFilter { - public static final String DIRECTIONAL_SOBEL_EDGE_DETECTION_FRAGMENT_SHADER = "" + - "precision mediump float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - " float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - " float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - " float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - " float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - " float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - " float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - " float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - " float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - "\n" + - " vec2 gradientDirection;\n" + - " gradientDirection.x = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" + - " gradientDirection.y = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" + - "\n" + - " float gradientMagnitude = length(gradientDirection);\n" + - " vec2 normalizedDirection = normalize(gradientDirection);\n" + - " normalizedDirection = sign(normalizedDirection) * floor(abs(normalizedDirection) + 0.617316); // Offset by 1-sin(pi/8) to set to 0 if near axis, 1 if away\n" + - " normalizedDirection = (normalizedDirection + 1.0) * 0.5; // Place -1.0 - 1.0 within 0 - 1.0\n" + - "\n" + - " gl_FragColor = vec4(gradientMagnitude, normalizedDirection.x, normalizedDirection.y, 1.0);\n" + - "}"; - - public GPUImageDirectionalSobelEdgeDetectionFilter() { - super(DIRECTIONAL_SOBEL_EDGE_DETECTION_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDissolveBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDissolveBlendFilter.java deleted file mode 100755 index cd2880a..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDissolveBlendFilter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Mix ranges from 0.0 (only image 1) to 1.0 (only image 2), with 0.5 (half of either) as the normal level - */ -public class GPUImageDissolveBlendFilter extends GPUImageMixBlendFilter{ - public static final String DISSOLVE_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " uniform lowp float mixturePercent;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = mix(textureColor, textureColor2, mixturePercent);\n" + - " }"; - - public GPUImageDissolveBlendFilter() { - super(DISSOLVE_BLEND_FRAGMENT_SHADER); - } - - public GPUImageDissolveBlendFilter(float mix) { - super(DISSOLVE_BLEND_FRAGMENT_SHADER, mix); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDivideBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDivideBlendFilter.java deleted file mode 100755 index 179cd4e..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageDivideBlendFilter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageDivideBlendFilter extends GPUImageTwoInputFilter { - public static final String DIVIDE_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " mediump float ra;\n" + - " if (overlay.a == 0.0 || ((base.r / overlay.r) > (base.a / overlay.a)))\n" + - " ra = overlay.a * base.a + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " else\n" + - " ra = (base.r * overlay.a * overlay.a) / overlay.r + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " \n" + - "\n" + - " mediump float ga;\n" + - " if (overlay.a == 0.0 || ((base.g / overlay.g) > (base.a / overlay.a)))\n" + - " ga = overlay.a * base.a + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - " else\n" + - " ga = (base.g * overlay.a * overlay.a) / overlay.g + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - "\n" + - " \n" + - " mediump float ba;\n" + - " if (overlay.a == 0.0 || ((base.b / overlay.b) > (base.a / overlay.a)))\n" + - " ba = overlay.a * base.a + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - " else\n" + - " ba = (base.b * overlay.a * overlay.a) / overlay.b + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - "\n" + - " mediump float a = overlay.a + base.a - overlay.a * base.a;\n" + - " \n" + - " gl_FragColor = vec4(ra, ga, ba, a);\n" + - " }"; - - public GPUImageDivideBlendFilter() { - super(DIVIDE_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageEmbossFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageEmbossFilter.java deleted file mode 100755 index f4cbdef..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageEmbossFilter.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * Applies an emboss effect to the image.
- *
- * Intensity ranges from 0.0 to 4.0, with 1.0 as the normal level - */ -public class GPUImageEmbossFilter extends GPUImage3x3ConvolutionFilter { - private float mIntensity; - - public GPUImageEmbossFilter() { - this(1.0f); - } - - public GPUImageEmbossFilter(final float intensity) { - super(); - mIntensity = intensity; - } - - @Override - public void onInit() { - super.onInit(); - setIntensity(mIntensity); - } - - public void setIntensity(final float intensity) { - mIntensity = intensity; - setConvolutionKernel(new float[] { - intensity * (-2.0f), -intensity, 0.0f, - -intensity, 1.0f, intensity, - 0.0f, intensity, intensity * 2.0f, - }); - } - - public float getIntensity() { - return mIntensity; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageExclusionBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageExclusionBlendFilter.java deleted file mode 100755 index dcfc934..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageExclusionBlendFilter.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageExclusionBlendFilter extends GPUImageTwoInputFilter { - public static final String EXCLUSION_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " // Dca = (Sca.Da + Dca.Sa - 2.Sca.Dca) + Sca.(1 - Da) + Dca.(1 - Sa)\n" + - " \n" + - " gl_FragColor = vec4((overlay.rgb * base.a + base.rgb * overlay.a - 2.0 * overlay.rgb * base.rgb) + overlay.rgb * (1.0 - base.a) + base.rgb * (1.0 - overlay.a), base.a);\n" + - " }"; - - public GPUImageExclusionBlendFilter() { - super(EXCLUSION_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageExposureFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageExposureFilter.java deleted file mode 100755 index de5de41..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageExposureFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * exposure: The adjusted exposure (-10.0 - 10.0, with 0.0 as the default) - */ -public class GPUImageExposureFilter extends GPUImageFilter { - public static final String EXPOSURE_FRAGMENT_SHADER = "" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform highp float exposure;\n" + - " \n" + - " void main()\n" + - " {\n" + - " highp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4(textureColor.rgb * pow(2.0, exposure), textureColor.w);\n" + - " } "; - - private int mExposureLocation; - private float mExposure; - - public GPUImageExposureFilter() { - this(1.0f); - } - - public GPUImageExposureFilter(final float exposure) { - super(NO_FILTER_VERTEX_SHADER, EXPOSURE_FRAGMENT_SHADER); - mExposure = exposure; - } - - @Override - public void onInit() { - super.onInit(); - mExposureLocation = GLES20.glGetUniformLocation(getProgram(), "exposure"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setExposure(mExposure); - } - - public void setExposure(final float exposure) { - mExposure = exposure; - setFloat(mExposureLocation, mExposure); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFalseColorFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFalseColorFilter.java deleted file mode 100755 index c815ad0..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFalseColorFilter.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImageFalseColorFilter extends GPUImageFilter { - public static final String FALSECOLOR_FRAGMENT_SHADER = "" + - "precision lowp float;\n" + - "\n" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform float intensity;\n" + - "uniform vec3 firstColor;\n" + - "uniform vec3 secondColor;\n" + - "\n" + - "const mediump vec3 luminanceWeighting = vec3(0.2125, 0.7154, 0.0721);\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - "float luminance = dot(textureColor.rgb, luminanceWeighting);\n" + - "\n" + - "gl_FragColor = vec4( mix(firstColor.rgb, secondColor.rgb, luminance), textureColor.a);\n" + - "}\n"; - - private float[] mFirstColor; - private int mFirstColorLocation; - private float[] mSecondColor; - private int mSecondColorLocation; - - public GPUImageFalseColorFilter() { - this(0f, 0f, 0.5f, 1f, 0f, 0f); - } - - public GPUImageFalseColorFilter(float firstRed, float firstGreen, float firstBlue, float secondRed, float secondGreen, float secondBlue) { - this(new float[]{firstRed, firstGreen, firstBlue}, new float[]{secondRed, secondGreen, secondBlue}); - } - - public GPUImageFalseColorFilter(float[] firstColor, float[] secondColor) { - super(NO_FILTER_VERTEX_SHADER, FALSECOLOR_FRAGMENT_SHADER); - mFirstColor = firstColor; - mSecondColor = secondColor; - } - - @Override - public void onInit() { - super.onInit(); - mFirstColorLocation = GLES20.glGetUniformLocation(getProgram(), "firstColor"); - mSecondColorLocation = GLES20.glGetUniformLocation(getProgram(), "secondColor"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setFirstColor(mFirstColor); - setSecondColor(mSecondColor); - } - - public void setFirstColor(final float[] firstColor) { - mFirstColor = firstColor; - setFloatVec3(mFirstColorLocation, firstColor); - } - - public void setSecondColor(final float[] secondColor) { - mSecondColor = secondColor; - setFloatVec3(mSecondColorLocation, secondColor); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFilter.java deleted file mode 100755 index 7a8641a..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFilter.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.content.Context; -import android.content.res.AssetManager; -import android.graphics.PointF; -import android.opengl.GLES20; - -import java.io.InputStream; -import java.nio.FloatBuffer; -import java.util.LinkedList; - -public class GPUImageFilter { - public static final String NO_FILTER_VERTEX_SHADER = "" + - "attribute vec4 position;\n" + - "attribute vec4 inputTextureCoordinate;\n" + - " \n" + - "varying vec2 textureCoordinate;\n" + - " \n" + - "void main()\n" + - "{\n" + - " gl_Position = position;\n" + - " textureCoordinate = inputTextureCoordinate.xy;\n" + - "}"; - public static final String NO_FILTER_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - " \n" + - "uniform sampler2D inputImageTexture;\n" + - " \n" + - "void main()\n" + - "{\n" + - " gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n" + - "}"; - - private final LinkedList mRunOnDraw; - private final String mVertexShader; - private final String mFragmentShader; - protected int mGLProgId; - protected int mGLAttribPosition; - protected int mGLUniformTexture; - protected int mGLAttribTextureCoordinate; - protected int mOutputWidth; - protected int mOutputHeight; - private boolean mIsInitialized; - - public GPUImageFilter() { - this(NO_FILTER_VERTEX_SHADER, NO_FILTER_FRAGMENT_SHADER); - } - - public GPUImageFilter(final String vertexShader, final String fragmentShader) { - mRunOnDraw = new LinkedList(); - mVertexShader = vertexShader; - mFragmentShader = fragmentShader; - } - - public final void init() { - onInit(); - mIsInitialized = true; - onInitialized(); - } - - public void onInit() { - mGLProgId = OpenGlUtils.loadProgram(mVertexShader, mFragmentShader); - mGLAttribPosition = GLES20.glGetAttribLocation(mGLProgId, "position"); - mGLUniformTexture = GLES20.glGetUniformLocation(mGLProgId, "inputImageTexture"); - mGLAttribTextureCoordinate = GLES20.glGetAttribLocation(mGLProgId, - "inputTextureCoordinate"); - mIsInitialized = true; - } - - public void onInitialized() { - } - - public final void destroy() { - mIsInitialized = false; - GLES20.glDeleteProgram(mGLProgId); - onDestroy(); - } - - public void onDestroy() { - } - - public void onOutputSizeChanged(final int width, final int height) { - mOutputWidth = width; - mOutputHeight = height; - } - - public void onDraw(final int textureId, final FloatBuffer cubeBuffer, - final FloatBuffer textureBuffer) { - GLES20.glUseProgram(mGLProgId); - runPendingOnDrawTasks(); - if (!mIsInitialized) { - return; - } - - cubeBuffer.position(0); - GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, cubeBuffer); - GLES20.glEnableVertexAttribArray(mGLAttribPosition); - textureBuffer.position(0); - GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, - textureBuffer); - GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate); - if (textureId != OpenGlUtils.NO_TEXTURE) { - GLES20.glActiveTexture(GLES20.GL_TEXTURE0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); - GLES20.glUniform1i(mGLUniformTexture, 0); - } - onDrawArraysPre(); - GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); - GLES20.glDisableVertexAttribArray(mGLAttribPosition); - GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); - } - - protected void onDrawArraysPre() {} - - protected void runPendingOnDrawTasks() { - while (!mRunOnDraw.isEmpty()) { - mRunOnDraw.removeFirst().run(); - } - } - - public boolean isInitialized() { - return mIsInitialized; - } - - public int getOutputWidth() { - return mOutputWidth; - } - - public int getOutputHeight() { - return mOutputHeight; - } - - public int getProgram() { - return mGLProgId; - } - - public int getAttribPosition() { - return mGLAttribPosition; - } - - public int getAttribTextureCoordinate() { - return mGLAttribTextureCoordinate; - } - - public int getUniformTexture() { - return mGLUniformTexture; - } - - protected void setInteger(final int location, final int intValue) { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glUniform1i(location, intValue); - } - }); - } - - protected void setFloat(final int location, final float floatValue) { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glUniform1f(location, floatValue); - } - }); - } - - protected void setFloatVec2(final int location, final float[] arrayValue) { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glUniform2fv(location, 1, FloatBuffer.wrap(arrayValue)); - } - }); - } - - protected void setFloatVec3(final int location, final float[] arrayValue) { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glUniform3fv(location, 1, FloatBuffer.wrap(arrayValue)); - } - }); - } - - protected void setFloatVec4(final int location, final float[] arrayValue) { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glUniform4fv(location, 1, FloatBuffer.wrap(arrayValue)); - } - }); - } - - protected void setFloatArray(final int location, final float[] arrayValue) { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glUniform1fv(location, arrayValue.length, FloatBuffer.wrap(arrayValue)); - } - }); - } - - protected void setPoint(final int location, final PointF point) { - runOnDraw(new Runnable() { - - @Override - public void run() { - float[] vec2 = new float[2]; - vec2[0] = point.x; - vec2[1] = point.y; - GLES20.glUniform2fv(location, 1, vec2, 0); - } - }); - } - - protected void setUniformMatrix3f(final int location, final float[] matrix) { - runOnDraw(new Runnable() { - - @Override - public void run() { - GLES20.glUniformMatrix3fv(location, 1, false, matrix, 0); - } - }); - } - - protected void setUniformMatrix4f(final int location, final float[] matrix) { - runOnDraw(new Runnable() { - - @Override - public void run() { - GLES20.glUniformMatrix4fv(location, 1, false, matrix, 0); - } - }); - } - - protected void runOnDraw(final Runnable runnable) { - synchronized (mRunOnDraw) { - mRunOnDraw.addLast(runnable); - } - } - - public static String loadShader(String file, Context context) { - try { - AssetManager assetManager = context.getAssets(); - InputStream ims = assetManager.open(file); - - String re = convertStreamToString(ims); - ims.close(); - return re; - } catch (Exception e) { - e.printStackTrace(); - } - - return ""; - } - - public static String convertStreamToString(java.io.InputStream is) { - java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); - return s.hasNext() ? s.next() : ""; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFilterGroup.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFilterGroup.java deleted file mode 100755 index 10ea41c..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageFilterGroup.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.annotation.SuppressLint; -import android.opengl.GLES20; -import jp.co.cyberagent.android.gpuimage.util.TextureRotationUtil; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; -import java.util.ArrayList; -import java.util.List; - -import static jp.co.cyberagent.android.gpuimage.GPUImageRenderer.CUBE; -import static jp.co.cyberagent.android.gpuimage.util.TextureRotationUtil.TEXTURE_NO_ROTATION; - -/** - * Resembles a filter that consists of multiple filters applied after each - * other. - */ -public class GPUImageFilterGroup extends GPUImageFilter { - - protected List mFilters; - protected List mMergedFilters; - private int[] mFrameBuffers; - private int[] mFrameBufferTextures; - - private final FloatBuffer mGLCubeBuffer; - private final FloatBuffer mGLTextureBuffer; - private final FloatBuffer mGLTextureFlipBuffer; - - /** - * Instantiates a new GPUImageFilterGroup with no filters. - */ - public GPUImageFilterGroup() { - this(null); - } - - /** - * Instantiates a new GPUImageFilterGroup with the given filters. - * - * @param filters the filters which represent this filter - */ - public GPUImageFilterGroup(List filters) { - mFilters = filters; - if (mFilters == null) { - mFilters = new ArrayList(); - } else { - updateMergedFilters(); - } - - mGLCubeBuffer = ByteBuffer.allocateDirect(CUBE.length * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer(); - mGLCubeBuffer.put(CUBE).position(0); - - mGLTextureBuffer = ByteBuffer.allocateDirect(TEXTURE_NO_ROTATION.length * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer(); - mGLTextureBuffer.put(TEXTURE_NO_ROTATION).position(0); - - float[] flipTexture = TextureRotationUtil.getRotation(Rotation.NORMAL, false, true); - mGLTextureFlipBuffer = ByteBuffer.allocateDirect(flipTexture.length * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer(); - mGLTextureFlipBuffer.put(flipTexture).position(0); - } - - public void addFilter(GPUImageFilter aFilter) { - if (aFilter == null) { - return; - } - mFilters.add(aFilter); - updateMergedFilters(); - } - - /* - * (non-Javadoc) - * @see jp.co.cyberagent.android.gpuimage.GPUImageFilter#onInit() - */ - @Override - public void onInit() { - super.onInit(); - for (GPUImageFilter filter : mFilters) { - filter.init(); - } - } - - /* - * (non-Javadoc) - * @see jp.co.cyberagent.android.gpuimage.GPUImageFilter#onDestroy() - */ - @Override - public void onDestroy() { - destroyFramebuffers(); - for (GPUImageFilter filter : mFilters) { - filter.destroy(); - } - super.onDestroy(); - } - - private void destroyFramebuffers() { - if (mFrameBufferTextures != null) { - GLES20.glDeleteTextures(mFrameBufferTextures.length, mFrameBufferTextures, 0); - mFrameBufferTextures = null; - } - if (mFrameBuffers != null) { - GLES20.glDeleteFramebuffers(mFrameBuffers.length, mFrameBuffers, 0); - mFrameBuffers = null; - } - } - - /* - * (non-Javadoc) - * @see - * jp.co.cyberagent.android.gpuimage.GPUImageFilter#onOutputSizeChanged(int, - * int) - */ - @Override - public void onOutputSizeChanged(final int width, final int height) { - super.onOutputSizeChanged(width, height); - if (mFrameBuffers != null) { - destroyFramebuffers(); - } - - int size = mFilters.size(); - for (int i = 0; i < size; i++) { - mFilters.get(i).onOutputSizeChanged(width, height); - } - - if (mMergedFilters != null && mMergedFilters.size() > 0) { - size = mMergedFilters.size(); - mFrameBuffers = new int[size - 1]; - mFrameBufferTextures = new int[size - 1]; - - for (int i = 0; i < size - 1; i++) { - GLES20.glGenFramebuffers(1, mFrameBuffers, i); - GLES20.glGenTextures(1, mFrameBufferTextures, i); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mFrameBufferTextures[i]); - GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, - GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); - - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[i]); - GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, - GLES20.GL_TEXTURE_2D, mFrameBufferTextures[i], 0); - - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); - } - } - } - - /* - * (non-Javadoc) - * @see jp.co.cyberagent.android.gpuimage.GPUImageFilter#onDraw(int, - * java.nio.FloatBuffer, java.nio.FloatBuffer) - */ - @SuppressLint("WrongCall") - @Override - public void onDraw(final int textureId, final FloatBuffer cubeBuffer, - final FloatBuffer textureBuffer) { - runPendingOnDrawTasks(); - if (!isInitialized() || mFrameBuffers == null || mFrameBufferTextures == null) { - return; - } - if (mMergedFilters != null) { - int size = mMergedFilters.size(); - int previousTexture = textureId; - for (int i = 0; i < size; i++) { - GPUImageFilter filter = mMergedFilters.get(i); - boolean isNotLast = i < size - 1; - if (isNotLast) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[i]); - GLES20.glClearColor(0, 0, 0, 0); - } - - if (i == 0) { - filter.onDraw(previousTexture, cubeBuffer, textureBuffer); - } else if (i == size - 1) { - filter.onDraw(previousTexture, mGLCubeBuffer, (size % 2 == 0) ? mGLTextureFlipBuffer : mGLTextureBuffer); - } else { - filter.onDraw(previousTexture, mGLCubeBuffer, mGLTextureBuffer); - } - - if (isNotLast) { - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); - previousTexture = mFrameBufferTextures[i]; - } - } - } - } - - /** - * Gets the filters. - * - * @return the filters - */ - public List getFilters() { - return mFilters; - } - - public List getMergedFilters() { - return mMergedFilters; - } - - public void updateMergedFilters() { - if (mFilters == null) { - return; - } - - if (mMergedFilters == null) { - mMergedFilters = new ArrayList(); - } else { - mMergedFilters.clear(); - } - - List filters; - for (GPUImageFilter filter : mFilters) { - if (filter instanceof GPUImageFilterGroup) { - ((GPUImageFilterGroup) filter).updateMergedFilters(); - filters = ((GPUImageFilterGroup) filter).getMergedFilters(); - if (filters == null || filters.isEmpty()) - continue; - mMergedFilters.addAll(filters); - continue; - } - mMergedFilters.add(filter); - } - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGammaFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGammaFilter.java deleted file mode 100755 index 1f902d0..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGammaFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * gamma value ranges from 0.0 to 3.0, with 1.0 as the normal level - */ -public class GPUImageGammaFilter extends GPUImageFilter { - public static final String GAMMA_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform lowp float gamma;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4(pow(textureColor.rgb, vec3(gamma)), textureColor.w);\n" + - " }"; - - private int mGammaLocation; - private float mGamma; - - public GPUImageGammaFilter() { - this(1.2f); - } - - public GPUImageGammaFilter(final float gamma) { - super(NO_FILTER_VERTEX_SHADER, GAMMA_FRAGMENT_SHADER); - mGamma = gamma; - } - - @Override - public void onInit() { - super.onInit(); - mGammaLocation = GLES20.glGetUniformLocation(getProgram(), "gamma"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setGamma(mGamma); - } - - public void setGamma(final float gamma) { - mGamma = gamma; - setFloat(mGammaLocation, mGamma); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGaussianBlurFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGaussianBlurFilter.java deleted file mode 100755 index c912f73..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGaussianBlurFilter.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * A more generalized 9x9 Gaussian blur filter - * blurSize value ranging from 0.0 on up, with a default of 1.0 - */ -public class GPUImageGaussianBlurFilter extends GPUImageTwoPassTextureSamplingFilter { - public static final String VERTEX_SHADER = - "attribute vec4 position;\n" + - "attribute vec4 inputTextureCoordinate;\n" + - "\n" + - "const int GAUSSIAN_SAMPLES = 9;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 blurCoordinates[GAUSSIAN_SAMPLES];\n" + - "\n" + - "void main()\n" + - "{\n" + - " gl_Position = position;\n" + - " textureCoordinate = inputTextureCoordinate.xy;\n" + - " \n" + - " // Calculate the positions for the blur\n" + - " int multiplier = 0;\n" + - " vec2 blurStep;\n" + - " vec2 singleStepOffset = vec2(texelHeightOffset, texelWidthOffset);\n" + - " \n" + - " for (int i = 0; i < GAUSSIAN_SAMPLES; i++)\n" + - " {\n" + - " multiplier = (i - ((GAUSSIAN_SAMPLES - 1) / 2));\n" + - " // Blur in x (horizontal)\n" + - " blurStep = float(multiplier) * singleStepOffset;\n" + - " blurCoordinates[i] = inputTextureCoordinate.xy + blurStep;\n" + - " }\n" + - "}\n"; - - public static final String FRAGMENT_SHADER = - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "const lowp int GAUSSIAN_SAMPLES = 9;\n" + - "\n" + - "varying highp vec2 textureCoordinate;\n" + - "varying highp vec2 blurCoordinates[GAUSSIAN_SAMPLES];\n" + - "\n" + - "void main()\n" + - "{\n" + - " lowp vec3 sum = vec3(0.0);\n" + - " lowp vec4 fragColor=texture2D(inputImageTexture,textureCoordinate);\n" + - " \n" + - " sum += texture2D(inputImageTexture, blurCoordinates[0]).rgb * 0.05;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[1]).rgb * 0.09;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[2]).rgb * 0.12;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[3]).rgb * 0.15;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[4]).rgb * 0.18;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[5]).rgb * 0.15;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[6]).rgb * 0.12;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[7]).rgb * 0.09;\n" + - " sum += texture2D(inputImageTexture, blurCoordinates[8]).rgb * 0.05;\n" + - "\n" + - " gl_FragColor = vec4(sum,fragColor.a);\n" + - "}"; - - protected float mBlurSize = 1f; - - public GPUImageGaussianBlurFilter() { - this(1f); - } - - public GPUImageGaussianBlurFilter(float blurSize) { - super(VERTEX_SHADER, FRAGMENT_SHADER, VERTEX_SHADER, FRAGMENT_SHADER); - mBlurSize = blurSize; - } - - @Override - public float getVerticalTexelOffsetRatio() { - return mBlurSize; - } - - @Override - public float getHorizontalTexelOffsetRatio() { - return mBlurSize; - } - - /** - * A multiplier for the blur size, ranging from 0.0 on up, with a default of 1.0 - * - * @param blurSize from 0.0 on up, default 1.0 - */ - public void setBlurSize(float blurSize) { - mBlurSize = blurSize; - runOnDraw(new Runnable() { - @Override - public void run() { - initTexelOffsets(); - } - }); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGlassSphereFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGlassSphereFilter.java deleted file mode 100755 index 460019c..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGlassSphereFilter.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.graphics.PointF; -import android.opengl.GLES20; - -public class GPUImageGlassSphereFilter extends GPUImageFilter { - public static final String SPHERE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform highp vec2 center;\n" + - "uniform highp float radius;\n" + - "uniform highp float aspectRatio;\n" + - "uniform highp float refractiveIndex;\n" + - "// uniform vec3 lightPosition;\n" + - "const highp vec3 lightPosition = vec3(-0.5, 0.5, 1.0);\n" + - "const highp vec3 ambientLightPosition = vec3(0.0, 0.0, 1.0);\n" + - "\n" + - "void main()\n" + - "{\n" + - "highp vec2 textureCoordinateToUse = vec2(textureCoordinate.x, (textureCoordinate.y * aspectRatio + 0.5 - 0.5 * aspectRatio));\n" + - "highp float distanceFromCenter = distance(center, textureCoordinateToUse);\n" + - "lowp float checkForPresenceWithinSphere = step(distanceFromCenter, radius);\n" + - "\n" + - "distanceFromCenter = distanceFromCenter / radius;\n" + - "\n" + - "highp float normalizedDepth = radius * sqrt(1.0 - distanceFromCenter * distanceFromCenter);\n" + - "highp vec3 sphereNormal = normalize(vec3(textureCoordinateToUse - center, normalizedDepth));\n" + - "\n" + - "highp vec3 refractedVector = 2.0 * refract(vec3(0.0, 0.0, -1.0), sphereNormal, refractiveIndex);\n" + - "refractedVector.xy = -refractedVector.xy;\n" + - "\n" + - "highp vec3 finalSphereColor = texture2D(inputImageTexture, (refractedVector.xy + 1.0) * 0.5).rgb;\n" + - "\n" + - "// Grazing angle lighting\n" + - "highp float lightingIntensity = 2.5 * (1.0 - pow(clamp(dot(ambientLightPosition, sphereNormal), 0.0, 1.0), 0.25));\n" + - "finalSphereColor += lightingIntensity;\n" + - "\n" + - "// Specular lighting\n" + - "lightingIntensity = clamp(dot(normalize(lightPosition), sphereNormal), 0.0, 1.0);\n" + - "lightingIntensity = pow(lightingIntensity, 15.0);\n" + - "finalSphereColor += vec3(0.8, 0.8, 0.8) * lightingIntensity;\n" + - "\n" + - "gl_FragColor = vec4(finalSphereColor, 1.0) * checkForPresenceWithinSphere;\n" + - "}\n"; - - private PointF mCenter; - private int mCenterLocation; - private float mRadius; - private int mRadiusLocation; - private float mAspectRatio; - private int mAspectRatioLocation; - private float mRefractiveIndex; - private int mRefractiveIndexLocation; - - public GPUImageGlassSphereFilter() { - this(new PointF(0.5f, 0.5f), 0.25f, 0.71f); - } - - public GPUImageGlassSphereFilter(PointF center, float radius, float refractiveIndex) { - super(NO_FILTER_VERTEX_SHADER, SPHERE_FRAGMENT_SHADER); - mCenter = center; - mRadius = radius; - mRefractiveIndex = refractiveIndex; - } - - @Override - public void onInit() { - super.onInit(); - mCenterLocation = GLES20.glGetUniformLocation(getProgram(), "center"); - mRadiusLocation = GLES20.glGetUniformLocation(getProgram(), "radius"); - mAspectRatioLocation = GLES20.glGetUniformLocation(getProgram(), "aspectRatio"); - mRefractiveIndexLocation = GLES20.glGetUniformLocation(getProgram(), "refractiveIndex"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setRadius(mRadius); - setCenter(mCenter); - setRefractiveIndex(mRefractiveIndex); - } - - @Override - public void onOutputSizeChanged(int width, int height) { - mAspectRatio = (float) height / width; - setAspectRatio(mAspectRatio); - super.onOutputSizeChanged(width, height); - } - - private void setAspectRatio(float aspectRatio) { - mAspectRatio = aspectRatio; - setFloat(mAspectRatioLocation, aspectRatio); - } - - public void setRefractiveIndex(float refractiveIndex) { - mRefractiveIndex = refractiveIndex; - setFloat(mRefractiveIndexLocation, refractiveIndex); - } - - public void setCenter(PointF center) { - mCenter = center; - setPoint(mCenterLocation, center); - } - - public void setRadius(float radius) { - mRadius = radius; - setFloat(mRadiusLocation, radius); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGrayscaleFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGrayscaleFilter.java deleted file mode 100755 index b0a67f9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageGrayscaleFilter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * Applies a grayscale effect to the image. - */ -public class GPUImageGrayscaleFilter extends GPUImageFilter { - public static final String GRAYSCALE_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" + - "\n" + - "void main()\n" + - "{\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " float luminance = dot(textureColor.rgb, W);\n" + - "\n" + - " gl_FragColor = vec4(vec3(luminance), textureColor.a);\n" + - "}"; - - public GPUImageGrayscaleFilter() { - super(NO_FILTER_VERTEX_SHADER, GRAYSCALE_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHardLightBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHardLightBlendFilter.java deleted file mode 100755 index 5bcb9c9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHardLightBlendFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageHardLightBlendFilter extends GPUImageTwoInputFilter { - public static final String HARD_LIGHT_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - "\n" + - " const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" + - "\n" + - " void main()\n" + - " {\n" + - " mediump vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - "\n" + - " highp float ra;\n" + - " if (2.0 * overlay.r < overlay.a) {\n" + - " ra = 2.0 * overlay.r * base.r + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " } else {\n" + - " ra = overlay.a * base.a - 2.0 * (base.a - base.r) * (overlay.a - overlay.r) + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " }\n" + - " \n" + - " highp float ga;\n" + - " if (2.0 * overlay.g < overlay.a) {\n" + - " ga = 2.0 * overlay.g * base.g + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - " } else {\n" + - " ga = overlay.a * base.a - 2.0 * (base.a - base.g) * (overlay.a - overlay.g) + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - " }\n" + - " \n" + - " highp float ba;\n" + - " if (2.0 * overlay.b < overlay.a) {\n" + - " ba = 2.0 * overlay.b * base.b + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - " } else {\n" + - " ba = overlay.a * base.a - 2.0 * (base.a - base.b) * (overlay.a - overlay.b) + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - " }\n" + - " \n" + - " gl_FragColor = vec4(ra, ga, ba, 1.0);\n" + - " }"; - - public GPUImageHardLightBlendFilter() { - super(HARD_LIGHT_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHazeFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHazeFilter.java deleted file mode 100755 index bb230ab..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHazeFilter.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * The haze filter can be used to add or remove haze. - * - * This is similar to a UV filter. - */ -public class GPUImageHazeFilter extends GPUImageFilter { - public static final String HAZE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform lowp float distance;\n" + - "uniform highp float slope;\n" + - "\n" + - "void main()\n" + - "{\n" + - " //todo reconsider precision modifiers \n" + - " highp vec4 color = vec4(1.0);//todo reimplement as a parameter\n" + - "\n" + - " highp float d = textureCoordinate.y * slope + distance; \n" + - "\n" + - " highp vec4 c = texture2D(inputImageTexture, textureCoordinate) ; // consider using unpremultiply\n" + - "\n" + - " c = (c - d * color) / (1.0 -d);\n" + - "\n" + - " gl_FragColor = c; //consider using premultiply(c);\n" + - "}\n"; - - private float mDistance; - private int mDistanceLocation; - private float mSlope; - private int mSlopeLocation; - - public GPUImageHazeFilter() { - this(0.2f, 0.0f); - } - - public GPUImageHazeFilter(float distance, float slope) { - super(NO_FILTER_VERTEX_SHADER, HAZE_FRAGMENT_SHADER); - mDistance = distance; - mSlope = slope; - } - - @Override - public void onInit() { - super.onInit(); - mDistanceLocation = GLES20.glGetUniformLocation(getProgram(), "distance"); - mSlopeLocation = GLES20.glGetUniformLocation(getProgram(), "slope"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setDistance(mDistance); - setSlope(mSlope); - } - - /** - * Strength of the color applied. Default 0. Values between -.3 and .3 are best. - * - * @param distance -0.3 to 0.3 are best, default 0 - */ - public void setDistance(float distance) { - mDistance = distance; - setFloat(mDistanceLocation, distance); - } - - /** - * Amount of color change. Default 0. Values between -.3 and .3 are best. - * - * @param slope -0.3 to 0.3 are best, default 0 - */ - public void setSlope(float slope) { - mSlope = slope; - setFloat(mSlopeLocation, slope); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHighlightShadowFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHighlightShadowFilter.java deleted file mode 100755 index 878c508..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHighlightShadowFilter.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Adjusts the shadows and highlights of an image - * shadows: Increase to lighten shadows, from 0.0 to 1.0, with 0.0 as the default. - * highlights: Decrease to darken highlights, from 0.0 to 1.0, with 1.0 as the default. - */ -public class GPUImageHighlightShadowFilter extends GPUImageFilter { - public static final String HIGHLIGHT_SHADOW_FRAGMENT_SHADER = "" + - " uniform sampler2D inputImageTexture;\n" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform lowp float shadows;\n" + - " uniform lowp float highlights;\n" + - " \n" + - " const mediump vec3 luminanceWeighting = vec3(0.3, 0.3, 0.3);\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 source = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump float luminance = dot(source.rgb, luminanceWeighting);\n" + - " \n" + - " mediump float shadow = clamp((pow(luminance, 1.0/(shadows+1.0)) + (-0.76)*pow(luminance, 2.0/(shadows+1.0))) - luminance, 0.0, 1.0);\n" + - " mediump float highlight = clamp((1.0 - (pow(1.0-luminance, 1.0/(2.0-highlights)) + (-0.8)*pow(1.0-luminance, 2.0/(2.0-highlights)))) - luminance, -1.0, 0.0);\n" + - " lowp vec3 result = vec3(0.0, 0.0, 0.0) + ((luminance + shadow + highlight) - 0.0) * ((source.rgb - vec3(0.0, 0.0, 0.0))/(luminance - 0.0));\n" + - " \n" + - " gl_FragColor = vec4(result.rgb, source.a);\n" + - " }"; - - private int mShadowsLocation; - private float mShadows; - private int mHighlightsLocation; - private float mHighlights; - - public GPUImageHighlightShadowFilter() { - this(0.0f, 1.0f); - } - - public GPUImageHighlightShadowFilter(final float shadows, final float highlights) { - super(NO_FILTER_VERTEX_SHADER, HIGHLIGHT_SHADOW_FRAGMENT_SHADER); - mHighlights = highlights; - mShadows = shadows; - } - - @Override - public void onInit() { - super.onInit(); - mHighlightsLocation = GLES20.glGetUniformLocation(getProgram(), "highlights"); - mShadowsLocation = GLES20.glGetUniformLocation(getProgram(), "shadows"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setHighlights(mHighlights); - setShadows(mShadows); - } - - public void setHighlights(final float highlights) { - mHighlights = highlights; - setFloat(mHighlightsLocation, mHighlights); - } - - public void setShadows(final float shadows) { - mShadows = shadows; - setFloat(mShadowsLocation, mShadows); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHueBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHueBlendFilter.java deleted file mode 100755 index 3950901..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHueBlendFilter.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageHueBlendFilter extends GPUImageTwoInputFilter { - public static final String HUE_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " highp float lum(lowp vec3 c) {\n" + - " return dot(c, vec3(0.3, 0.59, 0.11));\n" + - " }\n" + - " \n" + - " lowp vec3 clipcolor(lowp vec3 c) {\n" + - " highp float l = lum(c);\n" + - " lowp float n = min(min(c.r, c.g), c.b);\n" + - " lowp float x = max(max(c.r, c.g), c.b);\n" + - " \n" + - " if (n < 0.0) {\n" + - " c.r = l + ((c.r - l) * l) / (l - n);\n" + - " c.g = l + ((c.g - l) * l) / (l - n);\n" + - " c.b = l + ((c.b - l) * l) / (l - n);\n" + - " }\n" + - " if (x > 1.0) {\n" + - " c.r = l + ((c.r - l) * (1.0 - l)) / (x - l);\n" + - " c.g = l + ((c.g - l) * (1.0 - l)) / (x - l);\n" + - " c.b = l + ((c.b - l) * (1.0 - l)) / (x - l);\n" + - " }\n" + - " \n" + - " return c;\n" + - " }\n" + - " \n" + - " lowp vec3 setlum(lowp vec3 c, highp float l) {\n" + - " highp float d = l - lum(c);\n" + - " c = c + vec3(d);\n" + - " return clipcolor(c);\n" + - " }\n" + - " \n" + - " highp float sat(lowp vec3 c) {\n" + - " lowp float n = min(min(c.r, c.g), c.b);\n" + - " lowp float x = max(max(c.r, c.g), c.b);\n" + - " return x - n;\n" + - " }\n" + - " \n" + - " lowp float mid(lowp float cmin, lowp float cmid, lowp float cmax, highp float s) {\n" + - " return ((cmid - cmin) * s) / (cmax - cmin);\n" + - " }\n" + - " \n" + - " lowp vec3 setsat(lowp vec3 c, highp float s) {\n" + - " if (c.r > c.g) {\n" + - " if (c.r > c.b) {\n" + - " if (c.g > c.b) {\n" + - " /* g is mid, b is min */\n" + - " c.g = mid(c.b, c.g, c.r, s);\n" + - " c.b = 0.0;\n" + - " } else {\n" + - " /* b is mid, g is min */\n" + - " c.b = mid(c.g, c.b, c.r, s);\n" + - " c.g = 0.0;\n" + - " }\n" + - " c.r = s;\n" + - " } else {\n" + - " /* b is max, r is mid, g is min */\n" + - " c.r = mid(c.g, c.r, c.b, s);\n" + - " c.b = s;\n" + - " c.r = 0.0;\n" + - " }\n" + - " } else if (c.r > c.b) {\n" + - " /* g is max, r is mid, b is min */\n" + - " c.r = mid(c.b, c.r, c.g, s);\n" + - " c.g = s;\n" + - " c.b = 0.0;\n" + - " } else if (c.g > c.b) {\n" + - " /* g is max, b is mid, r is min */\n" + - " c.b = mid(c.r, c.b, c.g, s);\n" + - " c.g = s;\n" + - " c.r = 0.0;\n" + - " } else if (c.b > c.g) {\n" + - " /* b is max, g is mid, r is min */\n" + - " c.g = mid(c.r, c.g, c.b, s);\n" + - " c.b = s;\n" + - " c.r = 0.0;\n" + - " } else {\n" + - " c = vec3(0.0);\n" + - " }\n" + - " return c;\n" + - " }\n" + - " \n" + - " void main()\n" + - " {\n" + - " highp vec4 baseColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " highp vec4 overlayColor = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = vec4(baseColor.rgb * (1.0 - overlayColor.a) + setlum(setsat(overlayColor.rgb, sat(baseColor.rgb)), lum(baseColor.rgb)) * overlayColor.a, baseColor.a);\n" + - " }"; - - public GPUImageHueBlendFilter() { - super(HUE_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHueFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHueFilter.java deleted file mode 100755 index 9fcf793..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageHueFilter.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImageHueFilter extends GPUImageFilter { - public static final String HUE_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform mediump float hueAdjust;\n" + - "const highp vec4 kRGBToYPrime = vec4 (0.299, 0.587, 0.114, 0.0);\n" + - "const highp vec4 kRGBToI = vec4 (0.595716, -0.274453, -0.321263, 0.0);\n" + - "const highp vec4 kRGBToQ = vec4 (0.211456, -0.522591, 0.31135, 0.0);\n" + - "\n" + - "const highp vec4 kYIQToR = vec4 (1.0, 0.9563, 0.6210, 0.0);\n" + - "const highp vec4 kYIQToG = vec4 (1.0, -0.2721, -0.6474, 0.0);\n" + - "const highp vec4 kYIQToB = vec4 (1.0, -1.1070, 1.7046, 0.0);\n" + - "\n" + - "void main ()\n" + - "{\n" + - " // Sample the input pixel\n" + - " highp vec4 color = texture2D(inputImageTexture, textureCoordinate);\n" + - "\n" + - " // Convert to YIQ\n" + - " highp float YPrime = dot (color, kRGBToYPrime);\n" + - " highp float I = dot (color, kRGBToI);\n" + - " highp float Q = dot (color, kRGBToQ);\n" + - "\n" + - " // Calculate the hue and chroma\n" + - " highp float hue = atan (Q, I);\n" + - " highp float chroma = sqrt (I * I + Q * Q);\n" + - "\n" + - " // Make the user's adjustments\n" + - " hue += (-hueAdjust); //why negative rotation?\n" + - "\n" + - " // Convert back to YIQ\n" + - " Q = chroma * sin (hue);\n" + - " I = chroma * cos (hue);\n" + - "\n" + - " // Convert back to RGB\n" + - " highp vec4 yIQ = vec4 (YPrime, I, Q, 0.0);\n" + - " color.r = dot (yIQ, kYIQToR);\n" + - " color.g = dot (yIQ, kYIQToG);\n" + - " color.b = dot (yIQ, kYIQToB);\n" + - "\n" + - " // Save the result\n" + - " gl_FragColor = color;\n" + - "}\n"; - - private float mHue; - private int mHueLocation; - - public GPUImageHueFilter() { - this(90.0f); - } - - public GPUImageHueFilter(final float hue) { - super(NO_FILTER_VERTEX_SHADER, HUE_FRAGMENT_SHADER); - mHue = hue; - } - - @Override - public void onInit() { - super.onInit(); - mHueLocation = GLES20.glGetUniformLocation(getProgram(), "hueAdjust"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setHue(mHue); - } - - public void setHue(final float hue) { - mHue = hue; - float hueAdjust = (mHue % 360.0f) * (float) Math.PI / 180.0f; - setFloat(mHueLocation, hueAdjust); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageKuwaharaFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageKuwaharaFilter.java deleted file mode 100755 index 6fc7f32..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageKuwaharaFilter.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Kuwahara image abstraction, drawn from the work of Kyprianidis, et. al. in their publication - * "Anisotropic Kuwahara Filtering on the GPU" within the GPU Pro collection. This produces an oil-painting-like - * image, but it is extremely computationally expensive, so it can take seconds to render a frame on an iPad 2. - * This might be best used for still images. - */ -public class GPUImageKuwaharaFilter extends GPUImageFilter { - public static final String KUWAHARA_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform int radius;\n" + - "\n" + - "precision highp float;\n" + - "\n" + - "const vec2 src_size = vec2 (1.0 / 768.0, 1.0 / 1024.0);\n" + - "\n" + - "void main (void) \n" + - "{\n" + - "vec2 uv = textureCoordinate;\n" + - "float n = float((radius + 1) * (radius + 1));\n" + - "int i; int j;\n" + - "vec3 m0 = vec3(0.0); vec3 m1 = vec3(0.0); vec3 m2 = vec3(0.0); vec3 m3 = vec3(0.0);\n" + - "vec3 s0 = vec3(0.0); vec3 s1 = vec3(0.0); vec3 s2 = vec3(0.0); vec3 s3 = vec3(0.0);\n" + - "vec3 c;\n" + - "\n" + - "for (j = -radius; j <= 0; ++j) {\n" + - "for (i = -radius; i <= 0; ++i) {\n" + - "c = texture2D(inputImageTexture, uv + vec2(i,j) * src_size).rgb;\n" + - "m0 += c;\n" + - "s0 += c * c;\n" + - "}\n" + - "}\n" + - "\n" + - "for (j = -radius; j <= 0; ++j) {\n" + - "for (i = 0; i <= radius; ++i) {\n" + - "c = texture2D(inputImageTexture, uv + vec2(i,j) * src_size).rgb;\n" + - "m1 += c;\n" + - "s1 += c * c;\n" + - "}\n" + - "}\n" + - "\n" + - "for (j = 0; j <= radius; ++j) {\n" + - "for (i = 0; i <= radius; ++i) {\n" + - "c = texture2D(inputImageTexture, uv + vec2(i,j) * src_size).rgb;\n" + - "m2 += c;\n" + - "s2 += c * c;\n" + - "}\n" + - "}\n" + - "\n" + - "for (j = 0; j <= radius; ++j) {\n" + - "for (i = -radius; i <= 0; ++i) {\n" + - "c = texture2D(inputImageTexture, uv + vec2(i,j) * src_size).rgb;\n" + - "m3 += c;\n" + - "s3 += c * c;\n" + - "}\n" + - "}\n" + - "\n" + - "\n" + - "float min_sigma2 = 1e+2;\n" + - "m0 /= n;\n" + - "s0 = abs(s0 / n - m0 * m0);\n" + - "\n" + - "float sigma2 = s0.r + s0.g + s0.b;\n" + - "if (sigma2 < min_sigma2) {\n" + - "min_sigma2 = sigma2;\n" + - "gl_FragColor = vec4(m0, 1.0);\n" + - "}\n" + - "\n" + - "m1 /= n;\n" + - "s1 = abs(s1 / n - m1 * m1);\n" + - "\n" + - "sigma2 = s1.r + s1.g + s1.b;\n" + - "if (sigma2 < min_sigma2) {\n" + - "min_sigma2 = sigma2;\n" + - "gl_FragColor = vec4(m1, 1.0);\n" + - "}\n" + - "\n" + - "m2 /= n;\n" + - "s2 = abs(s2 / n - m2 * m2);\n" + - "\n" + - "sigma2 = s2.r + s2.g + s2.b;\n" + - "if (sigma2 < min_sigma2) {\n" + - "min_sigma2 = sigma2;\n" + - "gl_FragColor = vec4(m2, 1.0);\n" + - "}\n" + - "\n" + - "m3 /= n;\n" + - "s3 = abs(s3 / n - m3 * m3);\n" + - "\n" + - "sigma2 = s3.r + s3.g + s3.b;\n" + - "if (sigma2 < min_sigma2) {\n" + - "min_sigma2 = sigma2;\n" + - "gl_FragColor = vec4(m3, 1.0);\n" + - "}\n" + - "}\n"; - - private int mRadius; - private int mRadiusLocation; - - public GPUImageKuwaharaFilter() { - this(3); - } - - public GPUImageKuwaharaFilter(int radius) { - super(NO_FILTER_VERTEX_SHADER, KUWAHARA_FRAGMENT_SHADER); - mRadius = radius; - } - - @Override - public void onInit() { - super.onInit(); - mRadiusLocation = GLES20.glGetUniformLocation(getProgram(), "radius"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setRadius(mRadius); - } - - /** - * The radius to sample from when creating the brush-stroke effect, with a default of 3. - * The larger the radius, the slower the filter. - * - * @param radius default 3 - */ - public void setRadius(final int radius) { - mRadius = radius; - setInteger(mRadiusLocation, radius); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLaplacianFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLaplacianFilter.java deleted file mode 100755 index d320f64..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLaplacianFilter.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImageLaplacianFilter extends GPUImage3x3TextureSamplingFilter { - public static final String LAPLACIAN_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform mediump mat3 convolutionMatrix;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "mediump vec3 bottomColor = texture2D(inputImageTexture, bottomTextureCoordinate).rgb;\n" + - "mediump vec3 bottomLeftColor = texture2D(inputImageTexture, bottomLeftTextureCoordinate).rgb;\n" + - "mediump vec3 bottomRightColor = texture2D(inputImageTexture, bottomRightTextureCoordinate).rgb;\n" + - "mediump vec4 centerColor = texture2D(inputImageTexture, textureCoordinate);\n" + - "mediump vec3 leftColor = texture2D(inputImageTexture, leftTextureCoordinate).rgb;\n" + - "mediump vec3 rightColor = texture2D(inputImageTexture, rightTextureCoordinate).rgb;\n" + - "mediump vec3 topColor = texture2D(inputImageTexture, topTextureCoordinate).rgb;\n" + - "mediump vec3 topRightColor = texture2D(inputImageTexture, topRightTextureCoordinate).rgb;\n" + - "mediump vec3 topLeftColor = texture2D(inputImageTexture, topLeftTextureCoordinate).rgb;\n" + - "\n" + - "mediump vec3 resultColor = topLeftColor * convolutionMatrix[0][0] + topColor * convolutionMatrix[0][1] + topRightColor * convolutionMatrix[0][2];\n" + - "resultColor += leftColor * convolutionMatrix[1][0] + centerColor.rgb * convolutionMatrix[1][1] + rightColor * convolutionMatrix[1][2];\n" + - "resultColor += bottomLeftColor * convolutionMatrix[2][0] + bottomColor * convolutionMatrix[2][1] + bottomRightColor * convolutionMatrix[2][2];\n" + - "\n" + - "// Normalize the results to allow for negative gradients in the 0.0-1.0 colorspace\n" + - "resultColor = resultColor + 0.5;\n" + - "\n" + - "gl_FragColor = vec4(resultColor, centerColor.a);\n" + - "}\n"; - - private float[] mConvolutionKernel; - private int mUniformConvolutionMatrix; - - public GPUImageLaplacianFilter() { - this(new float[]{ - 0.5f, 1.0f, 0.5f, - 1.0f, -6.0f, 1.0f, - 0.5f, 1.0f, 0.5f - }); - } - - private GPUImageLaplacianFilter(final float[] convolutionKernel) { - super(LAPLACIAN_FRAGMENT_SHADER); - mConvolutionKernel = convolutionKernel; - } - - @Override - public void onInit() { - super.onInit(); - mUniformConvolutionMatrix = GLES20.glGetUniformLocation(getProgram(), "convolutionMatrix"); - setConvolutionKernel(mConvolutionKernel); - } - - private void setConvolutionKernel(final float[] convolutionKernel) { - mConvolutionKernel = convolutionKernel; - setUniformMatrix3f(mUniformConvolutionMatrix, mConvolutionKernel); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLevelsFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLevelsFilter.java deleted file mode 100755 index d7fbcfd..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLevelsFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -package jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; -import android.util.Log; - -/** - * Created by vashisthg 30/05/14. - */ -public class GPUImageLevelsFilter extends GPUImageFilter{ - - private static final String LOGTAG = GPUImageLevelsFilter.class.getSimpleName(); - - public static final String LEVELS_FRAGMET_SHADER = - - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform mediump vec3 levelMinimum;\n" + - " uniform mediump vec3 levelMiddle;\n" + - " uniform mediump vec3 levelMaximum;\n" + - " uniform mediump vec3 minOutput;\n" + - " uniform mediump vec3 maxOutput;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4( mix(minOutput, maxOutput, pow(min(max(textureColor.rgb -levelMinimum, vec3(0.0)) / (levelMaximum - levelMinimum ), vec3(1.0)), 1.0 /levelMiddle)) , textureColor.a);\n" + - " }\n"; - - private int mMinLocation; - private float[] mMin; - private int mMidLocation; - private float[] mMid; - private int mMaxLocation; - private float[] mMax; - private int mMinOutputLocation; - private float[] mMinOutput; - private int mMaxOutputLocation; - private float[] mMaxOutput; - - public GPUImageLevelsFilter() { - this(new float[] {0.0f,0.0f,0.0f}, new float[] {1.0f, 1.0f, 1.0f }, new float[] {1.0f, 1.0f ,1.0f}, new float[] {0.0f, 0.0f, 0.0f}, new float[] {1.0f,1.0f,1.0f}); - } - - private GPUImageLevelsFilter(final float[] min, final float[] mid, final float[] max, final float[] minOUt, final float[] maxOut) { - super(NO_FILTER_VERTEX_SHADER, LEVELS_FRAGMET_SHADER); - - mMin = min; - mMid = mid; - mMax = max; - mMinOutput = minOUt; - mMaxOutput = maxOut; - setMin(0.0f, 1.0f, 1.0f, 0.0f, 1.0f); - } - - @Override - public void onInit() { - super.onInit(); - mMinLocation = GLES20.glGetUniformLocation(getProgram(), "levelMinimum"); - mMidLocation = GLES20.glGetUniformLocation(getProgram(), "levelMiddle"); - mMaxLocation = GLES20.glGetUniformLocation(getProgram(), "levelMaximum"); - mMinOutputLocation = GLES20.glGetUniformLocation(getProgram(), "minOutput"); - mMaxOutputLocation = GLES20.glGetUniformLocation(getProgram(), "maxOutput"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - updateUniforms(); - } - - - public void updateUniforms () { - setFloatVec3(mMinLocation, mMin); - setFloatVec3(mMidLocation, mMid); - setFloatVec3(mMaxLocation, mMax); - setFloatVec3(mMinOutputLocation, mMinOutput); - setFloatVec3(mMaxOutputLocation, mMaxOutput); - } - - public void setMin(float min, float mid , float max ,float minOut , float maxOut) { - setRedMin(min, mid, max, minOut, maxOut); - setGreenMin(min, mid, max, minOut, maxOut); - setBlueMin(min, mid, max, minOut, maxOut); - } - - public void setMin(float min, float mid , float max ) { - setMin(min, mid, max, 0.0f, 1.0f); - } - - public void setRedMin(float min, float mid , float max ,float minOut , float maxOut) { - mMin[0] = min; - mMid[0] = mid; - mMax[0] = max; - mMinOutput[0] = minOut; - mMaxOutput[0] = maxOut; - updateUniforms(); - } - - public void setRedMin(float min, float mid , float max ){ - setRedMin(min, mid, max, 0, 1); - } - - public void setGreenMin(float min, float mid , float max ,float minOut , float maxOut) { - mMin[1] = min; - mMid[1] = mid; - mMax[1] = max; - mMinOutput[1] = minOut; - mMaxOutput[1] = maxOut; - updateUniforms(); - } - - public void setGreenMin(float min, float mid , float max ){ - setGreenMin(min, mid, max, 0, 1); - } - - public void setBlueMin(float min, float mid , float max ,float minOut , float maxOut) { - mMin[2] = min; - mMid[2] = mid; - mMax[2] = max; - mMinOutput[2] = minOut; - mMaxOutput[2] = maxOut; - updateUniforms(); - } - - public void setBlueMin(float min, float mid , float max ){ - setBlueMin(min, mid, max, 0, 1); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLightenBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLightenBlendFilter.java deleted file mode 100755 index 77399cb..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLightenBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageLightenBlendFilter extends GPUImageTwoInputFilter { - public static final String LIGHTEN_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = max(textureColor, textureColor2);\n" + - " }"; - - public GPUImageLightenBlendFilter() { - super(LIGHTEN_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLinearBurnBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLinearBurnBlendFilter.java deleted file mode 100755 index 2623b52..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLinearBurnBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageLinearBurnBlendFilter extends GPUImageTwoInputFilter { - public static final String LINEAR_BURN_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = vec4(clamp(textureColor.rgb + textureColor2.rgb - vec3(1.0), vec3(0.0), vec3(1.0)), textureColor.a);\n" + - " }"; - - public GPUImageLinearBurnBlendFilter() { - super(LINEAR_BURN_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLookupFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLookupFilter.java deleted file mode 100755 index b9cfa2b..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLookupFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageLookupFilter extends GPUImageTwoInputFilter { - - public static final String LOOKUP_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2; // TODO: This is not used\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2; // lookup texture\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " mediump float blueColor = textureColor.b * 63.0;\n" + - " \n" + - " mediump vec2 quad1;\n" + - " quad1.y = floor(floor(blueColor) / 8.0);\n" + - " quad1.x = floor(blueColor) - (quad1.y * 8.0);\n" + - " \n" + - " mediump vec2 quad2;\n" + - " quad2.y = floor(ceil(blueColor) / 8.0);\n" + - " quad2.x = ceil(blueColor) - (quad2.y * 8.0);\n" + - " \n" + - " highp vec2 texPos1;\n" + - " texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n" + - " texPos1.y = (quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\n" + - " \n" + - " highp vec2 texPos2;\n" + - " texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n" + - " texPos2.y = (quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\n" + - " \n" + - " lowp vec4 newColor1 = texture2D(inputImageTexture2, texPos1);\n" + - " lowp vec4 newColor2 = texture2D(inputImageTexture2, texPos2);\n" + - " \n" + - " lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));\n" + - " gl_FragColor = vec4(newColor.rgb, textureColor.w);\n" + - " }"; - - - public GPUImageLookupFilter() { - super(LOOKUP_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLuminosityBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLuminosityBlendFilter.java deleted file mode 100755 index 85e7bfd..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageLuminosityBlendFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageLuminosityBlendFilter extends GPUImageTwoInputFilter { - public static final String LUMINOSITY_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " highp float lum(lowp vec3 c) {\n" + - " return dot(c, vec3(0.3, 0.59, 0.11));\n" + - " }\n" + - " \n" + - " lowp vec3 clipcolor(lowp vec3 c) {\n" + - " highp float l = lum(c);\n" + - " lowp float n = min(min(c.r, c.g), c.b);\n" + - " lowp float x = max(max(c.r, c.g), c.b);\n" + - " \n" + - " if (n < 0.0) {\n" + - " c.r = l + ((c.r - l) * l) / (l - n);\n" + - " c.g = l + ((c.g - l) * l) / (l - n);\n" + - " c.b = l + ((c.b - l) * l) / (l - n);\n" + - " }\n" + - " if (x > 1.0) {\n" + - " c.r = l + ((c.r - l) * (1.0 - l)) / (x - l);\n" + - " c.g = l + ((c.g - l) * (1.0 - l)) / (x - l);\n" + - " c.b = l + ((c.b - l) * (1.0 - l)) / (x - l);\n" + - " }\n" + - " \n" + - " return c;\n" + - " }\n" + - " \n" + - " lowp vec3 setlum(lowp vec3 c, highp float l) {\n" + - " highp float d = l - lum(c);\n" + - " c = c + vec3(d);\n" + - " return clipcolor(c);\n" + - " }\n" + - " \n" + - " void main()\n" + - " {\n" + - " highp vec4 baseColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " highp vec4 overlayColor = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = vec4(baseColor.rgb * (1.0 - overlayColor.a) + setlum(baseColor.rgb, lum(overlayColor.rgb)) * overlayColor.a, baseColor.a);\n" + - " }"; - - public GPUImageLuminosityBlendFilter() { - super(LUMINOSITY_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMixBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMixBlendFilter.java deleted file mode 100755 index 7bf6885..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMixBlendFilter.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImageMixBlendFilter extends GPUImageTwoInputFilter { - - private int mMixLocation; - private float mMix; - - public GPUImageMixBlendFilter(String fragmentShader) { - this(fragmentShader, 0.5f); - } - - public GPUImageMixBlendFilter(String fragmentShader, float mix) { - super(fragmentShader); - mMix = mix; - } - - @Override - public void onInit() { - super.onInit(); - mMixLocation = GLES20.glGetUniformLocation(getProgram(), "mixturePercent"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setMix(mMix); - } - - /** - * @param mix ranges from 0.0 (only image 1) to 1.0 (only image 2), with 0.5 (half of either) as the normal level - */ - public void setMix(final float mix) { - mMix = mix; - setFloat(mMixLocation, mMix); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMonochromeFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMonochromeFilter.java deleted file mode 100755 index e426a34..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMonochromeFilter.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Converts the image to a single-color version, based on the luminance of each pixel - * intensity: The degree to which the specific color replaces the normal image color (0.0 - 1.0, with 1.0 as the default) - * color: The color to use as the basis for the effect, with (0.6, 0.45, 0.3, 1.0) as the default. - */ -public class GPUImageMonochromeFilter extends GPUImageFilter { - public static final String MONOCHROME_FRAGMENT_SHADER = "" + - " precision lowp float;\n" + - " \n" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform float intensity;\n" + - " uniform vec3 filterColor;\n" + - " \n" + - " const mediump vec3 luminanceWeighting = vec3(0.2125, 0.7154, 0.0721);\n" + - " \n" + - " void main()\n" + - " {\n" + - " //desat, then apply overlay blend\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " float luminance = dot(textureColor.rgb, luminanceWeighting);\n" + - " \n" + - " lowp vec4 desat = vec4(vec3(luminance), 1.0);\n" + - " \n" + - " //overlay\n" + - " lowp vec4 outputColor = vec4(\n" + - " (desat.r < 0.5 ? (2.0 * desat.r * filterColor.r) : (1.0 - 2.0 * (1.0 - desat.r) * (1.0 - filterColor.r))),\n" + - " (desat.g < 0.5 ? (2.0 * desat.g * filterColor.g) : (1.0 - 2.0 * (1.0 - desat.g) * (1.0 - filterColor.g))),\n" + - " (desat.b < 0.5 ? (2.0 * desat.b * filterColor.b) : (1.0 - 2.0 * (1.0 - desat.b) * (1.0 - filterColor.b))),\n" + - " 1.0\n" + - " );\n" + - " \n" + - " //which is better, or are they equal?\n" + - " gl_FragColor = vec4( mix(textureColor.rgb, outputColor.rgb, intensity), textureColor.a);\n" + - " }"; - - private int mIntensityLocation; - private float mIntensity; - private int mFilterColorLocation; - private float[] mColor; - - public GPUImageMonochromeFilter() { - this(1.0f, new float[] {0.6f, 0.45f, 0.3f, 1.0f}); - } - - public GPUImageMonochromeFilter(final float intensity, final float[] color) { - super(NO_FILTER_VERTEX_SHADER, MONOCHROME_FRAGMENT_SHADER); - mIntensity = intensity; - mColor = color; - } - - @Override - public void onInit() { - super.onInit(); - mIntensityLocation = GLES20.glGetUniformLocation(getProgram(), "intensity"); - mFilterColorLocation = GLES20.glGetUniformLocation(getProgram(), "filterColor"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setIntensity(1.0f); - setColor(new float[]{ 0.6f, 0.45f, 0.3f, 1.f }); - } - - public void setIntensity(final float intensity) { - mIntensity = intensity; - setFloat(mIntensityLocation, mIntensity); - } - - public void setColor(final float[] color) { - mColor = color; - setColorRed(mColor[0], mColor[1], mColor[2]); - - } - - public void setColorRed(final float red, final float green, final float blue) { - setFloatVec3(mFilterColorLocation, new float[]{ red, green, blue }); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMultiplyBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMultiplyBlendFilter.java deleted file mode 100755 index 1e002e3..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageMultiplyBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageMultiplyBlendFilter extends GPUImageTwoInputFilter { - public static final String MULTIPLY_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 overlayer = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = overlayer * base + overlayer * (1.0 - base.a) + base * (1.0 - overlayer.a);\n" + - " }"; - - public GPUImageMultiplyBlendFilter() { - super(MULTIPLY_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNativeLibrary.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNativeLibrary.java deleted file mode 100755 index ce8c31b..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNativeLibrary.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageNativeLibrary { - static { - System.loadLibrary("gpuimage-library"); - } - - public static native void YUVtoRBGA(byte[] yuv, int width, int height, int[] out); - - public static native void YUVtoARBG(byte[] yuv, int width, int height, int[] out); -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNonMaximumSuppressionFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNonMaximumSuppressionFilter.java deleted file mode 100755 index a6f5af4..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNonMaximumSuppressionFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageNonMaximumSuppressionFilter extends GPUImage3x3TextureSamplingFilter { - public static final String NMS_FRAGMENT_SHADER = "" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "varying highp vec2 textureCoordinate;\n" + - "varying highp vec2 leftTextureCoordinate;\n" + - "varying highp vec2 rightTextureCoordinate;\n" + - "\n" + - "varying highp vec2 topTextureCoordinate;\n" + - "varying highp vec2 topLeftTextureCoordinate;\n" + - "varying highp vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying highp vec2 bottomTextureCoordinate;\n" + - "varying highp vec2 bottomLeftTextureCoordinate;\n" + - "varying highp vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp float bottomColor = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - "lowp float bottomLeftColor = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - "lowp float bottomRightColor = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - "lowp vec4 centerColor = texture2D(inputImageTexture, textureCoordinate);\n" + - "lowp float leftColor = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - "lowp float rightColor = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - "lowp float topColor = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - "lowp float topRightColor = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - "lowp float topLeftColor = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - "\n" + - "// Use a tiebreaker for pixels to the left and immediately above this one\n" + - "lowp float multiplier = 1.0 - step(centerColor.r, topColor);\n" + - "multiplier = multiplier * 1.0 - step(centerColor.r, topLeftColor);\n" + - "multiplier = multiplier * 1.0 - step(centerColor.r, leftColor);\n" + - "multiplier = multiplier * 1.0 - step(centerColor.r, bottomLeftColor);\n" + - "\n" + - "lowp float maxValue = max(centerColor.r, bottomColor);\n" + - "maxValue = max(maxValue, bottomRightColor);\n" + - "maxValue = max(maxValue, rightColor);\n" + - "maxValue = max(maxValue, topRightColor);\n" + - "\n" + - "gl_FragColor = vec4((centerColor.rgb * step(maxValue, centerColor.r) * multiplier), 1.0);\n" + - "}\n"; - - public GPUImageNonMaximumSuppressionFilter() { - super(NMS_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNormalBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNormalBlendFilter.java deleted file mode 100755 index a886bd4..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageNormalBlendFilter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * This equation is a simplification of the general blending equation. It assumes the destination color is opaque, and therefore drops the destination color's alpha term. - * - * D = C1 * C1a + C2 * C2a * (1 - C1a) - * where D is the resultant color, C1 is the color of the first element, C1a is the alpha of the first element, C2 is the second element color, C2a is the alpha of the second element. The destination alpha is calculated with: - * - * Da = C1a + C2a * (1 - C1a) - * The resultant color is premultiplied with the alpha. To restore the color to the unmultiplied values, just divide by Da, the resultant alpha. - * - * http://stackoverflow.com/questions/1724946/blend-mode-on-a-transparent-and-semi-transparent-background - * - * For some reason Photoshop behaves - * D = C1 + C2 * C2a * (1 - C1a) - */ -public class GPUImageNormalBlendFilter extends GPUImageTwoInputFilter { - public static final String NORMAL_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 c2 = texture2D(inputImageTexture, textureCoordinate);\n" + - "\t lowp vec4 c1 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " lowp vec4 outputColor;\n" + - " \n" + - " outputColor.r = c1.r + c2.r * c2.a * (1.0 - c1.a);\n" + - "\n" + - " outputColor.g = c1.g + c2.g * c2.a * (1.0 - c1.a);\n" + - " \n" + - " outputColor.b = c1.b + c2.b * c2.a * (1.0 - c1.a);\n" + - " \n" + - " outputColor.a = c1.a + c2.a * (1.0 - c1.a);\n" + - " \n" + - " gl_FragColor = outputColor;\n" + - " }"; - - public GPUImageNormalBlendFilter() { - super(NORMAL_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageOpacityFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageOpacityFilter.java deleted file mode 100755 index 55f198d..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageOpacityFilter.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Adjusts the alpha channel of the incoming image - * opacity: The value to multiply the incoming alpha channel for each pixel by (0.0 - 1.0, with 1.0 as the default) -*/ -public class GPUImageOpacityFilter extends GPUImageFilter { - public static final String OPACITY_FRAGMENT_SHADER = "" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform lowp float opacity;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4(textureColor.rgb, textureColor.a * opacity);\n" + - " }\n"; - - private int mOpacityLocation; - private float mOpacity; - - public GPUImageOpacityFilter() { - this(1.0f); - } - - public GPUImageOpacityFilter(final float opacity) { - super(NO_FILTER_VERTEX_SHADER, OPACITY_FRAGMENT_SHADER); - mOpacity = opacity; - } - - @Override - public void onInit() { - super.onInit(); - mOpacityLocation = GLES20.glGetUniformLocation(getProgram(), "opacity"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setOpacity(mOpacity); - } - - public void setOpacity(final float opacity) { - mOpacity = opacity; - setFloat(mOpacityLocation, mOpacity); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageOverlayBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageOverlayBlendFilter.java deleted file mode 100755 index 4dba420..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageOverlayBlendFilter.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageOverlayBlendFilter extends GPUImageTwoInputFilter { - public static final String OVERLAY_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " mediump float ra;\n" + - " if (2.0 * base.r < base.a) {\n" + - " ra = 2.0 * overlay.r * base.r + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " } else {\n" + - " ra = overlay.a * base.a - 2.0 * (base.a - base.r) * (overlay.a - overlay.r) + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);\n" + - " }\n" + - " \n" + - " mediump float ga;\n" + - " if (2.0 * base.g < base.a) {\n" + - " ga = 2.0 * overlay.g * base.g + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - " } else {\n" + - " ga = overlay.a * base.a - 2.0 * (base.a - base.g) * (overlay.a - overlay.g) + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);\n" + - " }\n" + - " \n" + - " mediump float ba;\n" + - " if (2.0 * base.b < base.a) {\n" + - " ba = 2.0 * overlay.b * base.b + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - " } else {\n" + - " ba = overlay.a * base.a - 2.0 * (base.a - base.b) * (overlay.a - overlay.b) + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);\n" + - " }\n" + - " \n" + - " gl_FragColor = vec4(ra, ga, ba, 1.0);\n" + - " }"; - - public GPUImageOverlayBlendFilter() { - super(OVERLAY_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImagePixelationFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImagePixelationFilter.java deleted file mode 100755 index c0ec15d..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImagePixelationFilter.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; -/** - * Applies a grayscale effect to the image. - */ -public class GPUImagePixelationFilter extends GPUImageFilter { - public static final String PIXELATION_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - - "varying vec2 textureCoordinate;\n" + - - "uniform float imageWidthFactor;\n" + - "uniform float imageHeightFactor;\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform float pixel;\n" + - - "void main()\n" + - "{\n" + - " vec2 uv = textureCoordinate.xy;\n" + - " float dx = pixel * imageWidthFactor;\n" + - " float dy = pixel * imageHeightFactor;\n" + - " vec2 coord = vec2(dx * floor(uv.x / dx), dy * floor(uv.y / dy));\n" + - " vec3 tc = texture2D(inputImageTexture, coord).xyz;\n" + - " gl_FragColor = vec4(tc, 1.0);\n" + - "}"; - - private int mImageWidthFactorLocation; - private int mImageHeightFactorLocation; - private float mPixel; - private int mPixelLocation; - - public GPUImagePixelationFilter() { - super(NO_FILTER_VERTEX_SHADER, PIXELATION_FRAGMENT_SHADER); - mPixel = 1.0f; - } - - @Override - public void onInit() { - super.onInit(); - mImageWidthFactorLocation = GLES20.glGetUniformLocation(getProgram(), "imageWidthFactor"); - mImageHeightFactorLocation = GLES20.glGetUniformLocation(getProgram(), "imageHeightFactor"); - mPixelLocation = GLES20.glGetUniformLocation(getProgram(), "pixel"); - setPixel(mPixel); - } - - @Override - public void onOutputSizeChanged(final int width, final int height) { - super.onOutputSizeChanged(width, height); - setFloat(mImageWidthFactorLocation, 1.0f / width); - setFloat(mImageHeightFactorLocation, 1.0f / height); - } - - public void setPixel(final float pixel) { - mPixel = pixel; - setFloat(mPixelLocation, mPixel); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImagePosterizeFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImagePosterizeFilter.java deleted file mode 100755 index 3b7c8ff..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImagePosterizeFilter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Reduces the color range of the image.
- *
- * colorLevels: ranges from 1 to 256, with a default of 10 - */ -public class GPUImagePosterizeFilter extends GPUImageFilter { - public static final String POSTERIZE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform highp float colorLevels;\n" + - "\n" + - "void main()\n" + - "{\n" + - " highp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = floor((textureColor * colorLevels) + vec4(0.5)) / colorLevels;\n" + - "}"; - - private int mGLUniformColorLevels; - private int mColorLevels; - - public GPUImagePosterizeFilter() { - this(10); - } - - public GPUImagePosterizeFilter(final int colorLevels) { - super(GPUImageFilter.NO_FILTER_VERTEX_SHADER, POSTERIZE_FRAGMENT_SHADER); - mColorLevels = colorLevels; - } - - @Override - public void onInit() { - super.onInit(); - mGLUniformColorLevels = GLES20.glGetUniformLocation(getProgram(), "colorLevels"); - setColorLevels(mColorLevels); - } - - public void setColorLevels(final int colorLevels) { - mColorLevels = colorLevels; - setFloat(mGLUniformColorLevels, colorLevels); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRGBDilationFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRGBDilationFilter.java deleted file mode 100755 index 2d5e28c..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRGBDilationFilter.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * For each pixel, this sets it to the maximum value of each color channel in a rectangular neighborhood extending - * out dilationRadius pixels from the center. - * This extends out brighter colors, and can be used for abstraction of color images. - */ -public class GPUImageRGBDilationFilter extends GPUImageTwoPassTextureSamplingFilter { - public static final String VERTEX_SHADER_1 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset; \n" + - "uniform float texelHeightOffset; \n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "}\n"; - - public static final String VERTEX_SHADER_2 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "twoStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 2.0);\n" + - "twoStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 2.0);\n" + - "}\n"; - - public static final String VERTEX_SHADER_3 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "twoStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 2.0);\n" + - "twoStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 2.0);\n" + - "threeStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 3.0);\n" + - "threeStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 3.0);\n" + - "}\n"; - - public static final String VERTEX_SHADER_4 = - "attribute vec4 position;\n" + - "attribute vec2 inputTextureCoordinate;\n" + - "\n" + - "uniform float texelWidthOffset;\n" + - "uniform float texelHeightOffset;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "varying vec2 fourStepsPositiveTextureCoordinate;\n" + - "varying vec2 fourStepsNegativeTextureCoordinate;\n" + - "\n" + - "void main()\n" + - "{\n" + - "gl_Position = position;\n" + - "\n" + - "vec2 offset = vec2(texelWidthOffset, texelHeightOffset);\n" + - "\n" + - "centerTextureCoordinate = inputTextureCoordinate;\n" + - "oneStepNegativeTextureCoordinate = inputTextureCoordinate - offset;\n" + - "oneStepPositiveTextureCoordinate = inputTextureCoordinate + offset;\n" + - "twoStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 2.0);\n" + - "twoStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 2.0);\n" + - "threeStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 3.0);\n" + - "threeStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 3.0);\n" + - "fourStepsNegativeTextureCoordinate = inputTextureCoordinate - (offset * 4.0);\n" + - "fourStepsPositiveTextureCoordinate = inputTextureCoordinate + (offset * 4.0);\n" + - "}\n"; - - - public static final String FRAGMENT_SHADER_1 = - "precision highp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp vec4 centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate);\n" + - "lowp vec4 oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate);\n" + - "lowp vec4 oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate);\n" + - "\n" + - "lowp vec4 maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "\n" + - "gl_FragColor = max(maxValue, oneStepNegativeIntensity);\n" + - "}\n"; - - public static final String FRAGMENT_SHADER_2 = - "precision highp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp vec4 centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate);\n" + - "lowp vec4 oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate);\n" + - "lowp vec4 oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate);\n" + - "lowp vec4 twoStepsPositiveIntensity = texture2D(inputImageTexture, twoStepsPositiveTextureCoordinate);\n" + - "lowp vec4 twoStepsNegativeIntensity = texture2D(inputImageTexture, twoStepsNegativeTextureCoordinate);\n" + - "\n" + - "lowp vec4 maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "maxValue = max(maxValue, twoStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, twoStepsNegativeIntensity);\n" + - "\n" + - "gl_FragColor = max(maxValue, twoStepsNegativeIntensity);\n" + - "}\n"; - - public static final String FRAGMENT_SHADER_3 = - "precision highp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp vec4 centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate);\n" + - "lowp vec4 oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate);\n" + - "lowp vec4 oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate);\n" + - "lowp vec4 twoStepsPositiveIntensity = texture2D(inputImageTexture, twoStepsPositiveTextureCoordinate);\n" + - "lowp vec4 twoStepsNegativeIntensity = texture2D(inputImageTexture, twoStepsNegativeTextureCoordinate);\n" + - "lowp vec4 threeStepsPositiveIntensity = texture2D(inputImageTexture, threeStepsPositiveTextureCoordinate);\n" + - "lowp vec4 threeStepsNegativeIntensity = texture2D(inputImageTexture, threeStepsNegativeTextureCoordinate);\n" + - "\n" + - "lowp vec4 maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "maxValue = max(maxValue, twoStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, twoStepsNegativeIntensity);\n" + - "maxValue = max(maxValue, threeStepsPositiveIntensity);\n" + - "\n" + - "gl_FragColor = max(maxValue, threeStepsNegativeIntensity);\n" + - "}\n"; - - public static final String FRAGMENT_SHADER_4 = - "precision highp float;\n" + - "\n" + - "varying vec2 centerTextureCoordinate;\n" + - "varying vec2 oneStepPositiveTextureCoordinate;\n" + - "varying vec2 oneStepNegativeTextureCoordinate;\n" + - "varying vec2 twoStepsPositiveTextureCoordinate;\n" + - "varying vec2 twoStepsNegativeTextureCoordinate;\n" + - "varying vec2 threeStepsPositiveTextureCoordinate;\n" + - "varying vec2 threeStepsNegativeTextureCoordinate;\n" + - "varying vec2 fourStepsPositiveTextureCoordinate;\n" + - "varying vec2 fourStepsNegativeTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "lowp vec4 centerIntensity = texture2D(inputImageTexture, centerTextureCoordinate);\n" + - "lowp vec4 oneStepPositiveIntensity = texture2D(inputImageTexture, oneStepPositiveTextureCoordinate);\n" + - "lowp vec4 oneStepNegativeIntensity = texture2D(inputImageTexture, oneStepNegativeTextureCoordinate);\n" + - "lowp vec4 twoStepsPositiveIntensity = texture2D(inputImageTexture, twoStepsPositiveTextureCoordinate);\n" + - "lowp vec4 twoStepsNegativeIntensity = texture2D(inputImageTexture, twoStepsNegativeTextureCoordinate);\n" + - "lowp vec4 threeStepsPositiveIntensity = texture2D(inputImageTexture, threeStepsPositiveTextureCoordinate);\n" + - "lowp vec4 threeStepsNegativeIntensity = texture2D(inputImageTexture, threeStepsNegativeTextureCoordinate);\n" + - "lowp vec4 fourStepsPositiveIntensity = texture2D(inputImageTexture, fourStepsPositiveTextureCoordinate);\n" + - "lowp vec4 fourStepsNegativeIntensity = texture2D(inputImageTexture, fourStepsNegativeTextureCoordinate);\n" + - "\n" + - "lowp vec4 maxValue = max(centerIntensity, oneStepPositiveIntensity);\n" + - "maxValue = max(maxValue, oneStepNegativeIntensity);\n" + - "maxValue = max(maxValue, twoStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, twoStepsNegativeIntensity);\n" + - "maxValue = max(maxValue, threeStepsPositiveIntensity);\n" + - "maxValue = max(maxValue, threeStepsNegativeIntensity);\n" + - "maxValue = max(maxValue, fourStepsPositiveIntensity);\n" + - "\n" + - "gl_FragColor = max(maxValue, fourStepsNegativeIntensity);\n" + - "}\n"; - - - public GPUImageRGBDilationFilter() { - this(1); - } - - /** - * Acceptable values for dilationRadius, which sets the distance in pixels to sample out - * from the center, are 1, 2, 3, and 4. - * - * @param radius 1, 2, 3 or 4 - */ - public GPUImageRGBDilationFilter(int radius) { - this(getVertexShader(radius), getFragmentShader(radius)); - } - - private GPUImageRGBDilationFilter(String vertexShader, String fragmentShader) { - super(vertexShader, fragmentShader, vertexShader, fragmentShader); - } - - private static String getVertexShader(int radius) { - switch (radius) { - case 0: - case 1: - return VERTEX_SHADER_1; - case 2: - return VERTEX_SHADER_2; - case 3: - return VERTEX_SHADER_3; - default: - return VERTEX_SHADER_4; - } - } - - private static String getFragmentShader(int radius) { - switch (radius) { - case 0: - case 1: - return FRAGMENT_SHADER_1; - case 2: - return FRAGMENT_SHADER_2; - case 3: - return FRAGMENT_SHADER_3; - default: - return FRAGMENT_SHADER_4; - } - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRGBFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRGBFilter.java deleted file mode 100755 index f0af18c..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRGBFilter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Adjusts the individual RGB channels of an image - * red: Normalized values by which each color channel is multiplied. The range is from 0.0 up, with 1.0 as the default. - * green: - * blue: - */ -public class GPUImageRGBFilter extends GPUImageFilter { - public static final String RGB_FRAGMENT_SHADER = "" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform highp float red;\n" + - " uniform highp float green;\n" + - " uniform highp float blue;\n" + - " \n" + - " void main()\n" + - " {\n" + - " highp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " gl_FragColor = vec4(textureColor.r * red, textureColor.g * green, textureColor.b * blue, 1.0);\n" + - " }\n"; - - private int mRedLocation; - private float mRed; - private int mGreenLocation; - private float mGreen; - private int mBlueLocation; - private float mBlue; - private boolean mIsInitialized = false; - - public GPUImageRGBFilter() { - this(1.0f, 1.0f, 1.0f); - } - - public GPUImageRGBFilter(final float red, final float green, final float blue) { - super(NO_FILTER_VERTEX_SHADER, RGB_FRAGMENT_SHADER); - mRed = red; - mGreen = green; - mBlue = blue; - } - - @Override - public void onInit() { - super.onInit(); - mRedLocation = GLES20.glGetUniformLocation(getProgram(), "red"); - mGreenLocation = GLES20.glGetUniformLocation(getProgram(), "green"); - mBlueLocation = GLES20.glGetUniformLocation(getProgram(), "blue"); - mIsInitialized = true; - setRed(mRed); - setGreen(mGreen); - setBlue(mBlue); - } - - public void setRed(final float red) { - mRed = red; - if (mIsInitialized) { - setFloat(mRedLocation, mRed); - } - } - - public void setGreen(final float green) { - mGreen = green; - if (mIsInitialized) { - setFloat(mGreenLocation, mGreen); - } - } - - public void setBlue(final float blue) { - mBlue = blue; - if (mIsInitialized) { - setFloat(mBlueLocation, mBlue); - } - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRenderer.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRenderer.java deleted file mode 100755 index 9565b71..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageRenderer.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.annotation.TargetApi; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.SurfaceTexture; -import android.hardware.Camera; -import android.hardware.Camera.PreviewCallback; -import android.hardware.Camera.Size; -import android.opengl.GLES20; -import android.opengl.GLSurfaceView.Renderer; - -import jp.co.cyberagent.android.gpuimage.util.TextureRotationUtil; - -import javax.microedition.khronos.egl.EGLConfig; -import javax.microedition.khronos.opengles.GL10; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.util.LinkedList; -import java.util.Queue; - -import static jp.co.cyberagent.android.gpuimage.util.TextureRotationUtil.TEXTURE_NO_ROTATION; - -@TargetApi(11) -public class GPUImageRenderer implements Renderer, PreviewCallback { - public static final int NO_IMAGE = -1; - static final float CUBE[] = { - -1.0f, -1.0f, - 1.0f, -1.0f, - -1.0f, 1.0f, - 1.0f, 1.0f, - }; - - private GPUImageFilter mFilter; - - public final Object mSurfaceChangedWaiter = new Object(); - - private int mGLTextureId = NO_IMAGE; - private SurfaceTexture mSurfaceTexture = null; - private final FloatBuffer mGLCubeBuffer; - private final FloatBuffer mGLTextureBuffer; - private IntBuffer mGLRgbBuffer; - - private int mOutputWidth; - private int mOutputHeight; - private int mImageWidth; - private int mImageHeight; - private int mAddedPadding; - - private final Queue mRunOnDraw; - private final Queue mRunOnDrawEnd; - private Rotation mRotation; - private boolean mFlipHorizontal; - private boolean mFlipVertical; - private GPUImage.ScaleType mScaleType = GPUImage.ScaleType.CENTER_CROP; - - public GPUImageRenderer(final GPUImageFilter filter) { - mFilter = filter; - mRunOnDraw = new LinkedList(); - mRunOnDrawEnd = new LinkedList(); - - mGLCubeBuffer = ByteBuffer.allocateDirect(CUBE.length * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer(); - mGLCubeBuffer.put(CUBE).position(0); - - mGLTextureBuffer = ByteBuffer.allocateDirect(TEXTURE_NO_ROTATION.length * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer(); - setRotation(Rotation.NORMAL, false, false); - } - - @Override - public void onSurfaceCreated(final GL10 unused, final EGLConfig config) { - GLES20.glClearColor(0, 0, 0, 1); - GLES20.glDisable(GLES20.GL_DEPTH_TEST); - mFilter.init(); - } - - @Override - public void onSurfaceChanged(final GL10 gl, final int width, final int height) { - mOutputWidth = width; - mOutputHeight = height; - GLES20.glViewport(0, 0, width, height); - GLES20.glUseProgram(mFilter.getProgram()); - mFilter.onOutputSizeChanged(width, height); - adjustImageScaling(); - synchronized (mSurfaceChangedWaiter) { - mSurfaceChangedWaiter.notifyAll(); - } - } - - @Override - public void onDrawFrame(final GL10 gl) { - GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); - runAll(mRunOnDraw); - mFilter.onDraw(mGLTextureId, mGLCubeBuffer, mGLTextureBuffer); - runAll(mRunOnDrawEnd); - if (mSurfaceTexture != null) { - mSurfaceTexture.updateTexImage(); - } - } - - private void runAll(Queue queue) { - synchronized (queue) { - while (!queue.isEmpty()) { - queue.poll().run(); - } - } - } - - @Override - public void onPreviewFrame(final byte[] data, final Camera camera) { - final Size previewSize = camera.getParameters().getPreviewSize(); - if (mGLRgbBuffer == null) { - mGLRgbBuffer = IntBuffer.allocate(previewSize.width * previewSize.height); - } - if (mRunOnDraw.isEmpty()) { - runOnDraw(new Runnable() { - @Override - public void run() { - GPUImageNativeLibrary.YUVtoRBGA(data, previewSize.width, previewSize.height, - mGLRgbBuffer.array()); - mGLTextureId = OpenGlUtils.loadTexture(mGLRgbBuffer, previewSize, mGLTextureId); - camera.addCallbackBuffer(data); - - if (mImageWidth != previewSize.width) { - mImageWidth = previewSize.width; - mImageHeight = previewSize.height; - adjustImageScaling(); - } - } - }); - } - } - - public void setUpSurfaceTexture(final Camera camera) { - runOnDraw(new Runnable() { - @Override - public void run() { - int[] textures = new int[1]; - GLES20.glGenTextures(1, textures, 0); - mSurfaceTexture = new SurfaceTexture(textures[0]); - try { - camera.setPreviewTexture(mSurfaceTexture); - camera.setPreviewCallback(GPUImageRenderer.this); - camera.startPreview(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - } - - public void setFilter(final GPUImageFilter filter) { - runOnDraw(new Runnable() { - - @Override - public void run() { - final GPUImageFilter oldFilter = mFilter; - mFilter = filter; - if (oldFilter != null) { - oldFilter.destroy(); - } - mFilter.init(); - GLES20.glUseProgram(mFilter.getProgram()); - mFilter.onOutputSizeChanged(mOutputWidth, mOutputHeight); - } - }); - } - - public void deleteImage() { - runOnDraw(new Runnable() { - - @Override - public void run() { - GLES20.glDeleteTextures(1, new int[]{ - mGLTextureId - }, 0); - mGLTextureId = NO_IMAGE; - } - }); - } - - public void setImageBitmap(final Bitmap bitmap) { - setImageBitmap(bitmap, true); - } - - public void setImageBitmap(final Bitmap bitmap, final boolean recycle) { - if (bitmap == null) { - return; - } - - runOnDraw(new Runnable() { - - @Override - public void run() { - Bitmap resizedBitmap = null; - if (bitmap.getWidth() % 2 == 1) { - resizedBitmap = Bitmap.createBitmap(bitmap.getWidth() + 1, bitmap.getHeight(), - Bitmap.Config.ARGB_8888); - Canvas can = new Canvas(resizedBitmap); - can.drawARGB(0x00, 0x00, 0x00, 0x00); - can.drawBitmap(bitmap, 0, 0, null); - mAddedPadding = 1; - } else { - mAddedPadding = 0; - } - - mGLTextureId = OpenGlUtils.loadTexture( - resizedBitmap != null ? resizedBitmap : bitmap, mGLTextureId, recycle); - if (resizedBitmap != null) { - resizedBitmap.recycle(); - } - mImageWidth = bitmap.getWidth(); - mImageHeight = bitmap.getHeight(); - adjustImageScaling(); - } - }); - } - - public void setScaleType(GPUImage.ScaleType scaleType) { - mScaleType = scaleType; - } - - protected int getFrameWidth() { - return mOutputWidth; - } - - protected int getFrameHeight() { - return mOutputHeight; - } - - private void adjustImageScaling() { - float outputWidth = mOutputWidth; - float outputHeight = mOutputHeight; - if (mRotation == Rotation.ROTATION_270 || mRotation == Rotation.ROTATION_90) { - outputWidth = mOutputHeight; - outputHeight = mOutputWidth; - } - - float ratio1 = outputWidth / mImageWidth; - float ratio2 = outputHeight / mImageHeight; - float ratioMax = Math.max(ratio1, ratio2); - int imageWidthNew = Math.round(mImageWidth * ratioMax); - int imageHeightNew = Math.round(mImageHeight * ratioMax); - - float ratioWidth = imageWidthNew / outputWidth; - float ratioHeight = imageHeightNew / outputHeight; - - float[] cube = CUBE; - float[] textureCords = TextureRotationUtil.getRotation(mRotation, mFlipHorizontal, mFlipVertical); - if (mScaleType == GPUImage.ScaleType.CENTER_CROP) { - float distHorizontal = (1 - 1 / ratioWidth) / 2; - float distVertical = (1 - 1 / ratioHeight) / 2; - textureCords = new float[]{ - addDistance(textureCords[0], distHorizontal), addDistance(textureCords[1], distVertical), - addDistance(textureCords[2], distHorizontal), addDistance(textureCords[3], distVertical), - addDistance(textureCords[4], distHorizontal), addDistance(textureCords[5], distVertical), - addDistance(textureCords[6], distHorizontal), addDistance(textureCords[7], distVertical), - }; - } else { - cube = new float[]{ - CUBE[0] / ratioHeight, CUBE[1] / ratioWidth, - CUBE[2] / ratioHeight, CUBE[3] / ratioWidth, - CUBE[4] / ratioHeight, CUBE[5] / ratioWidth, - CUBE[6] / ratioHeight, CUBE[7] / ratioWidth, - }; - } - - mGLCubeBuffer.clear(); - mGLCubeBuffer.put(cube).position(0); - mGLTextureBuffer.clear(); - mGLTextureBuffer.put(textureCords).position(0); - } - - private float addDistance(float coordinate, float distance) { - return coordinate == 0.0f ? distance : 1 - distance; - } - - public void setRotationCamera(final Rotation rotation, final boolean flipHorizontal, - final boolean flipVertical) { - setRotation(rotation, flipVertical, flipHorizontal); - } - - public void setRotation(final Rotation rotation) { - mRotation = rotation; - adjustImageScaling(); - } - - public void setRotation(final Rotation rotation, - final boolean flipHorizontal, final boolean flipVertical) { - mFlipHorizontal = flipHorizontal; - mFlipVertical = flipVertical; - setRotation(rotation); - } - - public Rotation getRotation() { - return mRotation; - } - - public boolean isFlippedHorizontally() { - return mFlipHorizontal; - } - - public boolean isFlippedVertically() { - return mFlipVertical; - } - - protected void runOnDraw(final Runnable runnable) { - synchronized (mRunOnDraw) { - mRunOnDraw.add(runnable); - } - } - - protected void runOnDrawEnd(final Runnable runnable) { - synchronized (mRunOnDrawEnd) { - mRunOnDrawEnd.add(runnable); - } - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSaturationBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSaturationBlendFilter.java deleted file mode 100755 index 1c0f90d..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSaturationBlendFilter.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageSaturationBlendFilter extends GPUImageTwoInputFilter { - public static final String SATURATION_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " highp float lum(lowp vec3 c) {\n" + - " return dot(c, vec3(0.3, 0.59, 0.11));\n" + - " }\n" + - " \n" + - " lowp vec3 clipcolor(lowp vec3 c) {\n" + - " highp float l = lum(c);\n" + - " lowp float n = min(min(c.r, c.g), c.b);\n" + - " lowp float x = max(max(c.r, c.g), c.b);\n" + - " \n" + - " if (n < 0.0) {\n" + - " c.r = l + ((c.r - l) * l) / (l - n);\n" + - " c.g = l + ((c.g - l) * l) / (l - n);\n" + - " c.b = l + ((c.b - l) * l) / (l - n);\n" + - " }\n" + - " if (x > 1.0) {\n" + - " c.r = l + ((c.r - l) * (1.0 - l)) / (x - l);\n" + - " c.g = l + ((c.g - l) * (1.0 - l)) / (x - l);\n" + - " c.b = l + ((c.b - l) * (1.0 - l)) / (x - l);\n" + - " }\n" + - " \n" + - " return c;\n" + - " }\n" + - " \n" + - " lowp vec3 setlum(lowp vec3 c, highp float l) {\n" + - " highp float d = l - lum(c);\n" + - " c = c + vec3(d);\n" + - " return clipcolor(c);\n" + - " }\n" + - " \n" + - " highp float sat(lowp vec3 c) {\n" + - " lowp float n = min(min(c.r, c.g), c.b);\n" + - " lowp float x = max(max(c.r, c.g), c.b);\n" + - " return x - n;\n" + - " }\n" + - " \n" + - " lowp float mid(lowp float cmin, lowp float cmid, lowp float cmax, highp float s) {\n" + - " return ((cmid - cmin) * s) / (cmax - cmin);\n" + - " }\n" + - " \n" + - " lowp vec3 setsat(lowp vec3 c, highp float s) {\n" + - " if (c.r > c.g) {\n" + - " if (c.r > c.b) {\n" + - " if (c.g > c.b) {\n" + - " /* g is mid, b is min */\n" + - " c.g = mid(c.b, c.g, c.r, s);\n" + - " c.b = 0.0;\n" + - " } else {\n" + - " /* b is mid, g is min */\n" + - " c.b = mid(c.g, c.b, c.r, s);\n" + - " c.g = 0.0;\n" + - " }\n" + - " c.r = s;\n" + - " } else {\n" + - " /* b is max, r is mid, g is min */\n" + - " c.r = mid(c.g, c.r, c.b, s);\n" + - " c.b = s;\n" + - " c.r = 0.0;\n" + - " }\n" + - " } else if (c.r > c.b) {\n" + - " /* g is max, r is mid, b is min */\n" + - " c.r = mid(c.b, c.r, c.g, s);\n" + - " c.g = s;\n" + - " c.b = 0.0;\n" + - " } else if (c.g > c.b) {\n" + - " /* g is max, b is mid, r is min */\n" + - " c.b = mid(c.r, c.b, c.g, s);\n" + - " c.g = s;\n" + - " c.r = 0.0;\n" + - " } else if (c.b > c.g) {\n" + - " /* b is max, g is mid, r is min */\n" + - " c.g = mid(c.r, c.g, c.b, s);\n" + - " c.b = s;\n" + - " c.r = 0.0;\n" + - " } else {\n" + - " c = vec3(0.0);\n" + - " }\n" + - " return c;\n" + - " }\n" + - " \n" + - " void main()\n" + - " {\n" + - " highp vec4 baseColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " highp vec4 overlayColor = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = vec4(baseColor.rgb * (1.0 - overlayColor.a) + setlum(setsat(baseColor.rgb, sat(overlayColor.rgb)), lum(baseColor.rgb)) * overlayColor.a, baseColor.a);\n" + - " }"; - - public GPUImageSaturationBlendFilter() { - super(SATURATION_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSaturationFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSaturationFilter.java deleted file mode 100755 index 0725953..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSaturationFilter.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * saturation: The degree of saturation or desaturation to apply to the image (0.0 - 2.0, with 1.0 as the default) - */ -public class GPUImageSaturationFilter extends GPUImageFilter { - public static final String SATURATION_FRAGMENT_SHADER = "" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform lowp float saturation;\n" + - " \n" + - " // Values from \"Graphics Shaders: Theory and Practice\" by Bailey and Cunningham\n" + - " const mediump vec3 luminanceWeighting = vec3(0.2125, 0.7154, 0.0721);\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp float luminance = dot(textureColor.rgb, luminanceWeighting);\n" + - " lowp vec3 greyScaleColor = vec3(luminance);\n" + - " \n" + - " gl_FragColor = vec4(mix(greyScaleColor, textureColor.rgb, saturation), textureColor.w);\n" + - " \n" + - " }"; - - private int mSaturationLocation; - private float mSaturation; - - public GPUImageSaturationFilter() { - this(1.0f); - } - - public GPUImageSaturationFilter(final float saturation) { - super(NO_FILTER_VERTEX_SHADER, SATURATION_FRAGMENT_SHADER); - mSaturation = saturation; - } - - @Override - public void onInit() { - super.onInit(); - mSaturationLocation = GLES20.glGetUniformLocation(getProgram(), "saturation"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setSaturation(mSaturation); - } - - public void setSaturation(final float saturation) { - mSaturation = saturation; - setFloat(mSaturationLocation, mSaturation); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageScreenBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageScreenBlendFilter.java deleted file mode 100755 index 2c63a69..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageScreenBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageScreenBlendFilter extends GPUImageTwoInputFilter { - public static final String SCREEN_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " mediump vec4 whiteColor = vec4(1.0);\n" + - " gl_FragColor = whiteColor - ((whiteColor - textureColor2) * (whiteColor - textureColor));\n" + - " }"; - - public GPUImageScreenBlendFilter() { - super(SCREEN_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSepiaFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSepiaFilter.java deleted file mode 100755 index cbcf353..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSepiaFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -/** - * Applies a simple sepia effect. - */ -public class GPUImageSepiaFilter extends GPUImageColorMatrixFilter { - - public GPUImageSepiaFilter() { - this(1.0f); - } - - public GPUImageSepiaFilter(final float intensity) { - super(intensity, new float[] { - 0.3588f, 0.7044f, 0.1368f, 0.0f, - 0.2990f, 0.5870f, 0.1140f, 0.0f, - 0.2392f, 0.4696f, 0.0912f, 0.0f, - 0f, 0f, 0f, 1.0f - }); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSharpenFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSharpenFilter.java deleted file mode 100755 index 4317b66..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSharpenFilter.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Sharpens the picture.
- *
- * sharpness: from -4.0 to 4.0, with 0.0 as the normal level - */ -public class GPUImageSharpenFilter extends GPUImageFilter { - public static final String SHARPEN_VERTEX_SHADER = "" + - "attribute vec4 position;\n" + - "attribute vec4 inputTextureCoordinate;\n" + - "\n" + - "uniform float imageWidthFactor; \n" + - "uniform float imageHeightFactor; \n" + - "uniform float sharpness;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate; \n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "\n" + - "varying float centerMultiplier;\n" + - "varying float edgeMultiplier;\n" + - "\n" + - "void main()\n" + - "{\n" + - " gl_Position = position;\n" + - " \n" + - " mediump vec2 widthStep = vec2(imageWidthFactor, 0.0);\n" + - " mediump vec2 heightStep = vec2(0.0, imageHeightFactor);\n" + - " \n" + - " textureCoordinate = inputTextureCoordinate.xy;\n" + - " leftTextureCoordinate = inputTextureCoordinate.xy - widthStep;\n" + - " rightTextureCoordinate = inputTextureCoordinate.xy + widthStep;\n" + - " topTextureCoordinate = inputTextureCoordinate.xy + heightStep; \n" + - " bottomTextureCoordinate = inputTextureCoordinate.xy - heightStep;\n" + - " \n" + - " centerMultiplier = 1.0 + 4.0 * sharpness;\n" + - " edgeMultiplier = sharpness;\n" + - "}"; - - public static final String SHARPEN_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - "\n" + - "varying highp vec2 textureCoordinate;\n" + - "varying highp vec2 leftTextureCoordinate;\n" + - "varying highp vec2 rightTextureCoordinate; \n" + - "varying highp vec2 topTextureCoordinate;\n" + - "varying highp vec2 bottomTextureCoordinate;\n" + - "\n" + - "varying highp float centerMultiplier;\n" + - "varying highp float edgeMultiplier;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - " mediump vec3 textureColor = texture2D(inputImageTexture, textureCoordinate).rgb;\n" + - " mediump vec3 leftTextureColor = texture2D(inputImageTexture, leftTextureCoordinate).rgb;\n" + - " mediump vec3 rightTextureColor = texture2D(inputImageTexture, rightTextureCoordinate).rgb;\n" + - " mediump vec3 topTextureColor = texture2D(inputImageTexture, topTextureCoordinate).rgb;\n" + - " mediump vec3 bottomTextureColor = texture2D(inputImageTexture, bottomTextureCoordinate).rgb;\n" + - "\n" + - " gl_FragColor = vec4((textureColor * centerMultiplier - (leftTextureColor * edgeMultiplier + rightTextureColor * edgeMultiplier + topTextureColor * edgeMultiplier + bottomTextureColor * edgeMultiplier)), texture2D(inputImageTexture, bottomTextureCoordinate).w);\n" + - "}"; - - private int mSharpnessLocation; - private float mSharpness; - private int mImageWidthFactorLocation; - private int mImageHeightFactorLocation; - - public GPUImageSharpenFilter() { - this(0.0f); - } - - public GPUImageSharpenFilter(final float sharpness) { - super(SHARPEN_VERTEX_SHADER, SHARPEN_FRAGMENT_SHADER); - mSharpness = sharpness; - } - - @Override - public void onInit() { - super.onInit(); - mSharpnessLocation = GLES20.glGetUniformLocation(getProgram(), "sharpness"); - mImageWidthFactorLocation = GLES20.glGetUniformLocation(getProgram(), "imageWidthFactor"); - mImageHeightFactorLocation = GLES20.glGetUniformLocation(getProgram(), "imageHeightFactor"); - setSharpness(mSharpness); - } - - @Override - public void onOutputSizeChanged(final int width, final int height) { - super.onOutputSizeChanged(width, height); - setFloat(mImageWidthFactorLocation, 1.0f / width); - setFloat(mImageHeightFactorLocation, 1.0f / height); - } - - public void setSharpness(final float sharpness) { - mSharpness = sharpness; - setFloat(mSharpnessLocation, mSharpness); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSketchFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSketchFilter.java deleted file mode 100755 index dd78e70..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSketchFilter.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import java.util.ArrayList; -import java.util.List; - -/** - * Converts video to look like a sketch. - * This is just the Sobel edge detection filter with the colors inverted. - */ -public class GPUImageSketchFilter extends GPUImageFilterGroup { - public static final String SKETCH_FRAGMENT_SHADER = "" + - "precision mediump float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - "float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - "float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - "float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - "float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - "float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - "float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - "float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - "float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" + - "float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" + - "\n" + - "float mag = 1.0 - length(vec2(h, v));\n" + - "\n" + - "gl_FragColor = vec4(vec3(mag), 1.0);\n" + - "}\n"; - - public GPUImageSketchFilter() { - super(); - addFilter(new GPUImageGrayscaleFilter()); - addFilter(new GPUImage3x3TextureSamplingFilter(SKETCH_FRAGMENT_SHADER)); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSmoothToonFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSmoothToonFilter.java deleted file mode 100755 index a569ce9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSmoothToonFilter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * This uses a similar process as the GPUImageToonFilter, only it precedes the toon effect - * with a Gaussian blur to smooth out noise. - */ -public class GPUImageSmoothToonFilter extends GPUImageFilterGroup { - GPUImageGaussianBlurFilter blurFilter; - GPUImageToonFilter toonFilter; - - /** - * Setup and Tear down - */ - public GPUImageSmoothToonFilter() { - // First pass: apply a variable Gaussian blur - blurFilter = new GPUImageGaussianBlurFilter(); - addFilter(blurFilter); - - // Second pass: run the Sobel edge detection on this blurred image, along with a posterization effect - toonFilter = new GPUImageToonFilter(); - addFilter(toonFilter); - - getFilters().add(blurFilter); - - setBlurSize(0.5f); - setThreshold(0.2f); - setQuantizationLevels(10.0f); - } - - /** - * Accessors - */ - public void setTexelWidth(float value) { - toonFilter.setTexelWidth(value); - } - - public void setTexelHeight(float value) { - toonFilter.setTexelHeight(value); - } - - public void setBlurSize(float value) { - blurFilter.setBlurSize(value); - } - - public void setThreshold(float value) { - toonFilter.setThreshold(value); - } - - public void setQuantizationLevels(float value) { - toonFilter.setQuantizationLevels(value); - } - -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSobelEdgeDetection.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSobelEdgeDetection.java deleted file mode 100755 index 2a775d4..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSobelEdgeDetection.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import java.util.ArrayList; -import java.util.List; - -/** - * Applies sobel edge detection on the image. - */ -public class GPUImageSobelEdgeDetection extends GPUImageFilterGroup { - public static final String SOBEL_EDGE_DETECTION = "" + - "precision mediump float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - " float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - " float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - " float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - " float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - " float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - " float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - " float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - " float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - " float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" + - " float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" + - "\n" + - " float mag = length(vec2(h, v));\n" + - "\n" + - " gl_FragColor = vec4(vec3(mag), 1.0);\n" + - "}"; - - public GPUImageSobelEdgeDetection() { - super(); - addFilter(new GPUImageGrayscaleFilter()); - addFilter(new GPUImage3x3TextureSamplingFilter(SOBEL_EDGE_DETECTION)); - } - - public void setLineSize(final float size) { - ((GPUImage3x3TextureSamplingFilter) getFilters().get(1)).setLineSize(size); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSobelThresholdFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSobelThresholdFilter.java deleted file mode 100755 index f1dcf64..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSobelThresholdFilter.java +++ /dev/null @@ -1,74 +0,0 @@ -package jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImageSobelThresholdFilter extends - GPUImage3x3TextureSamplingFilter { - public static final String SOBEL_THRESHOLD_EDGE_DETECTION = "" + - "precision mediump float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "uniform lowp float threshold;\n" + - "\n" + - "const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" + - "\n" + - "void main()\n" + - "{\n" + - " float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - " float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - " float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - " float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - " float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - " float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - " float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - " float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - " float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" + - " float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" + - "\n" + - " float mag = 1.0 - length(vec2(h, v));\n" + - " mag = step(threshold, mag);\n" + - "\n" + - " gl_FragColor = vec4(vec3(mag), 1.0);\n" + - "}\n"; - - private int mUniformThresholdLocation; - private float mThreshold = 0.9f; - - public GPUImageSobelThresholdFilter() { - this(0.9f); - } - - public GPUImageSobelThresholdFilter(float threshold) { - super(SOBEL_THRESHOLD_EDGE_DETECTION); - mThreshold = threshold; - } - - @Override - public void onInit() { - super.onInit(); - mUniformThresholdLocation = GLES20.glGetUniformLocation(getProgram(), "threshold"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setThreshold(mThreshold); - } - - public void setThreshold(final float threshold) { - mThreshold = threshold; - setFloat(mUniformThresholdLocation, threshold); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSoftLightBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSoftLightBlendFilter.java deleted file mode 100755 index 0e1b742..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSoftLightBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageSoftLightBlendFilter extends GPUImageTwoInputFilter { - public static final String SOFT_LIGHT_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " mediump vec4 base = texture2D(inputImageTexture, textureCoordinate);\n" + - " mediump vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = base * (overlay.a * (base / base.a) + (2.0 * overlay * (1.0 - (base / base.a)))) + overlay * (1.0 - base.a) + base * (1.0 - overlay.a);\n" + - " }"; - - public GPUImageSoftLightBlendFilter() { - super(SOFT_LIGHT_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSourceOverBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSourceOverBlendFilter.java deleted file mode 100755 index fd6a7b9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSourceOverBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageSourceOverBlendFilter extends GPUImageTwoInputFilter { - public static final String SOURCE_OVER_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - " \n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - " \n" + - " gl_FragColor = mix(textureColor, textureColor2, textureColor2.a);\n" + - " }"; - - public GPUImageSourceOverBlendFilter() { - super(SOURCE_OVER_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSphereRefractionFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSphereRefractionFilter.java deleted file mode 100755 index 6314cf1..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSphereRefractionFilter.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.graphics.PointF; -import android.opengl.GLES20; - -public class GPUImageSphereRefractionFilter extends GPUImageFilter { - public static final String SPHERE_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform highp vec2 center;\n" + - "uniform highp float radius;\n" + - "uniform highp float aspectRatio;\n" + - "uniform highp float refractiveIndex;\n" + - "\n" + - "void main()\n" + - "{\n" + - "highp vec2 textureCoordinateToUse = vec2(textureCoordinate.x, (textureCoordinate.y * aspectRatio + 0.5 - 0.5 * aspectRatio));\n" + - "highp float distanceFromCenter = distance(center, textureCoordinateToUse);\n" + - "lowp float checkForPresenceWithinSphere = step(distanceFromCenter, radius);\n" + - "\n" + - "distanceFromCenter = distanceFromCenter / radius;\n" + - "\n" + - "highp float normalizedDepth = radius * sqrt(1.0 - distanceFromCenter * distanceFromCenter);\n" + - "highp vec3 sphereNormal = normalize(vec3(textureCoordinateToUse - center, normalizedDepth));\n" + - "\n" + - "highp vec3 refractedVector = refract(vec3(0.0, 0.0, -1.0), sphereNormal, refractiveIndex);\n" + - "\n" + - "gl_FragColor = texture2D(inputImageTexture, (refractedVector.xy + 1.0) * 0.5) * checkForPresenceWithinSphere; \n" + - "}\n"; - - private PointF mCenter; - private int mCenterLocation; - private float mRadius; - private int mRadiusLocation; - private float mAspectRatio; - private int mAspectRatioLocation; - private float mRefractiveIndex; - private int mRefractiveIndexLocation; - - public GPUImageSphereRefractionFilter() { - this(new PointF(0.5f, 0.5f), 0.25f, 0.71f); - } - - public GPUImageSphereRefractionFilter(PointF center, float radius, float refractiveIndex) { - super(NO_FILTER_VERTEX_SHADER, SPHERE_FRAGMENT_SHADER); - mCenter = center; - mRadius = radius; - mRefractiveIndex = refractiveIndex; - } - - @Override - public void onInit() { - super.onInit(); - mCenterLocation = GLES20.glGetUniformLocation(getProgram(), "center"); - mRadiusLocation = GLES20.glGetUniformLocation(getProgram(), "radius"); - mAspectRatioLocation = GLES20.glGetUniformLocation(getProgram(), "aspectRatio"); - mRefractiveIndexLocation = GLES20.glGetUniformLocation(getProgram(), "refractiveIndex"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setRadius(mRadius); - setCenter(mCenter); - setRefractiveIndex(mRefractiveIndex); - } - - @Override - public void onOutputSizeChanged(int width, int height) { - mAspectRatio = (float) height / width; - setAspectRatio(mAspectRatio); - super.onOutputSizeChanged(width, height); - } - - private void setAspectRatio(float aspectRatio) { - mAspectRatio = aspectRatio; - setFloat(mAspectRatioLocation, aspectRatio); - } - - /** - * The index of refraction for the sphere, with a default of 0.71 - * - * @param refractiveIndex default 0.71 - */ - public void setRefractiveIndex(float refractiveIndex) { - mRefractiveIndex = refractiveIndex; - setFloat(mRefractiveIndexLocation, refractiveIndex); - } - - /** - * The center about which to apply the distortion, with a default of (0.5, 0.5) - * - * @param center default (0.5, 0.5) - */ - public void setCenter(PointF center) { - mCenter = center; - setPoint(mCenterLocation, center); - } - - /** - * The radius of the distortion, ranging from 0.0 to 1.0, with a default of 0.25 - * - * @param radius from 0.0 to 1.0, default 0.25 - */ - public void setRadius(float radius) { - mRadius = radius; - setFloat(mRadiusLocation, radius); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSubtractBlendFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSubtractBlendFilter.java deleted file mode 100755 index 52b54ec..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSubtractBlendFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageSubtractBlendFilter extends GPUImageTwoInputFilter { - public static final String SUBTRACT_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + - " varying highp vec2 textureCoordinate2;\n" + - "\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D inputImageTexture2;\n" + - " \n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + - "\n" + - " gl_FragColor = vec4(textureColor.rgb - textureColor2.rgb, textureColor.a);\n" + - " }"; - - public GPUImageSubtractBlendFilter() { - super(SUBTRACT_BLEND_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSwirlFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSwirlFilter.java deleted file mode 100755 index d4947b9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageSwirlFilter.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.graphics.PointF; -import android.opengl.GLES20; - -/** - * Creates a swirl distortion on the image. - */ -public class GPUImageSwirlFilter extends GPUImageFilter { - public static final String SWIRL_FRAGMENT_SHADER = "" + - "varying highp vec2 textureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform highp vec2 center;\n" + - "uniform highp float radius;\n" + - "uniform highp float angle;\n" + - "\n" + - "void main()\n" + - "{\n" + - "highp vec2 textureCoordinateToUse = textureCoordinate;\n" + - "highp float dist = distance(center, textureCoordinate);\n" + - "if (dist < radius)\n" + - "{\n" + - "textureCoordinateToUse -= center;\n" + - "highp float percent = (radius - dist) / radius;\n" + - "highp float theta = percent * percent * angle * 8.0;\n" + - "highp float s = sin(theta);\n" + - "highp float c = cos(theta);\n" + - "textureCoordinateToUse = vec2(dot(textureCoordinateToUse, vec2(c, -s)), dot(textureCoordinateToUse, vec2(s, c)));\n" + - "textureCoordinateToUse += center;\n" + - "}\n" + - "\n" + - "gl_FragColor = texture2D(inputImageTexture, textureCoordinateToUse );\n" + - "\n" + - "}\n"; - - private float mAngle; - private int mAngleLocation; - private float mRadius; - private int mRadiusLocation; - private PointF mCenter; - private int mCenterLocation; - - public GPUImageSwirlFilter() { - this(0.5f, 1.0f, new PointF(0.5f, 0.5f)); - } - - public GPUImageSwirlFilter(float radius, float angle, PointF center) { - super(NO_FILTER_VERTEX_SHADER, SWIRL_FRAGMENT_SHADER); - mRadius = radius; - mAngle = angle; - mCenter = center; - } - - @Override - public void onInit() { - super.onInit(); - mAngleLocation = GLES20.glGetUniformLocation(getProgram(), "angle"); - mRadiusLocation = GLES20.glGetUniformLocation(getProgram(), "radius"); - mCenterLocation = GLES20.glGetUniformLocation(getProgram(), "center"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setRadius(mRadius); - setAngle(mAngle); - setCenter(mCenter); - } - - /** - * The radius of the distortion, ranging from 0.0 to 1.0, with a default of 0.5. - * - * @param radius from 0.0 to 1.0, default 0.5 - */ - public void setRadius(float radius) { - mRadius = radius; - setFloat(mRadiusLocation, radius); - } - - /** - * The amount of distortion to apply, with a minimum of 0.0 and a default of 1.0. - * - * @param angle minimum 0.0, default 1.0 - */ - public void setAngle(float angle) { - mAngle = angle; - setFloat(mAngleLocation, angle); - } - - /** - * The center about which to apply the distortion, with a default of (0.5, 0.5). - * - * @param center default (0.5, 0.5) - */ - public void setCenter(PointF center) { - mCenter = center; - setPoint(mCenterLocation, center); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageThresholdEdgeDetection.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageThresholdEdgeDetection.java deleted file mode 100755 index c136155..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageThresholdEdgeDetection.java +++ /dev/null @@ -1,20 +0,0 @@ -package jp.co.cyberagent.android.gpuimage; - -/** - * Applies sobel edge detection on the image. - */ -public class GPUImageThresholdEdgeDetection extends GPUImageFilterGroup { - public GPUImageThresholdEdgeDetection() { - super(); - addFilter(new GPUImageGrayscaleFilter()); - addFilter(new GPUImageSobelThresholdFilter()); - } - - public void setLineSize(final float size) { - ((GPUImage3x3TextureSamplingFilter) getFilters().get(1)).setLineSize(size); - } - - public void setThreshold(final float threshold) { - ((GPUImageSobelThresholdFilter) getFilters().get(1)).setThreshold(threshold); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageToneCurveFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageToneCurveFilter.java deleted file mode 100755 index 0f6e1d0..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageToneCurveFilter.java +++ /dev/null @@ -1,364 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.graphics.Point; -import android.graphics.PointF; -import android.opengl.GLES20; - -import java.io.*; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; - -public class GPUImageToneCurveFilter extends GPUImageFilter { - public static final String TONE_CURVE_FRAGMENT_SHADER = "" + - " varying highp vec2 textureCoordinate;\n" + - " uniform sampler2D inputImageTexture;\n" + - " uniform sampler2D toneCurveTexture;\n" + - "\n" + - " void main()\n" + - " {\n" + - " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - " lowp float redCurveValue = texture2D(toneCurveTexture, vec2(textureColor.r, 0.0)).r;\n" + - " lowp float greenCurveValue = texture2D(toneCurveTexture, vec2(textureColor.g, 0.0)).g;\n" + - " lowp float blueCurveValue = texture2D(toneCurveTexture, vec2(textureColor.b, 0.0)).b;\n" + - "\n" + - " gl_FragColor = vec4(redCurveValue, greenCurveValue, blueCurveValue, textureColor.a);\n" + - " }"; - - private int[] mToneCurveTexture = new int[]{OpenGlUtils.NO_TEXTURE}; - private int mToneCurveTextureUniformLocation; - - private PointF[] mRgbCompositeControlPoints; - private PointF[] mRedControlPoints; - private PointF[] mGreenControlPoints; - private PointF[] mBlueControlPoints; - - private ArrayList mRgbCompositeCurve; - private ArrayList mRedCurve; - private ArrayList mGreenCurve; - private ArrayList mBlueCurve; - - - public GPUImageToneCurveFilter() { - super(NO_FILTER_VERTEX_SHADER, TONE_CURVE_FRAGMENT_SHADER); - - PointF[] defaultCurvePoints = new PointF[]{new PointF(0.0f, 0.0f), new PointF(0.5f, 0.5f), new PointF(1.0f, 1.0f)}; - mRgbCompositeControlPoints = defaultCurvePoints; - mRedControlPoints = defaultCurvePoints; - mGreenControlPoints = defaultCurvePoints; - mBlueControlPoints = defaultCurvePoints; - } - - @Override - public void onInit() { - super.onInit(); - mToneCurveTextureUniformLocation = GLES20.glGetUniformLocation(getProgram(), "toneCurveTexture"); - GLES20.glActiveTexture(GLES20.GL_TEXTURE3); - GLES20.glGenTextures(1, mToneCurveTexture, 0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mToneCurveTexture[0]); - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setRgbCompositeControlPoints(mRgbCompositeControlPoints); - setRedControlPoints(mRedControlPoints); - setGreenControlPoints(mGreenControlPoints); - setBlueControlPoints(mBlueControlPoints); - } - - @Override - protected void onDrawArraysPre() { - if (mToneCurveTexture[0] != OpenGlUtils.NO_TEXTURE) { - GLES20.glActiveTexture(GLES20.GL_TEXTURE3); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mToneCurveTexture[0]); - GLES20.glUniform1i(mToneCurveTextureUniformLocation, 3); - } - } - - public void setFromCurveFileInputStream(InputStream input) { - try { - int version = readShort(input); - int totalCurves = readShort(input); - - ArrayList curves = new ArrayList(totalCurves); - float pointRate = 1.0f / 255; - - for (int i = 0; i < totalCurves; i++) { - // 2 bytes, Count of points in the curve (short integer from 2...19) - short pointCount = readShort(input); - - PointF[] points = new PointF[pointCount]; - - // point count * 4 - // Curve points. Each curve point is a pair of short integers where - // the first number is the output value (vertical coordinate on the - // Curves dialog graph) and the second is the input value. All coordinates have range 0 to 255. - for (int j = 0; j < pointCount; j++) { - short y = readShort(input); - short x = readShort(input); - - points[j] = new PointF(x * pointRate, y * pointRate); - } - - curves.add(points); - } - input.close(); - - mRgbCompositeControlPoints = curves.get(0); - mRedControlPoints = curves.get(1); - mGreenControlPoints = curves.get(2); - mBlueControlPoints = curves.get(3); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private short readShort(InputStream input) throws IOException { - return (short) (input.read() << 8 | input.read()); - } - - public void setRgbCompositeControlPoints(PointF[] points) { - mRgbCompositeControlPoints = points; - mRgbCompositeCurve = createSplineCurve(mRgbCompositeControlPoints); - updateToneCurveTexture(); - } - - public void setRedControlPoints(PointF[] points) { - mRedControlPoints = points; - mRedCurve = createSplineCurve(mRedControlPoints); - updateToneCurveTexture(); - } - - public void setGreenControlPoints(PointF[] points) { - mGreenControlPoints = points; - mGreenCurve = createSplineCurve(mGreenControlPoints); - updateToneCurveTexture(); - } - - public void setBlueControlPoints(PointF[] points) { - mBlueControlPoints = points; - mBlueCurve = createSplineCurve(mBlueControlPoints); - updateToneCurveTexture(); - } - - private void updateToneCurveTexture() { - runOnDraw(new Runnable() { - @Override - public void run() { - GLES20.glActiveTexture(GLES20.GL_TEXTURE3); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mToneCurveTexture[0]); - - if ((mRedCurve.size() >= 256) && (mGreenCurve.size() >= 256) && (mBlueCurve.size() >= 256) && (mRgbCompositeCurve.size() >= 256)) { - byte[] toneCurveByteArray = new byte[256 * 4]; - for (int currentCurveIndex = 0; currentCurveIndex < 256; currentCurveIndex++) { - // BGRA for upload to texture - toneCurveByteArray[currentCurveIndex * 4 + 2] = (byte) ((int) Math.min(Math.max(currentCurveIndex + mBlueCurve.get(currentCurveIndex) + mRgbCompositeCurve.get(currentCurveIndex), 0), 255) & 0xff); - toneCurveByteArray[currentCurveIndex * 4 + 1] = (byte) ((int) Math.min(Math.max(currentCurveIndex + mGreenCurve.get(currentCurveIndex) + mRgbCompositeCurve.get(currentCurveIndex), 0), 255) & 0xff); - toneCurveByteArray[currentCurveIndex * 4] = (byte) ((int) Math.min(Math.max(currentCurveIndex + mRedCurve.get(currentCurveIndex) + mRgbCompositeCurve.get(currentCurveIndex), 0), 255) & 0xff); - toneCurveByteArray[currentCurveIndex * 4 + 3] = (byte) (255 & 0xff); - } - - GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, 256 /*width*/, 1 /*height*/, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ByteBuffer.wrap(toneCurveByteArray)); - } -// Buffer pixels! -// GLES20.glTexImage2D(int target, -// int level, -// int internalformat, -// int width, -// int height, -// int border, -// int format, -// int type, -// java.nio.Buffer pixels); - } - }); - } - - private ArrayList createSplineCurve(PointF[] points) { - if (points == null || points.length <= 0) { - return null; - } - - // Sort the array - PointF[] pointsSorted = points.clone(); - Arrays.sort(pointsSorted, new Comparator() { - @Override - public int compare(PointF point1, PointF point2) { - if (point1.x < point2.x) { - return -1; - } else if (point1.x > point2.x) { - return 1; - } else { - return 0; - } - } - }); - - // Convert from (0, 1) to (0, 255). - Point[] convertedPoints = new Point[pointsSorted.length]; - for (int i = 0; i < points.length; i++) { - PointF point = pointsSorted[i]; - convertedPoints[i] = new Point((int) (point.x * 255), (int) (point.y * 255)); - } - - ArrayList splinePoints = createSplineCurve2(convertedPoints); - - // If we have a first point like (0.3, 0) we'll be missing some points at the beginning - // that should be 0. - Point firstSplinePoint = splinePoints.get(0); - if (firstSplinePoint.x > 0) { - for (int i = firstSplinePoint.x; i >= 0; i--) { - splinePoints.add(0, new Point(i, 0)); - } - } - - // Insert points similarly at the end, if necessary. - Point lastSplinePoint = splinePoints.get(splinePoints.size() - 1); - if (lastSplinePoint.x < 255) { - for (int i = lastSplinePoint.x + 1; i <= 255; i++) { - splinePoints.add(new Point(i, 255)); - } - } - - // Prepare the spline points. - ArrayList preparedSplinePoints = new ArrayList(splinePoints.size()); - for (Point newPoint : splinePoints) { - Point origPoint = new Point(newPoint.x, newPoint.x); - - float distance = (float) Math.sqrt(Math.pow((origPoint.x - newPoint.x), 2.0) + Math.pow((origPoint.y - newPoint.y), 2.0)); - - if (origPoint.y > newPoint.y) { - distance = -distance; - } - - preparedSplinePoints.add(distance); - } - - return preparedSplinePoints; - } - - private ArrayList createSplineCurve2(Point[] points) { - ArrayList sdA = createSecondDerivative(points); - - // Is [points count] equal to [sdA count]? -// int n = [points count]; - int n = sdA.size(); - if (n < 1) { - return null; - } - double sd[] = new double[n]; - - // From NSMutableArray to sd[n]; - for (int i = 0; i < n; i++) { - sd[i] = sdA.get(i); - } - - - ArrayList output = new ArrayList(n + 1); - - for (int i = 0; i < n - 1; i++) { - Point cur = points[i]; - Point next = points[i + 1]; - - for (int x = cur.x; x < next.x; x++) { - double t = (double) (x - cur.x) / (next.x - cur.x); - - double a = 1 - t; - double b = t; - double h = next.x - cur.x; - - double y = a * cur.y + b * next.y + (h * h / 6) * ((a * a * a - a) * sd[i] + (b * b * b - b) * sd[i + 1]); - - if (y > 255.0) { - y = 255.0; - } else if (y < 0.0) { - y = 0.0; - } - - output.add(new Point(x, (int) Math.round(y))); - } - } - - // If the last point is (255, 255) it doesn't get added. - if (output.size() == 255) { - output.add(points[points.length - 1]); - } - return output; - } - - private ArrayList createSecondDerivative(Point[] points) { - int n = points.length; - if (n <= 1) { - return null; - } - - double matrix[][] = new double[n][3]; - double result[] = new double[n]; - matrix[0][1] = 1; - // What about matrix[0][1] and matrix[0][0]? Assuming 0 for now (Brad L.) - matrix[0][0] = 0; - matrix[0][2] = 0; - - for (int i = 1; i < n - 1; i++) { - Point P1 = points[i - 1]; - Point P2 = points[i]; - Point P3 = points[i + 1]; - - matrix[i][0] = (double) (P2.x - P1.x) / 6; - matrix[i][1] = (double) (P3.x - P1.x) / 3; - matrix[i][2] = (double) (P3.x - P2.x) / 6; - result[i] = (double) (P3.y - P2.y) / (P3.x - P2.x) - (double) (P2.y - P1.y) / (P2.x - P1.x); - } - - // What about result[0] and result[n-1]? Assuming 0 for now (Brad L.) - result[0] = 0; - result[n - 1] = 0; - - matrix[n - 1][1] = 1; - // What about matrix[n-1][0] and matrix[n-1][2]? For now, assuming they are 0 (Brad L.) - matrix[n - 1][0] = 0; - matrix[n - 1][2] = 0; - - // solving pass1 (up->down) - for (int i = 1; i < n; i++) { - double k = matrix[i][0] / matrix[i - 1][1]; - matrix[i][1] -= k * matrix[i - 1][2]; - matrix[i][0] = 0; - result[i] -= k * result[i - 1]; - } - // solving pass2 (down->up) - for (int i = n - 2; i >= 0; i--) { - double k = matrix[i][2] / matrix[i + 1][1]; - matrix[i][1] -= k * matrix[i + 1][0]; - matrix[i][2] = 0; - result[i] -= k * result[i + 1]; - } - - ArrayList output = new ArrayList(n); - for (int i = 0; i < n; i++) output.add(result[i] / matrix[i][1]); - - return output; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageToonFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageToonFilter.java deleted file mode 100755 index 5148d1d..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageToonFilter.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * This uses Sobel edge detection to place a black border around objects, - * and then it quantizes the colors present in the image to give a cartoon-like quality to the image. - */ -public class GPUImageToonFilter extends GPUImage3x3TextureSamplingFilter { - public static final String TOON_FRAGMENT_SHADER = "" + - "precision highp float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "uniform highp float intensity;\n" + - "uniform highp float threshold;\n" + - "uniform highp float quantizationLevels;\n" + - "\n" + - "const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);\n" + - "\n" + - "void main()\n" + - "{\n" + - "vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + - "\n" + - "float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - "float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - "float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - "float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - "float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - "float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - "float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - "float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - "float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n" + - "float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n" + - "\n" + - "float mag = length(vec2(h, v));\n" + - "\n" + - "vec3 posterizedImageColor = floor((textureColor.rgb * quantizationLevels) + 0.5) / quantizationLevels;\n" + - "\n" + - "float thresholdTest = 1.0 - step(threshold, mag);\n" + - "\n" + - "gl_FragColor = vec4(posterizedImageColor * thresholdTest, textureColor.a);\n" + - "}\n"; - - float mThreshold; - int mThresholdLocation; - float mQuantizationLevels; - int mQuantizationLevelsLocation; - - public GPUImageToonFilter() { - this(0.2f, 10.0f); - } - - public GPUImageToonFilter(float threshold, float quantizationLevels) { - super(TOON_FRAGMENT_SHADER); - mThreshold = threshold; - mQuantizationLevels = quantizationLevels; - } - - @Override - public void onInit() { - super.onInit(); - mThresholdLocation = GLES20.glGetUniformLocation(getProgram(), "threshold"); - mQuantizationLevelsLocation = GLES20.glGetUniformLocation(getProgram(), "quantizationLevels"); - } - - @Override - public void onInitialized() { - super.onInitialized(); - setThreshold(mThreshold); - setQuantizationLevels(mQuantizationLevels); - } - - /** - * The threshold at which to apply the edges, default of 0.2. - * - * @param threshold default 0.2 - */ - public void setThreshold(final float threshold) { - mThreshold = threshold; - setFloat(mThresholdLocation, threshold); - } - - /** - * The levels of quantization for the posterization of colors within the scene, with a default of 10.0. - * - * @param quantizationLevels default 10.0 - */ - public void setQuantizationLevels(final float quantizationLevels) { - mQuantizationLevels = quantizationLevels; - setFloat(mQuantizationLevelsLocation, quantizationLevels); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoInputFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoInputFilter.java deleted file mode 100755 index afc3b86..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoInputFilter.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.FloatBuffer; - -import jp.co.cyberagent.android.gpuimage.util.TextureRotationUtil; -import android.graphics.Bitmap; -import android.opengl.GLES20; - -public class GPUImageTwoInputFilter extends GPUImageFilter { - private static final String VERTEX_SHADER = "attribute vec4 position;\n" + - "attribute vec4 inputTextureCoordinate;\n" + - "attribute vec4 inputTextureCoordinate2;\n" + - " \n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 textureCoordinate2;\n" + - " \n" + - "void main()\n" + - "{\n" + - " gl_Position = position;\n" + - " textureCoordinate = inputTextureCoordinate.xy;\n" + - " textureCoordinate2 = inputTextureCoordinate2.xy;\n" + - "}"; - - public int mFilterSecondTextureCoordinateAttribute; - public int mFilterInputTextureUniform2; - public int mFilterSourceTexture2 = OpenGlUtils.NO_TEXTURE; - private ByteBuffer mTexture2CoordinatesBuffer; - private Bitmap mBitmap; - - public GPUImageTwoInputFilter(String fragmentShader) { - this(VERTEX_SHADER, fragmentShader); - } - - public GPUImageTwoInputFilter(String vertexShader, String fragmentShader) { - super(vertexShader, fragmentShader); - setRotation(Rotation.NORMAL, false, false); - } - - @Override - public void onInit() { - super.onInit(); - - mFilterSecondTextureCoordinateAttribute = GLES20.glGetAttribLocation(getProgram(), "inputTextureCoordinate2"); - mFilterInputTextureUniform2 = GLES20.glGetUniformLocation(getProgram(), "inputImageTexture2"); // This does assume a name of "inputImageTexture2" for second input texture in the fragment shader - GLES20.glEnableVertexAttribArray(mFilterSecondTextureCoordinateAttribute); - - if (mBitmap != null&&!mBitmap.isRecycled()) { - setBitmap(mBitmap); - } - } - - public void setBitmap(final Bitmap bitmap) { - if (bitmap != null && bitmap.isRecycled()) { - return; - } - mBitmap = bitmap; - if (mBitmap == null) { - return; - } - runOnDraw(new Runnable() { - public void run() { - if (mFilterSourceTexture2 == OpenGlUtils.NO_TEXTURE) { - if (bitmap == null || bitmap.isRecycled()) { - return; - } - GLES20.glActiveTexture(GLES20.GL_TEXTURE3); - mFilterSourceTexture2 = OpenGlUtils.loadTexture(bitmap, OpenGlUtils.NO_TEXTURE, false); - } - } - }); - } - - public Bitmap getBitmap() { - return mBitmap; - } - - public void recycleBitmap() { - if (mBitmap != null && !mBitmap.isRecycled()) { - mBitmap.recycle(); - mBitmap = null; - } - } - - public void onDestroy() { - super.onDestroy(); - GLES20.glDeleteTextures(1, new int[]{ - mFilterSourceTexture2 - }, 0); - mFilterSourceTexture2 = OpenGlUtils.NO_TEXTURE; - } - - @Override - protected void onDrawArraysPre() { - GLES20.glEnableVertexAttribArray(mFilterSecondTextureCoordinateAttribute); - GLES20.glActiveTexture(GLES20.GL_TEXTURE3); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mFilterSourceTexture2); - GLES20.glUniform1i(mFilterInputTextureUniform2, 3); - - mTexture2CoordinatesBuffer.position(0); - GLES20.glVertexAttribPointer(mFilterSecondTextureCoordinateAttribute, 2, GLES20.GL_FLOAT, false, 0, mTexture2CoordinatesBuffer); - } - - public void setRotation(final Rotation rotation, final boolean flipHorizontal, final boolean flipVertical) { - float[] buffer = TextureRotationUtil.getRotation(rotation, flipHorizontal, flipVertical); - - ByteBuffer bBuffer = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()); - FloatBuffer fBuffer = bBuffer.asFloatBuffer(); - fBuffer.put(buffer); - fBuffer.flip(); - - mTexture2CoordinatesBuffer = bBuffer; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoPassFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoPassFilter.java deleted file mode 100755 index bf3fbf1..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoPassFilter.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageTwoPassFilter extends GPUImageFilterGroup { - public GPUImageTwoPassFilter(String firstVertexShader, String firstFragmentShader, - String secondVertexShader, String secondFragmentShader) { - super(null); - addFilter(new GPUImageFilter(firstVertexShader, firstFragmentShader)); - addFilter(new GPUImageFilter(secondVertexShader, secondFragmentShader)); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoPassTextureSamplingFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoPassTextureSamplingFilter.java deleted file mode 100755 index 19c0365..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageTwoPassTextureSamplingFilter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -public class GPUImageTwoPassTextureSamplingFilter extends GPUImageTwoPassFilter { - public GPUImageTwoPassTextureSamplingFilter(String firstVertexShader, String firstFragmentShader, - String secondVertexShader, String secondFragmentShader) { - super(firstVertexShader, firstFragmentShader, - secondVertexShader, secondFragmentShader); - } - - @Override - public void onInit() { - super.onInit(); - initTexelOffsets(); - } - - protected void initTexelOffsets() { - float ratio = getHorizontalTexelOffsetRatio(); - GPUImageFilter filter = mFilters.get(0); - int texelWidthOffsetLocation = GLES20.glGetUniformLocation(filter.getProgram(), "texelWidthOffset"); - int texelHeightOffsetLocation = GLES20.glGetUniformLocation(filter.getProgram(), "texelHeightOffset"); - filter.setFloat(texelWidthOffsetLocation, ratio / mOutputWidth); - filter.setFloat(texelHeightOffsetLocation, 0); - - ratio = getVerticalTexelOffsetRatio(); - filter = mFilters.get(1); - texelWidthOffsetLocation = GLES20.glGetUniformLocation(filter.getProgram(), "texelWidthOffset"); - texelHeightOffsetLocation = GLES20.glGetUniformLocation(filter.getProgram(), "texelHeightOffset"); - filter.setFloat(texelWidthOffsetLocation, 0); - filter.setFloat(texelHeightOffsetLocation, ratio / mOutputHeight); - } - - @Override - public void onOutputSizeChanged(int width, int height) { - super.onOutputSizeChanged(width, height); - initTexelOffsets(); - } - - public float getVerticalTexelOffsetRatio() { - return 1f; - } - - public float getHorizontalTexelOffsetRatio() { - return 1f; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageView.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageView.java deleted file mode 100755 index ff32e5d..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageView.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.media.MediaScannerConnection; -import android.net.Uri; -import android.opengl.GLES20; -import android.opengl.GLSurfaceView; -import android.os.*; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.ViewTreeObserver; -import android.widget.FrameLayout; -import android.widget.ProgressBar; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.nio.IntBuffer; -import java.util.concurrent.Semaphore; - -public class GPUImageView extends FrameLayout { - - private GLSurfaceView mGLSurfaceView; - private GPUImage mGPUImage; - private GPUImageFilter mFilter; - public Size mForceSize = null; - private float mRatio = 0.0f; - - public GPUImageView(Context context) { - super(context); - init(context, null); - } - - public GPUImageView(Context context, AttributeSet attrs) { - super(context, attrs); - init(context, attrs); - } - - private void init(Context context, AttributeSet attrs) { - mGLSurfaceView = new GPUImageGLSurfaceView(context, attrs); - addView(mGLSurfaceView); - mGPUImage = new GPUImage(getContext()); - mGPUImage.setGLSurfaceView(mGLSurfaceView); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - if (mRatio != 0.0f) { - int width = MeasureSpec.getSize(widthMeasureSpec); - int height = MeasureSpec.getSize(heightMeasureSpec); - - int newHeight; - int newWidth; - if (width / mRatio < height) { - newWidth = width; - newHeight = Math.round(width / mRatio); - } else { - newHeight = height; - newWidth = Math.round(height * mRatio); - } - - int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY); - int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY); - super.onMeasure(newWidthSpec, newHeightSpec); - } else { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - } - - /** - * Retrieve the GPUImage instance used by this view. - * - * @return used GPUImage instance - */ - public GPUImage getGPUImage() { - return mGPUImage; - } - - // TODO Should be an xml attribute. But then GPUImage can not be distributed as .jar anymore. - public void setRatio(float ratio) { - mRatio = ratio; - mGLSurfaceView.requestLayout(); - mGPUImage.deleteImage(); - } - - /** - * Set the scale type of GPUImage. - * - * @param scaleType the new ScaleType - */ - public void setScaleType(GPUImage.ScaleType scaleType) { - mGPUImage.setScaleType(scaleType); - } - - /** - * Sets the rotation of the displayed image. - * - * @param rotation new rotation - */ - public void setRotation(Rotation rotation) { - mGPUImage.setRotation(rotation); - requestRender(); - } - - /** - * Set the filter to be applied on the image. - * - * @param filter Filter that should be applied on the image. - */ - public void setFilter(GPUImageFilter filter) { - mFilter = filter; - mGPUImage.setFilter(filter); - requestRender(); - } - - /** - * Get the current applied filter. - * - * @return the current filter - */ - public GPUImageFilter getFilter() { - return mFilter; - } - - /** - * Sets the image on which the filter should be applied. - * - * @param bitmap the new image - */ - public void setImage(final Bitmap bitmap) { - mGPUImage.setImage(bitmap); - } - - /** - * Sets the image on which the filter should be applied from a Uri. - * - * @param uri the uri of the new image - */ - public void setImage(final Uri uri) { - mGPUImage.setImage(uri); - } - - /** - * Sets the image on which the filter should be applied from a File. - * - * @param file the file of the new image - */ - public void setImage(final File file) { - mGPUImage.setImage(file); - } - - public void requestRender() { - mGLSurfaceView.requestRender(); - } - - /** - * Save current image with applied filter to Pictures. It will be stored on - * the default Picture folder on the phone below the given folderName and - * fileName.
- * This method is async and will notify when the image was saved through the - * listener. - * - * @param folderName the folder name - * @param fileName the file name - * @param listener the listener - */ - public void saveToPictures(final String folderName, final String fileName, - final OnPictureSavedListener listener) { - new SaveTask(folderName, fileName, listener).execute(); - } - - /** - * Save current image with applied filter to Pictures. It will be stored on - * the default Picture folder on the phone below the given folderName and - * fileName.
- * This method is async and will notify when the image was saved through the - * listener. - * - * @param folderName the folder name - * @param fileName the file name - * @param width requested output width - * @param height requested output height - * @param listener the listener - */ - public void saveToPictures(final String folderName, final String fileName, - int width, int height, - final OnPictureSavedListener listener) { - new SaveTask(folderName, fileName, width, height, listener).execute(); - } - - /** - * Retrieve current image with filter applied and given size as Bitmap. - * - * @param width requested Bitmap width - * @param height requested Bitmap height - * @return Bitmap of picture with given size - * @throws InterruptedException - */ - public Bitmap capture(final int width, final int height) throws InterruptedException { - // This method needs to run on a background thread because it will take a longer time - if (Looper.myLooper() == Looper.getMainLooper()) { - throw new IllegalStateException("Do not call this method from the UI thread!"); - } - - mForceSize = new Size(width, height); - - final Semaphore waiter = new Semaphore(0); - - // Layout with new size - getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { - getViewTreeObserver().removeGlobalOnLayoutListener(this); - } else { - getViewTreeObserver().removeOnGlobalLayoutListener(this); - } - waiter.release(); - } - }); - post(new Runnable() { - @Override - public void run() { - // Show loading - addView(new LoadingView(getContext())); - - mGLSurfaceView.requestLayout(); - } - }); - waiter.acquire(); - - // Run one render pass - mGPUImage.runOnGLThread(new Runnable() { - @Override - public void run() { - waiter.release(); - } - }); - requestRender(); - waiter.acquire(); - Bitmap bitmap = capture(); - - - mForceSize = null; - post(new Runnable() { - @Override - public void run() { - mGLSurfaceView.requestLayout(); - } - }); - requestRender(); - - postDelayed(new Runnable() { - @Override - public void run() { - // Remove loading view - removeViewAt(1); - } - }, 300); - - return bitmap; - } - - /** - * Capture the current image with the size as it is displayed and retrieve it as Bitmap. - * @return current output as Bitmap - * @throws InterruptedException - */ - public Bitmap capture() throws InterruptedException { - final Semaphore waiter = new Semaphore(0); - - final int width = mGLSurfaceView.getMeasuredWidth(); - final int height = mGLSurfaceView.getMeasuredHeight(); - - // Take picture on OpenGL thread - final int[] pixelMirroredArray = new int[width * height]; - mGPUImage.runOnGLThread(new Runnable() { - @Override - public void run() { - final IntBuffer pixelBuffer = IntBuffer.allocate(width * height); - GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixelBuffer); - int[] pixelArray = pixelBuffer.array(); - - // Convert upside down mirror-reversed image to right-side up normal image. - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j++) { - pixelMirroredArray[(height - i - 1) * width + j] = pixelArray[i * width + j]; - } - } - waiter.release(); - } - }); - requestRender(); - waiter.acquire(); - - Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - bitmap.copyPixelsFromBuffer(IntBuffer.wrap(pixelMirroredArray)); - return bitmap; - } - - /** - * Pauses the GLSurfaceView. - */ - public void onPause() { - mGLSurfaceView.onPause(); - } - - /** - * Resumes the GLSurfaceView. - */ - public void onResume() { - mGLSurfaceView.onResume(); - } - - public static class Size { - int width; - int height; - - public Size(int width, int height) { - this.width = width; - this.height = height; - } - } - - private class GPUImageGLSurfaceView extends GLSurfaceView { - public GPUImageGLSurfaceView(Context context) { - super(context); - } - - public GPUImageGLSurfaceView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - if (mForceSize != null) { - super.onMeasure(MeasureSpec.makeMeasureSpec(mForceSize.width, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(mForceSize.height, MeasureSpec.EXACTLY)); - } else { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - } - } - - private class LoadingView extends FrameLayout { - public LoadingView(Context context) { - super(context); - init(); - } - - public LoadingView(Context context, AttributeSet attrs) { - super(context, attrs); - init(); - } - - public LoadingView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(); - } - - private void init() { - ProgressBar view = new ProgressBar(getContext()); - view.setLayoutParams( - new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER)); - addView(view); - setBackgroundColor(Color.BLACK); - } - } - - private class SaveTask extends AsyncTask { - private final String mFolderName; - private final String mFileName; - private final int mWidth; - private final int mHeight; - private final OnPictureSavedListener mListener; - private final Handler mHandler; - - public SaveTask(final String folderName, final String fileName, - final OnPictureSavedListener listener) { - this(folderName, fileName, 0, 0, listener); - } - - public SaveTask(final String folderName, final String fileName, int width, int height, - final OnPictureSavedListener listener) { - mFolderName = folderName; - mFileName = fileName; - mWidth = width; - mHeight = height; - mListener = listener; - mHandler = new Handler(); - } - - @Override - protected Void doInBackground(final Void... params) { - try { - Bitmap result = mWidth != 0 ? capture(mWidth, mHeight) : capture(); - saveImage(mFolderName, mFileName, result); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } - - private void saveImage(final String folderName, final String fileName, final Bitmap image) { - File path = Environment - .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); - File file = new File(path, folderName + "/" + fileName); - try { - file.getParentFile().mkdirs(); - image.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(file)); - MediaScannerConnection.scanFile(getContext(), - new String[]{ - file.toString() - }, null, - new MediaScannerConnection.OnScanCompletedListener() { - @Override - public void onScanCompleted(final String path, final Uri uri) { - if (mListener != null) { - mHandler.post(new Runnable() { - - @Override - public void run() { - mListener.onPictureSaved(uri); - } - }); - } - } - }); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - } - - public interface OnPictureSavedListener { - void onPictureSaved(Uri uri); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageVignetteFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageVignetteFilter.java deleted file mode 100755 index 439e8bd..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageVignetteFilter.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.graphics.PointF; -import android.opengl.GLES20; - -/** - * Performs a vignetting effect, fading out the image at the edges - * x: - * y: The directional intensity of the vignetting, with a default of x = 0.75, y = 0.5 - */ -public class GPUImageVignetteFilter extends GPUImageFilter { - public static final String VIGNETTING_FRAGMENT_SHADER = "" + - " uniform sampler2D inputImageTexture;\n" + - " varying highp vec2 textureCoordinate;\n" + - " \n" + - " uniform lowp vec2 vignetteCenter;\n" + - " uniform lowp vec3 vignetteColor;\n" + - " uniform highp float vignetteStart;\n" + - " uniform highp float vignetteEnd;\n" + - " \n" + - " void main()\n" + - " {\n" + - " /*\n" + - " lowp vec3 rgb = texture2D(inputImageTexture, textureCoordinate).rgb;\n" + - " lowp float d = distance(textureCoordinate, vec2(0.5,0.5));\n" + - " rgb *= (1.0 - smoothstep(vignetteStart, vignetteEnd, d));\n" + - " gl_FragColor = vec4(vec3(rgb),1.0);\n" + - " */\n" + - " \n" + - " lowp vec3 rgb = texture2D(inputImageTexture, textureCoordinate).rgb;\n" + - " lowp float d = distance(textureCoordinate, vec2(vignetteCenter.x, vignetteCenter.y));\n" + - " lowp float percent = smoothstep(vignetteStart, vignetteEnd, d);\n" + - " gl_FragColor = vec4(mix(rgb.x, vignetteColor.x, percent), mix(rgb.y, vignetteColor.y, percent), mix(rgb.z, vignetteColor.z, percent), 1.0);\n" + - " }"; - - private int mVignetteCenterLocation; - private PointF mVignetteCenter; - private int mVignetteColorLocation; - private float[] mVignetteColor; - private int mVignetteStartLocation; - private float mVignetteStart; - private int mVignetteEndLocation; - private float mVignetteEnd; - - public GPUImageVignetteFilter() { - this(new PointF(), new float[] {0.0f, 0.0f, 0.0f}, 0.3f, 0.75f); - } - - public GPUImageVignetteFilter(final PointF vignetteCenter, final float[] vignetteColor, final float vignetteStart, final float vignetteEnd) { - super(NO_FILTER_VERTEX_SHADER, VIGNETTING_FRAGMENT_SHADER); - mVignetteCenter = vignetteCenter; - mVignetteColor = vignetteColor; - mVignetteStart = vignetteStart; - mVignetteEnd = vignetteEnd; - - } - - @Override - public void onInit() { - super.onInit(); - mVignetteCenterLocation = GLES20.glGetUniformLocation(getProgram(), "vignetteCenter"); - mVignetteColorLocation = GLES20.glGetUniformLocation(getProgram(), "vignetteColor"); - mVignetteStartLocation = GLES20.glGetUniformLocation(getProgram(), "vignetteStart"); - mVignetteEndLocation = GLES20.glGetUniformLocation(getProgram(), "vignetteEnd"); - - setVignetteCenter(mVignetteCenter); - setVignetteColor(mVignetteColor); - setVignetteStart(mVignetteStart); - setVignetteEnd(mVignetteEnd); - } - - - public void setVignetteCenter(final PointF vignetteCenter) { - mVignetteCenter = vignetteCenter; - setPoint(mVignetteCenterLocation, mVignetteCenter); - } - - public void setVignetteColor(final float[] vignetteColor) { - mVignetteColor = vignetteColor; - setFloatVec3(mVignetteColorLocation, mVignetteColor); - } - - public void setVignetteStart(final float vignetteStart) { - mVignetteStart = vignetteStart; - setFloat(mVignetteStartLocation, mVignetteStart); - } - - public void setVignetteEnd(final float vignetteEnd) { - mVignetteEnd = vignetteEnd; - setFloat(mVignetteEndLocation, mVignetteEnd); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageWeakPixelInclusionFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageWeakPixelInclusionFilter.java deleted file mode 100755 index 3e1b8f0..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageWeakPixelInclusionFilter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public class GPUImageWeakPixelInclusionFilter extends GPUImage3x3TextureSamplingFilter { - public static final String WEAKPIXEL_FRAGMENT_SHADER = "" + - "precision lowp float;\n" + - "\n" + - "varying vec2 textureCoordinate;\n" + - "varying vec2 leftTextureCoordinate;\n" + - "varying vec2 rightTextureCoordinate;\n" + - "\n" + - "varying vec2 topTextureCoordinate;\n" + - "varying vec2 topLeftTextureCoordinate;\n" + - "varying vec2 topRightTextureCoordinate;\n" + - "\n" + - "varying vec2 bottomTextureCoordinate;\n" + - "varying vec2 bottomLeftTextureCoordinate;\n" + - "varying vec2 bottomRightTextureCoordinate;\n" + - "\n" + - "uniform sampler2D inputImageTexture;\n" + - "\n" + - "void main()\n" + - "{\n" + - "float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;\n" + - "float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;\n" + - "float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;\n" + - "float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;\n" + - "float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;\n" + - "float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;\n" + - "float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;\n" + - "float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;\n" + - "float centerIntensity = texture2D(inputImageTexture, textureCoordinate).r;\n" + - "\n" + - "float pixelIntensitySum = bottomLeftIntensity + topRightIntensity + topLeftIntensity + bottomRightIntensity + leftIntensity + rightIntensity + bottomIntensity + topIntensity + centerIntensity;\n" + - "float sumTest = step(1.5, pixelIntensitySum);\n" + - "float pixelTest = step(0.01, centerIntensity);\n" + - "\n" + - "gl_FragColor = vec4(vec3(sumTest * pixelTest), 1.0);\n" + - "}\n"; - - public GPUImageWeakPixelInclusionFilter() { - super(WEAKPIXEL_FRAGMENT_SHADER); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageWhiteBalanceFilter.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageWhiteBalanceFilter.java deleted file mode 100755 index 1818da9..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/GPUImageWhiteBalanceFilter.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import android.opengl.GLES20; - -/** - * Adjusts the white balance of incoming image.
- *
- * temperature: - * tint: - */ -public class GPUImageWhiteBalanceFilter extends GPUImageFilter { - public static final String WHITE_BALANCE_FRAGMENT_SHADER = "" + - "uniform sampler2D inputImageTexture;\n" + - "varying highp vec2 textureCoordinate;\n" + - " \n" + - "uniform lowp float temperature;\n" + - "uniform lowp float tint;\n" + - "\n" + - "const lowp vec3 warmFilter = vec3(0.93, 0.54, 0.0);\n" + - "\n" + - "const mediump mat3 RGBtoYIQ = mat3(0.299, 0.587, 0.114, 0.596, -0.274, -0.322, 0.212, -0.523, 0.311);\n" + - "const mediump mat3 YIQtoRGB = mat3(1.0, 0.956, 0.621, 1.0, -0.272, -0.647, 1.0, -1.105, 1.702);\n" + - "\n" + - "void main()\n" + - "{\n" + - " lowp vec4 source = texture2D(inputImageTexture, textureCoordinate);\n" + - " \n" + - " mediump vec3 yiq = RGBtoYIQ * source.rgb; //adjusting tint\n" + - " yiq.b = clamp(yiq.b + tint*0.5226*0.1, -0.5226, 0.5226);\n" + - " lowp vec3 rgb = YIQtoRGB * yiq;\n" + - "\n" + - " lowp vec3 processed = vec3(\n" + - " (rgb.r < 0.5 ? (2.0 * rgb.r * warmFilter.r) : (1.0 - 2.0 * (1.0 - rgb.r) * (1.0 - warmFilter.r))), //adjusting temperature\n" + - " (rgb.g < 0.5 ? (2.0 * rgb.g * warmFilter.g) : (1.0 - 2.0 * (1.0 - rgb.g) * (1.0 - warmFilter.g))), \n" + - " (rgb.b < 0.5 ? (2.0 * rgb.b * warmFilter.b) : (1.0 - 2.0 * (1.0 - rgb.b) * (1.0 - warmFilter.b))));\n" + - "\n" + - " gl_FragColor = vec4(mix(rgb, processed, temperature), source.a);\n" + - "}"; - - private int mTemperatureLocation; - private float mTemperature; - private int mTintLocation; - private float mTint; - - public GPUImageWhiteBalanceFilter() { - this(5000.0f, 0.0f); - } - - public GPUImageWhiteBalanceFilter(final float temperature, final float tint) { - super(NO_FILTER_VERTEX_SHADER, WHITE_BALANCE_FRAGMENT_SHADER); - mTemperature = temperature; - mTint = tint; - } - - @Override - public void onInit() { - super.onInit(); - mTemperatureLocation = GLES20.glGetUniformLocation(getProgram(), "temperature"); - mTintLocation = GLES20.glGetUniformLocation(getProgram(), "tint"); - - setTemperature(mTemperature); - setTint(mTint); - } - - - public void setTemperature(final float temperature) { - mTemperature = temperature; - setFloat(mTemperatureLocation, mTemperature < 5000 ? (float)(0.0004 * (mTemperature-5000.0)) : (float)(0.00006 * (mTemperature-5000.0))); - } - - public void setTint(final float tint) { - mTint = tint; - setFloat(mTintLocation, (float)(mTint/100.0)); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/OpenGlUtils.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/OpenGlUtils.java deleted file mode 100755 index e858970..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/OpenGlUtils.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -import java.nio.IntBuffer; - -import android.graphics.Bitmap; -import android.graphics.Bitmap.Config; -import android.hardware.Camera.Size; -import android.opengl.GLES20; -import android.opengl.GLUtils; -import android.util.Log; - -public class OpenGlUtils { - public static final int NO_TEXTURE = -1; - - public static int loadTexture(final Bitmap img, final int usedTexId) { - return loadTexture(img, usedTexId, true); - } - - public static int loadTexture(final Bitmap img, final int usedTexId, final boolean recycle) { - int textures[] = new int[1]; - if (usedTexId == NO_TEXTURE) { - GLES20.glGenTextures(1, textures, 0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); - - GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, img, 0); - } else { - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, usedTexId); - GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, img); - textures[0] = usedTexId; - } - if (recycle) { - img.recycle(); - } - return textures[0]; - } - - public static int loadTexture(final IntBuffer data, final Size size, final int usedTexId) { - int textures[] = new int[1]; - if (usedTexId == NO_TEXTURE) { - GLES20.glGenTextures(1, textures, 0); - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, - GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); - GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, size.width, size.height, - 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, data); - } else { - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, usedTexId); - GLES20.glTexSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, size.width, - size.height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, data); - textures[0] = usedTexId; - } - return textures[0]; - } - - public static int loadTextureAsBitmap(final IntBuffer data, final Size size, final int usedTexId) { - Bitmap bitmap = Bitmap - .createBitmap(data.array(), size.width, size.height, Config.ARGB_8888); - return loadTexture(bitmap, usedTexId); - } - - public static int loadShader(final String strSource, final int iType) { - int[] compiled = new int[1]; - int iShader = GLES20.glCreateShader(iType); - GLES20.glShaderSource(iShader, strSource); - GLES20.glCompileShader(iShader); - GLES20.glGetShaderiv(iShader, GLES20.GL_COMPILE_STATUS, compiled, 0); - if (compiled[0] == 0) { - Log.d("Load Shader Failed", "Compilation\n" + GLES20.glGetShaderInfoLog(iShader)); - return 0; - } - return iShader; - } - - public static int loadProgram(final String strVSource, final String strFSource) { - int iVShader; - int iFShader; - int iProgId; - int[] link = new int[1]; - iVShader = loadShader(strVSource, GLES20.GL_VERTEX_SHADER); - if (iVShader == 0) { - Log.d("Load Program", "Vertex Shader Failed"); - return 0; - } - iFShader = loadShader(strFSource, GLES20.GL_FRAGMENT_SHADER); - if (iFShader == 0) { - Log.d("Load Program", "Fragment Shader Failed"); - return 0; - } - - iProgId = GLES20.glCreateProgram(); - - GLES20.glAttachShader(iProgId, iVShader); - GLES20.glAttachShader(iProgId, iFShader); - - GLES20.glLinkProgram(iProgId); - - GLES20.glGetProgramiv(iProgId, GLES20.GL_LINK_STATUS, link, 0); - if (link[0] <= 0) { - Log.d("Load Program", "Linking Failed"); - return 0; - } - GLES20.glDeleteShader(iVShader); - GLES20.glDeleteShader(iFShader); - return iProgId; - } - - public static float rnd(final float min, final float max) { - float fRandNum = (float) Math.random(); - return min + (max - min) * fRandNum; - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/PixelBuffer.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/PixelBuffer.java deleted file mode 100755 index 45317a1..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/PixelBuffer.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * Copyright (C) 2010 jsemler - * - * Original publication without License - * http://www.anddev.org/android-2d-3d-graphics-opengl-tutorials-f2/possible-to-do-opengl-off-screen-rendering-in-android-t13232.html#p41662 - */ - -package jp.co.cyberagent.android.gpuimage; - -import static javax.microedition.khronos.egl.EGL10.EGL_ALPHA_SIZE; -import static javax.microedition.khronos.egl.EGL10.EGL_BLUE_SIZE; -import static javax.microedition.khronos.egl.EGL10.EGL_DEFAULT_DISPLAY; -import static javax.microedition.khronos.egl.EGL10.EGL_DEPTH_SIZE; -import static javax.microedition.khronos.egl.EGL10.EGL_GREEN_SIZE; -import static javax.microedition.khronos.egl.EGL10.EGL_HEIGHT; -import static javax.microedition.khronos.egl.EGL10.EGL_NONE; -import static javax.microedition.khronos.egl.EGL10.EGL_NO_CONTEXT; -import static javax.microedition.khronos.egl.EGL10.EGL_RED_SIZE; -import static javax.microedition.khronos.egl.EGL10.EGL_STENCIL_SIZE; -import static javax.microedition.khronos.egl.EGL10.EGL_WIDTH; -import static javax.microedition.khronos.opengles.GL10.GL_RGBA; -import static javax.microedition.khronos.opengles.GL10.GL_UNSIGNED_BYTE; - -import java.nio.IntBuffer; - -import javax.microedition.khronos.egl.EGL10; -import javax.microedition.khronos.egl.EGLConfig; -import javax.microedition.khronos.egl.EGLContext; -import javax.microedition.khronos.egl.EGLDisplay; -import javax.microedition.khronos.egl.EGLSurface; -import javax.microedition.khronos.opengles.GL10; - -import android.graphics.Bitmap; -import android.opengl.GLSurfaceView; -import android.util.Log; - -public class PixelBuffer { - final static String TAG = "PixelBuffer"; - final static boolean LIST_CONFIGS = false; - - GLSurfaceView.Renderer mRenderer; // borrow this interface - int mWidth, mHeight; - Bitmap mBitmap; - - EGL10 mEGL; - EGLDisplay mEGLDisplay; - EGLConfig[] mEGLConfigs; - EGLConfig mEGLConfig; - EGLContext mEGLContext; - EGLSurface mEGLSurface; - GL10 mGL; - - String mThreadOwner; - - public PixelBuffer(final int width, final int height) { - mWidth = width; - mHeight = height; - - int[] version = new int[2]; - int[] attribList = new int[] { - EGL_WIDTH, mWidth, - EGL_HEIGHT, mHeight, - EGL_NONE - }; - - // No error checking performed, minimum required code to elucidate logic - mEGL = (EGL10) EGLContext.getEGL(); - mEGLDisplay = mEGL.eglGetDisplay(EGL_DEFAULT_DISPLAY); - mEGL.eglInitialize(mEGLDisplay, version); - mEGLConfig = chooseConfig(); // Choosing a config is a little more - // complicated - - // mEGLContext = mEGL.eglCreateContext(mEGLDisplay, mEGLConfig, - // EGL_NO_CONTEXT, null); - int EGL_CONTEXT_CLIENT_VERSION = 0x3098; - int[] attrib_list = { - EGL_CONTEXT_CLIENT_VERSION, 2, - EGL10.EGL_NONE - }; - mEGLContext = mEGL.eglCreateContext(mEGLDisplay, mEGLConfig, EGL_NO_CONTEXT, attrib_list); - - mEGLSurface = mEGL.eglCreatePbufferSurface(mEGLDisplay, mEGLConfig, attribList); - mEGL.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext); - - mGL = (GL10) mEGLContext.getGL(); - - // Record thread owner of OpenGL context - mThreadOwner = Thread.currentThread().getName(); - } - - public void setRenderer(final GLSurfaceView.Renderer renderer) { - mRenderer = renderer; - - // Does this thread own the OpenGL context? - if (!Thread.currentThread().getName().equals(mThreadOwner)) { - Log.e(TAG, "setRenderer: This thread does not own the OpenGL context."); - return; - } - - // Call the renderer initialization routines - mRenderer.onSurfaceCreated(mGL, mEGLConfig); - mRenderer.onSurfaceChanged(mGL, mWidth, mHeight); - } - - public Bitmap getBitmap() { - // Do we have a renderer? - if (mRenderer == null) { - Log.e(TAG, "getBitmap: Renderer was not set."); - return null; - } - - // Does this thread own the OpenGL context? - if (!Thread.currentThread().getName().equals(mThreadOwner)) { - Log.e(TAG, "getBitmap: This thread does not own the OpenGL context."); - return null; - } - - // Call the renderer draw routine (it seems that some filters do not - // work if this is only called once) - mRenderer.onDrawFrame(mGL); - mRenderer.onDrawFrame(mGL); - convertToBitmap(); - return mBitmap; - } - - public void destroy() { - mRenderer.onDrawFrame(mGL); - mRenderer.onDrawFrame(mGL); - mEGL.eglMakeCurrent(mEGLDisplay, EGL10.EGL_NO_SURFACE, - EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); - - mEGL.eglDestroySurface(mEGLDisplay, mEGLSurface); - mEGL.eglDestroyContext(mEGLDisplay, mEGLContext); - mEGL.eglTerminate(mEGLDisplay); - } - - private EGLConfig chooseConfig() { - int[] attribList = new int[] { - EGL_DEPTH_SIZE, 0, - EGL_STENCIL_SIZE, 0, - EGL_RED_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, - EGL10.EGL_RENDERABLE_TYPE, 4, - EGL_NONE - }; - - // No error checking performed, minimum required code to elucidate logic - // Expand on this logic to be more selective in choosing a configuration - int[] numConfig = new int[1]; - mEGL.eglChooseConfig(mEGLDisplay, attribList, null, 0, numConfig); - int configSize = numConfig[0]; - mEGLConfigs = new EGLConfig[configSize]; - mEGL.eglChooseConfig(mEGLDisplay, attribList, mEGLConfigs, configSize, numConfig); - - if (LIST_CONFIGS) { - listConfig(); - } - - return mEGLConfigs[0]; // Best match is probably the first configuration - } - - private void listConfig() { - Log.i(TAG, "Config List {"); - - for (EGLConfig config : mEGLConfigs) { - int d, s, r, g, b, a; - - // Expand on this logic to dump other attributes - d = getConfigAttrib(config, EGL_DEPTH_SIZE); - s = getConfigAttrib(config, EGL_STENCIL_SIZE); - r = getConfigAttrib(config, EGL_RED_SIZE); - g = getConfigAttrib(config, EGL_GREEN_SIZE); - b = getConfigAttrib(config, EGL_BLUE_SIZE); - a = getConfigAttrib(config, EGL_ALPHA_SIZE); - Log.i(TAG, " = <" + d + "," + s + "," + - r + "," + g + "," + b + "," + a + ">"); - } - - Log.i(TAG, "}"); - } - - private int getConfigAttrib(final EGLConfig config, final int attribute) { - int[] value = new int[1]; - return mEGL.eglGetConfigAttrib(mEGLDisplay, config, - attribute, value) ? value[0] : 0; - } - - private void convertToBitmap() { - int[] iat = new int[mWidth * mHeight]; - IntBuffer ib = IntBuffer.allocate(mWidth * mHeight); - mGL.glReadPixels(0, 0, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, ib); - int[] ia = ib.array(); - - // Convert upside down mirror-reversed image to right-side up normal - // image. - for (int i = 0; i < mHeight; i++) { - for (int j = 0; j < mWidth; j++) { - iat[(mHeight - i - 1) * mWidth + j] = ia[i * mWidth + j]; - } - } - - - mBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); - mBitmap.copyPixelsFromBuffer(IntBuffer.wrap(iat)); - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/Rotation.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/Rotation.java deleted file mode 100755 index bd2e840..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/Rotation.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage; - -public enum Rotation { - NORMAL, ROTATION_90, ROTATION_180, ROTATION_270; - - /** - * Retrieves the int representation of the Rotation. - * - * @return 0, 90, 180 or 270 - */ - public int asInt() { - switch (this) { - case NORMAL: return 0; - case ROTATION_90: return 90; - case ROTATION_180: return 180; - case ROTATION_270: return 270; - default: throw new IllegalStateException("Unknown Rotation!"); - } - } - - /** - * Create a Rotation from an integer. Needs to be either 0, 90, 180 or 270. - * - * @param rotation 0, 90, 180 or 270 - * @return Rotation object - */ - public static Rotation fromInt(int rotation) { - switch (rotation) { - case 0: return NORMAL; - case 90: return ROTATION_90; - case 180: return ROTATION_180; - case 270: return ROTATION_270; - case 360: return NORMAL; - default: throw new IllegalStateException( - rotation + " is an unknown rotation. Needs to be either 0, 90, 180 or 270!"); - } - } -} diff --git a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/util/TextureRotationUtil.java b/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/util/TextureRotationUtil.java deleted file mode 100755 index c439d91..0000000 --- a/Gpu-Image/src/jp/co/cyberagent/android/gpuimage/util/TextureRotationUtil.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2012 CyberAgent - * - * 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 jp.co.cyberagent.android.gpuimage.util; - -import jp.co.cyberagent.android.gpuimage.Rotation; - -public class TextureRotationUtil { - - public static final float TEXTURE_NO_ROTATION[] = { - 0.0f, 1.0f, - 1.0f, 1.0f, - 0.0f, 0.0f, - 1.0f, 0.0f, - }; - - public static final float TEXTURE_ROTATED_90[] = { - 1.0f, 1.0f, - 1.0f, 0.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - }; - public static final float TEXTURE_ROTATED_180[] = { - 1.0f, 0.0f, - 0.0f, 0.0f, - 1.0f, 1.0f, - 0.0f, 1.0f, - }; - public static final float TEXTURE_ROTATED_270[] = { - 0.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - }; - - private TextureRotationUtil() { - } - - public static float[] getRotation(final Rotation rotation, final boolean flipHorizontal, - final boolean flipVertical) { - float[] rotatedTex; - switch (rotation) { - case ROTATION_90: - rotatedTex = TEXTURE_ROTATED_90; - break; - case ROTATION_180: - rotatedTex = TEXTURE_ROTATED_180; - break; - case ROTATION_270: - rotatedTex = TEXTURE_ROTATED_270; - break; - case NORMAL: - default: - rotatedTex = TEXTURE_NO_ROTATION; - break; - } - if (flipHorizontal) { - rotatedTex = new float[]{ - flip(rotatedTex[0]), rotatedTex[1], - flip(rotatedTex[2]), rotatedTex[3], - flip(rotatedTex[4]), rotatedTex[5], - flip(rotatedTex[6]), rotatedTex[7], - }; - } - if (flipVertical) { - rotatedTex = new float[]{ - rotatedTex[0], flip(rotatedTex[1]), - rotatedTex[2], flip(rotatedTex[3]), - rotatedTex[4], flip(rotatedTex[5]), - rotatedTex[6], flip(rotatedTex[7]), - }; - } - return rotatedTex; - } - - - private static float flip(final float i) { - if (i == 0.0f) { - return 1.0f; - } - return 0.0f; - } -} diff --git a/ImageViewTouch/build.gradle b/ImageViewTouch/build.gradle index 62fdab5..205ab72 100644 --- a/ImageViewTouch/build.gradle +++ b/ImageViewTouch/build.gradle @@ -1,24 +1,30 @@ apply plugin: 'com.android.library' android { - compileSdkVersion 22 - buildToolsVersion "22.0.1" + namespace 'com.imagezoom' + compileSdk 36 defaultConfig { - minSdkVersion 15 - targetSdkVersion 22 - versionCode 1 - versionName "1.0" + minSdk 26 } + buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + lint { + abortOnError false + } } dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:22.2.0' + implementation 'androidx.appcompat:appcompat:1.7.0' } diff --git a/ImageViewTouch/src/main/AndroidManifest.xml b/ImageViewTouch/src/main/AndroidManifest.xml index 00eedc3..9a40236 100644 --- a/ImageViewTouch/src/main/AndroidManifest.xml +++ b/ImageViewTouch/src/main/AndroidManifest.xml @@ -1,7 +1,3 @@ - - - - - - + + diff --git a/README.md b/README.md index 8da3a53..02faa10 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,10 @@ + +### [Android 工程师进阶手册(8 年 Android 开发者的成长感悟)](https://github.com/Skykai521/AndroidDeveloperAdvancedManual) + +### 点击查看:https://github.com/Skykai521/AndroidDeveloperAdvancedManual + +*** + # StickerCamera This is an Android application with camera,picture cropping,collage sticking and tagging. diff --git a/app/build.gradle b/app/build.gradle index a2f362d..3f5d0f3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,14 +1,13 @@ apply plugin: 'com.android.application' -apply plugin: 'me.tatarka.retrolambda' android { - compileSdkVersion 22 - buildToolsVersion "22.0.1" + namespace 'com.github.skykai.stickercamera' + compileSdk 36 defaultConfig { applicationId "com.github.skykai.stickercamera" - minSdkVersion 15 - targetSdkVersion 22 + minSdk 26 + targetSdk 36 versionCode 1 versionName "1.0" } @@ -18,26 +17,41 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } } +// ButterKnife 10.x 的注解处理器需访问 JDK 内部 javac API;JDK 16+ 默认封装, +// 通过 --add-exports/--add-opens 放行(保留 ButterKnife 所需的标准解法)。 +tasks.withType(JavaCompile).configureEach { + options.fork = true + options.forkOptions.jvmArgs += [ + '--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED', + '--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED', + '--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED', + '--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED', + '--add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED', + '--add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED', + '--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED' + ] +} + dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:22.2.0' - compile 'com.android.support:recyclerview-v7:22.2.0' - compile 'com.android.support:cardview-v7:22.2.0' - compile 'com.jakewharton:butterknife:6.1.0' - compile 'com.readystatesoftware.systembartint:systembartint:1.0.3' - compile 'com.melnykov:floatingactionbutton:1.3.0' - compile 'com.rengwuxian.materialedittext:library:2.1.3' - compile files('libs/fastjson-1.2.5.jar') - compile files('universal-image-loader-1.9.4.jar') - compile 'it.sephiroth.android.library.horizontallistview:hlistview:1.2.2' - compile project(":Gpu-Image") - compile project(":ImageViewTouch") - compile 'de.greenrobot:eventbus:2.4.0' + implementation 'androidx.appcompat:appcompat:1.7.0' + implementation 'androidx.recyclerview:recyclerview:1.3.2' + implementation 'androidx.cardview:cardview:1.0.0' + implementation 'androidx.core:core:1.13.1' + implementation 'androidx.fragment:fragment:1.8.5' + implementation 'androidx.viewpager:viewpager:1.0.0' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' + implementation 'com.google.android.material:material:1.12.0' + implementation 'com.jakewharton:butterknife:10.2.3' + annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3' + implementation 'com.alibaba:fastjson:1.2.83' + implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' + implementation 'org.greenrobot:eventbus:3.3.1' + implementation 'jp.co.cyberagent.android:gpuimage:2.1.0' + implementation project(':ImageViewTouch') } diff --git a/app/libs/fastjson-1.2.5.jar b/app/libs/fastjson-1.2.5.jar deleted file mode 100644 index d4a3f7d..0000000 Binary files a/app/libs/fastjson-1.2.5.jar and /dev/null differ diff --git a/app/libs/universal-image-loader-1.9.4.jar b/app/libs/universal-image-loader-1.9.4.jar deleted file mode 100644 index 871d0e8..0000000 Binary files a/app/libs/universal-image-loader-1.9.4.jar and /dev/null differ diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index cd4afe6..c1e7789 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,6 +1,5 @@ - + @@ -19,6 +18,7 @@ android:theme="@style/BlueTheme"> diff --git a/app/src/main/java/com/common/util/AppUtils.java b/app/src/main/java/com/common/util/AppUtils.java deleted file mode 100644 index 89a1d4d..0000000 --- a/app/src/main/java/com/common/util/AppUtils.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.common.util; - -import java.util.List; - -import android.app.ActivityManager; -import android.app.ActivityManager.RunningAppProcessInfo; -import android.app.ActivityManager.RunningTaskInfo; -import android.content.ComponentName; -import android.content.Context; - -/** - * AppUtils - *
    - *
  • {@link AppUtils#isNamedProcess(Context, String)}
  • - *
- * - * @author Trinea 2014-5-07 - */ -public class AppUtils { - - private AppUtils() { - throw new AssertionError(); - } - - /** - * whether this process is named with processName - * - * @param context - * @param processName - * @return
    - * return whether this process is named with processName - *
  • if context is null, return false
  • - *
  • if {@link ActivityManager#getRunningAppProcesses()} is null, return false
  • - *
  • if one process of {@link ActivityManager#getRunningAppProcesses()} is equal to processName, return - * true, otherwise return false
  • - *
- */ - public static boolean isNamedProcess(Context context, String processName) { - if (context == null) { - return false; - } - - int pid = android.os.Process.myPid(); - ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); - List processInfoList = manager.getRunningAppProcesses(); - if (ListUtils.isEmpty(processInfoList)) { - return false; - } - - for (RunningAppProcessInfo processInfo : processInfoList) { - if (processInfo != null && processInfo.pid == pid - && ObjectUtils.isEquals(processName, processInfo.processName)) { - return true; - } - } - return false; - } - - /** - * whether application is in background - *
    - *
  • need use permission android.permission.GET_TASKS in Manifest.xml
  • - *
- * - * @param context - * @return if application is in background return true, otherwise return false - */ - public static boolean isApplicationInBackground(Context context) { - ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); - List taskList = am.getRunningTasks(1); - if (taskList != null && !taskList.isEmpty()) { - ComponentName topActivity = taskList.get(0).topActivity; - if (topActivity != null && !topActivity.getPackageName().equals(context.getPackageName())) { - return true; - } - } - return false; - } -} diff --git a/app/src/main/java/com/common/util/ArrayUtils.java b/app/src/main/java/com/common/util/ArrayUtils.java deleted file mode 100644 index 1c59371..0000000 --- a/app/src/main/java/com/common/util/ArrayUtils.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.common.util; - -/** - * Array Utils - *
    - *
  • {@link #isEmpty(Object[])} is null or its length is 0
  • - *
  • {@link #getLast(Object[], Object, Object, boolean)} get last element of the target element, before the first one - * that match the target element front to back
  • - *
  • {@link #getNext(Object[], Object, Object, boolean)} get next element of the target element, after the first one - * that match the target element front to back
  • - *
  • {@link #getLast(Object[], Object, boolean)}
  • - *
  • {@link #getLast(int[], int, int, boolean)}
  • - *
  • {@link #getLast(long[], long, long, boolean)}
  • - *
  • {@link #getNext(Object[], Object, boolean)}
  • - *
  • {@link #getNext(int[], int, int, boolean)}
  • - *
  • {@link #getNext(long[], long, long, boolean)}
  • - *
- * - * @author Trinea 2011-10-24 - */ -public class ArrayUtils { - - private ArrayUtils() { - throw new AssertionError(); - } - - /** - * is null or its length is 0 - * - * @param - * @param sourceArray - * @return - */ - public static boolean isEmpty(V[] sourceArray) { - return (sourceArray == null || sourceArray.length == 0); - } - - /** - * get last element of the target element, before the first one that match the target element front to back - *
    - *
  • if array is empty, return defaultValue
  • - *
  • if target element is not exist in array, return defaultValue
  • - *
  • if target element exist in array and its index is not 0, return the last element
  • - *
  • if target element exist in array and its index is 0, return the last one in array if isCircle is true, else - * return defaultValue
  • - *
- * - * @param - * @param sourceArray - * @param value value of target element - * @param defaultValue default return value - * @param isCircle whether is circle - * @return - */ - public static V getLast(V[] sourceArray, V value, V defaultValue, boolean isCircle) { - if (isEmpty(sourceArray)) { - return defaultValue; - } - - int currentPosition = -1; - for (int i = 0; i < sourceArray.length; i++) { - if (ObjectUtils.isEquals(value, sourceArray[i])) { - currentPosition = i; - break; - } - } - if (currentPosition == -1) { - return defaultValue; - } - - if (currentPosition == 0) { - return isCircle ? sourceArray[sourceArray.length - 1] : defaultValue; - } - return sourceArray[currentPosition - 1]; - } - - /** - * get next element of the target element, after the first one that match the target element front to back - *
    - *
  • if array is empty, return defaultValue
  • - *
  • if target element is not exist in array, return defaultValue
  • - *
  • if target element exist in array and not the last one in array, return the next element
  • - *
  • if target element exist in array and the last one in array, return the first one in array if isCircle is - * true, else return defaultValue
  • - *
- * - * @param - * @param sourceArray - * @param value value of target element - * @param defaultValue default return value - * @param isCircle whether is circle - * @return - */ - public static V getNext(V[] sourceArray, V value, V defaultValue, boolean isCircle) { - if (isEmpty(sourceArray)) { - return defaultValue; - } - - int currentPosition = -1; - for (int i = 0; i < sourceArray.length; i++) { - if (ObjectUtils.isEquals(value, sourceArray[i])) { - currentPosition = i; - break; - } - } - if (currentPosition == -1) { - return defaultValue; - } - - if (currentPosition == sourceArray.length - 1) { - return isCircle ? sourceArray[0] : defaultValue; - } - return sourceArray[currentPosition + 1]; - } - - /** - * @see {@link ArrayUtils#getLast(Object[], Object, Object, boolean)} defaultValue is null - */ - public static V getLast(V[] sourceArray, V value, boolean isCircle) { - return getLast(sourceArray, value, null, isCircle); - } - - /** - * @see {@link ArrayUtils#getNext(Object[], Object, Object, boolean)} defaultValue is null - */ - public static V getNext(V[] sourceArray, V value, boolean isCircle) { - return getNext(sourceArray, value, null, isCircle); - } - - /** - * @see {@link ArrayUtils#getLast(Object[], Object, Object, boolean)} Object is Long - */ - public static long getLast(long[] sourceArray, long value, long defaultValue, boolean isCircle) { - if (sourceArray.length == 0) { - throw new IllegalArgumentException("The length of source array must be greater than 0."); - } - - Long[] array = ObjectUtils.transformLongArray(sourceArray); - return getLast(array, value, defaultValue, isCircle); - - } - - /** - * @see {@link ArrayUtils#getNext(Object[], Object, Object, boolean)} Object is Long - */ - public static long getNext(long[] sourceArray, long value, long defaultValue, boolean isCircle) { - if (sourceArray.length == 0) { - throw new IllegalArgumentException("The length of source array must be greater than 0."); - } - - Long[] array = ObjectUtils.transformLongArray(sourceArray); - return getNext(array, value, defaultValue, isCircle); - } - - /** - * @see {@link ArrayUtils#getLast(Object[], Object, Object, boolean)} Object is Integer - */ - public static int getLast(int[] sourceArray, int value, int defaultValue, boolean isCircle) { - if (sourceArray.length == 0) { - throw new IllegalArgumentException("The length of source array must be greater than 0."); - } - - Integer[] array = ObjectUtils.transformIntArray(sourceArray); - return getLast(array, value, defaultValue, isCircle); - - } - - /** - * @see {@link ArrayUtils#getNext(Object[], Object, Object, boolean)} Object is Integer - */ - public static int getNext(int[] sourceArray, int value, int defaultValue, boolean isCircle) { - if (sourceArray.length == 0) { - throw new IllegalArgumentException("The length of source array must be greater than 0."); - } - - Integer[] array = ObjectUtils.transformIntArray(sourceArray); - return getNext(array, value, defaultValue, isCircle); - } -} diff --git a/app/src/main/java/com/common/util/CollectionUtils.java b/app/src/main/java/com/common/util/CollectionUtils.java deleted file mode 100644 index 06b7e33..0000000 --- a/app/src/main/java/com/common/util/CollectionUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.common.util; - -import java.util.Collection; - -import android.text.TextUtils; - -/** - * CollectionUtils - * - * @author Trinea 2012-7-22 - */ -public class CollectionUtils { - - /** default join separator **/ - public static final CharSequence DEFAULT_JOIN_SEPARATOR = ","; - - private CollectionUtils() { - throw new AssertionError(); - } - - /** - * is null or its size is 0 - * - *
-     * isEmpty(null)   =   true;
-     * isEmpty({})     =   true;
-     * isEmpty({1})    =   false;
-     * 
- * - * @param - * @param c - * @return if collection is null or its size is 0, return true, else return false. - */ - public static boolean isEmpty(Collection c) { - return (c == null || c.size() == 0); - } - - /** - * join collection to string, separator is {@link #DEFAULT_JOIN_SEPARATOR} - * - *
-     * join(null)      =   "";
-     * join({})        =   "";
-     * join({a,b})     =   "a,b";
-     * 
- * - * @param collection - * @return join collection to string, separator is {@link #DEFAULT_JOIN_SEPARATOR}. if collection is empty, return - * "" - */ - public static String join(Iterable collection) { - return collection == null ? "" : TextUtils.join(DEFAULT_JOIN_SEPARATOR, collection); - } -} diff --git a/app/src/main/java/com/common/util/FileUtils.java b/app/src/main/java/com/common/util/FileUtils.java index fde84bd..8171a4b 100644 --- a/app/src/main/java/com/common/util/FileUtils.java +++ b/app/src/main/java/com/common/util/FileUtils.java @@ -149,14 +149,14 @@ public String getSystemPhotoPath() { private FileUtils() { - String sdcardState = Environment.getExternalStorageState(); - //如果没SD卡则放缓存 - if (Environment.MEDIA_MOUNTED.equals(sdcardState)) { - BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() - + "/stickercamera/"; - } else { - BASE_PATH = App.getApp().getCacheDirPath(); + // 分区存储(Android 10+ / targetSdk 36)下应用无法直接写公共外部目录, + // 改用应用专属外部目录:无需运行时权限,各 API 级别均可写。 + File baseDir = App.getApp().getExternalFilesDir(null); + if (baseDir == null) { + // 外部存储不可用时退回内部缓存目录 + baseDir = App.getApp().getCacheDir(); } + BASE_PATH = baseDir.getAbsolutePath() + "/stickercamera/"; STICKER_BASE_PATH = BASE_PATH + "/stickers/"; } @@ -174,10 +174,9 @@ public boolean createFile(File file) { } public boolean mkdir(File file) { - while (!file.getParentFile().exists()) { - mkdir(file.getParentFile()); - } - return file.mkdir(); + // 用 mkdirs() 一次性创建整条目录链。旧实现用 while 循环等待父目录出现, + // 一旦 mkdir 因权限失败(分区存储)便永远卡在循环里——这是保存线程卡死的根因。 + return file.exists() || file.mkdirs(); } public boolean writeSimpleString(File file, String string) { diff --git a/app/src/main/java/com/common/util/ListUtils.java b/app/src/main/java/com/common/util/ListUtils.java deleted file mode 100644 index 18f3eef..0000000 --- a/app/src/main/java/com/common/util/ListUtils.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.common.util; - -import java.util.ArrayList; -import java.util.List; - -import android.text.TextUtils; - -/** - * List Utils - * - * @author Trinea 2011-7-22 - */ -public class ListUtils { - - /** default join separator **/ - public static final String DEFAULT_JOIN_SEPARATOR = ","; - - private ListUtils() { - throw new AssertionError(); - } - - /** - * get size of list - * - *
-     * getSize(null)   =   0;
-     * getSize({})     =   0;
-     * getSize({1})    =   1;
-     * 
- * - * @param - * @param sourceList - * @return if list is null or empty, return 0, else return {@link List#size()}. - */ - public static int getSize(List sourceList) { - return sourceList == null ? 0 : sourceList.size(); - } - - /** - * is null or its size is 0 - * - *
-     * isEmpty(null)   =   true;
-     * isEmpty({})     =   true;
-     * isEmpty({1})    =   false;
-     * 
- * - * @param - * @param sourceList - * @return if list is null or its size is 0, return true, else return false. - */ - public static boolean isEmpty(List sourceList) { - return (sourceList == null || sourceList.size() == 0); - } - - /** - * compare two list - * - *
-     * isEquals(null, null) = true;
-     * isEquals(new ArrayList<String>(), null) = false;
-     * isEquals(null, new ArrayList<String>()) = false;
-     * isEquals(new ArrayList<String>(), new ArrayList<String>()) = true;
-     * 
- * - * @param - * @param actual - * @param expected - * @return - */ - public static boolean isEquals(ArrayList actual, ArrayList expected) { - if (actual == null) { - return expected == null; - } - if (expected == null) { - return false; - } - if (actual.size() != expected.size()) { - return false; - } - - for (int i = 0; i < actual.size(); i++) { - if (!ObjectUtils.isEquals(actual.get(i), expected.get(i))) { - return false; - } - } - return true; - } - - /** - * join list to string, separator is "," - * - *
-     * join(null)      =   "";
-     * join({})        =   "";
-     * join({a,b})     =   "a,b";
-     * 
- * - * @param list - * @return join list to string, separator is ",". if list is empty, return "" - */ - public static String join(List list) { - return join(list, DEFAULT_JOIN_SEPARATOR); - } - - /** - * join list to string - * - *
-     * join(null, '#')     =   "";
-     * join({}, '#')       =   "";
-     * join({a,b,c}, ' ')  =   "abc";
-     * join({a,b,c}, '#')  =   "a#b#c";
-     * 
- * - * @param list - * @param separator - * @return join list to string. if list is empty, return "" - */ - public static String join(List list, char separator) { - return join(list, new String(new char[] {separator})); - } - - /** - * join list to string. if separator is null, use {@link #DEFAULT_JOIN_SEPARATOR} - * - *
-     * join(null, "#")     =   "";
-     * join({}, "#$")      =   "";
-     * join({a,b,c}, null) =   "a,b,c";
-     * join({a,b,c}, "")   =   "abc";
-     * join({a,b,c}, "#")  =   "a#b#c";
-     * join({a,b,c}, "#$") =   "a#$b#$c";
-     * 
- * - * @param list - * @param separator - * @return join list to string with separator. if list is empty, return "" - */ - public static String join(List list, String separator) { - return list == null ? "" : TextUtils.join(separator, list); - } - - /** - * add distinct entry to list - * - * @param - * @param sourceList - * @param entry - * @return if entry already exist in sourceList, return false, else add it and return true. - */ - public static boolean addDistinctEntry(List sourceList, V entry) { - return (sourceList != null && !sourceList.contains(entry)) ? sourceList.add(entry) : false; - } - - /** - * add all distinct entry to list1 from list2 - * - * @param - * @param sourceList - * @param entryList - * @return the count of entries be added - */ - public static int addDistinctList(List sourceList, List entryList) { - if (sourceList == null || isEmpty(entryList)) { - return 0; - } - - int sourceCount = sourceList.size(); - for (V entry : entryList) { - if (!sourceList.contains(entry)) { - sourceList.add(entry); - } - } - return sourceList.size() - sourceCount; - } - - /** - * remove duplicate entries in list - * - * @param - * @param sourceList - * @return the count of entries be removed - */ - public static int distinctList(List sourceList) { - if (isEmpty(sourceList)) { - return 0; - } - - int sourceCount = sourceList.size(); - int sourceListSize = sourceList.size(); - for (int i = 0; i < sourceListSize; i++) { - for (int j = (i + 1); j < sourceListSize; j++) { - if (sourceList.get(i).equals(sourceList.get(j))) { - sourceList.remove(j); - sourceListSize = sourceList.size(); - j--; - } - } - } - return sourceCount - sourceList.size(); - } - - /** - * add not null entry to list - * - * @param sourceList - * @param value - * @return
    - *
  • if sourceList is null, return false
  • - *
  • if value is null, return false
  • - *
  • return {@link List#add(Object)}
  • - *
- */ - public static boolean addListNotNullValue(List sourceList, V value) { - return (sourceList != null && value != null) ? sourceList.add(value) : false; - } - - /** - * @see {@link ArrayUtils#getLast(Object[], Object, Object, boolean)} defaultValue is null, isCircle is true - */ - @SuppressWarnings("unchecked") - public static V getLast(List sourceList, V value) { - return (sourceList == null) ? null : (V)ArrayUtils.getLast(sourceList.toArray(), value, true); - } - - /** - * @see {@link ArrayUtils#getNext(Object[], Object, Object, boolean)} defaultValue is null, isCircle is true - */ - @SuppressWarnings("unchecked") - public static V getNext(List sourceList, V value) { - return (sourceList == null) ? null : (V)ArrayUtils.getNext(sourceList.toArray(), value, true); - } - - /** - * invert list - * - * @param - * @param sourceList - * @return - */ - public static List invertList(List sourceList) { - if (isEmpty(sourceList)) { - return sourceList; - } - - List invertList = new ArrayList(sourceList.size()); - for (int i = sourceList.size() - 1; i >= 0; i--) { - invertList.add(sourceList.get(i)); - } - return invertList; - } -} diff --git a/app/src/main/java/com/common/util/MapUtils.java b/app/src/main/java/com/common/util/MapUtils.java deleted file mode 100644 index b8866c5..0000000 --- a/app/src/main/java/com/common/util/MapUtils.java +++ /dev/null @@ -1,289 +0,0 @@ -package com.common.util; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Map Utils - * - * @author Trinea 2011-7-22 - */ -public class MapUtils { - - /** default separator between key and value **/ - public static final String DEFAULT_KEY_AND_VALUE_SEPARATOR = ":"; - /** default separator between key-value pairs **/ - public static final String DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR = ","; - - private MapUtils() { - throw new AssertionError(); - } - /** - * is null or its size is 0 - * - *
-     * isEmpty(null)   =   true;
-     * isEmpty({})     =   true;
-     * isEmpty({1, 2})    =   false;
-     * 
- * - * @param sourceMap - * @return if map is null or its size is 0, return true, else return false. - */ - public static boolean isEmpty(Map sourceMap) { - return (sourceMap == null || sourceMap.size() == 0); - } - - /** - * add key-value pair to map, and key need not null or empty - * - * @param map - * @param key - * @param value - * @return
    - *
  • if map is null, return false
  • - *
  • if key is null or empty, return false
  • - *
  • return {@link Map#put(Object, Object)}
  • - *
- */ - public static boolean putMapNotEmptyKey(Map map, String key, String value) { - if (map == null || StringUtils.isEmpty(key)) { - return false; - } - - map.put(key, value); - return true; - } - - /** - * add key-value pair to map, both key and value need not null or empty - * - * @param map - * @param key - * @param value - * @return
    - *
  • if map is null, return false
  • - *
  • if key is null or empty, return false
  • - *
  • if value is null or empty, return false
  • - *
  • return {@link Map#put(Object, Object)}
  • - *
- */ - public static boolean putMapNotEmptyKeyAndValue(Map map, String key, String value) { - if (map == null || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { - return false; - } - - map.put(key, value); - return true; - } - - /** - * add key-value pair to map, key need not null or empty - * - * @param map - * @param key - * @param value - * @param defaultValue - * @return
    - *
  • if map is null, return false
  • - *
  • if key is null or empty, return false
  • - *
  • if value is null or empty, put defaultValue, return true
  • - *
  • if value is neither null nor empty,put value, return true
  • - *
- */ - public static boolean putMapNotEmptyKeyAndValue(Map map, String key, String value, - String defaultValue) { - if (map == null || StringUtils.isEmpty(key)) { - return false; - } - - map.put(key, StringUtils.isEmpty(value) ? defaultValue : value); - return true; - } - - /** - * add key-value pair to map, key need not null - * - * @param map - * @param key - * @param value - * @return
    - *
  • if map is null, return false
  • - *
  • if key is null, return false
  • - *
  • return {@link Map#put(Object, Object)}
  • - *
- */ - public static boolean putMapNotNullKey(Map map, K key, V value) { - if (map == null || key == null) { - return false; - } - - map.put(key, value); - return true; - } - - /** - * add key-value pair to map, both key and value need not null - * - * @param map - * @param key - * @param value - * @return
    - *
  • if map is null, return false
  • - *
  • if key is null, return false
  • - *
  • if value is null, return false
  • - *
  • return {@link Map#put(Object, Object)}
  • - *
- */ - public static boolean putMapNotNullKeyAndValue(Map map, K key, V value) { - if (map == null || key == null || value == null) { - return false; - } - - map.put(key, value); - return true; - } - - /** - * get key by value, match the first entry front to back - *
    - * Attentions: - *
  • for HashMap, the order of entry not same to put order, so you may need to use TreeMap
  • - *
- * - * @param - * @param map - * @param value - * @return
    - *
  • if map is null, return null
  • - *
  • if value exist, return key
  • - *
  • return null
  • - *
- */ - public static K getKeyByValue(Map map, V value) { - if (isEmpty(map)) { - return null; - } - - for (Entry entry : map.entrySet()) { - if (ObjectUtils.isEquals(entry.getValue(), value)) { - return entry.getKey(); - } - } - return null; - } - - /** - * parse key-value pairs to map, ignore empty key - * - *
-     * parseKeyAndValueToMap("","","",true)=null
-     * parseKeyAndValueToMap(null,"","",true)=null
-     * parseKeyAndValueToMap("a:b,:","","",true)={(a,b)}
-     * parseKeyAndValueToMap("a:b,:d","","",true)={(a,b)}
-     * parseKeyAndValueToMap("a:b,c:d","","",true)={(a,b),(c,d)}
-     * parseKeyAndValueToMap("a=b, c = d","=",",",true)={(a,b),(c,d)}
-     * parseKeyAndValueToMap("a=b, c = d","=",",",false)={(a, b),( c , d)}
-     * parseKeyAndValueToMap("a=b, c=d","=", ",", false)={(a,b),( c,d)}
-     * parseKeyAndValueToMap("a=b; c=d","=", ";", false)={(a,b),( c,d)}
-     * parseKeyAndValueToMap("a=b, c=d", ",", ";", false)={(a=b, c=d)}
-     * 
- * - * @param source key-value pairs - * @param keyAndValueSeparator separator between key and value - * @param keyAndValuePairSeparator separator between key-value pairs - * @param ignoreSpace whether ignore space at the begging or end of key and value - * @return - */ - public static Map parseKeyAndValueToMap(String source, String keyAndValueSeparator, - String keyAndValuePairSeparator, boolean ignoreSpace) { - if (StringUtils.isEmpty(source)) { - return null; - } - - if (StringUtils.isEmpty(keyAndValueSeparator)) { - keyAndValueSeparator = DEFAULT_KEY_AND_VALUE_SEPARATOR; - } - if (StringUtils.isEmpty(keyAndValuePairSeparator)) { - keyAndValuePairSeparator = DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR; - } - Map keyAndValueMap = new HashMap(); - String[] keyAndValueArray = source.split(keyAndValuePairSeparator); - if (keyAndValueArray == null) { - return null; - } - - int seperator; - for (String valueEntity : keyAndValueArray) { - if (!StringUtils.isEmpty(valueEntity)) { - seperator = valueEntity.indexOf(keyAndValueSeparator); - if (seperator != -1) { - if (ignoreSpace) { - MapUtils.putMapNotEmptyKey(keyAndValueMap, valueEntity.substring(0, seperator).trim(), - valueEntity.substring(seperator + 1).trim()); - } else { - MapUtils.putMapNotEmptyKey(keyAndValueMap, valueEntity.substring(0, seperator), - valueEntity.substring(seperator + 1)); - } - } - } - } - return keyAndValueMap; - } - - /** - * parse key-value pairs to map, ignore empty key - * - * @param source key-value pairs - * @param ignoreSpace whether ignore space at the begging or end of key and value - * @return - * @see {@link MapUtils#parseKeyAndValueToMap(String, String, String, boolean)}, keyAndValueSeparator is - * {@link #DEFAULT_KEY_AND_VALUE_SEPARATOR}, keyAndValuePairSeparator is - * {@link #DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR} - */ - public static Map parseKeyAndValueToMap(String source, boolean ignoreSpace) { - return parseKeyAndValueToMap(source, DEFAULT_KEY_AND_VALUE_SEPARATOR, DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR, - ignoreSpace); - } - - /** - * parse key-value pairs to map, ignore empty key, ignore space at the begging or end of key and value - * - * @param source key-value pairs - * @return - * @see {@link MapUtils#parseKeyAndValueToMap(String, String, String, boolean)}, keyAndValueSeparator is - * {@link #DEFAULT_KEY_AND_VALUE_SEPARATOR}, keyAndValuePairSeparator is - * {@link #DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR}, ignoreSpace is true - */ - public static Map parseKeyAndValueToMap(String source) { - return parseKeyAndValueToMap(source, DEFAULT_KEY_AND_VALUE_SEPARATOR, DEFAULT_KEY_AND_VALUE_PAIR_SEPARATOR, - true); - } - - /** - * join map - * - * @param map - * @return - */ - public static String toJson(Map map) { - if (map == null || map.size() == 0) { - return null; - } - - StringBuilder paras = new StringBuilder(); - paras.append("{"); - Iterator> ite = map.entrySet().iterator(); - while (ite.hasNext()) { - Entry entry = (Entry)ite.next(); - paras.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\""); - if (ite.hasNext()) { - paras.append(","); - } - } - paras.append("}"); - return paras.toString(); - } -} diff --git a/app/src/main/java/com/common/util/NetWorkUtils.java b/app/src/main/java/com/common/util/NetWorkUtils.java deleted file mode 100644 index b10572f..0000000 --- a/app/src/main/java/com/common/util/NetWorkUtils.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.common.util; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.telephony.TelephonyManager; -import android.text.TextUtils; - -/** - * NetWork Utils - *
    - * Attentions - *
  • You should add android.permission.ACCESS_NETWORK_STATE in manifest, to get network status.
  • - *
- * - * @author Trinea 2014-11-03 - */ -public class NetWorkUtils { - - public static final String NETWORK_TYPE_WIFI = "wifi"; - public static final String NETWORK_TYPE_3G = "eg"; - public static final String NETWORK_TYPE_2G = "2g"; - public static final String NETWORK_TYPE_WAP = "wap"; - public static final String NETWORK_TYPE_UNKNOWN = "unknown"; - public static final String NETWORK_TYPE_DISCONNECT = "disconnect"; - - /** - * Get network type - * - * @param context - * @return - */ - public static int getNetworkType(Context context) { - ConnectivityManager connectivityManager = (ConnectivityManager)context - .getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo(); - return networkInfo == null ? -1 : networkInfo.getType(); - } - - /** - * Get network type name - * - * @param context - * @return - */ - public static String getNetworkTypeName(Context context) { - ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo networkInfo; - String type = NETWORK_TYPE_DISCONNECT; - if (manager == null || (networkInfo = manager.getActiveNetworkInfo()) == null) { - return type; - }; - - if (networkInfo.isConnected()) { - String typeName = networkInfo.getTypeName(); - if ("WIFI".equalsIgnoreCase(typeName)) { - type = NETWORK_TYPE_WIFI; - } else if ("MOBILE".equalsIgnoreCase(typeName)) { - String proxyHost = android.net.Proxy.getDefaultHost(); - type = TextUtils.isEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORK_TYPE_3G : NETWORK_TYPE_2G) - : NETWORK_TYPE_WAP; - } else { - type = NETWORK_TYPE_UNKNOWN; - } - } - return type; - } - - /** - * Whether is fast mobile network - * - * @param context - * @return - */ - private static boolean isFastMobileNetwork(Context context) { - TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); - if (telephonyManager == null) { - return false; - } - - switch (telephonyManager.getNetworkType()) { - case TelephonyManager.NETWORK_TYPE_1xRTT: - return false; - case TelephonyManager.NETWORK_TYPE_CDMA: - return false; - case TelephonyManager.NETWORK_TYPE_EDGE: - return false; - case TelephonyManager.NETWORK_TYPE_EVDO_0: - return true; - case TelephonyManager.NETWORK_TYPE_EVDO_A: - return true; - case TelephonyManager.NETWORK_TYPE_GPRS: - return false; - case TelephonyManager.NETWORK_TYPE_HSDPA: - return true; - case TelephonyManager.NETWORK_TYPE_HSPA: - return true; - case TelephonyManager.NETWORK_TYPE_HSUPA: - return true; - case TelephonyManager.NETWORK_TYPE_UMTS: - return true; - case TelephonyManager.NETWORK_TYPE_EHRPD: - return true; - case TelephonyManager.NETWORK_TYPE_EVDO_B: - return true; - case TelephonyManager.NETWORK_TYPE_HSPAP: - return true; - case TelephonyManager.NETWORK_TYPE_IDEN: - return false; - case TelephonyManager.NETWORK_TYPE_LTE: - return true; - case TelephonyManager.NETWORK_TYPE_UNKNOWN: - return false; - default: - return false; - } - } -} diff --git a/app/src/main/java/com/common/util/ObjectUtils.java b/app/src/main/java/com/common/util/ObjectUtils.java deleted file mode 100644 index 268a8b4..0000000 --- a/app/src/main/java/com/common/util/ObjectUtils.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.common.util; - -/** - * Object Utils - * - * @author Trinea 2011-10-24 - */ -public class ObjectUtils { - - private ObjectUtils() { - throw new AssertionError(); - } - - /** - * compare two object - * - * @param actual - * @param expected - * @return
    - *
  • if both are null, return true
  • - *
  • return actual.{@link Object#equals(Object)}
  • - *
- */ - public static boolean isEquals(Object actual, Object expected) { - return actual == expected || (actual == null ? expected == null : actual.equals(expected)); - } - - /** - * null Object to empty string - * - *
-     * nullStrToEmpty(null) = "";
-     * nullStrToEmpty("") = "";
-     * nullStrToEmpty("aa") = "aa";
-     * 
- * - * @param str - * @return - */ - public static String nullStrToEmpty(Object str) { - return (str == null ? "" : (str instanceof String ? (String)str : str.toString())); - } - - /** - * convert long array to Long array - * - * @param source - * @return - */ - public static Long[] transformLongArray(long[] source) { - Long[] destin = new Long[source.length]; - for (int i = 0; i < source.length; i++) { - destin[i] = source[i]; - } - return destin; - } - - /** - * convert Long array to long array - * - * @param source - * @return - */ - public static long[] transformLongArray(Long[] source) { - long[] destin = new long[source.length]; - for (int i = 0; i < source.length; i++) { - destin[i] = source[i]; - } - return destin; - } - - /** - * convert int array to Integer array - * - * @param source - * @return - */ - public static Integer[] transformIntArray(int[] source) { - Integer[] destin = new Integer[source.length]; - for (int i = 0; i < source.length; i++) { - destin[i] = source[i]; - } - return destin; - } - - /** - * convert Integer array to int array - * - * @param source - * @return - */ - public static int[] transformIntArray(Integer[] source) { - int[] destin = new int[source.length]; - for (int i = 0; i < source.length; i++) { - destin[i] = source[i]; - } - return destin; - } - - /** - * compare two object - *
    - * About result - *
  • if v1 > v2, return 1
  • - *
  • if v1 = v2, return 0
  • - *
  • if v1 < v2, return -1
  • - *
- *
    - * About rule - *
  • if v1 is null, v2 is null, then return 0
  • - *
  • if v1 is null, v2 is not null, then return -1
  • - *
  • if v1 is not null, v2 is null, then return 1
  • - *
  • return v1.{@link Comparable#compareTo(Object)}
  • - *
- * - * @param v1 - * @param v2 - * @return - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - public static int compare(V v1, V v2) { - return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 : ((Comparable)v1).compareTo(v2)); - } -} diff --git a/app/src/main/java/com/common/util/PackageUtils.java b/app/src/main/java/com/common/util/PackageUtils.java deleted file mode 100644 index 3554ab1..0000000 --- a/app/src/main/java/com/common/util/PackageUtils.java +++ /dev/null @@ -1,770 +0,0 @@ -package com.common.util; - -import java.io.File; -import java.util.List; - -import android.app.ActivityManager; -import android.app.ActivityManager.RunningTaskInfo; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.net.Uri; -import android.os.Build; -import android.provider.Settings; -import android.util.Log; -import com.common.util.ShellUtils.CommandResult; - - -public class PackageUtils { - - public static final String TAG = "PackageUtils"; - - private PackageUtils() { - throw new AssertionError(); - } - - /** - * App installation location settings values, same to {@link #PackageHelper} - */ - public static final int APP_INSTALL_AUTO = 0; - public static final int APP_INSTALL_INTERNAL = 1; - public static final int APP_INSTALL_EXTERNAL = 2; - - /** - * install according conditions - *
    - *
  • if system application or rooted, see {@link #installSilent(Context, String)}
  • - *
  • else see {@link #installNormal(Context, String)}
  • - *
- * - * @param context - * @param filePath - * @return - */ - public static final int install(Context context, String filePath) { - if (PackageUtils.isSystemApplication(context) || ShellUtils.checkRootPermission()) { - return installSilent(context, filePath); - } - return installNormal(context, filePath) ? INSTALL_SUCCEEDED : INSTALL_FAILED_INVALID_URI; - } - - /** - * install package normal by system intent - * - * @param context - * @param filePath file path of package - * @return whether apk exist - */ - public static boolean installNormal(Context context, String filePath) { - Intent i = new Intent(Intent.ACTION_VIEW); - File file = new File(filePath); - if (file == null || !file.exists() || !file.isFile() || file.length() <= 0) { - return false; - } - - i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive"); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(i); - return true; - } - - /** - * install package silent by root - *
    - * Attentions: - *
  • Don't call this on the ui thread, it may costs some times.
  • - *
  • You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root - * permission, if you are system app.
  • - *
  • Default pm install params is "-r".
  • - *
- * - * @param context - * @param filePath file path of package - * @return {@link PackageUtils#INSTALL_SUCCEEDED} means install success, other means failed. details see - * {@link PackageUtils}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_* - * @see #installSilent(Context, String, String) - */ - public static int installSilent(Context context, String filePath) { - return installSilent(context, filePath, " -r " + getInstallLocationParams()); - } - - /** - * install package silent by root - *
    - * Attentions: - *
  • Don't call this on the ui thread, it may costs some times.
  • - *
  • You should add android.permission.INSTALL_PACKAGES in manifest, so no need to request root - * permission, if you are system app.
  • - *
- * - * @param context - * @param filePath file path of package - * @param pmParams pm install params - * @return {@link PackageUtils#INSTALL_SUCCEEDED} means install success, other means failed. details see - * {@link PackageUtils}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_* - */ - public static int installSilent(Context context, String filePath, String pmParams) { - if (filePath == null || filePath.length() == 0) { - return INSTALL_FAILED_INVALID_URI; - } - - File file = new File(filePath); - if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) { - return INSTALL_FAILED_INVALID_URI; - } - - /** - * if context is system app, don't need root permission, but should add in mainfest - **/ - StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ") - .append(pmParams == null ? "" : pmParams).append(" ").append(filePath.replace(" ", "\\ ")); - CommandResult commandResult = ShellUtils.execCommand(command.toString(), !isSystemApplication(context), true); - if (commandResult.successMsg != null - && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) { - return INSTALL_SUCCEEDED; - } - - Log.e(TAG, - new StringBuilder().append("installSilent successMsg:").append(commandResult.successMsg) - .append(", ErrorMsg:").append(commandResult.errorMsg).toString()); - if (commandResult.errorMsg == null) { - return INSTALL_FAILED_OTHER; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_ALREADY_EXISTS")) { - return INSTALL_FAILED_ALREADY_EXISTS; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_INVALID_APK")) { - return INSTALL_FAILED_INVALID_APK; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_INVALID_URI")) { - return INSTALL_FAILED_INVALID_URI; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_INSUFFICIENT_STORAGE")) { - return INSTALL_FAILED_INSUFFICIENT_STORAGE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_DUPLICATE_PACKAGE")) { - return INSTALL_FAILED_DUPLICATE_PACKAGE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_NO_SHARED_USER")) { - return INSTALL_FAILED_NO_SHARED_USER; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_UPDATE_INCOMPATIBLE")) { - return INSTALL_FAILED_UPDATE_INCOMPATIBLE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE")) { - return INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_MISSING_SHARED_LIBRARY")) { - return INSTALL_FAILED_MISSING_SHARED_LIBRARY; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_REPLACE_COULDNT_DELETE")) { - return INSTALL_FAILED_REPLACE_COULDNT_DELETE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_DEXOPT")) { - return INSTALL_FAILED_DEXOPT; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_OLDER_SDK")) { - return INSTALL_FAILED_OLDER_SDK; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_CONFLICTING_PROVIDER")) { - return INSTALL_FAILED_CONFLICTING_PROVIDER; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_NEWER_SDK")) { - return INSTALL_FAILED_NEWER_SDK; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_TEST_ONLY")) { - return INSTALL_FAILED_TEST_ONLY; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_CPU_ABI_INCOMPATIBLE")) { - return INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_MISSING_FEATURE")) { - return INSTALL_FAILED_MISSING_FEATURE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_CONTAINER_ERROR")) { - return INSTALL_FAILED_CONTAINER_ERROR; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_INVALID_INSTALL_LOCATION")) { - return INSTALL_FAILED_INVALID_INSTALL_LOCATION; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_MEDIA_UNAVAILABLE")) { - return INSTALL_FAILED_MEDIA_UNAVAILABLE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_VERIFICATION_TIMEOUT")) { - return INSTALL_FAILED_VERIFICATION_TIMEOUT; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_VERIFICATION_FAILURE")) { - return INSTALL_FAILED_VERIFICATION_FAILURE; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_PACKAGE_CHANGED")) { - return INSTALL_FAILED_PACKAGE_CHANGED; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_UID_CHANGED")) { - return INSTALL_FAILED_UID_CHANGED; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_NOT_APK")) { - return INSTALL_PARSE_FAILED_NOT_APK; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_BAD_MANIFEST")) { - return INSTALL_PARSE_FAILED_BAD_MANIFEST; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION")) { - return INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_NO_CERTIFICATES")) { - return INSTALL_PARSE_FAILED_NO_CERTIFICATES; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES")) { - return INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING")) { - return INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME")) { - return INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID")) { - return INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_MANIFEST_MALFORMED")) { - return INSTALL_PARSE_FAILED_MANIFEST_MALFORMED; - } - if (commandResult.errorMsg.contains("INSTALL_PARSE_FAILED_MANIFEST_EMPTY")) { - return INSTALL_PARSE_FAILED_MANIFEST_EMPTY; - } - if (commandResult.errorMsg.contains("INSTALL_FAILED_INTERNAL_ERROR")) { - return INSTALL_FAILED_INTERNAL_ERROR; - } - return INSTALL_FAILED_OTHER; - } - - /** - * uninstall according conditions - *
    - *
  • if system application or rooted, see {@link #uninstallSilent(Context, String)}
  • - *
  • else see {@link #uninstallNormal(Context, String)}
  • - *
- * - * @param context - * @param packageName package name of app - * @return whether package name is empty - * @return - */ - public static final int uninstall(Context context, String packageName) { - if (PackageUtils.isSystemApplication(context) || ShellUtils.checkRootPermission()) { - return uninstallSilent(context, packageName); - } - return uninstallNormal(context, packageName) ? DELETE_SUCCEEDED : DELETE_FAILED_INVALID_PACKAGE; - } - - /** - * uninstall package normal by system intent - * - * @param context - * @param packageName package name of app - * @return whether package name is empty - */ - public static boolean uninstallNormal(Context context, String packageName) { - if (packageName == null || packageName.length() == 0) { - return false; - } - - Intent i = new Intent(Intent.ACTION_DELETE, Uri.parse(new StringBuilder(32).append("package:") - .append(packageName).toString())); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(i); - return true; - } - - /** - * uninstall package and clear data of app silent by root - * - * @param context - * @param packageName package name of app - * @return - * @see #uninstallSilent(Context, String, boolean) - */ - public static int uninstallSilent(Context context, String packageName) { - return uninstallSilent(context, packageName, true); - } - - /** - * uninstall package silent by root - *
    - * Attentions: - *
  • Don't call this on the ui thread, it may costs some times.
  • - *
  • You should add android.permission.DELETE_PACKAGES in manifest, so no need to request root - * permission, if you are system app.
  • - *
- * - * @param context file path of package - * @param packageName package name of app - * @param isKeepData whether keep the data and cache directories around after package removal - * @return
    - *
  • {@link #DELETE_SUCCEEDED} means uninstall success
  • - *
  • {@link #DELETE_FAILED_INTERNAL_ERROR} means internal error
  • - *
  • {@link #DELETE_FAILED_INVALID_PACKAGE} means package name error
  • - *
  • {@link #DELETE_FAILED_PERMISSION_DENIED} means permission denied
  • - */ - public static int uninstallSilent(Context context, String packageName, boolean isKeepData) { - if (packageName == null || packageName.length() == 0) { - return DELETE_FAILED_INVALID_PACKAGE; - } - - /** - * if context is system app, don't need root permission, but should add in mainfest - **/ - StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall") - .append(isKeepData ? " -k " : " ").append(packageName.replace(" ", "\\ ")); - CommandResult commandResult = ShellUtils.execCommand(command.toString(), !isSystemApplication(context), true); - if (commandResult.successMsg != null - && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) { - return DELETE_SUCCEEDED; - } - Log.e(TAG, - new StringBuilder().append("uninstallSilent successMsg:").append(commandResult.successMsg) - .append(", ErrorMsg:").append(commandResult.errorMsg).toString()); - if (commandResult.errorMsg == null) { - return DELETE_FAILED_INTERNAL_ERROR; - } - if (commandResult.errorMsg.contains("Permission denied")) { - return DELETE_FAILED_PERMISSION_DENIED; - } - return DELETE_FAILED_INTERNAL_ERROR; - } - - /** - * whether context is system application - * - * @param context - * @return - */ - public static boolean isSystemApplication(Context context) { - if (context == null) { - return false; - } - - return isSystemApplication(context, context.getPackageName()); - } - - /** - * whether packageName is system application - * - * @param context - * @param packageName - * @return - */ - public static boolean isSystemApplication(Context context, String packageName) { - if (context == null) { - return false; - } - - return isSystemApplication(context.getPackageManager(), packageName); - } - - /** - * whether packageName is system application - * - * @param packageManager - * @param packageName - * @return
      - *
    • if packageManager is null, return false
    • - *
    • if package name is null or is empty, return false
    • - *
    • if package name not exit, return false
    • - *
    • if package name exit, but not system app, return false
    • - *
    • else return true
    • - *
    - */ - public static boolean isSystemApplication(PackageManager packageManager, String packageName) { - if (packageManager == null || packageName == null || packageName.length() == 0) { - return false; - } - - try { - ApplicationInfo app = packageManager.getApplicationInfo(packageName, 0); - return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0); - } catch (NameNotFoundException e) { - e.printStackTrace(); - } - return false; - } - - /** - * whether the app whost package's name is packageName is on the top of the stack - *
      - * Attentions: - *
    • You should add android.permission.GET_TASKS in manifest
    • - *
    - * - * @param context - * @param packageName - * @return if params error or task stack is null, return null, otherwise retun whether the app is on the top of - * stack - */ - public static Boolean isTopActivity(Context context, String packageName) { - if (context == null || StringUtils.isEmpty(packageName)) { - return null; - } - - ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); - List tasksInfo = activityManager.getRunningTasks(1); - if (ListUtils.isEmpty(tasksInfo)) { - return null; - } - try { - return packageName.equals(tasksInfo.get(0).topActivity.getPackageName()); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * get app version code - * - * @param context - * @return - */ - public static int getAppVersionCode(Context context) { - if (context != null) { - PackageManager pm = context.getPackageManager(); - if (pm != null) { - PackageInfo pi; - try { - pi = pm.getPackageInfo(context.getPackageName(), 0); - if (pi != null) { - return pi.versionCode; - } - } catch (NameNotFoundException e) { - e.printStackTrace(); - } - } - } - return -1; - } - - /** - * get system install location
    - * can be set by System Menu Setting->Storage->Prefered install location - * - * @return - * @see {@link IPackageManager#getInstallLocation()} - */ - public static int getInstallLocation() { - CommandResult commandResult = ShellUtils.execCommand( - "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm get-install-location", false, true); - if (commandResult.result == 0 && commandResult.successMsg != null && commandResult.successMsg.length() > 0) { - try { - int location = Integer.parseInt(commandResult.successMsg.substring(0, 1)); - switch (location) { - case APP_INSTALL_INTERNAL: - return APP_INSTALL_INTERNAL; - case APP_INSTALL_EXTERNAL: - return APP_INSTALL_EXTERNAL; - } - } catch (NumberFormatException e) { - e.printStackTrace(); - Log.e(TAG, "pm get-install-location error"); - } - } - return APP_INSTALL_AUTO; - } - - /** - * get params for pm install location - * - * @return - */ - private static String getInstallLocationParams() { - int location = getInstallLocation(); - switch (location) { - case APP_INSTALL_INTERNAL: - return "-f"; - case APP_INSTALL_EXTERNAL: - return "-s"; - } - return ""; - } - - /** - * start InstalledAppDetails Activity - * - * @param context - * @param packageName - */ - public static void startInstalledAppDetails(Context context, String packageName) { - Intent intent = new Intent(); - int sdkVersion = Build.VERSION.SDK_INT; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { - intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - intent.setData(Uri.fromParts("package", packageName, null)); - } else { - intent.setAction(Intent.ACTION_VIEW); - intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); - intent.putExtra((sdkVersion == Build.VERSION_CODES.FROYO ? "pkg" - : "com.android.settings.ApplicationPkgName"), packageName); - } - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); - } - - /** - * Installation return code
    - * install success. - */ - public static final int INSTALL_SUCCEEDED = 1; - /** - * Installation return code
    - * the package is already installed. - */ - public static final int INSTALL_FAILED_ALREADY_EXISTS = -1; - - /** - * Installation return code
    - * the package archive file is invalid. - */ - public static final int INSTALL_FAILED_INVALID_APK = -2; - - /** - * Installation return code
    - * the URI passed in is invalid. - */ - public static final int INSTALL_FAILED_INVALID_URI = -3; - - /** - * Installation return code
    - * the package manager service found that the device didn't have enough storage space to install the app. - */ - public static final int INSTALL_FAILED_INSUFFICIENT_STORAGE = -4; - - /** - * Installation return code
    - * a package is already installed with the same name. - */ - public static final int INSTALL_FAILED_DUPLICATE_PACKAGE = -5; - - /** - * Installation return code
    - * the requested shared user does not exist. - */ - public static final int INSTALL_FAILED_NO_SHARED_USER = -6; - - /** - * Installation return code
    - * a previously installed package of the same name has a different signature than the new package (and the old - * package's data was not removed). - */ - public static final int INSTALL_FAILED_UPDATE_INCOMPATIBLE = -7; - - /** - * Installation return code
    - * the new package is requested a shared user which is already installed on the device and does not have matching - * signature. - */ - public static final int INSTALL_FAILED_SHARED_USER_INCOMPATIBLE = -8; - - /** - * Installation return code
    - * the new package uses a shared library that is not available. - */ - public static final int INSTALL_FAILED_MISSING_SHARED_LIBRARY = -9; - - /** - * Installation return code
    - * the new package uses a shared library that is not available. - */ - public static final int INSTALL_FAILED_REPLACE_COULDNT_DELETE = -10; - - /** - * Installation return code
    - * the new package failed while optimizing and validating its dex files, either because there was not enough storage - * or the validation failed. - */ - public static final int INSTALL_FAILED_DEXOPT = -11; - - /** - * Installation return code
    - * the new package failed because the current SDK version is older than that required by the package. - */ - public static final int INSTALL_FAILED_OLDER_SDK = -12; - - /** - * Installation return code
    - * the new package failed because it contains a content provider with the same authority as a provider already - * installed in the system. - */ - public static final int INSTALL_FAILED_CONFLICTING_PROVIDER = -13; - - /** - * Installation return code
    - * the new package failed because the current SDK version is newer than that required by the package. - */ - public static final int INSTALL_FAILED_NEWER_SDK = -14; - - /** - * Installation return code
    - * the new package failed because it has specified that it is a test-only package and the caller has not supplied - * the {@link #INSTALL_ALLOW_TEST} flag. - */ - public static final int INSTALL_FAILED_TEST_ONLY = -15; - - /** - * Installation return code
    - * the package being installed contains native code, but none that is compatible with the the device's CPU_ABI. - */ - public static final int INSTALL_FAILED_CPU_ABI_INCOMPATIBLE = -16; - - /** - * Installation return code
    - * the new package uses a feature that is not available. - */ - public static final int INSTALL_FAILED_MISSING_FEATURE = -17; - - /** - * Installation return code
    - * a secure container mount point couldn't be accessed on external media. - */ - public static final int INSTALL_FAILED_CONTAINER_ERROR = -18; - - /** - * Installation return code
    - * the new package couldn't be installed in the specified install location. - */ - public static final int INSTALL_FAILED_INVALID_INSTALL_LOCATION = -19; - - /** - * Installation return code
    - * the new package couldn't be installed in the specified install location because the media is not available. - */ - public static final int INSTALL_FAILED_MEDIA_UNAVAILABLE = -20; - - /** - * Installation return code
    - * the new package couldn't be installed because the verification timed out. - */ - public static final int INSTALL_FAILED_VERIFICATION_TIMEOUT = -21; - - /** - * Installation return code
    - * the new package couldn't be installed because the verification did not succeed. - */ - public static final int INSTALL_FAILED_VERIFICATION_FAILURE = -22; - - /** - * Installation return code
    - * the package changed from what the calling program expected. - */ - public static final int INSTALL_FAILED_PACKAGE_CHANGED = -23; - - /** - * Installation return code
    - * the new package is assigned a different UID than it previously held. - */ - public static final int INSTALL_FAILED_UID_CHANGED = -24; - - /** - * Installation return code
    - * if the parser was given a path that is not a file, or does not end with the expected '.apk' extension. - */ - public static final int INSTALL_PARSE_FAILED_NOT_APK = -100; - - /** - * Installation return code
    - * if the parser was unable to retrieve the AndroidManifest.xml file. - */ - public static final int INSTALL_PARSE_FAILED_BAD_MANIFEST = -101; - - /** - * Installation return code
    - * if the parser encountered an unexpected exception. - */ - public static final int INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION = -102; - - /** - * Installation return code
    - * if the parser did not find any certificates in the .apk. - */ - public static final int INSTALL_PARSE_FAILED_NO_CERTIFICATES = -103; - - /** - * Installation return code
    - * if the parser found inconsistent certificates on the files in the .apk. - */ - public static final int INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES = -104; - - /** - * Installation return code
    - * if the parser encountered a CertificateEncodingException in one of the files in the .apk. - */ - public static final int INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING = -105; - - /** - * Installation return code
    - * if the parser encountered a bad or missing package name in the manifest. - */ - public static final int INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME = -106; - - /** - * Installation return code
    - * if the parser encountered a bad shared user id name in the manifest. - */ - public static final int INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID = -107; - - /** - * Installation return code
    - * if the parser encountered some structural problem in the manifest. - */ - public static final int INSTALL_PARSE_FAILED_MANIFEST_MALFORMED = -108; - - /** - * Installation return code
    - * if the parser did not find any actionable tags (instrumentation or application) in the manifest. - */ - public static final int INSTALL_PARSE_FAILED_MANIFEST_EMPTY = -109; - - /** - * Installation return code
    - * if the system failed to install the package because of system issues. - */ - public static final int INSTALL_FAILED_INTERNAL_ERROR = -110; - /** - * Installation return code
    - * other reason - */ - public static final int INSTALL_FAILED_OTHER = -1000000; - - /** - * Uninstall return code
    - * uninstall success. - */ - public static final int DELETE_SUCCEEDED = 1; - - /** - * Uninstall return code
    - * uninstall fail if the system failed to delete the package for an unspecified reason. - */ - public static final int DELETE_FAILED_INTERNAL_ERROR = -1; - - /** - * Uninstall return code
    - * uninstall fail if the system failed to delete the package because it is the active DevicePolicy manager. - */ - public static final int DELETE_FAILED_DEVICE_POLICY_MANAGER = -2; - - /** - * Uninstall return code
    - * uninstall fail if pcakge name is invalid - */ - public static final int DELETE_FAILED_INVALID_PACKAGE = -3; - - /** - * Uninstall return code
    - * uninstall fail if permission denied - */ - public static final int DELETE_FAILED_PERMISSION_DENIED = -4; -} diff --git a/app/src/main/java/com/common/util/PreferencesUtils.java b/app/src/main/java/com/common/util/PreferencesUtils.java deleted file mode 100644 index 71373a9..0000000 --- a/app/src/main/java/com/common/util/PreferencesUtils.java +++ /dev/null @@ -1,248 +0,0 @@ -package com.common.util; - -import android.content.Context; -import android.content.SharedPreferences; - -/** - * PreferencesUtils, easy to get or put data - *
      - * Preference Name - *
    • you can change preference name by {@link #PREFERENCE_NAME}
    • - *
    - *
      - * Put Value - *
    • put string {@link #putString(Context, String, String)}
    • - *
    • put int {@link #putInt(Context, String, int)}
    • - *
    • put long {@link #putLong(Context, String, long)}
    • - *
    • put float {@link #putFloat(Context, String, float)}
    • - *
    • put boolean {@link #putBoolean(Context, String, boolean)}
    • - *
    - *
      - * Get Value - *
    • get string {@link #getString(Context, String)}, {@link #getString(Context, String, String)}
    • - *
    • get int {@link #getInt(Context, String)}, {@link #getInt(Context, String, int)}
    • - *
    • get long {@link #getLong(Context, String)}, {@link #getLong(Context, String, long)}
    • - *
    • get float {@link #getFloat(Context, String)}, {@link #getFloat(Context, String, float)}
    • - *
    • get boolean {@link #getBoolean(Context, String)}, {@link #getBoolean(Context, String, boolean)}
    • - *
    - * - * @author Trinea 2013-3-6 - */ -public class PreferencesUtils { - - public static String PREFERENCE_NAME = "TrineaAndroidCommon"; - - private PreferencesUtils() { - throw new AssertionError(); - } - - /** - * put string preferences - * - * @param context - * @param key The name of the preference to modify - * @param value The new value for the preference - * @return True if the new values were successfully written to persistent storage. - */ - public static boolean putString(Context context, String key, String value) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putString(key, value); - return editor.commit(); - } - - /** - * get string preferences - * - * @param context - * @param key The name of the preference to retrieve - * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this - * name that is not a string - * @see #getString(Context, String, String) - */ - public static String getString(Context context, String key) { - return getString(context, key, null); - } - - /** - * get string preferences - * - * @param context - * @param key The name of the preference to retrieve - * @param defaultValue Value to return if this preference does not exist - * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with - * this name that is not a string - */ - public static String getString(Context context, String key, String defaultValue) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - return settings.getString(key, defaultValue); - } - - /** - * put int preferences - * - * @param context - * @param key The name of the preference to modify - * @param value The new value for the preference - * @return True if the new values were successfully written to persistent storage. - */ - public static boolean putInt(Context context, String key, int value) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putInt(key, value); - return editor.commit(); - } - - /** - * get int preferences - * - * @param context - * @param key The name of the preference to retrieve - * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this - * name that is not a int - * @see #getInt(Context, String, int) - */ - public static int getInt(Context context, String key) { - return getInt(context, key, -1); - } - - /** - * get int preferences - * - * @param context - * @param key The name of the preference to retrieve - * @param defaultValue Value to return if this preference does not exist - * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with - * this name that is not a int - */ - public static int getInt(Context context, String key, int defaultValue) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - return settings.getInt(key, defaultValue); - } - - /** - * put long preferences - * - * @param context - * @param key The name of the preference to modify - * @param value The new value for the preference - * @return True if the new values were successfully written to persistent storage. - */ - public static boolean putLong(Context context, String key, long value) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong(key, value); - return editor.commit(); - } - - /** - * get long preferences - * - * @param context - * @param key The name of the preference to retrieve - * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this - * name that is not a long - * @see #getLong(Context, String, long) - */ - public static long getLong(Context context, String key) { - return getLong(context, key, -1); - } - - /** - * get long preferences - * - * @param context - * @param key The name of the preference to retrieve - * @param defaultValue Value to return if this preference does not exist - * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with - * this name that is not a long - */ - public static long getLong(Context context, String key, long defaultValue) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - return settings.getLong(key, defaultValue); - } - - /** - * put float preferences - * - * @param context - * @param key The name of the preference to modify - * @param value The new value for the preference - * @return True if the new values were successfully written to persistent storage. - */ - public static boolean putFloat(Context context, String key, float value) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat(key, value); - return editor.commit(); - } - - /** - * get float preferences - * - * @param context - * @param key The name of the preference to retrieve - * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this - * name that is not a float - * @see #getFloat(Context, String, float) - */ - public static float getFloat(Context context, String key) { - return getFloat(context, key, -1); - } - - /** - * get float preferences - * - * @param context - * @param key The name of the preference to retrieve - * @param defaultValue Value to return if this preference does not exist - * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with - * this name that is not a float - */ - public static float getFloat(Context context, String key, float defaultValue) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - return settings.getFloat(key, defaultValue); - } - - /** - * put boolean preferences - * - * @param context - * @param key The name of the preference to modify - * @param value The new value for the preference - * @return True if the new values were successfully written to persistent storage. - */ - public static boolean putBoolean(Context context, String key, boolean value) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putBoolean(key, value); - return editor.commit(); - } - - /** - * get boolean preferences, default is false - * - * @param context - * @param key The name of the preference to retrieve - * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this - * name that is not a boolean - * @see #getBoolean(Context, String, boolean) - */ - public static boolean getBoolean(Context context, String key) { - return getBoolean(context, key, false); - } - - /** - * get boolean preferences - * - * @param context - * @param key The name of the preference to retrieve - * @param defaultValue Value to return if this preference does not exist - * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with - * this name that is not a boolean - */ - public static boolean getBoolean(Context context, String key, boolean defaultValue) { - SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); - return settings.getBoolean(key, defaultValue); - } -} diff --git a/app/src/main/java/com/common/util/RandomUtils.java b/app/src/main/java/com/common/util/RandomUtils.java deleted file mode 100644 index 421e464..0000000 --- a/app/src/main/java/com/common/util/RandomUtils.java +++ /dev/null @@ -1,247 +0,0 @@ -package com.common.util; - -import java.util.Random; - -/** - * Random Utils - *
      - * Shuffling algorithm - *
    • {@link #shuffle(Object[])} Shuffling algorithm, Randomly permutes the specified array using a default source of - * randomness
    • - *
    • {@link #shuffle(Object[], int)} Shuffling algorithm, Randomly permutes the specified array
    • - *
    • {@link #shuffle(int[])} Shuffling algorithm, Randomly permutes the specified int array using a default source of - * randomness
    • - *
    • {@link #shuffle(int[], int)} Shuffling algorithm, Randomly permutes the specified int array
    • - *
    - *
      - * get random int - *
    • {@link #getRandom(int)} get random int between 0 and max
    • - *
    • {@link #getRandom(int, int)} get random int between min and max
    • - *
    - *
      - * get random numbers or letters - *
    • {@link #getRandomCapitalLetters(int)} get a fixed-length random string, its a mixture of uppercase letters
    • - *
    • {@link #getRandomLetters(int)} get a fixed-length random string, its a mixture of uppercase and lowercase letters - *
    • - *
    • {@link #getRandomLowerCaseLetters(int)} get a fixed-length random string, its a mixture of lowercase letters
    • - *
    • {@link #getRandomNumbers(int)} get a fixed-length random string, its a mixture of numbers
    • - *
    • {@link #getRandomNumbersAndLetters(int)} get a fixed-length random string, its a mixture of uppercase, lowercase - * letters and numbers
    • - *
    • {@link #getRandom(String, int)} get a fixed-length random string, its a mixture of chars in source
    • - *
    • {@link #getRandom(char[], int)} get a fixed-length random string, its a mixture of chars in sourceChar
    • - *
    - * - * @author Trinea 2012-5-12 - */ -public class RandomUtils { - - public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - public static final String NUMBERS = "0123456789"; - public static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - public static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; - - private RandomUtils() { - throw new AssertionError(); - } - - /** - * get a fixed-length random string, its a mixture of uppercase, lowercase letters and numbers - * - * @param length - * @return - * @see RandomUtils#getRandom(String source, int length) - */ - public static String getRandomNumbersAndLetters(int length) { - return getRandom(NUMBERS_AND_LETTERS, length); - } - - /** - * get a fixed-length random string, its a mixture of numbers - * - * @param length - * @return - * @see RandomUtils#getRandom(String source, int length) - */ - public static String getRandomNumbers(int length) { - return getRandom(NUMBERS, length); - } - - /** - * get a fixed-length random string, its a mixture of uppercase and lowercase letters - * - * @param length - * @return - * @see RandomUtils#getRandom(String source, int length) - */ - public static String getRandomLetters(int length) { - return getRandom(LETTERS, length); - } - - /** - * get a fixed-length random string, its a mixture of uppercase letters - * - * @param length - * @return - * @see RandomUtils#getRandom(String source, int length) - */ - public static String getRandomCapitalLetters(int length) { - return getRandom(CAPITAL_LETTERS, length); - } - - /** - * get a fixed-length random string, its a mixture of lowercase letters - * - * @param length - * @return - * @see RandomUtils#getRandom(String source, int length) - */ - public static String getRandomLowerCaseLetters(int length) { - return getRandom(LOWER_CASE_LETTERS, length); - } - - /** - * get a fixed-length random string, its a mixture of chars in source - * - * @param source - * @param length - * @return
      - *
    • if source is null or empty, return null
    • - *
    • else see {@link RandomUtils#getRandom(char[] sourceChar, int length)}
    • - *
    - */ - public static String getRandom(String source, int length) { - return StringUtils.isEmpty(source) ? null : getRandom(source.toCharArray(), length); - } - - /** - * get a fixed-length random string, its a mixture of chars in sourceChar - * - * @param sourceChar - * @param length - * @return
      - *
    • if sourceChar is null or empty, return null
    • - *
    • if length less than 0, return null
    • - *
    - */ - public static String getRandom(char[] sourceChar, int length) { - if (sourceChar == null || sourceChar.length == 0 || length < 0) { - return null; - } - - StringBuilder str = new StringBuilder(length); - Random random = new Random(); - for (int i = 0; i < length; i++) { - str.append(sourceChar[random.nextInt(sourceChar.length)]); - } - return str.toString(); - } - - /** - * get random int between 0 and max - * - * @param max - * @return
      - *
    • if max <= 0, return 0
    • - *
    • else return random int between 0 and max
    • - *
    - */ - public static int getRandom(int max) { - return getRandom(0, max); - } - - /** - * get random int between min and max - * - * @param min - * @param max - * @return
      - *
    • if min > max, return 0
    • - *
    • if min == max, return min
    • - *
    • else return random int between min and max
    • - *
    - */ - public static int getRandom(int min, int max) { - if (min > max) { - return 0; - } - if (min == max) { - return min; - } - return min + new Random().nextInt(max - min); - } - - /** - * Shuffling algorithm, Randomly permutes the specified array using a default source of randomness - * - * @param objArray - * @return - */ - public static boolean shuffle(Object[] objArray) { - if (objArray == null) { - return false; - } - - return shuffle(objArray, getRandom(objArray.length)); - } - - /** - * Shuffling algorithm, Randomly permutes the specified array - * - * @param objArray - * @param shuffleCount - * @return - */ - public static boolean shuffle(Object[] objArray, int shuffleCount) { - int length; - if (objArray == null || shuffleCount < 0 || (length = objArray.length) < shuffleCount) { - return false; - } - - for (int i = 1; i <= shuffleCount; i++) { - int random = getRandom(length - i); - Object temp = objArray[length - i]; - objArray[length - i] = objArray[random]; - objArray[random] = temp; - } - return true; - } - - /** - * Shuffling algorithm, Randomly permutes the specified int array using a default source of randomness - * - * @param intArray - * @return - */ - public static int[] shuffle(int[] intArray) { - if (intArray == null) { - return null; - } - - return shuffle(intArray, getRandom(intArray.length)); - } - - /** - * Shuffling algorithm, Randomly permutes the specified int array - * - * @param intArray - * @param shuffleCount - * @return - */ - public static int[] shuffle(int[] intArray, int shuffleCount) { - int length; - if (intArray == null || shuffleCount < 0 || (length = intArray.length) < shuffleCount) { - return null; - } - - int[] out = new int[shuffleCount]; - for (int i = 1; i <= shuffleCount; i++) { - int random = getRandom(length - i); - out[i - 1] = intArray[random]; - int temp = intArray[length - i]; - intArray[length - i] = intArray[random]; - intArray[random] = temp; - } - return out; - } -} diff --git a/app/src/main/java/com/common/util/ResourceUtils.java b/app/src/main/java/com/common/util/ResourceUtils.java deleted file mode 100644 index 0cd348f..0000000 --- a/app/src/main/java/com/common/util/ResourceUtils.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.common.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -import android.content.Context; - -/** - * ResourceUtils - * - * @author Trinea 2012-5-26 - */ -public class ResourceUtils { - - private ResourceUtils() { - throw new AssertionError(); - } - - /** - * get an asset using ACCESS_STREAMING mode. This provides access to files that have been bundled with an - * application as assets -- that is, files placed in to the "assets" directory. - * - * @param context - * @param fileName The name of the asset to open. This name can be hierarchical. - * @return - */ - public static String geFileFromAssets(Context context, String fileName) { - if (context == null || StringUtils.isEmpty(fileName)) { - return null; - } - - StringBuilder s = new StringBuilder(""); - try { - InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName)); - BufferedReader br = new BufferedReader(in); - String line; - while ((line = br.readLine()) != null) { - s.append(line); - } - return s.toString(); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - /** - * get content from a raw resource. This can only be used with resources whose value is the name of an asset files - * -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color - * resources. - * - * @param context - * @param resId The resource identifier to open, as generated by the appt tool. - * @return - */ - public static String geFileFromRaw(Context context, int resId) { - if (context == null) { - return null; - } - - StringBuilder s = new StringBuilder(); - try { - InputStreamReader in = new InputStreamReader(context.getResources().openRawResource(resId)); - BufferedReader br = new BufferedReader(in); - String line; - while ((line = br.readLine()) != null) { - s.append(line); - } - return s.toString(); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - /** - * same to {@link ResourceUtils#geFileFromAssets(Context, String)}, but return type is List - * - * @param context - * @param fileName - * @return - */ - public static List geFileToListFromAssets(Context context, String fileName) { - if (context == null || StringUtils.isEmpty(fileName)) { - return null; - } - - List fileContent = new ArrayList(); - try { - InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName)); - BufferedReader br = new BufferedReader(in); - String line; - while ((line = br.readLine()) != null) { - fileContent.add(line); - } - br.close(); - return fileContent; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - /** - * same to {@link ResourceUtils#geFileFromRaw(Context, int)}, but return type is List - * - * @param context - * @param resId - * @return - */ - public static List geFileToListFromRaw(Context context, int resId) { - if (context == null) { - return null; - } - - List fileContent = new ArrayList(); - BufferedReader reader = null; - try { - InputStreamReader in = new InputStreamReader(context.getResources().openRawResource(resId)); - reader = new BufferedReader(in); - String line = null; - while ((line = reader.readLine()) != null) { - fileContent.add(line); - } - reader.close(); - return fileContent; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/app/src/main/java/com/common/util/ShellUtils.java b/app/src/main/java/com/common/util/ShellUtils.java deleted file mode 100644 index ec5fd9c..0000000 --- a/app/src/main/java/com/common/util/ShellUtils.java +++ /dev/null @@ -1,222 +0,0 @@ -package com.common.util; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; - -/** - * ShellUtils - *
      - * Check root - *
    • {@link ShellUtils#checkRootPermission()}
    • - *
    - *
      - * Execte command - *
    • {@link ShellUtils#execCommand(String, boolean)}
    • - *
    • {@link ShellUtils#execCommand(String, boolean, boolean)}
    • - *
    • {@link ShellUtils#execCommand(List, boolean)}
    • - *
    • {@link ShellUtils#execCommand(List, boolean, boolean)}
    • - *
    • {@link ShellUtils#execCommand(String[], boolean)}
    • - *
    • {@link ShellUtils#execCommand(String[], boolean, boolean)}
    • - *
    - * - * @author Trinea 2013-5-16 - */ -public class ShellUtils { - - public static final String COMMAND_SU = "su"; - public static final String COMMAND_SH = "sh"; - public static final String COMMAND_EXIT = "exit\n"; - public static final String COMMAND_LINE_END = "\n"; - - private ShellUtils() { - throw new AssertionError(); - } - - /** - * check whether has root permission - * - * @return - */ - public static boolean checkRootPermission() { - return execCommand("echo root", true, false).result == 0; - } - - /** - * execute shell command, default return result msg - * - * @param command command - * @param isRoot whether need to run with root - * @return - * @see ShellUtils#execCommand(String[], boolean, boolean) - */ - public static CommandResult execCommand(String command, boolean isRoot) { - return execCommand(new String[] {command}, isRoot, true); - } - - /** - * execute shell commands, default return result msg - * - * @param commands command list - * @param isRoot whether need to run with root - * @return - * @see ShellUtils#execCommand(String[], boolean, boolean) - */ - public static CommandResult execCommand(List commands, boolean isRoot) { - return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, true); - } - - /** - * execute shell commands, default return result msg - * - * @param commands command array - * @param isRoot whether need to run with root - * @return - * @see ShellUtils#execCommand(String[], boolean, boolean) - */ - public static CommandResult execCommand(String[] commands, boolean isRoot) { - return execCommand(commands, isRoot, true); - } - - /** - * execute shell command - * - * @param command command - * @param isRoot whether need to run with root - * @param isNeedResultMsg whether need result msg - * @return - * @see ShellUtils#execCommand(String[], boolean, boolean) - */ - public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) { - return execCommand(new String[] {command}, isRoot, isNeedResultMsg); - } - - /** - * execute shell commands - * - * @param commands command list - * @param isRoot whether need to run with root - * @param isNeedResultMsg whether need result msg - * @return - * @see ShellUtils#execCommand(String[], boolean, boolean) - */ - public static CommandResult execCommand(List commands, boolean isRoot, boolean isNeedResultMsg) { - return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg); - } - - /** - * execute shell commands - * - * @param commands command array - * @param isRoot whether need to run with root - * @param isNeedResultMsg whether need result msg - * @return
      - *
    • if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and - * {@link CommandResult#errorMsg} is null.
    • - *
    • if {@link CommandResult#result} is -1, there maybe some excepiton.
    • - *
    - */ - public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) { - int result = -1; - if (commands == null || commands.length == 0) { - return new CommandResult(result, null, null); - } - - Process process = null; - BufferedReader successResult = null; - BufferedReader errorResult = null; - StringBuilder successMsg = null; - StringBuilder errorMsg = null; - - DataOutputStream os = null; - try { - process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); - os = new DataOutputStream(process.getOutputStream()); - for (String command : commands) { - if (command == null) { - continue; - } - - // donnot use os.writeBytes(commmand), avoid chinese charset error - os.write(command.getBytes()); - os.writeBytes(COMMAND_LINE_END); - os.flush(); - } - os.writeBytes(COMMAND_EXIT); - os.flush(); - - result = process.waitFor(); - // get command result - if (isNeedResultMsg) { - successMsg = new StringBuilder(); - errorMsg = new StringBuilder(); - successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); - errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); - String s; - while ((s = successResult.readLine()) != null) { - successMsg.append(s); - } - while ((s = errorResult.readLine()) != null) { - errorMsg.append(s); - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (os != null) { - os.close(); - } - if (successResult != null) { - successResult.close(); - } - if (errorResult != null) { - errorResult.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - if (process != null) { - process.destroy(); - } - } - return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null - : errorMsg.toString()); - } - - /** - * result of command - *
      - *
    • {@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in - * linux shell
    • - *
    • {@link CommandResult#successMsg} means success message of command result
    • - *
    • {@link CommandResult#errorMsg} means error message of command result
    • - *
    - * - * @author Trinea 2013-5-16 - */ - public static class CommandResult { - - /** result of command **/ - public int result; - /** success message of command result **/ - public String successMsg; - /** error message of command result **/ - public String errorMsg; - - public CommandResult(int result) { - this.result = result; - } - - public CommandResult(int result, String successMsg, String errorMsg) { - this.result = result; - this.successMsg = successMsg; - this.errorMsg = errorMsg; - } - } -} diff --git a/app/src/main/java/com/common/util/SystemUtils.java b/app/src/main/java/com/common/util/SystemUtils.java deleted file mode 100644 index 8c0eb4b..0000000 --- a/app/src/main/java/com/common/util/SystemUtils.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.common.util; - -/** - * SystemUtils - * - * @author Trinea 2013-5-15 - */ -public class SystemUtils { - - /** recommend default thread pool size according to system available processors, {@link #getDefaultThreadPoolSize()} **/ - public static final int DEFAULT_THREAD_POOL_SIZE = getDefaultThreadPoolSize(); - - private SystemUtils() { - throw new AssertionError(); - } - - /** - * get recommend default thread pool size - * - * @return if 2 * availableProcessors + 1 less than 8, return it, else return 8; - * @see {@link #getDefaultThreadPoolSize(int)} max is 8 - */ - public static int getDefaultThreadPoolSize() { - return getDefaultThreadPoolSize(8); - } - - /** - * get recommend default thread pool size - * - * @param max - * @return if 2 * availableProcessors + 1 less than max, return it, else return max; - */ - public static int getDefaultThreadPoolSize(int max) { - int availableProcessors = 2 * Runtime.getRuntime().availableProcessors() + 1; - return availableProcessors > max ? max : availableProcessors; - } -} diff --git a/app/src/main/java/com/customview/MyImageViewDrawableOverlay.java b/app/src/main/java/com/customview/MyImageViewDrawableOverlay.java index d014871..489540e 100755 --- a/app/src/main/java/com/customview/MyImageViewDrawableOverlay.java +++ b/app/src/main/java/com/customview/MyImageViewDrawableOverlay.java @@ -485,7 +485,7 @@ public void onDraw(Canvas canvas) { boolean shouldInvalidateAfter = false; for (int i = 0; i < mOverlayViews.size(); i++) { - canvas.save(Canvas.MATRIX_SAVE_FLAG); + canvas.save(); MyHighlightView current = mOverlayViews.get(i); current.draw(canvas); @@ -589,7 +589,7 @@ public void commit(Canvas canvas) { Matrix rotateMatrix = hv.getCropRotationMatrix(); Rect rect = hv.getCropRect(); - int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG); + int saveCount = canvas.save(); canvas.concat(rotateMatrix); content.setBounds(rect); content.draw(canvas); diff --git a/app/src/main/java/com/customview/PagerSlidingTabStrip.java b/app/src/main/java/com/customview/PagerSlidingTabStrip.java index bae07ca..773e31a 100644 --- a/app/src/main/java/com/customview/PagerSlidingTabStrip.java +++ b/app/src/main/java/com/customview/PagerSlidingTabStrip.java @@ -26,8 +26,8 @@ import android.os.Build; import android.os.Parcel; import android.os.Parcelable; -import android.support.v4.view.ViewPager; -import android.support.v4.view.ViewPager.OnPageChangeListener; +import androidx.viewpager.widget.ViewPager; +import androidx.viewpager.widget.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; diff --git a/app/src/main/java/com/stickercamera/app/camera/CameraBaseFragmentActivity.java b/app/src/main/java/com/stickercamera/app/camera/CameraBaseFragmentActivity.java deleted file mode 100644 index 8ae38de..0000000 --- a/app/src/main/java/com/stickercamera/app/camera/CameraBaseFragmentActivity.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.stickercamera.app.camera; - -import android.os.Bundle; - -import com.stickercamera.base.BaseFragmentActivity; - - -public class CameraBaseFragmentActivity extends BaseFragmentActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - CameraManager.getInst().addActivity(this); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - CameraManager.getInst().removeActivity(this); - } -} diff --git a/app/src/main/java/com/stickercamera/app/camera/adapter/FilterAdapter.java b/app/src/main/java/com/stickercamera/app/camera/adapter/FilterAdapter.java index 161c108..a371f5f 100755 --- a/app/src/main/java/com/stickercamera/app/camera/adapter/FilterAdapter.java +++ b/app/src/main/java/com/stickercamera/app/camera/adapter/FilterAdapter.java @@ -5,9 +5,10 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.BaseAdapter; import android.widget.TextView; +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; import com.github.skykai.stickercamera.R; import com.stickercamera.app.camera.effect.FilterEffect; @@ -15,78 +16,81 @@ import java.util.List; -import jp.co.cyberagent.android.gpuimage.GPUImageFilter; import jp.co.cyberagent.android.gpuimage.GPUImageView; +import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter; /** * @author tongqian.ni - * */ -public class FilterAdapter extends BaseAdapter { +public class FilterAdapter extends RecyclerView.Adapter { - List filterUris; - Context mContext; - private Bitmap background; + public interface OnItemClickListener { + void onItemClick(int position); + } - private int selectFilter = 0; + private final List filterUris; + private final Context mContext; + private final Bitmap background; - public void setSelectFilter(int selectFilter) { - this.selectFilter = selectFilter; + private int selectFilter = 0; + private OnItemClickListener onItemClickListener; + + public FilterAdapter(Context context, List effects, Bitmap background) { + this.mContext = context; + this.filterUris = effects; + this.background = background; } - public int getSelectFilter() { - return selectFilter; + public void setOnItemClickListener(OnItemClickListener l) { + this.onItemClickListener = l; } - public FilterAdapter(Context context, List effects, Bitmap backgroud) { - filterUris = effects; - mContext = context; - this.background = backgroud; + public void setSelectFilter(int selectFilter) { + this.selectFilter = selectFilter; } - @Override - public int getCount() { - return filterUris.size(); + public int getSelectFilter() { + return selectFilter; } - @Override - public Object getItem(int position) { + public FilterEffect getItem(int position) { return filterUris.get(position); } + @NonNull @Override - public long getItemId(int position) { - return position; + public EffectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(mContext).inflate(R.layout.item_bottom_filter, parent, false); + return new EffectHolder(v); } @Override - public View getView(int position, View convertView, ViewGroup parent) { - EffectHolder holder = null; - if (convertView == null) { - LayoutInflater layoutInflater = LayoutInflater.from(mContext); - convertView = layoutInflater.inflate(R.layout.item_bottom_filter, null); - holder = new EffectHolder(); - holder.filteredImg = (GPUImageView) convertView.findViewById(R.id.small_filter); - holder.filterName = (TextView) convertView.findViewById(R.id.filter_name); - convertView.setTag(holder); - } else { - holder = (EffectHolder) convertView.getTag(); - } - - final FilterEffect effect = (FilterEffect) getItem(position); - + public void onBindViewHolder(@NonNull EffectHolder holder, int position) { + final FilterEffect effect = getItem(position); holder.filteredImg.setImage(background); holder.filterName.setText(effect.getTitle()); - //if (!effect.isOri() && effect.getType() != null) { GPUImageFilter filter = GPUImageFilterTools.createFilterForType(mContext, effect.getType()); holder.filteredImg.setFilter(filter); + holder.itemView.setOnClickListener(v -> { + if (onItemClickListener != null) { + onItemClickListener.onItemClick(holder.getAdapterPosition()); + } + }); + } - return convertView; + @Override + public int getItemCount() { + return filterUris.size(); } - class EffectHolder { + static class EffectHolder extends RecyclerView.ViewHolder { GPUImageView filteredImg; TextView filterName; - } + EffectHolder(View itemView) { + super(itemView); + filteredImg = itemView.findViewById(R.id.small_filter); + filterName = itemView.findViewById(R.id.filter_name); + } + } } diff --git a/app/src/main/java/com/stickercamera/app/camera/adapter/StickerToolAdapter.java b/app/src/main/java/com/stickercamera/app/camera/adapter/StickerToolAdapter.java index 85e8c9a..c7a78c8 100644 --- a/app/src/main/java/com/stickercamera/app/camera/adapter/StickerToolAdapter.java +++ b/app/src/main/java/com/stickercamera/app/camera/adapter/StickerToolAdapter.java @@ -4,78 +4,77 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.BaseAdapter; import android.widget.ImageView; +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; import com.common.util.ImageLoaderUtils; import com.github.skykai.stickercamera.R; -import com.nostra13.universalimageloader.core.ImageLoader; import com.stickercamera.app.model.Addon; import java.util.List; /** - * * 贴纸适配器 + * * @author tongqian.ni */ -public class StickerToolAdapter extends BaseAdapter { +public class StickerToolAdapter extends RecyclerView.Adapter { - List filterUris; - Context mContext; + public interface OnItemClickListener { + void onItemClick(int position); + } + + private final List filterUris; + private final Context mContext; + private OnItemClickListener onItemClickListener; public StickerToolAdapter(Context context, List effects) { - filterUris = effects; - mContext = context; + this.mContext = context; + this.filterUris = effects; } - @Override - public int getCount() { - return filterUris.size(); + public void setOnItemClickListener(OnItemClickListener l) { + this.onItemClickListener = l; } - @Override - public Object getItem(int position) { + public Addon getItem(int position) { return filterUris.get(position); } + @NonNull @Override - public long getItemId(int position) { - return position; + public EffectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(mContext).inflate(R.layout.item_bottom_tool, parent, false); + return new EffectHolder(v); } @Override - public View getView(int position, View convertView, ViewGroup parent) { - EffectHolder holder = null; - if (convertView == null) { - LayoutInflater layoutInflater = LayoutInflater.from(mContext); - convertView = layoutInflater.inflate(R.layout.item_bottom_tool, null); - holder = new EffectHolder(); - holder.logo = (ImageView) convertView.findViewById(R.id.effect_image); - holder.container = (ImageView) convertView.findViewById(R.id.effect_background); - //holder.navImage.setOnClickListener(holder.clickListener); - convertView.setTag(holder); - } else { - holder = (EffectHolder) convertView.getTag(); - } - - final Addon effect = (Addon) getItem(position); - - return showItem(convertView, holder, effect); - } - - private View showItem(View convertView, EffectHolder holder, final Addon sticker) { - + public void onBindViewHolder(@NonNull EffectHolder holder, int position) { + final Addon sticker = getItem(position); holder.container.setVisibility(View.GONE); ImageLoaderUtils.displayDrawableImage(sticker.getId() + "", holder.logo, null); + holder.itemView.setOnClickListener(v -> { + if (onItemClickListener != null) { + onItemClickListener.onItemClick(holder.getAdapterPosition()); + } + }); + } - return convertView; + @Override + public int getItemCount() { + return filterUris.size(); } - class EffectHolder { + static class EffectHolder extends RecyclerView.ViewHolder { ImageView logo; ImageView container; - } + EffectHolder(View itemView) { + super(itemView); + logo = itemView.findViewById(R.id.effect_image); + container = itemView.findViewById(R.id.effect_background); + } + } } diff --git a/app/src/main/java/com/stickercamera/app/camera/fragment/AlbumFragment.java b/app/src/main/java/com/stickercamera/app/camera/fragment/AlbumFragment.java index a2d1d85..edca28d 100644 --- a/app/src/main/java/com/stickercamera/app/camera/fragment/AlbumFragment.java +++ b/app/src/main/java/com/stickercamera/app/camera/fragment/AlbumFragment.java @@ -1,7 +1,7 @@ package com.stickercamera.app.camera.fragment; import android.os.Bundle; -import android.support.v4.app.Fragment; +import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; diff --git a/app/src/main/java/com/stickercamera/app/camera/ui/AlbumActivity.java b/app/src/main/java/com/stickercamera/app/camera/ui/AlbumActivity.java index 370a5ba..3cfb854 100644 --- a/app/src/main/java/com/stickercamera/app/camera/ui/AlbumActivity.java +++ b/app/src/main/java/com/stickercamera/app/camera/ui/AlbumActivity.java @@ -2,10 +2,10 @@ import android.content.Intent; import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.view.ViewPager; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.viewpager.widget.ViewPager; import com.common.util.FileUtils; import com.common.util.ImageUtils; @@ -22,7 +22,7 @@ import java.util.Map; import butterknife.ButterKnife; -import butterknife.InjectView; +import butterknife.BindView; /** * 相册界面 @@ -35,16 +35,16 @@ public class AlbumActivity extends CameraBaseActivity { private Map albums; private List paths = new ArrayList(); - @InjectView(R.id.indicator) + @BindView(R.id.indicator) PagerSlidingTabStrip tab; - @InjectView(R.id.pager) + @BindView(R.id.pager) ViewPager pager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album); - ButterKnife.inject(this); + ButterKnife.bind(this); albums = ImageUtils.findGalleries(this, paths, 0); //ViewPager的adapter FragmentPagerAdapter adapter = new TabPageIndicatorAdapter(getSupportFragmentManager()); diff --git a/app/src/main/java/com/stickercamera/app/camera/ui/CameraActivity.java b/app/src/main/java/com/stickercamera/app/camera/ui/CameraActivity.java index 28e7a81..9106f52 100644 --- a/app/src/main/java/com/stickercamera/app/camera/ui/CameraActivity.java +++ b/app/src/main/java/com/stickercamera/app/camera/ui/CameraActivity.java @@ -13,7 +13,6 @@ import android.os.Build; import android.os.Bundle; import android.os.Handler; -import android.util.FloatMath; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; @@ -54,7 +53,7 @@ import java.util.List; import butterknife.ButterKnife; -import butterknife.InjectView; +import butterknife.BindView; /** * 相机界面 @@ -78,25 +77,25 @@ public class CameraActivity extends CameraBaseActivity { private int mCurrentCameraId = 0; //1是前置 0是后置 private Handler handler = new Handler(); - @InjectView(R.id.masking) + @BindView(R.id.masking) CameraGrid cameraGrid; - @InjectView(R.id.photo_area) + @BindView(R.id.photo_area) LinearLayout photoArea; - @InjectView(R.id.panel_take_photo) + @BindView(R.id.panel_take_photo) View takePhotoPanel; - @InjectView(R.id.takepicture) + @BindView(R.id.takepicture) Button takePicture; - @InjectView(R.id.flashBtn) + @BindView(R.id.flashBtn) ImageView flashBtn; - @InjectView(R.id.change) + @BindView(R.id.change) ImageView changeBtn; - @InjectView(R.id.back) + @BindView(R.id.back) ImageView backBtn; - @InjectView(R.id.next) + @BindView(R.id.next) ImageView galleryBtn; - @InjectView(R.id.focus_index) + @BindView(R.id.focus_index) View focusIndex; - @InjectView(R.id.surfaceView) + @BindView(R.id.surfaceView) SurfaceView surfaceView; @@ -105,7 +104,7 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); mCameraHelper = new CameraHelper(this); - ButterKnife.inject(this); + ButterKnife.bind(this); initView(); initEvent(); } @@ -286,7 +285,7 @@ private float spacing(MotionEvent event) { } float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); - return FloatMath.sqrt(x * x + y * y); + return (float) Math.sqrt(x * x + y * y); } //放大缩小 diff --git a/app/src/main/java/com/stickercamera/app/camera/ui/CropPhotoActivity.java b/app/src/main/java/com/stickercamera/app/camera/ui/CropPhotoActivity.java index 85e4f6a..968d2be 100644 --- a/app/src/main/java/com/stickercamera/app/camera/ui/CropPhotoActivity.java +++ b/app/src/main/java/com/stickercamera/app/camera/ui/CropPhotoActivity.java @@ -33,7 +33,7 @@ import java.io.InputStream; import butterknife.ButterKnife; -import butterknife.InjectView; +import butterknife.BindView; /** * 裁剪图片界面 @@ -49,15 +49,15 @@ public class CropPhotoActivity extends CameraBaseActivity { private int initWidth, initHeight; private static final int MAX_WRAP_SIZE = 2048; - @InjectView(R.id.crop_image) + @BindView(R.id.crop_image) ImageViewTouch cropImage; - @InjectView(R.id.draw_area) + @BindView(R.id.draw_area) ViewGroup drawArea; - @InjectView(R.id.wrap_image) + @BindView(R.id.wrap_image) View wrapImage; - @InjectView(R.id.btn_crop_type) + @BindView(R.id.btn_crop_type) View btnCropType; - @InjectView(R.id.image_center) + @BindView(R.id.image_center) ImageView imageCenter; @Override @@ -65,7 +65,7 @@ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 显示界面 setContentView(R.layout.activity_new_crop); - ButterKnife.inject(this); + ButterKnife.bind(this); fileUri = getIntent().getData(); initView(); initEvent(); diff --git a/app/src/main/java/com/stickercamera/app/camera/ui/PhotoProcessActivity.java b/app/src/main/java/com/stickercamera/app/camera/ui/PhotoProcessActivity.java index 810f94a..469be5f 100644 --- a/app/src/main/java/com/stickercamera/app/camera/ui/PhotoProcessActivity.java +++ b/app/src/main/java/com/stickercamera/app/camera/ui/PhotoProcessActivity.java @@ -9,7 +9,7 @@ import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; -import android.support.annotation.Nullable; +import androidx.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -49,11 +49,13 @@ import java.util.Date; import java.util.List; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + import butterknife.ButterKnife; -import butterknife.InjectView; -import de.greenrobot.event.EventBus; -import it.sephiroth.android.library.widget.HListView; -import jp.co.cyberagent.android.gpuimage.GPUImageFilter; +import butterknife.BindView; +import org.greenrobot.eventbus.EventBus; +import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter; import jp.co.cyberagent.android.gpuimage.GPUImageView; /** @@ -65,22 +67,22 @@ public class PhotoProcessActivity extends CameraBaseActivity { //滤镜图片 - @InjectView(R.id.gpuimage) + @BindView(R.id.gpuimage) GPUImageView mGPUImageView; //绘图区域 - @InjectView(R.id.drawing_view_container) + @BindView(R.id.drawing_view_container) ViewGroup drawArea; //底部按钮 - @InjectView(R.id.sticker_btn) + @BindView(R.id.sticker_btn) TextView stickerBtn; - @InjectView(R.id.filter_btn) + @BindView(R.id.filter_btn) TextView filterBtn; - @InjectView(R.id.text_btn) + @BindView(R.id.text_btn) TextView labelBtn; //工具区 - @InjectView(R.id.list_tools) - HListView bottomToolBar; - @InjectView(R.id.toolbar_area) + @BindView(R.id.list_tools) + RecyclerView bottomToolBar; + @BindView(R.id.toolbar_area) ViewGroup toolArea; private MyImageViewDrawableOverlay mImageView; private LabelSelector labelSelector; @@ -103,7 +105,7 @@ public class PhotoProcessActivity extends CameraBaseActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_process); - ButterKnife.inject(this); + ButterKnife.bind(this); EffectUtil.clear(); initView(); initEvent(); @@ -346,23 +348,20 @@ private boolean setCurrentBtn(TextView btn) { //初始化贴图 private void initStickerToolBar(){ - bottomToolBar.setAdapter(new StickerToolAdapter(PhotoProcessActivity.this, EffectUtil.addonList)); - bottomToolBar.setOnItemClickListener(new it.sephiroth.android.library.widget.AdapterView.OnItemClickListener() { - - @Override - public void onItemClick(it.sephiroth.android.library.widget.AdapterView arg0, - View arg1, int arg2, long arg3) { - labelSelector.hide(); - Addon sticker = EffectUtil.addonList.get(arg2); - EffectUtil.addStickerImage(mImageView, PhotoProcessActivity.this, sticker, - new EffectUtil.StickerCallback() { - @Override - public void onRemoveSticker(Addon sticker) { - labelSelector.hide(); - } - }); - } + bottomToolBar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); + StickerToolAdapter adapter = new StickerToolAdapter(PhotoProcessActivity.this, EffectUtil.addonList); + adapter.setOnItemClickListener(position -> { + labelSelector.hide(); + Addon sticker = EffectUtil.addonList.get(position); + EffectUtil.addStickerImage(mImageView, PhotoProcessActivity.this, sticker, + new EffectUtil.StickerCallback() { + @Override + public void onRemoveSticker(Addon sticker) { + labelSelector.hide(); + } + }); }); + bottomToolBar.setAdapter(adapter); setCurrentBtn(stickerBtn); } @@ -370,25 +369,18 @@ public void onRemoveSticker(Addon sticker) { //初始化滤镜 private void initFilterToolBar(){ final List filters = EffectService.getInst().getLocalFilters(); - final FilterAdapter adapter = new FilterAdapter(PhotoProcessActivity.this, filters,smallImageBackgroud); - bottomToolBar.setAdapter(adapter); - bottomToolBar.setOnItemClickListener(new it.sephiroth.android.library.widget.AdapterView.OnItemClickListener() { - @Override - public void onItemClick(it.sephiroth.android.library.widget.AdapterView arg0, View arg1, int arg2, long arg3) { - labelSelector.hide(); - if (adapter.getSelectFilter() != arg2) { - adapter.setSelectFilter(arg2); - GPUImageFilter filter = GPUImageFilterTools.createFilterForType( - PhotoProcessActivity.this, filters.get(arg2).getType()); - mGPUImageView.setFilter(filter); - GPUImageFilterTools.FilterAdjuster mFilterAdjuster = new GPUImageFilterTools.FilterAdjuster(filter); - //可调节颜色的滤镜 - if (mFilterAdjuster.canAdjust()) { - //mFilterAdjuster.adjust(100); 给可调节的滤镜选一个合适的值 - } - } + bottomToolBar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); + final FilterAdapter adapter = new FilterAdapter(PhotoProcessActivity.this, filters, smallImageBackgroud); + adapter.setOnItemClickListener(position -> { + labelSelector.hide(); + if (adapter.getSelectFilter() != position) { + adapter.setSelectFilter(position); + GPUImageFilter filter = GPUImageFilterTools.createFilterForType( + PhotoProcessActivity.this, filters.get(position).getType()); + mGPUImageView.setFilter(filter); } }); + bottomToolBar.setAdapter(adapter); } //添加标签 diff --git a/app/src/main/java/com/stickercamera/app/camera/util/EffectUtil.java b/app/src/main/java/com/stickercamera/app/camera/util/EffectUtil.java index 2f3ab57..7e631c8 100644 --- a/app/src/main/java/com/stickercamera/app/camera/util/EffectUtil.java +++ b/app/src/main/java/com/stickercamera/app/camera/util/EffectUtil.java @@ -218,7 +218,7 @@ private static void applyOnSave(Canvas mCanvas, ImageViewTouch processImage,MyHi Matrix matrix = new Matrix(processImage.getImageMatrix()); if (!matrix.invert(matrix)) { } - int saveCount = mCanvas.save(Canvas.MATRIX_SAVE_FLAG); + int saveCount = mCanvas.save(); mCanvas.concat(rotateMatrix); stickerDrawable.setDropShadow(false); diff --git a/app/src/main/java/com/stickercamera/app/camera/util/GPUImageFilterTools.java b/app/src/main/java/com/stickercamera/app/camera/util/GPUImageFilterTools.java index 2a0d238..3b7dd56 100755 --- a/app/src/main/java/com/stickercamera/app/camera/util/GPUImageFilterTools.java +++ b/app/src/main/java/com/stickercamera/app/camera/util/GPUImageFilterTools.java @@ -17,652 +17,65 @@ package com.stickercamera.app.camera.util; import android.content.Context; -import android.graphics.BitmapFactory; -import android.graphics.PointF; import com.github.skykai.stickercamera.R; -import jp.co.cyberagent.android.gpuimage.GPUImage3x3ConvolutionFilter; -import jp.co.cyberagent.android.gpuimage.GPUImage3x3TextureSamplingFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageAddBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageAlphaBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageBoxBlurFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageBrightnessFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageBulgeDistortionFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageCGAColorspaceFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageChromaKeyBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageColorBalanceFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageColorBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageColorBurnBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageColorDodgeBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageColorInvertFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageContrastFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageCrosshatchFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageDarkenBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageDifferenceBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageDilationFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageDirectionalSobelEdgeDetectionFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageDissolveBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageDivideBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageEmbossFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageExclusionBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageExposureFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageFalseColorFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageFilterGroup; -import jp.co.cyberagent.android.gpuimage.GPUImageGammaFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageGaussianBlurFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageGlassSphereFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageGrayscaleFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageHardLightBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageHazeFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageHighlightShadowFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageHueBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageHueFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageKuwaharaFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageLaplacianFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageLightenBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageLinearBurnBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageLookupFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageLuminosityBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageMonochromeFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageMultiplyBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageNonMaximumSuppressionFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageNormalBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageOpacityFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageOverlayBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImagePixelationFilter; -import jp.co.cyberagent.android.gpuimage.GPUImagePosterizeFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageRGBDilationFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageRGBFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSaturationBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSaturationFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageScreenBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSepiaFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSharpenFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSketchFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSmoothToonFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSobelEdgeDetection; -import jp.co.cyberagent.android.gpuimage.GPUImageSoftLightBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSourceOverBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSphereRefractionFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSubtractBlendFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageSwirlFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageToneCurveFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageToonFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageTwoInputFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageVignetteFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageWeakPixelInclusionFilter; -import jp.co.cyberagent.android.gpuimage.GPUImageWhiteBalanceFilter; - -import java.util.LinkedList; -import java.util.List; +import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter; +import jp.co.cyberagent.android.gpuimage.filter.GPUImageToneCurveFilter; +/** + * 滤镜工厂。本 app 仅使用「原始」滤镜与 res/raw 下的 .acv 色调曲线滤镜 + * (见 {@link com.stickercamera.app.camera.EffectService}),因此这里只保留 + * NORMAL + ACV_* 两类。 + */ public class GPUImageFilterTools { public static GPUImageFilter createFilterForType(final Context context, final FilterType type) { - GPUImageToneCurveFilter curveFilter = new GPUImageToneCurveFilter(); switch (type) { case NORMAL: return new GPUImageFilter(); case ACV_AIMEI: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.aimei)); - return curveFilter; + return createCurveFilter(context, R.raw.aimei); case ACV_DANLAN: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.danlan)); - return curveFilter; + return createCurveFilter(context, R.raw.danlan); case ACV_DANHUANG: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.danhuang)); - return curveFilter; - case ACV_FUGU: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.fugu)); - return curveFilter; + return createCurveFilter(context, R.raw.danhuang); + case ACV_FUGU: + return createCurveFilter(context, R.raw.fugu); case ACV_GAOLENG: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.gaoleng)); - return curveFilter; + return createCurveFilter(context, R.raw.gaoleng); case ACV_HUAIJIU: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.huaijiu)); - return curveFilter; + return createCurveFilter(context, R.raw.huaijiu); case ACV_JIAOPIAN: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.jiaopian)); - return curveFilter; + return createCurveFilter(context, R.raw.jiaopian); case ACV_KEAI: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.keai)); - return curveFilter; + return createCurveFilter(context, R.raw.keai); case ACV_LOMO: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.lomo)); - return curveFilter; + return createCurveFilter(context, R.raw.lomo); case ACV_MORENJIAQIANG: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.morenjiaqiang)); - return curveFilter; + return createCurveFilter(context, R.raw.morenjiaqiang); case ACV_NUANXIN: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.nuanxin)); - return curveFilter; + return createCurveFilter(context, R.raw.nuanxin); case ACV_QINGXIN: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.qingxin)); - return curveFilter; + return createCurveFilter(context, R.raw.qingxin); case ACV_RIXI: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.rixi)); - return curveFilter; + return createCurveFilter(context, R.raw.rixi); case ACV_WENNUAN: - curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.wennuan)); - return curveFilter; - case CONTRAST: - return new GPUImageContrastFilter(2.0f); - case GAMMA: - return new GPUImageGammaFilter(2.0f); - case INVERT: - return new GPUImageColorInvertFilter(); - case PIXELATION: - return new GPUImagePixelationFilter(); - case HUE: - return new GPUImageHueFilter(90.0f); - case BRIGHTNESS: - return new GPUImageBrightnessFilter(1.5f); - case GRAYSCALE: - return new GPUImageGrayscaleFilter(); - case SEPIA: - return new GPUImageSepiaFilter(); - case SHARPEN: - GPUImageSharpenFilter sharpness = new GPUImageSharpenFilter(); - sharpness.setSharpness(2.0f); - return sharpness; - case SOBEL_EDGE_DETECTION: - return new GPUImageSobelEdgeDetection(); - case THREE_X_THREE_CONVOLUTION: - GPUImage3x3ConvolutionFilter convolution = new GPUImage3x3ConvolutionFilter(); - convolution.setConvolutionKernel(new float[] { -1.0f, 0.0f, 1.0f, -2.0f, 0.0f, - 2.0f, -1.0f, 0.0f, 1.0f }); - return convolution; - case EMBOSS: - return new GPUImageEmbossFilter(); - case POSTERIZE: - return new GPUImagePosterizeFilter(); - case FILTER_GROUP: - List filters = new LinkedList(); - filters.add(new GPUImageContrastFilter()); - filters.add(new GPUImageDirectionalSobelEdgeDetectionFilter()); - filters.add(new GPUImageGrayscaleFilter()); - return new GPUImageFilterGroup(filters); - case SATURATION: - return new GPUImageSaturationFilter(1.0f); - case EXPOSURE: - return new GPUImageExposureFilter(0.0f); - case HIGHLIGHT_SHADOW: - return new GPUImageHighlightShadowFilter(0.0f, 1.0f); - case MONOCHROME: - return new GPUImageMonochromeFilter(1.0f, new float[] { 0.6f, 0.45f, 0.3f, 1.0f }); - case OPACITY: - return new GPUImageOpacityFilter(1.0f); - case RGB: - return new GPUImageRGBFilter(1.0f, 1.0f, 1.0f); - case WHITE_BALANCE: - return new GPUImageWhiteBalanceFilter(5000.0f, 0.0f); - case VIGNETTE: - PointF centerPoint = new PointF(); - centerPoint.x = 0.5f; - centerPoint.y = 0.5f; - return new GPUImageVignetteFilter(centerPoint, new float[] { 0.0f, 0.0f, 0.0f }, - 0.3f, 0.75f); - case TONE_CURVE: - GPUImageToneCurveFilter toneCurveFilter = new GPUImageToneCurveFilter(); - toneCurveFilter.setFromCurveFileInputStream(context.getResources().openRawResource( - R.raw.tone_cuver_sample)); - return toneCurveFilter; - case BLEND_DIFFERENCE: - return createBlendFilter(context, GPUImageDifferenceBlendFilter.class); - case BLEND_SOURCE_OVER: - return createBlendFilter(context, GPUImageSourceOverBlendFilter.class); - case BLEND_COLOR_BURN: - return createBlendFilter(context, GPUImageColorBurnBlendFilter.class); - case BLEND_COLOR_DODGE: - return createBlendFilter(context, GPUImageColorDodgeBlendFilter.class); - case BLEND_DARKEN: - return createBlendFilter(context, GPUImageDarkenBlendFilter.class); - case BLEND_DISSOLVE: - return createBlendFilter(context, GPUImageDissolveBlendFilter.class); - case BLEND_EXCLUSION: - return createBlendFilter(context, GPUImageExclusionBlendFilter.class); - - case BLEND_HARD_LIGHT: - return createBlendFilter(context, GPUImageHardLightBlendFilter.class); - case BLEND_LIGHTEN: - return createBlendFilter(context, GPUImageLightenBlendFilter.class); - case BLEND_ADD: - return createBlendFilter(context, GPUImageAddBlendFilter.class); - case BLEND_DIVIDE: - return createBlendFilter(context, GPUImageDivideBlendFilter.class); - case BLEND_MULTIPLY: - return createBlendFilter(context, GPUImageMultiplyBlendFilter.class); - case BLEND_OVERLAY: - return createBlendFilter(context, GPUImageOverlayBlendFilter.class); - case BLEND_SCREEN: - return createBlendFilter(context, GPUImageScreenBlendFilter.class); - case BLEND_ALPHA: - return createBlendFilter(context, GPUImageAlphaBlendFilter.class); - case BLEND_COLOR: - return createBlendFilter(context, GPUImageColorBlendFilter.class); - case BLEND_HUE: - return createBlendFilter(context, GPUImageHueBlendFilter.class); - case BLEND_SATURATION: - return createBlendFilter(context, GPUImageSaturationBlendFilter.class); - case BLEND_LUMINOSITY: - return createBlendFilter(context, GPUImageLuminosityBlendFilter.class); - case BLEND_LINEAR_BURN: - return createBlendFilter(context, GPUImageLinearBurnBlendFilter.class); - case BLEND_SOFT_LIGHT: - return createBlendFilter(context, GPUImageSoftLightBlendFilter.class); - case BLEND_SUBTRACT: - return createBlendFilter(context, GPUImageSubtractBlendFilter.class); - case BLEND_CHROMA_KEY: - return createBlendFilter(context, GPUImageChromaKeyBlendFilter.class); - case BLEND_NORMAL: - return createBlendFilter(context, GPUImageNormalBlendFilter.class); - - case LOOKUP_AMATORKA: - GPUImageLookupFilter amatorka = new GPUImageLookupFilter(); - amatorka.setBitmap(BitmapFactory.decodeResource(context.getResources(), - R.drawable.lookup_amatorka)); - return amatorka; - case GAUSSIAN_BLUR: - return new GPUImageGaussianBlurFilter(); - case CROSSHATCH: - return new GPUImageCrosshatchFilter(); - - case BOX_BLUR: - return new GPUImageBoxBlurFilter(); - case CGA_COLORSPACE: - return new GPUImageCGAColorspaceFilter(); - case DILATION: - return new GPUImageDilationFilter(); - case KUWAHARA: - return new GPUImageKuwaharaFilter(); - case RGB_DILATION: - return new GPUImageRGBDilationFilter(); - case SKETCH: - return new GPUImageSketchFilter(); - case TOON: - return new GPUImageToonFilter(); - case SMOOTH_TOON: - return new GPUImageSmoothToonFilter(); - - case BULGE_DISTORTION: - return new GPUImageBulgeDistortionFilter(); - case GLASS_SPHERE: - return new GPUImageGlassSphereFilter(); - case HAZE: - return new GPUImageHazeFilter(); - case LAPLACIAN: - return new GPUImageLaplacianFilter(); - case NON_MAXIMUM_SUPPRESSION: - return new GPUImageNonMaximumSuppressionFilter(); - case SPHERE_REFRACTION: - return new GPUImageSphereRefractionFilter(); - case SWIRL: - return new GPUImageSwirlFilter(); - case WEAK_PIXEL_INCLUSION: - return new GPUImageWeakPixelInclusionFilter(); - case FALSE_COLOR: - return new GPUImageFalseColorFilter(); - case COLOR_BALANCE: - return new GPUImageColorBalanceFilter(); - + return createCurveFilter(context, R.raw.wennuan); default: throw new IllegalStateException("No filter of that type!"); } - - } - - private static GPUImageFilter createBlendFilter(Context context, - Class filterClass) { - try { - GPUImageTwoInputFilter filter = filterClass.newInstance(); - filter.setBitmap(BitmapFactory.decodeResource(context.getResources(), - R.drawable.ic_launcher)); - return filter; - } catch (Exception e) { - e.printStackTrace(); - return null; - } } - public interface OnGpuImageFilterChosenListener { - void onGpuImageFilterChosenListener(GPUImageFilter filter); + private static GPUImageToneCurveFilter createCurveFilter(final Context context, final int rawResId) { + GPUImageToneCurveFilter curveFilter = new GPUImageToneCurveFilter(); + curveFilter.setFromCurveFileInputStream(context.getResources().openRawResource(rawResId)); + return curveFilter; } public enum FilterType { - NORMAL, ACV_AIMEI, ACV_DANLAN, ACV_DANHUANG, ACV_FUGU, ACV_GAOLENG, ACV_HUAIJIU, ACV_JIAOPIAN, ACV_KEAI, ACV_LOMO, ACV_MORENJIAQIANG, ACV_NUANXIN, ACV_QINGXIN, ACV_RIXI, ACV_WENNUAN, CONTRAST, GRAYSCALE, SHARPEN, SEPIA, SOBEL_EDGE_DETECTION, THREE_X_THREE_CONVOLUTION, FILTER_GROUP, EMBOSS, POSTERIZE, GAMMA, BRIGHTNESS, INVERT, HUE, PIXELATION, SATURATION, EXPOSURE, HIGHLIGHT_SHADOW, MONOCHROME, OPACITY, RGB, WHITE_BALANCE, VIGNETTE, TONE_CURVE, BLEND_COLOR_BURN, BLEND_COLOR_DODGE, BLEND_DARKEN, BLEND_DIFFERENCE, BLEND_DISSOLVE, BLEND_EXCLUSION, BLEND_SOURCE_OVER, BLEND_HARD_LIGHT, BLEND_LIGHTEN, BLEND_ADD, BLEND_DIVIDE, BLEND_MULTIPLY, BLEND_OVERLAY, BLEND_SCREEN, BLEND_ALPHA, BLEND_COLOR, BLEND_HUE, BLEND_SATURATION, BLEND_LUMINOSITY, BLEND_LINEAR_BURN, BLEND_SOFT_LIGHT, BLEND_SUBTRACT, BLEND_CHROMA_KEY, BLEND_NORMAL, LOOKUP_AMATORKA, GAUSSIAN_BLUR, CROSSHATCH, BOX_BLUR, CGA_COLORSPACE, DILATION, KUWAHARA, RGB_DILATION, SKETCH, TOON, SMOOTH_TOON, BULGE_DISTORTION, GLASS_SPHERE, HAZE, LAPLACIAN, NON_MAXIMUM_SUPPRESSION, SPHERE_REFRACTION, SWIRL, WEAK_PIXEL_INCLUSION, FALSE_COLOR, COLOR_BALANCE - } - - private static class FilterList { - public List names = new LinkedList(); - public List filters = new LinkedList(); - - public void addFilter(final String name, final FilterType filter) { - names.add(name); - filters.add(filter); - } - } - - public static class FilterAdjuster { - private final Adjuster adjuster; - - public FilterAdjuster(final GPUImageFilter filter) { - if (filter instanceof GPUImageSharpenFilter) { - adjuster = new SharpnessAdjuster().filter(filter); - } else if (filter instanceof GPUImageSepiaFilter) { - adjuster = new SepiaAdjuster().filter(filter); - } else if (filter instanceof GPUImageContrastFilter) { - adjuster = new ContrastAdjuster().filter(filter); - } else if (filter instanceof GPUImageGammaFilter) { - adjuster = new GammaAdjuster().filter(filter); - } else if (filter instanceof GPUImageBrightnessFilter) { - adjuster = new BrightnessAdjuster().filter(filter); - } else if (filter instanceof GPUImageSobelEdgeDetection) { - adjuster = new SobelAdjuster().filter(filter); - } else if (filter instanceof GPUImageEmbossFilter) { - adjuster = new EmbossAdjuster().filter(filter); - } else if (filter instanceof GPUImage3x3TextureSamplingFilter) { - adjuster = new GPU3x3TextureAdjuster().filter(filter); - } else if (filter instanceof GPUImageHueFilter) { - adjuster = new HueAdjuster().filter(filter); - } else if (filter instanceof GPUImagePosterizeFilter) { - adjuster = new PosterizeAdjuster().filter(filter); - } else if (filter instanceof GPUImagePixelationFilter) { - adjuster = new PixelationAdjuster().filter(filter); - } else if (filter instanceof GPUImageSaturationFilter) { - adjuster = new SaturationAdjuster().filter(filter); - } else if (filter instanceof GPUImageExposureFilter) { - adjuster = new ExposureAdjuster().filter(filter); - } else if (filter instanceof GPUImageHighlightShadowFilter) { - adjuster = new HighlightShadowAdjuster().filter(filter); - } else if (filter instanceof GPUImageMonochromeFilter) { - adjuster = new MonochromeAdjuster().filter(filter); - } else if (filter instanceof GPUImageOpacityFilter) { - adjuster = new OpacityAdjuster().filter(filter); - } else if (filter instanceof GPUImageRGBFilter) { - adjuster = new RGBAdjuster().filter(filter); - } else if (filter instanceof GPUImageWhiteBalanceFilter) { - adjuster = new WhiteBalanceAdjuster().filter(filter); - } else if (filter instanceof GPUImageVignetteFilter) { - adjuster = new VignetteAdjuster().filter(filter); - } else if (filter instanceof GPUImageDissolveBlendFilter) { - adjuster = new DissolveBlendAdjuster().filter(filter); - } else if (filter instanceof GPUImageGaussianBlurFilter) { - adjuster = new GaussianBlurAdjuster().filter(filter); - } else if (filter instanceof GPUImageCrosshatchFilter) { - adjuster = new CrosshatchBlurAdjuster().filter(filter); - } else if (filter instanceof GPUImageBulgeDistortionFilter) { - adjuster = new BulgeDistortionAdjuster().filter(filter); - } else if (filter instanceof GPUImageGlassSphereFilter) { - adjuster = new GlassSphereAdjuster().filter(filter); - } else if (filter instanceof GPUImageHazeFilter) { - adjuster = new HazeAdjuster().filter(filter); - } else if (filter instanceof GPUImageSphereRefractionFilter) { - adjuster = new SphereRefractionAdjuster().filter(filter); - } else if (filter instanceof GPUImageSwirlFilter) { - adjuster = new SwirlAdjuster().filter(filter); - } else if (filter instanceof GPUImageColorBalanceFilter) { - adjuster = new ColorBalanceAdjuster().filter(filter); - } else { - adjuster = null; - } - } - - public boolean canAdjust() { - return adjuster != null; - } - - public void adjust(final int percentage) { - if (adjuster != null) { - adjuster.adjust(percentage); - } - } - - private abstract class Adjuster { - private T filter; - - @SuppressWarnings("unchecked") - public Adjuster filter(final GPUImageFilter filter) { - this.filter = (T) filter; - return this; - } - - public T getFilter() { - return filter; - } - - public abstract void adjust(int percentage); - - protected float range(final int percentage, final float start, final float end) { - return (end - start) * percentage / 100.0f + start; - } - - protected int range(final int percentage, final int start, final int end) { - return (end - start) * percentage / 100 + start; - } - } - - private class SharpnessAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setSharpness(range(percentage, -4.0f, 4.0f)); - } - } - - private class PixelationAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setPixel(range(percentage, 1.0f, 100.0f)); - } - } - - private class HueAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setHue(range(percentage, 0.0f, 360.0f)); - } - } - - private class ContrastAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setContrast(range(percentage, 0.0f, 2.0f)); - } - } - - private class GammaAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setGamma(range(percentage, 0.0f, 3.0f)); - } - } - - private class BrightnessAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setBrightness(range(percentage, -1.0f, 1.0f)); - } - } - - private class SepiaAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setIntensity(range(percentage, 0.0f, 2.0f)); - } - } - - private class SobelAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setLineSize(range(percentage, 0.0f, 5.0f)); - } - } - - private class EmbossAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setIntensity(range(percentage, 0.0f, 4.0f)); - } - } - - private class PosterizeAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - // In theorie to 256, but only first 50 are interesting - getFilter().setColorLevels(range(percentage, 1, 50)); - } - } - - private class GPU3x3TextureAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setLineSize(range(percentage, 0.0f, 5.0f)); - } - } - - private class SaturationAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setSaturation(range(percentage, 0.0f, 2.0f)); - } - } - - private class ExposureAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setExposure(range(percentage, -10.0f, 10.0f)); - } - } - - private class HighlightShadowAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setShadows(range(percentage, 0.0f, 1.0f)); - getFilter().setHighlights(range(percentage, 0.0f, 1.0f)); - } - } - - private class MonochromeAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setIntensity(range(percentage, 0.0f, 1.0f)); - //getFilter().setColor(new float[]{0.6f, 0.45f, 0.3f, 1.0f}); - } - } - - private class OpacityAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setOpacity(range(percentage, 0.0f, 1.0f)); - } - } - - private class RGBAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setRed(range(percentage, 0.0f, 1.0f)); - //getFilter().setGreen(range(percentage, 0.0f, 1.0f)); - //getFilter().setBlue(range(percentage, 0.0f, 1.0f)); - } - } - - private class WhiteBalanceAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setTemperature(range(percentage, 2000.0f, 8000.0f)); - //getFilter().setTint(range(percentage, -100.0f, 100.0f)); - } - } - - private class VignetteAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setVignetteStart(range(percentage, 0.0f, 1.0f)); - } - } - - private class DissolveBlendAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setMix(range(percentage, 0.0f, 1.0f)); - } - } - - private class GaussianBlurAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setBlurSize(range(percentage, 0.0f, 1.0f)); - } - } - - private class CrosshatchBlurAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setCrossHatchSpacing(range(percentage, 0.0f, 0.06f)); - getFilter().setLineWidth(range(percentage, 0.0f, 0.006f)); - } - } - - private class BulgeDistortionAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setRadius(range(percentage, 0.0f, 1.0f)); - getFilter().setScale(range(percentage, -1.0f, 1.0f)); - } - } - - private class GlassSphereAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setRadius(range(percentage, 0.0f, 1.0f)); - } - } - - private class HazeAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setDistance(range(percentage, -0.3f, 0.3f)); - getFilter().setSlope(range(percentage, -0.3f, 0.3f)); - } - } - - private class SphereRefractionAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setRadius(range(percentage, 0.0f, 1.0f)); - } - } - - private class SwirlAdjuster extends Adjuster { - @Override - public void adjust(final int percentage) { - getFilter().setAngle(range(percentage, 0.0f, 2.0f)); - } - } - - private class ColorBalanceAdjuster extends Adjuster { - - @Override - public void adjust(int percentage) { - getFilter().setMidtones( - new float[] { range(percentage, 0.0f, 1.0f), range(percentage / 2, 0.0f, 1.0f), - range(percentage / 3, 0.0f, 1.0f) }); - } - } + NORMAL, ACV_AIMEI, ACV_DANLAN, ACV_DANHUANG, ACV_FUGU, ACV_GAOLENG, ACV_HUAIJIU, + ACV_JIAOPIAN, ACV_KEAI, ACV_LOMO, ACV_MORENJIAQIANG, ACV_NUANXIN, ACV_QINGXIN, + ACV_RIXI, ACV_WENNUAN } } diff --git a/app/src/main/java/com/stickercamera/app/ui/EditTextActivity.java b/app/src/main/java/com/stickercamera/app/ui/EditTextActivity.java index 0325333..d7b0a8a 100755 --- a/app/src/main/java/com/stickercamera/app/ui/EditTextActivity.java +++ b/app/src/main/java/com/stickercamera/app/ui/EditTextActivity.java @@ -17,7 +17,7 @@ import com.stickercamera.base.BaseActivity; import butterknife.ButterKnife; -import butterknife.InjectView; +import butterknife.BindView; /** @@ -30,9 +30,9 @@ public class EditTextActivity extends BaseActivity { private final static int MAX = 10; private int maxlength = MAX; - @InjectView(R.id.text_input) + @BindView(R.id.text_input) EditText contentView; - @InjectView(R.id.tag_input_tips) + @BindView(R.id.tag_input_tips) TextView numberTips; public static void openTextEdit(Activity mContext, String defaultStr,int maxLength, int reqCode) { @@ -48,7 +48,7 @@ public static void openTextEdit(Activity mContext, String defaultStr,int maxLeng public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_text); - ButterKnife.inject(this); + ButterKnife.bind(this); maxlength = getIntent().getIntExtra(AppConstants.PARAM_MAX_SIZE, MAX); String defaultStr = getIntent().getStringExtra(AppConstants.PARAM_EDIT_TEXT); diff --git a/app/src/main/java/com/stickercamera/app/ui/MainActivity.java b/app/src/main/java/com/stickercamera/app/ui/MainActivity.java index fc6c585..3941674 100644 --- a/app/src/main/java/com/stickercamera/app/ui/MainActivity.java +++ b/app/src/main/java/com/stickercamera/app/ui/MainActivity.java @@ -1,12 +1,12 @@ package com.stickercamera.app.ui; import android.graphics.BitmapFactory; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.app.AppCompatActivity; +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; +import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; -import android.support.v7.widget.CardView; -import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.RecyclerView; +import androidx.cardview.widget.CardView; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; @@ -24,7 +24,7 @@ import com.common.util.StringUtils; import com.customview.LabelView; import com.github.skykai.stickercamera.R; -import com.melnykov.fab.FloatingActionButton; +import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.stickercamera.App; import com.stickercamera.AppConstants; import com.stickercamera.app.camera.CameraManager; @@ -38,8 +38,10 @@ import java.util.List; import butterknife.ButterKnife; -import butterknife.InjectView; -import de.greenrobot.event.EventBus; +import butterknife.BindView; +import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; /** * 主界面 @@ -49,9 +51,9 @@ */ public class MainActivity extends BaseActivity { - @InjectView(R.id.fab) + @BindView(R.id.fab) FloatingActionButton fab; - @InjectView(R.id.recycler_view) + @BindView(R.id.recycler_view) RecyclerView mRecyclerView; private List feedList; private PictureAdapter mAdapter; @@ -61,7 +63,7 @@ public class MainActivity extends BaseActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); - ButterKnife.inject(this); + ButterKnife.bind(this); EventBus.getDefault().register(this); initView(); @@ -79,7 +81,8 @@ protected void onCreate(Bundle savedInstanceState) { } - public void onEventMainThread(FeedItem feedItem) { + @Subscribe(threadMode = ThreadMode.MAIN) + public void onEvent(FeedItem feedItem) { if (feedList == null) { feedList = new ArrayList(); } @@ -186,9 +189,9 @@ public void run() { } public static class ViewHolder extends RecyclerView.ViewHolder { - @InjectView(R.id.pictureLayout) + @BindView(R.id.pictureLayout) RelativeLayout pictureLayout; - @InjectView(R.id.picture) + @BindView(R.id.picture) ImageView picture; private List tagList = new ArrayList<>(); @@ -206,7 +209,7 @@ public void setTagList(List tagList) { public ViewHolder(View itemView) { super(itemView); - ButterKnife.inject(this, itemView); + ButterKnife.bind(this, itemView); } } diff --git a/app/src/main/java/com/stickercamera/base/BaseActivity.java b/app/src/main/java/com/stickercamera/base/BaseActivity.java index 74d5328..35d0a02 100644 --- a/app/src/main/java/com/stickercamera/base/BaseActivity.java +++ b/app/src/main/java/com/stickercamera/base/BaseActivity.java @@ -1,21 +1,20 @@ package com.stickercamera.base; -import android.annotation.TargetApi; import android.app.Activity; import android.content.DialogInterface; -import android.os.Build; import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; +import androidx.appcompat.app.AppCompatActivity; import android.util.TypedValue; import android.view.Menu; import android.view.View; -import android.view.WindowManager; + +import androidx.core.graphics.Insets; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowCompat; +import androidx.core.view.WindowInsetsCompat; import com.github.skykai.stickercamera.R; import com.customview.CommonTitleBar; -import com.readystatesoftware.systembartint.SystemBarTintManager; - -import butterknife.ButterKnife; /** * Created by sky on 15/7/6. @@ -35,19 +34,8 @@ protected void onCreate(Bundle savedInstanceState) { } - @TargetApi(19) private void initWindow() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); - getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); - SystemBarTintManager tintManager = new SystemBarTintManager(this); - tintManager.setStatusBarTintColor(getStatusBarColor()); - tintManager.setStatusBarTintEnabled(true); - } - } - - public int getStatusBarColor() { - return getColorPrimary(); + WindowCompat.setDecorFitsSystemWindows(getWindow(), false); } public int getColorPrimary() { @@ -59,6 +47,14 @@ public int getColorPrimary() { @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); + final View content = findViewById(android.R.id.content); + if (content != null) { + ViewCompat.setOnApplyWindowInsetsListener(content, (v, insets) -> { + Insets bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); + v.setPadding(bars.left, bars.top, bars.right, bars.bottom); + return insets; + }); + } titleBar = (CommonTitleBar) findViewById(R.id.title_layout); if (titleBar != null) titleBar.setLeftBtnOnclickListener(new View.OnClickListener() { diff --git a/app/src/main/java/com/stickercamera/base/BaseFragmentActivity.java b/app/src/main/java/com/stickercamera/base/BaseFragmentActivity.java deleted file mode 100644 index d973f10..0000000 --- a/app/src/main/java/com/stickercamera/base/BaseFragmentActivity.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.stickercamera.base; - -import android.support.v4.app.FragmentActivity; -import android.view.View; - -import com.customview.CommonTitleBar; -import com.github.skykai.stickercamera.R; - -/** - * Created by sky on 15/7/6. - */ -public class BaseFragmentActivity extends FragmentActivity { - - protected CommonTitleBar titleBar; - - @Override - public void setContentView(int layoutResID) { - super.setContentView(layoutResID); - //titleBar = (CommonTitleBar) findViewById(R.id.title_layout); - if (titleBar != null) - titleBar.setLeftBtnOnclickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - } -} diff --git a/app/src/main/res/drawable-hdpi/lookup_amatorka.png b/app/src/main/res/drawable-hdpi/lookup_amatorka.png deleted file mode 100755 index 4a2cc8a..0000000 Binary files a/app/src/main/res/drawable-hdpi/lookup_amatorka.png and /dev/null differ diff --git a/app/src/main/res/layout/activity_album.xml b/app/src/main/res/layout/activity_album.xml index 471a0a4..ced9b27 100644 --- a/app/src/main/res/layout/activity_album.xml +++ b/app/src/main/res/layout/activity_album.xml @@ -19,7 +19,7 @@ app:pstsIndicatorHeight="2dp" app:pstsIndicatorColor="@color/pink"/> - - + android:overScrollMode="always"/> diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 794929e..a17c35b 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -9,7 +9,7 @@ app:titleTxt="贴纸相机" /> - - + app:backgroundTint="?attr/colorPrimary" + app:rippleColor="?attr/colorPrimaryDark" + app:tint="@android:color/white" /> diff --git a/app/src/main/res/layout/item_picture.xml b/app/src/main/res/layout/item_picture.xml index e6ed65e..aff6490 100644 --- a/app/src/main/res/layout/item_picture.xml +++ b/app/src/main/res/layout/item_picture.xml @@ -1,5 +1,5 @@ - - \ No newline at end of file + \ No newline at end of file diff --git a/app/src/main/res/raw/tone_cuver_sample.acv b/app/src/main/res/raw/tone_cuver_sample.acv deleted file mode 100755 index 5b6c955..0000000 Binary files a/app/src/main/res/raw/tone_cuver_sample.acv and /dev/null differ diff --git a/build.gradle b/build.gradle index 6b77860..7ac1d6d 100644 --- a/build.gradle +++ b/build.gradle @@ -2,23 +2,13 @@ buildscript { repositories { - jcenter() - + google() + mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.3' - classpath 'me.tatarka:gradle-retrolambda:3.1.0' + classpath 'com.android.tools.build:gradle:8.11.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } - - -} - -allprojects { - repositories { - jcenter() - maven { url("https://oss.sonatype.org/content/repositories/snapshots/") } - } } diff --git a/docs/superpowers/plans/2026-06-18-build-toolchain-modernization.md b/docs/superpowers/plans/2026-06-18-build-toolchain-modernization.md new file mode 100644 index 0000000..0049ea0 --- /dev/null +++ b/docs/superpowers/plans/2026-06-18-build-toolchain-modernization.md @@ -0,0 +1,927 @@ +# StickerCamera 编译链现代化 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 把 StickerCamera 的编译链升级到 AGP 8.11 / Gradle 8.13 / JDK 17 / AndroidX,在现代开发机上构建通过并保持原有功能。 + +**Architecture:** 先升级构建系统骨架(wrapper/根/settings/properties),再逐模块(两个 library 可独立验证),最后迁移 :app 源码(AndroidX、ButterKnife、EventBus、死库替换、edge-to-edge),以 `assembleDebug` + 模拟器冒烟为终点验证。 + +**Tech Stack:** Android Gradle Plugin 8.11.x, Gradle 8.13, JDK 17, AndroidX(appcompat/recyclerview/cardview/core/fragment/viewpager/swiperefreshlayout), Material Components, ButterKnife 10.2.3, EventBus 3.3.1, GPUImage(prebuilt .so)。 + +## Global Constraints + +- JDK 运行版本:17;Java source/target:17(移除 Retrolambda)。 +- Gradle:8.13;AGP:8.11.1(以"能稳定支持 compileSdk 36 的最近 AGP 8.11+ / 配套 Gradle"为准)。 +- compileSdk = 36;targetSdk = 36;minSdk = 26。 +- 仓库:仅 `google()` + `mavenCentral()`(+ pluginManagement 加 `gradlePluginPortal()`);禁止 `jcenter()`。 +- AndroidX:`android.useAndroidX=true`;为降低旧工程风险 `android.nonTransitiveRClass=false`(保留传递 R,避免跨模块 R 引用断裂)。 +- 各模块必须声明 `namespace`,并从对应 `AndroidManifest.xml` 删除 `package=`。 +- 依赖配置用 `implementation`/`api`,不用已废弃的 `compile`。 +- 死库一律移除:`systembartint`、melnykov `floatingactionbutton`、rengwuxian `materialedittext`、sephiroth `hlistview`。 +- 模块 namespace:`:app`=`com.github.skykai.stickercamera`,`:Gpu-Image`=`jp.co.cyberagent.android.gpuimage`,`:ImageViewTouch`=`com.imagezoom`。 + +> 说明:本工程无单元测试,"测试周期"为构建/grep 验证。:app 源码在全部迁移完成前无法编译,因此 Task 5–10 的验证用定向 grep/检视,首个完整构建绿灯在 Task 11。 + +--- + +### Task 1: 构建系统骨架 + +**Files:** +- Modify: `gradle/wrapper/gradle-wrapper.properties` +- Modify: `build.gradle`(根) +- Modify: `settings.gradle` +- Modify: `gradle.properties` +- Create: `local.properties`(不入 git) + +- [ ] **Step 1: 升级 Gradle wrapper** + +`gradle/wrapper/gradle-wrapper.properties` 的 `distributionUrl` 改为: + +``` +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +``` + +- [ ] **Step 2: 重写根 `build.gradle`** + +```gradle +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.11.1' + } +} +``` + +(删除 retrolambda classpath、`allprojects {}` 与所有 `jcenter()`。) + +- [ ] **Step 3: 重写 `settings.gradle`** + +```gradle +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + } +} +rootProject.name = "StickerCamera" +include ':app', ':Gpu-Image', ':ImageViewTouch' +``` + +- [ ] **Step 4: 更新 `gradle.properties`** + +追加: + +``` +android.useAndroidX=true +android.nonTransitiveRClass=false +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +``` + +- [ ] **Step 5: 写 `local.properties`** + +``` +sdk.dir=/Users/skykai/Library/Android/sdk +``` + +- [ ] **Step 6: 验证 Gradle/AGP 起得来** + +Run: `JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew --version` +Expected: `Gradle 8.13` + +Run: `JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew projects` +Expected: 列出 `:app`、`:Gpu-Image`、`:ImageViewTouch`,无 jcenter/AGP 报错(模块自身配置报错下一步处理)。 + +- [ ] **Step 7: Commit** + +```bash +git add gradle/wrapper/gradle-wrapper.properties build.gradle settings.gradle gradle.properties +git commit -m "build: 升级 Gradle 8.13 + AGP 8.11 骨架,仓库切换到 google/mavenCentral" +``` + +--- + +### Task 2: ImageViewTouch library 模块 + +**Files:** +- Modify: `ImageViewTouch/build.gradle` +- Modify: `ImageViewTouch/AndroidManifest.xml` + +**Interfaces:** +- Produces: AndroidX 版 `com.imagezoom.ImageViewTouch`(供 :app 使用,API 不变)。 + +- [ ] **Step 1: 重写 `ImageViewTouch/build.gradle`** + +```gradle +apply plugin: 'com.android.library' + +android { + namespace 'com.imagezoom' + compileSdk 36 + + defaultConfig { + minSdk 26 + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + lint { + abortOnError false + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'androidx.appcompat:appcompat:1.7.0' +} +``` + +- [ ] **Step 2: 精简 `ImageViewTouch/AndroidManifest.xml`** + +```xml + + + +``` + +(删除 `package=` 与 `` 块,namespace 已提供包名,避免 library label 合并问题。) + +- [ ] **Step 3: 验证模块独立编译** + +Run: `JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew :ImageViewTouch:assembleDebug` +Expected: `BUILD SUCCESSFUL` + +- [ ] **Step 4: Commit** + +```bash +git add ImageViewTouch/build.gradle ImageViewTouch/AndroidManifest.xml +git commit -m "build(ImageViewTouch): AGP 8 + AndroidX + namespace" +``` + +--- + +### Task 3: Gpu-Image library 模块(含 .so 迁移) + +**Files:** +- Modify: `Gpu-Image/build.gradle` +- Modify: `Gpu-Image/AndroidManifest.xml` +- Delete: `Gpu-Image/libs/armeabi/`、`Gpu-Image/libs/mips/`、`Gpu-Image/libs/mips64/` + +**Interfaces:** +- Produces: AndroidX 版 `jp.co.cyberagent.android.gpuimage.*`(GPUImageView/GPUImageFilter 等,API 不变);`.so` 通过 `jniLibs.srcDirs=['libs']` 打包。 + +- [ ] **Step 1: 删除废弃 ABI** + +```bash +git rm -r Gpu-Image/libs/armeabi Gpu-Image/libs/mips Gpu-Image/libs/mips64 +``` + +保留:`arm64-v8a`、`armeabi-v7a`、`x86`、`x86_64`。 + +- [ ] **Step 2: 重写 `Gpu-Image/build.gradle`** + +```gradle +apply plugin: 'com.android.library' + +android { + namespace 'jp.co.cyberagent.android.gpuimage' + compileSdk 36 + + defaultConfig { + minSdk 26 + } + + sourceSets { + main { + manifest.srcFile 'AndroidManifest.xml' + java.srcDirs = ['src'] + res.srcDirs = ['res'] + assets.srcDirs = ['assets'] + jniLibs.srcDirs = ['libs'] + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + lint { + abortOnError false + } +} +``` + +(沿用非标准 `src/`/`res/` 布局;把原 `jni.srcDirs`/`renderscript`/`aidl` 去掉——本模块只有预编译 `.so`,无 native/rs/aidl 源;`.so` 用 `jniLibs.srcDirs=['libs']` 打包。) + +- [ ] **Step 3: 清理 `Gpu-Image/AndroidManifest.xml`** + +```xml + + + +``` + +(删除 `package=`。) + +- [ ] **Step 4: 验证模块独立编译且打包 .so** + +Run: `JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew :Gpu-Image:assembleDebug` +Expected: `BUILD SUCCESSFUL` + +Run: `unzip -l Gpu-Image/build/outputs/aar/Gpu-Image-debug.aar | grep '\.so'` +Expected: 仅列出 `arm64-v8a`、`armeabi-v7a`、`x86`、`x86_64` 下的 `libgpuimage-library.so` + +- [ ] **Step 5: Commit** + +```bash +git add Gpu-Image/build.gradle Gpu-Image/AndroidManifest.xml Gpu-Image/libs +git commit -m "build(Gpu-Image): AGP 8 + namespace, .so 迁 jniLibs 并裁废弃 ABI" +``` + +--- + +### Task 4: :app 构建脚本与依赖映射 + +**Files:** +- Modify: `app/build.gradle` +- Modify: `app/src/main/AndroidManifest.xml` +- Delete: `app/libs/fastjson-1.2.5.jar`、`app/libs/universal-image-loader-1.9.4.jar` + +> 本任务后 :app 仍无法编译(源码未迁移),验证仅到"配置可解析"。 + +- [ ] **Step 1: 删除被坐标替换的本地 jar** + +```bash +git rm app/libs/fastjson-1.2.5.jar app/libs/universal-image-loader-1.9.4.jar +``` + +- [ ] **Step 2: 重写 `app/build.gradle`** + +```gradle +apply plugin: 'com.android.application' + +android { + namespace 'com.github.skykai.stickercamera' + compileSdk 36 + + defaultConfig { + applicationId "com.github.skykai.stickercamera" + minSdk 26 + targetSdk 36 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.7.0' + implementation 'androidx.recyclerview:recyclerview:1.3.2' + implementation 'androidx.cardview:cardview:1.0.0' + implementation 'androidx.core:core:1.13.1' + implementation 'androidx.fragment:fragment:1.8.5' + implementation 'androidx.viewpager:viewpager:1.0.0' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' + implementation 'com.google.android.material:material:1.12.0' + implementation 'com.jakewharton:butterknife:10.2.3' + annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3' + implementation 'com.alibaba:fastjson:1.2.83' + implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' + implementation 'org.greenrobot:eventbus:3.3.1' + implementation project(':Gpu-Image') + implementation project(':ImageViewTouch') +} +``` + +- [ ] **Step 3: 删除 manifest 的 `package`** + +`app/src/main/AndroidManifest.xml` 的 `` 删去 `package="com.github.skykai.stickercamera"`,其余(权限、application、activity 全限定名)不变。 + +- [ ] **Step 4: 验证配置解析** + +Run: `JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew :app:dependencies --configuration debugRuntimeClasspath` +Expected: 依赖树解析成功(出现 androidx/material/eventbus/fastjson),无"Could not resolve"。 + +- [ ] **Step 5: Commit** + +```bash +git add app/build.gradle app/src/main/AndroidManifest.xml app/libs +git commit -m "build(app): AGP 8 依赖映射到 AndroidX/Material,移除死库与本地 jar" +``` + +--- + +### Task 5: :app AndroidX 源码迁移 + +**Files(java,8 个):** +- Modify: `app/src/main/java/com/stickercamera/base/BaseActivity.java:8` +- Modify: `app/src/main/java/com/stickercamera/base/BaseFragmentActivity.java:3` +- Modify: `app/src/main/java/com/stickercamera/app/ui/MainActivity.java:4-9` +- Modify: `app/src/main/java/com/stickercamera/app/camera/ui/AlbumActivity.java:5-8` +- Modify: `app/src/main/java/com/stickercamera/app/camera/fragment/AlbumFragment.java:4` +- Modify: `app/src/main/java/com/stickercamera/app/camera/ui/PhotoProcessActivity.java:12` +- Modify: `app/src/main/java/com/customview/PagerSlidingTabStrip.java:29-30` + +**Files(xml):** 含 `android.support.*` 标签的布局(用 grep 定位,通常 `activity_main.xml`、`activity_album.xml`、`item_picture.xml`)。 + +- [ ] **Step 1: 替换 java import(按下表逐项全局替换)** + +| 旧 | 新 | +|---|---| +| `android.support.v7.app.AppCompatActivity` | `androidx.appcompat.app.AppCompatActivity` | +| `android.support.v4.app.Fragment` | `androidx.fragment.app.Fragment` | +| `android.support.v4.app.FragmentActivity` | `androidx.fragment.app.FragmentActivity` | +| `android.support.v4.app.FragmentManager` | `androidx.fragment.app.FragmentManager` | +| `android.support.v4.app.FragmentPagerAdapter` | `androidx.fragment.app.FragmentPagerAdapter` | +| `android.support.v4.view.ViewPager` | `androidx.viewpager.widget.ViewPager` | +| `android.support.v4.view.ViewPager.OnPageChangeListener` | `androidx.viewpager.widget.ViewPager.OnPageChangeListener` | +| `android.support.v4.widget.SwipeRefreshLayout` | `androidx.swiperefreshlayout.widget.SwipeRefreshLayout` | +| `android.support.v7.widget.RecyclerView` | `androidx.recyclerview.widget.RecyclerView` | +| `android.support.v7.widget.LinearLayoutManager` | `androidx.recyclerview.widget.LinearLayoutManager` | +| `android.support.v7.widget.CardView` | `androidx.cardview.widget.CardView` | +| `android.support.annotation.Nullable` | `androidx.annotation.Nullable` | + +可用: + +```bash +cd app/src/main/java +grep -rl "android.support" . | while read f; do + sed -i '' \ + -e 's#android\.support\.v7\.app\.AppCompatActivity#androidx.appcompat.app.AppCompatActivity#g' \ + -e 's#android\.support\.v4\.app\.FragmentPagerAdapter#androidx.fragment.app.FragmentPagerAdapter#g' \ + -e 's#android\.support\.v4\.app\.FragmentActivity#androidx.fragment.app.FragmentActivity#g' \ + -e 's#android\.support\.v4\.app\.FragmentManager#androidx.fragment.app.FragmentManager#g' \ + -e 's#android\.support\.v4\.app\.Fragment#androidx.fragment.app.Fragment#g' \ + -e 's#android\.support\.v4\.view\.ViewPager#androidx.viewpager.widget.ViewPager#g' \ + -e 's#android\.support\.v4\.widget\.SwipeRefreshLayout#androidx.swiperefreshlayout.widget.SwipeRefreshLayout#g' \ + -e 's#android\.support\.v7\.widget\.RecyclerView#androidx.recyclerview.widget.RecyclerView#g' \ + -e 's#android\.support\.v7\.widget\.LinearLayoutManager#androidx.recyclerview.widget.LinearLayoutManager#g' \ + -e 's#android\.support\.v7\.widget\.CardView#androidx.cardview.widget.CardView#g' \ + -e 's#android\.support\.annotation\.Nullable#androidx.annotation.Nullable#g' \ + "$f" +done +``` + +- [ ] **Step 2: 替换 xml 中的全限定 support 标签** + +```bash +cd app/src/main/res +grep -rl "android.support" . | while read f; do + sed -i '' \ + -e 's#android\.support\.v4\.view\.ViewPager#androidx.viewpager.widget.ViewPager#g' \ + -e 's#android\.support\.v7\.widget\.RecyclerView#androidx.recyclerview.widget.RecyclerView#g' \ + -e 's#android\.support\.v7\.widget\.CardView#androidx.cardview.widget.CardView#g' \ + "$f" +done +``` + +- [ ] **Step 3: 验证无残留** + +Run: `grep -rn "android.support" app/src && echo "STILL HAS SUPPORT" || echo "CLEAN"` +Expected: `CLEAN` + +- [ ] **Step 4: Commit** + +```bash +git add app/src +git commit -m "refactor(app): android.support.* 全量迁移到 androidx" +``` + +--- + +### Task 6: :app ButterKnife 6 → 10 + +**Files(6 个含注解):** `EditTextActivity.java`、`MainActivity.java`、`AlbumActivity.java`、`CameraActivity.java`、`CropPhotoActivity.java`、`PhotoProcessActivity.java`(`BaseActivity.java` 仅有一行无用 `import butterknife.ButterKnife` 可一并删)。 + +- [ ] **Step 1: 注解与调用改名** + +```bash +cd app/src/main/java +grep -rl "InjectView\|ButterKnife" . | while read f; do + sed -i '' \ + -e 's#import butterknife\.InjectView;#import butterknife.BindView;#g' \ + -e 's#@InjectView#@BindView#g' \ + -e 's#ButterKnife\.inject(#ButterKnife.bind(#g' \ + "$f" +done +``` + +(若某文件同时有 `@OnClick` 等其它 ButterKnife 注解,10.x API 兼容,无需改;仅 `@InjectView`→`@BindView`、`inject`→`bind` 有变。) + +- [ ] **Step 2: 删除 BaseActivity 无用 import** + +`app/src/main/java/com/stickercamera/base/BaseActivity.java` 删除 `import butterknife.ButterKnife;`(该类不调用 ButterKnife)。 + +- [ ] **Step 3: 验证无残留旧 API** + +Run: `grep -rn "InjectView\|ButterKnife.inject" app/src && echo "STILL OLD" || echo "CLEAN"` +Expected: `CLEAN` + +- [ ] **Step 4: Commit** + +```bash +git add app/src +git commit -m "refactor(app): ButterKnife 6 -> 10 (@BindView/bind)" +``` + +--- + +### Task 7: :app EventBus 2 → 3 + +**Files:** `MainActivity.java`、`PhotoProcessActivity.java` + +- [ ] **Step 1: 改包名 import** + +两文件:`import de.greenrobot.event.EventBus;` → `import org.greenrobot.eventbus.EventBus;` +`MainActivity.java` 另加:`import org.greenrobot.eventbus.Subscribe;` 和 `import org.greenrobot.eventbus.ThreadMode;` + +- [ ] **Step 2: 注解订阅方法(MainActivity)** + +`MainActivity.java` 中: + +```java +public void onEventMainThread(FeedItem feedItem) { +``` + +改为: + +```java +@Subscribe(threadMode = ThreadMode.MAIN) +public void onEvent(FeedItem feedItem) { +``` + +(`register`/`unregister`/`post` API 在 3.x 不变,无需改。) + +- [ ] **Step 3: 验证无残留旧包** + +Run: `grep -rn "de.greenrobot" app/src && echo "STILL OLD" || echo "CLEAN"` +Expected: `CLEAN` + +- [ ] **Step 4: Commit** + +```bash +git add app/src +git commit -m "refactor(app): EventBus 2.4 -> 3.3.1 (@Subscribe)" +``` + +--- + +### Task 8: melnykov FAB → Material FAB + +**Files:** `app/src/main/res/layout/activity_main.xml`、`app/src/main/java/com/stickercamera/app/ui/MainActivity.java` + +- [ ] **Step 1: 替换布局中的 FAB** + +`activity_main.xml` 把 `com.melnykov.fab.FloatingActionButton` 节点整体替换为: + +```xml + +``` + +- [ ] **Step 2: 替换 MainActivity import** + +`MainActivity.java`:`import com.melnykov.fab.FloatingActionButton;` → `import com.google.android.material.floatingactionbutton.FloatingActionButton;` +(字段 `FloatingActionButton fab;` 与 `fab.setOnClickListener(...)` 不变。) + +- [ ] **Step 3: 验证无残留** + +Run: `grep -rn "melnykov" app/src && echo "STILL OLD" || echo "CLEAN"` +Expected: `CLEAN` + +- [ ] **Step 4: Commit** + +```bash +git add app/src +git commit -m "refactor(app): melnykov FAB -> Material FloatingActionButton" +``` + +--- + +### Task 9: sephiroth HListView → 水平 RecyclerView + +**Files:** +- Modify: `app/src/main/res/layout/activity_image_process.xml` +- Modify: `app/src/main/java/com/stickercamera/app/camera/ui/PhotoProcessActivity.java` +- Rewrite: `app/src/main/java/com/stickercamera/app/camera/adapter/FilterAdapter.java` +- Rewrite: `app/src/main/java/com/stickercamera/app/camera/adapter/StickerToolAdapter.java` + +**Interfaces:** +- Produces: `FilterAdapter` / `StickerToolAdapter` 提供 `setOnItemClickListener(OnItemClickListener)`,回调签名 `void onItemClick(int position)`;`FilterAdapter` 保留 `getSelectFilter()`/`setSelectFilter(int)`。 + +> 观感微调:放弃 `hlv_dividerWidth` 的 15px 分隔(功能优先,可接受)。 + +- [ ] **Step 1: 布局替换** + +`activity_image_process.xml` 把 `it.sephiroth.android.library.widget.HListView`(id `list_tools`)替换为: + +```xml + +``` + +(删除 `app:hlv_dividerWidth` 与 `android:gravity`。) + +- [ ] **Step 2: 重写 `FilterAdapter.java`** + +```java +package com.stickercamera.app.camera.adapter; + +import android.content.Context; +import android.graphics.Bitmap; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.github.skykai.stickercamera.R; +import com.stickercamera.app.camera.effect.FilterEffect; +import com.stickercamera.app.camera.util.GPUImageFilterTools; + +import java.util.List; + +import jp.co.cyberagent.android.gpuimage.GPUImageFilter; +import jp.co.cyberagent.android.gpuimage.GPUImageView; + +public class FilterAdapter extends RecyclerView.Adapter { + + public interface OnItemClickListener { + void onItemClick(int position); + } + + private final List filterUris; + private final Context mContext; + private final Bitmap background; + private int selectFilter = 0; + private OnItemClickListener onItemClickListener; + + public FilterAdapter(Context context, List effects, Bitmap background) { + this.mContext = context; + this.filterUris = effects; + this.background = background; + } + + public void setOnItemClickListener(OnItemClickListener l) { + this.onItemClickListener = l; + } + + public void setSelectFilter(int selectFilter) { + this.selectFilter = selectFilter; + } + + public int getSelectFilter() { + return selectFilter; + } + + public FilterEffect getItem(int position) { + return filterUris.get(position); + } + + @NonNull + @Override + public EffectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(mContext).inflate(R.layout.item_bottom_filter, parent, false); + return new EffectHolder(v); + } + + @Override + public void onBindViewHolder(@NonNull EffectHolder holder, int position) { + final FilterEffect effect = getItem(position); + holder.filteredImg.setImage(background); + holder.filterName.setText(effect.getTitle()); + GPUImageFilter filter = GPUImageFilterTools.createFilterForType(mContext, effect.getType()); + holder.filteredImg.setFilter(filter); + holder.itemView.setOnClickListener(v -> { + if (onItemClickListener != null) { + onItemClickListener.onItemClick(holder.getAdapterPosition()); + } + }); + } + + @Override + public int getItemCount() { + return filterUris.size(); + } + + static class EffectHolder extends RecyclerView.ViewHolder { + GPUImageView filteredImg; + TextView filterName; + + EffectHolder(View itemView) { + super(itemView); + filteredImg = itemView.findViewById(R.id.small_filter); + filterName = itemView.findViewById(R.id.filter_name); + } + } +} +``` + +- [ ] **Step 3: 重写 `StickerToolAdapter.java`** + +```java +package com.stickercamera.app.camera.adapter; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.common.util.ImageLoaderUtils; +import com.github.skykai.stickercamera.R; +import com.stickercamera.app.model.Addon; + +import java.util.List; + +public class StickerToolAdapter extends RecyclerView.Adapter { + + public interface OnItemClickListener { + void onItemClick(int position); + } + + private final List filterUris; + private final Context mContext; + private OnItemClickListener onItemClickListener; + + public StickerToolAdapter(Context context, List effects) { + this.mContext = context; + this.filterUris = effects; + } + + public void setOnItemClickListener(OnItemClickListener l) { + this.onItemClickListener = l; + } + + public Addon getItem(int position) { + return filterUris.get(position); + } + + @NonNull + @Override + public EffectHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(mContext).inflate(R.layout.item_bottom_tool, parent, false); + return new EffectHolder(v); + } + + @Override + public void onBindViewHolder(@NonNull EffectHolder holder, int position) { + final Addon sticker = getItem(position); + holder.container.setVisibility(View.GONE); + ImageLoaderUtils.displayDrawableImage(sticker.getId() + "", holder.logo, null); + holder.itemView.setOnClickListener(v -> { + if (onItemClickListener != null) { + onItemClickListener.onItemClick(holder.getAdapterPosition()); + } + }); + } + + @Override + public int getItemCount() { + return filterUris.size(); + } + + static class EffectHolder extends RecyclerView.ViewHolder { + ImageView logo; + ImageView container; + + EffectHolder(View itemView) { + super(itemView); + logo = itemView.findViewById(R.id.effect_image); + container = itemView.findViewById(R.id.effect_background); + } + } +} +``` + +- [ ] **Step 4: 改 PhotoProcessActivity** + +字段与 import:删 `import it.sephiroth.android.library.widget.HListView;`,新增 `import androidx.recyclerview.widget.RecyclerView;` 和 `import androidx.recyclerview.widget.LinearLayoutManager;`(PhotoProcessActivity 原本用的是 HListView,Task 5 未给它引入 RecyclerView);字段 `@BindView(R.id.list_tools) HListView bottomToolBar;` 的类型 `HListView` → `RecyclerView`(注解不变)。同时删除文件里残留的 `import android.widget.GridView;` 若未被使用(由编译器报未用 import 时清理,非必须)。 + +`initStickerToolBar()` 改为: + +```java +private void initStickerToolBar() { + bottomToolBar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); + StickerToolAdapter adapter = new StickerToolAdapter(PhotoProcessActivity.this, EffectUtil.addonList); + adapter.setOnItemClickListener(position -> { + labelSelector.hide(); + Addon sticker = EffectUtil.addonList.get(position); + EffectUtil.addStickerImage(mImageView, PhotoProcessActivity.this, sticker, + new EffectUtil.StickerCallback() { + @Override + public void onRemoveSticker(Addon sticker) { + labelSelector.hide(); + } + }); + }); + bottomToolBar.setAdapter(adapter); + setCurrentBtn(stickerBtn); +} +``` + +`initFilterToolBar()` 改为: + +```java +private void initFilterToolBar() { + final List filters = EffectService.getInst().getLocalFilters(); + bottomToolBar.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); + final FilterAdapter adapter = new FilterAdapter(PhotoProcessActivity.this, filters, smallImageBackgroud); + adapter.setOnItemClickListener(position -> { + labelSelector.hide(); + if (adapter.getSelectFilter() != position) { + adapter.setSelectFilter(position); + GPUImageFilter filter = GPUImageFilterTools.createFilterForType( + PhotoProcessActivity.this, filters.get(position).getType()); + mGPUImageView.setFilter(filter); + GPUImageFilterTools.FilterAdjuster mFilterAdjuster = new GPUImageFilterTools.FilterAdjuster(filter); + if (mFilterAdjuster.canAdjust()) { + //mFilterAdjuster.adjust(100); + } + } + }); + bottomToolBar.setAdapter(adapter); +} +``` + +- [ ] **Step 5: 验证无残留** + +Run: `grep -rn "sephiroth\|HListView" app/src && echo "STILL OLD" || echo "CLEAN"` +Expected: `CLEAN` + +- [ ] **Step 6: Commit** + +```bash +git add app/src +git commit -m "refactor(app): HListView -> 水平 RecyclerView,适配器改 RecyclerView.Adapter" +``` + +--- + +### Task 10: systembartint 移除 + edge-to-edge 适配 + +**Files:** `app/src/main/java/com/stickercamera/base/BaseActivity.java` + +- [ ] **Step 1: 重写 BaseActivity 的窗口/状态栏处理** + +删除 import:`android.annotation.TargetApi`、`android.os.Build`、`android.util.TypedValue`、`android.view.WindowManager`、`com.readystatesoftware.systembartint.SystemBarTintManager`。 +新增 import(`android.view.View` 原文件已有,勿重复): + +```java +import androidx.core.graphics.Insets; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowCompat; +import androidx.core.view.WindowInsetsCompat; +``` + +`onCreate` 里把 `initWindow();` 保留;`initWindow()` 改为: + +```java +private void initWindow() { + WindowCompat.setDecorFitsSystemWindows(getWindow(), false); +} +``` + +删除 `getStatusBarColor()` 方法(原仅供 tint 使用);`getColorPrimary()` 保留。 + +`setContentView(int)` 改为(在 super 之后、titleBar 绑定之前插入 inset 处理): + +```java +@Override +public void setContentView(int layoutResID) { + super.setContentView(layoutResID); + final View content = findViewById(android.R.id.content); + if (content != null) { + ViewCompat.setOnApplyWindowInsetsListener(content, (v, insets) -> { + Insets bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); + v.setPadding(bars.left, bars.top, bars.right, bars.bottom); + return insets; + }); + } + titleBar = (CommonTitleBar) findViewById(R.id.title_layout); + if (titleBar != null) + titleBar.setLeftBtnOnclickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); +} +``` + +- [ ] **Step 2: 验证无残留** + +Run: `grep -rn "systembartint\|SystemBarTint" app/src && echo "STILL OLD" || echo "CLEAN"` +Expected: `CLEAN` + +- [ ] **Step 3: Commit** + +```bash +git add app/src +git commit -m "refactor(app): 移除 systembartint,改 edge-to-edge + WindowInsets 适配" +``` + +--- + +### Task 11: 全量构建绿灯 + +- [ ] **Step 1: clean + assembleDebug** + +Run: `JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew clean assembleDebug` +Expected: `BUILD SUCCESSFUL`,产出 `app/build/outputs/apk/debug/app-debug.apk` + +- [ ] **Step 2: 迭代修编译错误** + +若有报错(常见:遗漏的 import、ButterKnife 与 AGP 8 注解处理冲突、个别 androidx 类名),逐个修复后重跑 Step 1。 +**ButterKnife 兜底:** 若 ButterKnife 10.2.3 与 AGP 8/Java 17 注解处理无法通过,停止并与用户确认改用 ViewBinding(见 spec 风险 1),不要私自大改。 + +- [ ] **Step 3: Commit(若有修复)** + +```bash +git add -A +git commit -m "fix: 修复 AGP 8 全量构建编译问题" +``` + +--- + +### Task 12: 模拟器冒烟测试 + +- [ ] **Step 1: 启动模拟器并安装** + +```bash +adb devices +JAVA_HOME=$(/usr/libexec/java_home -v 17) ./gradlew installDebug +adb shell am start -n com.github.skykai.stickercamera/com.stickercamera.app.ui.MainActivity +``` + +- [ ] **Step 2: 走主流程并观察** + +拍照 → 裁剪 → 进入图片处理 → 切滤镜(验证 GPU `.so` 加载、滤镜生效)→ 加贴纸(工具条横向滚动+点击)→ 加标签 → 保存 → 返回主界面展示。 +用 `adb logcat` 观察有无崩溃 / `UnsatisfiedLinkError`(.so)/ inset 遮挡。 + +- [ ] **Step 3: 修正 edge-to-edge 遮挡(如有)** + +若某全屏界面(相机/裁剪/处理)控件被状态栏或导航栏遮挡或留白异常,针对该界面根布局微调 inset 应用(只动受影响界面)。重装验证。 + +- [ ] **Step 4: Commit(若有修复)** + +```bash +git add -A +git commit -m "fix: 模拟器冒烟回归修正" +``` + +--- + +## 验收标准 + +- `./gradlew clean assembleDebug` 成功产出 APK。 +- 模拟器主流程跑通,GPU 滤镜生效,无崩溃。 +- `grep -rn "android.support\|de.greenrobot\|sephiroth\|melnykov\|systembartint\|InjectView" app/src` 为空。 +- 全程在 `modernize-build-toolchain` 分支。 diff --git a/docs/superpowers/specs/2026-06-18-build-toolchain-modernization-design.md b/docs/superpowers/specs/2026-06-18-build-toolchain-modernization-design.md new file mode 100644 index 0000000..75e5310 --- /dev/null +++ b/docs/superpowers/specs/2026-06-18-build-toolchain-modernization-design.md @@ -0,0 +1,161 @@ +# StickerCamera 编译链现代化设计 + +- 日期: 2026-06-18 +- 状态: 已批准设计,待写实现计划 +- 作者: SkyKai + Claude Code + +## 背景 + +StickerCamera 是 2015 年的 Android 工程,编译链停留在 AGP 1.2.3 / Gradle 2.4 / compileSdk 22,依赖 `jcenter()`(2021 年已停服)、`android.support.*`(已 EOL)、Retrolambda、ButterKnife 6.1.0,以及若干已废弃的 jcenter UI 库。本工程当前无法在现代开发机上构建。 + +开发机环境已就绪:JDK 8/11/17(默认 17),Android SDK 含 `android-36` 平台与 `build-tools 36.0.0`,NDK 已装。 + +## 目标 + +把整个工程的编译链升级到现代、可长期维护的版本,完成 AndroidX 全面迁移,使其能在当前开发机上 `./gradlew assembleDebug` 构建通过,并保持原有功能。 + +### 目标版本(已确认) + +| 项 | 现状 | 目标 | +|---|---|---| +| JDK(运行 Gradle) | — | 17 | +| Java source/target | Retrolambda 模拟 8 | 17(移除 Retrolambda) | +| Gradle wrapper | 2.4 | 8.13 | +| AGP | 1.2.3 | 8.11.1 | +| compileSdk | 22 | 36 | +| targetSdk | 22 | 36 | +| minSdk | 15 | 26 | +| 仓库 | `jcenter()` | `google()` + `mavenCentral()` | +| AndroidX | support 库 | `android.useAndroidX=true` 全迁移 | + +> 备注:AGP 8.11.x 是稳定支持 compileSdk 36 的版本线,配对 Gradle 8.13。若实现时该精确版本号有微调,以"能稳定支持 compileSdk 36 的最近 AGP 8.11+/配套 Gradle"为准。 + +## 范围 + +### 范围内 + +1. 构建脚本与 wrapper 全面升级(根、settings、gradle.properties、三模块、wrapper、local.properties)。 +2. `android.support.*` → `androidx.*` 全迁移(java + xml)。 +3. ButterKnife 6.1.0 → 10.2.3(保留 ButterKnife)。 +4. EventBus 2.4.0 → 3.3.1。 +5. 替换 3 个仍在用的废弃 UI 库:melnykov FAB、sephiroth HListView、systembartint。 +6. 删除未使用的 rengwuxian MaterialEditText 依赖。 +7. Gpu-Image 原生 `.so` 迁移到 `jniLibs` 并裁剪废弃 ABI。 +8. 本地 jar(fastjson、UIL)切换为 mavenCentral 坐标。 +9. 移除 Retrolambda。 +10. targetSdk 36 带来的强制 edge-to-edge 适配(各界面 WindowInsets)。 + +### 范围外(本次不做) + +- 不替换 UIL 为 Glide、不替换 fastjson 为 fastjson2(仅升版本/换坐标,API 不变)。 +- 不重构 app 业务架构、不动自定义控件(贴纸/标签引擎)逻辑。 +- 不引入 Kotlin、不引入 View Binding(除非 ButterKnife 与 AGP 8 冲突,见风险)。 +- 不做单元测试补全(工程现仅有空的 instrumentation 桩)。 + +## 详细设计 + +### 1. 构建文件 + +- **根 `build.gradle`**:删除 `me.tatarka:gradle-retrolambda` classpath;AGP `1.2.3` → `8.11.1`;移除 `buildscript`/`allprojects` 里的 `jcenter()`(仓库改到 settings 集中声明)。 +- **`settings.gradle`**:新增 `pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }` 与 `dependencyResolutionManagement { repositories { google(); mavenCentral() } }`;保留 `include ':app', ':Gpu-Image', ':ImageViewTouch'`。 +- **`gradle.properties`**:新增 `android.useAndroidX=true`、`android.nonTransitiveRClass=true`;设置合理 `org.gradle.jvmargs`(如 `-Xmx2048m -Dfile.encoding=UTF-8`)。 +- **`gradle/wrapper/gradle-wrapper.properties`**:`distributionUrl` → `gradle-8.13-all.zip`。 +- **`local.properties`**:写入 `sdk.dir=/Users/skykai/Library/Android/sdk`(该文件不纳入 git)。 +- **各模块 `build.gradle`**: + - `apply plugin` 形式保留或转 `plugins {}` 均可,但移除 `me.tatarka.retrolambda`。 + - `android { namespace "" }`,并从对应 `AndroidManifest.xml` 删除 `package=` 属性。 + - `compileSdk 36`;`:app` 设 `minSdk 26 / targetSdk 36`,库模块设 `minSdk 26`。 + - `buildToolsVersion` 可省略(AGP 自动选默认)。 + - `compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }`。 + - 依赖配置 `compile` → `implementation`(模块间 `compile project(...)` → `implementation project(...)`;库模块对外暴露的 API 用 `api`)。 + - 启用 `buildFeatures { }` 视需要(本次无需 viewBinding,除非回退方案触发)。 + +各模块 namespace: +- `:app` → `com.github.skykai.stickercamera` +- `:Gpu-Image` → `jp.co.cyberagent.android.gpuimage` +- `:ImageViewTouch` → `com.imagezoom`(已确认;该模块为标准 `src/main` 布局,无需 sourceSets 调整,仅需加 namespace、删 manifest 的 `package`) + +### 2. AndroidX 迁移(实测范围) + +仅 7 个 java 文件 + 3 处 XML 含 `android.support.*`,均为 1:1 改名: + +| 旧 | 新 | +|---|---| +| `android.support.v7.app.AppCompatActivity` | `androidx.appcompat.app.AppCompatActivity` | +| `android.support.v4.app.Fragment` / `FragmentActivity` / `FragmentManager` / `FragmentPagerAdapter` | `androidx.fragment.app.*` | +| `android.support.v4.view.ViewPager`(含 `OnPageChangeListener`) | `androidx.viewpager.widget.ViewPager` | +| `android.support.v4.widget.SwipeRefreshLayout` | `androidx.swiperefreshlayout.widget.SwipeRefreshLayout` | +| `android.support.v7.widget.RecyclerView` / `LinearLayoutManager` | `androidx.recyclerview.widget.*` | +| `android.support.v7.widget.CardView` | `androidx.cardview.widget.CardView` | +| `android.support.annotation.Nullable` | `androidx.annotation.Nullable` | + +XML 中 3 处全限定标签同步改名:`android.support.v4.view.ViewPager`、`android.support.v7.widget.CardView`、`android.support.v7.widget.RecyclerView`。 + +### 3. ButterKnife 6.1.0 → 10.2.3 + +- 依赖:`implementation 'com.jakewharton:butterknife:10.2.3'` + `annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'`。 +- 代码:`@InjectView` → `@BindView`(6 文件共 30 处);`ButterKnife.inject(...)` → `ButterKnife.bind(...)`(7 处,含 MainActivity 的 ViewHolder `bind(this, itemView)`);其它 ButterKnife 注解(如 `@OnClick`,若有)一并按 10.x API 调整。 +- 注意:ButterKnife 10.x 要求 AndroidX,需先完成第 2 步。 + +### 4. EventBus 2.4.0 → 3.3.1 + +- 依赖:`implementation 'org.greenrobot:eventbus:3.3.1'`。 +- 代码(2 文件):`import de.greenrobot.event.EventBus` → `org.greenrobot.eventbus.EventBus`;`register`/`unregister`/`post` API 不变;`public void onEventMainThread(FeedItem)` → 加注解 `@Subscribe(threadMode = ThreadMode.MAIN)`,方法名可改为 `onEvent`(MainActivity)。 + +### 5. 废弃 UI 库替换(功能优先,允许观感微调) + +- **melnykov FAB → Material Components FAB**(`com.google.android.material:material:1.11.0`): + - `activity_main.xml`:`com.melnykov.fab.FloatingActionButton` → `com.google.android.material.floatingactionbutton.FloatingActionButton`,属性按 Material API 调整。 + - `MainActivity.java`:导入与字段类型改为 Material FAB;放弃 `attachToRecyclerView` 的随滚动自动隐藏特性(Material FAB 无此 API)。 +- **sephiroth HListView → 水平 RecyclerView**(本次最重一块): + - `activity_image_process.xml`:`it.sephiroth.android.library.widget.HListView` → `androidx.recyclerview.widget.RecyclerView`。 + - `PhotoProcessActivity.java`:`bottomToolBar` 类型改为 `RecyclerView`,设置 `LinearLayoutManager(HORIZONTAL)`;`setOnItemClickListener` 改走 adapter 点击回调。 + - `FilterAdapter`、`StickerToolAdapter`:从 `BaseAdapter` 重写为 `RecyclerView.Adapter`(getView → onCreateViewHolder/onBindViewHolder,新增点击回调接口)。 +- **systembartint → edge-to-edge + 状态栏着色**: + - `BaseActivity.initWindow()`:移除 `FLAG_TRANSLUCENT_STATUS/NAVIGATION` 与 `SystemBarTintManager`;改用 `getWindow().setStatusBarColor(getColorPrimary())` 等价表达原"状态栏着主题色"意图。 +- **rengwuxian MaterialEditText → 删除**:实测全工程无引用,直接从 `app/build.gradle` 删依赖,无代码改动。 + +### 6. Gpu-Image 原生库 + +- 将 `Gpu-Image/libs//libgpuimage-library.so` 迁移到 `Gpu-Image/src/main/jniLibs//`(或在 build.gradle 配 `sourceSets.main.jniLibs.srcDirs`)。 +- 裁剪废弃 ABI:删除 `armeabi`、`mips`、`mips64`;保留 `arm64-v8a`、`armeabi-v7a`、`x86`、`x86_64`。 +- 非标准 sourceSets(`src/`、`res/`)归位到 AGP 8 标准布局或显式声明 `sourceSets`;加 `namespace`,删 manifest 的 `package`。 + +### 7. 依赖坐标与版本映射 + +| 旧 | 新 | +|---|---| +| `com.android.support:appcompat-v7:22.2.0` | `androidx.appcompat:appcompat:1.6.1` | +| `com.android.support:recyclerview-v7:22.2.0` | `androidx.recyclerview:recyclerview:1.3.2` | +| `com.android.support:cardview-v7:22.2.0` | `androidx.cardview:cardview:1.0.0` | +| (新增) | `com.google.android.material:material:1.11.0` | +| `com.jakewharton:butterknife:6.1.0` | `com.jakewharton:butterknife:10.2.3` + compiler | +| `de.greenrobot:eventbus:2.4.0` | `org.greenrobot:eventbus:3.3.1` | +| `files('libs/fastjson-1.2.5.jar')` | `com.alibaba:fastjson:1.2.83` | +| `files('universal-image-loader-1.9.4.jar')` | `com.nostra13.universalimageloader:universal-image-loader:1.9.5` | +| `systembartint` / melnykov FAB / MaterialEditText / hlistview | 移除 | + +> 上述 androidx/material 版本为兼容 minSdk 26 的稳定版;实现时若 AGP 8.11 要求更高的某传递依赖版本,以 Gradle 实际解析为准做最小上调。 + +### 8. targetSdk 36 的 edge-to-edge 适配 + +targetSdk ≥ 35 在 Android 15+/16 设备上强制 edge-to-edge,内容会延伸到系统栏后方。需: + +- 在 `BaseActivity` 启用 `WindowCompat.setDecorFitsSystemWindows(window, false)` 并对内容根视图应用 `systemBars()` insets 作为 padding,避免标题栏/按钮被状态栏或导航栏遮挡。 +- 全屏相机/裁剪预览(已是 FullScreen 主题)按需对覆盖控件(快门、返回等)应用 insets。 +- 该适配与第 5 步 systembartint 的移除合并处理。 + +## 风险与缓解 + +1. **ButterKnife 10.2.3 + AGP 8 / Java 17 注解处理兼容性(最高风险)**:这是已知痛点。用户选择保留 ButterKnife,先按此实施;若构建无法通过,**回退方案为改用 ViewBinding**(届时再与用户确认,涉及各 Activity 注入代码改写)。 +2. **edge-to-edge 遮挡**:targetSdk 36 下界面可能被系统栏遮挡,需逐界面验证 insets。 +3. **HListView → RecyclerView 行为差异**:滤镜/贴纸工具条滚动与点击需实机回归。 +4. **依赖解析**:个别旧坐标在 mavenCentral 的可用性与传递依赖版本冲突,以 Gradle 解析报错为准逐个修正。 +5. **原生库加载**:ABI 裁剪后需在真机(arm64)与模拟器(x86_64)各验证一次滤镜功能,确保 `.so` 正确打包加载。 + +## 验证标准 + +- `./gradlew clean assembleDebug` 构建成功产出 APK。 +- (可选)`./gradlew installDebug` 后实机/模拟器走通主流程:拍照 → 裁剪 → 滤镜 → 贴纸 → 标签 → 保存 → 主界面展示。 +- GPU 滤镜实际生效(验证 `.so` 加载)。 +- 各界面无被系统栏遮挡的可见问题。 diff --git a/gradle.properties b/gradle.properties index 1d3591c..ce29e0e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -15,4 +15,9 @@ # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects -# org.gradle.parallel=true \ No newline at end of file +# org.gradle.parallel=true + +android.useAndroidX=true +android.nonTransitiveRClass=false +android.nonFinalResIds=false +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5ee4adf..e16eca7 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip diff --git a/settings.gradle b/settings.gradle index 6d6a821..062b0af 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,15 @@ -include ':app', ':Gpu-Image', ':ImageViewTouch' +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + } +} +rootProject.name = "StickerCamera" +include ':app', ':ImageViewTouch'