Debian Codegraph @

core/jni/android/opengl/util.cpp

raw symbols SCIP
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
44 static void doThrowIAE(JNIEnv* env, const char* msg = nullptr) {
45 jniThrowException(env, "java/lang/IllegalArgumentException", msg);
46 }
47
48 static inline
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
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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
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
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
276 void bind() {
277 mBase = (T*) ArrayGetter::Get(mEnv, mRef, (jboolean *) 0);
278 mData = mBase + mOffset;
279 }
280
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
302 inline float distance2(float x, float y, float z) {
303 return x * x + y * y + z * z;
304 }
305
306 inline float distance(float x, float y, float z) {
307 return sqrtf(distance2(x, y, z));
308 }
309
310 static
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 AndroidBitmapInfo bitmapInfo = bitmap.getInfo();
643
644 if (internalformat < 0) {
645 internalformat = getInternalFormat(bitmapInfo.format);
646 }
647 if (type < 0) {
648 type = getType(bitmapInfo.format);
649 }
650
651 if (checkInternalFormat(bitmapInfo.format, internalformat, type)) {
652 glTexImage2D(target, level, internalformat, bitmapInfo.width, bitmapInfo.height, border,
653 getPixelFormatFromInternalFormat(internalformat), type, bitmap.getPixels());
654 return 0;
655 }
656 return -1;
657 }
658
659 static jint util_texSubImage2D(JNIEnv *env, jclass clazz, jint target, jint level,
660 jint xoffset, jint yoffset, jobject bitmapObj, jint format, jint type)
661 {
662 graphics::Bitmap bitmap(env, bitmapObj);
663 AndroidBitmapInfo bitmapInfo = bitmap.getInfo();
664
665 int internalFormat = getInternalFormat(bitmapInfo.format);
666 if (format < 0) {
667 format = getPixelFormatFromInternalFormat(internalFormat);
668 if (format == GL_PALETTE8_RGBA8_OES)
669 return -1; // glCompressedTexSubImage2D() not supported
670 }
671
672 if (checkInternalFormat(bitmapInfo.format, internalFormat, type)) {
673 glTexSubImage2D(target, level, xoffset, yoffset, bitmapInfo.width, bitmapInfo.height,
674 format, type, bitmap.getPixels());
675 return 0;
676 }
677 return -1;
678 }
679
680 /*
681 * ETC1 methods.
682 */
683
684 static void *
685 getPointer(JNIEnv *_env, jobject buffer, jint *remaining)
686 {
687 jint position;
688 jint limit;
689 jint elementSizeShift;
690 jlong pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
691 if (pointer != 0L) {
692 pointer += position << elementSizeShift;
693 }
694 *remaining = (limit - position) << elementSizeShift;
695 return reinterpret_cast<void*>(pointer);
696 }
697
698 class BufferHelper {
699 public:
700 BufferHelper(JNIEnv *env, jobject buffer) {
701 mEnv = env;
702 mBuffer = buffer;
703 mData = NULL;
704 mRemaining = 0;
705 }
706
707 bool checkPointer(const char* errorMessage) {
708 if (mBuffer) {
709 mData = getPointer(mEnv, mBuffer, &mRemaining);
710 if (mData == NULL) {
711 doThrowIAE(mEnv, errorMessage);
712 }
713 return mData != NULL;
714 } else {
715 doThrowIAE(mEnv, errorMessage);
716 return false;
717 }
718 }
719
720 inline void* getData() {
721 return mData;
722 }
723
724 inline jint remaining() {
725 return mRemaining;
726 }
727
728 private:
729 JNIEnv* mEnv;
730 jobject mBuffer;
731 void* mData;
732 jint mRemaining;
733 };
734
735 /**
736 * Encode a block of pixels.
737 *
738 * @param in a pointer to a ETC1_DECODED_BLOCK_SIZE array of bytes that represent a
739 * 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R
740 * value of pixel (x, y).
741 *
742 * @param validPixelMask is a 16-bit mask where bit (1 << (x + y * 4)) indicates whether
743 * the corresponding (x,y) pixel is valid. Invalid pixel color values are ignored when compressing.
744 *
745 * @param out an ETC1 compressed version of the data.
746 *
747 */
748 static void etc1_encodeBlock(JNIEnv *env, jclass clazz,
749 jobject in, jint validPixelMask, jobject out) {
750 if (validPixelMask < 0 || validPixelMask > 15) {
751 doThrowIAE(env, "validPixelMask");
752 return;
753 }
754 BufferHelper inB(env, in);
755 BufferHelper outB(env, out);
756 if (inB.checkPointer("in") && outB.checkPointer("out")) {
757 if (inB.remaining() < ETC1_DECODED_BLOCK_SIZE) {
758 doThrowIAE(env, "in's remaining data < DECODED_BLOCK_SIZE");
759 } else if (outB.remaining() < ETC1_ENCODED_BLOCK_SIZE) {
760 doThrowIAE(env, "out's remaining data < ENCODED_BLOCK_SIZE");
761 } else {
762 etc1_encode_block((etc1_byte*) inB.getData(), validPixelMask,
763 (etc1_byte*) outB.getData());
764 }
765 }
766 }
767
768 /**
769 * Decode a block of pixels.
770 *
771 * @param in an ETC1 compressed version of the data.
772 *
773 * @param out a pointer to a ETC_DECODED_BLOCK_SIZE array of bytes that represent a
774 * 4 x 4 square of 3-byte pixels in form R, G, B. Byte (3 * (x + 4 * y) is the R
775 * value of pixel (x, y).
776 */
777 static void etc1_decodeBlock(JNIEnv *env, jclass clazz,
778 jobject in, jobject out){
779 BufferHelper inB(env, in);
780 BufferHelper outB(env, out);
781 if (inB.checkPointer("in") && outB.checkPointer("out")) {
782 if (inB.remaining() < ETC1_ENCODED_BLOCK_SIZE) {
783 doThrowIAE(env, "in's remaining data < ENCODED_BLOCK_SIZE");
784 } else if (outB.remaining() < ETC1_DECODED_BLOCK_SIZE) {
785 doThrowIAE(env, "out's remaining data < DECODED_BLOCK_SIZE");
786 } else {
787 etc1_decode_block((etc1_byte*) inB.getData(),
788 (etc1_byte*) outB.getData());
789 }
790 }
791 }
792
793 /**
794 * Return the size of the encoded image data (does not include size of PKM header).
795 */
796 static jint etc1_getEncodedDataSize(JNIEnv *env, jclass clazz,
797 jint width, jint height) {
798 return etc1_get_encoded_data_size(width, height);
799 }
800
801 /**
802 * Encode an entire image.
803 * @param in pointer to the image data. Formatted such that
804 * pixel (x,y) is at pIn + pixelSize * x + stride * y + redOffset;
805 * @param out pointer to encoded data. Must be large enough to store entire encoded image.
806 */
807 static void etc1_encodeImage(JNIEnv *env, jclass clazz,
808 jobject in, jint width, jint height,
809 jint pixelSize, jint stride, jobject out) {
810 if (pixelSize < 2 || pixelSize > 3) {
811 doThrowIAE(env, "pixelSize must be 2 or 3");
812 return;
813 }
814 BufferHelper inB(env, in);
815 BufferHelper outB(env, out);
816 if (inB.checkPointer("in") && outB.checkPointer("out")) {
817 jint imageSize = stride * height;
818 jint encodedImageSize = etc1_get_encoded_data_size(width, height);
819 if (inB.remaining() < imageSize) {
820 doThrowIAE(env, "in's remaining data < image size");
821 } else if (outB.remaining() < encodedImageSize) {
822 doThrowIAE(env, "out's remaining data < encoded image size");
823 } else {
824 etc1_encode_image((etc1_byte*) inB.getData(), width, height, pixelSize, stride,
825 (etc1_byte*) outB.getData());
826 }
827 }
828 }
829
830 /**
831 * Decode an entire image.
832 * @param in the encoded data.
833 * @param out pointer to the image data. Will be written such that
834 * pixel (x,y) is at pIn + pixelSize * x + stride * y. Must be
835 * large enough to store entire image.
836 */
837 static void etc1_decodeImage(JNIEnv *env, jclass clazz,
838 jobject in, jobject out,
839 jint width, jint height,
840 jint pixelSize, jint stride) {
841 if (pixelSize < 2 || pixelSize > 3) {
842 doThrowIAE(env, "pixelSize must be 2 or 3");
843 return;
844 }
845 BufferHelper inB(env, in);
846 BufferHelper outB(env, out);
847 if (inB.checkPointer("in") && outB.checkPointer("out")) {
848 jint imageSize = stride * height;
849 jint encodedImageSize = etc1_get_encoded_data_size(width, height);
850 if (inB.remaining() < encodedImageSize) {
851 doThrowIAE(env, "in's remaining data < encoded image size");
852 } else if (outB.remaining() < imageSize) {
853 doThrowIAE(env, "out's remaining data < image size");
854 } else {
855 etc1_decode_image((etc1_byte*) inB.getData(), (etc1_byte*) outB.getData(),
856 width, height, pixelSize, stride);
857 }
858 }
859 }
860
861 /**
862 * Format a PKM header
863 */
864 static void etc1_formatHeader(JNIEnv *env, jclass clazz,
865 jobject header, jint width, jint height) {
866 BufferHelper headerB(env, header);
867 if (headerB.checkPointer("header") ){
868 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
869 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
870 } else {
871 etc1_pkm_format_header((etc1_byte*) headerB.getData(), width, height);
872 }
873 }
874 }
875
876 /**
877 * Check if a PKM header is correctly formatted.
878 */
879 static jboolean etc1_isValid(JNIEnv *env, jclass clazz,
880 jobject header) {
881 jboolean result = false;
882 BufferHelper headerB(env, header);
883 if (headerB.checkPointer("header") ){
884 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
885 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
886 } else {
887 result = etc1_pkm_is_valid((etc1_byte*) headerB.getData());
888 }
889 }
890 return result ? JNI_TRUE : JNI_FALSE;
891 }
892
893 /**
894 * Read the image width from a PKM header
895 */
896 static jint etc1_getWidth(JNIEnv *env, jclass clazz,
897 jobject header) {
898 jint result = 0;
899 BufferHelper headerB(env, header);
900 if (headerB.checkPointer("header") ){
901 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
902 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
903 } else {
904 result = etc1_pkm_get_width((etc1_byte*) headerB.getData());
905 }
906 }
907 return result;
908 }
909
910 /**
911 * Read the image height from a PKM header
912 */
913 static jint etc1_getHeight(JNIEnv *env, jclass clazz,
914 jobject header) {
915 jint result = 0;
916 BufferHelper headerB(env, header);
917 if (headerB.checkPointer("header") ){
918 if (headerB.remaining() < ETC_PKM_HEADER_SIZE) {
919 doThrowIAE(env, "header's remaining data < ETC_PKM_HEADER_SIZE");
920 } else {
921 result = etc1_pkm_get_height((etc1_byte*) headerB.getData());
922 }
923 }
924 return result;
925 }
926
927 /*
928 * JNI registration
929 */
930
931 static const JNINativeMethod gVisibilityMethods[] = {
932 { "computeBoundingSphere", "([FII[FI)V", (void*)util_computeBoundingSphere },
933 { "frustumCullSpheres", "([FI[FII[III)I", (void*)util_frustumCullSpheres },
934 { "visibilityTest", "([FI[FI[CII)I", (void*)util_visibilityTest },
935 };
936
937 static const JNINativeMethod gUtilsMethods[] = {
938 { "native_getInternalFormat", "(Landroid/graphics/Bitmap;)I", (void*) util_getInternalFormat },
939 { "native_getType", "(Landroid/graphics/Bitmap;)I", (void*) util_getType },
940 { "native_texImage2D", "(IIILandroid/graphics/Bitmap;II)I", (void*)util_texImage2D },
941 { "native_texSubImage2D", "(IIIILandroid/graphics/Bitmap;II)I", (void*)util_texSubImage2D },
942 };
943
944 static const JNINativeMethod gEtc1Methods[] = {
945 { "encodeBlock", "(Ljava/nio/Buffer;ILjava/nio/Buffer;)V", (void*) etc1_encodeBlock },
946 { "decodeBlock", "(Ljava/nio/Buffer;Ljava/nio/Buffer;)V", (void*) etc1_decodeBlock },
947 { "getEncodedDataSize", "(II)I", (void*) etc1_getEncodedDataSize },
948 { "encodeImage", "(Ljava/nio/Buffer;IIIILjava/nio/Buffer;)V", (void*) etc1_encodeImage },
949 { "decodeImage", "(Ljava/nio/Buffer;Ljava/nio/Buffer;IIII)V", (void*) etc1_decodeImage },
950 { "formatHeader", "(Ljava/nio/Buffer;II)V", (void*) etc1_formatHeader },
951 { "isValid", "(Ljava/nio/Buffer;)Z", (void*) etc1_isValid },
952 { "getWidth", "(Ljava/nio/Buffer;)I", (void*) etc1_getWidth },
953 { "getHeight", "(Ljava/nio/Buffer;)I", (void*) etc1_getHeight },
954 };
955
956 typedef struct _ClassRegistrationInfo {
957 const char* classPath;
958 const JNINativeMethod* methods;
959 size_t methodCount;
960 } ClassRegistrationInfo;
961
962 static const ClassRegistrationInfo gClasses[] = {
963 {"android/opengl/Visibility", gVisibilityMethods, NELEM(gVisibilityMethods)},
964 {"android/opengl/GLUtils", gUtilsMethods, NELEM(gUtilsMethods)},
965 {"android/opengl/ETC1", gEtc1Methods, NELEM(gEtc1Methods)},
966 };
967
968 int register_android_opengl_classes(JNIEnv* env)
969 {
970 int result = 0;
971 for (int i = 0; i < NELEM(gClasses); i++) {
972 const ClassRegistrationInfo* cri = &gClasses[i];
973 result = RegisterMethodsOrDie(env, cri->classPath, cri->methods, cri->methodCount);
974 }
975 return result;
976 }
977
978 } // namespace android