1 /**
2 ** Copyright 2007, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
17 #include "jni.h"
18 #include <nativehelper/JNIHelp.h>
19
20 #include <math.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <assert.h>
25 #include <dlfcn.h>
26
27 #include <android/graphics/bitmap.h>
28 #include <GLES2/gl2.h>
29 #include <GLES2/gl2ext.h>
30 #include <GLES3/gl3.h>
31 #include <ETC1/etc1.h>
32
33 #include "core_jni_helpers.h"
34
35 #undef LOG_TAG
36 #define LOG_TAG "OpenGLUtil"
37 #include <utils/Log.h>
38 #include "utils/misc.h"
39
40 #include "poly.h"
41
42 namespace android {
43
doThrowIAE(JNIEnv * env,const char * msg=nullptr)44 static void doThrowIAE(JNIEnv* env, const char* msg = nullptr) {
45 jniThrowException(env, "java/lang/IllegalArgumentException", msg);
46 }
47
48 static inline
mx4transform(float x,float y,float z,float w,const float * pM,float * pDest)49 void mx4transform(float x, float y, float z, float w, const float* pM, float* pDest) {
50 pDest[0] = pM[0 + 4 * 0] * x + pM[0 + 4 * 1] * y + pM[0 + 4 * 2] * z + pM[0 + 4 * 3] * w;
51 pDest[1] = pM[1 + 4 * 0] * x + pM[1 + 4 * 1] * y + pM[1 + 4 * 2] * z + pM[1 + 4 * 3] * w;
52 pDest[2] = pM[2 + 4 * 0] * x + pM[2 + 4 * 1] * y + pM[2 + 4 * 2] * z + pM[2 + 4 * 3] * w;
53 pDest[3] = pM[3 + 4 * 0] * x + pM[3 + 4 * 1] * y + pM[3 + 4 * 2] * z + pM[3 + 4 * 3] * w;
54 }
55
56 #if 0
57 static
58 void
59 print_poly(const char* label, Poly* pPoly) {
60 ALOGI("%s: %d verts", label, pPoly->n);
61 for(int i = 0; i < pPoly->n; i++) {
62 Poly_vert* pV = & pPoly->vert[i];
63 ALOGI("[%d] %g, %g, %g %g", i, pV->sx, pV->sy, pV->sz, pV->sw);
64 }
65 }
66 #endif
67
68 static
visibilityTest(float * pWS,float * pPositions,int positionsLength,unsigned short * pIndices,int indexCount)69 int visibilityTest(float* pWS, float* pPositions, int positionsLength,
70 unsigned short* pIndices, int indexCount) {
71 int result = POLY_CLIP_OUT;
72
73 if ( indexCount < 3 ) {
74 return POLY_CLIP_OUT;
75 }
76
77 // Find out how many vertices we need to transform
78 // We transform every vertex between the min and max indices, inclusive.
79 // This is OK for the data sets we expect to use with this function, but
80 // for other loads it might be better to use a more sophisticated vertex
81 // cache of some sort.
82
83 int minIndex = 65536;
84 int maxIndex = -1;
85 for(int i = 0; i < indexCount; i++) {
86 int index = pIndices[i];
87 if ( index < minIndex ) {
88 minIndex = index;
89 }
90 if ( index > maxIndex ) {
91 maxIndex = index;
92 }
93 }
94
95 if ( maxIndex * 3 > positionsLength) {
96 return -1;
97 }
98
99 int transformedIndexCount = maxIndex - minIndex + 1;
100 std::unique_ptr<float[]> holder{new float[transformedIndexCount * 4]};
101 float* pTransformed = holder.get();
102
103 if (pTransformed == 0 ) {
104 return -2;
105 }
106
107 // Transform the vertices
108 {
109 const float* pSrc = pPositions + 3 * minIndex;
110 float* pDst = pTransformed;
111 for (int i = 0; i < transformedIndexCount; i++, pSrc += 3, pDst += 4) {
112 mx4transform(pSrc[0], pSrc[1], pSrc[2], 1.0f, pWS, pDst);
113 }
114 }
115
116 // Clip the triangles
117
118 Poly poly;
119 float* pDest = & poly.vert[0].sx;
120 for (int i = 0; i < indexCount; i += 3) {
121 poly.n = 3;
122 memcpy(pDest , pTransformed + 4 * (pIndices[i ] - minIndex), 4 * sizeof(float));
123 memcpy(pDest + 4, pTransformed + 4 * (pIndices[i + 1] - minIndex), 4 * sizeof(float));
124 memcpy(pDest + 8, pTransformed + 4 * (pIndices[i + 2] - minIndex), 4 * sizeof(float));
125 result = poly_clip_to_frustum(&poly);
126 if ( result != POLY_CLIP_OUT) {
127 return result;
128 }
129 }
130
131 return result;
132 }
133
134 class ByteArrayGetter {
135 public:
Get(JNIEnv * _env,jbyteArray array,jboolean * is_copy)136 static void* Get(JNIEnv* _env, jbyteArray array, jboolean* is_copy) {
137 return _env->GetByteArrayElements(array, is_copy);
138 }
139 };
140 class BooleanArrayGetter {
141 public:
Get(JNIEnv * _env,jbooleanArray array,jboolean * is_copy)142 static void* Get(JNIEnv* _env, jbooleanArray array, jboolean* is_copy) {
143 return _env->GetBooleanArrayElements(array, is_copy);
144 }
145 };
146 class CharArrayGetter {
147 public:
Get(JNIEnv * _env,jcharArray array,jboolean * is_copy)148 static void* Get(JNIEnv* _env, jcharArray array, jboolean* is_copy) {
149 return _env->GetCharArrayElements(array, is_copy);
150 }
151 };
152 class ShortArrayGetter {
153 public:
Get(JNIEnv * _env,jshortArray array,jboolean * is_copy)154 static void* Get(JNIEnv* _env, jshortArray array, jboolean* is_copy) {
155 return _env->GetShortArrayElements(array, is_copy);
156 }
157 };
158 class IntArrayGetter {
159 public:
Get(JNIEnv * _env,jintArray array,jboolean * is_copy)160 static void* Get(JNIEnv* _env, jintArray array, jboolean* is_copy) {
161 return _env->GetIntArrayElements(array, is_copy);
162 }
163 };
164 class LongArrayGetter {
165 public:
Get(JNIEnv * _env,jlongArray array,jboolean * is_copy)166 static void* Get(JNIEnv* _env, jlongArray array, jboolean* is_copy) {
167 return _env->GetLongArrayElements(array, is_copy);
168 }
169 };
170 class FloatArrayGetter {
171 public:
Get(JNIEnv * _env,jfloatArray array,jboolean * is_copy)172 static void* Get(JNIEnv* _env, jfloatArray array, jboolean* is_copy) {
173 return _env->GetFloatArrayElements(array, is_copy);
174 }
175 };
176 class DoubleArrayGetter {
177 public:
Get(JNIEnv * _env,jdoubleArray array,jboolean * is_copy)178 static void* Get(JNIEnv* _env, jdoubleArray array, jboolean* is_copy) {
179 return _env->GetDoubleArrayElements(array, is_copy);
180 }
181 };
182
183 class ByteArrayReleaser {
184 public:
Release(JNIEnv * _env,jbyteArray array,jbyte * data,jint mode)185 static void Release(JNIEnv* _env, jbyteArray array, jbyte* data, jint mode) {
186 _env->ReleaseByteArrayElements(array, data, mode);
187 }
188 };
189 class BooleanArrayReleaser {
190 public:
Release(JNIEnv * _env,jbooleanArray array,jboolean * data,jint mode)191 static void Release(JNIEnv* _env, jbooleanArray array, jboolean* data, jint mode) {
192 _env->ReleaseBooleanArrayElements(array, data, mode);
193 }
194 };
195 class CharArrayReleaser {
196 public:
Release(JNIEnv * _env,jcharArray array,jchar * data,jint mode)197 static void Release(JNIEnv* _env, jcharArray array, jchar* data, jint mode) {
198 _env->ReleaseCharArrayElements(array, data, mode);
199 }
200 };
201 class ShortArrayReleaser {
202 public:
Release(JNIEnv * _env,jshortArray array,jshort * data,jint mode)203 static void Release(JNIEnv* _env, jshortArray array, jshort* data, jint mode) {
204 _env->ReleaseShortArrayElements(array, data, mode);
205 }
206 };
207 class IntArrayReleaser {
208 public:
Release(JNIEnv * _env,jintArray array,jint * data,jint mode)209 static void Release(JNIEnv* _env, jintArray array, jint* data, jint mode) {
210 _env->ReleaseIntArrayElements(array, data, mode);
211 }
212 };
213 class LongArrayReleaser {
214 public:
Release(JNIEnv * _env,jlongArray array,jlong * data,jint mode)215 static void Release(JNIEnv* _env, jlongArray array, jlong* data, jint mode) {
216 _env->ReleaseLongArrayElements(array, data, mode);
217 }
218 };
219 class FloatArrayReleaser {
220 public:
Release(JNIEnv * _env,jfloatArray array,jfloat * data,jint mode)221 static void Release(JNIEnv* _env, jfloatArray array, jfloat* data, jint mode) {
222 _env->ReleaseFloatArrayElements(array, data, mode);
223 }
224 };
225 class DoubleArrayReleaser {
226 public:
Release(JNIEnv * _env,jdoubleArray array,jdouble * data,jint mode)227 static void Release(JNIEnv* _env, jdoubleArray array, jdouble* data, jint mode) {
228 _env->ReleaseDoubleArrayElements(array, data, mode);
229 }
230 };
231
232 template<class JArray, class T, class ArrayGetter, class ArrayReleaser>
233 class ArrayHelper {
234 public:
ArrayHelper(JNIEnv * env,JArray ref,jint offset,jint minSize)235 ArrayHelper(JNIEnv* env, JArray ref, jint offset, jint minSize) {
236 mEnv = env;
237 mRef = ref;
238 mOffset = offset;
239 mMinSize = minSize;
240 mBase = 0;
241 mReleaseParam = JNI_ABORT;
242 }
243
~ArrayHelper()244 ~ArrayHelper() {
245 if (mBase) {
246 ArrayReleaser::Release(mEnv, mRef, mBase, mReleaseParam);
247 }
248 }
249
250 // We seperate the bounds check from the initialization because we want to
251 // be able to bounds-check multiple arrays, and we can't throw an exception
252 // after we've called GetPrimitiveArrayCritical.
253
254 // Return true if the bounds check succeeded
255 // Else instruct the runtime to throw an exception
256
check()257 bool check() {
258 if ( ! mRef) {
259 doThrowIAE(mEnv, "array == null");
260 return false;
261 }
262 if ( mOffset < 0) {
263 doThrowIAE(mEnv, "offset < 0");
264 return false;
265 }
266 mLength = mEnv->GetArrayLength(mRef) - mOffset;
267 if (mLength < mMinSize ) {
268 doThrowIAE(mEnv, "length - offset < n");
269 return false;
270 }
271 return true;
272 }
273
274 // Bind the array.
275
bind()276 void bind() {
277 mBase = (T*) ArrayGetter::Get(mEnv, mRef, (jboolean *) 0);
278 mData = mBase + mOffset;
279 }
280
commitChanges()281 void commitChanges() {
282 mReleaseParam = 0;
283 }
284
285 T* mData;
286 int mLength;
287
288 private:
289 T* mBase;
290 JNIEnv* mEnv;
291 JArray mRef;
292 jint mOffset;
293 jint mMinSize;
294 int mReleaseParam;
295 };
296
297 typedef ArrayHelper<jfloatArray, float, FloatArrayGetter, FloatArrayReleaser> FloatArrayHelper;
298 typedef ArrayHelper<jcharArray, unsigned short, CharArrayGetter, CharArrayReleaser> UnsignedShortArrayHelper;
299 typedef ArrayHelper<jintArray, int, IntArrayGetter, IntArrayReleaser> IntArrayHelper;
300 typedef ArrayHelper<jbyteArray, unsigned char, ByteArrayGetter, ByteArrayReleaser> ByteArrayHelper;
301
distance2(float x,float y,float z)302 inline float distance2(float x, float y, float z) {
303 return x * x + y * y + z * z;
304 }
305
distance(float x,float y,float z)306 inline float distance(float x, float y, float z) {
307 return sqrtf(distance2(x, y, z));
308 }
309
310 static
util_computeBoundingSphere(JNIEnv * env,jclass clazz,jfloatArray positions_ref,jint positionsOffset,jint positionsCount,jfloatArray sphere_ref,jint sphereOffset)311 void util_computeBoundingSphere(JNIEnv *env, jclass clazz,
312 jfloatArray positions_ref, jint positionsOffset, jint positionsCount,
313 jfloatArray sphere_ref, jint sphereOffset) {
314 FloatArrayHelper positions(env, positions_ref, positionsOffset, 0);
315 FloatArrayHelper sphere(env, sphere_ref, sphereOffset, 4);
316
317 bool checkOK = positions.check() && sphere.check();
318 if (! checkOK) {
319 return;
320 }
321
322 positions.bind();
323 sphere.bind();
324
325 if ( positionsCount < 1 ) {
326 doThrowIAE(env, "positionsCount < 1");
327 return;
328 }
329
330 const float* pSrc = positions.mData;
331
332 // find bounding box
333 float x0 = *pSrc++;
334 float x1 = x0;
335 float y0 = *pSrc++;
336 float y1 = y0;
337 float z0 = *pSrc++;
338 float z1 = z0;
339
340 for(int i = 1; i < positionsCount; i++) {
341 {
342 float x = *pSrc++;
343 if (x < x0) {
344 x0 = x;
345 }
346 else if (x > x1) {
347 x1 = x;
348 }
349 }
350 {
351 float y = *pSrc++;
352 if (y < y0) {
353 y0 = y;
354 }
355 else if (y > y1) {
356 y1 = y;
357 }
358 }
359 {
360 float z = *pSrc++;
361 if (z < z0) {
362 z0 = z;
363 }
364 else if (z > z1) {
365 z1 = z;
366 }
367 }
368 }
369
370 // Because we know our input meshes fit pretty well into bounding boxes,
371 // just take the diagonal of the box as defining our sphere.
372 float* pSphere = sphere.mData;
373 float dx = x1 - x0;
374 float dy = y1 - y0;
375 float dz = z1 - z0;
376 *pSphere++ = x0 + dx * 0.5f;
377 *pSphere++ = y0 + dy * 0.5f;
378 *pSphere++ = z0 + dz * 0.5f;
379 *pSphere++ = distance(dx, dy, dz) * 0.5f;
380
381 sphere.commitChanges();
382 }
383
normalizePlane(float * p)384 static void normalizePlane(float* p) {
385 float rdist = 1.0f / distance(p[0], p[1], p[2]);
386 for(int i = 0; i < 4; i++) {
387 p[i] *= rdist;
388 }
389 }
390
dot3(float x0,float y0,float z0,float x1,float y1,float z1)391 static inline float dot3(float x0, float y0, float z0, float x1, float y1, float z1) {
392 return x0 * x1 + y0 * y1 + z0 * z1;
393 }
394
signedDistance(const float * pPlane,float x,float y,float z)395 static inline float signedDistance(const float* pPlane, float x, float y, float z) {
396 return dot3(pPlane[0], pPlane[1], pPlane[2], x, y, z) + pPlane[3];
397 }
398
399 // Return true if the sphere intersects or is inside the frustum
400
sphereHitsFrustum(const float * pFrustum,const float * pSphere)401 static bool sphereHitsFrustum(const float* pFrustum, const float* pSphere) {
402 float x = pSphere[0];
403 float y = pSphere[1];
404 float z = pSphere[2];
405 float negRadius = -pSphere[3];
406 for (int i = 0; i < 6; i++, pFrustum += 4) {
407 if (signedDistance(pFrustum, x, y, z) <= negRadius) {
408 return false;
409 }
410 }
411 return true;
412 }
413
computeFrustum(const float * m,float * f)414 static void computeFrustum(const float* m, float* f) {
415 float m3 = m[3];
416 float m7 = m[7];
417 float m11 = m[11];
418 float m15 = m[15];
419 // right
420 f[0] = m3 - m[0];
421 f[1] = m7 - m[4];
422 f[2] = m11 - m[8];
423 f[3] = m15 - m[12];
424 normalizePlane(f);
425 f+= 4;
426
427 // left
428 f[0] = m3 + m[0];
429 f[1] = m7 + m[4];
430 f[2] = m11 + m[8];
431 f[3] = m15 + m[12];
432 normalizePlane(f);
433 f+= 4;
434
435 // top
436 f[0] = m3 - m[1];
437 f[1] = m7 - m[5];
438 f[2] = m11 - m[9];
439 f[3] = m15 - m[13];
440 normalizePlane(f);
441 f+= 4;
442
443 // bottom
444 f[0] = m3 + m[1];
445 f[1] = m7 + m[5];
446 f[2] = m11 + m[9];
447 f[3] = m15 + m[13];
448 normalizePlane(f);
449 f+= 4;
450
451 // far
452 f[0] = m3 - m[2];
453 f[1] = m7 - m[6];
454 f[2] = m11 - m[10];
455 f[3] = m15 - m[14];
456 normalizePlane(f);
457 f+= 4;
458
459 // near
460 f[0] = m3 + m[2];
461 f[1] = m7 + m[6];
462 f[2] = m11 + m[10];
463 f[3] = m15 + m[14];
464 normalizePlane(f);
465 }
466
467 static
util_frustumCullSpheres(JNIEnv * env,jclass clazz,jfloatArray mvp_ref,jint mvpOffset,jfloatArray spheres_ref,jint spheresOffset,jint spheresCount,jintArray results_ref,jint resultsOffset,jint resultsCapacity)468 jint util_frustumCullSpheres(JNIEnv *env, jclass clazz,
469 jfloatArray mvp_ref, jint mvpOffset,
470 jfloatArray spheres_ref, jint spheresOffset, jint spheresCount,
471 jintArray results_ref, jint resultsOffset, jint resultsCapacity) {
472 float frustum[6*4];
473 int outputCount;
474 int* pResults;
475 float* pSphere;
476 FloatArrayHelper mvp(env, mvp_ref, mvpOffset, 16);
477 FloatArrayHelper spheres(env, spheres_ref, spheresOffset, spheresCount * 4);
478 IntArrayHelper results(env, results_ref, resultsOffset, resultsCapacity);
479
480 bool initializedOK = mvp.check() && spheres.check() && results.check();
481 if (! initializedOK) {
482 return -1;
483 }
484
485 mvp.bind();
486 spheres.bind();
487 results.bind();
488
489 computeFrustum(mvp.mData, frustum);
490
491 // Cull the spheres
492
493 pSphere = spheres.mData;
494 pResults = results.mData;
495 outputCount = 0;
496 for(int i = 0; i < spheresCount; i++, pSphere += 4) {
497 if (sphereHitsFrustum(frustum, pSphere)) {
498 if (outputCount < resultsCapacity) {
499 *pResults++ = i;
500 }
501 outputCount++;
502 }
503 }
504 results.commitChanges();
505 return outputCount;
506 }
507
508 /*
509 public native int visibilityTest(float[] ws, int wsOffset,
510 float[] positions, int positionsOffset,
511 char[] indices, int indicesOffset, int indexCount);
512 */
513
514 static
util_visibilityTest(JNIEnv * env,jclass clazz,jfloatArray ws_ref,jint wsOffset,jfloatArray positions_ref,jint positionsOffset,jcharArray indices_ref,jint indicesOffset,jint indexCount)515 jint util_visibilityTest(JNIEnv *env, jclass clazz,
516 jfloatArray ws_ref, jint wsOffset,
517 jfloatArray positions_ref, jint positionsOffset,
518 jcharArray indices_ref, jint indicesOffset, jint indexCount) {
519
520 FloatArrayHelper ws(env, ws_ref, wsOffset, 16);
521 FloatArrayHelper positions(env, positions_ref, positionsOffset, 0);
522 UnsignedShortArrayHelper indices(env, indices_ref, indicesOffset, 0);
523
524 bool checkOK = ws.check() && positions.check() && indices.check();
525 if (! checkOK) {
526 // Return value will be ignored, because an exception has been thrown.
527 return -1;
528 }
529
530 if (indices.mLength < indexCount) {
531 doThrowIAE(env, "length < offset + indexCount");
532 return -1;
533 }
534
535 ws.bind();
536 positions.bind();
537 indices.bind();
538
539 return visibilityTest(ws.mData,
540 positions.mData, positions.mLength,
541 indices.mData, indexCount);
542 }
543
544 // ---------------------------------------------------------------------------
545
546 // The internal format is no longer the same as pixel format, per Table 2 in
547 // https://www.khronos.org/registry/OpenGL-Refpages/es3.1/html/glTexImage2D.xhtml
checkInternalFormat(int32_t bitmapFormat,int internalformat,int type)548 static bool checkInternalFormat(int32_t bitmapFormat, int internalformat, int type)
549 {
550 if (internalformat == GL_PALETTE8_RGBA8_OES) {
551 return false;
552 }
553 switch(bitmapFormat) {
554 case ANDROID_BITMAP_FORMAT_RGBA_8888:
555 return (type == GL_UNSIGNED_BYTE && internalformat == GL_RGBA) ||
556 (type == GL_UNSIGNED_BYTE && internalformat == GL_SRGB8_ALPHA8);
557 case ANDROID_BITMAP_FORMAT_A_8:
558 return (type == GL_UNSIGNED_BYTE && internalformat == GL_ALPHA);
559 case ANDROID_BITMAP_FORMAT_RGBA_4444:
560 return (type == GL_UNSIGNED_SHORT_4_4_4_4 && internalformat == GL_RGBA);
561 case ANDROID_BITMAP_FORMAT_RGB_565:
562 return (type == GL_UNSIGNED_SHORT_5_6_5 && internalformat == GL_RGB);
563 case ANDROID_BITMAP_FORMAT_RGBA_F16:
564 return (type == GL_HALF_FLOAT && internalformat == GL_RGBA16F);
565 case ANDROID_BITMAP_FORMAT_RGBA_1010102:
566 return (type == GL_UNSIGNED_INT_2_10_10_10_REV && internalformat == GL_RGB10_A2);
567 default:
568 break;
569 }
570 return false;
571 }
572
573 // The internal format is no longer the same as pixel format, per Table 2 in
574 // https://www.khronos.org/registry/OpenGL-Refpages/es3.1/html/glTexImage2D.xhtml
getPixelFormatFromInternalFormat(uint32_t internalFormat)575 static int getPixelFormatFromInternalFormat(uint32_t internalFormat) {
576 switch (internalFormat) {
577 // For sized internal format.
578 case GL_RGBA16F:
579 case GL_SRGB8_ALPHA8:
580 return GL_RGBA;
581 // Base internal formats and pixel formats are still the same, see Table 1 in
582 // https://www.khronos.org/registry/OpenGL-Refpages/es3.1/html/glTexImage2D.xhtml
583 default:
584 return internalFormat;
585 }
586 }
587
getInternalFormat(int32_t bitmapFormat)588 static int getInternalFormat(int32_t bitmapFormat) {
589 switch(bitmapFormat) {
590 case ANDROID_BITMAP_FORMAT_A_8:
591 return GL_ALPHA;
592 case ANDROID_BITMAP_FORMAT_RGBA_4444:
593 return GL_RGBA;
594 case ANDROID_BITMAP_FORMAT_RGBA_8888:
595 return GL_RGBA;
596 case ANDROID_BITMAP_FORMAT_RGB_565:
597 return GL_RGB;
598 case ANDROID_BITMAP_FORMAT_RGBA_F16:
599 return GL_RGBA16F;
600 case ANDROID_BITMAP_FORMAT_RGBA_1010102:
601 return GL_RGB10_A2;
602 default:
603 return -1;
604 }
605 }
606
getType(int32_t bitmapFormat)607 static int getType(int32_t bitmapFormat) {
608 switch(bitmapFormat) {
609 case ANDROID_BITMAP_FORMAT_A_8:
610 return GL_UNSIGNED_BYTE;
611 case ANDROID_BITMAP_FORMAT_RGBA_4444:
612 return GL_UNSIGNED_SHORT_4_4_4_4;
613 case ANDROID_BITMAP_FORMAT_RGBA_8888:
614 return GL_UNSIGNED_BYTE;
615 case ANDROID_BITMAP_FORMAT_RGB_565:
616 return GL_UNSIGNED_SHORT_5_6_5;
617 case ANDROID_BITMAP_FORMAT_RGBA_F16:
618 return GL_HALF_FLOAT;
619 case ANDROID_BITMAP_FORMAT_RGBA_1010102:
620 return GL_UNSIGNED_INT_2_10_10_10_REV;
621 default:
622 return -1;
623 }
624 }
625
util_getInternalFormat(JNIEnv * env,jclass clazz,jobject bitmapObj)626 static jint util_getInternalFormat(JNIEnv *env, jclass clazz, jobject bitmapObj)
627 {
628 graphics::Bitmap bitmap(env, bitmapObj);
629 return getInternalFormat(bitmap.getInfo().format);
630 }
631
util_getType(JNIEnv * env,jclass clazz,jobject bitmapObj)632 static jint util_getType(JNIEnv *env, jclass clazz, jobject bitmapObj)
633 {
634 graphics::Bitmap bitmap(env, bitmapObj);
635 return getType(bitmap.getInfo().format);
636 }
637
util_texImage2D(JNIEnv * env,jclass clazz,jint target,jint level,jint internalformat,jobject bitmapObj,jint type,jint border)638 static jint util_texImage2D(JNIEnv *env, jclass clazz, jint target, jint level,
639 jint internalformat, jobject bitmapObj, jint type, jint border)
640 {
641 graphics::Bitmap bitmap(env, bitmapObj);
642 if (bitmap.isValid() && bitmap.getPixels() != nullptr) {
643 AndroidBitmapInfo bitmapInfo = bitmap.getInfo();
644
645 if (internalformat < 0) {
646 internalformat = getInternalFormat(bitmapInfo.format);
647 }
648 if (type < 0) {
649 type = getType(bitmapInfo.format);
650 }
651
652 if (checkInternalFormat(bitmapInfo.format, internalformat, type)) {
653 glTexImage2D(target, level, internalformat, bitmapInfo.width, bitmapInfo.height, border,
654 getPixelFormatFromInternalFormat(internalformat), type,
655 bitmap.getPixels());
656 return 0;
657 }
658 }
659 return -1;
660 }
661
util_texSubImage2D(JNIEnv * env,jclass clazz,jint target,jint level,jint xoffset,jint yoffset,jobject bitmapObj,jint format,jint type)662 static jint util_texSubImage2D(JNIEnv *env, jclass clazz, jint target, jint level,
663 jint xoffset, jint yoffset, jobject bitmapObj, jint format, jint type)
664 {
665 graphics::Bitmap bitmap(env, bitmapObj);
666 if (bitmap.isValid() && bitmap.getPixels() != nullptr) {
667 AndroidBitmapInfo bitmapInfo = bitmap.getInfo();
668
669 int internalFormat = getInternalFormat(bitmapInfo.format);
670 if (format < 0) {
671 format = getPixelFormatFromInternalFormat(internalFormat);
672 if (format == GL_PALETTE8_RGBA8_OES)
673 return -1; // glCompressedTexSubImage2D() not supported
674 }
675
676 if (checkInternalFormat(bitmapInfo.format, internalFormat, type)) {
677 glTexSubImage2D(target, level, xoffset, yoffset, bitmapInfo.width, bitmapInfo.height,
678 format, type, bitmap.getPixels());
679 return 0;
680 }
681 }
682 return -1;
683 }
684
685 /*
686 * ETC1 methods.
687 */
688
689 static void *
getPointer(JNIEnv * _env,jobject buffer,jint * remaining)690 getPointer(JNIEnv *_env, jobject buffer, jint *remaining)
691 {
692 jint position;
693 jint limit;
694 jint elementSizeShift;
695 jlong pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
696 if (pointer != 0L) {
697 pointer += position << elementSizeShift;
698 }
699 *remaining = (limit - position) << elementSizeShift;
700 return reinterpret_cast<void*>(pointer);
701 }
702
703 class BufferHelper {
704 public:
BufferHelper(JNIEnv * env,jobject buffer)705 BufferHelper(JNIEnv *env, jobject buffer) {
706 mEnv = env;
707 mBuffer = buffer;
708 mData = NULL;
709 mRemaining = 0;
710 }
711
checkPointer(const char * errorMessage)712 bool checkPointer(const char* errorMessage) {
713 if (mBuffer) {
714 mData = getPointer(mEnv, mBuffer, &mRemaining);
715 if (mData == NULL) {
716 doThrowIAE(mEnv, errorMessage);
717 }
718 return mData != NULL;
719 } else {
720 doThrowIAE(mEnv, errorMessage);
721 return false;
722 }
723 }
724
getData()725 inline void* getData() {
726 return mData;
727 }
728
remaining()729 inline jint remaining() {
730 return mRemaining;
731 }
732
733 private:
734 JNIEnv* mEnv;
735 jobject mBuffer;
736 void* mData;
737 jint mRemaining;
738 };
739
740 /**
741 * Encode a block of pixels.
742 *
743 * @param in a pointer to a ETC1_DECODED_BLOCK_SIZE array of bytes that represent a
744 * 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R
745 * value of pixel (x, y).
746 *
747 * @param validPixelMask is a 16-bit mask where bit (1 << (x + y * 4)) indicates whether
748 * the corresponding (x,y) pixel is valid. Invalid pixel color values are ignored when compressing.
749 *
750 * @param out an ETC1 compressed version of the data.
751 *
752 */
etc1_encodeBlock(JNIEnv * env,jclass clazz,jobject in,jint validPixelMask,jobject out)753 static void etc1_encodeBlock(JNIEnv *env, jclass clazz,
754 jobject in, jint validPixelMask, jobject out) {
755 if (validPixelMask < 0 || validPixelMask > 15) {
756 doThrowIAE(env, "validPixelMask");
757 return;
758 }
759 BufferHelper inB(env, in);
760 BufferHelper outB(env, out);
761 if (inB.checkPointer("in") && outB.checkPointer("out")) {
762 if (inB.remaining() < ETC1_DECODED_BLOCK_SIZE) {
763 doThrowIAE(env, "in's remaining data < DECODED_BLOCK_SIZE");
764 } else if (outB.remaining() < ETC1_ENCODED_BLOCK_SIZE) {
765 doThrowIAE(env, "out's remaining data < ENCODED_BLOCK_SIZE");
766 } else {
767 etc1_encode_block((etc1_byte*) inB.getData(), validPixelMask,
768 (etc1_byte*) outB.getData());
769 }
770 }
771 }
772
773 /**
774 * Decode a block of pixels.
775 *
776 * @param in an ETC1 compressed version of the data.
777 *
778 * @param out a pointer to a ETC_DECODED_BLOCK_SIZE array of bytes that represent a
779 * 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R
780 * value of pixel (x, y).
781 */
etc1_decodeBlock(JNIEnv * env,jclass clazz,jobject in,jobject out)782 static void etc1_decodeBlock(JNIEnv *env, jclass clazz,
783 jobject in, jobject out){
784 BufferHelper inB(env, in);
785 BufferHelper outB(env, out);
786 if (inB.checkPointer("in") && outB.checkPointer("out")) {
787 if (inB.remaining() < ETC1_ENCODED_BLOCK_SIZE) {
788 doThrowIAE(env, "in's remaining data < ENCODED_BLOCK_SIZE");
789 } else if (outB.remaining() < ETC1_DECODED_BLOCK_SIZE) {
790 doThrowIAE(env, "out's remaining data < DECODED_BLOCK_SIZE");
791 } else {
792 etc1_decode_block((etc1_byte*) inB.getData(),
793 (etc1_byte*) outB.getData());
794 }
795 }
796 }
797
798 /**
799 * Return the size of the encoded image data (does not include size of PKM header).
800 */
etc1_getEncodedDataSize(JNIEnv * env,jclass clazz,jint width,jint height)801 static jint etc1_getEncodedDataSize(JNIEnv *env, jclass clazz,
802 jint width, jint height) {
803 return etc1_get_encoded_data_size(width, height);
804 }
805
806 /**
807 * Encode an entire image.
808 * @param in pointer to the image data. Formatted such that
809 * pixel (x,y) is at pIn + pixelSize * x + stride * y + redOffset;
810 * @param out pointer to encoded data. Must be large enough to store entire encoded image.
811 */
etc1_encodeImage(JNIEnv * env,jclass clazz,jobject in,jint width,jint height,jint pixelSize,jint stride,jobject out)812 static void etc1_encodeImage(JNIEnv *env, jclass clazz,
813 jobject in, jint width, jint height,
814 jint pixelSize, jint stride, jobject out) {
815 if (pixelSize < 2 || pixelSize > 3) {
816 doThrowIAE(env, "pixelSize must be 2 or 3");
817 return;
818 }
819 BufferHelper inB(env, in);
820 BufferHelper outB(env, out);
821 if (inB.checkPointer("in") && outB.checkPointer("out")) {
822 jint imageSize = stride * height;
823 jint encodedImageSize = etc1_get_encoded_data_size(width, height);
824 if (inB.remaining() < imageSize) {
825 doThrowIAE(env, "in's remaining data < image size");
826 } else if (outB.remaining() < encodedImageSize) {
827 doThrowIAE(env, "out's remaining data < encoded image size");
828 } else {
829 etc1_encode_image((etc1_byte*) inB.getData(), width, height, pixelSize, stride,
830 (etc1_byte*) outB.getData());
831 }
832 }
833 }
834
835 /**
836 * Decode an entire image.
837 * @param in the encoded data.
838 * @param out pointer to the image data. Will be written such that
839 * pixel (x,y) is at pIn + pixelSize * x + stride * y. Must be
840 * large enough to store entire image.
841 */
etc1_decodeImage(JNIEnv * env,jclass clazz,jobject in,jobject out,jint width,jint height,jint pixelSize,jint stride)842 static void etc1_decodeImage(JNIEnv *env, jclass clazz,
843 jobject in, jobject out,
844 jint width, jint height,
845 jint pixelSize, jint stride) {
846 if (pixelSize < 2 || pixelSize > 3) {
847 doThrowIAE(env, "pixelSize must be 2 or 3");
848 return;
849 }
850 BufferHelper inB(env, in);
851 BufferHelper outB(env, out);
852 if (inB.checkPointer("in") && outB.checkPointer("out")) {
853 jint imageSize = stride * height;
854 jint encodedImageSize = etc1_get_encoded_data_size(width, height);
855 if (inB.remaining() < encodedImageSize) {
856 doThrowIAE(env, "in's remaining data < encoded image size");
857 } else if (outB.remaining() < imageSize) {
858 doThrowIAE(env, "out's remaining data < image size");
859 } else {
860 etc1_decode_image((etc1_byte*) inB.getData(), (etc1_byte*) outB.getData(),
861 width, height, pixelSize, stride);
862 }
863 }
864 }
865
866 /**
867 * Format a PKM header
868 */
etc1_formatHeader(JNIEnv * env,jclass clazz,jobject header,jint width,jint height)869 static void etc1_formatHeader(JNIEnv *env, jclass clazz,
870 jobject header, jint width, jint height) {
871 BufferHelper headerB(env, header);
872 if (headerB.checkPointer("header") ){
873 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
874 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
875 } else {
876 etc1_pkm_format_header((etc1_byte*) headerB.getData(), width, height);
877 }
878 }
879 }
880
881 /**
882 * Check if a PKM header is correctly formatted.
883 */
etc1_isValid(JNIEnv * env,jclass clazz,jobject header)884 static jboolean etc1_isValid(JNIEnv *env, jclass clazz,
885 jobject header) {
886 jboolean result = false;
887 BufferHelper headerB(env, header);
888 if (headerB.checkPointer("header") ){
889 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
890 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
891 } else {
892 result = etc1_pkm_is_valid((etc1_byte*) headerB.getData());
893 }
894 }
895 return result ? JNI_TRUE : JNI_FALSE;
896 }
897
898 /**
899 * Read the image width from a PKM header
900 */
etc1_getWidth(JNIEnv * env,jclass clazz,jobject header)901 static jint etc1_getWidth(JNIEnv *env, jclass clazz,
902 jobject header) {
903 jint result = 0;
904 BufferHelper headerB(env, header);
905 if (headerB.checkPointer("header") ){
906 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
907 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
908 } else {
909 result = etc1_pkm_get_width((etc1_byte*) headerB.getData());
910 }
911 }
912 return result;
913 }
914
915 /**
916 * Read the image height from a PKM header
917 */
etc1_getHeight(JNIEnv * env,jclass clazz,jobject header)918 static jint etc1_getHeight(JNIEnv *env, jclass clazz,
919 jobject header) {
920 jint result = 0;
921 BufferHelper headerB(env, header);
922 if (headerB.checkPointer("header") ){
923 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
924 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
925 } else {
926 result = etc1_pkm_get_height((etc1_byte*) headerB.getData());
927 }
928 }
929 return result;
930 }
931
932 /*
933 * JNI registration
934 */
935
936 static const JNINativeMethod gVisibilityMethods[] = {
937 { "computeBoundingSphere", "([FII[FI)V", (void*)util_computeBoundingSphere },
938 { "frustumCullSpheres", "([FI[FII[III)I", (void*)util_frustumCullSpheres },
939 { "visibilityTest", "([FI[FI[CII)I", (void*)util_visibilityTest },
940 };
941
942 static const JNINativeMethod gUtilsMethods[] = {
943 { "native_getInternalFormat", "(Landroid/graphics/Bitmap;)I", (void*) util_getInternalFormat },
944 { "native_getType", "(Landroid/graphics/Bitmap;)I", (void*) util_getType },
945 { "native_texImage2D", "(IIILandroid/graphics/Bitmap;II)I", (void*)util_texImage2D },
946 { "native_texSubImage2D", "(IIIILandroid/graphics/Bitmap;II)I", (void*)util_texSubImage2D },
947 };
948
949 static const JNINativeMethod gEtc1Methods[] = {
950 { "encodeBlock", "(Ljava/nio/Buffer;ILjava/nio/Buffer;)V", (void*) etc1_encodeBlock },
951 { "decodeBlock", "(Ljava/nio/Buffer;Ljava/nio/Buffer;)V", (void*) etc1_decodeBlock },
952 { "getEncodedDataSize", "(II)I", (void*) etc1_getEncodedDataSize },
953 { "encodeImage", "(Ljava/nio/Buffer;IIIILjava/nio/Buffer;)V", (void*) etc1_encodeImage },
954 { "decodeImage", "(Ljava/nio/Buffer;Ljava/nio/Buffer;IIII)V", (void*) etc1_decodeImage },
955 { "formatHeader", "(Ljava/nio/Buffer;II)V", (void*) etc1_formatHeader },
956 { "isValid", "(Ljava/nio/Buffer;)Z", (void*) etc1_isValid },
957 { "getWidth", "(Ljava/nio/Buffer;)I", (void*) etc1_getWidth },
958 { "getHeight", "(Ljava/nio/Buffer;)I", (void*) etc1_getHeight },
959 };
960
961 typedef struct _ClassRegistrationInfo {
962 const char* classPath;
963 const JNINativeMethod* methods;
964 size_t methodCount;
965 } ClassRegistrationInfo;
966
967 static const ClassRegistrationInfo gClasses[] = {
968 {"android/opengl/Visibility", gVisibilityMethods, NELEM(gVisibilityMethods)},
969 {"android/opengl/GLUtils", gUtilsMethods, NELEM(gUtilsMethods)},
970 {"android/opengl/ETC1", gEtc1Methods, NELEM(gEtc1Methods)},
971 };
972
register_android_opengl_classes(JNIEnv * env)973 int register_android_opengl_classes(JNIEnv* env)
974 {
975 int result = 0;
976 for (int i = 0; i < NELEM(gClasses); i++) {
977 const ClassRegistrationInfo* cri = &gClasses[i];
978 result = RegisterMethodsOrDie(env, cri->classPath, cri->methods, cri->methodCount);
979 }
980 return result;
981 }
982
983 } // namespace android
984