Judul
BELAJAR CEPAT DAN PRAKTIS TENTANG GRAFIKA KOMPUTER (Teori & Aplikasi) “Untuk Pengembangan Aplikasi Mobile Dengan Menggunakan Eclipse Bundle Android, Android Studio Dan OpenGL ES”
Oleh : Imam Cholissodin Maya Kurniawati, dkk.
PENGANTAR Modul ini disusun untuk memberikan pemahaman konsep dasar dan detail pengembangan Grafika Komputer berbasis aplikasi Mobile. Materi yang tersedia selain memudahkan para developer, juga untuk mendukung perkuliahan yang membantu pengayaan mahasiswa. Imam Cholissodin S.Si., M.Kom Dosen Pengampu MK Grafika Komputer FILKOM UB
2014-2016
Kata Pengantar
Alhamdulillahhi robbil alamin, puji syukur kehadirat Allah SWT atas segala rahmat dan karunia-Nya dengan terselesaikannya penulisan modul ini dengan judul “Belajar Cepat & Praktis Tentang Grafika Komputer (Teori & Aplikasi) Untuk Pengembangan Aplikasi Mobile Dengan Menggunakan Eclipse Bundle Android Dan OpenGL”. Buku ini merupakan uraian dari pemahaman konsep dasar dalam grafika komputer dan penerapannya, dengan mengedepankan keterampilan dalam pembuatan dan menampilkan grafik komputer serta berbagai algoritmanya, untuk mengaplikasikan grafika komputer pada pemodelan agar memudahkan dalam pembuatan visualisasi informasi menjadi bentuk geometri, serta mengembangkan teori geometri pada pembuatan grafik komputer untuk tingkat lanjut yang lebih kompleks. Grafika komputer telah banyak diaplikasikan pada beberapa perangkat lunak dengan bahasa pemrograman yang populer seperti C/C++, Java, dan lainnya. Namun aplikasi grafika komputer pada perangkat Mobile (Smartphone) masih jarang ditemukan (sangat langka), terutama dalam bentuk buku yang berbahasa Indonesia. Dan teknologi Mobile saat ini memang sedang naik daun, baik dimata pengembang Aplikasi (Developer) maupun dikalangan pengguna (End User). Hal inilah yang mendasari penulis untuk menyusun catatan-catatan kecil untuk dibuat sebuah naskah tulisan yang mudah untuk dipahami. Dan penulis mengucapkan terimakasih yang sebesarbesarnya kepada beberapa pihak terkait yang telah membantu dalam penyelesaian buku ini : 1. Para penulis artikel tentang grafika komputer di forum, web, blog dan buku yang menjadi referensi buku ini, dan memberi masukan yang sangat berharga untuk perbaikan dan penyelesaian buku ini. 2. Mbak Maya Kurniawati, yang telah banyak membantu penulisan buku ini. Dan beberapa mahasiswa terbaik saya lainnya (M. Abyan Safitra, M. Fatqur Rohman, Abdul Khoir, Faisol Andi Sefihara, Faisal Akbar, Pasca Immanuddin, Dani Devito, dkk.). Semoga kontribusi kalian menjadi ilmu yang barokah dan bermanfaat. Amiin. :) Buku ini masih jauh dari sempurna, begitulah kata yang tepat terkait dengan buku ini. Maka penulis mohon kritik dan saran untuk perbaikan dan penyempurnaan buku ini. Selamat membaca buku ini dan semoga bermanfaat. Malang, 19 Agustus 2014 Penulis ii
Daftar Isi
Judul ...................................................................................................... i Kata Pengantar ..................................................................................... ii Daftar Isi ...............................................................................................iii Daftar Tabel .........................................................................................vii Daftar Gambar .................................................................................... viii Daftar Source Code ........................................................................... xxii BAB 1
Introduction to OpenGL.................................................... 1 1.1
Pengertian Grafika Komputer .......................................... 1
1.2
Persiapan di Eclipse (ADT) .............................................. 1
1.3
BAB 2
1.2.1
Fast Emulator With Intel (HAXM) ......................... 1
1.2.2
Konfigurasi "Eclipse + Bluestacks" ...................... 7
1.2.3
Konfigurasi "Eclipse + Genymotion" .................. 14
1.2.4
Konfigurasi pada Smartphone Android .............. 35
1.2.5
Solusi Error/Problem/Bug .................................. 38
1.2.6
Membuat Project Baru ....................................... 42
1.2.7
Siklus Hidup Kode Program ............................... 45
Persiapan di Android Studio (AS) .................................. 46 1.3.1
Installasi Android Studio .................................... 46
1.3.2
View SDK Android Studio .................................. 61
1.3.3
Solusi Error/ Problem Android Studio ................ 64
1.3.4
Compare Eclipse dengan Android Studio .......... 92
1.3.5
Membuat AVD baru dari AVD Manager............. 93
1.3.6
Import Project Eclipse ke Android Studio ........ 102
1.3.7
Konfigurasi pada Smartphone Android ............ 120
1.3.8
Konfigurasi "AS + Genymotion" ....................... 121
1.3.9
Membuat Project Baru di AS............................ 155
1.3.10
Membuat Module Baru di Project AS............. 164
Primitives Object .......................................................... 169 2.1
Pengertian Primitives Object........................................ 169 iii
2.2
Membuat Titik............................................................... 170
2.3
Membuat Garis dengan Titik ........................................ 182
2.4
Membuat Segitiga & Segiempat .................................. 198
2.5
Membuat Polygon/Segibanyak .................................... 232
2.6
Membuat Lingkaran ..................................................... 247
2.7
Membuat Polar Object ................................................. 279
BAB 3
Transformations ........................................................... 286 3.1
Pengertian Transformasi.............................................. 286
3.2
Matematika & Proses Transformasi ............................. 286
3.3
Urutan Transformasi .................................................... 290
3.4
Membuat Kincir Angin .................................................. 290
BAB 4
Viewing / Camera ......................................................... 300 4.1
Pengertian Viewing / Camera ...................................... 300 4.1.1
Proyeksi Paralel ............................................... 300
4.1.2
Syntax Proyeksi Paralel ................................... 300
4.1.3
Proyeksi Perspektif .......................................... 301
4.1.4
Syntax Proyeksi Perspektif .............................. 301
4.2
Matematika Synthetic Camera ..................................... 303
4.3
Membuat Multiple View Object .................................... 307
BAB 5
Texture Mapping .......................................................... 317 5.1
Pengertian Texture Mapping........................................ 317
5.2
Representasi Texture Mapping .................................... 318
5.3
Parameter Texture Mapping ........................................ 319
5.4
Texture Mapping Pada Segitiga................................... 321
5.5
Texture Mapping Pada Lingkaran ................................ 339
5.6
Texture Mapping Pada Kubus ..................................... 359
5.7
Texture Mapping Pada Bola ........................................ 367
BAB 6
Blending ....................................................................... 378 6.1
Pengertian Blending ..................................................... 378
6.2
Source and Destination Factor Pada Blending ............ 379
6.3
Matematika Blending ................................................... 379 iv
6.4
Blending Dua Segitiga ................................................. 381
6.5
Blending Pada Kubus .................................................. 400
6.6
Blending Pada Bola ..................................................... 411
BAB 7
Lighting & Shading ....................................................... 422 7.1
Pengertian Lighting & Shading .................................... 422
7.2
Proses dan Fungsi Pada Lighting ................................ 423
7.3
Normal Vektor Pada Lighting ....................................... 424
7.4
Lighting Pada Interior ................................................... 425
BAB 8
Model Loading & Curve ............................................... 542 8.1
Pengertian Model Loading & Curve ............................. 542
8.2
Model Creator .............................................................. 543
8.3
Model Loading ............................................................. 544
8.4
Fractal Curve................................................................ 551
BAB 9
Project Pilihan .............................................................. 558 9.1
9.2
9.3
9.4
Random Maze .............................................................. 558 9.1.1
Konsep ............................................................. 558
9.1.2
Tampilan Implementasi .................................... 558
9.1.3
Source Code .................................................... 560
Smart Flappy ................................................................ 723 9.2.1
Konsep ............................................................. 723
9.2.2
Tampilan Implementasi .................................... 723
9.2.3
Source Code .................................................... 725
Chicken Hero ............................................................... 760 9.3.1
Konsep ............................................................. 760
9.3.2
Fungsi Dasar Pembentuk Objek ...................... 761
9.3.3
Tampilan Implementasi .................................... 762
9.3.4
Source Code .................................................... 763
Ayo Nyoblos ................................................................. 854 9.4.1
Konsep ............................................................. 854
9.4.2
Fitur/Menu ........................................................ 855
9.4.3
Tampilan Implementasi .................................... 855 v
9.4.4 9.5
9.6
9.7
9.8
Source Code .................................................... 857
Touch Your Coin .......................................................... 918 9.5.1
Konsep ............................................................. 918
9.5.2
Fungsi Dasar Pembentuk Objek ...................... 920
9.5.3
Tampilan Implementasi .................................... 921
9.5.4
Source Code .................................................... 923
Zoo Photo Attack ....................................................... 1064 9.6.1
Konsep ........................................................... 1064
9.6.2
Nilai-Nilai Edukasi .......................................... 1064
9.6.3
Fitur Yang Digunakan .................................... 1065
9.6.4
Tampilan Implementasi .................................. 1065
9.6.5
Source Code .................................................. 1066
Ular Tangga ............................................................... 1118 9.7.1
Konsep ........................................................... 1118
9.7.2
Peraturan Permainan ..................................... 1119
9.7.3
Nilai-Nilai Edukasi .......................................... 1120
9.7.4
Fitur Yang Digunakan .................................... 1121
9.7.5
Fungsi Dasar Pembentuk Objek .................... 1121
9.7.6
Tampilan Implementasi .................................. 1124
9.7.7
Source Code .................................................. 1127
Math Snail .................................................................. 1158 9.8.1
Konsep ........................................................... 1158
9.8.2
Fungsi Dasar Pembentuk Objek .................... 1159
9.8.3
Tampilan Implementasi .................................. 1175
9.8.4
Source Code .................................................. 1177
Daftar Pustaka ................................................................................ 1311 Biografi Penulis ............................................................................... 1312
vi
Daftar Tabel
Tabel 1.1 Log “Run adb.exe by cmd as Administrator” ...................... 75 Tabel 1.2 Concepts Map : Eclipse Vs Android Studio ........................ 92 Tabel 9.1 Fungsi Dasar Pembentuk Objek ...................................... 761 Tabel 9.2 Fungsi Dasar Pembentuk Objek ...................................... 920 Tabel 9.3 Fungsi Dasar Pembentuk Objek .................................... 1122 Tabel 9.4 Fungsi Dasar Pembentuk Objek .................................... 1159
vii
Daftar Gambar
Gambar 1.1 Android SDK Manager Sebelum Klik Deselect All ........... 2 Gambar 1.2 Klik Intel x86 Atom System Image.................................... 2 Gambar 1.3 Beri tanda cek Intel x86 Emulator Accelerator (HAXM) ... 3 Gambar 1.4 Klik Install 2 packages ...................................................... 3 Gambar 1.5 Klik Android SDK License lalu klik Accept Lisense .......... 4 Gambar 1.6 Klik Intel Android Extra License lalu klik Accept Lisense . 4 Gambar 1.7 Proses Download ............................................................. 4 Gambar 1.8 Tampilan setelah download dan instalasiselesai ............. 5 Gambar 1.9 Membuat Android Virtual Device (AVD) baru................... 6 Gambar 1.10 Klik AVD pada list lalu klik Start ..................................... 6 Gambar 1.11 Intel HAXM ..................................................................... 7 Gambar 1.12 Tampilan AVD ................................................................ 7 Gambar 1.13 Download SDK ADT Bundle Eclipse .............................. 8 Gambar 1.14 Download Bluestacks ..................................................... 8 Gambar 1.15 ADW Launcher ............................................................... 9 Gambar 1.16 Interface Bluestacks ....................................................... 9 Gambar 1.17 Pesan “Failed to create the Java Virtual Machine” ........ 9 Gambar 1.18 Advanced system settings............................................ 10 Gambar 1.19 Click Path ..................................................................... 11 Gambar 1.20 Edit System Variables .................................................. 11 Gambar 1.21 Menjalankan cmd ......................................................... 12 Gambar 1.22 Command masuk ke folder BlueStacks ....................... 12 Gambar 1.23 HD-Adb.exe start-server............................................... 12 Gambar 1.24 Setelah HD-Adb.exe start-server dijalankan ................ 13 Gambar 1.25 Klik"Window ->"Show view"->“Other” ........................... 13 Gambar 1.26 Tampilan device pada Bluestacks emulator................. 14 Gambar 1.27 Android Device Chooser .............................................. 14 Gambar 1.28 Main Window Genymotion ........................................... 15 Gambar 1.29 Pop-up Menambah Virtual Device ............................... 15 viii
Gambar 1.30 Klik OK.......................................................................... 15 Gambar 1.31 Isi Username/Password ,Connect ................................ 16 Gambar 1.32 Pilih Virtual Device ....................................................... 16 Gambar 1.33 Beri Nama Virtual Device ............................................. 17 Gambar 1.34 Virtual Device Terdownload & Terdeploy ..................... 17 Gambar 1.35 Deployment window Finish........................................... 18 Gambar 1.36 Play............................................................................... 18 Gambar 1.37 File .ova ........................................................................ 19 Gambar 1.38 Deploying virtual device.. ............................................. 19 Gambar 1.39 Virtual device Finish ..................................................... 20 Gambar 1.40 Virtual device is Ready ................................................. 20 Gambar 1.41 Import Virtual Devices (*.ova) di Virtual Box ................ 21 Gambar 1.42 Virtual device is Ready Pada Virtual Box ..................... 22 Gambar 1.43 Virtual device is Ready Pada Genymotion ................... 22 Gambar 1.44 Set Letak Android SDK di Genymotion ........................ 23 Gambar 1.45 Add Repository, lalu klik OK ......................................... 23 Gambar 1.46 There are not categorized items................................... 24 Gambar 1.47 Uncheck “Group items by category” ............................. 24 Gambar 1.48 Cek "Genymotion Eclipse Tools".................................. 25 Gambar 1.49 "Genymotion Eclipse Tools", Klik Finish ...................... 25 Gambar 1.50 plugin is unsigned, klik OK saja.................................... 25 Gambar 1.51 Software Updates, restart to take effect ....................... 26 Gambar 1.52 Set directory Genymotion ............................................. 26 Gambar 1.53 Icon Genymotion di Eclipse .......................................... 26 Gambar 1.54 Start Virtual Device ....................................................... 27 Gambar 1.55 Loading Virtual Device ................................................. 27 Gambar 1.56 Tampilan Virtual Samsung Galaxy S2 - 4.1.1 - API 16 480x800 .............................................................................................. 28 Gambar 1.57 Error unable to start the virtual device ......................... 28 Gambar 1.58 Kosongkan Host-only Networks ................................... 29 Gambar 1.59 Auto Create VirtualBox Host-Only Ethernet Adapter ... 29 Gambar 1.60 Network Connections ................................................... 30 ix
Gambar 1.61 VirtualBox Host-Only Network ...................................... 30 Gambar 1.62 klik “Edits selected” ...................................................... 31 Gambar 1.63 Adapter & DHCP VB Host-Only Ethernet Adapter ....... 32 Gambar 1.64 Adapter & DHCP VB Host-Only Ethernet Adapter #2 .. 32 Gambar 1.65 Pilih Android Applicaton atau Run Configuration.. ....... 33 Gambar 1.66 Target, pilih “Always prompt to pick device”................. 33 Gambar 1.67 Genymotion– samsung_galaxy_s2.. ............................ 34 Gambar 1.68 Segitiga, Etc. ................................................................ 34 Gambar 1.69 USB Debugging Pada Smartphone Samsung ............. 35 Gambar 1.70 adt-bundle-windows-x86-20131030_sdk_platform-tools ............................................................................................................ 35 Gambar 1.71 Setelah mengetikkan drive lokasi sdk .......................... 36 Gambar 1.72 adb.exe devices ........................................................... 36 Gambar 1.73 Setelah adb.exe devices dijalankan ............................. 36 Gambar 1.74 Setelah adb.exe devices dijalankan pada Eclipse ....... 37 Gambar 1.75 Muncul smartphone Samsung pada Android devices chooser ............................................................................................... 37 Gambar 1.76 adb.exe kill-server dan start-server .............................. 38 Gambar 1.77 R cannot be resolved to a variable ............................... 38 Gambar 1.78 Error pada MainActivity.java......................................... 39 Gambar 1.79 Ubah package pada AndroidManifest.xml ................... 39 Gambar 1.80 c.
Pilih “com.example.mygl” ................................... 40
Gambar 1.81 Package pada AndroidManifest.xml telah diubah ....... 40 Gambar 1.82 d.
Save file “AndroidManifest.xml” .......................... 41
Gambar 1.83 Fix pada MainActivity.java ............................................ 41 Gambar 1.84 New Android Application Project .................................. 42 Gambar 1.85 Configure Project .......................................................... 42 Gambar 1.86 Configure the attributes of the icon set ........................ 43 Gambar 1.87 Pilih “Blank Activity” ...................................................... 43 Gambar 1.88 Create “Blank Activity” .................................................. 44 Gambar 1.89 Tampilan Project .......................................................... 44 Gambar 1.90 Tampilan Project Membuat Titik ................................... 45 x
Gambar 1.91 main() vs activity ........................................................... 45 Gambar 1.93 Android Studio (Hero)................................................... 46 Gambar 1.94 Mater Android Studio .................................................... 47 Gambar 1.95 Please Wait Setup is Loading ...................................... 47 Gambar 1.96 Android Studio Setup ................................................... 48 Gambar 1.97 Pilih Komponen ............................................................ 48 Gambar 1.98 License Agreement ...................................................... 49 Gambar 1.99 Configuration Setting .................................................... 49 Gambar 1.100 Choose Start Menu Folder ......................................... 50 Gambar 1.101 Proses Installing Android Studio ................................ 50 Gambar 1.102 Extracting Android SDK.............................................. 51 Gambar 1.103 Installation MVC++ 2010 x86 Redistributable Setup . 51 Gambar 1.104 MVC++ Installation Is Complete ................................. 52 Gambar 1.105 Setup Was Successfully ............................................. 52 Gambar 1.106 Completing the Android Studio Setup ........................ 53 Gambar 1.107 Error launching Android Studio .................................. 53 Gambar 1.108 Advanced system settings.......................................... 54 Gambar 1.109 Click Path ................................................................... 54 Gambar 1.110 Edit System Variables ................................................ 54 Gambar 1.111 Studio64.exe – System Error ..................................... 55 Gambar 1.112 MVC++ 2010 x86 Redistributable Package ............... 55 Gambar 1.113 Start Android Studio ................................................... 55 Gambar 1.114 Import Previous Version Of Android Studio ............... 56 Gambar 1.115 Android Studio Powered by the IntelliJ Paltform ........ 56 Gambar 1.116 Fetching Android SDK component information .......... 56 Gambar 1.117 Checking for updated SDK component ...................... 57 Gambar 1.118 The following SDK … : build-tools-21.1.1 .................. 57 Gambar 1.119 Setup Wizard - Downloading Components ................ 58 Gambar 1.120 Start Android Studio dari Apps Search ...................... 58 Gambar 1.121 Setup Wizard (Klik Retry) ........................................... 59 Gambar 1.122 Downloading Android SDK Build-tools, revision 21.1.1 ............................................................................................................ 59 xi
Gambar 1.123 Download Android SDK Build-tools was successfully 60 Gambar 1.124 Welcome to Android Studio ........................................ 60 Gambar 1.125 Masuk di path “C:\Users\[Nama Komputer]” .............. 61 Gambar 1.126 Klik "Options" .............................................................. 61 Gambar 1.127 Folder Options ............................................................ 62 Gambar 1.128 Klik “Show hidden files, folders, and drivers” ............. 62 Gambar 1.129 “AppData” sudah terlihat ............................................ 63 Gambar 1.130 Lokasi SDK Android Studio ........................................ 63 Gambar 1.131 Run “MainActivity” ...................................................... 64 Gambar 1.132 Edit System Variables JDK 1.8 .................................. 64 Gambar 1.133 Launch Emulator (Launch emulator) .......................... 65 Gambar 1.134 Launch Emulator (running device) ............................. 65 Gambar 1.135 Unexpected Error (Local path doesn't exist) Sync.. ... 66 Gambar 1.136 Local path doesn't exist (Event Log) .......................... 66 Gambar 1.137 Jalankan perintah “gradlew clean packageDebug” .... 66 Gambar 1.138 Klik “Setting” di Android Studio .................................. 66 Gambar 1.139 isi “Gradle VM options:” dengan “-Xmx256m” ............ 67 Gambar 1.140 Check “Edit Configurations….” ................................... 67 Gambar 1.141 Android Application (app) ........................................... 68 Gambar 1.142 Android Application (MainActivity) .............................. 68 Gambar 1.143 Failed to complete Gradle execution .......................... 69 Gambar 1.144 ERROR: This AVD's is missing a kernel file .............. 69 Gambar 1.145 Failed to complete Gradle execution .......................... 70 Gambar 1.146 ERROR: requires hardware acceleration ................... 70 Gambar 1.147 Cannot launch AVD in emulator ................................. 70 Gambar 1.148 intelhaxm-android.exe ................................................ 71 Gambar 1.149 Install HAXM 1.1.1 ...................................................... 71 Gambar 1.150 Error launching Android Studio .................................. 72 Gambar 1.151 Delete “JAVA_HOME” dari “Environment Variables” . 72 Gambar 1.152 After Delete “JAVA_HOME” ....................................... 73 Gambar 1.153 Error launching Android Studio .................................. 73 xii
Gambar 1.154 Menganti variable value “JAVA_HOME” .................... 73 Gambar 1.155 Menghubungkan Android Studio + Bluestack I .......... 74 Gambar 1.156 Menghubungkan Android Studio + Bluestack II ......... 74 Gambar 1.157 Run cmd.exe as Administrator ................................... 75 Gambar 1.158 Run adb.exe by cmd as Administrator ....................... 75 Gambar 1.159 Klik “Android Device Monitor” ..................................... 82 Gambar 1.160 Bluestack telah aktif di Android Studio ....................... 82 Gambar 1.161 Success run App (Android Studio + Bluestack) ......... 83 Gambar 1.162 Lokasi file *.apk hasil running ..................................... 83 Gambar 1.163 INSTALL FAILED OLDER SDK ................................. 84 Gambar 1.164 Klik “build.gradle(Module:app)” .................................. 84 Gambar 1.165 Ubah compileSdkVersion 19 ...................................... 84 Gambar 1.166 Ubah minSdkVersion & targetSdkVersion ................. 85 Gambar 1.167 Klik "Sync Now" .......................................................... 85 Gambar 1.168 Gradle project sync in progress... .............................. 85 Gambar 1.169 Language Level Changed .......................................... 86 Gambar 1.170 Files under the build folder are generated and should not be edited ....................................................................................... 86 Gambar 1.171 Ubah “dependencies” ................................................. 86 Gambar 1.172 File android-support-v4.jar ......................................... 87 Gambar 1.173 Klik “Sync Now” .......................................................... 87 Gambar 1.174 Setting untuk old version dari appcompat library ....... 88 Gambar 1.175 Ubah styles.xml .......................................................... 88 Gambar 1.176 Ubah file “menu_main.xml” ........................................ 88 Gambar 1.177 Content Asli "menu_main.xml” ................................... 89 Gambar 1.178 Ubah Content Asli "menu_main.xml” ......................... 89 Gambar 1.179 Solusi error “Unfortunately, [NamaProject] has stopped” .............................................................................................. 90 Gambar 1.180 Tampilan Primitive Object .......................................... 90 Gambar 1.181 Project Structure ......................................................... 91 Gambar 1.182 Remove Module ......................................................... 91 Gambar 1.183 Gradle project sync in progress.... ............................. 91 xiii
Gambar 1.184 Klik OK........................................................................ 92 Gambar 1.185 Delete directory "Nama Project..." .............................. 92 Gambar 1.186 AVD Manager ............................................................. 93 Gambar 1.187 Daftar Virtual Device .................................................. 94 Gambar 1.188 Pilih Hardware (Phone) .............................................. 94 Gambar 1.189 Pilih System Image (Lollipop) ..................................... 95 Gambar 1.190 Virtual Device Configuration ....................................... 96 Gambar 1.191 Verify Configuration .................................................... 96 Gambar 1.192 Creating/Updating AVD .............................................. 97 Gambar 1.193 AVD baru sudah terbentuk ......................................... 97 Gambar 1.194 Running AVD di Android Studio ................................. 97 Gambar 1.195 Tampilan Loading AVD di Android Studio .................. 98 Gambar 1.196 Tampilan AVD di Android Studio I .............................. 99 Gambar 1.197 Tampilan AVD di Android Studio II ........................... 100 Gambar 1.198 Tampilan AVD di Android Studio III .......................... 101 Gambar 1.199 Tampilan AVD di Android Studio IV ......................... 102 Gambar 1.200 Import Project ........................................................... 102 Gambar 1.201 Import Project ADT-Eclipse ke Android Studio ........ 103 Gambar 1.202 Memilih Tipe Import Project...................................... 103 Gambar 1.203 Tutup semua Project yang masih aktif ..................... 104 Gambar 1.204 Muncul “Welcome to Android Studio’ ....................... 104 Gambar 1.205 Klik “Import Non-Android Studio project”.................. 105 Gambar 1.206 Import Project ADT-Eclipse ke Android Studio ........ 105 Gambar 1.207 Memilih Tipe Import (.. from external model Gradle) 106 Gambar 1.208 Proses Importing ...................................................... 106 Gambar 1.209 List Project hasil Import ............................................ 107 Gambar 1.210 Error Can’t start Mercurial: hg.exe setelah Import ... 108 Gambar 1.211 Klik “Fix it” ................................................................. 108 Gambar 1.212 Memiih satu Project yang mau di-Import.................. 108 Gambar 1.213 Path tujuan untuk menyimpan hasil Import Project .. 109 Gambar 1.214 Import Destination Directory, Klik Next .................... 109 xiv
Gambar 1.215 Import per Project From ADT Eclipse ...................... 110 Gambar 1.216 Proses Importing sedang dilakukan ......................... 110 Gambar 1.217 Summary setelah proses Import .............................. 110 Gambar 1.218 Tampilan Project hasil Import ................................... 111 Gambar 1.219 Error Message “Gradle project sync failed ............... 111 Gambar 1.220 Klik “Try Again” ......................................................... 111 Gambar 1.221 Error “Project SDK is not defined” ............................ 112 Gambar 1.222 Klik “Setup SDK” ...................................................... 112 Gambar 1.223 Select Project SDK ................................................... 112 Gambar 1.224 Klik “Try Again” lagi .................................................. 113 Gambar 1.225 Masuk di “Setting”, lalu pilih “Grade” ........................ 113 Gambar 1.226 Buka “Open Module Settings” .................................. 114 Gambar 1.227 Lokasi SDK dan JDK ................................................ 115 Gambar 1.228 Project Structure ....................................................... 115 Gambar 1.229 Project Structure modules masih kosong................. 116 Gambar 1.230 Project Structure modules telah disi ......................... 116 Gambar 1.231 Klik “Try Again” ......................................................... 117 Gambar 1.232 Klik Install missing paltform(s) and sync project ...... 117 Gambar 1.233 License Agreement .................................................. 117 Gambar 1.234 Pilih Android SDK Platform 19 ................................. 118 Gambar 1.235 Installing Requested Components ........................... 118 Gambar 1.236 Installing Requested Components (Klik Finish) ....... 119 Gambar 1.237 Terlihat Android 19 sudah terinstall .......................... 119 Gambar 1.238 USB Debugging Pada Smartphone Samsung ......... 120 Gambar 1.239 Pilih Devices pada Android Studio ........................... 120 Gambar 1.240 Install Genymotion .................................................... 121 Gambar 1.241 Select Setup Language ............................................ 121 Gambar 1.242 Setup – Genymotion I............................................... 122 Gambar 1.243 Setup – Genymotion II.............................................. 122 Gambar 1.244 Setup – Genymotion III............................................. 123 Gambar 1.245 Setup – Genymotion IV ............................................ 123 xv
Gambar 1.246 Setup – Genymotion V ............................................. 124 Gambar 1.247 Proses Installing Genymotion................................... 124 Gambar 1.248 Install VirtualBox I ..................................................... 125 Gambar 1.249 Install VirtualBox II .................................................... 125 Gambar 1.250 Install VirtualBox III ................................................... 126 Gambar 1.251 Install VirtualBox IV .................................................. 126 Gambar 1.252 Install VirtualBox VI .................................................. 127 Gambar 1.253 Install VirtualBox VII ................................................. 127 Gambar 1.254 Install VirtualBox VIII ................................................ 128 Gambar 1.255 Yes, restart the computer now ................................. 128 Gambar 1.256 Ketik “Genymotion”, Klik “Install plugin” ................... 129 Gambar 1.257 Download and Install ................................................ 129 Gambar 1.258 Download Plugins ..................................................... 130 Gambar 1.259 Klik “Close” ............................................................... 130 Gambar 1.260 Plugin Changed ........................................................ 130 Gambar 1.261 Android Studio, Klik File > Settings. ......................... 131 Gambar 1.262 Klik Genymotion ....................................................... 131 Gambar 1.263 Klik “Kotak Kecil” disebelah kanan text field ............ 132 Gambar 1.264 Browse lokasi menginstall Genymotion ................... 132 Gambar 1.265 Content Select the path to the Genymotion folder ... 133 Gambar 1.266 Logo Genymotion di Android Studio ........................ 133 Gambar 1.267 Genymotion Device Manager ................................... 133 Gambar 1.268 Pilih salah satu virtual device ................................... 134 Gambar 1.269 Klik Start (Run Virtual Device) .................................. 134 Gambar 1.270 Initializing virtual device............................................ 134 Gambar 1.271 Loading Android di virtual device ............................. 135 Gambar 1.272 Virtual device Genymotion I ..................................... 136 Gambar 1.273 Virtual device Genymotion II .................................... 137 Gambar 1.274 Virtual device Genymotion III ................................... 138 Gambar 1.275 Virtual device Genymotion IV ................................... 139 Gambar 1.276 MainActivity.java ....................................................... 140 xvi
Gambar 1.277 Point_n_Lines_with_Points_Object.java .................. 140 Gambar 1.278 ESRender.java ......................................................... 141 Gambar 1.279 Run 'app'................................................................... 152 Gambar 1.280 Gradle: Executing Tasks [:app:assembleDebug] ..... 152 Gambar 1.281 Pilih running device .................................................. 152 Gambar 1.282 Gradle build finished................................................. 153 Gambar 1.283 Tampilah aplikasi OpenGL ....................................... 153 Gambar 1.284 “Log.v” di kode program ........................................... 154 Gambar 1.285 Tracking log.v ........................................................... 154 Gambar 1.290 Klik “Start a new Android Studio project” ................. 155 Gambar 1.291 Android Studio, Klik File > New Project…. ............... 155 Gambar 1.292 Berikan nama aplikasi yang anda buat .................... 156 Gambar 1.293 Pilih “Phone and Tablet” dan “API 8:.. (Froyo)” ........ 156 Gambar 1.294 API Level:Froyo sampai Lollipop .............................. 157 Gambar 1.295 APIs Level:Froyo for OpenGL ES 2.0 ...................... 157 Gambar 1.296 APIs Level:Gingerbread ........................................... 158 Gambar 1.297 APIs Level:Ice Cream Sandwicth ............................. 158 Gambar 1.298 APIs Level:Jelly Bean 16.......................................... 159 Gambar 1.299 APIs Level:Jelly Bean 17.......................................... 159 Gambar 1.300 APIs Level:Jelly Bean 18.......................................... 160 Gambar 1.301 APIs Level:Kit Kat 19 ................................................ 160 Gambar 1.302 APIs Level:Lollipop 21 .............................................. 161 Gambar 1.303 Pilih “Blank Activity” .................................................. 161 Gambar 1.304 Choose options for your new file .............................. 162 Gambar 1.305 Building PrimitiveObjectES....................................... 162 Gambar 1.306 Initializing Rendering Library .................................... 162 Gambar 1.307 Missing styles. Is the correct theme chosen ............ 163 Gambar 1.308 “java -> com.example.imacho.primitiveobjectes” ..... 163 Gambar 1.309 Siapkan file-file project ............................................. 164 Gambar 1.310 module default "app" ................................................ 164 Gambar 1.311 Android Studio, Klik File > New Module…. .............. 165 xvii
Gambar 1.312 Pilih “Phone and Tablet Application” ........................ 165 Gambar 1.313 Berikan nama Aplikasi/Library name ........................ 166 Gambar 1.314 Pilih “Blank Activity” .................................................. 166 Gambar 1.315 Default isi dari “Choose options for your new file”.... 167 Gambar 1.316 Tunggu beberapa saat “Gradle in progress...” ......... 167 Gambar 1.317 Module siap dikoding................................................ 167 Gambar 1.318 Module “app” dan “createpoint” ................................ 168 Gambar 2.1 GL_POINTS & GL_[LINES/LINE_STRIP/LINE_LOOP] .......................................................................................................... 169 Gambar 2.2 GL_[TRIANGLES/TRIANGLE_STRIP/TRIANGLE_FAN] .......................................................................................................... 170 Gambar 2.3 Titik manual dan generate ............................................ 171 Gambar 2.4 Membuat Titik Sederhana ............................................ 182 Gambar 2.5 Membuat garis dengan GL_POINTS ........................... 184 Gambar 2.6 Log.v("value Math.abs((.. ............................................. 184 Gambar 2.7 Tracking log.v (logcat) .................................................. 184 Gambar 2.8 Membuat Garis dan Titik .............................................. 198 Gambar 2.9 Membuat Segiempat dengan 2 Segitiga ...................... 199 Gambar 2.10 Segitiga dan segiempat .............................................. 200 Gambar 2.11 Membuat Segitiga Sederhana .................................... 220 Gambar 2.12 Membuat Segiempat .................................................. 232 Gambar 2.13 Wired-Flat-Color Segilima (Pentagon) ....................... 233 Gambar 2.14 Polygon statis dan dinamis (n-sisi) ............................. 234 Gambar 2.15 Ilustrasi membuat Lingkaran ...................................... 247 Gambar 2.16 Ilustrasi Membuat Bola ............................................... 248 Gambar 2.17 Membuat Lingkaran Flat dan Gradasi ........................ 250 Gambar 2.18 Membuat Lingkaran Flat dan Gradasi dinamis .......... 250 Gambar 2.19 Membuat Lingkaran Sederhana ................................. 278 Gambar 2.20 Sistem Koordinat Polar (r, Ө) ..................................... 279 Gambar 2.21 Membuat Polar Object................................................ 285 Gambar 3.1 Vertex Transformation Pipeline .................................... 286 Gambar 3.2 Contoh Proses Translasi .............................................. 287 xviii
Gambar 3.3 Contoh Proses Scaling ................................................. 288 Gambar 3.4 Contoh Proses Rotasi .................................................. 288 Gambar 3.5 Contoh Proses Shearing .............................................. 288 Gambar 3.6 Contoh Proses Kombinasi Transformasi ...................... 289 Gambar 3.7 Membuat Kincir Angin .................................................. 299 Gambar 4.1 Proyeksi paralel ............................................................ 300 Gambar 4.2 Proyeksi Perspektif ....................................................... 301 Gambar 4.3 gluPerspective()............................................................ 302 Gambar 4.4 glFrustum() ................................................................... 302 Gambar 4.5 Cara Kerja Kamera Sintetik .......................................... 303 Gambar 4.6 Sistem koordinat kamera sintetik ................................. 303 Gambar 4.7 Gambar synthetic camera dari vertex hasil trtasformasi perspektif (u*,v*) ............................................................................... 307 Gambar 4.8 Ilustrasi Multiple View Object ....................................... 307 Gambar 4.9 Multiple View Object ..................................................... 316 Gambar 5.1 Texture Mapping .......................................................... 317 Gambar 5.2 Ilustrasi Rasterisasi ...................................................... 318 Gambar 5.3 Bitmap Texture ............................................................. 319 Gambar 5.4 Magnification dan Minification ...................................... 319 Gambar 5.5 Repeating Texture ........................................................ 320 Gambar 5.6 Clamping Texture ......................................................... 320 Gambar 5.7 Repeating dan Clamping Texture................................. 321 Gambar 5.8 Texture Mapping Pada Segitiga ................................... 339 Gambar 5.9 Texture Mapping Pada Lingkaran ................................ 359 Gambar 5.10 Texture Mapping Pada Kubus .................................... 367 Gambar 5.11 Texture Mapping Pada Bola ....................................... 377 Gambar 6.1 Teknik blending untuk mendapatkan efek pantulan ..... 378 Gambar 6.2 Blending Dua Segitiga .................................................. 399 Gambar 6.3 Blending Pada Kubus (Blending tidak terlihat jika belum ada gerakan sentuhan ke sembarang arah pada layarnya)............. 411 Gambar 6.4 Blending Pada Bola ...................................................... 421 Gambar 7.1 Pencahayaan................................................................ 422 xix
Gambar 7.2 Normal Vector............................................................... 424 Gambar 7.3 Lighting Pada Interior .................................................. 541 Gambar 8.1 Pembuatan Model 3D ................................................... 542 Gambar 8.2 Aplikasi Blender ............................................................ 542 Gambar 8.3 Model Loading (objek belum diberi texture) ................. 550 Gambar 8.4 Garis Lurus ................................................................... 551 Gambar 8.5 Garis Lurus yang telah dibagi menjadi 3 bagian .......... 551 Gambar 8.6 Garis Lurus yang telah dibentuk segitiga di tengah bagiannya ......................................................................................... 551 Gambar 8.7 Kurva Fraktal Koch ....................................................... 552 Gambar 8.8 Kurva Fraktal LindenMayer (L System) ........................ 552 Gambar 8.9 Polinomial berderajat 2................................................. 553 Gambar 8.10 Polinomial berderajat 3............................................... 554 Gambar 8.11 Polinomial berderajat 4............................................... 554 Gambar 8.12 Polinomial berderajat 5............................................... 554 Gambar 8.13 Polinomial berderajat 6............................................... 555 Gambar 8.14 Polinomial berderajat 7............................................... 555 Gambar 8.15 Kurva Fraktal Set MandelBrot .................................... 556 Gambar 8.16 Kurva Set Julia 1 ........................................................ 556 Gambar 8.17 Kurva Set Julia 2 ........................................................ 557 Gambar 9.1 Random Maze dengan Background Hitam .................. 558 Gambar 9.2 Random Maze dengan Background Abu-Abu.............. 559 Gambar 9.3 Random Maze Background Gambar ............................ 559 Gambar 9.4 Random Maze Background Gambar, Control Objek.... 559 Gambar 9.5 file “Roboto-Regular.ttf” ................................................ 718 Gambar 9.6 File res\layout ............................................................... 718 Gambar 9.7 File Audio...................................................................... 722 Gambar 9.8 File Gambar untuk Texture Mapping ............................ 722 Gambar 9.9 Tampilan Awal Untuk Memulai Game .......................... 723 Gambar 9.10 Tampilan Menu Utama ............................................... 724 Gambar 9.11 Tampilan Soal Pada Aplikasi...................................... 724 Gambar 9.12 Tampilan skor saat game selsai dan jawaban salah . 724 xx
Gambar 9.13 Tampilan skor akhir saat game belum selesai karena objek burung menabrak tiang ........................................................... 725 Gambar 9.14 Tampilan skor saat game selsai dan jawaban benar semua ............................................................................................... 725 Gambar 9.15 Tampilan Awal Untuk Memulai Game ........................ 762 Gambar 9.16 Tampilan Game ketika di play .................................... 763 Gambar 9.17 Tampilan Score .......................................................... 763 Gambar 9.18 Menu Utama ............................................................... 855 Gambar 9.19 Tutorial Game ............................................................. 856 Gambar 9.20 Game .......................................................................... 856 Gambar 9.21 Developers ................................................................. 856 Gambar 9.22 Flowchart Touch Your Coin ........................................ 919 Gambar 9.23 Tampilan Loading ....................................................... 922 Gambar 9.24 Tampilan Menu Utama ............................................... 922 Gambar 9.25 Tampilan Help ............................................................ 922 Gambar 9.26 Tampilan About .......................................................... 923 Gambar 9.27 Tampilan Memulai Game ........................................... 923 Gambar 9.28 Tampilan Awal Untuk Memulai Game ...................... 1065 Gambar 9.29 Tampilan Bentuk Quiz .............................................. 1065 Gambar 9.30 Ular Tangga Awal ..................................................... 1119 Gambar 9.31 Tampilan Awal Untuk Memulai Game ...................... 1125 Gambar 9.32 Tampilan Menu Utama ............................................. 1125 Gambar 9.33 Tampilan Petunjuk Permainan ................................. 1126 Gambar 9.34 Tampilan Permainan Ular Tangga Sejarah .............. 1126 Gambar 9.35 Tampilan Menang ..................................................... 1127 Gambar 9.36 Menu Awal ................................................................ 1175 Gambar 9.37 Get Ready ................................................................ 1175 Gambar 9.38 Soal .......................................................................... 1176 Gambar 9.39 Finish ........................................................................ 1176
xxi
Daftar Source Code
Source Code 1.1 MainActivity.java ................................................... 141 Source Code 1.2 Point_n_Lines_with_Points_Object.java .............. 143 Source Code 1.3 ESRender.java ..................................................... 150 Source Code 2.1 Code Membuat Titik (Ukuran Dinamis) ................ 171 Source Code 2.2 Code Lain Membuat Titik Sederhana................... 176 Source Code 2.3 Code Membuat Garis dengan Titik (Solid) ........... 185 Source Code 2.4 Code Lain Membuat Garis dengan Titik............... 192 Source Code 2.5 Code Membuat Segitiga & Segiempat ................. 201 Source Code 2.6 Code Lain Membuat Segitiga Sederhana ............ 208 Source Code 2.7 Code Membuat Segiempat................................... 220 Source Code 2.8 Membuat Polygon Statis dan Dinamis ................. 234 Source Code 2.9 Code Membuat Lingkaran Gradasi & Dinamis ..... 250 Source Code 2.10 Code Lain Membuat Lingkaran Sederhana ....... 272 Source Code 2.11 Code Membuat Polar Object .............................. 279 Source Code 3.1 Code Membuat Kincir Angin................................. 290 Source Code 4.1 Code Membuat Multiple View Object ................... 308 Source Code 5.1 Code Texture Mapping Pada Segitiga ................. 321 Source Code 5.2 Code Texture Mapping Pada Lingkaran .............. 339 Source Code 5.3 Code Texture Mapping Pada Kubus .................... 359 Source Code 5.4 Code Texture Mapping Pada Bola ....................... 367 Source Code 6.1 Code Blending Dua Segitiga ................................ 381 Source Code 6.2 Code Blending Pada Kubus ................................. 400 Source Code 6.3 Code Blending Pada Bola .................................... 411 Source Code 7.1 Code Lighting Pada Interior.................................. 425 Source Code 8.1 Code Model Loading ............................................ 544 Source Code 9.1 Code Random Maze ............................................ 560 Source Code 9.2 Code Smart Flappy .............................................. 725 Source Code 9.3 Code Chicken Hero .............................................. 763 Source Code 9.4 Code Ayo Nyoblos!............................................... 857 xxii
Source Code 9.5 Code Touch Your Coin ......................................... 923 Source Code 9.6 Code Guess The Animal .................................... 1066 Source Code 9.7 Code Ular Tangga .............................................. 1127
xxiii
BAB 1 Introduction to OpenGL You can buy the books, but not knowledge.
1.1 Pengertian Grafika Komputer Grafika Komputer adalah bagian dari Ilmu Komputer yang memiliki konsep mengkorversi dari informasi menjadi objek visual secara digital, sekaligus didalamnya proses manipulasi. Konsep ini merupakan kebalikan dari computer vision. Objek visual tersebut dapat berupa 3 dimensi maupun 2 dimensi yang meliputi beberapa contoh seperti titik, garis lurus, garis lengkung, maupun objek yang komplek. Operasi yang dilakukan pada objek visual tersebut, dimulai dari setiap pixel matrik yang membentuk suatu objek tertentu dengan ukuran tertentu. Meskipun objek tertentu tersebut terlihat sangat komplek, apalagi jika sudah diberikan beberapa efek dan manipulasi yang sangat detail dan bagus, namun sebenarnya objek tersebut sebenarnya hanya disusun dari objek sederhana yaitu titik-titik yang sangat banyak, yang meliputi keseluruhan permukaan objek komplek tersebut. Selain itu, dukungan perkembangan perangkat lunak dan perangkat keras juga menjadikan Grafika Komputer memiliki perkembangan yang sangat pesat, terutama pada aplikasi mobile yang menjanjikan hasil produk grafis menjadi sangat berkulitas.
1.2 Persiapan di Eclipse (ADT) 1.2.1 Fast Emulator With Intel (HAXM) Android memiliki dukungan penuh untuk OpenGL, meskipun library-nya tidak selengkap pada C/C++ di Visual Studio (GLUT OpenGL Utility Toolkit- Library) atau di Netbean OpenGL (LWJGL Lightweight Java Game Library). Berikut ini adalah cara untuk membuat dan mengaktifkan emulator Android dengan prosesor Intel (HAXM). 1. Aktifkan “Intel VT” atau intel virtualization technology di BIOS. 2. UpdateAndroid SDK pada Android target, pada contoh ini yang diperbarui adalah “Android 4.4 – API Level 19″dengan CPU/ABI menggunakan“Intel Atom x86″. 1
Pada Tool Bar, klik “Windows” –>klik “Android SDK Manager”.
Gambar 1.1 Android SDK Manager Sebelum Klik Deselect All
Klik “Deselect All” menghilangkan tanda cek pada item yang saat ini dipilihlalui klik pada Android target yang diinginkan, jika menggunakan “Android 4.4 – API Level 19″beri tanda cek untuk “Intel x86 Atom System Image”kemudian beri tanda cek untuk “Intel x86 Emulator Accelerator (HAXM)”.
Gambar 1.2 Klik Intel x86 Atom System Image 2
Gambar 1.3 Beri tanda cek Intel x86 Emulator Accelerator (HAXM)
Klik “Install 2 packages”.
Gambar 1.4 Klik Install 2 packages
Klik “Android SDK License”, kemudian klik “Accept Lisense”.
3
Gambar 1.5 Klik Android SDK License lalu klik Accept Lisense
Klik “Intel Android Extra License”, then click “Accept Lisense”.
Gambar 1.6 Klik Intel Android Extra License lalu klik Accept Lisense
Klik “Install”. Tunggu hingga download selesai.
Gambar 1.7 Proses Download 4
Tampilan setelah download serta instalasi “Intel x86 Atom System Image” dan “Intel x86 Emulator Accelerator (HAXM)” selesai. Lalu Close “Android SDK Manager”.
Gambar 1.8 Tampilan setelah download dan instalasiselesai Restart Eclipse. 3. Untuk membuat AVD, klik “Android Virtual Device Manager”, pada CPU/ABI menggunakan pilihan “Intel Atom x86″lalu pada Emulation Option, beri tanda cekuntuk “Use Host GPU”. Lalu klik “OK”.
5
Gambar 1.9 Membuat Android Virtual Device (AVD) baru 4. Setelah membuat AVD lalu klik AVD pada list lalu klik Start.
Gambar 1.10 Klik AVD pada list lalu klik Start 6
5. Agar AVD atau “Android Emulator” dapat dijalankan dengan cepat. Close AVD atau “Android Emulator” yang saat ini digunakan. 6. Install HAXM pada sdk android path berikut “…/adt-bundlewindows-x8620131030\sdk\extras\intel\Hardware_Accelerated_Execution_Ma nager\IntelHaxm.exe”.
Gambar 1.11 Intel HAXM 7. Lalu jalankan kembali AVD atau “Android Emulator” (Jika ingin merotasi layar AVD, gunakan Ctrl + F11).
Gambar 1.12 Tampilan AVD 8. Selesai dan emulator Android telah dapat digunakan.
1.2.2 Konfigurasi "Eclipse + Bluestacks" Bluestack adalah aplikasi emulator Android untuk PC. Langkahlangkah untuk konfigurasi Eclipse dan Bluestack pada Android adalah sebagai berikut: 1. Download Eclipse + Android SDK (Eclipse Bundle Android) pada link (32 bit) https://goo.gl/KZwJcz (± 491.8 MB), (64 bit) 7
https://goo.gl/05lUbF (± 491.9 MB) atau Android Studio di http://developer.android.com/sdk/index.html#download.
Gambar 1.13 Download SDK ADT Bundle Eclipse 2. Setup Android Developer Tools (ADT Bundle) hingga instalasi selesai. 3. Install Bluestacks dengan installer offline pada link : a. (ver. 1.1) https://goo.gl/o6zNpH (± 108.35 MB), atau b. (ver. 1.2) https://goo.gl/CGbphW (± 128 MB), c. (ver. 2) https://goo.gl/MUUQLM (± 267.98 MB). atau online pada link http://www.bluestacks.com.
Gambar 1.14 Download Bluestacks 4. Setelah instalasi Bluestacks selesai, jalankanBluestacks, lalu install launcher seperti “ADW Launcher, LauncherPro” dari Google Play untuk memudahkan dalam menjalankan aplikasi Android pada Bluestacks.
8
Gambar 1.15 ADW Launcher
Gambar 1.16 Interface Bluestacks 5. Jalankan Eclipse, jika gagal dan muncul pesan sebagai berikut: Failed to create the Java Virtual Machine, untuk mengatasinya:
Gambar 1.17 Pesan “Failed to create the Java Virtual Machine” 9
Buka file “..\adt-bundle-windows-x8620131030\eclipse\eclipse.ini”,kemudian edit “XX:MaxPermSize=256M” menjadi “XX:MaxPermSize=128M” atau sebaliknya. Ketikkan tanpa tanda kutip.
Failed to run JDK (meskipun JDK sudah ter-install sebelumnya), maka untuk mengatasinya: o Copy path JDK pada komputer, misalnya “C:\Program Files\Java\jdk1.7.0_40\bin”. o Buka “Control panel”–>”System and Security”– >”System”–>”Advanced system settings”.
Gambar 1.18 Advanced system settings o
Klik “Environment Variable…”, variables” klik “path” lalu klik “Edit”.
pada
This books is only a-z,0-9, few symbol & picture. Although like this, those are irreplaceble with treasure or anything and how much money that you have spend to buy it.
10
“System
Gambar 1.19 Click Path o
Tambahkan “Variable value:” dengan “;C:\Program Files\Java\jdk1.7.0_40\bin”, kemudian klik “OK” sebanyak 3 kali.
Gambar 1.20 Edit System Variables o
Jalankan, kembali Eclipse.
11
6. Kemudian untuk mengkoneksikan Bluestack langkah-langkahnya sebagai berikut: Jalankan cmd (Window + R), lalu klik “Ok”.
dan
Eclipse,
Gambar 1.21 Menjalankan cmd
Ketikkan “cd c:\Program Files\BlueStacks” lalu tekan “Enter” button.
Gambar 1.22 Command masuk ke folder BlueStacks
Ketikkan ini“HD-Adb.exe start-server”, lalu tekan “Enter”.
Gambar 1.23 HD-Adb.exe start-server 12
Tampilan setelah dikoneksikan (pada cmd) :
Gambar 1.24 Setelah HD-Adb.exe start-server dijalankan
Tampilan setelah dikoneksikan (pada Eclipse) : Untuk menampilkan “Devices”, click “Window” –> ”Show view” –> ”Other” –> ”Android” –> ”Devices”.
Gambar 1.25 Klik"Window ->"Show view"->“Other”
13
Gambar 1.26 Tampilan device pada Bluestacks emulator
Gambar 1.27 Android Device Chooser Jika gagal dalam mengkoneksikan, ketikkan“HD-Adb.exe killserver” lalu tekan “Enter”, tunggu beberapa saat lalu ketikkan lagi“HDAdb.exe start-server” selanjutnya tekan “Enter”.
1.2.3 Konfigurasi "Eclipse + Genymotion" Langkah-langkah konfigurasi Eclipse dan Genymotion pada Android adalah sebagai berikut:
1. Download Genymotion di link :
a. (Master + Virtual Devices) https://goo.gl/bNm9W7 (± 1.6 GB) b. (Master Only) https://goo.gl/WPxuP1 (± 183 MB) 2. Run Genymotion, dan buat dahulu virtual device di Genymotion. 14
3. Run Genymotion (klik icon di desktop) 4. Main window akan muncul
Gambar 1.28 Main Window Genymotion
5. Lalu akan muncul pop-up dan meminta untuk menambah virtual device.
Gambar 1.29 Pop-up Menambah Virtual Device
6. Klik ok lalu akan muncul
Gambar 1.30 Klik OK 15
7. Klik connect. Isi dengan username/email address dan password, lalu klik "Connect" .
Gambar 1.31 Isi Username/Password ,Connect
8. Setelah terkoneksi akan muncul virtual device di bawah ini.Pilih virtual device misalkan (Nexus 7 - 4.3) lalu klik "Next" .
Gambar 1.32 Pilih Virtual Device
16
9. Beri nama untuk virtual devicenya lalu klik next.
Gambar 1.33 Beri Nama Virtual Device
10. Virtual device akan terdownload dan di deploy.
Gambar 1.34 Virtual Device Terdownload & Terdeploy
17
11. Klik finish untuk mengakhiri deployment window.
Gambar 1.35 Deployment window Finish
12. Klik play untuk memulai virtual device.
Gambar 1.36 Play
18
13. Jika ingin meng-install secara offline “virtual devices”, siapkan, misal beberapa file berikut di folder “..\VirtualDevicesGenymobile\Genymobile\Genymotion\ova” :
Gambar 1.37 File .ova Copykan ke folder : “C:\Users\{ComputerName}\AppData\Local\Genymobile\Genymot ion\ova”. Klik “Add”, lalu “Next”, “Next”, dan “Finish”
Gambar 1.38 Deploying virtual device.. 19
Gambar 1.39 Virtual device Finish
Gambar 1.40 Virtual device is Ready
20
14. Atau dengan cara membuka Virtual Box, Klik FileImport
Appliance.. Klik (Pilih salah satu file *.ova) pada “C:\Users\{ComputerName}\AppData\Local\Genymobile\Genymot ion\ova”. Lalu Klik “Next”, Klik “Import’.
Gambar 1.41 Import Virtual Devices (*.ova) di Virtual Box
21
15. Virtual device yang sudah di-import, dapat cek pada Virtual Box dan juga pada Genymotion dan siap untuk dijalankan.
Gambar 1.42 Virtual device is Ready Pada Virtual Box
Gambar 1.43 Virtual device is Ready Pada Genymotion
22
16. Klik “Settings”, lalu klik “ADB”, isikan dengan, misal letak folder
sdk anda ada di “E:/adt-bundle-windows-x86_64-20131030/sdk”
Gambar 1.44 Set Letak Android SDK di Genymotion
17. Opsi lainnya, lakukan instalasi plugin Genymotion ke Eclipse. Caranya sebagai berikut: a. Start Eclipse b. Buka menu "HelpInstall New Software..." c. Pada window yang muncul, klik tombol "Add..." d. Isi form dengan Name: Genymobile Location: http://plugins.genymotion.com/eclipse
Gambar 1.45 Add Repository, lalu klik OK 23
Gambar 1.46 There are not categorized items e. Jika “Genymotion Eclipse Tools” tidak ada pada list, dan hanya ada “There are not categorized items”, maka solusinya uncheck “Group items by category”.
Gambar 1.47 Uncheck “Group items by category” 24
f.
Pliih opsi “Genymotion Eclipse Tools”, lalu klik "Next"
Gambar 1.48 Cek "Genymotion Eclipse Tools"
Gambar 1.49 "Genymotion Eclipse Tools", Klik Finish g. Eclipse akan mengingatkan bahwa plugin is unsigned, klik OK saja.
Gambar 1.50 plugin is unsigned, klik OK saja
25
h. Restart Eclipse
Gambar 1.51 Software Updates, restart to take effect i. j.
Setelah restart, maka akan muncul tombol di toolbar: Klik icon tersebut, jika belum diset directory Genymotionnya, pada “WindowPreferencesGenymotion”, Set directory Genymotion misal dengan “C:\Program Files\Genymobile\Genymotion”.
Gambar 1.52 Set directory Genymotion
Gambar 1.53 Icon Genymotion di Eclipse
26
18. Pada pilihan muncul beberapa nama virtual devices, pilih salah satu, lalu klik start
Gambar 1.54 Start Virtual Device Lokasi Virtual Devices : C:/Users/{ComputerName}/AppData/Local/Genymobile/Genymoti on/deployed/ 19. Akan loading seperti dibawah ini
Gambar 1.55 Loading Virtual Device
27
20. Lalu setelah loadingnya selesai akan keluar seperti ini
Gambar 1.56 Tampilan Virtual Samsung Galaxy S2 - 4.1.1 - API 16 480x800
21. Jika keluar error “unable to start the virtual device, virtualbox can't start the virtual device”
Gambar 1.57 Error unable to start the virtual device 28
a. Close Genymotion, buka Virtual Box. Klik FilePreferencesNetworkTab Host-only Network, Hapus semua “VirtualBox Host-Only Ethernet Adapter” satu per satu, dengan cara klik “Removes selected”, Klik tombol “remove” (Pastikan Host-only Networks, telah kosong), Klik OK. Close Virtual Box.
Gambar 1.58 Kosongkan Host-only Networks b. Buka Genymotion, maka secara otomatis “VirtualBox HostOnly Ethernet Adapter” pada Virtual Box akan dibuat kembali, dan pada “Your virtual devices” jangan di klik “Start” terlebih dahulu. Lakukan langkah “c”.
Gambar 1.59 Auto Create VirtualBox Host-Only Ethernet Adapter 29
c.
Kemudian, masuk ke “Control Internet\Network Connections”.
Panel\Network
and
Gambar 1.60 Network Connections d. Klik Kanan “VirtualBox Host-Only Network”, klik “Properties”, checked “VirtualBox NDIS6 Bridged Networking Driver”, lalu klik pada “Internet Protocol Version 4 (TCP/IPv4)”, lalu klik “Properties”, lakukan juga pada “VirtualBox Host-Only Network #2”, atau semua yang diawali dengan “VirtualBox Host-Only Network ..”.
Gambar 1.61 VirtualBox Host-Only Network
30
e. Pada “VirtualBox Host-Only Network” Gambar diatas, tertera “IP address: 192.168.56.2”, “Subnet mask : 255.255.255.0”. Kemudian cek pada Virtual Box, Klik FilePreferencesNetworkTab Host-only Network, lalu klik “Edits selected” untuk “VirtualBox Host-Only Ethernet Adapter” (Pastikan sama). Setelah itu, pada Genymotion “Your virtual devices”, Pilih salah satu Virtual Devices, lalu Klik “Start”.
Gambar 1.62 klik “Edits selected”
31
Gambar 1.63 Adapter & DHCP VB Host-Only Ethernet Adapter
Gambar 1.64 Adapter & DHCP VB Host-Only Ethernet Adapter #2
32
22. Buka eclipse > pada project openGL “2_2Primitives_Project_ES” klik kanan run as > Pilih Android Applicaton atau Run Configuration..
Gambar 1.65 Pilih Android Applicaton atau Run Configuration..
23. Pada Current Project, klik Target (Pilih) lalu Run
Gambar 1.66 Target, pilih “Always prompt to pick device”
33
24. Akan keluar “Android Device Chooser” seperti di bawah ini dan klik “genymotion – samsung_galaxy_s2..”, lalu klik “ok”
Gambar 1.67 Genymotion– samsung_galaxy_s2..
25. Lalu pada akhirnya akan keluar gambar seperti di bawah ini.
Gambar 1.68 Segitiga, Etc.
34
1.2.4 Konfigurasi pada Smartphone Android Jika ingin menjadikan smartphone Android sebagai emulator, maka langkah-langkah konfigurasinya adalah sebagai berikut: 1. Siapkan smartphone Android. Pada contoh ini, smartphone Android yang digunakan adalah Samsung GT-i9070 Galaxy S Advance. 2. Pada smartphone, pililh “setting”, lalu klik “Applications/Application Manager” –> ”Development” –> klik/ beri tanda cek pada “USB debugging”.
Gambar 1.69 USB Debugging Pada Smartphone Samsung
3. Pada PC, jalankan cmd (Window + R), lalu klik “OK. Ketikkan lokasi sdk pada komputer, misalnya “cd I:\Master\adt-bundle-windows-x86-20131030\sdk\platformtools” lalu tekan “Enter”.
Gambar 1.70 adt-bundle-windows-x86-20131030_sdk_platform-tools
35
4. Ketikkan “I:” sebagai drive lokasi sdk, lalu tekan “Enter”.
Gambar 1.71 Setelah mengetikkan drive lokasi sdk
5. Ketikkan “adb.exe devices”, lalu tekan “Enter”.
Gambar 1.72 adb.exe devices
Gambar 1.73 Setelah adb.exe devices dijalankan
36
Gambar 1.74 Setelah adb.exe devices dijalankan pada Eclipse 6. Cek “Devices” pada Eclipse.
Gambar 1.75 Muncul smartphone Samsung pada Android devices chooser 7. Jika gagal dalam mengkoneksikan, ketikkan“adb.exe kill-server” lalu tekan “Enter”, tunggu beberapa saat lalu ketikkan lagi“adb.exe start-server” selanjutnya tekan “Enter”.
37
Gambar 1.76 adb.exe kill-server dan start-server 8. Konfigurasi selesai.
1.2.5 Solusi Error/Problem/Bug Berikut beberapa error yang sering terjadi ketika mejalankan kode program : 1. Error “R cannot be resolved to a variable”, biasanya pada “MainActivity.java”.
Gambar 1.77 R cannot be resolved to a variable Solusi : a. Penyebabnya biasanya karena setelah me-rename nama “package” pada folder “src” (misal dari “com.example.myopengl” diubah sedikit menjadi “com.example.mygl”). Meskipun pada folder “src” sudah berhasil direname, biasanya pada folder “gen” masih ada nama “package” dengan “com.example.myopengl”.
38
Gambar 1.78 Error pada MainActivity.java b. Open File “MyIntro_OpenGL/AndroidManifest.xml”, pada tab “Manifest”, ubah Package “com.example.myopengl” dengan cara klik “Browse...”, lalu pilih
Gambar 1.79 Ubah package pada AndroidManifest.xml
39
c.
Pilih “com.example.mygl”, lalu klik “OK”
Gambar 1.80 c. Pilih “com.example.mygl”
Gambar 1.81 Package pada AndroidManifest.xml telah diubah
40
d. Save file “AndroidManifest.xml”. Lalu klik “Yes”
Gambar 1.82 d. Save file “AndroidManifest.xml” e. Tampilan project, setelah tidak ada error
Gambar 1.83 Fix pada MainActivity.java
41
1.2.6 Membuat Project Baru Berikut beberapa langkah untuk membuat project baru aplikasi android pada eclipse : 1. Klik “FileNewAndroid Application Project”, Masukkan misal “Application Name = IntroToOpenGL”. Klik Next.
Gambar 1.84 New Android Application Project 2. Konfigurasi Project, Klik Next
Gambar 1.85 Configure Project 42
3. Konfigurasi icon, Klik Next
Gambar 1.86 Configure the attributes of the icon set 4. Pilih “Blank Activity”, Klik Next
Gambar 1.87 Pilih “Blank Activity” 43
5. Create Blank Activity, Klik Finish
Gambar 1.88 Create “Blank Activity”
6. Tampilan Project. Setelah itu, replace file “MainActivity.java” tersebut dengan contoh kode program “Primitive Object” pada sub bab 2 dan selanjutnya.
Gambar 1.89 Tampilan Project 44
7. Tampilan Project, setelah di-replace (dilengkapi) dengan file “MainActivity.java”, “Create_Points.java”, dan “ESRender.java” dari contoh kode program Bab 2 “Primitive Object”. Misal untuk “Membuat Titik”.
Gambar 1.90 Tampilan Project Membuat Titik
1.2.7 Siklus Hidup Kode Program Penjelasan ini meliputi proses siklus hidup atau lifecycle dari aplikasi android, hubungan antara kode-kode sampai pada alur jalannya kode mulai dari awal hingga akhir. Paradigma awal jalannya pemrograman umumnya menggunakan main(), pada Android berjalannya sistem diawali dengan Activity dengan menerapkan metode callback tertentu yang sesuai dengan tahapan lifecycle-nya. Terdapat metode callback untuk memulai suatu Activity dan ada juga ada callback untuk men-destroy suatu Activity.
Gambar 1.91 main() vs activity 45
1.3 Persiapan di Android Studio (AS) 1.3.1 Installasi Android Studio Master installer android-studio-bundle-135.1641136 ini merupakan versi stabil pertama dari lingkungan pengembangan Android yang terintegrasi, dan ke depan, versi ini akan menjadi platform untuk pengembangan aplikasi Android. “Google releases Android Studio, kills off Eclipse ADT plugin”, ini adalah suatu berita yang sangat besar. Bagaimana tidak, selama ini kami biasanya menggunakan “Eclipse ADT plugin” untuk development aplikasi android selama kurun waktu kurang lebih 2 tahun terakhir. Google mengumumkan pada hari Selasa 8 Desember 2014 bahwa setelah dua tahun bekerja, akhirnya siap untuk meluncurkan pengembangan terpadu berbasis IDE, yaitu IntelliJ, Android Studio, kepada dunia dengan rilis versi 1.0. Android Studio akan menawarkan pengalaman yang lebih baik bagi para pengembang Android dari pada Eclipse tradisional yang digunakan sebelumnya, "kick" artinya Google menghentian Plugin Android Developer Tools (ADT) untuk Eclipse yang mengintegrasikan sejumlah alat Android ke dalamnya.
Gambar 1.92 Android Studio (Hero)
46
"Plugin ADT untuk Eclipse tidak lagi aktif atau di-support lagi," kata situs pengembang Google. "Jika saat ini Anda menggunakannya, Anda harus bermigrasi ke Android Studio dengan sesegera mungkin." Beberapa penggemar Eclipse juga banyak yang mempertanyakan hal ini, namun beberapa kalangan pengembang berpendapat bahwa, dibandingkan dengan Eclipse, Android Studio menawarkan lingkungan pengembang dan desainer antarmuka pengguna yang lebih baik, serta efisiensi memori yang lebih baik dan meningkatkan kecepatan eksekusi kode program. Dan kemungkinan hal ini pasti banyak yang berbeda pendapat dari para pengembang. Ketika Android Studio diresmikan pada Mei tahun lalu, terdapat komentar di TechRepublic: "Eclipse dapat mencoba, tetapi tidak dapat bersaing dengan Visual Studio (Milik Microsoft), atau bahkan Xcode (Milik Apple). “The Eclipse Foundation” yang meliputi Google, telah mencoba lebih dari satu dekade untuk membuat Eclipse IDE menjadi lebih layak dan lebih baik, akan tetapi masih saja berat untuk mampu bersaing." Berikut adalah langkah-langkah instalasi Android Studio untuk pengembangan aplikasi android :
Double klik Master Android Studio
Gambar 1.93 Mater Android Studio
Tunggu beberapa detik
Gambar 1.94 Please Wait Setup is Loading 47
Welcome to the Android Studio Setup, Klik “Next”
Gambar 1.95 Android Studio Setup
Pilih Komponen, Klik “Next”
Gambar 1.96 Pilih Komponen
48
License Agreement, Klik “I Agree”
Gambar 1.97 License Agreement
Configuration Setting, Klik “Next”
Gambar 1.98 Configuration Setting
49
Choose Start Menu Folder, Klik “Install”
Gambar 1.99 Choose Start Menu Folder
Proses Installing
Gambar 1.100 Proses Installing Android Studio
50
Gambar 1.101 Extracting Android SDK
Gambar 1.102 Installation MVC++ 2010 x86 Redistributable Setup
51
Gambar 1.103 MVC++ Installation Is Complete
Setup Was Successfully, Klik “Next”
Gambar 1.104 Setup Was Successfully 52
Completing the Android Studio Setup
Gambar 1.105 Completing the Android Studio Setup Ketika menjalankan Android Studio, kemungkinan anda mengalami hal-hal berikut ini :
Error launching Android Studio, Solusi “Setting di Control Panel”
Gambar 1.106 Error launching Android Studio Detail solusinya adalah sebagai berikut : a. Copy path JDK pada komputer, misalnya “C:\Program Files\Java\jdk1.7.0_40\bin”. b. Buka “Control panel”–>”System and Security”– >”System”–>”Advanced system settings”.
53
Gambar 1.107 Advanced system settings c.
Klik “Environment Variable…”, variables” klik “path” lalu klik “Edit”.
pada
“System
Gambar 1.108 Click Path d. Tambahkan “Variable value:” dengan “;C:\Program Files\Java\jdk1.7.0_40\bin”, kemudian klik “OK” sebanyak 3 kali.
Gambar 1.109 Edit System Variables 54
studio64.exe – System Error (The program can’t start because MSVCR100.dll is missing from your computer. Try reinstalling the program to fix this problem.)
Gambar 1.110 Studio64.exe – System Error Solusi untuk “The program can’t start because MSVCR100.dll is missing from your computer. Try reinstalling the program to fix this problem” adalah dengan men-download dan install “MVC++ 2010 x86 Redistributable Package” dari web Microsoft.
Gambar 1.111 MVC++ 2010 x86 Redistributable Package
Start Android Studio
Gambar 1.112 Start Android Studio 55
Gambar 1.113 Import Previous Version Of Android Studio
Gambar 1.114 Android Studio Powered by the IntelliJ Paltform
Gambar 1.115 Fetching Android SDK component information
56
The following SDK component was not installed: buildtools-21.1.1, jika memang tidak terkoneksi dengan internet, Klik “Cancel”
Gambar 1.116 Checking for updated SDK component
Gambar 1.117 The following SDK … : build-tools-21.1.1
57
Gambar 1.118 Setup Wizard - Downloading Components Pada Gambar 1.118, “The following SDK component was not installed: build-tools-21.1.1” akan muncul setelah klik “Cancel”. Kemudian pada Gambar 1.119, setelah klik “Finish”, jika tidak muncul Android Studio, maka sebaiknya anda install terlebih dahulu “buildtools-21.1.1”.
Start Android Studio dari Apps Search
Gambar 1.119 Start Android Studio dari Apps Search
58
Pastikan komputer atau laptop anda internetnya sudah “connected”, lalu Klik “Retry”
Gambar 1.120 Setup Wizard (Klik Retry)
Gambar 1.121 Downloading Android SDK Build-tools, revision 21.1.1
59
Setelah selesai “Downloading Android SDK Build-tools”, Klik “Finish”
Gambar 1.122 Download Android SDK Build-tools was successfully
Android Studio siap untuk digunakan
Gambar 1.123 Welcome to Android Studio 60
1.3.2 View SDK Android Studio Berikut ini adalah langkah-langkah untuk menampilkan folder AppData SDK dari Android yang sudah di-install dalam komputer di “C:\Users\[Nama Komputer]” anda.
Masuk di path “C:\Users\[Nama Komputer]”, Klik “Vew”
Gambar 1.124 Masuk di path “C:\Users\[Nama Komputer]”
Klik “Options”
Gambar 1.125 Klik "Options"
61
Klik “View” pada Folder Options
Gambar 1.126 Folder Options
Klik “Show hidden files, folders, and drivers”, Lalu Klik “Applay” lalu Klik “OK”
Gambar 1.127 Klik “Show hidden files, folders, and drivers” 62
Tampilan path sekarang, “AppData” sudah terlihat
Gambar 1.128 “AppData” sudah terlihat
Double Klik “AppData”, atau langsung kunjungi path ini “C:\Users\[Nama Komputer]\AppData\Local\Android\sdk”
Gambar 1.129 Lokasi SDK Android Studio
63
1.3.3 Solusi Error/ Problem Android Studio
Run “MainActivity”
Gambar 1.130 Run “MainActivity” Ketika anda menjalankan pertama kali, jika terdapat Error “JDK”. Maka coba cek di “Variable value:” misal ada jdk yang anda install lebih dari satu versi, dan telah diisikan juga di “Variable value:” misal “;C:\Program Files\Java\jdk1.7.0_40\bin”, maka anda harus menggantinya dengan versi yang terbaru misal “;C:\Program Files\Java\jdk1.8.0_31\bin”. Kemudian Klik “Try Again”. Tunggu beberapa detik.
Gambar 1.131 Edit System Variables JDK 1.8
64
Gambar 1.132 Launch Emulator (Launch emulator)
Gambar 1.133 Launch Emulator (running device) 65
Klik “OK”, jIka ada bug akan tampil seperti ini. Solusinya Klik “Sync Project with Grandle files”
Gambar 1.134 Unexpected Error (Local path doesn't exist) Sync..
Gambar 1.135 Local path doesn't exist (Event Log) Solusi awal yang dapat dilakukan untuk Error “Local path doesn’t exist” adalah download dengan memasukkan perintah pada terminal “gradlew clean packageDebug” seperti dibawah ini.
Gambar 1.136 Jalankan perintah “gradlew clean packageDebug” Lalu dengan Klik “Setting”, Klik “Gradle”, kemudian isi “Gradle VM options:” dengan “-Xmx256m”.
Gambar 1.137 Klik “Setting” di Android Studio 66
Gambar 1.138 isi “Gradle VM options:” dengan “-Xmx256m”
Check “Edit Configurations….”
Gambar 1.139 Check “Edit Configurations….” Di dalam “Edit Configurations….””, nama form-nya “Run/Debug Configurations”. Disana terdapat Android Application “app” dan “MainActivity”. Pastikan anda juga telah men-setting seperti pada gambar di bawah ini, terdapat juga “Gradle-aware Make”.
67
Gambar 1.140 Android Application (app)
Gambar 1.141 Android Application (MainActivity) 68
Error ketika running dengan MyAVD (“C:\Users\Imacho\AppData\Local\Android\sdk\tools\emulat or.exe -avd MyAVD -netspeed full -netdelay none emulator: ERROR: This AVD's configuration is missing a kernel file!!”)
Gambar 1.142 Failed to complete Gradle execution
Gambar 1.143 ERROR: This AVD's is missing a kernel file
Error ketika running dengan Nexus 5 API … (“C:\Users\Imacho\AppData\Local\Android\sdk\tools\emulat or.exe -avd Nexus_5_API_21_x86 -netspeed full -netdelay none emulator: ERROR: x86 emulation currently requires hardware acceleration! Please ensure Intel HAXM is properly installed and usable. CPU acceleration status: HAX kernel module is not installed!”)
69
Gambar 1.144 Failed to complete Gradle execution
Gambar 1.145 ERROR: requires hardware acceleration
Gambar 1.146 Cannot launch AVD in emulator
70
Solusinya adalah sebagai berikut : a. Install HAXM dari path “C:\Users\[Nama Komputer]\AppData\Local\Android\sdk\extras\intel\Hardware_ Accelerated_Execution_Manager”
Gambar 1.147 intelhaxm-android.exe
Gambar 1.148 Install HAXM 1.1.1
Error ketika menjalankan kembali “Android Studio”
71
Gambar 1.149 Error launching Android Studio Solusi dengan men-delete “JAVA_HOME” dari “Environment Variables” , atau dengan menganti variable value “JAVA_HOME” menjadi “C:\Program Files\Java\jdk1.8.0_31\”, solusi ini juga digunakan untuk mengatasi “Failed to complete Gradle execution”. Langkah alternatif ini akan dilakukan pada tahapan kedua.
Gambar 1.150 Delete “JAVA_HOME” dari “Environment Variables”
72
Gambar 1.151 After Delete “JAVA_HOME”
Gambar 1.152 Error launching Android Studio Solusi dengan menganti variable value “JAVA_HOME” menjadi “C:\Program Files\Java\jdk1.8.0_31\”, solusi ini juga digunakan untuk mengatasi “Failed to complete Gradle execution”:
Gambar 1.153 Menganti variable value “JAVA_HOME”
73
Untuk mengkoneksikan Android Studio + Bluestack, yaitu dengan cara klik kanan file “adb.exe” di path “C:\Users\Imacho\AppData\Local\Android\sdk\platformtools”, pilih “run as administrator”.
Gambar 1.154 Menghubungkan Android Studio + Bluestack I
Gambar 1.155 Menghubungkan Android Studio + Bluestack II Proses di atas berjalan sangat cepat, dan hampir tidak terlihat secara jelas oleh mata. Untuk melihatnya, kita bisa menggunakan perintah berikut :
Menjalankan “cmd.exe” as administrator di “”, lalu menjalankan file “adb.exe” yang ada pada file “C:\Users\Imacho\AppData\Local\Android\sdk\platformtools\adb.exe”
74
Gambar 1.156 Run cmd.exe as Administrator
Gambar 1.157 Run adb.exe by cmd as Administrator
Tabel 1.1 Log “Run adb.exe by cmd as Administrator” Log ‘‘Run adb.exe by cmd as Administrator’’ Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation. All rights reserved. C:\Windows\system32>cd C:\Users\Imacho\AppData\Local\Android\sdk\platformtools C:\Users\Imacho\AppData\Local\Android\sdk\platformtools>adb.exe Android Debug Bridge version 1.0.32
75
-a on all interfaces for a c onnection -d the only connected USB devic e
- directs adb to listen
- directs command to
returns an error if more than one USB device is present. -e the only running emulator.
- directs command to returns an error if
more than one emulator is r unning. -s <specific device> the device or emulator with the given
- directs command to
serial number or qualifier. Overrides ANDROID_S ERIAL environment variable. - simple product name
-p <product name or path> like 'sooner', or
a relative/absolute path to a product out directory like 'out/target/product/sooner'. If -p is not specified, the ANDROID_PRODUCT_OUT environment variable is used, which must be an absolute path. - Name of adb server
-H host (default: localhost) -P (default: 5037) devices [-l] devices
- Port of adb server - list all connected ('-l' will also list
device qualifiers) connect
[:<port>] via TCP/IP
- connect to a device Port 5555 is used by
default if no port number is specified. disconnect [[:<port>]] TCP/IP device.
76
- disconnect from a
Port 5555 is used by default if no port number is specified. Using this command with no additional arguments will disconnect from all connected TCP/IP devic es. device commands: adb push [-p] - copy file/dir to device ('-p' to display the transfer progress) adb pull [-p] [-a] [] - copy file/dir from device ('-p' to display the transfer progress) ('-a' means copy timestamp and mode) adb sync [ ] - copy host->device only if changed (-l means list but don't copy) (see 'adb help all') adb shell - run remote shell interactively adb shell - run remote shell command adb emu - run emulator console command adb logcat [ ] - View device log adb forward --list - list all forward socket connections. the format is a list of lines with the followin g format: <serial> " " " " "\n" adb forward - forward socket connections forward specs are one of: tcp:<port> localabstract:
77
localreserved: localfilesystem: dev: jdwp:<process pid> (remote only) adb forward --no-rebind - same as 'adb forward ' but fail s if is already forwarded adb forward --remove - remove a specific forward socket connection adb forward --remove-all - remove all forward socket connections adb reverse --list - list all reverse socket connections from device adb reverse - reverse socket connections reverse specs are one of: tcp:<port> localabstract: localreserved: localfilesystem: adb reverse --norebind - same as 'adb reverse ' but fail s if is already reversed. adb reverse --remove - remove a specific reversed socket connection adb reverse --remove-all - remove all reversed socket connections from dev ice adb jdwp - list PIDs of processes hosting a JDWP transport adb install [-lrtsd] adb install-multiple [-lrtsdp]
78
- push this package file to the device and instal l it (-l: forward lock application) (-r: replace existing application) (-t: allow test packages) (-s: install application on sdcard) (-d: allow version code downgrade) (-p: partial application install) adb uninstall [-k] <package> - remove this app package from the device ('-k' means keep the data and cache directories ) adb bugreport - return all information from the device that should be included in a bug report. adb backup [-f ] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>] - write an archive of the device's data to . If no -f option is supplied then the data is wr itten to "backup.ab" in the current directory. (-apk|-noapk enable/disable backup of the .apks themselves in the archive; the default is noapk.) (-obb|-noobb enable/disable backup of any insta lled apk expansion (aka .obb) files associated with each applic ation; the default is noobb.) (-shared|-noshared
79
enable/disable backup of the device's shared storage / SD card contents; the defau lt is noshared.) (-all means to back up all installed applicatio ns) (-system|-nosystem toggles whether -all automat ically includes system applications; the default is to inclu de system apps) (<packages...> is the list of applications to b e backed up. If the -all or shared flags are passed, then t he package list is optional. Applications explicitly g iven on the command line will be included even if -nosys tem would ordinarily cause them to be omitted.) adb restore tents from the backup archive
- restore device con-
adb help sage adb version
- show this help mes- show version num
scripting: adb wait-for-device online adb start-server a server running adb kill-server is running adb get-state bootloader | device adb get-serialno number> adb get-devpath
- block until device is - ensure that there is - kill the server if it - prints: offline | - prints: <serial- prints: <device-path>
80
adb status-window - continuously print device status for a specifie d device adb remount - remounts the /system and /vendor (if present) p artitions on the device read-write adb reboot [bootloader|recovery] - reboots the device, optionally into the boo tloader or recovery program adb reboot-bootloader - reboots the device into the bootloader adb root - restarts the adbd daemon with root permissions adb usb - restarts the adbd daemon listening on USB adb tcpip <port> - restarts the adbd daemon listening on TCP on th e specified port networking: adb ppp [parameters] - Run PPP over USB. Note: you should not automatically start a PPP connection. refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1 [parameters] - Eg. defaultroute debug dump local notty usepeerdns adb sync notes: adb sync [ ] can be interpreted in several ways: - If is not specified, /system, /vendor (if present), and /data pa rtitions will be updated. - If it is "system", "vendor" or "data", only the corresponding partition is updated. environmental variables: ADB_TRACE - Print debug information. A comma separated list of the following values 1 or all, adb, sockets, packets, rwx, usb, sync , sysdeps, transport, jdwp ANDROID_SERIAL - The serial number to connect to. -s takes prior ity over this if given. ANDROID_LOG_TAGS - When used with the
81
logcat option, only these de bug tags are printed. C:\Users\Imacho\AppData\Local\Android\sdk\platformtools>
Setelah run “adb.exe”, lalu lihatlah dari Android Studio apakah Bluestack sudah terkoneksi dengan Android Studio, dengan Klik “Android Device Monitor”
Gambar 1.158 Klik “Android Device Monitor”
Tunggu beberapa saat, sampai terlihat bahwa Bluestack telah aktif
Gambar 1.159 Bluestack telah aktif di Android Studio
82
Gambar 1.160 Success run App (Android Studio + Bluestack)
Lokasi file *.apk hasil running
Gambar 1.161 Lokasi file *.apk hasil running
83
Error lainnya ketika setelah membuat Project baru “Failure [INSTALL_FAILED_OLDER_SDK]”:
Gambar 1.162 INSTALL FAILED OLDER SDK Solusinya, Masuk ke “Gradle Scripts”, klik “build.gradle(Module:app)” ubah dibagian “compileSdkVersion 19” ubah dibagian “minSdkVersion & targetSdkVersion”:
Gambar 1.163 Klik “build.gradle(Module:app)”
Gambar 1.164 Ubah compileSdkVersion 19
84
Gambar 1.165 Ubah minSdkVersion & targetSdkVersion
Klik pada bagian Gradle files have changed since last project sync. A project sync may be necessary for the IDE to work properly "Sync Now".
Gambar 1.166 Klik "Sync Now"
:
Tunggu beberapa detik, maka akan muncul tampilan seperti ini
Gambar 1.167 Gradle project sync in progress...
Klik “Yes” di Language Level Changed.
85
Gambar 1.168 Language Level Changed Error “Files under the build folder are generated and should not be edited” atau Error “Error:(50, 21) No resource found that matches the given name: attr 'android:actionModeShareDrawable'.”
Gambar 1.169 Files under the build folder are generated and should not be edited Ubah “dependencies”.
Gambar 1.170 Ubah “dependencies” 86
Copykan file “android-support-v4.jar” “D:\ProjectAndroidStudio_2015\B_2_1Primitives_Object\app\libs”.
ke
Gambar 1.171 File android-support-v4.jar Klik “Sync Now”
Gambar 1.172 Klik “Sync Now” Atau solusi untuk error “” adalah dengan langkah berikut : Dalam Android Studio ketika mencoba menggunakan compileSdkVersion dan targetSdkVersion of 19, dengan mengubah file “build.gradle” dari : dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompatv7:21.0.3' } Setting untuk older version dari appcompat library, menjadi : dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompatv7:19.+' }
87
Jika menggunakan “Setting untuk older version dari appcompat library”, maka anda tanpa perlu melakukan copy paste file “androidsupport-v4.jar” ke D:\ProjectAndroidStudio_2015\B_2_1Primitives_Object\app\libs”.
Gambar 1.173 Setting untuk old version dari appcompat library Ubah “<style name="AppTheme" ent="Theme.AppCompat.Light.DarkActionBar">” name="AppTheme" ent="android:Theme.Holo.Light.DarkActionBar">”.
par“<style par-
Gambar 1.174 Ubah styles.xml Jika ada error : Error:(4) No resource identifier found for attribute 'showAsAction' in package 'com.example.imacho.bbprimitiveobjectblankactivity'. Solusi : Ubah file “menu_main.xml”
Gambar 1.175 Ubah file “menu_main.xml”
88
Gambar 1.176 Content Asli "menu_main.xml” menjadi berikut :
Gambar 1.177 Ubah Content Asli "menu_main.xml” Kemudian jika terdapat error “Unfortunately, [.Nama Project.] has stopped” saat menjalankan program, maka bisa jadi ada asset yang belum dimasukkan atau bahkan folder assetnya belum dibuat didalam folder main.
89
Gambar 1.178 Solusi error “Unfortunately, [NamaProject] has stopped” Berikut tampilan ketika berhasil menjalankan tampilan primitive object :
Gambar 1.179 Tampilan Primitive Object
90
Cara menghapus Module pada Andorid Studio :
Klik "File -> Project Structure", lalu Pilih Module yang ingin anda hapus, lalu klik tanda “--”
Gambar 1.180 Project Structure
Gambar 1.181 Remove Module
Gambar 1.182 Gradle project sync in progress.... 91
Klik “OK”
Gambar 1.183 Klik OK
Gambar 1.184 Delete directory "Nama Project..."
1.3.4 Compare Eclipse dengan Android Studio Berikut ini perbandingan antara Eclipse dengan Android Studio (base IntelliJ IDEA) : Tabel 1.2 Concepts Map : Eclipse Vs Android Studio No
Eclipse
Android Studio
1
Ant
Gradle
2
Workspace
Project
3
Project
Module
4
Project-specific JRE
Module JDK
5
User library
Global library
6
Classpath variable
Path variable
7
Project dependency
Module dependency
92
8
Library
Module library
1.3.5 Membuat AVD baru dari AVD Manager
Klik “AVD Manager” Pada Tool bar Android Studio di pojok kanan atas
Gambar 1.185 AVD Manager
Daftar Virtual Device, Klik “Create Virtual Device….”
93
Gambar 1.186 Daftar Virtual Device
Pilih Phone, Klik “Next”
Gambar 1.187 Pilih Hardware (Phone)
Pilih System Image
94
Gambar 1.188 Pilih System Image (Lollipop)
Virtual Device Configuration, Lalu Klik “Show Advanced Setting”
95
Gambar 1.189 Virtual Device Configuration
Verify Configuration, misal mengubah SD card dari 200 MB menjadi 500 MB, Camera Front dari none menjadi Webcam0, lalu Klik “Finish”
Gambar 1.190 Verify Configuration
AVD baru sudah terbentuk
96
Gambar 1.191 Creating/Updating AVD
Gambar 1.192 AVD baru sudah terbentuk
Running AVD
Gambar 1.193 Running AVD di Android Studio
Tampilan AVD, Tunggu -+ 5 menit
97
Gambar 1.194 Tampilan Loading AVD di Android Studio
98
Gambar 1.195 Tampilan AVD di Android Studio I
99
Gambar 1.196 Tampilan AVD di Android Studio II
100
Gambar 1.197 Tampilan AVD di Android Studio III
101
Gambar 1.198 Tampilan AVD di Android Studio IV
1.3.6 Import Project Eclipse ke Android Studio
Gambar 1.199 Import Project
102
Select satu folder project, misal “1_1Introduction_To_OpenGL_ES” dari folder workspace “z_EclipseProjectAndroid_2014” Eclipse atau Gradle Project to Import, Lalu Klik OK
Gambar 1.200 Import Project ADT-Eclipse ke Android Studio
Gambar 1.201 Memilih Tipe Import Project 103
Karena Project dari Eclipse, maka pilihlah “Import Project from external model”, lalu Pilih Gradle. Cara yang paling sederhana untuk Import dari Project Eclipse ke Android Studio adalah sebagai berikut :
Tutup semua project apapun yang ada di Android Studio
Gambar 1.202 Tutup semua Project yang masih aktif
Setelah muncul “Welcome to Android Studio’, lalu Klik “Import Non-Android Studio project”
Gambar 1.203 Muncul “Welcome to Android Studio’ 104
Gambar 1.204 Klik “Import Non-Android Studio project” Langkahnya sama seperti sebelumnya, yaitu Select satu folder project, misal “1_1Introduction_To_OpenGL_ES” dari folder workspace “z_EclipseProjectAndroid_2014” Eclipse.
Gambar 1.205 Import Project ADT-Eclipse ke Android Studio
105
Gambar 1.206 Memilih Tipe Import (.. from external model Gradle)
Pada form “Import Project”, Klik Finish
Gambar 1.207 Proses Importing 106
Setelah Import, terdapat error “Can’t start Mercurial: hg.exe”
Gambar 1.208 List Project hasil Import 107
Gambar 1.209 Error Can’t start Mercurial: hg.exe setelah Import
Mencoba mengatasi Error diatas dengan Klik “Fix it”
Gambar 1.210 Klik “Fix it”
Import per Project From ADT Eclipse dengan memiih satu Project yang mau di-Import, Misal Project “1_1Introduction_To_OpenGL_ES”, lalu Klik OK
Gambar 1.211 Memiih satu Project yang mau di-Import 108
Memilih path tujuan untuk menyimpan hasil Import Project, Misal di “D:\Data Kuliah\!Genap 2014-2015\2. Grafika Komputer\z_ProjectAndroidStudio_2015\ 1_1Introduction_To_OpenGL_ES”
Gambar 1.212 Path tujuan untuk menyimpan hasil Import Project
Gambar 1.213 Import Destination Directory, Klik Next Hilangkan atau uncheck “Replace jars …. when possible”, sedangkan yang lainnya tetap di checked.
109
Gambar 1.214 Import per Project From ADT Eclipse
Proses Importing sedang dilakukan, tunggu beberapa waktu sampai selesai
Gambar 1.215 Proses Importing sedang dilakukan
Summary setelah proses Import
Gambar 1.216 Summary setelah proses Import 110
Tampilan Project hasil Import
Gambar 1.217 Tampilan Project hasil Import
Error Message “Gradle project sync failed. Basic functionality (e.g. editing debugging) will not work properly”
Gambar 1.218 Error Message “Gradle project sync failed
Solusi yang ditawarkan oleh Android Studio, Klik “Try Again”
Gambar 1.219 Klik “Try Again”
Akan tetapi jika solusi yang ditawarkan oleh Android Studio itu tidak berhasil, maka coba cara lainnya. Buka salah satu code *.java yang ada pada Prohect. Jika muncul Error “Project SDK is not defined”
111
Gambar 1.220 Error “Project SDK is not defined”
Klik “Setup SDK”
Gambar 1.221 Klik “Setup SDK”
Select Project SDK, lalu Klik “OK”
Gambar 1.222 Select Project SDK
112
Coba Klik File “Invalidate Caches / Restart” Project, lalu Klik “Try Again” lagi
Gambar 1.223 Klik “Try Again” lagi
Masuk di “Setting”, lalu pilih “Grade”, isi Gradle home = “C:/Program Files/Android/Android Studio/gradle/gradle2.2.1” dan isilah seperti berikut :
Gambar 1.224 Masuk di “Setting”, lalu pilih “Grade”
113
Cara lainnya adalah dengan Klik kanan project lalu pilih “Open Module Settings”.
Klik “Open Module Settings”
Gambar 1.225 Buka “Open Module Settings”
114
Gambar 1.226 Lokasi SDK dan JDK
Gambar 1.227 Project Structure
115
Jika “Project Structure” pada bagian modules masih kosong, seperti pada gambar berikut.
Gambar 1.228 Project Structure modules masih kosong Maka anda harus mengisikan dengan contoh sebagaimana pada gambar berikut ini, lalu klik Apply
Gambar 1.229 Project Structure modules telah disi
116
Cara lainnya mengatasi Error Message “Gradle project sync failed. Basic functionality (e.g. editing debugging) will not work properly” adalah dengan membuka “Android SDK Manager”, kemudian Install “Extras Android Support Repository”. Lalu Klik “Tray Again”.
Gambar 1.230 Klik “Try Again” “1_1Introduction_To_OpenGL_ES” adalah nama project dari ADT-Eclipse yang telah di-import ke Android Studio. Penyebab errornya adalah “failed to find target android-19 : C:\Users\Imacho\AppData\Local\Android\sdk”.
Gambar 1.231 Klik Install missing paltform(s) and sync project
Gambar 1.232 License Agreement
117
Kemudian pilih “Android SDK Platform 19”, pilih “Accept”, lalu klik “Next”.
Gambar 1.233 Pilih Android SDK Platform 19
Gambar 1.234 Installing Requested Components
118
Gambar 1.235 Installing Requested Components (Klik Finish)
Gambar 1.236 Terlihat Android 19 sudah terinstall
119
1.3.7 Konfigurasi pada Smartphone Android Jika ingin menjadikan smartphone Android sebagai emulator, maka langkah-langkah konfigurasinya adalah sebagai berikut: 9. Siapkan smartphone Android. Pada contoh ini, smartphone Android yang digunakan adalah Samsung GT-i9070 Galaxy S Advance. 10. Pada smartphone, pililh “setting”, lalu klik “Applications/Application Manager” –> ”Development” –> klik/ beri tanda cek pada “USB debugging”.
Gambar 1.237 USB Debugging Pada Smartphone Samsung 11. Pasang kabel USB smartphone dengan PC, run app, lalu cek “Devices” pada Android Studio.
Gambar 1.238 Pilih Devices pada Android Studio 12. Konfigurasi selesai. 120
1.3.8 Konfigurasi "AS + Genymotion" Langkah-langkah untuk install Genymotion Master installer genymotion-2.3.1-vbox.exe adalah sebagai berikut : 1. Install “Genymotion”
Gambar 1.239 Install Genymotion 2. Klik OK
Gambar 1.240 Select Setup Language
121
3. Setup Genymotion, Klik “Next”
Gambar 1.241 Setup – Genymotion I
Gambar 1.242 Setup – Genymotion II
122
Gambar 1.243 Setup – Genymotion III
Gambar 1.244 Setup – Genymotion IV
123
Gambar 1.245 Setup – Genymotion V 4. Proses Installing, Klik Yes To Install Virtual Box baru
Gambar 1.246 Proses Installing Genymotion
124
Gambar 1.247 Install VirtualBox I
Gambar 1.248 Install VirtualBox II
125
Gambar 1.249 Install VirtualBox III
Gambar 1.250 Install VirtualBox IV
126
Gambar 1.251 Install VirtualBox VI
Gambar 1.252 Install VirtualBox VII
127
5. Klik Finish
Gambar 1.253 Install VirtualBox VIII
Gambar 1.254 Yes, restart the computer now
128
Langkah-langkah untuk Konfigurasi Genymotion di Android Studio adalah sebagai berikut : 1. Android Studio, Klik File > Settings. 2. Pilih Plugins 3. Browse Repositories, ketik “Genymotion”, Klik “Install plugin”
Gambar 1.255 Ketik “Genymotion”, Klik “Install plugin” 4. Klik Yes
Gambar 1.256 Download and Install
129
Gambar 1.257 Download Plugins 5. Klik “Restart Android Studio”
Gambar 1.258 Klik “Close”
Gambar 1.259 Plugin Changed
130
Langkah-langkah untuk Running Project OpenGL dari Android Studio (dengan emulator Genymotion) adalah sebagai berikut : 1. Android Studio, Klik File > Settings.
Gambar 1.260 Android Studio, Klik File > Settings. 2. Klik Genymotion
Gambar 1.261 Klik Genymotion
131
3. Tekan Tombol “Shift + Enter” atau Klik “Kotak Kecil” disebelah kanan text field “Select the path to the Genymotion folder”
Gambar 1.262 Klik “Kotak Kecil” disebelah kanan text field
4. Browse lokasi dimana anda menginstall Genymotion misal di “C:\Program Files\Genymobile\Genymotion”, lalu klik OK
Gambar 1.263 Browse lokasi menginstall Genymotion
132
5. Sehingga di “” tampil seperti gambar berikut, lalu klik OK
Gambar 1.264 Content Select the path to the Genymotion folder 6. Jalankan Genymotion di Android Studio dengan klik logo Genymotion
Gambar 1.265 Logo Genymotion di Android Studio 7. Tampilan beberapa list virtual device (emulator) Android di Genymotion yang sudah anda download sebelumnya dari Genymotion yang dijalankan melalui Program Files atau double klik logo Genymotion di Desktop. Jika belum ada yang tampil di list, klik Refresh
Gambar 1.266 Genymotion Device Manager
133
8. Pilih salah satu virtual device yang ingin anda jalankan
Gambar 1.267 Pilih salah satu virtual device 9. Klik Start untuk menjalankan virtual device
Gambar 1.268 Klik Start (Run Virtual Device)
Gambar 1.269 Initializing virtual device
134
10. Loading Android di virtual device
Gambar 1.270 Loading Android di virtual device
135
11. Tampilan awal virtual device Genymotion
Gambar 1.271 Virtual device Genymotion I
136
Gambar 1.272 Virtual device Genymotion II
137
Gambar 1.273 Virtual device Genymotion III
138
Gambar 1.274 Virtual device Genymotion IV
139
12. Tampilan kode program
Gambar 1.275 MainActivity.java
Gambar 1.276 Point_n_Lines_with_Points_Object.java
140
Gambar 1.277 ESRender.java 13. Detail Sourcecode Source Code 1.1 MainActivity.java MainActivity.java package com.introduction_to_opengl_es; import import import import import import
android.opengl.GLSurfaceView; android.os.Bundle; android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
// By : Imam Cholissodin ([email protected]) public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE);
141
// making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCR EEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
142
Source Code 1.2 Point_n_Lines_with_Points_Object.java Point_n_Lines_with_Points_Object.java package com.introduction_to_opengl_es; import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10;
import android.util.Log; // By : Imam Cholissodin ([email protected]) public class Point_n_Lines_with_Points_Object { private float vertices_line_with_points[] = null; private float vertices_line_with_points_color[] = null; float x, y; float step_loop = 0.001f; float x1, y1; float x2, y2; float array_factor = 2.0f; private int loop_line, loop_line_color; public Point_n_Lines_with_Points_Object() { // ============ start to generate vertices to create line with point ========================== x1 = -1.0f; y1 = -1.0f; x2 = 1.0f; y2 = 1.0f; loop_line = 0; loop_line_color = 0; vertices_line_with_points = new float[(int)(array_factor*(x2 - x1) / step_loop) * 3]; // 3 is number of dimension x,y,z vertices_line_with_points_color = new float[(int)(array_factor*(x2 - x1) / step_loop) * 4]; // 4 is number of channel color r,g,b,a float m = (y2 - y1) / (x2 - x1); // count gradient for (x = x1; x <= x2; x += step_loop) {
143
vertices_line_with_points[loop_line] = (float)(x); // as x value vertices_line_with_points[loop_line + 1] = (float)(m*(x x1) + y1); // as y value vertices_line_with_points[loop_line + 2] = 0; // as z value, z=0 is to assume that the object is on 2D loop_line += 3; //Generate color for each vertex vertices_line_with_points_color[loop_line_color] = (float)Math.abs(Math.sin(x)); // Red Channel vertices_line_with_points_color[loop_line_color + 1] = (float)Math.abs(Math.cos((m*(x - x1) + y1))); // Green Channel vertices_line_with_points_color[loop_line_color + 2] = 0.0f; // Blue Channel vertices_line_with_points_color[loop_line_color + 3] = 1.0f; // set transparant value (alpha) loop_line_color += 4; } /* x=x1; while(x<=x2){ vertices_line_with_points[loop_line] = (float) (x); // as x value vertices_line_with_points[loop_line+1] = (float) (m*(x-x1)+y1); // as y value vertices_line_with_points[loop_line+2]=0; // as z value, z=0 is to assume that the object is on 2D loop_line+=3; //Generate color for each vertex vertices_line_with_points_color[loop_line_color]=(float) Math.abs(Math.sin(x)); // Red Channel vertices_line_with_points_color[loop_line_color+1]=(float) Math.abs(Math.cos((m*(x-x1)+y1))); // Green Channel vertices_line_with_points_color[loop_line_color+2]=0.0f; //
144
Blue Channel vertices_line_with_points_color[loop_line_color+3]=1.0f; // set transparant value (alpha) loop_line_color+=4; x+=step_loop; } */ // ============= end for generate vertices to create line with point ==================== } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_points(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for all the points gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // List Point to our vertex buffer with manually gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, 0.8f, 0.0f, // V2 1.0f, 0.6f, 0.0f, // V3 1.0f, 0.4f, 0.0f, // V4 1.0f, 0.2f, 0.0f,
145
// V5 1.0f, 0.0f, 0.0f, // V6 1.0f, -0.2f, 0.0f, // V7 1.0f, -0.4f, 0.0f, // V8 1.0f, -0.6f, 0.0f, // V9 1.0f, -0.8f, 0.0f, // V10 1.0f, -1.0f, 0.0f, // V11 0.8f, -1.0f, 0.0f, // V12 0.6f, -1.0f, 0.0f, // V13 0.4f, -1.0f, 0.0f, // V14 0.2f, -1.0f, 0.0f, // V15 0.0f, -1.0f, 0.0f, // V16 -0.2f, -0.4f, -0.6f, -0.7f, -0.8f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
// // // // // //
V17 V18 V19 V20 V21 V22
})); // Draw the vertices as points gl.glDrawArrays(GL10.GL_POINTS, 0, 22); // 0 is start index, 22 is length of list points
//Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } /*public void draw_line(GL10 gl){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the line gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
146
// Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex (x,y,z) -1.0f, -1.0f, 0.0f, // V2 - second vertex })); // Draw the vertices as lines gl.glDrawArrays(GL10.GL_LINES, 0, 2); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); }*/ public void draw_line_with_points_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Lish all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points)); // Set/ mapping the colour for the line each vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points_color)); // Draw the vertices as lines with points :
/////////////////////////////////////////// // start draw with exact length of array // /////////////////////////////////////////// gl.glDrawArrays(GL10.GL_POINTS, 0, (int)(loop_line / 3)); // 3 is number of dimension x,y,z
// or
147
//gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (loop_line_color / 4)); // 4 is number of channel color r,g,b,a
///////////////////////////////////////////
//
end draw with exact length of array
//
///////////////////////////////////////////
///////////////////////////////////////////////
// start draw with not exact length of array //
///////////////////////////////////////////////
//gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (Math.abs((x2 - x1)) / step_loop));
// or
//gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (vertices_line_with_points.length/(array_factor*3))); // 3 is number of dimension x,y,z
// or
//gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (vertices_line_with_points_color.length/(array_factor*4)));
148
// 3 is number of dimension x,y,z
///////////////////////////////////////////////
// array
end draw with not exact length of
//
///////////////////////////////////////////////
// to tracking log.v
// try type like this "tag:value.loop_" without quotes on search "verbose". Log.v("value loop_line", "" + loop_line); Log.v("value loop_line/3", "" + loop_line / 3); Log.v("value loop_line_color", "" + loop_line_color); Log.v("value loop_line_color/4", "" + loop_line_color / 4); Log.v("value Math.abs((x2 - x1)) / step_loop)", "" + (Math.abs((x2 - x1)) / step_loop)); Log.v("value vertices_line_with_points.length", "" + vertices_line_with_points.length); Log.v("value vertices_line_with_points.length/(array_factor*3)", "" + (int)(vertices_line_with_points.length / (array_factor * 3))); Log.v("value vertices_line_with_points_color.length", "" + vertices_line_with_points_color.length); Log.v("value vertices_line_with_points_color.length/(array_factor*4)", "" + (int)(vertices_line_with_points_color.length / (array_factor * 4))); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
149
gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
Source Code 1.3 ESRender.java ESRender.java package com.introduction_to_opengl_es; import import import import
javax.microedition.khronos.egl.EGLConfig; javax.microedition.khronos.opengles.GL10; android.opengl.GLSurfaceView.Renderer; android.opengl.GLU;
// By : Imam Cholissodin ([email protected]) public class ESRender implements Renderer { private Point_n_Lines_with_Points_Object point_n_linesobject; // the object to be drawn
/** Constructor to set the handed over context */ public ESRender() { this.point_n_linesobject = new Point_n_Lines_with_Points_Object(); } @Override public void onDrawFrame(GL10 gl) { gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background with white color
//gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background with black color gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // clear Screen and Depth Buffer
// display drawing points
150
gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glPointSize(3); gl.glEnable(GL10.GL_POINT_SMOOTH); point_n_linesobject.draw_points(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing create line with points gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glPointSize(3); // set size of points gl.glEnable(GL10.GL_POINT_SMOOTH); point_n_linesobject.draw_line_with_points_color( gl); gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float)width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) {
151
point_n_linesobject = new Point_n_Lines_with_Points_Object(); } }
14. Klik Run ‘app’ untuk menjalankan project OpenGL
Gambar 1.278 Run 'app'
Gambar 1.279 Gradle: Executing Tasks [:app:assembleDebug] 15. Pilih running device, klik OK
Gambar 1.280 Pilih running device 16. Tampilan aplikasi OpenGL “Membuat Titik dan Garis dengan Titik”
152
Gambar 1.281 Gradle build finished
Gambar 1.282 Tampilah aplikasi OpenGL
153
17. “Log.v” di kode program
Gambar 1.283 “Log.v” di kode program 18. Tampilan tracking log.v “try type like this "tag:value.loop_" without quotes on search "verbose" di Android Device Monitor.
Gambar 1.284 Tracking log.v
154
1.3.9 Membuat Project Baru di AS 1. Android Studio, Klik “Start a new Android Studio project”
Gambar 1.285 Klik “Start a new Android Studio project” 2. Atau Klik File > New Project….
Gambar 1.286 Android Studio, Klik File > New Project….
3. Berikan nama aplikasi, misal “Primitive Object ES”, dan project location-nya di “D:\ProjectAndroidStudio_2015\PrimitiveObjectES” lalu klik Next 155
Gambar 1.287 Berikan nama aplikasi yang anda buat 4. Pilih “Phone and Tablet” dan Minimum SDK “API 8:Android 2.2 (Froyo)”, lalu klik Next
Gambar 1.288 Pilih “Phone and Tablet” dan “API 8:.. (Froyo)”
156
Gambar 1.289 API Level:Froyo sampai Lollipop
Gambar 1.290 APIs Level:Froyo for OpenGL ES 2.0
157
Gambar 1.291 APIs Level:Gingerbread
Gambar 1.292 APIs Level:Ice Cream Sandwicth
158
Gambar 1.293 APIs Level:Jelly Bean 16
Gambar 1.294 APIs Level:Jelly Bean 17
159
Gambar 1.295 APIs Level:Jelly Bean 18
Gambar 1.296 APIs Level:Kit Kat 19
160
Gambar 1.297 APIs Level:Lollipop 21
5. Pilih “Blank Activity”, lalu klik Next
Gambar 1.298 Pilih “Blank Activity”
161
6. Biarkan saja isi dari tampilan berikut, lalu klik Finish
Gambar 1.299 Choose options for your new file 7. Tunggu beberapa saat
Gambar 1.300 Building PrimitiveObjectES
Gambar 1.301 Initializing Rendering Library 162
Jika muncul “Missing styles. Is the correct theme chosen for this layout? Use Theme combo box above the layout to choose a different layout, or fix the theme style references. Failed to find styles ‘textViewStyle’ in current theme (4 similar errors not shows) ”. Abaikan, ini tidak akan membuat error aplikasi OpenGL ES.
Gambar 1.302 Missing styles. Is the correct theme chosen 8. Klik “java com.example.imacho.primitiveobjectes”
Gambar 1.303 “java -> com.example.imacho.primitiveobjectes”
163
9. Isikan dengan file-file project yang sudah anda siapkan, misal sebagai berikut
Gambar 1.304 Siapkan file-file project 10. Project siap dijalankan. Selesai
1.3.10 AS
Membuat Module Baru di Project
1. Setelah membuat project, maka module default yang ada hanya satu, yaitu “app”
Gambar 1.305 module default "app"
164
2. Untuk menambah module baru pada project “Primitive Object ES” di Android Studio, Klik “Android Studio, Klik File > New Module….”
Gambar 1.306 Android Studio, Klik File > New Module…. 3. Pilih “Phone and Tablet Application”, lalu Klik Next
Gambar 1.307 Pilih “Phone and Tablet Application”
165
4. Berikan nama Aplikasi/Library name, misal “Create Point”, lalu Klik Next
Gambar 1.308 Berikan nama Aplikasi/Library name 5. Pilih “Blank Activity”, lalu Klik Next
Gambar 1.309 Pilih “Blank Activity”
166
6. Biarkan secara default isi dari “Choose options for your new file”. Silahkan jika ingin mengubah Title, misal dengan ”CreatePoint”, lalu Klik Finish
Gambar 1.310 Default isi dari “Choose options for your new file” 7. Tunggu beberapa saat “Gradle project sync in progress...”
Gambar 1.311 Tunggu beberapa saat “Gradle in progress...” 8. Module siap dikoding
Gambar 1.312 Module siap dikoding 167
9. Sekarang dapat dilihat bahwa terdapat dua module, yaitu “app” dan “createpoint”
Gambar 1.313 Module “app” dan “createpoint” 10. Selesai
168
BAB 2 Primitives Object 2.1 Pengertian Primitives Object Primitive object merupakan objek dasar yang nantinya dapat dibuat untuk menghasilkan bentuk komplek tertentu yang diinginkan oleh programmer dengan menggabungkan atau mengkombinasikan bentuk-bentuk seperti titik (points), garis (lines), segiempat (quads), dan segitiga (triangles). Pada masing-masing sub bab akan dijelaskan contoh pembuatan dan cara me-render objek primitives. Berikut beberapa parameter ditanda “[..]” pada “gl.glDrawArrays(GL10.[..] , IndexAwal, BanyakData)”.
1 7
2 3
6 5
4
GL_POINTS
Gambar 2.1 GL_POINTS & GL_[LINES/LINE_STRIP/LINE_LOOP]
169
Gambar 2.2 GL_[TRIANGLES/TRIANGLE_STRIP/TRIANGLE_FAN]
2.2 Membuat Titik Dalam membuat titik, disini kita dapat menggunakan “gl.glDrawArrays(GL10.GL_POINTS, 0, 21);”, dimana “0” merupakan start index dan “21” merupakan banyaknya titik yang akan di-plot. Misalnya kita ingin membuat titik secara manual, maka kita cukup memanggil perintah “gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [ ] { x1,y1,z1, // titik ke-1 x2,y2,z2, // titik ke-2 …. , x21, y21, z21 // titik ke-21 }));” Pada glVertexPointer, nilai “3” menyatakan besarnya dimensi dari titik vertex, sedangkan “0” menyatakan nilai start index. Artinya anda ingin menampilkan titik mulai dari index ke-0. GL_FLOAT, karena memang tipe data pada titik-titiknya adalah float, sedangkan “makeFloatBuffer” digunakan untuk membangun vertex buffer dari titik vertices yang sudah dimasukkan oleh user. Kemudian script untuk mengenerate titik-titik secara otomatis menggunakan persamaan garis lurus dengan ukuran titik yang bervariasi dan step_loop “0.2” dapat dilakukan dengan cara berikut. “float size_point=1; for(x=x1;x<=x2;x+=step_loop) { 170
coord_x=(float) (x); coord_y=(float) (m * (x - x1) + y1); coord_z=0.0f; gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glPointSize(size_point); size_point+=1; points_object.draw_points2(gl,coord_x,coord_y,coord_z); gl.glPopMatrix(); }” Hasil ketika kode tersebut dijalankan, maka akan 21 titik yang diset manual dan beberapa titik pada arah sisi miring yang memiliki ukuran dinamis.
Gambar 2.3 Titik manual dan generate Source Code 2.1 Code Membuat Titik (Ukuran Dinamis) ESRender.java package com.example.introduction_to_opengl_es; import import import import
android.opengl.GLSurfaceView.Renderer; android.opengl.GLU; javax.microedition.khronos.egl.EGLConfig; javax.microedition.khronos.opengles.GL10;
171
/** * Created by Imacho on 4/4/2015. */ public class ESRender implements Renderer { private Create_Points points_object; ject to be drawn private float coord_x,coord_y,coord_z; float x,y; float step_loop=0.2f; float x1,y1; float x2,y2; float m;
// the ob-
//private int loop_line,loop_line_color; /** Constructor to set the handed over context */ public ESRender() { this.points_object = new Create_Points(); // ============ set parameter to generate vertices to create dynamic point ========================== x1 = -1.0f; y1 = -1.0f; x2= 1.0f; y2 = 1.0f; m = (y2-y1)/(x2-x1); // count gradient } @Override public void onDrawFrame(GL10 gl) { gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background with white color //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background with black color gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // clear Screen and Depth Buffer // display drawing points gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glPointSize(3); gl.glEnable(GL10.GL_POINT_SMOOTH); points_object.draw_points(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing points with dynamic size float size_point=1; for(x=x1;x<=x2;x+=step_loop) { coord_x=(float) (x); coord_y=(float) (m * (x - x1) + y1); coord_z=0.0f; gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glPointSize(size_point);
172
size_point+=1; points_object.draw_points2(gl,coord_x,coord_y,coord_z); gl.glPopMatrix(); // end freeze state/event to each object } } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { points_object = new Create_Points(); } }
MainActivity.java package com.example.introduction_to_opengl_es; //import javax.microedition.khronos.egl.EGLConfig; //import javax.microedition.khronos.opengles.GL10; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.app.Activity; import android.view.Window; import android.view.WindowManager; /** * Created by Imacho on 4/4/2015.
173
*/ public class MainActivity extends Activity { /** The OpenGL View */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); glSurfaceView = new GLSurfaceView(this); glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); //setContentView(R.layout.activity_main); }
/** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); }
}
Create_Points.java package com.example.introduction_to_opengl_es; //import android.util.Log;
174
import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10;
/** * Created by Imacho on 4/4/2015. */ public class Create_Points { /** Constructor */ public Create_Points() {} // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_points(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for all the points gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // List Point to our vertex buffer with gl.glVertexPointer(3, GL10.GL_FLOAT, 0, FloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // first vertex (x,y,z) 1.0f, 0.8f, 0.0f, // 1.0f, 0.6f, 0.0f, // 1.0f, 0.4f, 0.0f, // 1.0f, 0.2f, 0.0f, // 1.0f, 0.0f, 0.0f, // 1.0f, -0.2f, 0.0f, // 1.0f, -0.4f, 0.0f, // 1.0f, -0.6f, 0.0f, // 1.0f, -0.8f, 0.0f, // 1.0f, -1.0f, 0.0f, // 0.8f, -1.0f, 0.0f, // 0.6f, -1.0f, 0.0f, // 0.4f, -1.0f, 0.0f, // 0.2f, -1.0f, 0.0f, // 0.0f, -1.0f, 0.0f, // -0.2f, -1.0f, 0.0f, // V17 -0.4f, -1.0f, 0.0f, // V18 -0.6f, -1.0f, 0.0f, // V19 -0.8f, -1.0f, 0.0f, // V20 -1.0f, -1.0f, 0.0f, // V21
175
manually makeV1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16
})); // Draw the vertices as points gl.glDrawArrays(GL10.GL_POINTS, 0, 21); // 0 is start index, 22 is length of list points //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_points2(GL10 gl,float coord_x,float coord_y,float coord_z) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for all the points gl.glColor4f(0.0f, 0.0f,1.0f, 1.0f); // List Point to our vertex buffer with manually gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { coord_x, coord_y,coord_z // V1 - first vertex (x,y,z) })); // Draw the vertices as points gl.glDrawArrays(GL10.GL_POINTS, 0, 1); // 0 is start index, 22 is length of list points //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } }
Source Code 2.2 Code Lain Membuat Titik Sederhana ESRender.java package com.introduction_to_opengl_es; import import import import
javax.microedition.khronos.egl.EGLConfig; javax.microedition.khronos.opengles.GL10; android.opengl.GLSurfaceView.Renderer; android.opengl.GLU;
public class ESRender implements Renderer { // the object to be drawn private Point_n_Lines_with_Points_Object point_n_linesobject; /** Constructor to set the handed over context */ public ESRender() { this.point_n_linesobject = new Point_n_Lines_with_Points_Object(); } @Override public void onDrawFrame(GL10 gl) {
176
// set background with white color gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // clear Screen and Depth Buffer gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // display drawing points // start freeze state/event to each object gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glPointSize(3); gl.glEnable(GL10.GL_POINT_SMOOTH); point_n_linesobject.draw_points(gl); // end freeze state/event to each object gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) // To prevent divide by zero height = 1; float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport // Select projection matrix gl.glMatrixMode(GL10.GL_PROJECTION); // Reset projection matrix gl.glLoadIdentity(); // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); // Select model-view matrix gl.glMatrixMode(GL10.GL_MODELVIEW); // Reset gl.glLoadIdentity(); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { point_n_linesobject = new Point_n_Lines_with_Points_Object(); } }
MainActivity.java package com.introduction_to_opengl_es; import android.opengl.GLSurfaceView; import android.os.Bundle;
177
import import import import
android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
178
Point_n_Lines_Points_Object.java package com.introduction_to_opengl_es; import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10;
import android.util.Log; public class Point_n_Lines_with_Points_Object { private float vertices_line_with_points[]=null; private float vertices_line_with_points_color[] = null; float x,y; float step_loop=0.001f; float x1,y1; float x2,y2; float array_factor=2.0f; private int loop_line,loop_line_color; public Point_n_Lines_with_Points_Object() { // ============ start to generate vertices to create line with point ========================== x1 = -1.0f; y1 = -1.0f; x2= 1.0f; y2 = 1.0f; loop_line=0; loop_line_color=0; vertices_line_with_points=new float[(int)(array_factor*(x2-x1)/step_loop)*3]; // 3 is number of dimension x,y,z vertices_line_with_points_color=new float[(int)(array_factor*(x2-x1)/step_loop)*4]; // 4 is number of channel color r,g,b,a // count gradient float m = (y2-y1)/(x2-x1); for(x=x1;x<=x2;x+=step_loop){ // as x value vertices_line_with_points[loop_line] = (float) (x); // as y value vertices_line_with_points[loop_line+1] = (float) (m*(x-x1)+y1); // as z value, z=0 is to assume that the object is on 2D vertices_line_with_points[loop_line+2]=0; loop_line+=3; //Generate color for each vertex // Red Channel verti-
179
ces_line_with_points_color[loop_line_color]=(float) Math.abs(Math.sin(x)); // Green Channel vertices_line_with_points_color[loop_line_color+1]=(float ) Math.abs(Math.cos((m*(x-x1)+y1))); // Blue Channel vertices_line_with_points_color[loop_line_color+2]=0.0f; // set transparant value (alpha) vertices_line_with_points_color[loop_line_color+3]=1.0f; loop_line_color+=4; } // ============= end for generate vertices to create line with point ==================== } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_points(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for all the points gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // List Point to our vertex buffer with manually gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, 0.8f, 0.0f, // V2 1.0f, 0.6f, 0.0f, // V3 1.0f, 0.4f, 0.0f, // V4 1.0f, 0.2f, 0.0f, // V5 1.0f, 0.0f, 0.0f, // V6 1.0f, -0.2f, 0.0f, // V7 1.0f, -0.4f, 0.0f, // V8 1.0f, -0.6f, 0.0f, // V9 1.0f, -0.8f, 0.0f, // V10 1.0f, -1.0f, 0.0f, // V11 0.8f, -1.0f, 0.0f, // V12 0.6f, -1.0f, 0.0f, // V13 0.4f, -1.0f, 0.0f, // V14 0.2f, -1.0f, 0.0f, // V15 0.0f, -1.0f, 0.0f, // V16
180
-0.2f, -0.4f, -0.6f, -0.7f, -0.8f, -1.0f, }));
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
// // // // // //
V17 V18 V19 V20 V21 V22
// Draw the vertices as points gl.glDrawArrays(GL10.GL_POINTS, 0, 22); // 0 is start index, 22 is length of list points //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_line_with_points_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // List all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points)); // Set/ mapping the colour for the line each vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points_color)); // Draw the vertices as lines with points : /////////////////////////////////////////// // start draw with exact length of array // /////////////////////////////////////////// gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (loop_line / 3)); // 3 is number of dimension x,y,z /////////////////////////////////////////// // end draw with exact length of array // /////////////////////////////////////////// // to tracking log.v // try type like this "tag:value.loop_" without quotes on search "verbose". Log.v("value loop_line", ""+ loop_line); Log.v("value loop_line/3", ""+ loop_line/3); Log.v("value loop_line_color", ""+ loop_line_color); Log.v("value loop_line_color/4", ""+ loop_line_color/4); Log.v("value Math.abs((x2 - x1)) / step_loop)", ""+ (Math.abs((x2 - x1)) / step_loop)); Log.v("value vertices_line_with_points.length", ""+vertices_line_with_points.length); Log.v("value vertices_line_with_points.length/(array_factor*3)", ""+(int) (vertices_line_with_points.length/(array_factor*3))); Log.v("value vertices_line_with_points_color.length", ""+vertices_line_with_points_color.length); Log.v("value verti-
181
ces_line_with_points_color.length/(array_factor*4)", ""+(int) (vertices_line_with_points_color.length/(array_factor*4))); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
Gambar 2.4 Membuat Titik Sederhana
2.3 Membuat Garis dengan Titik Logika pembentukannya adalah membuat garis lurus dari dua buah titik, misal (x1,y1) dan (x2,y2) yang kemudian digunakan untuk membentuk persamaan garis lurus, y=mx+c. Adapun penghitungan gradient adalah m = (y2-y1)/(x2-x1) Setelah mendapatkan nilai m, maka dengan menggunakan persamaan y-y1 = m(x-x1) akan didapatkan persamaan garis lurusnya. Dari setiap nilai x dan y akan dipasangkan menjadi satu titik dalam vertex untuk menyusun garis secara berurutan. Dari segitiga pada Gambar 2.5, untuk sisi yang miring dibentuk dengan titik-titik dan warna yang ditampung dalam array 2D menggunakan potongan script 182
“float m = (y2-y1)/(x2-x1); // count gradient for(x=x1;x<=x2;x+=step_loop){ // Generate (x,y,z) for vertex vert..points[loop_line] = .. (x); // as x vert..points[loop_line+1] = .. (m*(x-x1)+y1); // as y vert..points[loop_line+2]=0; // as z loop_line+=3; //Generate color (r,g,b,a) for each vertex vert..color[loop_line_color]=.. abs(sin(x)); vert..color[loop_line_color+1]=.. abs(cos((m * (x - x1) + y1))); vert..color[loop_line_color+2]=0.0f; vert..color[loop_line_color+3]=1.0f; loop_line_color+=4; }” Dimana “vet..point” menyatakan “vertices_line_with_points” dan “vert..color” menyatakan “vertices_line_with_points_color” yang keduanya diinisialisasi dengan “private float vertices_line_with_points[]=null; private float vertices_line_with_points_color[] = null;” dengan step_loop=0.001f; dan memiliki ukuran 2 kali defult size. Nilai 2 tersebut merupakan “array_factor=2.0f” yang digunakan untuk menghidari ukuran array yang dipesan di memory kurang dari array yang dibutuhkan setelah degenerate titik-titiknya. Sehingga lebih baik dibuat lebih yaitu dengan mengalikan 2 kali default size-nya. Script untuk ukuran masing-masing array tersebut adalah “vertices_line_with_points= new float[(int)(array_factor*(x2-x1)/step_loop)*3]; // 3 is number of dimension x,y,z vertices_line_with_points_color= new float[(int)(array_factor*(x2-x1)/step_loop)*4]; // 4 is number of channel color r,g,b,a”
183
Gambar 2.5 Membuat garis dengan GL_POINTS Untuk melakukan “tracking log.v” pada Eclipse, misal ketik “value Math.abs((x2 - x1))” sebagai mana kata yang ada pada Log.v("value Math.abs((x2 - x1)) / step_loop)", "" + (Math.abs((x2 x1)) / step_loop));
Gambar 2.6 Log.v("value Math.abs((..
Gambar 2.7 Tracking log.v (logcat)
184
Source Code 2.3 Code Membuat Garis dengan Titik (Solid) ESRender.java package com.example.imacho.createlinewithpoints; import import import import
android.opengl.GLSurfaceView.Renderer; android.opengl.GLU; javax.microedition.khronos.egl.EGLConfig; javax.microedition.khronos.opengles.GL10;
/** * Created by Imacho on 4/5/2015. */ public class ESRender implements Renderer { private Line_With_Points linewithpoints; // the object to be drawn /** Constructor to set the handed over context */ public ESRender() { this.linewithpoints = new Line_With_Points(); } @Override public void onDrawFrame(GL10 gl) { gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background with white color //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background with black color gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // clear Screen and Depth Buffer // display drawing lines with gl_lines gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glLineWidth(4); // set size of line gl.glEnable(GL10.GL_LINE_SMOOTH); linewithpoints.draw_lines_with_gl_lines(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing create line with points gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glPointSize(3); // set size of points gl.glEnable(GL10.GL_POINT_SMOOTH); linewithpoints.draw_line_with_points_color(gl); gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) {
185
if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { linewithpoints = new Line_With_Points(); } }
MainActivity.java package com.example.imacho.createlinewithpoints; import import import import import import
android.app.Activity; android.opengl.GLSurfaceView; android.os.Bundle; android.view.Menu; android.view.Window; android.view.WindowManager;
/** * Created by Imacho on 4/5/2015. */ public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREE
186
N, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
Line_With_Points.java package com.example.imacho.createlinewithpoints; import import import import import
android.util.Log; java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10;
/** * Created by Imacho on 4/5/2015. */ public class Line_With_Points {
187
private float vertices_line_with_points[]=null; private float vertices_line_with_points_color[] = null; float x,y; float step_loop=0.001f; float x1,y1; float x2,y2; float array_factor=2.0f; private int loop_line,loop_line_color; public Line_With_Points() { // ============ start to generate vertices to create line with point ========================== x1 = -1.0f; y1 = -1.0f; x2= 1.0f; y2 = 1.0f; loop_line=0; loop_line_color=0; vertices_line_with_points=new float[(int)(array_factor*(x2-x1)/step_loop)*3]; // 3 is number of dimension x,y,z vertices_line_with_points_color=new float[(int)(array_factor*(x2-x1)/step_loop)*4]; // 4 is number of channel color r,g,b,a float m = (y2-y1)/(x2-x1); // count gradient for(x=x1;x<=x2;x+=step_loop){ vertices_line_with_points[loop_line] = (float) (x); // as x value vertices_line_with_points[loop_line+1] = (float) (m*(x-x1)+y1); // as y value vertices_line_with_points[loop_line+2]=0; // as z value, z=0 is to assume that the object is on 2D loop_line+=3; //Generate color for each vertex vertices_line_with_points_color[loop_line_color]=(float) Math.abs(Math.sin(x)); // Red Channel vertices_line_with_points_color[loop_line_color+1]=(float) Math.abs(Math.cos((m * (x - x1) + y1))); // Green Channel vertices_line_with_points_color[loop_line_color+2]=0.0f; // Blue Channel vertices_line_with_points_color[loop_line_color+3]=1.0f; // set transparant value (alpha) loop_line_color+=4; } /* x=x1; while(x<=x2){ vertices_line_with_points[loop_line] = (float) (x); // as x value vertices_line_with_points[loop_line+1] =
188
(float) (m*(x-x1)+y1); // as y value vertices_line_with_points[loop_line+2]=0; // as z value, z=0 is to assume that the object is on 2D loop_line+=3; //Generate color for each vertex vertices_line_with_points_color[loop_line_color]=(float) Math.abs(Math.sin(x)); // Red Channel vertices_line_with_points_color[loop_line_color+1]=(float) Math.abs(Math.cos((m*(x-x1)+y1))); // Green Channel vertices_line_with_points_color[loop_line_color+2]=0.0f; // Blue Channel vertices_line_with_points_color[loop_line_color+3]=1.0f; // set transparant value (alpha) loop_line_color+=4; x+=step_loop; } */ // ============= end for generate vertices to create line with point ==================== } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_lines_with_gl_lines(GL10 gl){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the global colour for the line //gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Set/ mapping the colour for each line /*gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 0.0f, 0.0f, 1.0f, 1.0f, // first color (r,g,b,a) 0.0f, 0.0f, 1.0f, 1.0f, // second color (r,g,b,a) 0.0f, 1.0f, 0.0f, 1.0f, // third color (r,g,b,a)
189
0.0f, 1.0f,
0.0f, 1.0f
//
fourth
color (r,g,b,a) }));*/ // Set/ mapping the colour for each line (half) gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 0.0f, 0.0f, 1.0f, 1.0f, // first color (r,g,b,a) 0.0f, 1.0f, 0.0f, 1.0f, // second color (r,g,b,a) 0.0f, 0.0f, 1.0f, 1.0f, // third color (r,g,b,a) 0.0f, 1.0f, 0.0f, 1.0f // fourth color (r,g,b,a) })); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 1.0f, -1.0f, 0.0f, // V3 - third vertex (x,y,z) 1.0f, 1.0f, 0.0f // V4 - fourth vertex })); // Draw the vertices as lines gl.glDrawArrays(GL10.GL_LINES, 0, 4); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_line_with_points_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Lish all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points)); // Set/ mapping the colour for the line each vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points_color)); // Draw the vertices as lines with points : /////////////////////////////////////////// // start draw with exact length of array // /////////////////////////////////////////// gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (loop_line / 3)); // 3 is number of dimension x,y,z
190
// or //gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (loop_line_color / 4)); // 4 is number of channel color r,g,b,a /////////////////////////////////////////// // end draw with exact length of array // /////////////////////////////////////////// /////////////////////////////////////////////// // start draw with not exact length of array // /////////////////////////////////////////////// //gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (Math.abs((x2 - x1)) / step_loop)); // or //gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (vertices_line_with_points.length/(array_factor*3))); // 3 is number of dimension x,y,z // or //gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (vertices_line_with_points_color.length/(array_factor*4))); // 3 is number of dimension x,y,z /////////////////////////////////////////////// // end draw with not exact length of array // /////////////////////////////////////////////// // to tracking log.v // try type like this "tag:value.loop_" without quotes on search "verbose". // or // "value loop_line" without quotes on search "verbose". Log.v("value loop_line", "" + loop_line); Log.v("value loop_line/3", "" + loop_line / 3); Log.v("value loop_line_color", "" + loop_line_color); Log.v("value loop_line_color/4", "" + loop_line_color / 4); Log.v("value Math.abs((x2 - x1)) / step_loop)", "" + (Math.abs((x2 - x1)) / step_loop)); Log.v("value vertices_line_with_points.length", "" + vertices_line_with_points.length); Log.v("value vertices_line_with_points.length/(array_factor*3)", "" + (int) (vertices_line_with_points.length / (array_factor * 3))); Log.v("value vertices_line_with_points_color.length", "" + vertices_line_with_points_color.length); Log.v("value vertices_line_with_points_color.length/(array_factor*4)", "" + (int) (vertices_line_with_points_color.length / (array_factor * 4))); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
191
Source Code 2.4 Code Lain Membuat Garis dengan Titik ESRender.java package com.introduction_to_opengl_es; import import import import
javax.microedition.khronos.egl.EGLConfig; javax.microedition.khronos.opengles.GL10; android.opengl.GLSurfaceView.Renderer; android.opengl.GLU;
public class ESRender implements Renderer { // the object to be drawn private Point_n_Lines_with_Points_Object point_n_linesobject; /** Constructor to set the handed over context */ public ESRender() { this.point_n_linesobject = new Point_n_Lines_with_Points_Object(); } @Override public void onDrawFrame(GL10 gl) { // set background with white color gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // clear Screen and Depth Buffer gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // display drawing points // start freeze state/event to each object gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glPointSize(3); gl.glEnable(GL10.GL_POINT_SMOOTH); point_n_linesobject.draw_points(gl); // end freeze state/event to each object gl.glPopMatrix(); // display drawing create line with points gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); // set size of points gl.glPointSize(3); gl.glEnable(GL10.GL_POINT_SMOOTH); point_n_linesobject.draw_line_with_points_color(gl); gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) // To prevent divide by zero height = 1;
192
float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport // Select projection matrix gl.glMatrixMode(GL10.GL_PROJECTION); // Reset projection matrix gl.glLoadIdentity(); // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); // Select model-view matrix gl.glMatrixMode(GL10.GL_MODELVIEW); // Reset gl.glLoadIdentity(); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { point_n_linesobject = new Point_n_Lines_with_Points_Object(); } }
MainActivity.java package com.introduction_to_opengl_es; import import import import import import
android.opengl.GLSurfaceView; android.os.Bundle; android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance
193
with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Point_n_Lines_Points_Object.java package com.introduction_to_opengl_es; import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10;
import android.util.Log; public class Point_n_Lines_with_Points_Object { private float vertices_line_with_points[]=null; private float vertices_line_with_points_color[] = null; float x,y; float step_loop=0.001f; float x1,y1; float x2,y2; float array_factor=2.0f;
194
private int loop_line,loop_line_color; public Point_n_Lines_with_Points_Object() { // ============ start to generate vertices to create line with point ========================== x1 = -1.0f; y1 = -1.0f; x2= 1.0f; y2 = 1.0f; loop_line=0; loop_line_color=0; vertices_line_with_points=new float[(int)(array_factor*(x2-x1)/step_loop)*3]; // 3 is number of dimension x,y,z vertices_line_with_points_color=new float[(int)(array_factor*(x2-x1)/step_loop)*4]; // 4 is number of channel color r,g,b,a // count gradient float m = (y2-y1)/(x2-x1); for(x=x1;x<=x2;x+=step_loop){ // as x value vertices_line_with_points[loop_line] = (float) (x); // as y value vertices_line_with_points[loop_line+1] = (float) (m*(x-x1)+y1); // as z value, z=0 is to assume that the object is on 2D vertices_line_with_points[loop_line+2]=0; loop_line+=3; //Generate color for each vertex // Red Channel vertices_line_with_points_color[loop_line_color]=(float) Math.abs(Math.sin(x)); // Green Channel vertices_line_with_points_color[loop_line_color+1]=(float ) Math.abs(Math.cos((m*(x-x1)+y1))); // Blue Channel vertices_line_with_points_color[loop_line_color+2]=0.0f; // set transparant value (alpha) vertices_line_with_points_color[loop_line_color+3]=1.0f; loop_line_color+=4; } // ============= end for generate vertices to create line with point ==================== } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length
195
* 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_points(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for all the points gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // List Point to our vertex buffer with manually gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, 0.8f, 0.0f, // V2 1.0f, 0.6f, 0.0f, // V3 1.0f, 0.4f, 0.0f, // V4 1.0f, 0.2f, 0.0f, // V5 1.0f, 0.0f, 0.0f, // V6 1.0f, -0.2f, 0.0f, // V7 1.0f, -0.4f, 0.0f, // V8 1.0f, -0.6f, 0.0f, // V9 1.0f, -0.8f, 0.0f, // V10 1.0f, -1.0f, 0.0f, // V11 0.8f, -1.0f, 0.0f, // V12 0.6f, -1.0f, 0.0f, // V13 0.4f, -1.0f, 0.0f, // V14 0.2f, -1.0f, 0.0f, // V15 0.0f, -1.0f, 0.0f, // V16 -0.2f, -1.0f, 0.0f, // V17 -0.4f, -1.0f, 0.0f, // V18 -0.6f, -1.0f, 0.0f, // V19 -0.7f, -1.0f, 0.0f, // V20 -0.8f, -1.0f, 0.0f, // V21 -1.0f, -1.0f, 0.0f, // V22 })); // Draw the vertices as points gl.glDrawArrays(GL10.GL_POINTS, 0, 22); // 0 is start index, 22 is length of list points //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_line_with_points_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // List all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points));
196
// Set/ mapping the colour for the line each vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_with_points_color)); // Draw the vertices as lines with points : /////////////////////////////////////////// // start draw with exact length of array // /////////////////////////////////////////// gl.glDrawArrays(GL10.GL_POINTS, 0, (int) (loop_line / 3)); // 3 is number of dimension x,y,z /////////////////////////////////////////// // end draw with exact length of array // /////////////////////////////////////////// // to tracking log.v // try type like this "tag:value.loop_" without quotes on search "verbose". Log.v("value loop_line", ""+ loop_line); Log.v("value loop_line/3", ""+ loop_line/3); Log.v("value loop_line_color", ""+ loop_line_color); Log.v("value loop_line_color/4", ""+ loop_line_color/4); Log.v("value Math.abs((x2 - x1)) / step_loop)", ""+ (Math.abs((x2 - x1)) / step_loop)); Log.v("value vertices_line_with_points.length", ""+vertices_line_with_points.length); Log.v("value vertices_line_with_points.length/(array_factor*3)", ""+(int) (vertices_line_with_points.length/(array_factor*3))); Log.v("value vertices_line_with_points_color.length", ""+vertices_line_with_points_color.length); Log.v("value vertices_line_with_points_color.length/(array_factor*4)", ""+(int) (vertices_line_with_points_color.length/(array_factor*4))); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
197
Gambar 2.8 Membuat Garis dan Titik
2.4 Membuat Segitiga & Segiempat Segitiga dibuat dengan “GL_TRIANGLES”. Dan khusus untuk yang segiempat akan dibuat dengan 2 segitiga yang menjadi primitive object-nya. Ada beberapa cara yang dapat digunakan untuk membuat segiempat, diantaranya : a. Menggunakan GL_TRIANGLE_STRIP “// Draw the vertices as rectangle gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0,4); // 4 is number of data vertices_rect” b. Menggunakan GL_TRIANGLES “// Draw the vertices as rectangle gl.glDrawElements(GL10.GL_TRIANGLES, Indices.length, GL10.GL_UNSIGNED_SHORT, makeShortBuffer(Indices));” Indices menyatakan urutan dari index vertex yang akan dikoneksikan untuk membentuk segiempat. Masing-masing cara menggunakan buffer yang sedikit berbeda, untuk GL_TRIANGLE_STRIP menggunakan “makeFloatBuffer” untuk membuffer semua posisi vertice dan warna penyusun objek. Potongan scriptnya sebagai berikut “// List all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, 198
makeFloatBuffer(vertices_rect)); // Set/ mapping the colour for object gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(color_rect));” Sedangkan untuk GL_TRIANGLES menggunakan “makeFloatBuffer” dan sekaligus “makeShortBuffer”, pada cara yang kedua ini “makeShortBuffer” digunakan untuk draw objek segitiga. Spesifikasi kedua metode “public static FloatBuffer makeFloatBuffer(float[] arr)” untuk 4 bytes untuk membangun vertices dan color penyusun objek, “public static ShortBuffer makeShortBuffer(short[] arr)” untuk 2 bytes untuk membangun urutan index dari vertex untuk draw objek sesuai dengan yang diinginkan. “gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise / Counter-clockwise winding. // orientation gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display) remove face with culling.” (x4,y4,z4)
(x1,y1,z1)
(x2,y2,z2)
(x3,y3,z3)
Gambar 2.9 Membuat Segiempat dengan 2 Segitiga Karena segiempat tersebut dibentuk dengan menggunakan dua segitiga, maka efek persilangkan pada sisi miring dari kedua segitiga akan nampak jelas. Untuk menghilangkan efek tersebut, dapat digunakan script di atas. Pada Gambar 2.9, nilai-nilai “Indices” dapat dibentuk dengan cara mengambil index masing-masing vertex penyusun objek. Misal (x1,y1,z1) disimpan pada vertices index 0, (x2,y2,z2) pada index 1, (x3,y3,z3) pada index 2, dan (x4,y4,z4) pada index 3. Misal diketahui nilai vertex-vertex sebagai berikut
199
“private float[] vertices_rect = { -1.0f, -1.0f, 0.0f, // 0. left-bottom-front 1.0f, -1.0f, 0.0f, // 1. right-bottom-front -1.0f, 1.0f, 0.0f, // 2. left-top-front 1.0f, 1.0f, 0.0f // 3. right-top-front };” maka list dari index-index pada tersebut “Indices” adalah “// The order vertices_rect to connect them //(diagonal must crossing) private short[] Indices = { 0, 1, 2, 2, 1, 3 };” Nilai dalam “Indices” tidak selalu sama, tetapi akan menghasilkan urutan yang berbeda jika diketahui urutan index dari nilai vertex-vertex juga berbeda, contoh diketahui “private float[] vertices_rect = { -1.0f, 1.0f, 0.0f, // 0, Top Left -1.0f, -1.0f, 0.0f, // 1, Bottom Left 1.0f, -1.0f, 0.0f, // 2, Bottom Right 1.0f, 1.0f, 0.0f, // 3, Top Right };”
Gambar 2.10 Segitiga dan segiempat
200
maka list dari index-index pada tersebut “Indices” akan benar jika diisi dengan urutan berikut ini “// The order vertices_rect to connect them //(diagonal must crossing) private short[] Indices = { 0, 1, 2, 0, 2, 3 };” Source Code 2.5 Code Membuat Segitiga & Segiempat ESRender.java
package com.example.imacho.createtrianglenrect; import import import import
android.opengl.GLSurfaceView.Renderer; android.opengl.GLU; javax.microedition.khronos.egl.EGLConfig; javax.microedition.khronos.opengles.GL10;
/** * Created by Imacho on 4/5/2015. */ public class ESRender implements Renderer { private Triangle_n_Rectangle triangle_n_rectangle; // the object to be drawn /** Constructor to set the handed over context */ public ESRender() { this.triangle_n_rectangle = new Triangle_n_Rectangle(); } @Override public void onDrawFrame(GL10 gl) { gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background with white color //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background with black color gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // clear Screen and Depth Buffer // display drawing triangle one color /*gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, -2.0f, -5.0f); triangle_n_rectangle.draw_triangle_one_color(gl); gl.glPopMatrix(); // end freeze state/event to each object */ // display drawing triangle three color
201
gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, 0.0f, -5.0f); triangle_n_rectangle.draw_triangle_three_color(gl); gl.glPopMatrix(); // end freeze state/event to each object // display rectangle dengan cara ke-1 gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(2.5f, 0.0f, 0.0f); gl.glTranslatef(0.0f, 0.0f, -5.0f); triangle_n_rectangle.draw_rectangle_cara1(gl); gl.glPopMatrix(); // display rectangle dengan cara ke-2 gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-2.5f, 0.0f, 0.0f); gl.glTranslatef(0.0f, 0.0f, -5.0f); triangle_n_rectangle.draw_rectangle_cara2(gl); gl.glPopMatrix();
} @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { triangle_n_rectangle = new Triangle_n_Rectangle(); }
202
}
MainActivity.java
package com.example.imacho.createtrianglenrect; import import import import import import
android.app.Activity; android.opengl.GLSurfaceView; android.os.Bundle; android.view.Menu; android.view.Window; android.view.WindowManager;
/** * Created by Imacho on 4/5/2015. */ public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_ FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRen-
203
der()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
Triangle_n_Rectangle.java
package com.example.imacho.createtrianglenrect; import import import import import
android.util.Log; java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10; /** * Created by Imacho on 4/5/2015. */ public class Triangle_n_Rectangle {
204
private float vertices_line_with_points[]=null; private float vertices_line_with_points_color[] = null; float x,y; float step_loop=0.001f; float x1,y1; float x2,y2; float array_factor=2.0f; private int loop_line,loop_line_color; private float[] vertices_rect = { -1.0f, -1.0f, 0.0f, // 0. left-bottomfront 1.0f, -1.0f, 0.0f, // 1. right-bottomfront -1.0f, 1.0f, 0.0f, // 2. left-top-front 1.0f, 1.0f, 0.0f // 3. right-top-front }; private float[] color_rect = { // Vertices for color 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f }; // The order vertices_rect to connect them (diagonal must crossing) private short[] Indices = { 0, 1, 2, 2, 1, 3 }; public Triangle_n_Rectangle() { } // Point to our vertex buffer, return buffer holding the vertices // a float is 4 bytes, therefore we multiply the number if // vertices with 4. public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } // short is 2 bytes, therefore we multiply the number if // vertices with 2. public static ShortBuffer makeShortBuffer(short[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 2); bb.order(ByteOrder.nativeOrder()); ShortBuffer sb = bb.asShortBuffer();
205
sb.put(arr); sb.position(0); return sb; } /** The draw method for the primitive object with the GL context */ public void draw_triangle_one_color(GL10 gl){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 second vertex 0.0f, 1.0f, 0.0f // V3 - third vertex (x,y,z) })); // Draw the vertices as triangle gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 3); // set the global colour for wire the triangle gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge triangle gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, 3); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_triangle_three_color(GL10 gl){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 second vertex 0.0f, 1.0f, 0.0f // V3 - third vertex (x,y,z) })); // Set/ mapping the colour for object gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[]{ 1.0f, 0.0f, 0.0f, 1.0f, // first
206
color (r,g,b,a) 0.0f, 1.0f, 0.0f, 1.0f, //
second
color (r,g,b,a) 0.0f, 0.0f, 1.0f, 1.0f //
third col-
or (r,g,b,a) })); // Draw the vertices as triangle gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 3); // set the global colour for wire the triangle gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge triangle gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, 3); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_rectangle_cara1(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise / Counter-clockwise winding. // orientation gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display) / What faces to remove with the face culling. gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the global colour for the triangle //gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // List all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_rect)); // Set/ mapping the colour for object gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(color_rect)); // Draw the vertices as rectangle gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0,4); // 4 is number of data vertices_rect //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); // Disable face culling. gl.glDisable(GL10.GL_CULL_FACE);
207
} public void draw_rectangle_cara2(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise / Counter-clockwise winding. // orientation gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display) / What faces to remove with the face culling. gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the global colour for the triangle //gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Lish all points to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_rect)); // Set/ mapping the colour for object gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(color_rect)); // Draw the vertices as rectangle gl.glDrawElements(GL10.GL_TRIANGLES, Indices.length, GL10.GL_UNSIGNED_SHORT, makeShortBuffer(Indices)); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); // Disable face culling. gl.glDisable(GL10.GL_CULL_FACE); } }
Source Code 2.6 Code Lain Membuat Segitiga Sederhana ESRender.java
package com.example.primitives_project_es; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; //import android.opengl.GLU; import android.opengl.GLSurfaceView.Renderer; import android.opengl.GLU;
208
public class ESRender implements Renderer { // the primitive object to be drawn private PrimitivesObject primitivesobject; private PrimitivesPolarObject primitivespolarobject; float sudut=0.0f; float step_sudut=0.0f; /** Constructor to set the handed over context */ public ESRender() { this.primitivesobject = new PrimitivesObject(); this.primitivespolarobject = new PrimitivesPolarObject(); } @Override public void onDrawFrame(GL10 gl) { // clear Screen and Depth Buffer // set background dgn warna putih gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // Reset the Modelview Matrix gl.glLoadIdentity(); // segitiga dengan gradasi warna gl.glPushMatrix(); gl.glRotatef(-sudut, 0.0f, 0.0f, 1.0f); gl.glTranslatef(0.0f, 0.0f, -6.5f); gl.glRotatef(180, 0.0f, 0.0f, 1.0f); primitivesobject.draw_segitiga(gl); gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override
209
public void onSurfaceCreated(GL10 gl, EGLConfig config) { primitivesobject = new PrimitivesObject(); primitivespolarobject = new PrimitivesPolarObject(); } }
MainActivity.java
package com.example.primitives_project_es; import import import import import import
android.opengl.GLSurfaceView; android.os.Bundle; android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_ FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and // create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main ren-
210
derer with // the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
PrimitivesObject.java
package com.example.primitives_project_es; import import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10; android.opengl.GLES20;
public class PrimitivesObject { private float vertices[] = { -0.5f, -0.5f, 0.0f,
211
// V1 - first vertex // (x,y,z) -0.5f, 0.5f, 0.0f, // V2 0.5f, 0.5f, 0.0f, // V3 0.5f, -0.5f, 0.0f, // V4 -0.5f, -0.5f, 0.0f // V5 }; private float[] vertices_quad = { // Vertices for the square -1.0f, -1.0f, 0.0f, // 0. left-bottom 1.0f, -1.0f, 0.0f, // 1. rightbottom -1.0f, 1.0f, 0.0f, // 2. left-top 1.0f, 1.0f, 0.0f // 3. right-top }; private float vertices_color[] = { 1.0f, 0.0f, 0.0f, 1.0f, // CV1 - first // color // (red,green,blue) 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
1.0f, // CV2 1.0f, // CV3 1.0f, // CV4 1.0f // CV5
}; private float vertices_circle[] = { 0.0f, 0.0f, 0.0f }; private float vertices_circle_color[] = { 0.0f, 0.0f, 0.0f, 0.5f }; private float vertices_line[] = { 0.0f, 0.0f, 0.0f }; private float vertices_line_color[] = { 0.0f, 0.0f, 0.0f, 1.0f }; private int batas_sudut = 360; float jari_jari; float a, b; float x, y; float step = 3.0f, step_line = 0.2f; float x1, y1; float x2, y2; private int loop, loop_color, loop_line, loop_line_color; public PrimitivesObject() { // ============ start to generate vertices to circle // ========================== // Inisialisasi jari_jari = 1.0f; // Titik Pusat a = 0.0f; b = 0.0f;
212
x = a + jari_jari; y = b; loop = 3; loop_color = 4; vertices_circle = new float[(int) (3 * batas_sudut / step) * 3]; vertices_circle_color = new float[(int) (3 * batas_sudut / step) * 4]; for (float teta = 0; teta <= 2 * batas_sudut; teta += step) { vertices_circle[loop] = (float) ((x - a) * Math.cos((teta / 180) * (22 / 7)) - ((y - b) * Math.sin((teta / 180) * (22 / 7))) + a); vertices_circle[loop + 1] = (float) ((x - a) * Math.sin((teta / 180) * (22 / 7)) - ((y - b) * Math.cos((teta / 180) * (22 / 7))) + b); vertices_circle[loop + 2] = 0; loop += 3; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos((teta / 180) * (22 / 7)) - ((y - b) * Math.sin((teta / 180) * (22 / 7))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin((teta / 180) * (22 / 7)) - ((y - b) * Math.cos((teta / 180) * (22 / 7))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; } // ============= end for generate vertices to circle // ==================== // ============ start to generate vertices to line // x1 y1 x2 y2
========================== = -1.0f; = -1.0f; = 1.0f; = 1.0f;
loop_line = 3;
213
loop_line_color = 4; vertices_line = new float[(int) (2 * (x2 - x1) / step_line) * 3]; vertices_line_color = new float[(int) (2 * (x2 - x1) / step_line) * 4]; float m = (y2 - y1) / (x2 - x1); for (x = x1; x <= x2; x += step_line) { vertices_line[loop_line] = (float) (x); vertices_line[loop_line + 1] = (float) (m * (x - x1) + y1); vertices_line[loop_line + 2] = 0; loop_line += 3; // mengenerate warna untuk setiap vertex vertices_line_color[loop_line_color] = (float) (0.5 * x); vertices_line_color[loop_line_color + 1] = (float) (0.5 * m * (x - x1) + y1); vertices_line_color[loop_line_color + 2] = 1.0f; vertices_line_color[loop_line_color + 3] = 1.0f; loop_line_color += 4; } // ============= end for generate vertices to line ==================== } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_points(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the points (pemberian warna untuk titik) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
214
// Point to our vertex buffer (mendata nilai lokasi/posisi titik) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[] { 1.0f, 1.0f, 0.0f, // V1 first vertex (x,y,z) 1.0f, 0.8f, 0.0f, // V2 1.0f, 0.6f, 0.0f, // V3 1.0f, 0.4f, 0.0f, // V4 1.0f, 0.2f, 0.0f, // V5 1.0f, 0.0f, 0.0f, // V6 1.0f, -0.2f, 0.0f, // V7 1.0f, -0.4f, 0.0f, // V8 1.0f, -0.6f, 0.0f, // V9 1.0f, -0.8f, 0.0f, // V10 1.0f, -1.0f, 0.0f, // V11 0.8f, -1.0f, 0.0f, // V12 0.6f, -1.0f, 0.0f, // V13 0.4f, -1.0f, 0.0f, // V14 0.2f, -1.0f, 0.0f, // V15 0.0f, -1.0f, 0.0f, // V16 -0.2f, -1.0f, 0.0f, // V17 -0.4f, -1.0f, 0.0f, // V18 -0.6f, -1.0f, 0.0f, // V19 -0.7f, -1.0f, 0.0f, // V20 -0.8f, -1.0f, 0.0f, // V21 -1.0f, -1.0f, 0.0f, // V22 })); // Draw the vertices as points (menggambar titik-titik) gl.glDrawArrays(GL10.GL_POINTS, 0, 22); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_line(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the line (pemberian warna untuk garis) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer (mendata nilai lokasi/posisi titik yang // menyusun garis) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[] {
215
1.0f, 1.0f, 0.0f, // V1 first vertex (x,y,z) -1.0f, -1.0f, 0.0f, // V2 - second vertex })); // Draw the vertices as lines (menggambar garis dari titik-titik) gl.glDrawArrays(GL10.GL_LINES, 0, 2); /* * gl.glDrawElements(GL10.GL_LINES, 2, GL10.GL_UNSIGNED_SHORT, * makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex * (x,y,z) -1.0f, -1.0f, 0.0f, // V2 second vertex })); */ // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_line_color(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the line (pemberian warna untuk garis) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer (mendata nilai lokasi/posisi titik yang // menyusun garis) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line)); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_color)); // Draw the vertices as lines (menggambar garis dari titik-titik) gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, (int) (2 * (x2 - x1) / step_line)); /* * gl.glDrawElements(GL10.GL_LINES, 2, GL10.GL_UNSIGNED_SHORT, * makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex
216
* (x,y,z) -1.0f, -1.0f, 0.0f, // V2 second vertex })); */ // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the object circle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); // draw circle as filled shape // gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 1, (int) ((int) // 2*batas_sudut/step)); // draw circle contours // gl.glDrawArrays(GL10.GL_LINES, 1, (int) ((int) 2*batas_sudut/step)); // // membuat garis putus-putus pada tepi lingkaran gl.glDrawArrays(GL10.GL_LINES, 1, (int) ((int) 2 * batas_sudut / step)); // gl.glDrawArrays(GL10.GL_LINE_STRIP, 1, (int) ((int) // 2*batas_sudut/step)); // gl.glDrawArrays(GL10.GL_POINTS, 1, (int) ((int) 2*batas_sudut/step)); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
217
// set the colour edge for the object circle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle_color)); // draw circle as filled shape // gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 1, (int) ((int) // 2*batas_sudut/step)); gl.glDrawArrays(GL10.GL_LINE_STRIP, 1, (int) ((int) 2 * batas_sudut / step)); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_kotak(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices)); // Draw the vertices as square gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GL10.GL_TRIANGLES, 2, 3); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
218
} public void draw_segitiga(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[] { -0.5f, -0.5f, 0.0f, // V1 - first vertex (x,y,z) 0.5f, -0.5f, 0.0f, // V2 second vertex 0.0f, 0.5f, 0.0f // V3 third vertex })); // Draw the vertices as triangle gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } // Render the shape quad public void draw_quad(GL10 gl) { // Enable vertex-array and define its buffer gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_quad)); // Draw the primitives from the vertexarray directly gl.glPolygonOffset(0.0f, 1.0f); gl.glScalef(0.5f, 0.5f, 0.5f); gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); // Set the current color (NEW) gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices_quad.length / 3); //gl.glDrawArrays(GL10.GL_TRIANGLES, 0, vertices_quad.length / 3); //gl.glDrawArrays(GL10.GL_LINES, 0, vertices_quad.length / 3);
219
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } }
Gambar 2.11 Membuat Segitiga Sederhana
Source Code 2.7 Code Membuat Segiempat ESRender.java package com.example.primitives_project_es; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; //import android.opengl.GLU; import android.opengl.GLSurfaceView.Renderer; import android.opengl.GLU; public class ESRender implements Renderer { private PrimitivesObject primitivesobject; // the primitive object to be drawn private PrimitivesPolarObject primitivespolarobject; float sudut=0.0f; float step_sudut=0.0f; /** Constructor to set the handed over context */ public ESRender() { this.primitivesobject = new PrimitivesObject(); this.primitivespolarobject = new PrimitivesPolarObject();
220
} @Override public void onDrawFrame(GL10 gl) { // clear Screen and Depth Buffer gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background dgn warna putih //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background dgn warna hitam gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // Reset the Modelview Matrix gl.glLoadIdentity(); // menampilkan persegi dengan gradasi warna gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, 5.0f); primitivesobject.draw_kotak(gl); gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { //primitivesobject = new PrimitivesObject(); primitivesobject = new PrimitivesObject(); primitivespolarobject = new PrimitivesPolarObject();
221
} }
MainActivity.java package com.example.primitives_project_es; import import import import import import
android.opengl.GLSurfaceView; android.os.Bundle; android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and // create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with // the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /**
222
* Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
PrimitivesObject.java package com.example.primitives_project_es; import import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10; android.opengl.GLES20;
public class PrimitivesObject { private float vertices[] = { -0.5f, -0.5f, 0.0f, // V1 - first vertex // (x,y,z) -0.5f, 0.5f, 0.0f, // V2 0.5f, 0.5f, 0.0f, // V3 0.5f, -0.5f, 0.0f, // V4 -0.5f, -0.5f, 0.0f // V5 }; private float[] vertices_quad = { // Vertices for the square -1.0f, -1.0f, 0.0f, // 0. left-bottom 1.0f, -1.0f, 0.0f, // 1. rightbottom -1.0f, 1.0f, 0.0f, // 2. left-top 1.0f, 1.0f, 0.0f // 3. right-top }; private float vertices_color[] = { 1.0f, 0.0f, 0.0f, 1.0f, // CV1 - first
// color
223
// (red,green,blue) 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
1.0f, // CV2 1.0f, // CV3 1.0f, // CV4 1.0f // CV5
}; private float vertices_circle[] = { 0.0f, 0.0f, 0.0f }; private float vertices_circle_color[] = { 0.0f, 0.0f, 0.0f, 0.5f }; private float vertices_line[] = { 0.0f, 0.0f, 0.0f }; private float vertices_line_color[] = { 0.0f, 0.0f, 0.0f, 1.0f }; private int batas_sudut = 360; float jari_jari; float a, b; float x, y; float step = 3.0f, step_line = 0.2f; float x1, y1; float x2, y2; private int loop, loop_color, loop_line, loop_line_color; public PrimitivesObject() { // ============ start to generate vertices to circle // ========================== // Inisialisasi jari_jari = 1.0f; // Titik Pusat a = 0.0f; b = 0.0f; x = a + jari_jari; y = b; loop = 3; loop_color = 4; vertices_circle = new float[(int) (3 * batas_sudut / step) * 3]; vertices_circle_color = new float[(int) (3 * batas_sudut / step) * 4]; for (float teta = 0; teta <= 2 * batas_sudut; teta += step) { vertices_circle[loop] = (float) ((x - a) * Math.cos((teta / 180) * (22 / 7)) - ((y - b) * Math.sin((teta / 180) * (22 / 7))) + a); vertices_circle[loop + 1] = (float) ((x - a) * Math.sin((teta / 180) * (22 / 7)) - ((y - b) *
224
Math.cos((teta / 180) * (22 / 7))) + b); vertices_circle[loop + 2] = 0; loop += 3; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos((teta / 180) * (22 / 7)) - ((y - b) * Math.sin((teta / 180) * (22 / 7))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin((teta / 180) * (22 / 7)) - ((y - b) * Math.cos((teta / 180) * (22 / 7))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; } // ============= end for generate vertices to circle // ==================== // ============ start to generate vertices to line // x1 y1 x2 y2
========================== = -1.0f; = -1.0f; = 1.0f; = 1.0f;
loop_line = 3; loop_line_color = 4; vertices_line = new float[(int) (2 * (x2 - x1) / step_line) * 3]; vertices_line_color = new float[(int) (2 * (x2 - x1) / step_line) * 4]; float m = (y2 - y1) / (x2 - x1); for (x = x1; x <= x2; x += step_line) { vertices_line[loop_line] = (float) (x); vertices_line[loop_line + 1] = (float) (m * (x - x1) + y1); vertices_line[loop_line + 2] = 0; loop_line += 3; // mengenerate warna untuk setiap vertex vertices_line_color[loop_line_color] = (float) (0.5 * x); vertices_line_color[loop_line_color + 1] = (float) (0.5 * m
225
* (x - x1) + y1); vertices_line_color[loop_line_color + 2] = 1.0f; vertices_line_color[loop_line_color + 3] = 1.0f; loop_line_color += 4; } // ============= end for generate vertices to line ==================== } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_points(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the points (pemberian warna untuk titik) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer (mendata nilai lokasi/posisi titik) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[] { 1.0f, 1.0f, 0.0f, // V1 first vertex (x,y,z) 1.0f, 0.8f, 0.0f, // V2 1.0f, 0.6f, 0.0f, // V3 1.0f, 0.4f, 0.0f, // V4 1.0f, 0.2f, 0.0f, // V5 1.0f, 0.0f, 0.0f, // V6 1.0f, -0.2f, 0.0f, // V7 1.0f, -0.4f, 0.0f, // V8 1.0f, -0.6f, 0.0f, // V9 1.0f, -0.8f, 0.0f, // V10 1.0f, -1.0f, 0.0f, // V11 0.8f, 0.6f, 0.4f, 0.2f, 0.0f,
226
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
// // // // //
V12 V13 V14 V15 V16
-0.2f, -0.4f, -0.6f, -0.7f, -0.8f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
// // // // // //
V17 V18 V19 V20 V21 V22
})); // Draw the vertices as points (menggambar titik-titik) gl.glDrawArrays(GL10.GL_POINTS, 0, 22); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_line(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the line (pemberian warna untuk garis) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer (mendata nilai lokasi/posisi titik yang // menyusun garis) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[] { 1.0f, 1.0f, 0.0f, // V1 first vertex (x,y,z) -1.0f, -1.0f, 0.0f, // V2 - second vertex })); // Draw the vertices as lines (menggambar garis dari titik-titik) gl.glDrawArrays(GL10.GL_LINES, 0, 2); /* * gl.glDrawElements(GL10.GL_LINES, 2, GL10.GL_UNSIGNED_SHORT, * makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex * (x,y,z) -1.0f, -1.0f, 0.0f, // V2 second vertex })); */ // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
227
// gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_line_color(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the line (pemberian warna untuk garis) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer (mendata nilai lokasi/posisi titik yang // menyusun garis) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line)); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_line_color)); // Draw the vertices as lines (menggambar garis dari titik-titik) gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, (int) (2 * (x2 - x1) / step_line)); /* * gl.glDrawElements(GL10.GL_LINES, 2, GL10.GL_UNSIGNED_SHORT, * makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex * (x,y,z) -1.0f, -1.0f, 0.0f, // V2 second vertex })); */ // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the object circle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
228
// create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); // draw circle as filled shape // gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 1, (int) ((int) // 2*batas_sudut/step)); // draw circle contours // gl.glDrawArrays(GL10.GL_LINES, 1, (int) ((int) 2*batas_sudut/step)); // // membuat garis putus-putus pada tepi lingkaran gl.glDrawArrays(GL10.GL_LINES, 1, (int) ((int) 2 * batas_sudut / step)); // gl.glDrawArrays(GL10.GL_LINE_STRIP, 1, (int) ((int) // 2*batas_sudut/step)); // gl.glDrawArrays(GL10.GL_POINTS, 1, (int) ((int) 2*batas_sudut/step)); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour edge for the object circle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle_color)); // draw circle as filled shape // gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 1, (int) ((int) // 2*batas_sudut/step)); gl.glDrawArrays(GL10.GL_LINE_STRIP, 1, (int) ((int) 2 * ba-
229
tas_sudut / step)); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_kotak(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices)); // Draw the vertices as square gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GL10.GL_TRIANGLES, 2, 3); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_segitiga(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float[] { -0.5f, -0.5f, 0.0f, // V1 - first vertex (x,y,z) 0.5f, -0.5f, 0.0f, // V2 second vertex 0.0f, 0.5f, 0.0f // V3 third vertex }));
230
// Draw the vertices as triangle gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } // Render the shape quad public void draw_quad(GL10 gl) { // Enable vertex-array and define its buffer gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_quad)); // Draw the primitives from the vertexarray directly gl.glPolygonOffset(0.0f, 1.0f); gl.glScalef(0.5f, 0.5f, 0.5f); gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); // Set the current color (NEW) gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices_quad.length / 3); //gl.glDrawArrays(GL10.GL_TRIANGLES, 0, vertices_quad.length / 3); //gl.glDrawArrays(GL10.GL_LINES, 0, vertices_quad.length / 3);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } }
231
Gambar 2.12 Membuat Segiempat
2.5 Membuat Polygon/Segibanyak Polygon adalah bangun dua dimensi yang memiliki sejumlah sisi dan sudut. Segitiga merupakan bentuk polygon dengan tiga sisi dan sudut. Segiempat merupakan bentuk polygon dengan empat sisi dan empat sudut. Segilima (pentagon) merupakan bentuk polygon dengan lima sisi dan sudut. Segienam (hexagon) merupakan bentuk polygon dengan enam sisi dan sudut. Dan Polygon dengan sisi terbanyak adaalah bangun lingkaran. Berikut adalah potongan script untuk membuat pentagon, “public void draw_polygon3(GL10 gl, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly3)); if(myGL_Wire==false) { // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly3.length/3); }else {
232
// set the global colour for wire the triangle gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly3.length / 3); } //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); }”
Gambar 2.13 Wired-Flat-Color Segilima (Pentagon) Pada Gambar 2.14, objek-objek tersebut merupakan hasil running kode program di file “ESRender.java” yaitu “polygonObject.draw_polygon3_multi_color(gl,true); .. polygonObject.draw_polygon3(gl,false); .. polygonObject.draw_polygon3_multi_color(gl,false);” Jika parameter ke-2 dalam setiap kode program di atas bernilai “true”, maka wire (garis tepian) dari objek akan nampak, tetapi jika “false” maka akan nampak warna dari keseluruhan pada permukaan objek, baik satu warna maupun beberapa warna disetiap vertex atau sudut objek. 233
Gambar 2.14 Polygon statis dan dinamis (n-sisi) Source Code 2.8 Membuat Polygon Statis dan Dinamis ESRender.java package com.example.imacho.createpolygon; import android.opengl.GLSurfaceView.Renderer; import android.opengl.GLU; import android.os.SystemClock; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by Imacho on 4/5/2015. */ public class ESRender implements Renderer { private PolygonObject polygonObject; // the object to be drawn private long prevtime = SystemClock.uptimeMillis(); private int sisi = 3; private int runMode=1; /** Constructor to set the handed over context */ public ESRender() { this.polygonObject = new PolygonObject(); } @Override public void onDrawFrame(GL10 gl) { gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background with white color //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background with black color gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // clear Screen and Depth
234
Buffer // display drawing polygon wire gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-3.5f, -1.0f, -7.0f); polygonObject.draw_polygon3(gl, true); gl.glPopMatrix(); // end freeze state/event to each object // display drawing polygon wire color gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-1.2f, -1.0f, -7.0f); polygonObject.draw_polygon3_multi_color(gl,true); gl.glPopMatrix(); // end freeze state/event to each object // display drawing polygon flat gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(1.2f, -1.0f, -7.0f); polygonObject.draw_polygon3(gl, false); gl.glPopMatrix(); // end freeze state/event to each object // display drawing polygon color gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(3.5f, -1.0f, -7.0f); polygonObject.draw_polygon3_multi_color(gl, false); gl.glPopMatrix(); // end freeze state/event to each object //====================================================== ========= // display drawing polygon dinamis wire gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-3.5f, 1.0f, -7.0f); polygonObject.draw_polygon_dinamis(gl, 10, true); gl.glPopMatrix(); // end freeze state/event to each object // display drawing polygon dinamis wire color gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-1.2f, 1.0f, -7.0f); polygonObject.draw_polygon_dinamis_multi_color(gl, 10, true); gl.glPopMatrix(); // end freeze state/event to each object // display drawing polygon dinamis flat gl.glPushMatrix(); // start freeze
235
state/event to each object gl.glTranslatef(1.2f, 1.0f, -7.0f); polygonObject.draw_polygon_dinamis(gl, 10, false); gl.glPopMatrix(); // end freeze state/event to each object // display drawing polygon dinamis color long curtime = SystemClock.uptimeMillis(); if ((curtime - prevtime) > 2000) { prevtime = curtime; if (runMode==1) { sisi += 1; if (sisi > 20) { runMode=0; } } else{ sisi -= 1; if (sisi == 3) { runMode=1; } } } gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(3.5f, 1.0f, -7.0f); polygonObject.draw_polygon_dinamis_multi_color(gl, sisi, false); gl.glPopMatrix(); // end freeze state/event to each object } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override
236
public void onSurfaceCreated(GL10 gl, EGLConfig config) { polygonObject = new PolygonObject(); } }
MainActivity.java package com.example.imacho.createpolygon; import android.app.Activity; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.view.Menu; import android.view.Window; import android.view.WindowManager; public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface
237
*/ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
PolygonObject.java package com.example.imacho.createpolygon; import import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; java.nio.ShortBuffer; javax.microedition.khronos.opengles.GL10;
/** * Created by Imacho on 4/5/2015. */ public class PolygonObject { private float vertices_poly_dinamis[]=null; private float color_poly_dinamis[]=null; private float[] vertices_poly1 = { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 0.0f, 1.0f, 0.0f // V3 - third vertex (x,y,z) }; private float[] vertices_poly2 = { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 2.0f, 1.0f, 0.0f, // V3 - third vertex (x,y,z) 0.0f, 1.0f, 0.0f // V4 }; private float[] color_poly2 = { // Vertices for color 1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
238
}; private float[] vertices_poly3 = { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 1.0f, 0.0f, 0.0f, // V3 - third vertex (x,y,z) 0.0f, 1.0f, 0.0f, // V4 -1.0f, 0.0f, 0.0f // V5 }; private float[] color_poly3 = { // Vertices for color 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
1.0f, 0.5f, 0.5f, 1.0f, 0.5f
}; public PolygonObject() { } // Point to our vertex buffer, return buffer holding the vertices // a float is 4 bytes, therefore we multiply the number if // vertices with 4. public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } public float[] getAngleArrays(int sides) { float[] angleArray = new float[sides]; float commonAngle = 360.0f/sides; float halfAngle = commonAngle/2.0f; float firstAngle = 360.0f - (90+halfAngle); angleArray[0] = firstAngle; float curAngle = firstAngle; for(int i=1;i<sides;i++) { float newAngle = curAngle - commonAngle; angleArray[i] = newAngle; curAngle = newAngle; } //printArray(angleArray, "angleArray"); return angleArray; }
239
private float getApproxValue(float f) { if (Math.abs(f) < 0.001) { return 0; } return f; } public float[] rotasi_titik2D(float titik_pusat_x, float titik_pusat_y, float jari_jari, float nilai_sudut) { // Titik Pusat dan titik awal float a = titik_pusat_x; float b = titik_pusat_y; float x = a + jari_jari; float y = b; float[] vertices_rotate = new float[3]; vertices_rotate[0] = (float) ((x - a) * getApproxValue((float)Math.cos(Math.toRadians(nilai_sudut))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(nilai_sudut)))) + a); vertices_rotate[1] = (float) ((x - a) * getApproxValue((float)Math.sin(Math.toRadians(nilai_sudut))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(nilai_sudut)))) + b); vertices_rotate[2] = 0; return vertices_rotate; } // short is 2 bytes, therefore we multiply the number if // vertices with 2. public static ShortBuffer makeShortBuffer(short[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 2); bb.order(ByteOrder.nativeOrder()); ShortBuffer sb = bb.asShortBuffer(); sb.put(arr); sb.position(0); return sb; } /** The draw method for the primitive object with the GL context */ public void draw_polygon(GL10 gl){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
240
// Point to our vertex buffer /*gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 0.0f, 1.0f, 0.0f // V3 - third vertex (x,y,z) }));*/ gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly1)); // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly1.length/3); // set the global colour for wire the triangle gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon //gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly1.length/3); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_polygon2(GL10 gl, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer /*gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 2.0f, 1.0f, 0.0f, // V3 - third vertex (x,y,z) 0.0f, 1.0f, 0.0f // V3 - third vertex (x,y,z) }));*/ gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly2)); // Draw the vertices as polygon //gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly2.length/3); // set the global colour for wire the polygon gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon
241
gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly2.length/3); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_polygon2_multi_color(GL10 gl, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer /*gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 2.0f, 1.0f, 0.0f, // V3 - third vertex (x,y,z) 0.0f, 1.0f, 0.0f // V3 - third vertex (x,y,z) }));*/ gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly2)); gl.glColorPointer(4,GL10.GL_FLOAT,0, makeFloatBuffer(color_poly2)); if(myGL_Wire==false) { // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly2.length/3); }else { // set the global colour for wire the polygon gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly2.length / 3); } //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_polygon3(GL10 gl, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer
242
/*gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 1.0f, 0.0f, 0.0f, // V3 - third vertex (x,y,z) 0.0f, 1.0f, 0.0f, // V3 - third vertex (x,y,z) -1.0f, 0.0f, 0.0f // V3 - third vertex (x,y,z) }));*/ gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly3)); if(myGL_Wire==false) { // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly3.length/3); }else { // set the global colour for wire the triangle gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly3.length / 3); } //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_polygon3_multi_color(GL10 gl, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the global colour for the triangle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer /*gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -1.0f, -1.0f, 0.0f, // V1 - first vertex (x,y,z) 1.0f, -1.0f, 0.0f, // V2 - second vertex 1.0f, 0.0f, 0.0f, // V3 - third vertex (x,y,z) 0.0f, 1.0f, 0.0f, // V3 - third vertex (x,y,z) -1.0f, 0.0f, 0.0f // V3 - third vertex (x,y,z) }));*/ gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly3)); gl.glColorPointer(4,GL10.GL_FLOAT,0, makeFloat-
243
Buffer(color_poly3)); if(myGL_Wire==false) { // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly3.length/3); }else { // set the global colour for wire the triangle gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly3.length / 3); } //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_polygon_dinamis(GL10 gl, int sisi, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the global colour for the polygon dinamis gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // get sudut polygon dengan sides=sisi float [] ArraySudut=new float[sisi]; ArraySudut=getAngleArrays(sisi); // init nilai x,y,z float [] ArrayNilaiXYZ=new float[sisi]; float sudutTemp; int loop=0; // set ukuran dari vertices_poly_dinamis = new float[sisi * 3]; vertices_poly_dinamis = new float[sisi * 3]; for(int i=1;i<=sisi;i++){ // get sudut ke-i sudutTemp=ArraySudut[i-1]; // transformasi titik ArrayNilaiXYZ=rotasi_titik2D(0.0f, 0.0f, 1.0f, sudutTemp); vertices_poly_dinamis[loop]=ArrayNilaiXYZ[0]; vertices_poly_dinamis[loop+1]=ArrayNilaiXYZ[1]; vertices_poly_dinamis[loop+2]=ArrayNilaiXYZ[2]; loop+=3; } gl.glVertexPointer(3, GL10.GL_FLOAT, 0, make-
244
FloatBuffer(vertices_poly_dinamis)); if(myGL_Wire==false) { // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly_dinamis.length/3); }else { // set the global colour for wire the polygon dinamis gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly_dinamis.length / 3); } //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_polygon_dinamis_multi_color(GL10 gl, int sisi, boolean myGL_Wire){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the global colour for the polygon dinamis //gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // init titik pusat dan jari-jari float titik_pusat_x=0.0f; float titik_pusat_y=0.0f; float jari_jari=1.0f; // get sudut polygon dengan sides=sisi float [] ArraySudut=new float[sisi]; ArraySudut=getAngleArrays(sisi); // init nilai x,y,z float [] ArrayNilaiXYZ=new float[sisi]; float sudutTemp; int loop=0; int loop_color=0; // set ukuran dari vertices_poly_dinamis = new float[sisi * 3]; vertices_poly_dinamis = new float[sisi * 3]; // set ukuran dari color_poly_dinamis = new float[sisi * 4]; color_poly_dinamis = new float[sisi * 4]; for(int i=1;i<=sisi;i++){ // get sudut ke-i sudutTemp=ArraySudut[i-1]; // transformasi titik ArrayNilaiXYZ=rotasi_titik2D(titik_pusat_x, titik_pusat_y, jari_jari, sudutTemp);
245
// set nilai x, y, z dari polygon vertices_poly_dinamis[loop]=ArrayNilaiXYZ[0]; vertices_poly_dinamis[loop+1]=ArrayNilaiXYZ[1]; vertices_poly_dinamis[loop+2]=ArrayNilaiXYZ[2]; loop+=3; // set nilai warna setiap vertex (x,y,z) --> (r,g,b,a) float a = titik_pusat_x; float b = titik_pusat_y; float x = a + jari_jari; float y = b; color_poly_dinamis[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(sudutTemp)) - ((y - b) * Math.sin(Math.toRadians(sudutTemp))) + a); color_poly_dinamis[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(sudutTemp)) - ((y - b) * Math.cos(Math.toRadians(sudutTemp))) + b); color_poly_dinamis[loop_color + 2] = 0.5f; color_poly_dinamis[loop_color + 3] = 0.5f; loop_color += 4; } gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_poly_dinamis)); gl.glColorPointer(4,GL10.GL_FLOAT,0, makeFloatBuffer(color_poly_dinamis)); if(myGL_Wire==false) { // Draw the vertices as polygon gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, vertices_poly_dinamis.length/3); }else { // set the global colour for wire the polygon dinamis //gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Draw the wire as edge polygon gl.glDrawArrays(GL10.GL_LINE_LOOP, 0, vertices_poly_dinamis.length / 3); } //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
246
AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/androi d" package="com.example.imacho.createpolygon" >
2.6 Membuat Lingkaran Lingkaran merupakan bangun 2D yang memiliki titik pusat (a,b) dan jari-jari (r). Bangun tersebut dapat dibentuk dengan cara merotasi titik pada koordinat (a+r,b) mulai dari sudut 0 sampai 360 derajat. y
(a,b)
(0,0)
(a+r,b)
x
Gambar 2.15 Ilustrasi membuat Lingkaran 247
Ilustrasi dalam membuat lingkaran dapat digunakan sebagai dasar untuk membuat objek visual bola. Bola secara teori sudah dapat dikatakan sebagai objek yang komplek, sehingga codenya tidak dimasukkan pada bab Primitive Object. Pada beberapa bab berikutnya akan diberikan source code Bola secara lengkap. Langkah pertama dalam membuat Bola dengan mengenerate titik-titik dari sudut 0o sampai 180o secara vertikal, mulai dari ujung atas sampai ujung bawah (top-down) atau sebaliknya dengan step atau interval tertentu (latitude). Kemudian setiap titik tersebut akan menjadi titik awal untuk membentuk lingkaran, yang digerakkan secara horizontal, mulai dari sudut 0o sampai 360o dengan step atau interval tertentu (azimuth). y
x
z
Gambar 2.16 Ilustrasi Membuat Bola Kembali lagi pada lingkaran, rumus untuk merotasi titik (a+r,b) menggunakan konsep transformasi geometri dengan inisialisasi jari_jari = 1.0f; titik pusat lingkaran (a = 0.0f;, b = 0.0f;) dan titik awal (x,y) = (x = a + jari_jari;, y = b;) step = 3.0f;, yaitu sebagai berikut “for (float teta = batas_sudut_lower; teta <= batas_sudut_upper+step; teta += step) { vertices_circle[loop] = (float) ((x - a)* getApproxValue((float)Math.cos(Math.toRadians(teta)))((y - b) *getApproxValue((float)Math.sin(Math.toRadians(teta)))) 248
+ a); vertices_circle[loop + 1] = (float) ((x - a)* getApproxValue((float)Math.sin(Math.toRadians(teta)))((y - b)*getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; }” Kode program untuk mewarnai bagian dalam lingkaran dapat menggunakan inisialisasi loop_color = 0; “ …. vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(teta)) - ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; ” Kedua potongan kode di atas menggunakan penghitungan banyaknya titik dan juga warnanya untuk menentukan alokasi panjang array berdasarkan nilai sesilih batas sudut dan step-nya. “ ….. byk_vertices=(((int) batas_sudut_lower)/ step))+1);
Math.round((batas_sudut_upper-
” Hasil running program menampilkan beberapa macam dari lingkaran, mulai dari yang hanya satu warna di bagian tepiannya, bahkan sampai yang memiliki gradasi warna.
249
Gambar 2.17 Membuat Lingkaran Flat dan Gradasi
Gambar 2.18 Membuat Lingkaran Flat dan Gradasi dinamis Source Code 2.9 Code Membuat Lingkaran Gradasi & Dinamis ESRender.java package com.example.imacho.createcircle; import android.opengl.GLSurfaceView.Renderer; import android.opengl.GLU; import android.os.SystemClock; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by Imacho on 4/5/2015. */ public class ESRender implements Renderer {
250
private Circle circle; // the object to be drawn private long prevtime = SystemClock.uptimeMillis(); private float sudut_max = 0.0f; private int runMode=1; /** Constructor to set the handed over context */ public ESRender() { this.circle = new Circle(); } @Override public void onDrawFrame(GL10 gl) { gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background with white color //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background with black color gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // clear Screen and Depth Buffer // display drawing polygon dinamis color long curtime = SystemClock.uptimeMillis(); if ((curtime - prevtime) > 1000.0f) { prevtime = curtime; if (runMode==1) { sudut_max += 10; if (sudut_max == 360.0f) { runMode=0; } } else{ sudut_max -= 10; if (sudut_max == 0) { runMode=1; } } } // display drawing circle gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-3.5f, 1.5f, -7.0f); circle.draw_circle_fraction(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing circle fraction with no fill function sudut_min dan sudut_max gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-3.5f, -1.5f, -7.0f); circle.draw_circle_fraction_one_color_with_nofill_functi on(gl,0,sudut_max);
251
gl.glPopMatrix(); to each object
// end freeze state/event
// display drawing circle one color gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-1.2f, 1.5f, -7.0f); circle.draw_circle_one_color(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing circle with no fill function sudut_min dan sudut_max gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(-1.2f, -1.5f, -7.0f); circle.draw_circle_one_color_with_nofill_function(gl,0,s udut_max); gl.glPopMatrix(); // end freeze state/event to each object // display drawing circle color gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(1.2f, 1.5f, -7.0f); circle.draw_circle_color(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing circle with no fill function sudut_min dan sudut_max gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(1.2f, -1.5f, -7.0f); circle.draw_circle_color_with_nofill_function(gl,0,sudut _max); gl.glPopMatrix(); // end freeze state/event to each object // display drawing circle color2 gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(3.5f, 1.5f, -7.0f); circle.draw_circle_dinamic_color_fill(gl); gl.glPopMatrix(); // end freeze state/event to each object // display drawing circle with function sudut_min dan sudut_max center gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(3.5f, -1.5f, -7.0f); circle.draw_circle_color_with_fill_function_center(gl,0, sudut_max); gl.glPopMatrix(); // end freeze state/event
252
to each object // display drawing circle with function sudut_min dan sudut_max gl.glPushMatrix(); // start freeze state/event to each object gl.glTranslatef(0.0f, 0.0f, -7.0f); gl.glScalef(0.5f,0.5f,0.5f); circle.draw_circle_color_with_fill_function(gl,0,sudut_m ax); gl.glPopMatrix(); // end freeze state/event to each object } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { circle = new Circle(); } }
MainActivity.java package com.example.imacho.createcircle; import import import import import import
android.app.Activity; android.opengl.GLSurfaceView; android.os.Bundle; android.view.Menu; android.view.Window; android.view.WindowManager;
253
/** * Created by Imacho on 4/5/2015. */ public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflat-
254
er().inflate(R.menu.menu_main, menu); return true; } }
Circle.java package com.example.imacho.createcircle; import android.util.Log; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * Created by Imacho on 4/12/2015. */ public class Circle { private float vertices[] = { -0.5f, -0.5f, 0.0f, // V1 - first vertex // (x,y,z) -0.5f, 0.5f, 0.0f, // V2 0.5f, 0.5f, 0.0f, // V3 0.5f, -0.5f, 0.0f, // V4 -0.5f, -0.5f, 0.0f // V5 }; private float[] vertices_quad = { // Vertices for the square -1.0f, -1.0f, 0.0f, // 0. left-bottom 1.0f, -1.0f, 0.0f, // 1. right-bottom -1.0f, 1.0f, 0.0f, // 2. left-top 1.0f, 1.0f, 0.0f // 3. right-top }; private float vertices_color[] = { 1.0f, 0.0f, 0.0f, 1.0f, // CV1 - first // color // (red,green,blue) 0.0f, 1.0f, 0.0f, 1.0f, // CV2 0.0f, 0.0f, 1.0f, 1.0f, // CV3 0.0f, 1.0f, 0.0f, 1.0f, // CV4 1.0f, 0.0f, 0.0f, 1.0f // CV5 }; //private float vertices_circle[] = { 0.0f, 0.0f, 0.0f }; //private float vertices_circle_color[] = { 0.0f, 0.0f, 0.0f, 0.5f }; private float vertices_circle[] = null; private float vertices_circle_color[] = null; private float batas_sudut_lower=0.0f,batas_sudut_upper = 360.0f;
255
float jari_jari; float a, b; float x, y; private int loop, loop_color; float step; int byk_vertices,byk_vertices1; // menyatakan banyaknya titik yang di-generate int realloop; private float getApproxValue(float f) { if (Math.abs(f) < 0.001) { return 0; } return f; } public Circle() { // ============ start to generate vertices to circle // ========================== // Inisialisasi jari_jari = 1.0f; // Titik Pusat a = 0.0f; b = 0.0f; x = a + jari_jari; y = b; //step = 1.0f; step = 3.0f; byk_vertices1=(int) (((batas_sudut_upperbatas_sudut_lower)+step)/ step); //byk_vertices=(((int) Math.floor((batas_sudut_upper-batas_sudut_lower)/ step))+1); // 4.7/0.1 = 46.9999 ?? byk_vertices=(((int) Math.round((batas_sudut_upper-batas_sudut_lower)/ step))+1);
loop = 0; loop_color = 0; realloop=0; // menambah nilai +1 untuk byk_vertices untuk menghindari pemesanan memori yang kurang vertices_circle = new float[(byk_vertices+1) * 3]; vertices_circle_color = new float[(byk_vertices+1) * 4]; // dengan menggunakan while /*float teta = batas_sudut_lower; while(teta <= batas_sudut_upper+step){ // +step untuk batas_sudut_upper, untuk mengatasi looping yang kurang pada while dikarenakan bug pada nilai
256
update tetanya karena float dan double android studio tidak stabil vertices_circle[loop] = (float) ((x - a) * getApproxValue((float)Math.cos(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(teta)))) + a); vertices_circle[loop + 1] = (float) ((x a) * getApproxValue((float)Math.sin(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; realloop=realloop+1; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(teta)) - ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; teta += step; }*/ // dengan for for (float teta = batas_sudut_lower; teta <= batas_sudut_upper+step; teta += step) { vertices_circle[loop] = (float) ((x - a) * getApproxValue((float)Math.cos(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(teta)))) + a); vertices_circle[loop + 1] = (float) ((x a) * getApproxValue((float)Math.sin(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; realloop=realloop+1; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a)
257
* Math.cos(Math.toRadians(teta)) - ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; } // ============= end for generate vertices to circle // ==================== } public float[] create_circle(float fntitik_pusat_x, float fntitik_pusat_y, float fnjari_jari, float fnbatas_sudut_lower,float fnbatas_sudut_upper, float fnstep) { // Titik Pusat dan titik awal float fna = fntitik_pusat_x; float fnb = fntitik_pusat_y; float fnx = fna + fnjari_jari; float fny = fnb; //int byk_vertices1=(int) (((batas_sudut_upper-batas_sudut_lower)+step)/ step); //byk_vertices=(((int) Math.floor((batas_sudut_upper-batas_sudut_lower)/ step))+1); // 4.7/0.1 = 46.9999 ?? int fnbyk_vertices=(((int) Math.round((fnbatas_sudut_upper-fnbatas_sudut_lower)/ fnstep))+1); int fnloop = 0; int fnloop_color = 0; int fnrealloop=0; // menambah nilai +1 untuk byk_vertices untuk menghindari pemesanan memori yang kurang float[] fnvertices_circle = new float[(fnbyk_vertices+1) * 3]; float[] fnvertices_circle_color = new float[(fnbyk_vertices+1) * 4]; // dengan menggunakan while /*float teta = batas_sudut_lower; while(teta <= batas_sudut_upper+step){ // +step untuk batas_sudut_upper, untuk mengatasi looping yang kurang pada while dikarenakan bug pada nilai update tetanya karena float dan double android studio tidak stabil vertices_circle[loop] = (float) ((x - a)
258
* getApproxValue((float)Math.cos(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(teta)))) + a); vertices_circle[loop + 1] = (float) ((x a) * getApproxValue((float)Math.sin(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; realloop=realloop+1; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(teta)) - ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; teta += step; }*/ // dengan for for (float fnteta = fnbatas_sudut_lower; fnteta <= fnbatas_sudut_upper+fnstep; fnteta += fnstep) { fnvertices_circle[fnloop] = (float) ((fnx - fna) * getApproxValue((float)Math.cos(Math.toRadians(fnteta))) - ((fny - fnb) * getApproxValue((float)Math.sin(Math.toRadians(fnteta)))) + fna); fnvertices_circle[fnloop + 1] = (float) ((fnx - fna) * getApproxValue((float)Math.sin(Math.toRadians(fnteta))) - ((fny - fnb) * getApproxValue((float)Math.cos(Math.toRadians(fnteta)))) + fnb); fnvertices_circle[fnloop + 2] = 0; fnloop += 3; fnrealloop=fnrealloop+1; } return fnvertices_circle;
259
} public float[] create_circle_color(float fntitik_pusat_x, float fntitik_pusat_y, float fnjari_jari, float fnbatas_sudut_lower,float fnbatas_sudut_upper, float fnstep) { // Titik Pusat dan titik awal float fna = fntitik_pusat_x; float fnb = fntitik_pusat_y; float fnx = fna + fnjari_jari; float fny = fnb; //int byk_vertices1=(int) (((batas_sudut_upper-batas_sudut_lower)+step)/ step); //byk_vertices=(((int) Math.floor((batas_sudut_upper-batas_sudut_lower)/ step))+1); // 4.7/0.1 = 46.9999 ?? int fnbyk_vertices=(((int) Math.round((fnbatas_sudut_upper-fnbatas_sudut_lower)/ fnstep))+1); //int fnloop = 0; int fnloop_color = 0; //int fnrealloop=0; // menambah nilai +1 untuk byk_vertices untuk menghindari pemesanan memori yang kurang //float[] fnvertices_circle = new float[(fnbyk_vertices+1) * 3]; float[] fnvertices_circle_color = new float[(fnbyk_vertices+1) * 4]; // dengan menggunakan while /*float teta = batas_sudut_lower; while(teta <= batas_sudut_upper+step){ // +step untuk batas_sudut_upper, untuk mengatasi looping yang kurang pada while dikarenakan bug pada nilai update tetanya karena float dan double android studio tidak stabil vertices_circle[loop] = (float) ((x - a) * getApproxValue((float)Math.cos(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(teta)))) + a); vertices_circle[loop + 1] = (float) ((x a) * getApproxValue((float)Math.sin(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; realloop=realloop+1; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(teta))
260
- ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; teta += step; }*/ // dengan for for (float fnteta = fnbatas_sudut_lower; fnteta <= fnbatas_sudut_upper+fnstep; fnteta += fnstep) { // mengenerate warna untuk setiap vertex fnvertices_circle_color[fnloop_color] = (float) ((fnx - fna) * Math.cos(Math.toRadians(fnteta)) - ((fny - fnb) * Math.sin(Math.toRadians(fnteta))) + fna); fnvertices_circle_color[fnloop_color + 1] = (float) ((fnx - fna) * Math.sin(Math.toRadians(fnteta)) - ((fny - fnb) * Math.cos(Math.toRadians(fnteta))) + fnb); fnvertices_circle_color[fnloop_color + 2] = 0.5f; fnvertices_circle_color[fnloop_color + 3] = 0.5f; fnloop_color += 4; } return fnvertices_circle_color; } public float[] create_circle_center(float fntitik_pusat_x, float fntitik_pusat_y, float fnjari_jari, float fnbatas_sudut_lower,float fnbatas_sudut_upper, float fnstep) { // Titik Pusat dan titik awal float fna = fntitik_pusat_x; float fnb = fntitik_pusat_y; float fnx = fna + fnjari_jari; float fny = fnb; //int byk_vertices1=(int) (((batas_sudut_upper-batas_sudut_lower)+step)/ step); //byk_vertices=(((int)
261
Math.floor((batas_sudut_upper-batas_sudut_lower)/ step))+1); // 4.7/0.1 = 46.9999 ?? int fnbyk_vertices=(((int) Math.round((fnbatas_sudut_upper-fnbatas_sudut_lower)/ fnstep))+1); //int fnloop = 0; int fnloop = 3; // dimulai dengan 3, karena terdapat inisialisasi vertex awal fnvertices_circle[] = {0.0f,0.0f,0.0f}; // yang membutuhkan 3 lokasi // karena fnloop = 3, maka fnbyk_vertices=fnbyk_vertices+1; fnbyk_vertices=fnbyk_vertices+1; //int fnloop_color = 0; int fnrealloop=0; float fnvertices_circle[] = {0.0f,0.0f,0.0f}; // menambah nilai +1 untuk byk_vertices untuk menghindari pemesanan memori yang kurang //float[] fnvertices_circle = new float[(fnbyk_vertices+1) * 3]; fnvertices_circle = new float[(fnbyk_vertices+1) * 3];
// dengan menggunakan while /*float teta = batas_sudut_lower; while(teta <= batas_sudut_upper+step){ // +step untuk batas_sudut_upper, untuk mengatasi looping yang kurang pada while dikarenakan bug pada nilai update tetanya karena float dan double android studio tidak stabil vertices_circle[loop] = (float) ((x - a) * getApproxValue((float)Math.cos(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(teta)))) + a); vertices_circle[loop + 1] = (float) ((x a) * getApproxValue((float)Math.sin(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; realloop=realloop+1; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(teta)) - ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] =
262
(float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f; vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; teta += step; }*/ // dengan for for (float fnteta = fnbatas_sudut_lower; fnteta <= fnbatas_sudut_upper+fnstep; fnteta += fnstep) { fnvertices_circle[fnloop] = (float) ((fnx - fna) * getApproxValue((float)Math.cos(Math.toRadians(fnteta))) - ((fny - fnb) * getApproxValue((float)Math.sin(Math.toRadians(fnteta)))) + fna); fnvertices_circle[fnloop + 1] = (float) ((fnx - fna) * getApproxValue((float)Math.sin(Math.toRadians(fnteta))) - ((fny - fnb) * getApproxValue((float)Math.cos(Math.toRadians(fnteta)))) + fnb); fnvertices_circle[fnloop + 2] = 0; fnloop += 3; fnrealloop=fnrealloop+1; } return fnvertices_circle; } public float[] create_circle_color_center(float fntitik_pusat_x, float fntitik_pusat_y, float fnjari_jari, float fnbatas_sudut_lower,float fnbatas_sudut_upper, float fnstep) { // Titik Pusat dan titik awal float fna = fntitik_pusat_x; float fnb = fntitik_pusat_y; float fnx = fna + fnjari_jari; float fny = fnb; //int byk_vertices1=(int) (((batas_sudut_upper-batas_sudut_lower)+step)/ step); //byk_vertices=(((int) Math.floor((batas_sudut_upper-batas_sudut_lower)/ step))+1); // 4.7/0.1 = 46.9999 ?? int fnbyk_vertices=(((int) Math.round((fnbatas_sudut_upper-fnbatas_sudut_lower)/
263
fnstep))+1); int fnloop_color = 4; // dimulai dengan 4, karena terdapat inisialisasi color awal fnvertices_circle_color[] = {0.0f,0.0f,0.0f,0.0f}; // yang membutuhkan 4 lokasi, dengan warna dibuat transparan (alpha=0.0f) // karena fnloop_color = 4, maka fnbyk_vertices=fnbyk_vertices+1; fnbyk_vertices=fnbyk_vertices+1; float fnvertices_circle_color[] = {0.0f,0.0f,0.0f,0.0f}; // menambah nilai +1 untuk byk_vertices untuk menghindari pemesanan memori yang kurang //float[] fnvertices_circle_color = new float[(fnbyk_vertices+1) * 4]; fnvertices_circle_color = new float[(fnbyk_vertices+1) * 4];
// dengan menggunakan while /*float teta = batas_sudut_lower; while(teta <= batas_sudut_upper+step){ // +step untuk batas_sudut_upper, untuk mengatasi looping yang kurang pada while dikarenakan bug pada nilai update tetanya karena float dan double android studio tidak stabil vertices_circle[loop] = (float) ((x - a) * getApproxValue((float)Math.cos(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.sin(Math.toRadians(teta)))) + a); vertices_circle[loop + 1] = (float) ((x a) * getApproxValue((float)Math.sin(Math.toRadians(teta))) - ((y - b) * getApproxValue((float)Math.cos(Math.toRadians(teta)))) + b); vertices_circle[loop + 2] = 0; loop += 3; realloop=realloop+1; // mengenerate warna untuk setiap vertex vertices_circle_color[loop_color] = (float) ((x - a) * Math.cos(Math.toRadians(teta)) - ((y - b) * Math.sin(Math.toRadians(teta))) + a); vertices_circle_color[loop_color + 1] = (float) ((x - a) * Math.sin(Math.toRadians(teta)) - ((y - b) * Math.cos(Math.toRadians(teta))) + b); vertices_circle_color[loop_color + 2] = 0.5f;
264
vertices_circle_color[loop_color + 3] = 0.5f; loop_color += 4; teta += step; }*/ // dengan for for (float fnteta = fnbatas_sudut_lower; fnteta <= fnbatas_sudut_upper+fnstep; fnteta += fnstep) { // mengenerate warna untuk setiap vertex fnvertices_circle_color[fnloop_color] = (float) ((fnx - fna) * Math.cos(Math.toRadians(fnteta)) - ((fny - fnb) * Math.sin(Math.toRadians(fnteta))) + fna); fnvertices_circle_color[fnloop_color + 1] = (float) ((fnx - fna) * Math.sin(Math.toRadians(fnteta)) - ((fny - fnb) * Math.cos(Math.toRadians(fnteta))) + fnb); fnvertices_circle_color[fnloop_color + 2] = 0.5f; fnvertices_circle_color[fnloop_color + 3] = 0.5f; fnloop_color += 4; } return fnvertices_circle_color; } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr) { ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_circle_fraction(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the colour for the object circle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle));
265
// draw circle contours gl.glDrawArrays(GL10.GL_LINES, 0, byk_vertices); /*Log.v("value loop", "" + loop); Log.v("value realloop", "" + realloop); Log.v("value loop/3", "" + loop / 3); Log.v("value loop/3", "" + (int) (loop / 3)); Log.v("value byk_vertices1", "" + byk_vertices1); Log.v("value byk_vertices", "" + byk_vertices);*/ //Log.v("value vertices_circle.length", "" + vertices_circle.length); //Log.v("value batas_sudut / step", "" + (int) Math.ceil(batas_sudut_upper /step)); //Log.v("value byk_vertices dgn Ceil", "" + (int) Math.ceil((((batas_sudut_upperbatas_sudut_lower)+step)/ step))); /*Log.v("value byk_vertices dgn Floor", "" + (((int) Math.floor((batas_sudut_upperbatas_sudut_lower)/ step))+1) ); Log.v("value batas_sudut_upperbatas_sudut_lower", "" + (batas_sudut_upperbatas_sudut_lower)); Log.v("value batas_sudut_upperbatas_sudut_lower/ step", "" + (batas_sudut_upperbatas_sudut_lower)/ step); Log.v("value batas_sudut_upperbatas_sudut_lower/ step ceil ", "" + Math.ceil((batas_sudut_upperbatas_sudut_lower)/step)); Log.v("value batas_sudut_upperbatas_sudut_lower/ step floor", "" + Math.ceil((batas_sudut_upperbatas_sudut_lower)/step)); Log.v("value batas_sudut_upperbatas_sudut_lower/ step round", "" + Math.round((batas_sudut_upperbatas_sudut_lower)/step));*/ /*if(0.9f<=1.0f){ //Log.v("value 0.9f<=1.0f", "" + "True"); }else{ //Log.v("value 0.9f<=1.0f", "" + "False"); } float aa=0.1f; float bb=1.0f; float cc=0.1f; while(aa<=bb+cc){ Log.v("value "+aa+"<="+ bb +"", "" + aa); aa=aa+cc; Log.v("value -----------"+aa+"<="+ bb +"", "" + aa);
266
} Log.v("value 0.6f+0.1f", "" + (0.6f+0.1f)); Log.v("value 0.6+0.1", "" + (0.6+0.1));*/
/*Log.v("value round 9.0", "" + Math.round(9.0f)); Log.v("value round 9.1", "" + Math.round(9.1f)); Log.v("value round 9.2", "" + Math.round(9.2f)); Log.v("value round 9.3", "" + Math.round(9.3f)); Log.v("value round 9.4", "" + Math.round(9.4f)); Log.v("value round 9.5", "" + Math.round(9.5f)); Log.v("value round 9.6", "" + Math.round(9.6f)); Log.v("value round 9.7", "" + Math.round(9.7f)); Log.v("value round 9.8", "" + Math.round(9.8f)); Log.v("value round 9.9", "" + Math.round(9.9f));*/ /*Log.v("value step", "" + step);*/ //Log.v("value (int) (batas_sudut / step) * 3", "" + (int) (batas_sudut_upper / step) * 3); /*Log.v("value ceil 2.5 ", "" + Math.ceil(2.5)); Log.v("value int ceil 2.5 ", "" + (int) Math.ceil(2.5)); Log.v("value floor ", "" + Math.floor(2.5)); Log.v("value int ", "" + (int) (2.5)); Log.v("value ceil 5.0 ", "" + Math.ceil(5.0)); Log.v("value int ceil 2.5 ", "" + (int) Math.ceil(5.0)); Log.v("value floor ", "" + Math.floor(5.0)); Log.v("value int ", "" + (int) (5.0));*/ // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_circle_fraction_one_color_with_nofill_function(G L10 gl, float sudut_min, float sudut_max) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the colour edge for the object circle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle(0.0f, 0.0f, 1.0f,sudut_min,sudut_max, 3.0f)));
267
// draw circle as filled shape gl.glDrawArrays(GL10.GL_LINES, 0,(int)(create_circle(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 3.0f).length/3)-1); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_circle_one_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the colour for the object circle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); // draw circle contours gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, byk_vertices); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_circle_one_color_with_nofill_function(GL10 gl, float sudut_min, float sudut_max) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the colour edge for the object circle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle(0.0f, 0.0f, 1.0f,sudut_min,sudut_max, 0.1f))); // draw circle as filled shape gl.glDrawArrays(GL10.GL_LINE_STRIP, 0,(int)(create_circle(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f).length/3)-1); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_circle_color(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour edge for the object circle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
268
// create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle_color)); // draw circle as filled shape gl.glDrawArrays(GL10.GL_LINE_STRIP, 0,byk_vertices); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle_color_with_nofill_function(GL10 gl, float sudut_min, float sudut_max) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle(0.0f, 0.0f, 1.0f,sudut_min,sudut_max, 0.1f))); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle_color(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f))); // draw circle as filled shape gl.glDrawArrays(GL10.GL_LINE_STRIP, 0,(int)(create_circle(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f).length/3)-1); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle_dinamic_color_fill(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour edge for the object circle gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle));
269
// memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle_color)); // draw circle as filled shape gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0,byk_vertices); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle_color_with_fill_function(GL10 gl, float sudut_min, float sudut_max) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle(0.0f, 0.0f, 1.0f,sudut_min,sudut_max, 0.1f))); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle_color(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f))); // draw circle as filled shape gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0,(int)(create_circle(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f).length/3)-1); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle_color_with_fill_function_center(GL10 gl, float sudut_min, float sudut_max) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(create_circle_center(0.0f, 0.0f, 1.0f,sudut_min,sudut_max, 0.1f))); // memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuff-
270
er(create_circle_color_center(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f))); // draw circle as filled shape gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0,(int)(create_circle_center(0.0f, 0.0f, 1.0f, sudut_min,sudut_max, 0.1f).length/3)-1); // Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); }
}
AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/androi d" package="com.example.imacho.createcircle" >
271
Source Code 2.10 Code Lain Membuat Lingkaran Sederhana GlRenderer.java package com.example.opengl_introduction; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLU; import android.opengl.GLSurfaceView.Renderer;
public class GlRenderer implements Renderer { private Object object; // the triangle to be drawn /** Constructor to set the handed over context */ public GlRenderer() { this.object = new Object(); } @Override public void onDrawFrame(GL10 gl) { // clear Screen and Depth Buffer gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background dgn warna putih gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glPushMatrix(); gl.glEnable(GL10.GL_LINE_SMOOTH); gl.glTranslatef(0.0f, 0.0f, 5.0f); object.draw_circle(gl); gl.glPopMatrix();
gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, 5.0f);
} @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if(height == 0) { //Prevent A Divide By Zero By height = 1; //Making Height Equal One } gl.glViewport(0, 0, width, height); //Reset The Current Viewport gl.glMatrixMode(GL10.GL_PROJECTION); //Select The Projection Matrix
272
gl.glLoadIdentity(); //Reset The Projection Matrix //Calculate The Aspect Ratio Of The Window GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); //Select The Modelview Matrix gl.glLoadIdentity(); //Reset The Modelview Matrix
/*gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluOrtho2D(gl, -1.0f, 1.0f, -1.0f, 1.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity();*/ } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { object = new Object(); } }
MainActivity.java package com.example.opengl_introduction; import import import import import
android.app.Activity; android.opengl.GLSurfaceView; android.os.Bundle; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen
273
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and // create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with // the current activity context glSurfaceView.setRenderer(new GlRenderer()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } }
Object.java package com.example.opengl_introduction; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLES20; public class Object { private FloatBuffer vertexBuffer,vertexBuffer3,vertexBuffer4; // buffer holding the vertices private float vertices3[] = new float[20 * 3]; private float vertices[] = {
274
-0.5f, -0.5f, 0.0f, V1 - first vertex (x,y,z) -0.5f, 0.5f, 0.0f, V1 - first vertex (x,y,z) 0.5f, 0.5f, 0.0f, V1 - first vertex (x,y,z) 0.5f, -0.5f, 0.0f, V2 - second vertex -0.5f, -0.5f, 0.0f V1 - first vertex (x,y,z) };
// // // // //
private float v_segitiga[] = { 1.0f,0.0f,0.0f, // titik ke-1 0.0f,1.0f,0.0f, // titik ke-2 -1.0f,0.0f,0.0f, // titik ke-3 }; private float vertices_color[] = { 1.0f, 0.0f, 0.0f, 1.0f, // V1 - first vertex (x,y,z) 0.0f, 1.0f, 0.0f, 1.0f, // V1 - first vertex (x,y,z) 0.0f, 0.0f, 1.0f, 1.0f, // V1 - first vertex (x,y,z) 0.0f, 1.0f, 0.0f, 1.0f, // V2 - second vertex 1.0f, 0.0f, 0.0f, 1.0f // V1 - first vertex (x,y,z) }; float in_i; int x1 = -5, y1 = -5 ; int x2= 5, y2 = 5 ; int outerVertexCount; private float vertices_circle[]={0.0f,0.0f,0.0f}; private int points=360; float step=0.1f; private int loop; public Object() { //initial; float jari_jari=1.0f; // Titik Pusat float a = 0.0f, b = 0.0f ; float x=a+jari_jari, y=b;
loop=3; //step=3; vertices_circle=new float[(int)(3*points/step)*3]; for(float teta=0;teta<=2*points;teta+=step){ vertices_circle[loop] = (float) ((x-a)*Math.cos((teta/180)*(22/7)) - ((yb)*Math.sin((teta/180)*(22/7))) + a); vertices_circle[loop+1] = (float)
275
((x-a)*Math.sin((teta/180)*(22/7)) - ((yb)*Math.cos((teta/180)*(22/7))) + b); vertices_circle[loop+2]=0; loop+=3; } } public static FloatBuffer makeFloatBuffer(float[] arr){ ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_line(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the line (pemberian warna untuk garis) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // Point to our vertex buffer (mendata nilai lokasi/posisi titik yang menyusun garis) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex (x,y,z) -1.0f, -1.0f, 0.0f, // V2 - second vertex })); // Draw the vertices as lines (menggambar garis dari titik-titik) gl.glDrawArrays(GL10.GL_LINES, 0, 2); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_circle(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
276
//create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_circle)); //draw circle contours gl.glDrawArrays(GL10.GL_LINE_STRIP, 1, (int) ((int) 2*points/step)); //gl.glDrawArrays(GL10.GL_POINTS, 1, (int) ((int) 2*points/step));
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glPopMatrix(); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_triangle(GL10 gl){ gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //warna untuk triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // memanggil lokasi titik x, y, z yang sdh diset gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(v_segitiga)); // drawing gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public void draw_segitiga(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -0.5f, -0.5f, 0.0f, // V1 - first vertex (x,y,z) 0.5f, -0.5f, 0.0f, // V2 - second vertex 0.0f, 0.5f, 0.0f
277
// V3 - third vertex })); gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); // Draw the vertices as square gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
//Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
Gambar 2.19 Membuat Lingkaran Sederhana
278
2.7 Membuat Polar Object Koordinat Kartesius digunakan untuk menentukan tiap titik dalam bidang dengan menggunakan dua bilangan yang biasa disebut koordinat x dan koordinat y dari titik tersebut. Sedangkan koordinat polar adalah koordinat dua dimensi yang menggunakan aturan arah perpindahan dan besar sudut atau jarak dan sudut titik yang dituju.
P(x,y)=P(r cos Ө, r sin Ө)
r
y = r sin Ө
Ө
x = r cos Ө Gambar 2.20 Sistem Koordinat Polar (r, Ө) Source Code 2.11 Code Membuat Polar Object ESRender.java package com.example.primitives_project_es; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; //import android.opengl.GLU; import android.opengl.GLSurfaceView.Renderer; import android.opengl.GLU;
public class ESRender implements Renderer { private PrimitivesObject primitivesobject; // the primitive object to be drawn private PrimitivesPolarObject primitivespolarobject; float sudut=0.0f; float step_sudut=0.0f; /** Constructor to set the handed over context */
279
public ESRender() { this.primitivesobject = new PrimitivesObject(); this.primitivespolarobject = new PrimitivesPolarObject(); } @Override public void onDrawFrame(GL10 gl) { // clear Screen and Depth Buffer gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set background dgn warna putih //gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // set background dgn warna hitam gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // Reset the Modelview Matrix gl.glLoadIdentity(); // menampilkan limacon atau object polar lainnya gl.glPushMatrix(); gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glTranslatef(0.0f, 0.0f, 5.0f); gl.glLineWidth(0.15f); //gl.glScalef(0.15f,0.15f, 0.15f); //gl.glScalef(50.0f,50.0f, 50.0f); gl.glLineWidth(0.3f); primitivespolarobject.draw_limacon(gl); gl.glPopMatrix(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // To prevent divide by zero float aspect = (float) width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix
280
gl.glLoadIdentity(); // Reset } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { //primitivesobject = new PrimitivesObject(); primitivesobject = new PrimitivesObject(); primitivespolarobject = new PrimitivesPolarObject(); } }
MainActivity.java package com.example.primitives_project_es; import import import import import import
android.opengl.GLSurfaceView; android.os.Bundle; android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { /** The OpenGL view */ private GLSurfaceView glSurfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSC REEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and // create an instance with this activity glSurfaceView = new GLSurfaceView(this); // set our renderer to be the main renderer with
281
// the current activity context glSurfaceView.setRenderer(new ESRender()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
PrimitivesPolarObject.java package com.example.primitives_project_es; import import import import import
java.nio.ByteBuffer; java.nio.ByteOrder; java.nio.FloatBuffer; javax.microedition.khronos.opengles.GL10; android.opengl.GLES20;
public class PrimitivesPolarObject { private float vertices_limacon[]={0.0f,0.0f,0.0f}; private float vertices_limacon_color[]={0.0f,0.0f,0.0f,0.5f}; private int batas_sudut=360; float step=1.0f; private int loop,loop_color; public PrimitivesPolarObject() {
282
//Inisialisasi //Menggambar persamaan koordinat polar, misal r=b+acos(sudut) float a = 1; float b = 1; loop=3; loop_color=4; vertices_limacon=new float[(int)(11*batas_sudut/step)*3]; vertices_limacon_color=new float[(int)(11*batas_sudut/step)*4]; for(float teta=0;teta<=10*batas_sudut;teta+=step){ float radian=(float) ((teta/180)*3.14); //float _r=(float) (b+(a*Math.cos(radian))); float _r=(float) (Math.cos((7*radian)/4)); //float _r=(float) (2+7*Math.sin(3*radian)); //float _r=(float) ((2+7*Math.sin(3*radian))*Math.cos(5*radian)); //float _r=(a*exp(b*radian)); //float _r=10*(a+(b*radian)); vertices_limacon[loop] = (float) (_r*Math.cos(radian)); vertices_limacon[loop+1] = (float) (_r*Math.sin(radian)); vertices_limacon[loop+2]=0; loop+=3; //mengenerate warna untuk setiap vertex vertices_limacon_color[loop_color]=(float) (_r*Math.cos(radian)); vertices_limacon_color[loop_color+1]=(float) (_r*Math.sin(radian)); vertices_limacon_color[loop_color+2]=0.5f; vertices_limacon_color[loop_color+3]=0.1f; loop_color+=4; } } // Point to our vertex buffer, return buffer holding the vertices public static FloatBuffer makeFloatBuffer(float[] arr){ ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr);
283
fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_limacon(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); //create VBO from buffer with glBufferData() gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_limacon)); //memetakan warna untuk setiap vertex gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_limacon_color)); //draw circle as filled shape //gl.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 1, (int) ((int) 10*batas_sudut/step)); //draw circle contours //gl.glDrawArrays(GL10.GL_LINES, 1, (int) ((int) 2*batas_sudut/step)); // membuat garis putusputus pada tepi lingkaran gl.glDrawArrays(GLES20.GL_LINE_STRIP, 1, (int) ((int) 10*batas_sudut/step)); //gl.glDrawArrays(GLES20.GL_POINTS, 1, (int) ((int) 10*batas_sudut/step));
//Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
284
Gambar 2.21 Membuat Polar Object
285
BAB 3 Transformations 3.1 Pengertian Transformasi Transformasi adalah memindahkan objek tanpa merusak bentuk aslinya, meskipun ada perubahan bentuk atau modifikasi pada hasil akhirnya. Tujuan transformasi: 1. 2. 3. 4.
Melihat objek dari sudut pandang yang berbeda. Membuat komposisi pemandangan yang sesuai. Memudahkan membuat objek yang simetris. Memindahkan satu atau beberapa objek dari satu tempat ke tempat lain, ini biasa dipakai untuk animasi komputer.
Jenis-jenis transformasi: 1. 2. 3. 4. 5.
Modeling Viewing Projection Viewport Modelview
3.2 Matematika & Proses Transformasi Transformasi dalam OpenGL dilakukan dengan menggunakan konsep matriks.
Gambar 3.1 Vertex Transformation Pipeline Matrix modes: -
ModelView Matrix (GL_MODELVIEW) Untuk traslasi, rotasi, dan scaling. Projection Matrix (GL_PROJECTION) Untuk setup camera projection
286
Transformasi dapat dilakukan dengan dua operasi, yaitu operasi matrik, dan operasi vektor. 1.Operasi matrik a.Penambahan dan pengurangan b.Perkalian c.Determinan d.Transpos e.Kebalikan (inverse) 2.Operasi vector a.Penambahan dan pengurangan b.Pekalian titik (dot product) c.Perkalian silang (cross product) Dalam transformasi dasar yang akan dibahas meliputi translasi, scaling, rotasi, dan shearing. 1. Translasi Translasi berarti memindahkan objek sepanjang garis lurus dari suatu lokasi koordinat tertentu kelokasi yang lain tanpa mengubah bentuk objek. Bila suatu objek terbentuk daribeberapa titik maka bila melakukan translasi akan dikenakan terhadap setiap titikpembentuk objek tersebut. Untuk melakukan translasi dapat menggunakan rumus: x’ = x + tx y’ = y + ty
Gambar 3.2 Contoh Proses Translasi 2. Scaling Scaling digunakan untuk mengubah ukuran suatu objek, bila pada translasi operasi yangdigunakan adalah penjumlahan sedangkan pada skala operasi yang digunakan adalah perkalian. Untuk melakukan skala dapat menggunakan rumus: x’= x * tx y’ = y * ty tx dan ty merupakan nilai dari scaling factor terhadap sumbu x dan sumbu y. 287
Gambar 3.3 Contoh Proses Scaling 1. Rotasi Rotasi merupakan pemutaran terhadap suatu objek, rotasi dapat dinyatakan dalam bentuk matriks. Nilai matriks untuk melakukan rotasi adalah rotasi suatu titik terhadap pivot point (xp, yp) menggunakan bentuk trigonometri.
Gambar 3.4 Contoh Proses Rotasi 2. Shearing Shearing yaitu transformasi yang mengubah sisi objek.
Gambar 3.5 Contoh Proses Shearing
288
3. Kombinasi (Translasi + Skala + Rotasi + Shearing)
Gambar 3.6 Contoh Proses Kombinasi Transformasi Syntax transformasi: 1. glTranslate(T x, T y, T z) - Memindahkan titik/ objek dalam arah x, y, dan z. - Nilai x, y, dan z ditambah atau dikurangi dengan nilai tertentu. - Jika titik A ditranslasikan ke B dengan matriks translasi K, maka persamaannya adalah A = KB. 2. glScale(T x, T y, T z) - Nilai x, y, dan z dikalikan dengan bilangan scalar. 3. glRotate(T angle, T x, T y, T z) - T angle (dinyatakan dalam derajat) dengan arah berlawanan dengan jarum jam (counterclockwise). - Nilai koordinat x, y, dan z diputar ke sekeliling titik referensi.
289
3.3 Urutan Transformasi Hasil transformasi dikatakan benar jika dilakukan sesuai dengan kondisi yang tepat. Contoh: Jika (Px,Py) = (4,6) dilakukan Translasi (6,-3), Rotasi(60˚), dan Skala (0.5,2) Cara 1 : Step by Step Qx 1 0 dPx Px 1 0 6 4 10 Qy 0 1 dPy Py 0 1 3 6 3 1 0 0 1 1 0 0 1 1 1 Qx cos60 sin 60 0 Px 0.5 0.87 0 10 5 2.6 2.4 Qy sin 60 cos60 0 Py 0.87 0.5 0 3 8.7 1.5 10.2 1 0 1 0 1 1 0 0 1 1 1 Qx sPx 0 0 Px 0.5 0 0 2.4 1.2 Qy 0 sPx 0 Py 0 2 0 10.2 20.4 1 0 0 1 1 0 0 1 1 1
Jadi (Qx, Qy) akhir = (1.2, 20.4, 1)
Cara 2 : Transformasi berturut-turut dapat dilakukan dengan mengalikan matriks-matriks transformasi sesuai dengan urutan terbalik Qx 0.5 0 0 cos60 sin 60 0 1 0 6 4 1.2 Qy 0 2 0 sin 60 cos60 0 0 1 3 6 20.4 1 0 0 1 0 0 1 0 0 1 1 1
Jadi (Qx, Qy) akhir = (1.2, 20.4, 1)
3.4 Membuat Kincir Angin Source Code 3.1 Code Membuat Kincir Angin ESSurfaceFungsi.java package com.example.project_c; import import import import
android.content.Context; android.opengl.GLSurfaceView; android.util.Log; android.view.MotionEvent;
public class ESSurfaceFungsi extends GLSurfaceView{
290
private final GlRenderer glRenderer; public ESSurfaceFungsi(Context context) { super(context); // TODO Auto-generated constructor stub glRenderer = new GlRenderer(); setRenderer(glRenderer); } public boolean onTouchEvent(MotionEvent v){ switch (v.getAction()) { case MotionEvent.ACTION_DOWN: Log.v("Test Action Down", "action down working"); Log.i("Test Action Nilai", ""+Math.abs(glRenderer.getRunMode()-1)); glRenderer.setRunMode(Math.abs(glRenderer.getRunMode()-1)); requestRender(); } return true; } }
GlRenderer.java package com.example.project_c; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import com.example.project_c.Object; import android.opengl.GLU; import android.opengl.GLSurfaceView.Renderer; public class GlRenderer implements Renderer { private Object object; // the triangle to be drawn int RunMode=1; // Angle in degrees float CurrentAngle = 0.0f; // Rotation step per update float AnimateStep = 1.0f; float sudut = 0.0f; float step_sudut = 2.0f; float back_sudut = -4.0f; /** Constructor to set the handed over context */ public GlRenderer() { this.object = new Object(); } @Override public void onDrawFrame(GL10 gl) { // clear Screen and Depth Buffer
291
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // menampilkan segitiga sama kaki paling bawah gl.glLoadIdentity(); gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, 0.0f); // move y+1 gl.glTranslatef(0.0f, -1.0f, 0.0f); gl.glTranslatef(0.0f, 0.0f, -7.0f); object.draw_segitigasamakaki(gl); gl.glPopMatrix(); // menampilkan persegi dengan gradasi warna gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glRotatef(-CurrentAngle, 0.0f, 0.0f, 1.0f); gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); object.draw_kotak(gl); gl.glPopMatrix(); // menampilkan persegi dengan gradasi warna pindah gl.glPushMatrix(); gl.glTranslatef(0.0f, 0.0f, -5.0f); gl.glRotatef(-CurrentAngle, 0.0f, 0.0f, 1.0f); gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glRotatef(90, 0.0f, 0.0f, 1.0f); object.draw_kotak(gl); gl.glPopMatrix(); if (RunMode==1) { // re-Calculate animation parameters CurrentAngle += AnimateStep; if (CurrentAngle > 360.0) { CurrentAngle=0.0f; CurrentAngle += AnimateStep; } } if (RunMode==1) { // re-Calculate animation parameters CurrentAngle += AnimateStep; if (CurrentAngle > 360.0) { CurrentAngle=0.0f; CurrentAngle += AnimateStep; } } } @Override public void height) { //Prevent if(height //Making height = }
onSurfaceChanged(GL10 gl, int width, int A Divide By Zero By == 0) { Height Equal One 1;
292
//Reset The Current Viewport gl.glViewport(0, 0, width, height); //Select The Projection Matrix gl.glMatrixMode(GL10.GL_PROJECTION); //Reset The Projection Matrix gl.glLoadIdentity();
//Calculate The Aspect Ratio Of The Window GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); //Select The Modelview Matrix gl.glLoadIdentity(); //Reset The Modelview Matrix } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { object = new Object(); gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Enable Smooth Shading, default not really needed. gl.glShadeModel(GL10.GL_SMOOTH); // Depth buffer setup. gl.glClearDepthf(1.0f); // Enables depth testing. gl.glEnable(GL10.GL_DEPTH_TEST); // The type of depth testing to do. gl.glDepthFunc(GL10.GL_LEQUAL); // Really nice perspective calculations. gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); } public int getRunMode() { return RunMode; } public void setRunMode(int mRunMode) { RunMode = mRunMode; } }
293
MainActivity.java package com.example.project_c; import import import import import import
android.opengl.GLSurfaceView; android.os.Bundle; android.app.Activity; android.view.Menu; android.view.Window; android.view.WindowManager;
public class MainActivity extends Activity { private GLSurfaceView glSurfaceView; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requesting to turn the title OFF requestWindowFeature(Window.FEATURE_NO_TITLE); // making it full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREE N, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Initiate the Open GL view and // create an instance with this activity glSurfaceView = new ESSurfaceFungsi(this); // set our renderer to be the main renderer with // the current activity context //glSurfaceView.setRenderer(new GlRenderer()); setContentView(glSurfaceView); } /** * Remember to resume the glSurface */ @Override protected void onResume() { super.onResume(); glSurfaceView.onResume(); } /** * Also pause the glSurface */ @Override protected void onPause() { super.onPause(); glSurfaceView.onPause(); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to
294
the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Object.java package com.example.project_c; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLES20; public class Object { private FloatBuffer vertexBuffer,vertexBuffer3,vertexBuffer4; the vertices
// buffer holding
private float vertices3[] = new float[20 * 3];
V1 V1 V1 V2 V1 -
private float vertices[] = { -0.8f, -0.1f, 0.0f, first vertex (x,y,z) -0.8f, 0.1f, 0.0f, first vertex (x,y,z) 0.8f, 0.1f, 0.0f, first vertex (x,y,z) 0.8f, -0.1f, 0.0f, second vertex -0.8f, -0.1f, 0.0f first vertex (x,y,z)
// // // // //
}; private float vertices_color[] = { 1.0f, 0.0f, 0.0f, 1.0f, CV1 - first color (red,green,blue) 0.0f, 1.0f, 0.0f, 1.0f, CV2 0.0f, 0.0f, 1.0f, 1.0f, CV3 0.0f, 1.0f, 0.0f, 1.0f, CV4 1.0f, 0.0f, 0.0f, 1.0f // V1 - first vertex (x,y,z)
// // // //
}; private float vertices_color1[] = { 1.0f, 0.0f, 0.0f, 1.0f,
295
//
CV1 - first color (red,green,blue) 0.0f, 1.0f, 0.0f, CV2 0.0f, 0.0f, 1.0f, CV3 0.0f, 1.0f, 0.0f, CV4 1.0f, 0.0f, 0.0f, // V1 - first vertex (x,y,z)
1.0f,
//
1.0f,
//
1.0f,
//
1.0f
}; public static FloatBuffer makeFloatBuffer(float[] arr){ ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4); bb.order(ByteOrder.nativeOrder()); FloatBuffer fb = bb.asFloatBuffer(); fb.put(arr); fb.position(0); return fb; } /** The draw method for the primitive object with the GL context */ public void draw_line(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the line (pemberian warna untuk garis) gl.glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
// Point to our vertex buffer (mendata nilai lokasi/posisi titik yang menyusun garis) gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { 0.5f, 0.5f, 0.0f, // V1 - first vertex (x,y,z) -0.5f, -0.5f, 0.0f, // V2 - second vertex })); // Draw the vertices as lines (menggambar garis dari titik-titik) gl.glDrawArrays(GL10.GL_LINES, 0, 2); /*gl.glDrawElements(GL10.GL_LINES, 2, GL10.GL_UNSIGNED_SHORT, makeFloatBuffer(new float [] { 1.0f, 1.0f, 0.0f, // V1 - first vertex (x,y,z) -1.0f, -1.0f, 0.0f, // V2 - second vertex }));*/
296
//Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); //gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_kotak(GL10 gl) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); //gl.glClear(GL10.GL_COLOR_BUFFER_BIT); gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Point to our vertex buffer gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices)); // Draw the vertices as square gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GL10.GL_TRIANGLES, 2, 3);
//Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_segitiga(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -0.3f, -0.3f, 0.0f, // V1 - first vertex (x,y,z) 0.3f, -0.3f, 0.0f, // V2 - second vertex 0.0f, 0.6f, 0.0f // V3 - third vertex }));
297
// Draw the vertices as triangle gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color)); gl.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void draw_segitigasamakaki(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // set the colour for the triangle gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, makeFloatBuffer(new float [] { -0.7f, -1.7f, 0.0f, // V1 - first vertex (x,y,z) 0.7f, -1.7f, 0.0f, // V2 - second vertex 0.0f, 1.0f, 0.0f // V3 - third vertex })); // Draw the vertices as triangle gl.glColorPointer(4, GL10.GL_FLOAT, 0, makeFloatBuffer(vertices_color1)); gl.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } }
298
Gambar 3.7 Membuat Kincir Angin
299