1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Low-level services to load pixel data from the assets
18 intrude import android
::assets_and_resources
21 redef class CByteArray
22 # Get a `Java_nio_ByteBuffer` wrapping `native_array`
23 fun to_java_nio_buffer
: Java_nio_ByteBuffer
25 return jni_env
.new_direct_byte_buffer
(native_array
, length
)
29 redef extern class NativeBitmap
31 # Copy the pixel data into a new `CByteArray`
33 # If `pad_to_pow2` the new buffer contains artificial pixels used to make
34 # the width and the height powers of 2 for compatibility with older OpenGL.
36 # If `unmultiply`, extra work is done to revert the multiplication of color
37 # values per the alpha channel applied by the Android system.
38 fun copy_pixels
(pad_to_pow2
, unmultiply
: nullable Bool): CByteArray
41 var row_bytes
= row_bytes
42 var bytes
= row_bytes
* height
44 var w2
= width
.next_pow
(2)
45 var h2
= height
.next_pow
(2)
46 var row_bytes2
= row_bytes
* w2
/ width
49 if pad_to_pow2
== true then capacity
= row_bytes2
* h2
51 var buf
= new CByteArray(capacity
)
52 var java_buf
= buf
.to_java_nio_buffer
53 copy_pixels_to_buffer java_buf
55 if has_alpha
and unmultiply
== true then buf
.native_array
.unmultiply
(width
, height
)
57 if pad_to_pow2
== true then
58 for r
in [height-1
..0[.step
(-1) do
59 var src_offset
= row_bytes
*r
60 var dst_offset
= row_bytes2
*r
61 buf
.move
(dst_offset
, src_offset
, row_bytes
)
68 # Copy raw pixel data to `buffer`
70 # Wraps Java: `void android.graphics.Bitmap.copyPixelsToBuffer(java.nio.Buffer)`
71 fun copy_pixels_to_buffer
(buffer
: Java_nio_Buffer) in "Java" `{
72 self.copyPixelsToBuffer(buffer);
77 # The first power of `exp` greater or equal to `self`
78 private fun next_pow
(exp
: Int): Int
81 while p
< self do p
= p
*exp
86 redef class NativeCByteArray
87 # Reverse Android multiplication of color values per the alpha channel
88 private fun unmultiply
(w
, h
: Int) `{
91 for (x = 0; x < w; x ++)
92 for (y = 0; y < h; y ++) {
93 unsigned char a = self[offset+3];
94 if (a != 0 && a != 0xFF) {
95 self[offset] = self[offset] * 256 / a;
96 self[offset+1] = self[offset+1] * 256 / a;
97 self[offset+2] = self[offset+2] * 256 / a;