From 3ab0ddb69c2fbac64ad719f09fa7c336e3267670 Mon Sep 17 00:00:00 2001 From: Jeffrey Phillips Freeman <jeffrey.freeman@syncleus.com> Date: Fri, 28 Jul 2017 00:10:47 -0400 Subject: [PATCH] docs(license): added license notice and headers to all files.y --- NOTICE | 13 + src/main/java/com/aparapi/examples/All.java | 15 + .../java/com/aparapi/examples/add/Main.java | 187 ++-- .../aparapi/examples/blackscholes/Main.java | 437 +++++----- .../configuration/AutoCleanUpArraysDemo.java | 15 + .../configuration/CleanUpArraysDemo.java | 15 + .../configuration/ConfigurationDemo.java | 195 +++-- .../CustomConfigurationDemo.java | 119 +-- .../configuration/KernelOkayInOpenCL.java | 77 +- .../KernelWithAlternateFallbackAlgorithm.java | 83 +- ...rnelWithoutAlternateFallbackAlgorithm.java | 63 +- .../LegacyConfigurationDemo.java | 87 +- .../examples/configuration/ProfilingDemo.java | 15 + .../ProfilingDemoNoBinaryCaching.java | 15 + .../convolution/ConvMatrix3x3Editor.java | 337 ++++---- .../examples/convolution/Convolution.java | 273 +++--- .../convolution/ConvolutionOpenCL.java | 219 ++--- .../convolution/ConvolutionViewer.java | 297 +++---- .../examples/convolution/PureJava.java | 269 +++--- .../com/aparapi/examples/effects/Main.java | 15 + .../examples/extension/FFTExample.java | 287 ++++--- .../aparapi/examples/extension/Histogram.java | 227 ++--- .../examples/extension/HistogramIdeal.java | 199 +++-- .../examples/extension/JavaMandelBrot.java | 15 + .../extension/JavaMandelBrotMultiThread.java | 15 + .../aparapi/examples/extension/Mandel.java | 15 + .../examples/extension/MandelBrot.java | 15 + .../examples/extension/MandelExample.java | 517 ++++++------ .../examples/extension/MandelSimple.java | 447 +++++----- .../examples/extension/Pow4Example.java | 137 +-- .../examples/extension/SquareExample.java | 213 ++--- .../aparapi/examples/extension/StopWatch.java | 65 +- .../examples/extension/SwapExample.java | 163 ++-- .../java/com/aparapi/examples/info/Main.java | 205 ++--- .../aparapi/examples/javaonedemo/Life.java | 639 +++++++------- .../aparapi/examples/javaonedemo/Mandel.java | 729 ++++++++-------- .../aparapi/examples/javaonedemo/NBody.java | 797 +++++++++--------- .../java/com/aparapi/examples/life/Main.java | 575 +++++++------ .../com/aparapi/examples/mandel/Main.java | 647 +++++++------- .../com/aparapi/examples/mandel/Main2D.java | 567 +++++++------ .../com/aparapi/examples/mapreduce/Main.java | 15 + .../aparapi/examples/mdarray/BMatMul1D.java | 93 +- .../aparapi/examples/mdarray/BMatMul2D.java | 93 +- .../aparapi/examples/mdarray/BMatMul3D.java | 101 ++- .../aparapi/examples/mdarray/DMatMul1D.java | 93 +- .../aparapi/examples/mdarray/DMatMul2D.java | 93 +- .../aparapi/examples/mdarray/DMatMul3D.java | 95 ++- .../aparapi/examples/mdarray/FMatMul1D.java | 93 +- .../aparapi/examples/mdarray/FMatMul2D.java | 93 +- .../aparapi/examples/mdarray/FMatMul3D.java | 95 ++- .../aparapi/examples/mdarray/IMatMul1D.java | 93 +- .../aparapi/examples/mdarray/IMatMul2D.java | 93 +- .../aparapi/examples/mdarray/IMatMul3D.java | 95 ++- .../aparapi/examples/mdarray/LMatMul1D.java | 93 +- .../aparapi/examples/mdarray/LMatMul2D.java | 93 +- .../aparapi/examples/mdarray/LMatMul3D.java | 95 ++- .../com/aparapi/examples/mdarray/MDArray.java | 15 + .../aparapi/examples/mdarray/SMatMul1D.java | 93 +- .../aparapi/examples/mdarray/SMatMul2D.java | 93 +- .../aparapi/examples/mdarray/SMatMul3D.java | 95 ++- .../aparapi/examples/mdarray/ZMatMul1D.java | 93 +- .../aparapi/examples/mdarray/ZMatMul2D.java | 93 +- .../aparapi/examples/mdarray/ZMatMul3D.java | 95 ++- .../aparapi/examples/median/MedianDemo.java | 245 +++--- .../examples/median/MedianKernel7x7.java | 373 ++++---- .../examples/median/MedianSettings.java | 65 +- .../com/aparapi/examples/nbody/Local.java | 765 +++++++++-------- .../java/com/aparapi/examples/nbody/Main.java | 775 ++++++++--------- .../java/com/aparapi/examples/nbody/Seq.java | 757 +++++++++-------- .../com/aparapi/examples/oopnbody/Body.java | 15 + .../com/aparapi/examples/oopnbody/Main.java | 783 ++++++++--------- .../examples/progress/LongRunningKernel.java | 97 ++- .../MultiPassKernelSwingWorkerDemo.java | 299 +++---- .../progress/ProgressAndCancelDemo.java | 367 ++++---- .../com/aparapi/examples/squares/Main.java | 227 ++--- 75 files changed, 8557 insertions(+), 7434 deletions(-) create mode 100644 NOTICE diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..41187df2 --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +Copyright (c) 2016 - 2017 Syncleus, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/src/main/java/com/aparapi/examples/All.java b/src/main/java/com/aparapi/examples/All.java index b27b601a..e1080f3d 100644 --- a/src/main/java/com/aparapi/examples/All.java +++ b/src/main/java/com/aparapi/examples/All.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/add/Main.java b/src/main/java/com/aparapi/examples/add/Main.java index 97a4c7e0..ceac1bac 100644 --- a/src/main/java/com/aparapi/examples/add/Main.java +++ b/src/main/java/com/aparapi/examples/add/Main.java @@ -1,86 +1,101 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.add; - -import com.aparapi.Kernel; -import com.aparapi.Range; - -public class Main{ - - public static void main(String[] _args) { - - final int size = 512; - - final float[] a = new float[size]; - final float[] b = new float[size]; - - for (int i = 0; i < size; i++) { - a[i] = (float) (Math.random() * 100); - b[i] = (float) (Math.random() * 100); - } - - final float[] sum = new float[size]; - - Kernel kernel = new Kernel(){ - @Override public void run() { - int gid = getGlobalId(); - sum[gid] = a[gid] + b[gid]; - } - }; - - kernel.execute(Range.create(size)); - - for (int i = 0; i < size; i++) { - System.out.printf("%6.2f + %6.2f = %8.2f\n", a[i], b[i], sum[i]); - } - - kernel.dispose(); - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.add; + +import com.aparapi.Kernel; +import com.aparapi.Range; + +public class Main{ + + public static void main(String[] _args) { + + final int size = 512; + + final float[] a = new float[size]; + final float[] b = new float[size]; + + for (int i = 0; i < size; i++) { + a[i] = (float) (Math.random() * 100); + b[i] = (float) (Math.random() * 100); + } + + final float[] sum = new float[size]; + + Kernel kernel = new Kernel(){ + @Override public void run() { + int gid = getGlobalId(); + sum[gid] = a[gid] + b[gid]; + } + }; + + kernel.execute(Range.create(size)); + + for (int i = 0; i < size; i++) { + System.out.printf("%6.2f + %6.2f = %8.2f\n", a[i], b[i], sum[i]); + } + + kernel.dispose(); + } + +} diff --git a/src/main/java/com/aparapi/examples/blackscholes/Main.java b/src/main/java/com/aparapi/examples/blackscholes/Main.java index c462d201..744eacdb 100644 --- a/src/main/java/com/aparapi/examples/blackscholes/Main.java +++ b/src/main/java/com/aparapi/examples/blackscholes/Main.java @@ -1,211 +1,226 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ -package com.aparapi.examples.blackscholes; - -import com.aparapi.Kernel; -import com.aparapi.Range; - -public class Main{ - - public static class BlackScholesKernel extends Kernel{ - - /* - * For a description of the algorithm and the terms used, please see the - * documentation for this sample. - * - * On invocation of kernel blackScholes, each work thread calculates call price - * and put price values for given stock price, option strike price, - * time to expiration date, risk free interest and volatility factor. - */ - - final float S_LOWER_LIMIT = 10.0f; - - final float S_UPPER_LIMIT = 100.0f; - - final float K_LOWER_LIMIT = 10.0f; - - final float K_UPPER_LIMIT = 100.0f; - - final float T_LOWER_LIMIT = 1.0f; - - final float T_UPPER_LIMIT = 10.0f; - - final float R_LOWER_LIMIT = 0.01f; - - final float R_UPPER_LIMIT = 0.05f; - - final float SIGMA_LOWER_LIMIT = 0.01f; - - final float SIGMA_UPPER_LIMIT = 0.10f; - - /** - * @brief Abromowitz Stegun approxmimation for PHI (Cumulative Normal Distribution Function) - * @param X input value - */ - float phi(float X) { - final float c1 = 0.319381530f; - final float c2 = -0.356563782f; - final float c3 = 1.781477937f; - final float c4 = -1.821255978f; - final float c5 = 1.330274429f; - - final float zero = 0.0f; - final float one = 1.0f; - final float two = 2.0f; - final float temp4 = 0.2316419f; - - final float oneBySqrt2pi = 0.398942280f; - - float absX = abs(X); - float t = one / (one + temp4 * absX); - - float y = one - oneBySqrt2pi * exp(-X * X / two) * t * (c1 + t * (c2 + t * (c3 + t * (c4 + t * c5)))); - - float result = (X < zero) ? (one - y) : y; - - return result; - } - - /* - * @brief Calculates the call and put prices by using Black Scholes model - * @param s Array of random values of current option price - * @param sigma Array of random values sigma - * @param k Array of random values strike price - * @param t Array of random values of expiration time - * @param r Array of random values of risk free interest rate - * @param width Width of call price or put price array - * @param call Array of calculated call price values - * @param put Array of calculated put price values - */ - @Override public void run() { - float d1, d2; - float phiD1, phiD2; - float sigmaSqrtT; - float KexpMinusRT; - - int gid = getGlobalId(); - float two = 2.0f; - float inRand = randArray[gid]; - float S = S_LOWER_LIMIT * inRand + S_UPPER_LIMIT * (1.0f - inRand); - float K = K_LOWER_LIMIT * inRand + K_UPPER_LIMIT * (1.0f - inRand); - float T = T_LOWER_LIMIT * inRand + T_UPPER_LIMIT * (1.0f - inRand); - float R = R_LOWER_LIMIT * inRand + R_UPPER_LIMIT * (1.0f - inRand); - float sigmaVal = SIGMA_LOWER_LIMIT * inRand + SIGMA_UPPER_LIMIT * (1.0f - inRand); - - sigmaSqrtT = sigmaVal * sqrt(T); - - d1 = (log(S / K) + (R + sigmaVal * sigmaVal / two) * T) / sigmaSqrtT; - d2 = d1 - sigmaSqrtT; - - KexpMinusRT = K * exp(-R * T); - - phiD1 = phi(d1); - phiD2 = phi(d2); - - call[gid] = S * phiD1 - KexpMinusRT * phiD2; - - phiD1 = phi(-d1); - phiD2 = phi(-d2); - - put[gid] = KexpMinusRT * phiD2 - S * phiD1; - } - - private float randArray[]; - - private float put[]; - - private float call[]; - - public BlackScholesKernel(int size) { - randArray = new float[size]; - call = new float[size]; - put = new float[size]; - - for (int i = 0; i < size; i++) { - randArray[i] = i * 1.0f / size; - } - } - - public void showArray(float ary[], String name, int count) { - String line; - line = name + ": "; - for (int i = 0; i < count; i++) { - if (i > 0) - line += ", "; - line += ary[i]; - } - System.out.println(line); - } - - public void showResults(int count) { - showArray(call, "Call Prices", count); - showArray(put, "Put Prices", count); - } - } - - public static void main(String[] _args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - - int size = Integer.getInteger("size", 1024); - Range range = Range.create(size); - int iterations = Integer.getInteger("iterations", 10000); - System.out.println("size =" + size); - System.out.println("iterations =" + iterations); - BlackScholesKernel kernel = new BlackScholesKernel(size); - - for (int i = 0; i < iterations; i++) { - kernel.execute(size).getExecutionTime(); - } - - kernel.execute(range, iterations); - System.out.println("Average execution time " + kernel.getAccumulatedExecutionTime() / iterations); - kernel.showResults(10); - - kernel.dispose(); - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ +package com.aparapi.examples.blackscholes; + +import com.aparapi.Kernel; +import com.aparapi.Range; + +public class Main{ + + public static class BlackScholesKernel extends Kernel{ + + /* + * For a description of the algorithm and the terms used, please see the + * documentation for this sample. + * + * On invocation of kernel blackScholes, each work thread calculates call price + * and put price values for given stock price, option strike price, + * time to expiration date, risk free interest and volatility factor. + */ + + final float S_LOWER_LIMIT = 10.0f; + + final float S_UPPER_LIMIT = 100.0f; + + final float K_LOWER_LIMIT = 10.0f; + + final float K_UPPER_LIMIT = 100.0f; + + final float T_LOWER_LIMIT = 1.0f; + + final float T_UPPER_LIMIT = 10.0f; + + final float R_LOWER_LIMIT = 0.01f; + + final float R_UPPER_LIMIT = 0.05f; + + final float SIGMA_LOWER_LIMIT = 0.01f; + + final float SIGMA_UPPER_LIMIT = 0.10f; + + /** + * @brief Abromowitz Stegun approxmimation for PHI (Cumulative Normal Distribution Function) + * @param X input value + */ + float phi(float X) { + final float c1 = 0.319381530f; + final float c2 = -0.356563782f; + final float c3 = 1.781477937f; + final float c4 = -1.821255978f; + final float c5 = 1.330274429f; + + final float zero = 0.0f; + final float one = 1.0f; + final float two = 2.0f; + final float temp4 = 0.2316419f; + + final float oneBySqrt2pi = 0.398942280f; + + float absX = abs(X); + float t = one / (one + temp4 * absX); + + float y = one - oneBySqrt2pi * exp(-X * X / two) * t * (c1 + t * (c2 + t * (c3 + t * (c4 + t * c5)))); + + float result = (X < zero) ? (one - y) : y; + + return result; + } + + /* + * @brief Calculates the call and put prices by using Black Scholes model + * @param s Array of random values of current option price + * @param sigma Array of random values sigma + * @param k Array of random values strike price + * @param t Array of random values of expiration time + * @param r Array of random values of risk free interest rate + * @param width Width of call price or put price array + * @param call Array of calculated call price values + * @param put Array of calculated put price values + */ + @Override public void run() { + float d1, d2; + float phiD1, phiD2; + float sigmaSqrtT; + float KexpMinusRT; + + int gid = getGlobalId(); + float two = 2.0f; + float inRand = randArray[gid]; + float S = S_LOWER_LIMIT * inRand + S_UPPER_LIMIT * (1.0f - inRand); + float K = K_LOWER_LIMIT * inRand + K_UPPER_LIMIT * (1.0f - inRand); + float T = T_LOWER_LIMIT * inRand + T_UPPER_LIMIT * (1.0f - inRand); + float R = R_LOWER_LIMIT * inRand + R_UPPER_LIMIT * (1.0f - inRand); + float sigmaVal = SIGMA_LOWER_LIMIT * inRand + SIGMA_UPPER_LIMIT * (1.0f - inRand); + + sigmaSqrtT = sigmaVal * sqrt(T); + + d1 = (log(S / K) + (R + sigmaVal * sigmaVal / two) * T) / sigmaSqrtT; + d2 = d1 - sigmaSqrtT; + + KexpMinusRT = K * exp(-R * T); + + phiD1 = phi(d1); + phiD2 = phi(d2); + + call[gid] = S * phiD1 - KexpMinusRT * phiD2; + + phiD1 = phi(-d1); + phiD2 = phi(-d2); + + put[gid] = KexpMinusRT * phiD2 - S * phiD1; + } + + private float randArray[]; + + private float put[]; + + private float call[]; + + public BlackScholesKernel(int size) { + randArray = new float[size]; + call = new float[size]; + put = new float[size]; + + for (int i = 0; i < size; i++) { + randArray[i] = i * 1.0f / size; + } + } + + public void showArray(float ary[], String name, int count) { + String line; + line = name + ": "; + for (int i = 0; i < count; i++) { + if (i > 0) + line += ", "; + line += ary[i]; + } + System.out.println(line); + } + + public void showResults(int count) { + showArray(call, "Call Prices", count); + showArray(put, "Put Prices", count); + } + } + + public static void main(String[] _args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + + int size = Integer.getInteger("size", 1024); + Range range = Range.create(size); + int iterations = Integer.getInteger("iterations", 10000); + System.out.println("size =" + size); + System.out.println("iterations =" + iterations); + BlackScholesKernel kernel = new BlackScholesKernel(size); + + for (int i = 0; i < iterations; i++) { + kernel.execute(size).getExecutionTime(); + } + + kernel.execute(range, iterations); + System.out.println("Average execution time " + kernel.getAccumulatedExecutionTime() / iterations); + kernel.showResults(10); + + kernel.dispose(); + } + +} diff --git a/src/main/java/com/aparapi/examples/configuration/AutoCleanUpArraysDemo.java b/src/main/java/com/aparapi/examples/configuration/AutoCleanUpArraysDemo.java index c00e97af..d7fd5955 100644 --- a/src/main/java/com/aparapi/examples/configuration/AutoCleanUpArraysDemo.java +++ b/src/main/java/com/aparapi/examples/configuration/AutoCleanUpArraysDemo.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/configuration/CleanUpArraysDemo.java b/src/main/java/com/aparapi/examples/configuration/CleanUpArraysDemo.java index 3891f04b..63608098 100644 --- a/src/main/java/com/aparapi/examples/configuration/CleanUpArraysDemo.java +++ b/src/main/java/com/aparapi/examples/configuration/CleanUpArraysDemo.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/configuration/ConfigurationDemo.java b/src/main/java/com/aparapi/examples/configuration/ConfigurationDemo.java index 6ad8894c..afad2d6f 100644 --- a/src/main/java/com/aparapi/examples/configuration/ConfigurationDemo.java +++ b/src/main/java/com/aparapi/examples/configuration/ConfigurationDemo.java @@ -1,90 +1,105 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.configuration; - -import com.aparapi.*; -import com.aparapi.internal.kernel.*; - -import java.util.*; - -/** - * Tests device selection via {@link com.aparapi.internal.kernel.KernelManager}. - */ -public class ConfigurationDemo { - public static void main(String[] ignored) { - StringBuilder report; - - List<Integer> tests = Arrays.asList(0, 1, 2, 3); - int reps = 1; - for (int rep = 0; rep < reps; ++rep) { - runTests(rep == 0, tests); - - if (rep % 100 == 99 || rep == 0 || rep == reps - 1) { - report = new StringBuilder("rep = " + rep + "\n"); - KernelManager.instance().reportDeviceUsage(report, true); - System.out.println(report); - } - } - } - - private static void runTests(boolean verbose, List<Integer> testIndicesToRun) { - final int globalSize = 1; - Kernel kernel; - if (testIndicesToRun.contains(0)) { - if (verbose) { - System.out.println(); - System.out.println("Testing default KernelPreferences with kernel which cannot be run in OpenCL, with fallback algorithm"); - System.out.println(); - } - kernel = new KernelWithAlternateFallbackAlgorithm(); - kernel.execute(globalSize); - kernel.dispose(); - } - - if (testIndicesToRun.contains(1)) { - if (verbose) { - System.out.println(); - System.out.println("Testing default KernelPreferences with kernel which cannot be run in OpenCL, without fallback algorithm"); - System.out.println(); - } - kernel = new KernelWithoutAlternateFallbackAlgorithm(); - kernel.execute(globalSize); - kernel.dispose(); - } - - if (testIndicesToRun.contains(2)) { - if (verbose) { - System.out.println(); - System.out.println("Retesting previous case, should jump straight to regular java implementation without warnings"); - System.out.println(); - } - kernel = new KernelWithoutAlternateFallbackAlgorithm(); - kernel.execute(globalSize); - kernel.dispose(); - } - - if (testIndicesToRun.contains(3)) { - if (verbose) { - System.out.println(); - System.out.println("Testing default KernelPreferences with kernel which should be run in OpenCL"); - System.out.println(); - } - KernelOkayInOpenCL clKernel = new KernelOkayInOpenCL(); - kernel = clKernel; - kernel.execute(clKernel.inChars.length); - String result = new String(clKernel.outChars); - if (verbose) { - System.out.println("kernel output: " + result); - } - kernel.dispose(); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.configuration; + +import com.aparapi.*; +import com.aparapi.internal.kernel.*; + +import java.util.*; + +/** + * Tests device selection via {@link com.aparapi.internal.kernel.KernelManager}. + */ +public class ConfigurationDemo { + public static void main(String[] ignored) { + StringBuilder report; + + List<Integer> tests = Arrays.asList(0, 1, 2, 3); + int reps = 1; + for (int rep = 0; rep < reps; ++rep) { + runTests(rep == 0, tests); + + if (rep % 100 == 99 || rep == 0 || rep == reps - 1) { + report = new StringBuilder("rep = " + rep + "\n"); + KernelManager.instance().reportDeviceUsage(report, true); + System.out.println(report); + } + } + } + + private static void runTests(boolean verbose, List<Integer> testIndicesToRun) { + final int globalSize = 1; + Kernel kernel; + if (testIndicesToRun.contains(0)) { + if (verbose) { + System.out.println(); + System.out.println("Testing default KernelPreferences with kernel which cannot be run in OpenCL, with fallback algorithm"); + System.out.println(); + } + kernel = new KernelWithAlternateFallbackAlgorithm(); + kernel.execute(globalSize); + kernel.dispose(); + } + + if (testIndicesToRun.contains(1)) { + if (verbose) { + System.out.println(); + System.out.println("Testing default KernelPreferences with kernel which cannot be run in OpenCL, without fallback algorithm"); + System.out.println(); + } + kernel = new KernelWithoutAlternateFallbackAlgorithm(); + kernel.execute(globalSize); + kernel.dispose(); + } + + if (testIndicesToRun.contains(2)) { + if (verbose) { + System.out.println(); + System.out.println("Retesting previous case, should jump straight to regular java implementation without warnings"); + System.out.println(); + } + kernel = new KernelWithoutAlternateFallbackAlgorithm(); + kernel.execute(globalSize); + kernel.dispose(); + } + + if (testIndicesToRun.contains(3)) { + if (verbose) { + System.out.println(); + System.out.println("Testing default KernelPreferences with kernel which should be run in OpenCL"); + System.out.println(); + } + KernelOkayInOpenCL clKernel = new KernelOkayInOpenCL(); + kernel = clKernel; + kernel.execute(clKernel.inChars.length); + String result = new String(clKernel.outChars); + if (verbose) { + System.out.println("kernel output: " + result); + } + kernel.dispose(); + } + } +} diff --git a/src/main/java/com/aparapi/examples/configuration/CustomConfigurationDemo.java b/src/main/java/com/aparapi/examples/configuration/CustomConfigurationDemo.java index 86f30f71..6256bf05 100644 --- a/src/main/java/com/aparapi/examples/configuration/CustomConfigurationDemo.java +++ b/src/main/java/com/aparapi/examples/configuration/CustomConfigurationDemo.java @@ -1,52 +1,67 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.configuration; - -import com.aparapi.device.*; -import com.aparapi.internal.kernel.*; - -import java.util.*; - -/** - * Created by Barney on 31/08/2015. - */ -public class CustomConfigurationDemo { - - public static void main(String[] ignored) { - System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); - KernelManager manager = new KernelManager() { - @Override - protected List<Device.TYPE> getPreferredDeviceTypes() { - return Arrays.asList(Device.TYPE.CPU, Device.TYPE.ALT, Device.TYPE.JTP); - } - }; - KernelManager.setKernelManager(manager); - - System.out.println("\nTesting custom KernelPreferences with kernel, preferences choose CPU"); - KernelOkayInOpenCL kernel = new KernelOkayInOpenCL(); - kernel.execute(kernel.inChars.length); - System.out.println(kernel.outChars); - - System.out.println("\nTesting custom KernelPreferences with kernel, preferences specify CPU but kernel vetos CPU"); - kernel = new KernelOkayInOpenCL() { - @Override - public boolean isAllowDevice(Device _device) { - return _device.getType() != Device.TYPE.CPU; - } - }; - kernel.execute(kernel.inChars.length); - System.out.println(kernel.outChars); - - StringBuilder report = new StringBuilder("\n"); - KernelManager.instance().reportDeviceUsage(report, true); - System.out.println(report); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.configuration; + +import com.aparapi.device.*; +import com.aparapi.internal.kernel.*; + +import java.util.*; + +/** + * Created by Barney on 31/08/2015. + */ +public class CustomConfigurationDemo { + + public static void main(String[] ignored) { + System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); + KernelManager manager = new KernelManager() { + @Override + protected List<Device.TYPE> getPreferredDeviceTypes() { + return Arrays.asList(Device.TYPE.CPU, Device.TYPE.ALT, Device.TYPE.JTP); + } + }; + KernelManager.setKernelManager(manager); + + System.out.println("\nTesting custom KernelPreferences with kernel, preferences choose CPU"); + KernelOkayInOpenCL kernel = new KernelOkayInOpenCL(); + kernel.execute(kernel.inChars.length); + System.out.println(kernel.outChars); + + System.out.println("\nTesting custom KernelPreferences with kernel, preferences specify CPU but kernel vetos CPU"); + kernel = new KernelOkayInOpenCL() { + @Override + public boolean isAllowDevice(Device _device) { + return _device.getType() != Device.TYPE.CPU; + } + }; + kernel.execute(kernel.inChars.length); + System.out.println(kernel.outChars); + + StringBuilder report = new StringBuilder("\n"); + KernelManager.instance().reportDeviceUsage(report, true); + System.out.println(report); + } +} diff --git a/src/main/java/com/aparapi/examples/configuration/KernelOkayInOpenCL.java b/src/main/java/com/aparapi/examples/configuration/KernelOkayInOpenCL.java index 1e6dc5f8..725145b3 100644 --- a/src/main/java/com/aparapi/examples/configuration/KernelOkayInOpenCL.java +++ b/src/main/java/com/aparapi/examples/configuration/KernelOkayInOpenCL.java @@ -1,31 +1,46 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.configuration; - -/** - * Created by Barney on 24/08/2015. - */ -public class KernelOkayInOpenCL extends com.aparapi.Kernel { - char[] inChars = "KernelOkayInOpenCL".toCharArray(); - char[] outChars = new char[inChars.length]; - - @Override - public void run() { - int index = getGlobalId(); - oops(); - outChars[index] = inChars[index]; - } - - @NoCL - private void oops() { - System.out.println("Oops, running in kernel in Java"); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.configuration; + +/** + * Created by Barney on 24/08/2015. + */ +public class KernelOkayInOpenCL extends com.aparapi.Kernel { + char[] inChars = "KernelOkayInOpenCL".toCharArray(); + char[] outChars = new char[inChars.length]; + + @Override + public void run() { + int index = getGlobalId(); + oops(); + outChars[index] = inChars[index]; + } + + @NoCL + private void oops() { + System.out.println("Oops, running in kernel in Java"); + } +} diff --git a/src/main/java/com/aparapi/examples/configuration/KernelWithAlternateFallbackAlgorithm.java b/src/main/java/com/aparapi/examples/configuration/KernelWithAlternateFallbackAlgorithm.java index e7d4cb59..cac9b5ef 100644 --- a/src/main/java/com/aparapi/examples/configuration/KernelWithAlternateFallbackAlgorithm.java +++ b/src/main/java/com/aparapi/examples/configuration/KernelWithAlternateFallbackAlgorithm.java @@ -1,34 +1,49 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.configuration; - -import com.aparapi.*; - -/** - * Kernel which will always fail to run on an OpenCLDevice but has an alternative fallback algorithm. - */ -public class KernelWithAlternateFallbackAlgorithm extends Kernel { - @Override - public void run() { - // deliberately, will fail to generate OpenCL as println is unsupported - System.out.println("Running in Java (regular algorithm)"); - } - - @Override - public boolean hasFallbackAlgorithm() { - return true; - } - - @Override - public void executeFallbackAlgorithm(Range _range, int _passes) { - System.out.println("Running in Java (alternate non-parallel algorithm)"); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.configuration; + +import com.aparapi.*; + +/** + * Kernel which will always fail to run on an OpenCLDevice but has an alternative fallback algorithm. + */ +public class KernelWithAlternateFallbackAlgorithm extends Kernel { + @Override + public void run() { + // deliberately, will fail to generate OpenCL as println is unsupported + System.out.println("Running in Java (regular algorithm)"); + } + + @Override + public boolean hasFallbackAlgorithm() { + return true; + } + + @Override + public void executeFallbackAlgorithm(Range _range, int _passes) { + System.out.println("Running in Java (alternate non-parallel algorithm)"); + } +} diff --git a/src/main/java/com/aparapi/examples/configuration/KernelWithoutAlternateFallbackAlgorithm.java b/src/main/java/com/aparapi/examples/configuration/KernelWithoutAlternateFallbackAlgorithm.java index 8253af72..0149d4ea 100644 --- a/src/main/java/com/aparapi/examples/configuration/KernelWithoutAlternateFallbackAlgorithm.java +++ b/src/main/java/com/aparapi/examples/configuration/KernelWithoutAlternateFallbackAlgorithm.java @@ -1,24 +1,39 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.configuration; - -import com.aparapi.*; - -/** - * Kernel which will always fail to run on an OpenCLDevice but has an alternative fallback algorithm. - */ -public class KernelWithoutAlternateFallbackAlgorithm extends Kernel { - @Override - public void run() { - // deliberately, will fail to generate OpenCL as println is unsupported - System.out.println("Running in Java (regular algorithm)"); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.configuration; + +import com.aparapi.*; + +/** + * Kernel which will always fail to run on an OpenCLDevice but has an alternative fallback algorithm. + */ +public class KernelWithoutAlternateFallbackAlgorithm extends Kernel { + @Override + public void run() { + // deliberately, will fail to generate OpenCL as println is unsupported + System.out.println("Running in Java (regular algorithm)"); + } +} diff --git a/src/main/java/com/aparapi/examples/configuration/LegacyConfigurationDemo.java b/src/main/java/com/aparapi/examples/configuration/LegacyConfigurationDemo.java index 02f8bfa7..2e55c983 100644 --- a/src/main/java/com/aparapi/examples/configuration/LegacyConfigurationDemo.java +++ b/src/main/java/com/aparapi/examples/configuration/LegacyConfigurationDemo.java @@ -1,36 +1,51 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.configuration; - -import com.aparapi.*; -import com.aparapi.internal.kernel.*; - -/** - * Tests device selection when circumventing the {@link com.aparapi.internal.kernel.KernelManager} by using the legacy mechanism - * (setExecutionMode, etc.). - */ -public class LegacyConfigurationDemo { - - @SuppressWarnings("deprecation") - public static void main(String[] ignored) { - System.setProperty("com.aparapi.executionMode", "GPU,CPU,SEQ"); - System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); - - KernelWithAlternateFallbackAlgorithm kernel = new KernelWithAlternateFallbackAlgorithm(); - kernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); - int globalRange = 1; - kernel.execute(globalRange); - - StringBuilder report = new StringBuilder("\n"); - KernelManager.instance().reportDeviceUsage(report, true); - System.out.println(report); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.configuration; + +import com.aparapi.*; +import com.aparapi.internal.kernel.*; + +/** + * Tests device selection when circumventing the {@link com.aparapi.internal.kernel.KernelManager} by using the legacy mechanism + * (setExecutionMode, etc.). + */ +public class LegacyConfigurationDemo { + + @SuppressWarnings("deprecation") + public static void main(String[] ignored) { + System.setProperty("com.aparapi.executionMode", "GPU,CPU,SEQ"); + System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); + + KernelWithAlternateFallbackAlgorithm kernel = new KernelWithAlternateFallbackAlgorithm(); + kernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); + int globalRange = 1; + kernel.execute(globalRange); + + StringBuilder report = new StringBuilder("\n"); + KernelManager.instance().reportDeviceUsage(report, true); + System.out.println(report); + } +} diff --git a/src/main/java/com/aparapi/examples/configuration/ProfilingDemo.java b/src/main/java/com/aparapi/examples/configuration/ProfilingDemo.java index 5bb76f50..ce56ce55 100644 --- a/src/main/java/com/aparapi/examples/configuration/ProfilingDemo.java +++ b/src/main/java/com/aparapi/examples/configuration/ProfilingDemo.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/configuration/ProfilingDemoNoBinaryCaching.java b/src/main/java/com/aparapi/examples/configuration/ProfilingDemoNoBinaryCaching.java index ca0c36a8..47d8ff24 100644 --- a/src/main/java/com/aparapi/examples/configuration/ProfilingDemoNoBinaryCaching.java +++ b/src/main/java/com/aparapi/examples/configuration/ProfilingDemoNoBinaryCaching.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/convolution/ConvMatrix3x3Editor.java b/src/main/java/com/aparapi/examples/convolution/ConvMatrix3x3Editor.java index 9c0abc0c..eb61007c 100644 --- a/src/main/java/com/aparapi/examples/convolution/ConvMatrix3x3Editor.java +++ b/src/main/java/com/aparapi/examples/convolution/ConvMatrix3x3Editor.java @@ -1,161 +1,176 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.convolution; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Arrays; - -import javax.swing.BoxLayout; -import javax.swing.JComboBox; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -public class ConvMatrix3x3Editor{ - Component component; - - float[] default3x3; - - float[] none3x3 = new float[] { - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0 - }; - - float[] blur3x3 = new float[] { - .1f, - .1f, - .1f, - .1f, - .1f, - .1f, - .1f, - .1f, - .1f - }; - - JSpinner[] spinners = new JSpinner[9]; - - protected void updated(float[] _convMatrix3x3) { - - }; - - void set(float[] _to, float[] _from) { - for (int i = 0; i < 9; i++) { - _to[i] = _from[i]; - spinners[i].setValue((Double) (double) _to[i]); - - } - updated(_to); - } - - ConvMatrix3x3Editor(final float[] _convMatrix3x3) { - default3x3 = Arrays.copyOf(_convMatrix3x3, _convMatrix3x3.length); - JPanel leftPanel = new JPanel(); - JPanel controlPanel = new JPanel(); - BoxLayout layout = new BoxLayout(controlPanel, BoxLayout.Y_AXIS); - controlPanel.setLayout(layout); - component = leftPanel; - JPanel grid3x3Panel = new JPanel(); - controlPanel.add(grid3x3Panel); - grid3x3Panel.setLayout(new GridLayout(3, 3)); - for (int i = 0; i < 9; i++) { - final int index = i; - SpinnerModel model = new SpinnerNumberModel(_convMatrix3x3[index], -50f, 50f, 1f); - JSpinner spinner = new JSpinner(model); - spinners[i] = spinner; - spinner.addChangeListener(new ChangeListener(){ - public void stateChanged(ChangeEvent ce) { - JSpinner source = (JSpinner) ce.getSource(); - double value = ((Double) source.getValue()); - _convMatrix3x3[index] = (float) value; - updated(_convMatrix3x3); - } - }); - grid3x3Panel.add(spinner); - } - String[] options = new String[] { - "DEFAULT", - "NONE", - "BLUR" - }; - JComboBox combo = new JComboBox(options); - combo.addActionListener(new ActionListener(){ - - @Override public void actionPerformed(ActionEvent e) { - JComboBox cb = (JComboBox) e.getSource(); - String value = (String) cb.getSelectedItem(); - if (value.equals("DEFAULT")) { - set(_convMatrix3x3, default3x3); - } else if (value.equals("NONE")) { - set(_convMatrix3x3, none3x3); - } else if (value.equals("BLUR")) { - set(_convMatrix3x3, blur3x3); - } - } - - }); - controlPanel.add(combo); - - leftPanel.add(controlPanel, BorderLayout.NORTH); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.convolution; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Arrays; + +import javax.swing.BoxLayout; +import javax.swing.JComboBox; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerModel; +import javax.swing.SpinnerNumberModel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +public class ConvMatrix3x3Editor{ + Component component; + + float[] default3x3; + + float[] none3x3 = new float[] { + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0 + }; + + float[] blur3x3 = new float[] { + .1f, + .1f, + .1f, + .1f, + .1f, + .1f, + .1f, + .1f, + .1f + }; + + JSpinner[] spinners = new JSpinner[9]; + + protected void updated(float[] _convMatrix3x3) { + + }; + + void set(float[] _to, float[] _from) { + for (int i = 0; i < 9; i++) { + _to[i] = _from[i]; + spinners[i].setValue((Double) (double) _to[i]); + + } + updated(_to); + } + + ConvMatrix3x3Editor(final float[] _convMatrix3x3) { + default3x3 = Arrays.copyOf(_convMatrix3x3, _convMatrix3x3.length); + JPanel leftPanel = new JPanel(); + JPanel controlPanel = new JPanel(); + BoxLayout layout = new BoxLayout(controlPanel, BoxLayout.Y_AXIS); + controlPanel.setLayout(layout); + component = leftPanel; + JPanel grid3x3Panel = new JPanel(); + controlPanel.add(grid3x3Panel); + grid3x3Panel.setLayout(new GridLayout(3, 3)); + for (int i = 0; i < 9; i++) { + final int index = i; + SpinnerModel model = new SpinnerNumberModel(_convMatrix3x3[index], -50f, 50f, 1f); + JSpinner spinner = new JSpinner(model); + spinners[i] = spinner; + spinner.addChangeListener(new ChangeListener(){ + public void stateChanged(ChangeEvent ce) { + JSpinner source = (JSpinner) ce.getSource(); + double value = ((Double) source.getValue()); + _convMatrix3x3[index] = (float) value; + updated(_convMatrix3x3); + } + }); + grid3x3Panel.add(spinner); + } + String[] options = new String[] { + "DEFAULT", + "NONE", + "BLUR" + }; + JComboBox combo = new JComboBox(options); + combo.addActionListener(new ActionListener(){ + + @Override public void actionPerformed(ActionEvent e) { + JComboBox cb = (JComboBox) e.getSource(); + String value = (String) cb.getSelectedItem(); + if (value.equals("DEFAULT")) { + set(_convMatrix3x3, default3x3); + } else if (value.equals("NONE")) { + set(_convMatrix3x3, none3x3); + } else if (value.equals("BLUR")) { + set(_convMatrix3x3, blur3x3); + } + } + + }); + controlPanel.add(combo); + + leftPanel.add(controlPanel, BorderLayout.NORTH); + } +} diff --git a/src/main/java/com/aparapi/examples/convolution/Convolution.java b/src/main/java/com/aparapi/examples/convolution/Convolution.java index c7ed5495..29ffe62f 100644 --- a/src/main/java/com/aparapi/examples/convolution/Convolution.java +++ b/src/main/java/com/aparapi/examples/convolution/Convolution.java @@ -1,130 +1,145 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - - */ - -package com.aparapi.examples.convolution; - -import com.aparapi.*; - -import java.io.*; - -public class Convolution { - - public static void main(final String[] _args) throws IOException { - - final File file = new File(_args.length == 1 ? _args[0] : "./src/main/resources/testcard.jpg").getCanonicalFile(); - - final ImageConvolution convolution = new ImageConvolution(); - - final float convMatrix3x3[] = new float[] { - 0f, - -10f, - 0f, - -10f, - 40f, - -10f, - 0f, - -10f, - 0f, - }; - - new ConvolutionViewer(file, convMatrix3x3) { - - private static final long serialVersionUID = 7858079467616904028L; - - @Override - protected void applyConvolution(float[] _convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, - int _height) { - convolution.applyConvolution(_convMatrix3x3, _inBytes, _outBytes, _width, _height); - } - }; - } - - final static class ImageConvolution extends Kernel { - - private float convMatrix3x3[]; - - private int width, height; - - private byte imageIn[], imageOut[]; - - public void processPixel(int x, int y, int w, int h) { - float accum = 0f; - int count = 0; - for (int dx = -3; dx < 6; dx += 3) { - for (int dy = -1; dy < 2; dy += 1) { - final int rgb = 0xff & imageIn[((y + dy) * w) + (x + dx)]; - - accum += rgb * convMatrix3x3[count++]; - } - } - final byte value = (byte) (max(0, min((int) accum, 255))); - imageOut[(y * w) + x] = value; - - } - - @Override - public void run() { - final int x = getGlobalId(0) % (width * 3); - final int y = getGlobalId(0) / (width * 3); - - if ((x > 3) && (x < ((width * 3) - 3)) && (y > 1) && (y < (height - 1))) { - processPixel(x, y, width * 3, height); - } - - } - - public void applyConvolution(float[] _convMatrix3x3, byte[] _imageIn, byte[] _imageOut, int _width, int _height) { - imageIn = _imageIn; - imageOut = _imageOut; - width = _width; - height = _height; - convMatrix3x3 = _convMatrix3x3; - execute(3 * width * height); - } - } +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + + */ + +package com.aparapi.examples.convolution; + +import com.aparapi.*; + +import java.io.*; + +public class Convolution { + + public static void main(final String[] _args) throws IOException { + + final File file = new File(_args.length == 1 ? _args[0] : "./src/main/resources/testcard.jpg").getCanonicalFile(); + + final ImageConvolution convolution = new ImageConvolution(); + + final float convMatrix3x3[] = new float[] { + 0f, + -10f, + 0f, + -10f, + 40f, + -10f, + 0f, + -10f, + 0f, + }; + + new ConvolutionViewer(file, convMatrix3x3) { + + private static final long serialVersionUID = 7858079467616904028L; + + @Override + protected void applyConvolution(float[] _convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, + int _height) { + convolution.applyConvolution(_convMatrix3x3, _inBytes, _outBytes, _width, _height); + } + }; + } + + final static class ImageConvolution extends Kernel { + + private float convMatrix3x3[]; + + private int width, height; + + private byte imageIn[], imageOut[]; + + public void processPixel(int x, int y, int w, int h) { + float accum = 0f; + int count = 0; + for (int dx = -3; dx < 6; dx += 3) { + for (int dy = -1; dy < 2; dy += 1) { + final int rgb = 0xff & imageIn[((y + dy) * w) + (x + dx)]; + + accum += rgb * convMatrix3x3[count++]; + } + } + final byte value = (byte) (max(0, min((int) accum, 255))); + imageOut[(y * w) + x] = value; + + } + + @Override + public void run() { + final int x = getGlobalId(0) % (width * 3); + final int y = getGlobalId(0) / (width * 3); + + if ((x > 3) && (x < ((width * 3) - 3)) && (y > 1) && (y < (height - 1))) { + processPixel(x, y, width * 3, height); + } + + } + + public void applyConvolution(float[] _convMatrix3x3, byte[] _imageIn, byte[] _imageOut, int _width, int _height) { + imageIn = _imageIn; + imageOut = _imageOut; + width = _width; + height = _height; + convMatrix3x3 = _convMatrix3x3; + execute(3 * width * height); + } + } } \ No newline at end of file diff --git a/src/main/java/com/aparapi/examples/convolution/ConvolutionOpenCL.java b/src/main/java/com/aparapi/examples/convolution/ConvolutionOpenCL.java index 588a60e8..676ed4f2 100644 --- a/src/main/java/com/aparapi/examples/convolution/ConvolutionOpenCL.java +++ b/src/main/java/com/aparapi/examples/convolution/ConvolutionOpenCL.java @@ -1,102 +1,117 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.convolution; - -import com.aparapi.*; -import com.aparapi.device.*; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.*; -import com.aparapi.opencl.OpenCL.*; - -import java.io.*; - -public class ConvolutionOpenCL{ - - @Resource("com/aparapi/examples/convolution/convolution.cl") interface Convolution extends OpenCL<Convolution>{ - Convolution applyConvolution(// - Range range, // - @GlobalReadOnly("_convMatrix3x3") float[] _convMatrix3x3,//// only read from kernel - @GlobalReadOnly("_imagIn") byte[] _imageIn,// only read from kernel (actually char[]) - @GlobalWriteOnly("_imagOut") byte[] _imageOut, // only written to (never read) from kernel (actually char[]) - @Arg("_width") int _width,// - @Arg("_height") int _height); - } - - public static void main(final String[] _args) { - final File file = new File(_args.length == 1 ? _args[0] : "./src/main/resources/testcard.jpg"); - - final OpenCLDevice openclDevice = (OpenCLDevice) KernelManager.instance().bestDevice(); - - final Convolution convolution = openclDevice.bind(Convolution.class); - final float convMatrix3x3[] = new float[] { - 0f, - -10f, - 0f, - -10f, - 40f, - -10f, - 0f, - -10f, - 0f, - }; - - new ConvolutionViewer(file, convMatrix3x3){ - Range range = null; - - @Override protected void applyConvolution(float[] _convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, - int _height) { - if (range == null) { - range = openclDevice.createRange(_width * _height * 3); - } - - convolution.applyConvolution(range, _convMatrix3x3, _inBytes, _outBytes, _width, _height); - } - }; - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.convolution; + +import com.aparapi.*; +import com.aparapi.device.*; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.*; +import com.aparapi.opencl.OpenCL.*; + +import java.io.*; + +public class ConvolutionOpenCL{ + + @Resource("com/aparapi/examples/convolution/convolution.cl") interface Convolution extends OpenCL<Convolution>{ + Convolution applyConvolution(// + Range range, // + @GlobalReadOnly("_convMatrix3x3") float[] _convMatrix3x3,//// only read from kernel + @GlobalReadOnly("_imagIn") byte[] _imageIn,// only read from kernel (actually char[]) + @GlobalWriteOnly("_imagOut") byte[] _imageOut, // only written to (never read) from kernel (actually char[]) + @Arg("_width") int _width,// + @Arg("_height") int _height); + } + + public static void main(final String[] _args) { + final File file = new File(_args.length == 1 ? _args[0] : "./src/main/resources/testcard.jpg"); + + final OpenCLDevice openclDevice = (OpenCLDevice) KernelManager.instance().bestDevice(); + + final Convolution convolution = openclDevice.bind(Convolution.class); + final float convMatrix3x3[] = new float[] { + 0f, + -10f, + 0f, + -10f, + 40f, + -10f, + 0f, + -10f, + 0f, + }; + + new ConvolutionViewer(file, convMatrix3x3){ + Range range = null; + + @Override protected void applyConvolution(float[] _convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, + int _height) { + if (range == null) { + range = openclDevice.createRange(_width * _height * 3); + } + + convolution.applyConvolution(range, _convMatrix3x3, _inBytes, _outBytes, _width, _height); + } + }; + } +} diff --git a/src/main/java/com/aparapi/examples/convolution/ConvolutionViewer.java b/src/main/java/com/aparapi/examples/convolution/ConvolutionViewer.java index 53cc34c1..71f185f1 100644 --- a/src/main/java/com/aparapi/examples/convolution/ConvolutionViewer.java +++ b/src/main/java/com/aparapi/examples/convolution/ConvolutionViewer.java @@ -1,141 +1,156 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.convolution; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferByte; -import java.io.File; -import java.io.IOException; - -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.WindowConstants; - -@SuppressWarnings("serial") public abstract class ConvolutionViewer extends JFrame{ - - private int height; - - private int width; - - private BufferedImage outputImage; - - private BufferedImage inputImage; - - private byte[] inBytes; - - private byte[] outBytes; - - private Graphics2D gc; - - private float[] convMatrix3x3; - - public ConvolutionViewer(File _file, float[] _convMatrix3x3) { - - JFrame frame = new JFrame("Convolution Viewer"); - - convMatrix3x3 = _convMatrix3x3; - try { - inputImage = ImageIO.read(_file); - - // System.out.println(inputImage); - - height = inputImage.getHeight(); - - width = inputImage.getWidth(); - - outputImage = new BufferedImage(width, height, inputImage.getType()); - - gc = outputImage.createGraphics(); - - inBytes = ((DataBufferByte) inputImage.getRaster().getDataBuffer()).getData(); - outBytes = ((DataBufferByte) outputImage.getRaster().getDataBuffer()).getData(); - - final JLabel imageLabel = new JLabel(); - imageLabel.setIcon(new ImageIcon(outputImage)); - - ConvMatrix3x3Editor editor = new ConvMatrix3x3Editor(_convMatrix3x3){ - @Override protected void updated(float[] _convMatrix3x3) { - convMatrix3x3 = _convMatrix3x3; - long start = System.currentTimeMillis(); - - applyConvolution(convMatrix3x3, inBytes, outBytes, width, height); - long end = System.currentTimeMillis(); - gc.setColor(Color.BLACK); - gc.fillRect(0, 0, 50, 40); - gc.setColor(Color.YELLOW); - gc.drawString("" + (end - start) + "ms", 10, 20); - - imageLabel.repaint(); - } - }; - frame.getContentPane().add(editor.component, BorderLayout.WEST); - - frame.getContentPane().add(imageLabel, BorderLayout.CENTER); - frame.pack(); - frame.setVisible(true); - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - - applyConvolution(convMatrix3x3, inBytes, outBytes, width, height); - - imageLabel.repaint(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - } - - abstract protected void applyConvolution(float[] convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, int _height); - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.convolution; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferByte; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.WindowConstants; + +@SuppressWarnings("serial") public abstract class ConvolutionViewer extends JFrame{ + + private int height; + + private int width; + + private BufferedImage outputImage; + + private BufferedImage inputImage; + + private byte[] inBytes; + + private byte[] outBytes; + + private Graphics2D gc; + + private float[] convMatrix3x3; + + public ConvolutionViewer(File _file, float[] _convMatrix3x3) { + + JFrame frame = new JFrame("Convolution Viewer"); + + convMatrix3x3 = _convMatrix3x3; + try { + inputImage = ImageIO.read(_file); + + // System.out.println(inputImage); + + height = inputImage.getHeight(); + + width = inputImage.getWidth(); + + outputImage = new BufferedImage(width, height, inputImage.getType()); + + gc = outputImage.createGraphics(); + + inBytes = ((DataBufferByte) inputImage.getRaster().getDataBuffer()).getData(); + outBytes = ((DataBufferByte) outputImage.getRaster().getDataBuffer()).getData(); + + final JLabel imageLabel = new JLabel(); + imageLabel.setIcon(new ImageIcon(outputImage)); + + ConvMatrix3x3Editor editor = new ConvMatrix3x3Editor(_convMatrix3x3){ + @Override protected void updated(float[] _convMatrix3x3) { + convMatrix3x3 = _convMatrix3x3; + long start = System.currentTimeMillis(); + + applyConvolution(convMatrix3x3, inBytes, outBytes, width, height); + long end = System.currentTimeMillis(); + gc.setColor(Color.BLACK); + gc.fillRect(0, 0, 50, 40); + gc.setColor(Color.YELLOW); + gc.drawString("" + (end - start) + "ms", 10, 20); + + imageLabel.repaint(); + } + }; + frame.getContentPane().add(editor.component, BorderLayout.WEST); + + frame.getContentPane().add(imageLabel, BorderLayout.CENTER); + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + applyConvolution(convMatrix3x3, inBytes, outBytes, width, height); + + imageLabel.repaint(); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + } + + abstract protected void applyConvolution(float[] convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, int _height); + +} diff --git a/src/main/java/com/aparapi/examples/convolution/PureJava.java b/src/main/java/com/aparapi/examples/convolution/PureJava.java index e76f313f..ab37dc03 100644 --- a/src/main/java/com/aparapi/examples/convolution/PureJava.java +++ b/src/main/java/com/aparapi/examples/convolution/PureJava.java @@ -1,127 +1,142 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.convolution; - -import java.io.File; - -import com.aparapi.Kernel; - -public class PureJava{ - - final static class ImageConvolution extends Kernel{ - private float convMatrix3x3[]; - - private int width, height; - - private byte imageIn[], imageOut[]; - - public void processPixel(int x, int y, int w, int h) { - float accum = 0f; - int count = 0; - for (int dx = -3; dx < 6; dx += 3) { - for (int dy = -1; dy < 2; dy += 1) { - int rgb = 0xff & imageIn[((y + dy) * w) + (x + dx)]; - - accum += rgb * convMatrix3x3[count++]; - } - } - byte value = (byte) (max(0, min((int) accum, 255))); - imageOut[y * w + x] = value; - - } - - @Override public void run() { - int x = getGlobalId(0) % (width * 3); - int y = getGlobalId(0) / (width * 3); - - if (x > 3 && x < (width * 3 - 3) && y > 1 && y < (height - 1)) { - processPixel(x, y, width * 3, height); - } - - } - - public void applyConvolution(float[] _convMatrix3x3, byte[] _imageIn, byte[] _imageOut, int _width, int _height) { - imageIn = _imageIn; - imageOut = _imageOut; - width = _width; - height = _height; - convMatrix3x3 = _convMatrix3x3; - - execute(3 * width * height); - } - - } - - public static void main(final String[] _args) { - File file = new File(_args.length == 1 ? _args[0] : "./src/main/resources/testcard.jpg"); - - final ImageConvolution convolution = new ImageConvolution(); - - float convMatrix3x3[] = new float[] { - 0f, - -10f, - 0f, - -10f, - 40f, - -10f, - 0f, - -10f, - 0f, - }; - - new ConvolutionViewer(file, convMatrix3x3){ - @Override protected void applyConvolution(float[] _convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, - int _height) { - convolution.applyConvolution(_convMatrix3x3, _inBytes, _outBytes, _width, _height); - } - }; - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.convolution; + +import java.io.File; + +import com.aparapi.Kernel; + +public class PureJava{ + + final static class ImageConvolution extends Kernel{ + private float convMatrix3x3[]; + + private int width, height; + + private byte imageIn[], imageOut[]; + + public void processPixel(int x, int y, int w, int h) { + float accum = 0f; + int count = 0; + for (int dx = -3; dx < 6; dx += 3) { + for (int dy = -1; dy < 2; dy += 1) { + int rgb = 0xff & imageIn[((y + dy) * w) + (x + dx)]; + + accum += rgb * convMatrix3x3[count++]; + } + } + byte value = (byte) (max(0, min((int) accum, 255))); + imageOut[y * w + x] = value; + + } + + @Override public void run() { + int x = getGlobalId(0) % (width * 3); + int y = getGlobalId(0) / (width * 3); + + if (x > 3 && x < (width * 3 - 3) && y > 1 && y < (height - 1)) { + processPixel(x, y, width * 3, height); + } + + } + + public void applyConvolution(float[] _convMatrix3x3, byte[] _imageIn, byte[] _imageOut, int _width, int _height) { + imageIn = _imageIn; + imageOut = _imageOut; + width = _width; + height = _height; + convMatrix3x3 = _convMatrix3x3; + + execute(3 * width * height); + } + + } + + public static void main(final String[] _args) { + File file = new File(_args.length == 1 ? _args[0] : "./src/main/resources/testcard.jpg"); + + final ImageConvolution convolution = new ImageConvolution(); + + float convMatrix3x3[] = new float[] { + 0f, + -10f, + 0f, + -10f, + 40f, + -10f, + 0f, + -10f, + 0f, + }; + + new ConvolutionViewer(file, convMatrix3x3){ + @Override protected void applyConvolution(float[] _convMatrix3x3, byte[] _inBytes, byte[] _outBytes, int _width, + int _height) { + convolution.applyConvolution(_convMatrix3x3, _inBytes, _outBytes, _width, _height); + } + }; + + } + +} diff --git a/src/main/java/com/aparapi/examples/effects/Main.java b/src/main/java/com/aparapi/examples/effects/Main.java index b64abba7..2b5f96e5 100644 --- a/src/main/java/com/aparapi/examples/effects/Main.java +++ b/src/main/java/com/aparapi/examples/effects/Main.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/extension/FFTExample.java b/src/main/java/com/aparapi/examples/extension/FFTExample.java index 2e9fcd3c..9651d57b 100644 --- a/src/main/java/com/aparapi/examples/extension/FFTExample.java +++ b/src/main/java/com/aparapi/examples/extension/FFTExample.java @@ -1,136 +1,151 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -import com.aparapi.*; -import com.aparapi.device.*; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.*; -import com.aparapi.opencl.OpenCL.*; - -import java.util.*; - -public class FFTExample{ - - @Resource("com/aparapi/examples/extension/fft.cl") interface FFT extends OpenCL<FFT>{ - - public FFT forward(// - Range _range,// - @GlobalReadWrite("real") float[] real,// - @GlobalReadWrite("imaginary") float[] imaginary// - ); - } - - static void fft(float[] x, float[] y) { - final short dir = 1; - final long m = 10; - int n, i, i1, j, k, i2, l, l1, l2; - double c1, c2, tx, ty, t1, t2, u1, u2, z; - - /* Calculate the number of points */ - n = 1; - for (i = 0; i < m; i++) { - n *= 2; - } - - /* Do the bit reversal */ - i2 = n >> 1; - j = 0; - for (i = 0; i < (n - 1); i++) { - if (i < j) { - tx = x[i]; - ty = y[i]; - x[i] = x[j]; - y[i] = y[j]; - x[j] = (float) tx; - y[j] = (float) ty; - } - k = i2; - while (k <= j) { - j -= k; - k >>= 1; - } - j += k; - } - - /* Compute the FFT */ - c1 = -1.0; - c2 = 0.0; - l2 = 1; - for (l = 0; l < m; l++) { - l1 = l2; - l2 <<= 1; - u1 = 1.0; - u2 = 0.0; - for (j = 0; j < l1; j++) { - for (i = j; i < n; i += l2) { - i1 = i + l1; - t1 = (u1 * x[i1]) - (u2 * y[i1]); - t2 = (u1 * y[i1]) + (u2 * x[i1]); - x[i1] = (float) (x[i] - t1); - y[i1] = (float) (y[i] - t2); - x[i] += (float) t1; - y[i] += (float) t2; - } - z = (u1 * c1) - (u2 * c2); - u2 = (u1 * c2) + (u2 * c1); - u1 = z; - } - c2 = Math.sqrt((1.0 - c1) / 2.0); - if (dir == 1) { - c2 = -c2; - } - c1 = Math.sqrt((1.0 + c1) / 2.0); - } - - /* Scaling for forward transform */ - /*if (dir == 1) { - for (i=0;i<n;i++) { - x[i] /= n; - y[i] /= n; - } - }*/ - - } - - public static void main(String[] args) { - final int LEN = 1024; - final float initial[] = new float[LEN]; - final float real[] = new float[LEN]; - final float imaginary[] = new float[LEN]; - final float referenceReal[] = Arrays.copyOf(real, real.length); - final float referenceImaginary[] = Arrays.copyOf(imaginary, imaginary.length); - final OpenCLDevice device = (OpenCLDevice) KernelManager.instance().getDefaultPreferences().getPreferredDevice(null); - final FFT fft = device.bind(FFT.class); - for (int i = 0; i < LEN; i++) { - initial[i] = real[i] = referenceReal[i] = (float) (Math.random() * 256); - imaginary[i] = referenceImaginary[0] = 0f; - } - - final Range range = device.createRange(64); - System.out.println("range=" + range); - - final StopWatch timer = new StopWatch(); - timer.start(); - fft.forward(range, real, imaginary); - timer.print("opencl"); - - timer.start(); - fft(referenceReal, referenceImaginary); - timer.print("java"); - for (int i = 0; i < LEN; i++) { - if (Math.abs(real[i] - referenceReal[i]) > 0.01) { - System.out.printf("%d %5.2f %5.2f %5.2f\n", i, initial[i], real[i], referenceReal[i]); - } - } - - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +import com.aparapi.*; +import com.aparapi.device.*; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.*; +import com.aparapi.opencl.OpenCL.*; + +import java.util.*; + +public class FFTExample{ + + @Resource("com/aparapi/examples/extension/fft.cl") interface FFT extends OpenCL<FFT>{ + + public FFT forward(// + Range _range,// + @GlobalReadWrite("real") float[] real,// + @GlobalReadWrite("imaginary") float[] imaginary// + ); + } + + static void fft(float[] x, float[] y) { + final short dir = 1; + final long m = 10; + int n, i, i1, j, k, i2, l, l1, l2; + double c1, c2, tx, ty, t1, t2, u1, u2, z; + + /* Calculate the number of points */ + n = 1; + for (i = 0; i < m; i++) { + n *= 2; + } + + /* Do the bit reversal */ + i2 = n >> 1; + j = 0; + for (i = 0; i < (n - 1); i++) { + if (i < j) { + tx = x[i]; + ty = y[i]; + x[i] = x[j]; + y[i] = y[j]; + x[j] = (float) tx; + y[j] = (float) ty; + } + k = i2; + while (k <= j) { + j -= k; + k >>= 1; + } + j += k; + } + + /* Compute the FFT */ + c1 = -1.0; + c2 = 0.0; + l2 = 1; + for (l = 0; l < m; l++) { + l1 = l2; + l2 <<= 1; + u1 = 1.0; + u2 = 0.0; + for (j = 0; j < l1; j++) { + for (i = j; i < n; i += l2) { + i1 = i + l1; + t1 = (u1 * x[i1]) - (u2 * y[i1]); + t2 = (u1 * y[i1]) + (u2 * x[i1]); + x[i1] = (float) (x[i] - t1); + y[i1] = (float) (y[i] - t2); + x[i] += (float) t1; + y[i] += (float) t2; + } + z = (u1 * c1) - (u2 * c2); + u2 = (u1 * c2) + (u2 * c1); + u1 = z; + } + c2 = Math.sqrt((1.0 - c1) / 2.0); + if (dir == 1) { + c2 = -c2; + } + c1 = Math.sqrt((1.0 + c1) / 2.0); + } + + /* Scaling for forward transform */ + /*if (dir == 1) { + for (i=0;i<n;i++) { + x[i] /= n; + y[i] /= n; + } + }*/ + + } + + public static void main(String[] args) { + final int LEN = 1024; + final float initial[] = new float[LEN]; + final float real[] = new float[LEN]; + final float imaginary[] = new float[LEN]; + final float referenceReal[] = Arrays.copyOf(real, real.length); + final float referenceImaginary[] = Arrays.copyOf(imaginary, imaginary.length); + final OpenCLDevice device = (OpenCLDevice) KernelManager.instance().getDefaultPreferences().getPreferredDevice(null); + final FFT fft = device.bind(FFT.class); + for (int i = 0; i < LEN; i++) { + initial[i] = real[i] = referenceReal[i] = (float) (Math.random() * 256); + imaginary[i] = referenceImaginary[0] = 0f; + } + + final Range range = device.createRange(64); + System.out.println("range=" + range); + + final StopWatch timer = new StopWatch(); + timer.start(); + fft.forward(range, real, imaginary); + timer.print("opencl"); + + timer.start(); + fft(referenceReal, referenceImaginary); + timer.print("java"); + for (int i = 0; i < LEN; i++) { + if (Math.abs(real[i] - referenceReal[i]) > 0.01) { + System.out.printf("%d %5.2f %5.2f %5.2f\n", i, initial[i], real[i], referenceReal[i]); + } + } + + } +} diff --git a/src/main/java/com/aparapi/examples/extension/Histogram.java b/src/main/java/com/aparapi/examples/extension/Histogram.java index 0cdba98f..87ae8fd3 100644 --- a/src/main/java/com/aparapi/examples/extension/Histogram.java +++ b/src/main/java/com/aparapi/examples/extension/Histogram.java @@ -1,106 +1,121 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -import com.aparapi.Kernel; -import com.aparapi.Range; -import com.aparapi.device.Device; -import com.aparapi.device.OpenCLDevice; -import com.aparapi.opencl.OpenCL; -import com.aparapi.opencl.OpenCL.Resource; - -public class Histogram{ - - @Resource("com/aparapi/examples/extension/HistogramKernel.cl") interface HistogramKernel extends OpenCL<HistogramKernel>{ - - public HistogramKernel histogram256(// - Range _range,// - @GlobalReadOnly("data") byte[] data,// - @Local("sharedArray") byte[] sharedArray,// - @GlobalWriteOnly("binResult") int[] binResult,// - @Arg("binSize") int binSize); - - public HistogramKernel bin256(// - Range _range,// - @GlobalWriteOnly("histo") int[] histo,// - @GlobalReadOnly("binResult") int[] binResult,// - @Arg("subHistogramSize") int subHistogramSize); - } - - public static void main(String[] args) { - final int WIDTH = 1024 * 16; - final int HEIGHT = 1024 * 8; - final int BIN_SIZE = 128; - final int GROUP_SIZE = 128; - final int SUB_HISTOGRAM_COUNT = ((WIDTH * HEIGHT) / (GROUP_SIZE * BIN_SIZE)); - - final byte[] data = new byte[WIDTH * HEIGHT]; - for (int i = 0; i < (WIDTH * HEIGHT); i++) { - data[i] = (byte) ((Math.random() * BIN_SIZE) / 2); - } - final byte[] sharedArray = new byte[GROUP_SIZE * BIN_SIZE]; - final int[] binResult = new int[SUB_HISTOGRAM_COUNT * BIN_SIZE]; - System.out.println("binResult size=" + binResult.length); - final int[] histo = new int[BIN_SIZE]; - final int[] refHisto = new int[BIN_SIZE]; - final Kernel k = new Kernel(){ - - @Override public void run() { - final int j = getGlobalId(0); - for (int i = 0; i < SUB_HISTOGRAM_COUNT; ++i) { - histo[j] += binResult[(i * BIN_SIZE) + j]; - } - } - - }; - final Device device = k.getTargetDevice(); - final Range range2 = device.createRange(BIN_SIZE); - k.execute(range2); - - final Range range = Range.create((WIDTH * HEIGHT) / BIN_SIZE, GROUP_SIZE); - - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - final HistogramKernel histogram = openclDevice.bind(HistogramKernel.class); - - final StopWatch timer = new StopWatch(); - timer.start(); - - histogram.histogram256(range, data, sharedArray, binResult, BIN_SIZE); - final boolean java = false; - final boolean aparapiKernel = false; - if (java) { - // Calculate final histogram bin - for (int j = 0; j < BIN_SIZE; ++j) { - for (int i = 0; i < SUB_HISTOGRAM_COUNT; ++i) { - histo[j] += binResult[(i * BIN_SIZE) + j]; - } - } - } else if (aparapiKernel) { - k.execute(range2); - } else { - histogram.bin256(range2, histo, binResult, SUB_HISTOGRAM_COUNT); - } - timer.print("opencl"); - timer.start(); - for (int i = 0; i < (WIDTH * HEIGHT); i++) { - refHisto[data[i]]++; - } - timer.print("java"); - for (int i = 0; i < 128; i++) { - if (refHisto[i] != histo[i]) { - System.out.println(i + " " + histo[i] + " " + refHisto[i]); - } - } - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +import com.aparapi.Kernel; +import com.aparapi.Range; +import com.aparapi.device.Device; +import com.aparapi.device.OpenCLDevice; +import com.aparapi.opencl.OpenCL; +import com.aparapi.opencl.OpenCL.Resource; + +public class Histogram{ + + @Resource("com/aparapi/examples/extension/HistogramKernel.cl") interface HistogramKernel extends OpenCL<HistogramKernel>{ + + public HistogramKernel histogram256(// + Range _range,// + @GlobalReadOnly("data") byte[] data,// + @Local("sharedArray") byte[] sharedArray,// + @GlobalWriteOnly("binResult") int[] binResult,// + @Arg("binSize") int binSize); + + public HistogramKernel bin256(// + Range _range,// + @GlobalWriteOnly("histo") int[] histo,// + @GlobalReadOnly("binResult") int[] binResult,// + @Arg("subHistogramSize") int subHistogramSize); + } + + public static void main(String[] args) { + final int WIDTH = 1024 * 16; + final int HEIGHT = 1024 * 8; + final int BIN_SIZE = 128; + final int GROUP_SIZE = 128; + final int SUB_HISTOGRAM_COUNT = ((WIDTH * HEIGHT) / (GROUP_SIZE * BIN_SIZE)); + + final byte[] data = new byte[WIDTH * HEIGHT]; + for (int i = 0; i < (WIDTH * HEIGHT); i++) { + data[i] = (byte) ((Math.random() * BIN_SIZE) / 2); + } + final byte[] sharedArray = new byte[GROUP_SIZE * BIN_SIZE]; + final int[] binResult = new int[SUB_HISTOGRAM_COUNT * BIN_SIZE]; + System.out.println("binResult size=" + binResult.length); + final int[] histo = new int[BIN_SIZE]; + final int[] refHisto = new int[BIN_SIZE]; + final Kernel k = new Kernel(){ + + @Override public void run() { + final int j = getGlobalId(0); + for (int i = 0; i < SUB_HISTOGRAM_COUNT; ++i) { + histo[j] += binResult[(i * BIN_SIZE) + j]; + } + } + + }; + final Device device = k.getTargetDevice(); + final Range range2 = device.createRange(BIN_SIZE); + k.execute(range2); + + final Range range = Range.create((WIDTH * HEIGHT) / BIN_SIZE, GROUP_SIZE); + + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + final HistogramKernel histogram = openclDevice.bind(HistogramKernel.class); + + final StopWatch timer = new StopWatch(); + timer.start(); + + histogram.histogram256(range, data, sharedArray, binResult, BIN_SIZE); + final boolean java = false; + final boolean aparapiKernel = false; + if (java) { + // Calculate final histogram bin + for (int j = 0; j < BIN_SIZE; ++j) { + for (int i = 0; i < SUB_HISTOGRAM_COUNT; ++i) { + histo[j] += binResult[(i * BIN_SIZE) + j]; + } + } + } else if (aparapiKernel) { + k.execute(range2); + } else { + histogram.bin256(range2, histo, binResult, SUB_HISTOGRAM_COUNT); + } + timer.print("opencl"); + timer.start(); + for (int i = 0; i < (WIDTH * HEIGHT); i++) { + refHisto[data[i]]++; + } + timer.print("java"); + for (int i = 0; i < 128; i++) { + if (refHisto[i] != histo[i]) { + System.out.println(i + " " + histo[i] + " " + refHisto[i]); + } + } + } + } +} diff --git a/src/main/java/com/aparapi/examples/extension/HistogramIdeal.java b/src/main/java/com/aparapi/examples/extension/HistogramIdeal.java index f72fe809..a70a23af 100644 --- a/src/main/java/com/aparapi/examples/extension/HistogramIdeal.java +++ b/src/main/java/com/aparapi/examples/extension/HistogramIdeal.java @@ -1,92 +1,107 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -import com.aparapi.Range; -import com.aparapi.device.Device; -import com.aparapi.device.OpenCLDevice; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.OpenCL; - -public class HistogramIdeal{ - - // @Resource("com/amd/aparapi/sample/extension/HistogramKernel.cl") - interface HistogramKernel extends OpenCL<HistogramKernel>{ - - public HistogramKernel histogram256(// - Range _range,// - @GlobalReadOnly("data") byte[] data,// - @Local("sharedArray") byte[] sharedArray,// - @GlobalWriteOnly("binResult") int[] binResult,// - @Arg("binSize") int binSize); - - public HistogramKernel bin256(// - Range _range,// - @GlobalWriteOnly("histo") int[] histo,// - @GlobalReadOnly("binResult") int[] binResult,// - @Arg("subHistogramSize") int subHistogramSize); - } - - public static void main(String[] args) { - final int WIDTH = 1024 * 16; - final int HEIGHT = 1024 * 8; - final int BIN_SIZE = 128; - final int GROUP_SIZE = 128; - final int SUB_HISTOGRAM_COUNT = ((WIDTH * HEIGHT) / (GROUP_SIZE * BIN_SIZE)); - - final byte[] data = new byte[WIDTH * HEIGHT]; - for (int i = 0; i < (WIDTH * HEIGHT); i++) { - data[i] = (byte) ((Math.random() * BIN_SIZE) / 2); - } - final byte[] sharedArray = new byte[GROUP_SIZE * BIN_SIZE]; - final int[] binResult = new int[SUB_HISTOGRAM_COUNT * BIN_SIZE]; - System.out.println("binResult size=" + binResult.length); - final int[] histo = new int[BIN_SIZE]; - final int[] refHisto = new int[BIN_SIZE]; - final Device device = KernelManager.instance().bestDevice(); - - if (device != null) { - System.out.println(((OpenCLDevice) device).getOpenCLPlatform().getName()); - final Range rangeBinSize = device.createRange(BIN_SIZE); - - final Range range = Range.create((WIDTH * HEIGHT) / BIN_SIZE, GROUP_SIZE); - - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - final HistogramKernel histogram = openclDevice.bind(HistogramKernel.class, Histogram.class.getClassLoader() - .getResourceAsStream("com/amd/aparapi/sample/extension/HistogramKernel.cl")); - long start = System.nanoTime(); - histogram.begin()// - .put(data)// - .histogram256(range, data, sharedArray, binResult, BIN_SIZE)// - // by leaving binResult on the GPU we can save two 1Mb transfers - .bin256(rangeBinSize, histo, binResult, SUB_HISTOGRAM_COUNT)// - .get(histo)// - .end(); - System.out.println("opencl " + ((System.nanoTime() - start) / 1000000)); - start = System.nanoTime(); - for (int i = 0; i < (WIDTH * HEIGHT); i++) { - refHisto[data[i]]++; - } - System.out.println("java " + ((System.nanoTime() - start) / 1000000)); - for (int i = 0; i < 128; i++) { - if (refHisto[i] != histo[i]) { - System.out.println(i + " " + histo[i] + " " + refHisto[i]); - } - } - - } - } else { - System.out.println("no GPU device"); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +import com.aparapi.Range; +import com.aparapi.device.Device; +import com.aparapi.device.OpenCLDevice; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.OpenCL; + +public class HistogramIdeal{ + + // @Resource("com/amd/aparapi/sample/extension/HistogramKernel.cl") + interface HistogramKernel extends OpenCL<HistogramKernel>{ + + public HistogramKernel histogram256(// + Range _range,// + @GlobalReadOnly("data") byte[] data,// + @Local("sharedArray") byte[] sharedArray,// + @GlobalWriteOnly("binResult") int[] binResult,// + @Arg("binSize") int binSize); + + public HistogramKernel bin256(// + Range _range,// + @GlobalWriteOnly("histo") int[] histo,// + @GlobalReadOnly("binResult") int[] binResult,// + @Arg("subHistogramSize") int subHistogramSize); + } + + public static void main(String[] args) { + final int WIDTH = 1024 * 16; + final int HEIGHT = 1024 * 8; + final int BIN_SIZE = 128; + final int GROUP_SIZE = 128; + final int SUB_HISTOGRAM_COUNT = ((WIDTH * HEIGHT) / (GROUP_SIZE * BIN_SIZE)); + + final byte[] data = new byte[WIDTH * HEIGHT]; + for (int i = 0; i < (WIDTH * HEIGHT); i++) { + data[i] = (byte) ((Math.random() * BIN_SIZE) / 2); + } + final byte[] sharedArray = new byte[GROUP_SIZE * BIN_SIZE]; + final int[] binResult = new int[SUB_HISTOGRAM_COUNT * BIN_SIZE]; + System.out.println("binResult size=" + binResult.length); + final int[] histo = new int[BIN_SIZE]; + final int[] refHisto = new int[BIN_SIZE]; + final Device device = KernelManager.instance().bestDevice(); + + if (device != null) { + System.out.println(((OpenCLDevice) device).getOpenCLPlatform().getName()); + final Range rangeBinSize = device.createRange(BIN_SIZE); + + final Range range = Range.create((WIDTH * HEIGHT) / BIN_SIZE, GROUP_SIZE); + + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + final HistogramKernel histogram = openclDevice.bind(HistogramKernel.class, Histogram.class.getClassLoader() + .getResourceAsStream("com/amd/aparapi/sample/extension/HistogramKernel.cl")); + long start = System.nanoTime(); + histogram.begin()// + .put(data)// + .histogram256(range, data, sharedArray, binResult, BIN_SIZE)// + // by leaving binResult on the GPU we can save two 1Mb transfers + .bin256(rangeBinSize, histo, binResult, SUB_HISTOGRAM_COUNT)// + .get(histo)// + .end(); + System.out.println("opencl " + ((System.nanoTime() - start) / 1000000)); + start = System.nanoTime(); + for (int i = 0; i < (WIDTH * HEIGHT); i++) { + refHisto[data[i]]++; + } + System.out.println("java " + ((System.nanoTime() - start) / 1000000)); + for (int i = 0; i < 128; i++) { + if (refHisto[i] != histo[i]) { + System.out.println(i + " " + histo[i] + " " + refHisto[i]); + } + } + + } + } else { + System.out.println("no GPU device"); + } + } +} diff --git a/src/main/java/com/aparapi/examples/extension/JavaMandelBrot.java b/src/main/java/com/aparapi/examples/extension/JavaMandelBrot.java index bb299d17..571f3741 100644 --- a/src/main/java/com/aparapi/examples/extension/JavaMandelBrot.java +++ b/src/main/java/com/aparapi/examples/extension/JavaMandelBrot.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/extension/JavaMandelBrotMultiThread.java b/src/main/java/com/aparapi/examples/extension/JavaMandelBrotMultiThread.java index 5dab1b4f..8564d9ea 100644 --- a/src/main/java/com/aparapi/examples/extension/JavaMandelBrotMultiThread.java +++ b/src/main/java/com/aparapi/examples/extension/JavaMandelBrotMultiThread.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/extension/Mandel.java b/src/main/java/com/aparapi/examples/extension/Mandel.java index 8a4c6c64..23c71880 100644 --- a/src/main/java/com/aparapi/examples/extension/Mandel.java +++ b/src/main/java/com/aparapi/examples/extension/Mandel.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/extension/MandelBrot.java b/src/main/java/com/aparapi/examples/extension/MandelBrot.java index c24e3dd4..03274dc8 100644 --- a/src/main/java/com/aparapi/examples/extension/MandelBrot.java +++ b/src/main/java/com/aparapi/examples/extension/MandelBrot.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/extension/MandelExample.java b/src/main/java/com/aparapi/examples/extension/MandelExample.java index bcf244ff..f0cbba06 100644 --- a/src/main/java/com/aparapi/examples/extension/MandelExample.java +++ b/src/main/java/com/aparapi/examples/extension/MandelExample.java @@ -1,251 +1,266 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.extension; - -import com.aparapi.*; -import com.aparapi.device.*; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.*; -import com.aparapi.opencl.OpenCL.*; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; -import java.util.concurrent.*; - -public class MandelExample{ - - /** User selected zoom-in point on the Mandelbrot view. */ - public static volatile Point to = null; - - public static MandelBrot mandelBrot = null; - - public static MandelBrot gpuMandelBrot = null; - - public static MandelBrot javaMandelBrot = null; - - public static MandelBrot javaMandelBrotMultiThread = null; - - // new JavaMandelBrot(); - //new JavaMandelBrotMultiThread(); - @SuppressWarnings("serial") public static void main(String[] _args) { - - final JFrame frame = new JFrame("MandelBrot"); - - /** Width of Mandelbrot view. */ - final int width = 768; - - /** Height of Mandelbrot view. */ - final int height = 768; - - /** Mandelbrot image height. */ - - /** Image for Mandelbrot view. */ - final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - - final Object framePaintedDoorBell = new Object(); - final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - - g.drawImage(image, 0, 0, width, height, this); - synchronized (framePaintedDoorBell) { - framePaintedDoorBell.notify(); - } - } - }; - - // Set the size of JComponent which displays Mandelbrot image - viewer.setPreferredSize(new Dimension(width, height)); - - final Object userClickDoorBell = new Object(); - - // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view - viewer.addMouseListener(new MouseAdapter(){ - @Override public void mouseClicked(MouseEvent e) { - to = e.getPoint(); - synchronized (userClickDoorBell) { - userClickDoorBell.notify(); - } - } - }); - - final JPanel controlPanel = new JPanel(new FlowLayout()); - - final String[] choices = new String[] { - "Java Sequential", - "Java Threads", - "GPU OpenCL" - }; - - final JComboBox startButton = new JComboBox(choices); - - startButton.addItemListener(new ItemListener(){ - @Override public void itemStateChanged(ItemEvent e) { - final String item = (String) startButton.getSelectedItem(); - - if (item.equals(choices[2])) { - mandelBrot = gpuMandelBrot; - } else if (item.equals(choices[0])) { - mandelBrot = javaMandelBrot; - } else if (item.equals(choices[1])) { - mandelBrot = javaMandelBrotMultiThread; - } - } - - }); - controlPanel.add(startButton); - - controlPanel.add(new JLabel("FPS")); - final JTextField framesPerSecondTextField = new JTextField("0", 5); - - controlPanel.add(framesPerSecondTextField); - - // Swing housework to create the frame - frame.getContentPane().add(viewer); - frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - - // Extract the underlying RGB buffer from the image. - // Pass this to the kernel so it operates directly on the RGB buffer of the image - - final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - - /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ - float scale = .0f; - - float offsetx = .0f; - - float offsety = .0f; - Device device = KernelManager.instance().bestDevice(); - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - System.out.println("max memory = " + openclDevice.getGlobalMemSize()); - System.out.println("max mem alloc size = " + openclDevice.getMaxMemAllocSize()); - gpuMandelBrot = openclDevice.bind(MandelBrot.class); - } - - javaMandelBrot = new JavaMandelBrot(); - javaMandelBrotMultiThread = new JavaMandelBrotMultiThread(); - mandelBrot = javaMandelBrot; - final float defaultScale = 3f; - scale = defaultScale; - offsetx = -1f; - offsety = 0f; - final Range range = device.createRange2D(width, height); - mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); - viewer.repaint(); - - // Window listener to dispose Kernel resources on user exit. - frame.addWindowListener(new WindowAdapter(){ - @Override public void windowClosing(WindowEvent _windowEvent) { - // mandelBrot.dispose(); - System.exit(0); - } - }); - - while (true) { - // Wait for the user to click somewhere - while (to == null) { - synchronized (userClickDoorBell) { - try { - userClickDoorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - } - - float x = -1f; - float y = 0f; - final float tox = ((float) (to.x - (width / 2)) / width) * scale; - final float toy = ((float) (to.y - (height / 2)) / height) * scale; - - // This is how many frames we will display as we zoom in and out. - final int frames = 128; - long startMillis = System.currentTimeMillis(); - int frameCount = 0; - for (int sign = -1; sign < 2; sign += 2) { - for (int i = 0; i < (frames - 4); i++) { - scale = scale + ((sign * defaultScale) / frames); - x = x - (sign * (tox / frames)); - y = y - (sign * (toy / frames)); - offsetx = x; - offsety = y; - mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); - viewer.repaint(); - synchronized (framePaintedDoorBell) { - try { - framePaintedDoorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - frameCount++; - final long endMillis = System.currentTimeMillis(); - final long elapsedMillis = endMillis - startMillis; - if (elapsedMillis > 1000) { - framesPerSecondTextField.setText("" + ((frameCount * 1000) / elapsedMillis)); - frameCount = 0; - startMillis = endMillis; - } - } - } - - // Reset zoom-in point. - to = null; - - } - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.extension; + +import com.aparapi.*; +import com.aparapi.device.*; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.*; +import com.aparapi.opencl.OpenCL.*; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import java.util.concurrent.*; + +public class MandelExample{ + + /** User selected zoom-in point on the Mandelbrot view. */ + public static volatile Point to = null; + + public static MandelBrot mandelBrot = null; + + public static MandelBrot gpuMandelBrot = null; + + public static MandelBrot javaMandelBrot = null; + + public static MandelBrot javaMandelBrotMultiThread = null; + + // new JavaMandelBrot(); + //new JavaMandelBrotMultiThread(); + @SuppressWarnings("serial") public static void main(String[] _args) { + + final JFrame frame = new JFrame("MandelBrot"); + + /** Width of Mandelbrot view. */ + final int width = 768; + + /** Height of Mandelbrot view. */ + final int height = 768; + + /** Mandelbrot image height. */ + + /** Image for Mandelbrot view. */ + final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + + final Object framePaintedDoorBell = new Object(); + final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + + g.drawImage(image, 0, 0, width, height, this); + synchronized (framePaintedDoorBell) { + framePaintedDoorBell.notify(); + } + } + }; + + // Set the size of JComponent which displays Mandelbrot image + viewer.setPreferredSize(new Dimension(width, height)); + + final Object userClickDoorBell = new Object(); + + // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view + viewer.addMouseListener(new MouseAdapter(){ + @Override public void mouseClicked(MouseEvent e) { + to = e.getPoint(); + synchronized (userClickDoorBell) { + userClickDoorBell.notify(); + } + } + }); + + final JPanel controlPanel = new JPanel(new FlowLayout()); + + final String[] choices = new String[] { + "Java Sequential", + "Java Threads", + "GPU OpenCL" + }; + + final JComboBox startButton = new JComboBox(choices); + + startButton.addItemListener(new ItemListener(){ + @Override public void itemStateChanged(ItemEvent e) { + final String item = (String) startButton.getSelectedItem(); + + if (item.equals(choices[2])) { + mandelBrot = gpuMandelBrot; + } else if (item.equals(choices[0])) { + mandelBrot = javaMandelBrot; + } else if (item.equals(choices[1])) { + mandelBrot = javaMandelBrotMultiThread; + } + } + + }); + controlPanel.add(startButton); + + controlPanel.add(new JLabel("FPS")); + final JTextField framesPerSecondTextField = new JTextField("0", 5); + + controlPanel.add(framesPerSecondTextField); + + // Swing housework to create the frame + frame.getContentPane().add(viewer); + frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + // Extract the underlying RGB buffer from the image. + // Pass this to the kernel so it operates directly on the RGB buffer of the image + + final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); + + /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ + float scale = .0f; + + float offsetx = .0f; + + float offsety = .0f; + Device device = KernelManager.instance().bestDevice(); + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + System.out.println("max memory = " + openclDevice.getGlobalMemSize()); + System.out.println("max mem alloc size = " + openclDevice.getMaxMemAllocSize()); + gpuMandelBrot = openclDevice.bind(MandelBrot.class); + } + + javaMandelBrot = new JavaMandelBrot(); + javaMandelBrotMultiThread = new JavaMandelBrotMultiThread(); + mandelBrot = javaMandelBrot; + final float defaultScale = 3f; + scale = defaultScale; + offsetx = -1f; + offsety = 0f; + final Range range = device.createRange2D(width, height); + mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); + viewer.repaint(); + + // Window listener to dispose Kernel resources on user exit. + frame.addWindowListener(new WindowAdapter(){ + @Override public void windowClosing(WindowEvent _windowEvent) { + // mandelBrot.dispose(); + System.exit(0); + } + }); + + while (true) { + // Wait for the user to click somewhere + while (to == null) { + synchronized (userClickDoorBell) { + try { + userClickDoorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + } + + float x = -1f; + float y = 0f; + final float tox = ((float) (to.x - (width / 2)) / width) * scale; + final float toy = ((float) (to.y - (height / 2)) / height) * scale; + + // This is how many frames we will display as we zoom in and out. + final int frames = 128; + long startMillis = System.currentTimeMillis(); + int frameCount = 0; + for (int sign = -1; sign < 2; sign += 2) { + for (int i = 0; i < (frames - 4); i++) { + scale = scale + ((sign * defaultScale) / frames); + x = x - (sign * (tox / frames)); + y = y - (sign * (toy / frames)); + offsetx = x; + offsety = y; + mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); + viewer.repaint(); + synchronized (framePaintedDoorBell) { + try { + framePaintedDoorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + frameCount++; + final long endMillis = System.currentTimeMillis(); + final long elapsedMillis = endMillis - startMillis; + if (elapsedMillis > 1000) { + framesPerSecondTextField.setText("" + ((frameCount * 1000) / elapsedMillis)); + frameCount = 0; + startMillis = endMillis; + } + } + } + + // Reset zoom-in point. + to = null; + + } + + } + +} diff --git a/src/main/java/com/aparapi/examples/extension/MandelSimple.java b/src/main/java/com/aparapi/examples/extension/MandelSimple.java index ec895fa2..6b3d1d17 100644 --- a/src/main/java/com/aparapi/examples/extension/MandelSimple.java +++ b/src/main/java/com/aparapi/examples/extension/MandelSimple.java @@ -1,216 +1,231 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.extension; - -import com.aparapi.device.*; -import com.aparapi.examples.extension.Mandel; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.*; -import com.aparapi.opencl.OpenCL.*; -import com.aparapi.Range; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; - -public class MandelSimple{ - - /** User selected zoom-in point on the Mandelbrot view. */ - public static volatile Point to = null; - - public static Mandel mandelBrot = null; - - @SuppressWarnings("serial") public static void main(String[] _args) { - - final JFrame frame = new JFrame("MandelBrot"); - - /** Width of Mandelbrot view. */ - final int width = 768; - - /** Height of Mandelbrot view. */ - final int height = 768; - - /** Mandelbrot image height. */ - - /** Image for Mandelbrot view. */ - final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - - final Object framePaintedDoorBell = new Object(); - final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - - g.drawImage(image, 0, 0, width, height, this); - synchronized (framePaintedDoorBell) { - framePaintedDoorBell.notify(); - } - } - }; - - // Set the size of JComponent which displays Mandelbrot image - viewer.setPreferredSize(new Dimension(width, height)); - - final Object userClickDoorBell = new Object(); - - // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view - viewer.addMouseListener(new MouseAdapter(){ - @Override public void mouseClicked(MouseEvent e) { - to = e.getPoint(); - synchronized (userClickDoorBell) { - userClickDoorBell.notify(); - } - } - }); - - final JPanel controlPanel = new JPanel(new FlowLayout()); - - controlPanel.add(new JLabel("FPS")); - final JTextField framesPerSecondTextField = new JTextField("0", 5); - - controlPanel.add(framesPerSecondTextField); - - // Swing housework to create the frame - frame.getContentPane().add(viewer); - frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - - // Extract the underlying RGB buffer from the image. - // Pass this to the kernel so it operates directly on the RGB buffer of the image - - final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - - /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ - float scale = .0f; - - float offsetx = .0f; - - float offsety = .0f; - final Device device = KernelManager.instance().bestDevice(); - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - System.out.println("max memory = " + openclDevice.getGlobalMemSize()); - System.out.println("max mem alloc size = " + openclDevice.getMaxMemAllocSize()); - mandelBrot = openclDevice.bind(Mandel.class); - - final float defaultScale = 3f; - scale = defaultScale; - offsetx = -1f; - offsety = 0f; - final Range range = device.createRange2D(width, height); - mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); - viewer.repaint(); - - // Window listener to dispose Kernel resources on user exit. - frame.addWindowListener(new WindowAdapter(){ - @Override public void windowClosing(WindowEvent _windowEvent) { - // mandelBrot.dispose(); - System.exit(0); - } - }); - - while (true) { - // Wait for the user to click somewhere - while (to == null) { - synchronized (userClickDoorBell) { - try { - userClickDoorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - } - - float x = -1f; - float y = 0f; - final float tox = ((float) (to.x - (width / 2)) / width) * scale; - final float toy = ((float) (to.y - (height / 2)) / height) * scale; - - // This is how many frames we will display as we zoom in and out. - final int frames = 128; - long startMillis = System.currentTimeMillis(); - int frameCount = 0; - for (int sign = -1; sign < 2; sign += 2) { - for (int i = 0; i < (frames - 4); i++) { - scale = scale + ((sign * defaultScale) / frames); - x = x - (sign * (tox / frames)); - y = y - (sign * (toy / frames)); - offsetx = x; - offsety = y; - mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); - viewer.repaint(); - synchronized (framePaintedDoorBell) { - try { - framePaintedDoorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - frameCount++; - final long endMillis = System.currentTimeMillis(); - final long elapsedMillis = endMillis - startMillis; - if (elapsedMillis > 1000) { - framesPerSecondTextField.setText("" + ((frameCount * 1000) / elapsedMillis)); - frameCount = 0; - startMillis = endMillis; - } - } - } - - // Reset zoom-in point. - to = null; - - } - } - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.extension; + +import com.aparapi.device.*; +import com.aparapi.examples.extension.Mandel; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.*; +import com.aparapi.opencl.OpenCL.*; +import com.aparapi.Range; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; + +public class MandelSimple{ + + /** User selected zoom-in point on the Mandelbrot view. */ + public static volatile Point to = null; + + public static Mandel mandelBrot = null; + + @SuppressWarnings("serial") public static void main(String[] _args) { + + final JFrame frame = new JFrame("MandelBrot"); + + /** Width of Mandelbrot view. */ + final int width = 768; + + /** Height of Mandelbrot view. */ + final int height = 768; + + /** Mandelbrot image height. */ + + /** Image for Mandelbrot view. */ + final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + + final Object framePaintedDoorBell = new Object(); + final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + + g.drawImage(image, 0, 0, width, height, this); + synchronized (framePaintedDoorBell) { + framePaintedDoorBell.notify(); + } + } + }; + + // Set the size of JComponent which displays Mandelbrot image + viewer.setPreferredSize(new Dimension(width, height)); + + final Object userClickDoorBell = new Object(); + + // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view + viewer.addMouseListener(new MouseAdapter(){ + @Override public void mouseClicked(MouseEvent e) { + to = e.getPoint(); + synchronized (userClickDoorBell) { + userClickDoorBell.notify(); + } + } + }); + + final JPanel controlPanel = new JPanel(new FlowLayout()); + + controlPanel.add(new JLabel("FPS")); + final JTextField framesPerSecondTextField = new JTextField("0", 5); + + controlPanel.add(framesPerSecondTextField); + + // Swing housework to create the frame + frame.getContentPane().add(viewer); + frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + // Extract the underlying RGB buffer from the image. + // Pass this to the kernel so it operates directly on the RGB buffer of the image + + final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); + + /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ + float scale = .0f; + + float offsetx = .0f; + + float offsety = .0f; + final Device device = KernelManager.instance().bestDevice(); + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + System.out.println("max memory = " + openclDevice.getGlobalMemSize()); + System.out.println("max mem alloc size = " + openclDevice.getMaxMemAllocSize()); + mandelBrot = openclDevice.bind(Mandel.class); + + final float defaultScale = 3f; + scale = defaultScale; + offsetx = -1f; + offsety = 0f; + final Range range = device.createRange2D(width, height); + mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); + viewer.repaint(); + + // Window listener to dispose Kernel resources on user exit. + frame.addWindowListener(new WindowAdapter(){ + @Override public void windowClosing(WindowEvent _windowEvent) { + // mandelBrot.dispose(); + System.exit(0); + } + }); + + while (true) { + // Wait for the user to click somewhere + while (to == null) { + synchronized (userClickDoorBell) { + try { + userClickDoorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + } + + float x = -1f; + float y = 0f; + final float tox = ((float) (to.x - (width / 2)) / width) * scale; + final float toy = ((float) (to.y - (height / 2)) / height) * scale; + + // This is how many frames we will display as we zoom in and out. + final int frames = 128; + long startMillis = System.currentTimeMillis(); + int frameCount = 0; + for (int sign = -1; sign < 2; sign += 2) { + for (int i = 0; i < (frames - 4); i++) { + scale = scale + ((sign * defaultScale) / frames); + x = x - (sign * (tox / frames)); + y = y - (sign * (toy / frames)); + offsetx = x; + offsety = y; + mandelBrot.createMandleBrot(range, scale, offsetx, offsety, imageRgb); + viewer.repaint(); + synchronized (framePaintedDoorBell) { + try { + framePaintedDoorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + frameCount++; + final long endMillis = System.currentTimeMillis(); + final long elapsedMillis = endMillis - startMillis; + if (elapsedMillis > 1000) { + framesPerSecondTextField.setText("" + ((frameCount * 1000) / elapsedMillis)); + frameCount = 0; + startMillis = endMillis; + } + } + } + + // Reset zoom-in point. + to = null; + + } + } + + } + +} diff --git a/src/main/java/com/aparapi/examples/extension/Pow4Example.java b/src/main/java/com/aparapi/examples/extension/Pow4Example.java index ff029df5..0856f1a1 100644 --- a/src/main/java/com/aparapi/examples/extension/Pow4Example.java +++ b/src/main/java/com/aparapi/examples/extension/Pow4Example.java @@ -1,61 +1,76 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -import com.aparapi.Range; -import com.aparapi.device.Device; -import com.aparapi.device.OpenCLDevice; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.OpenCL; -import com.aparapi.opencl.OpenCL.Resource; - -public class Pow4Example{ - - @Resource("com/aparapi/examples/extension/squarer.cl") - interface Squarer extends OpenCL<Squarer>{ - - public Squarer square(// - Range _range,// - @GlobalReadWrite("in") float[] in,// - @GlobalReadWrite("out") float[] out); - } - - public static void main(String[] args) { - - final int size = 32; - final float[] in = new float[size]; - for (int i = 0; i < size; i++) { - in[i] = i; - } - final float[] squares = new float[size]; - final Range range = Range.create(size); - - final Device device = KernelManager.instance().bestDevice(); - - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - final Squarer squarer = openclDevice.bind(Squarer.class); - squarer.square(range, in, squares); - - for (int i = 0; i < size; i++) { - System.out.println(in[i] + " " + squares[i]); - } - - squarer.square(range, squares, in); - - for (int i = 0; i < size; i++) { - System.out.println(i + " " + squares[i] + " " + in[i]); - } - } - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +import com.aparapi.Range; +import com.aparapi.device.Device; +import com.aparapi.device.OpenCLDevice; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.OpenCL; +import com.aparapi.opencl.OpenCL.Resource; + +public class Pow4Example{ + + @Resource("com/aparapi/examples/extension/squarer.cl") + interface Squarer extends OpenCL<Squarer>{ + + public Squarer square(// + Range _range,// + @GlobalReadWrite("in") float[] in,// + @GlobalReadWrite("out") float[] out); + } + + public static void main(String[] args) { + + final int size = 32; + final float[] in = new float[size]; + for (int i = 0; i < size; i++) { + in[i] = i; + } + final float[] squares = new float[size]; + final Range range = Range.create(size); + + final Device device = KernelManager.instance().bestDevice(); + + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + final Squarer squarer = openclDevice.bind(Squarer.class); + squarer.square(range, in, squares); + + for (int i = 0; i < size; i++) { + System.out.println(in[i] + " " + squares[i]); + } + + squarer.square(range, squares, in); + + for (int i = 0; i < size; i++) { + System.out.println(i + " " + squares[i] + " " + in[i]); + } + } + } + +} diff --git a/src/main/java/com/aparapi/examples/extension/SquareExample.java b/src/main/java/com/aparapi/examples/extension/SquareExample.java index 76df5839..598b68a8 100644 --- a/src/main/java/com/aparapi/examples/extension/SquareExample.java +++ b/src/main/java/com/aparapi/examples/extension/SquareExample.java @@ -1,99 +1,114 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -import com.aparapi.ProfileInfo; -import com.aparapi.Range; -import com.aparapi.device.Device; -import com.aparapi.device.OpenCLDevice; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.OpenCL; -import com.aparapi.opencl.OpenCL.Resource; -import com.aparapi.opencl.OpenCL.Source; -import java.util.List; - -public class SquareExample{ - - interface Squarer extends OpenCL<Squarer>{ - @Kernel("{\n"// - + " const size_t id = get_global_id(0);\n"// - + " out[id] = in[id]*in[id];\n"// - + "}\n")// - public Squarer square(// - Range _range,// - @GlobalReadWrite("in") float[] in,// - @GlobalReadWrite("out") float[] out); - } - - @Resource("com/aparapi/examples/extension/squarer.cl") interface SquarerWithResource extends OpenCL<SquarerWithResource>{ - public SquarerWithResource square(// - Range _range,// - @GlobalReadWrite("in") float[] in,// - @GlobalReadWrite("out") float[] out); - } - - @Source("\n"// - + "__kernel void square (\n" // - + " __global float *in,\n"// - + " __global float *out\n" + "){\n"// - + " const size_t id = get_global_id(0);\n"// - + " out[id] = in[id]*in[id];\n"// - + "}\n") interface SquarerWithSource extends OpenCL<SquarerWithSource>{ - public SquarerWithSource square(// - Range _range,// - @GlobalReadOnly("in") float[] in,// - @GlobalWriteOnly("out") float[] out); - } - - public static void main(String[] args) { - final int size = 32; - final float[] in = new float[size]; - - for (int i = 0; i < size; i++) { - in[i] = i; - } - - final float[] squares = new float[size]; - final float[] quads = new float[size]; - final Range range = Range.create(size); - - final Device device = KernelManager.instance().bestDevice(); - - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - for (int l=0; l<5; l++){ - - final SquarerWithResource squarer = openclDevice.bind(SquarerWithResource.class); - squarer.square(range, in, squares); - - for (int i = 0; i < size; i++) { - System.out.println(l+" "+in[i] + " " + squares[i]); - } - - squarer.square(range, squares, quads); - - for (int i = 0; i < size; i++) { - System.out.println(l+" "+ in[i] + " " + squares[i] + " " + quads[i]); - } - final List<ProfileInfo> profileInfo = squarer.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " - + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); - System.out.println(); - } - } - squarer.dispose(); - } - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +import com.aparapi.ProfileInfo; +import com.aparapi.Range; +import com.aparapi.device.Device; +import com.aparapi.device.OpenCLDevice; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.OpenCL; +import com.aparapi.opencl.OpenCL.Resource; +import com.aparapi.opencl.OpenCL.Source; +import java.util.List; + +public class SquareExample{ + + interface Squarer extends OpenCL<Squarer>{ + @Kernel("{\n"// + + " const size_t id = get_global_id(0);\n"// + + " out[id] = in[id]*in[id];\n"// + + "}\n")// + public Squarer square(// + Range _range,// + @GlobalReadWrite("in") float[] in,// + @GlobalReadWrite("out") float[] out); + } + + @Resource("com/aparapi/examples/extension/squarer.cl") interface SquarerWithResource extends OpenCL<SquarerWithResource>{ + public SquarerWithResource square(// + Range _range,// + @GlobalReadWrite("in") float[] in,// + @GlobalReadWrite("out") float[] out); + } + + @Source("\n"// + + "__kernel void square (\n" // + + " __global float *in,\n"// + + " __global float *out\n" + "){\n"// + + " const size_t id = get_global_id(0);\n"// + + " out[id] = in[id]*in[id];\n"// + + "}\n") interface SquarerWithSource extends OpenCL<SquarerWithSource>{ + public SquarerWithSource square(// + Range _range,// + @GlobalReadOnly("in") float[] in,// + @GlobalWriteOnly("out") float[] out); + } + + public static void main(String[] args) { + final int size = 32; + final float[] in = new float[size]; + + for (int i = 0; i < size; i++) { + in[i] = i; + } + + final float[] squares = new float[size]; + final float[] quads = new float[size]; + final Range range = Range.create(size); + + final Device device = KernelManager.instance().bestDevice(); + + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + for (int l=0; l<5; l++){ + + final SquarerWithResource squarer = openclDevice.bind(SquarerWithResource.class); + squarer.square(range, in, squares); + + for (int i = 0; i < size; i++) { + System.out.println(l+" "+in[i] + " " + squares[i]); + } + + squarer.square(range, squares, quads); + + for (int i = 0; i < size; i++) { + System.out.println(l+" "+ in[i] + " " + squares[i] + " " + quads[i]); + } + final List<ProfileInfo> profileInfo = squarer.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); + System.out.println(); + } + } + squarer.dispose(); + } + } + } +} diff --git a/src/main/java/com/aparapi/examples/extension/StopWatch.java b/src/main/java/com/aparapi/examples/extension/StopWatch.java index a5ac4b26..112a7fa7 100644 --- a/src/main/java/com/aparapi/examples/extension/StopWatch.java +++ b/src/main/java/com/aparapi/examples/extension/StopWatch.java @@ -1,25 +1,40 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -public class StopWatch{ - long start = 0L; - - public void start() { - start = System.nanoTime(); - } - - public void print(String _str) { - long end = (System.nanoTime() - start) / 1000000; - System.out.println(_str + " " + end); - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +public class StopWatch{ + long start = 0L; + + public void start() { + start = System.nanoTime(); + } + + public void print(String _str) { + long end = (System.nanoTime() - start) / 1000000; + System.out.println(_str + " " + end); + } + +} diff --git a/src/main/java/com/aparapi/examples/extension/SwapExample.java b/src/main/java/com/aparapi/examples/extension/SwapExample.java index beafe59a..8f657f6c 100644 --- a/src/main/java/com/aparapi/examples/extension/SwapExample.java +++ b/src/main/java/com/aparapi/examples/extension/SwapExample.java @@ -1,74 +1,89 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.extension; - -import com.aparapi.Range; -import com.aparapi.device.Device; -import com.aparapi.device.OpenCLDevice; -import com.aparapi.internal.kernel.*; -import com.aparapi.opencl.OpenCL; - -public class SwapExample{ - - interface Swapper extends OpenCL<Swapper>{ - @Kernel("{\n"// - + " const size_t id = get_global_id(0);\n"// - + " float temp=lhs[id];" + " lhs[id] = rhs[id];\n"// - + " rhs[id] = temp;\n"// - + "}\n")// - public Swapper swap(// - Range _range,// - @GlobalReadWrite("lhs") float[] lhs,// - @GlobalReadWrite("rhs") float[] rhs); - } - - public static void main(String[] args) { - - final int size = 32; - final float[] lhs = new float[size]; - for (int i = 0; i < size; i++) { - lhs[i] = i; - } - final float[] rhs = new float[size]; - final Range range = Range.create(size); - - final Device device = KernelManager.instance().bestDevice(); - - if (device instanceof OpenCLDevice) { - final OpenCLDevice openclDevice = (OpenCLDevice) device; - - final Swapper swapper = openclDevice.bind(Swapper.class); - for (int i = 0; i < size; i++) { - System.out.println(lhs[i] + " " + rhs[i]); - } - - swapper.swap(range, lhs, rhs); - - for (int i = 0; i < size; i++) { - System.out.println(lhs[i] + " " + rhs[i]); - } - - swapper.swap(range, lhs, rhs); - - for (int i = 0; i < size; i++) { - System.out.println(lhs[i] + " " + rhs[i]); - } - - swapper.swap(range, rhs, lhs); - - for (int i = 0; i < size; i++) { - System.out.println(lhs[i] + " " + rhs[i]); - } - - } - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.extension; + +import com.aparapi.Range; +import com.aparapi.device.Device; +import com.aparapi.device.OpenCLDevice; +import com.aparapi.internal.kernel.*; +import com.aparapi.opencl.OpenCL; + +public class SwapExample{ + + interface Swapper extends OpenCL<Swapper>{ + @Kernel("{\n"// + + " const size_t id = get_global_id(0);\n"// + + " float temp=lhs[id];" + " lhs[id] = rhs[id];\n"// + + " rhs[id] = temp;\n"// + + "}\n")// + public Swapper swap(// + Range _range,// + @GlobalReadWrite("lhs") float[] lhs,// + @GlobalReadWrite("rhs") float[] rhs); + } + + public static void main(String[] args) { + + final int size = 32; + final float[] lhs = new float[size]; + for (int i = 0; i < size; i++) { + lhs[i] = i; + } + final float[] rhs = new float[size]; + final Range range = Range.create(size); + + final Device device = KernelManager.instance().bestDevice(); + + if (device instanceof OpenCLDevice) { + final OpenCLDevice openclDevice = (OpenCLDevice) device; + + final Swapper swapper = openclDevice.bind(Swapper.class); + for (int i = 0; i < size; i++) { + System.out.println(lhs[i] + " " + rhs[i]); + } + + swapper.swap(range, lhs, rhs); + + for (int i = 0; i < size; i++) { + System.out.println(lhs[i] + " " + rhs[i]); + } + + swapper.swap(range, lhs, rhs); + + for (int i = 0; i < size; i++) { + System.out.println(lhs[i] + " " + rhs[i]); + } + + swapper.swap(range, rhs, lhs); + + for (int i = 0; i < size; i++) { + System.out.println(lhs[i] + " " + rhs[i]); + } + + } + } + +} diff --git a/src/main/java/com/aparapi/examples/info/Main.java b/src/main/java/com/aparapi/examples/info/Main.java index 0b835133..e20d911a 100644 --- a/src/main/java/com/aparapi/examples/info/Main.java +++ b/src/main/java/com/aparapi/examples/info/Main.java @@ -1,95 +1,110 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.info; - -import com.aparapi.device.*; -import com.aparapi.internal.kernel.*; -import com.aparapi.internal.opencl.*; - -import java.util.*; - -public class Main{ - public static void main(String[] _args) { - System.out.println("com.aparapi.examples.info.Main"); - List<OpenCLPlatform> platforms = (new OpenCLPlatform()).getOpenCLPlatforms(); - System.out.println("Machine contains " + platforms.size() + " OpenCL platforms"); - int platformc = 0; - for (OpenCLPlatform platform : platforms) { - System.out.println("Platform " + platformc + "{"); - System.out.println(" Name : \"" + platform.getName() + "\""); - System.out.println(" Vendor : \"" + platform.getVendor() + "\""); - System.out.println(" Version : \"" + platform.getVersion() + "\""); - List<OpenCLDevice> devices = platform.getOpenCLDevices(); - System.out.println(" Platform contains " + devices.size() + " OpenCL devices"); - int devicec = 0; - for (OpenCLDevice device : devices) { - System.out.println(" Device " + devicec + "{"); - System.out.println(" Type : " + device.getType()); - System.out.println(" GlobalMemSize : " + device.getGlobalMemSize()); - System.out.println(" LocalMemSize : " + device.getLocalMemSize()); - System.out.println(" MaxComputeUnits : " + device.getMaxComputeUnits()); - System.out.println(" MaxWorkGroupSizes : " + device.getMaxWorkGroupSize()); - System.out.println(" MaxWorkItemDimensions : " + device.getMaxWorkItemDimensions()); - System.out.println(" }"); - devicec++; - } - System.out.println("}"); - platformc++; - } - - KernelPreferences preferences = KernelManager.instance().getDefaultPreferences(); - System.out.println("\nDevices in preferred order:\n"); - - for (Device device : preferences.getPreferredDevices(null)) { - System.out.println(device); - System.out.println(); - } - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.info; + +import com.aparapi.device.*; +import com.aparapi.internal.kernel.*; +import com.aparapi.internal.opencl.*; + +import java.util.*; + +public class Main{ + public static void main(String[] _args) { + System.out.println("com.aparapi.examples.info.Main"); + List<OpenCLPlatform> platforms = (new OpenCLPlatform()).getOpenCLPlatforms(); + System.out.println("Machine contains " + platforms.size() + " OpenCL platforms"); + int platformc = 0; + for (OpenCLPlatform platform : platforms) { + System.out.println("Platform " + platformc + "{"); + System.out.println(" Name : \"" + platform.getName() + "\""); + System.out.println(" Vendor : \"" + platform.getVendor() + "\""); + System.out.println(" Version : \"" + platform.getVersion() + "\""); + List<OpenCLDevice> devices = platform.getOpenCLDevices(); + System.out.println(" Platform contains " + devices.size() + " OpenCL devices"); + int devicec = 0; + for (OpenCLDevice device : devices) { + System.out.println(" Device " + devicec + "{"); + System.out.println(" Type : " + device.getType()); + System.out.println(" GlobalMemSize : " + device.getGlobalMemSize()); + System.out.println(" LocalMemSize : " + device.getLocalMemSize()); + System.out.println(" MaxComputeUnits : " + device.getMaxComputeUnits()); + System.out.println(" MaxWorkGroupSizes : " + device.getMaxWorkGroupSize()); + System.out.println(" MaxWorkItemDimensions : " + device.getMaxWorkItemDimensions()); + System.out.println(" }"); + devicec++; + } + System.out.println("}"); + platformc++; + } + + KernelPreferences preferences = KernelManager.instance().getDefaultPreferences(); + System.out.println("\nDevices in preferred order:\n"); + + for (Device device : preferences.getPreferredDevices(null)) { + System.out.println(device); + System.out.println(); + } + } + +} diff --git a/src/main/java/com/aparapi/examples/javaonedemo/Life.java b/src/main/java/com/aparapi/examples/javaonedemo/Life.java index c0559259..2494ce6d 100644 --- a/src/main/java/com/aparapi/examples/javaonedemo/Life.java +++ b/src/main/java/com/aparapi/examples/javaonedemo/Life.java @@ -1,312 +1,327 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.javaonedemo; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.util.Arrays; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.WindowConstants; - -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; - -/** - * An example Aparapi application which demonstrates Conways 'Game Of Life'. - * - * Original code from Witold Bolt's site https://github.com/houp/aparapi/tree/master/samples/gameoflife. - * - * Converted to use int buffer and some performance tweaks by Gary Frost - * - * @author Wiltold Bolt - * @author Gary Frost - */ -public class Life{ - - /** - * LifeKernel represents the data parallel algorithm describing by Conway's game of life. - * - * http://en.wikipedia.org/wiki/Conway's_Game_of_Life - * - * We examine the state of each pixel and its 8 neighbors and apply the following rules. - * - * if pixel is dead (off) and number of neighbors == 3 { - * pixel is turned on - * } else if pixel is alive (on) and number of neighbors is neither 2 or 3 - * pixel is turned off - * } - * - * We use an image buffer which is 2*width*height the size of screen and we use fromBase and toBase to track which half of the buffer is being mutated for each pass. We basically - * copy from getGlobalId()+fromBase to getGlobalId()+toBase; - * - * - * Prior to each pass the values of fromBase and toBase are swapped. - * - */ - - public static class LifeKernel extends Kernel{ - - private static final int ALIVE = 0xffffff; - - private static final int DEAD = 0; - - private final int[] imageData; - - private final int width; - - private final int height; - - private final Range range; - - private int fromBase; - - private int toBase; - - public LifeKernel(int _width, int _height, BufferedImage _image) { - - imageData = ((DataBufferInt) _image.getRaster().getDataBuffer()).getData(); - width = _width; - height = _height; - range = Range.create(width * height, 256); - System.out.println("range = " + range); - - setExplicit(true); // This gives us a performance boost for GPU mode. - - fromBase = height * width; - toBase = 0; - Arrays.fill(imageData, LifeKernel.DEAD); - /** draw a line across the image **/ - for (int i = (width * (height / 2)) + (width / 10); i < ((width * ((height / 2) + 1)) - (width / 10)); i++) { - imageData[toBase + i] = LifeKernel.ALIVE; - imageData[fromBase + i] = LifeKernel.ALIVE; - } - - put(imageData); // Because we are using explicit buffer management we must put the imageData array - - } - - @Override public void run() { - final int gid = getGlobalId(); - final int to = gid + toBase; - final int from = gid + fromBase; - final int x = gid % width; - final int y = gid / width; - - if (((x == 0) || (x == (width - 1)) || (y == 0) || (y == (height - 1)))) { - // This pixel is on the border of the view, just keep existing value - imageData[to] = imageData[from]; - } else { - // Count the number of neighbors. We use (value&1x) to turn pixel value into either 0 or 1 - final int neighbors = (imageData[from - 1] & 1) + // EAST - (imageData[from + 1] & 1) + // WEST - (imageData[from - width - 1] & 1) + // NORTHEAST - (imageData[from - width] & 1) + // NORTH - (imageData[(from - width) + 1] & 1) + // NORTHWEST - (imageData[(from + width) - 1] & 1) + // SOUTHEAST - (imageData[from + width] & 1) + // SOUTH - (imageData[from + width + 1] & 1); // SOUTHWEST - - // The game of life logic - if ((neighbors == 3) || ((neighbors == 2) && (imageData[from] == ALIVE))) { - imageData[to] = ALIVE; - } else { - imageData[to] = DEAD; - } - - } - - } - - public void nextGeneration() { - // swap fromBase and toBase - final int swap = fromBase; - fromBase = toBase; - toBase = swap; - - execute(range); - - } - - } - - static boolean running = false; - - // static LifeKernel lifeKernel = null; - - static long start = 0L; - - static int generations = 0; - - static double generationsPerSecondField = 0; - - public static void main(String[] _args) { - - final JFrame frame = new JFrame("Game of Life"); - final int width = Integer.getInteger("width", 1024 + 256); - - final int height = Integer.getInteger("height", 768 - 64 - 32); - - // Buffer is twice the size as the screen. We will alternate between mutating data from top to bottom - // and bottom to top in alternate generation passses. The LifeKernel will track which pass is which - final BufferedImage image = new BufferedImage(width, height * 2, BufferedImage.TYPE_INT_RGB); - - final LifeKernel lifeKernel = new LifeKernel(width, height, image); - lifeKernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); - - final Font font = new Font("Garamond", Font.BOLD, 100); - // Create a component for viewing the offsecreen image - @SuppressWarnings("serial") final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - g.setFont(font); - g.setColor(Color.WHITE); - if (lifeKernel.isExplicit()) { - lifeKernel.get(lifeKernel.imageData); // We only pull the imageData when we intend to use it. - final List<ProfileInfo> profileInfo = lifeKernel.getProfileInfo(); - if (profileInfo != null) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " - + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - } - // We copy one half of the offscreen buffer to the viewer, we copy the half that we just mutated. - if (lifeKernel.fromBase == 0) { - g.drawImage(image, 0, 0, width, height, 0, 0, width, height, this); - } else { - g.drawImage(image, 0, 0, width, height, 0, height, width, 2 * height, this); - } - final long now = System.currentTimeMillis(); - if ((now - start) > 1000) { - generationsPerSecondField = (generations * 1000.0) / (now - start); - start = now; - generations = 0; - } - g.drawString(String.format("%5.2f", generationsPerSecondField), 20, 100); - - } - }; - - final JPanel controlPanel = new JPanel(new FlowLayout()); - frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - - final String[] choices = new String[] { - "Java Threads", - "GPU OpenCL" - }; - - final JComboBox modeButton = new JComboBox(choices); - - modeButton.addItemListener(new ItemListener(){ - @Override public void itemStateChanged(ItemEvent e) { - final String item = (String) modeButton.getSelectedItem(); - if (item.equals(choices[0])) { - lifeKernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); - } else if (item.equals(choices[1])) { - lifeKernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); - } - } - - }); - controlPanel.add(modeButton); - - // Set the default size and add to the frames content pane - viewer.setPreferredSize(new Dimension(width, height)); - frame.getContentPane().add(viewer); - - // Swing housekeeping - frame.pack(); - frame.setVisible(true); - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - - while (!running) { - try { - Thread.sleep(10); - viewer.repaint(); - } catch (final InterruptedException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - start = System.currentTimeMillis(); - while (true) { - lifeKernel.nextGeneration(); // Work is performed here - generations++; - viewer.repaint(); // Request a repaint of the viewer (causes paintComponent(Graphics) to be called later not synchronous - } - - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.javaonedemo; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.util.Arrays; +import java.util.List; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; + +/** + * An example Aparapi application which demonstrates Conways 'Game Of Life'. + * + * Original code from Witold Bolt's site https://github.com/houp/aparapi/tree/master/samples/gameoflife. + * + * Converted to use int buffer and some performance tweaks by Gary Frost + * + * @author Wiltold Bolt + * @author Gary Frost + */ +public class Life{ + + /** + * LifeKernel represents the data parallel algorithm describing by Conway's game of life. + * + * http://en.wikipedia.org/wiki/Conway's_Game_of_Life + * + * We examine the state of each pixel and its 8 neighbors and apply the following rules. + * + * if pixel is dead (off) and number of neighbors == 3 { + * pixel is turned on + * } else if pixel is alive (on) and number of neighbors is neither 2 or 3 + * pixel is turned off + * } + * + * We use an image buffer which is 2*width*height the size of screen and we use fromBase and toBase to track which half of the buffer is being mutated for each pass. We basically + * copy from getGlobalId()+fromBase to getGlobalId()+toBase; + * + * + * Prior to each pass the values of fromBase and toBase are swapped. + * + */ + + public static class LifeKernel extends Kernel{ + + private static final int ALIVE = 0xffffff; + + private static final int DEAD = 0; + + private final int[] imageData; + + private final int width; + + private final int height; + + private final Range range; + + private int fromBase; + + private int toBase; + + public LifeKernel(int _width, int _height, BufferedImage _image) { + + imageData = ((DataBufferInt) _image.getRaster().getDataBuffer()).getData(); + width = _width; + height = _height; + range = Range.create(width * height, 256); + System.out.println("range = " + range); + + setExplicit(true); // This gives us a performance boost for GPU mode. + + fromBase = height * width; + toBase = 0; + Arrays.fill(imageData, LifeKernel.DEAD); + /** draw a line across the image **/ + for (int i = (width * (height / 2)) + (width / 10); i < ((width * ((height / 2) + 1)) - (width / 10)); i++) { + imageData[toBase + i] = LifeKernel.ALIVE; + imageData[fromBase + i] = LifeKernel.ALIVE; + } + + put(imageData); // Because we are using explicit buffer management we must put the imageData array + + } + + @Override public void run() { + final int gid = getGlobalId(); + final int to = gid + toBase; + final int from = gid + fromBase; + final int x = gid % width; + final int y = gid / width; + + if (((x == 0) || (x == (width - 1)) || (y == 0) || (y == (height - 1)))) { + // This pixel is on the border of the view, just keep existing value + imageData[to] = imageData[from]; + } else { + // Count the number of neighbors. We use (value&1x) to turn pixel value into either 0 or 1 + final int neighbors = (imageData[from - 1] & 1) + // EAST + (imageData[from + 1] & 1) + // WEST + (imageData[from - width - 1] & 1) + // NORTHEAST + (imageData[from - width] & 1) + // NORTH + (imageData[(from - width) + 1] & 1) + // NORTHWEST + (imageData[(from + width) - 1] & 1) + // SOUTHEAST + (imageData[from + width] & 1) + // SOUTH + (imageData[from + width + 1] & 1); // SOUTHWEST + + // The game of life logic + if ((neighbors == 3) || ((neighbors == 2) && (imageData[from] == ALIVE))) { + imageData[to] = ALIVE; + } else { + imageData[to] = DEAD; + } + + } + + } + + public void nextGeneration() { + // swap fromBase and toBase + final int swap = fromBase; + fromBase = toBase; + toBase = swap; + + execute(range); + + } + + } + + static boolean running = false; + + // static LifeKernel lifeKernel = null; + + static long start = 0L; + + static int generations = 0; + + static double generationsPerSecondField = 0; + + public static void main(String[] _args) { + + final JFrame frame = new JFrame("Game of Life"); + final int width = Integer.getInteger("width", 1024 + 256); + + final int height = Integer.getInteger("height", 768 - 64 - 32); + + // Buffer is twice the size as the screen. We will alternate between mutating data from top to bottom + // and bottom to top in alternate generation passses. The LifeKernel will track which pass is which + final BufferedImage image = new BufferedImage(width, height * 2, BufferedImage.TYPE_INT_RGB); + + final LifeKernel lifeKernel = new LifeKernel(width, height, image); + lifeKernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); + + final Font font = new Font("Garamond", Font.BOLD, 100); + // Create a component for viewing the offsecreen image + @SuppressWarnings("serial") final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + g.setFont(font); + g.setColor(Color.WHITE); + if (lifeKernel.isExplicit()) { + lifeKernel.get(lifeKernel.imageData); // We only pull the imageData when we intend to use it. + final List<ProfileInfo> profileInfo = lifeKernel.getProfileInfo(); + if (profileInfo != null) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + } + // We copy one half of the offscreen buffer to the viewer, we copy the half that we just mutated. + if (lifeKernel.fromBase == 0) { + g.drawImage(image, 0, 0, width, height, 0, 0, width, height, this); + } else { + g.drawImage(image, 0, 0, width, height, 0, height, width, 2 * height, this); + } + final long now = System.currentTimeMillis(); + if ((now - start) > 1000) { + generationsPerSecondField = (generations * 1000.0) / (now - start); + start = now; + generations = 0; + } + g.drawString(String.format("%5.2f", generationsPerSecondField), 20, 100); + + } + }; + + final JPanel controlPanel = new JPanel(new FlowLayout()); + frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + + final String[] choices = new String[] { + "Java Threads", + "GPU OpenCL" + }; + + final JComboBox modeButton = new JComboBox(choices); + + modeButton.addItemListener(new ItemListener(){ + @Override public void itemStateChanged(ItemEvent e) { + final String item = (String) modeButton.getSelectedItem(); + if (item.equals(choices[0])) { + lifeKernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); + } else if (item.equals(choices[1])) { + lifeKernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); + } + } + + }); + controlPanel.add(modeButton); + + // Set the default size and add to the frames content pane + viewer.setPreferredSize(new Dimension(width, height)); + frame.getContentPane().add(viewer); + + // Swing housekeeping + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + while (!running) { + try { + Thread.sleep(10); + viewer.repaint(); + } catch (final InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + start = System.currentTimeMillis(); + while (true) { + lifeKernel.nextGeneration(); // Work is performed here + generations++; + viewer.repaint(); // Request a repaint of the viewer (causes paintComponent(Graphics) to be called later not synchronous + } + + } +} diff --git a/src/main/java/com/aparapi/examples/javaonedemo/Mandel.java b/src/main/java/com/aparapi/examples/javaonedemo/Mandel.java index fe73d360..d1f56c27 100644 --- a/src/main/java/com/aparapi/examples/javaonedemo/Mandel.java +++ b/src/main/java/com/aparapi/examples/javaonedemo/Mandel.java @@ -1,357 +1,372 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.javaonedemo; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Point; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.util.List; - -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import com.aparapi.annotation.*; -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; - -/** - * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. - * - * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. - * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example - * application might suffer with sub-optimal frame refresh rate as compared to GPU. - * - * @author gfrost - * - */ - -public class Mandel{ - - /** - * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. - * - * @author gfrost - * - */ - - public static class MandelKernel extends Kernel{ - - /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ - final private int rgb[]; - - /** Mandelbrot image width. */ - final private int width; - - /** Mandelbrot image height. */ - final private int height; - - /** Maximum iterations for Mandelbrot. */ - final private int maxIterations = 64; - - /** Palette which maps iteration values to RGB values. */ - @Constant final private int pallette[] = new int[maxIterations + 1]; - - /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ - private float scale = .0f; - - private float offsetx = .0f; - - private float offsety = .0f; - - /** - * Initialize the Kernel. - * - * @param _width Mandelbrot image width - * @param _height Mandelbrot image height - * @param _rgb Mandelbrot image RGB buffer - * @param _pallette Mandelbrot image palette - */ - public MandelKernel(int _width, int _height, int[] _rgb) { - //Initialize palette values - for (int i = 0; i < maxIterations; i++) { - final float h = i / (float) maxIterations; - final float b = 1.0f - (h * h); - pallette[i] = Color.HSBtoRGB(h, 1f, b); - } - - width = _width; - height = _height; - rgb = _rgb; - - } - - @Override public void run() { - - /** Determine which RGB value we are going to process (0..RGB.length). */ - final int gid = getGlobalId(); - - /** Translate the gid into an x an y value. */ - final float x = ((((gid % width) * scale) - ((scale / 2) * width)) / width) + offsetx; - - final float y = ((((gid / height) * scale) - ((scale / 2) * height)) / height) + offsety; - - int count = 0; - - float zx = x; - float zy = y; - float new_zx = 0f; - - // Iterate until the algorithm converges or until maxIterations are reached. - while ((count < maxIterations) && (((zx * zx) + (zy * zy)) < 8)) { - new_zx = ((zx * zx) - (zy * zy)) + x; - zy = (2 * zx * zy) + y; - zx = new_zx; - count++; - } - - // Pull the value out of the palette for this iteration count. - rgb[gid] = pallette[count]; - } - - public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { - offsetx = _offsetx; - offsety = _offsety; - scale = _scale; - } - - } - - /** User selected zoom-in point on the Mandelbrot view. */ - public static volatile Point to = null; - - public static int frameCount = 0; - - public static long start = 0; - - @SuppressWarnings("serial") public static void main(String[] _args) { - - final JFrame frame = new JFrame("MandelBrot"); - - /** Width of Mandelbrot view. */ - final int width = 768 - 64 - 32; - - /** Height of Mandelbrot view. */ - final int height = 768 - 64 - 32; - - /** Mandelbrot image height. */ - final Range range = Range.create(width * height); - - /** Image for Mandelbrot view. */ - final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - final BufferedImage offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - // Extract the underlying RGB buffer from the image. - // Pass this to the kernel so it operates directly on the RGB buffer of the image - final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); - final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - // Create a Kernel passing the size, RGB buffer and the palette. - final MandelKernel kernel = new MandelKernel(width, height, rgb); - - final Font font = new Font("Garamond", Font.BOLD, 100); - // Draw Mandelbrot image - final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - - g.drawImage(image, 0, 0, width, height, this); - g.setFont(font); - g.setColor(Color.WHITE); - final long now = System.currentTimeMillis(); - // if (now - start > 1000) { - final double framesPerSecond = (frameCount * 1000.0) / (now - start); - g.drawString(String.format("%5.2f", framesPerSecond), 20, 100); - // generationsPerSecond.setText(String.format("%5.2f", generationsPerSecondField)); - - // frames++; - // } - } - }; - - final JPanel controlPanel = new JPanel(new FlowLayout()); - frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); - - final String[] choices = new String[] { - // "Java Sequential", - "Java Threads", - "GPU OpenCL" - }; - - final JComboBox modeButton = new JComboBox(choices); - - modeButton.addItemListener(new ItemListener(){ - @Override public void itemStateChanged(ItemEvent e) { - final String item = (String) modeButton.getSelectedItem(); - - // if (item.equals(choices[2])) { - // modeButton = gpuMandelBrot; - // } else - if (item.equals(choices[0])) { - kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); - frameCount = 0; - start = System.currentTimeMillis(); - - // modeButton = javaMandelBrot; - } else if (item.equals(choices[1])) { - kernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); - frameCount = 0; - start = System.currentTimeMillis(); - // modeButton = javaMandelBrotMultiThread; - } - } - - }); - controlPanel.add(modeButton); - - // Set the size of JComponent which displays Mandelbrot image - viewer.setPreferredSize(new Dimension(width, height)); - - final Object doorBell = new Object(); - - // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view - viewer.addMouseListener(new MouseAdapter(){ - @Override public void mouseClicked(MouseEvent e) { - to = e.getPoint(); - synchronized (doorBell) { - doorBell.notify(); - } - } - }); - - // Swing housework to create the frame - frame.getContentPane().add(viewer, BorderLayout.CENTER); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - - final float defaultScale = 3f; - - // Set the default scale and offset, execute the kernel and force a repaint of the viewer. - kernel.setScaleAndOffset(defaultScale, -1f, 0f); - kernel.execute(range); - kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); - System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); - viewer.repaint(); - - // Window listener to dispose Kernel resources on user exit. - frame.addWindowListener(new WindowAdapter(){ - @Override public void windowClosing(WindowEvent _windowEvent) { - kernel.dispose(); - System.exit(0); - } - }); - - // Wait until the user selects a zoom-in point on the Mandelbrot view. - while (true) { - - // Wait for the user to click somewhere - while (to == null) { - synchronized (doorBell) { - try { - doorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - } - - float x = -1f; - float y = 0f; - float scale = defaultScale; - final float tox = ((float) (to.x - (width / 2)) / width) * scale; - final float toy = ((float) (to.y - (height / 2)) / height) * scale; - - // This is how many frames we will display as we zoom in and out. - final int frames = 128; - frameCount = 0; - start = System.currentTimeMillis(); - for (int sign = -1; sign < 2; sign += 2) { - for (int i = 0; i < (frames - 4); i++) { - frameCount++; - scale = scale + ((sign * defaultScale) / frames); - x = x - (sign * (tox / frames)); - y = y - (sign * (toy / frames)); - - // Set the scale and offset, execute the kernel and force a repaint of the viewer. - kernel.setScaleAndOffset(scale, x, y); - kernel.execute(range); - final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " - + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - - System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); - viewer.repaint(); - } - } - - // Reset zoom-in point. - to = null; - - } - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.javaonedemo; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.util.List; + +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; + +import com.aparapi.annotation.*; +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; + +/** + * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. + * + * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. + * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example + * application might suffer with sub-optimal frame refresh rate as compared to GPU. + * + * @author gfrost + * + */ + +public class Mandel{ + + /** + * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. + * + * @author gfrost + * + */ + + public static class MandelKernel extends Kernel{ + + /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ + final private int rgb[]; + + /** Mandelbrot image width. */ + final private int width; + + /** Mandelbrot image height. */ + final private int height; + + /** Maximum iterations for Mandelbrot. */ + final private int maxIterations = 64; + + /** Palette which maps iteration values to RGB values. */ + @Constant final private int pallette[] = new int[maxIterations + 1]; + + /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ + private float scale = .0f; + + private float offsetx = .0f; + + private float offsety = .0f; + + /** + * Initialize the Kernel. + * + * @param _width Mandelbrot image width + * @param _height Mandelbrot image height + * @param _rgb Mandelbrot image RGB buffer + * @param _pallette Mandelbrot image palette + */ + public MandelKernel(int _width, int _height, int[] _rgb) { + //Initialize palette values + for (int i = 0; i < maxIterations; i++) { + final float h = i / (float) maxIterations; + final float b = 1.0f - (h * h); + pallette[i] = Color.HSBtoRGB(h, 1f, b); + } + + width = _width; + height = _height; + rgb = _rgb; + + } + + @Override public void run() { + + /** Determine which RGB value we are going to process (0..RGB.length). */ + final int gid = getGlobalId(); + + /** Translate the gid into an x an y value. */ + final float x = ((((gid % width) * scale) - ((scale / 2) * width)) / width) + offsetx; + + final float y = ((((gid / height) * scale) - ((scale / 2) * height)) / height) + offsety; + + int count = 0; + + float zx = x; + float zy = y; + float new_zx = 0f; + + // Iterate until the algorithm converges or until maxIterations are reached. + while ((count < maxIterations) && (((zx * zx) + (zy * zy)) < 8)) { + new_zx = ((zx * zx) - (zy * zy)) + x; + zy = (2 * zx * zy) + y; + zx = new_zx; + count++; + } + + // Pull the value out of the palette for this iteration count. + rgb[gid] = pallette[count]; + } + + public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { + offsetx = _offsetx; + offsety = _offsety; + scale = _scale; + } + + } + + /** User selected zoom-in point on the Mandelbrot view. */ + public static volatile Point to = null; + + public static int frameCount = 0; + + public static long start = 0; + + @SuppressWarnings("serial") public static void main(String[] _args) { + + final JFrame frame = new JFrame("MandelBrot"); + + /** Width of Mandelbrot view. */ + final int width = 768 - 64 - 32; + + /** Height of Mandelbrot view. */ + final int height = 768 - 64 - 32; + + /** Mandelbrot image height. */ + final Range range = Range.create(width * height); + + /** Image for Mandelbrot view. */ + final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + final BufferedImage offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + // Extract the underlying RGB buffer from the image. + // Pass this to the kernel so it operates directly on the RGB buffer of the image + final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); + final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); + // Create a Kernel passing the size, RGB buffer and the palette. + final MandelKernel kernel = new MandelKernel(width, height, rgb); + + final Font font = new Font("Garamond", Font.BOLD, 100); + // Draw Mandelbrot image + final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + + g.drawImage(image, 0, 0, width, height, this); + g.setFont(font); + g.setColor(Color.WHITE); + final long now = System.currentTimeMillis(); + // if (now - start > 1000) { + final double framesPerSecond = (frameCount * 1000.0) / (now - start); + g.drawString(String.format("%5.2f", framesPerSecond), 20, 100); + // generationsPerSecond.setText(String.format("%5.2f", generationsPerSecondField)); + + // frames++; + // } + } + }; + + final JPanel controlPanel = new JPanel(new FlowLayout()); + frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); + + final String[] choices = new String[] { + // "Java Sequential", + "Java Threads", + "GPU OpenCL" + }; + + final JComboBox modeButton = new JComboBox(choices); + + modeButton.addItemListener(new ItemListener(){ + @Override public void itemStateChanged(ItemEvent e) { + final String item = (String) modeButton.getSelectedItem(); + + // if (item.equals(choices[2])) { + // modeButton = gpuMandelBrot; + // } else + if (item.equals(choices[0])) { + kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); + frameCount = 0; + start = System.currentTimeMillis(); + + // modeButton = javaMandelBrot; + } else if (item.equals(choices[1])) { + kernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); + frameCount = 0; + start = System.currentTimeMillis(); + // modeButton = javaMandelBrotMultiThread; + } + } + + }); + controlPanel.add(modeButton); + + // Set the size of JComponent which displays Mandelbrot image + viewer.setPreferredSize(new Dimension(width, height)); + + final Object doorBell = new Object(); + + // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view + viewer.addMouseListener(new MouseAdapter(){ + @Override public void mouseClicked(MouseEvent e) { + to = e.getPoint(); + synchronized (doorBell) { + doorBell.notify(); + } + } + }); + + // Swing housework to create the frame + frame.getContentPane().add(viewer, BorderLayout.CENTER); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + final float defaultScale = 3f; + + // Set the default scale and offset, execute the kernel and force a repaint of the viewer. + kernel.setScaleAndOffset(defaultScale, -1f, 0f); + kernel.execute(range); + kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); + System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); + viewer.repaint(); + + // Window listener to dispose Kernel resources on user exit. + frame.addWindowListener(new WindowAdapter(){ + @Override public void windowClosing(WindowEvent _windowEvent) { + kernel.dispose(); + System.exit(0); + } + }); + + // Wait until the user selects a zoom-in point on the Mandelbrot view. + while (true) { + + // Wait for the user to click somewhere + while (to == null) { + synchronized (doorBell) { + try { + doorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + } + + float x = -1f; + float y = 0f; + float scale = defaultScale; + final float tox = ((float) (to.x - (width / 2)) / width) * scale; + final float toy = ((float) (to.y - (height / 2)) / height) * scale; + + // This is how many frames we will display as we zoom in and out. + final int frames = 128; + frameCount = 0; + start = System.currentTimeMillis(); + for (int sign = -1; sign < 2; sign += 2) { + for (int i = 0; i < (frames - 4); i++) { + frameCount++; + scale = scale + ((sign * defaultScale) / frames); + x = x - (sign * (tox / frames)); + y = y - (sign * (toy / frames)); + + // Set the scale and offset, execute the kernel and force a repaint of the viewer. + kernel.setScaleAndOffset(scale, x, y); + kernel.execute(range); + final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + + System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); + viewer.repaint(); + } + } + + // Reset zoom-in point. + to = null; + + } + + } + +} diff --git a/src/main/java/com/aparapi/examples/javaonedemo/NBody.java b/src/main/java/com/aparapi/examples/javaonedemo/NBody.java index 0bdc8d2d..74b41f41 100644 --- a/src/main/java/com/aparapi/examples/javaonedemo/NBody.java +++ b/src/main/java/com/aparapi/examples/javaonedemo/NBody.java @@ -1,391 +1,406 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ -package com.aparapi.examples.javaonedemo; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import com.jogamp.opengl.GL; -import com.jogamp.opengl.GL2; -import com.jogamp.opengl.GLAutoDrawable; -import com.jogamp.opengl.GLCapabilities; -import com.jogamp.opengl.GLEventListener; -import com.jogamp.opengl.GLException; -import com.jogamp.opengl.GLProfile; -import com.jogamp.opengl.awt.GLCanvas; -import com.jogamp.opengl.fixedfunc.GLLightingFunc; -import com.jogamp.opengl.glu.GLU; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.WindowConstants; - -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; -import com.jogamp.opengl.util.FPSAnimator; -import com.jogamp.opengl.util.gl2.GLUT; -import com.jogamp.opengl.util.texture.Texture; -import com.jogamp.opengl.util.texture.TextureIO; - -/** - * NBody implementing demonstrating Aparapi kernels. - * - * For a description of the NBody problem. - * @see http://en.wikipedia.org/wiki/N-body_problem - * - * We use JOGL to render the bodies. - * @see http://jogamp.org/jogl/www/ - * - * @author gfrost - * - */ -public class NBody{ - - public static class NBodyKernel extends Kernel{ - protected final float delT = .005f; - - protected final float espSqr = 1.0f; - - protected final float mass = 5f; - - private final Range range; - - private final float[] xyz; // positions xy and z of bodies - - private final float[] vxyz; // velocity component of x,y and z of bodies - - /** - * Constructor initializes xyz and vxyz arrays. - * @param _bodies - */ - public NBodyKernel(Range _range) { - range = _range; - // range = Range.create(bodies); - xyz = new float[range.getGlobalSize(0) * 3]; - vxyz = new float[range.getGlobalSize(0) * 3]; - final float maxDist = 20f; - for (int body = 0; body < (range.getGlobalSize(0) * 3); body += 3) { - - final float theta = (float) (Math.random() * Math.PI * 2); - final float phi = (float) (Math.random() * Math.PI * 2); - final float radius = (float) (Math.random() * maxDist); - - // get the 3D dimensional coordinates - xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); - xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); - xyz[body + 2] = (float) (radius * Math.cos(phi)); - - // divide into two 'spheres of bodies' by adjusting x - - if ((body % 2) == 0) { - xyz[body + 0] += maxDist * 1.5; - } else { - xyz[body + 0] -= maxDist * 1.5; - } - } - setExplicit(true); - } - - /** - * Here is the kernel entrypoint. Here is where we calculate the position of each body - */ - @Override public void run() { - final int body = getGlobalId(); - final int count = getGlobalSize(0) * 3; - final int globalId = body * 3; - - float accx = 0.f; - float accy = 0.f; - float accz = 0.f; - - final float myPosx = xyz[globalId + 0]; - final float myPosy = xyz[globalId + 1]; - final float myPosz = xyz[globalId + 2]; - for (int i = 0; i < count; i += 3) { - final float dx = xyz[i + 0] - myPosx; - final float dy = xyz[i + 1] - myPosy; - final float dz = xyz[i + 2] - myPosz; - final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); - final float s = mass * invDist * invDist * invDist; - accx = accx + (s * dx); - accy = accy + (s * dy); - accz = accz + (s * dz); - } - accx = accx * delT; - accy = accy * delT; - accz = accz * delT; - xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); - xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); - xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); - - vxyz[globalId + 0] = vxyz[globalId + 0] + accx; - vxyz[globalId + 1] = vxyz[globalId + 1] + accy; - vxyz[globalId + 2] = vxyz[globalId + 2] + accz; - } - - /** - * Render all particles to the OpenGL context - * @param gl - */ - - protected void render(GL2 gl) { - gl.glBegin(GL2.GL_QUADS); - - for (int i = 0; i < (range.getGlobalSize(0) * 3); i += 3) { - gl.glTexCoord2f(0, 1); - gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); - gl.glTexCoord2f(0, 0); - gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 0); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 1); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); - } - gl.glEnd(); - } - - } - - public static int width; - - public static int height; - - public static boolean running; - - public static Texture texture; - - public static void main(String _args[]) { - - final NBodyKernel kernel = new NBodyKernel(Range.create(Integer.getInteger("bodies", 10000))); - kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); - final JFrame frame = new JFrame("NBody"); - - final JPanel panel = new JPanel(new BorderLayout()); - final JPanel controlPanel = new JPanel(new FlowLayout()); - panel.add(controlPanel, BorderLayout.SOUTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - - // controlPanel.add(new JLabel(" Particles")); - - final String[] choices = new String[] { - // "Java Sequential", - "Java Threads", - "GPU OpenCL" - }; - - final JComboBox modeButton = new JComboBox(choices); - - modeButton.addItemListener(new ItemListener(){ - @Override public void itemStateChanged(ItemEvent e) { - final String item = (String) modeButton.getSelectedItem(); - - // if (item.equals(choices[2])) { - // modeButton = gpuMandelBrot; - // } else - if (item.equals(choices[0])) { - kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); - - // modeButton = javaMandelBrot; - } else if (item.equals(choices[1])) { - // lifeKernel = lifeKernelGPU; - // modeButton = javaMandelBrotMultiThread; - kernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); - } - } - - }); - controlPanel.add(modeButton); - - controlPanel.add(new JLabel(" " + kernel.range.getGlobalSize(0) + " Particles")); - - final GLCapabilities caps = new GLCapabilities(null); - final GLProfile profile = caps.getGLProfile(); - caps.setDoubleBuffered(true); - caps.setHardwareAccelerated(true); - final GLCanvas canvas = new GLCanvas(caps); - - final GLUT glut = new GLUT(); - - final Dimension dimension = new Dimension(Integer.getInteger("width", 1024 + 256), - Integer.getInteger("height", 768 - 64 - 32)); - canvas.setPreferredSize(dimension); - - canvas.addGLEventListener(new GLEventListener(){ - private double ratio; - - private final float xeye = 0f; - - private final float yeye = 0f; - - private final float zeye = 100f; - - private final float xat = 0f; - - private final float yat = 0f; - - private final float zat = 0f; - - public final float zoomFactor = 1.0f; - - private int frames; - - private long last = System.currentTimeMillis(); - - @Override public void dispose(GLAutoDrawable drawable) { - - } - - @Override public void display(GLAutoDrawable drawable) { - - final GL2 gl = drawable.getGL().getGL2(); - texture.enable(gl); - texture.bind(gl); - - gl.glLoadIdentity(); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glColor3f(1f, 1f, 1f); - - final GLU glu = new GLU(); - glu.gluPerspective(45f, ratio, 0f, 1000f); - - glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); - if (running) { - kernel.execute(kernel.range); - if (kernel.isExplicit()) { - kernel.get(kernel.xyz); - } - final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - } - kernel.render(gl); - - final long now = System.currentTimeMillis(); - final long time = now - last; - frames++; - - if (running) { - final float framesPerSecond = (frames * 1000.0f) / time; - - gl.glColor3f(.5f, .5f, .5f); - gl.glRasterPos2i(-40, 38); - glut.glutBitmapString(8, String.format("%5.2f fps", framesPerSecond)); - gl.glFlush(); - } - frames = 0; - last = now; - - } - - @Override public void init(GLAutoDrawable drawable) { - final GL2 gl = drawable.getGL().getGL2(); - - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - gl.glEnable(GL.GL_BLEND); - gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); - try { - final InputStream textureStream = NBody.class.getResourceAsStream("particle.jpg"); - texture = TextureIO.newTexture(textureStream, false, null); - } catch (final IOException e) { - e.printStackTrace(); - } catch (final GLException e) { - e.printStackTrace(); - } - - } - - @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { - width = _width; - height = _height; - - final GL2 gl = drawable.getGL().getGL2(); - gl.glViewport(0, 0, width, height); - - ratio = (double) width / (double) height; - - } - - }); - - panel.add(canvas, BorderLayout.CENTER); - frame.getContentPane().add(panel, BorderLayout.CENTER); - final FPSAnimator animator = new FPSAnimator(canvas, 100); - - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - frame.pack(); - frame.setVisible(true); - - animator.start(); - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ +package com.aparapi.examples.javaonedemo; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLException; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.fixedfunc.GLLightingFunc; +import com.jogamp.opengl.glu.GLU; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; +import com.jogamp.opengl.util.FPSAnimator; +import com.jogamp.opengl.util.gl2.GLUT; +import com.jogamp.opengl.util.texture.Texture; +import com.jogamp.opengl.util.texture.TextureIO; + +/** + * NBody implementing demonstrating Aparapi kernels. + * + * For a description of the NBody problem. + * @see http://en.wikipedia.org/wiki/N-body_problem + * + * We use JOGL to render the bodies. + * @see http://jogamp.org/jogl/www/ + * + * @author gfrost + * + */ +public class NBody{ + + public static class NBodyKernel extends Kernel{ + protected final float delT = .005f; + + protected final float espSqr = 1.0f; + + protected final float mass = 5f; + + private final Range range; + + private final float[] xyz; // positions xy and z of bodies + + private final float[] vxyz; // velocity component of x,y and z of bodies + + /** + * Constructor initializes xyz and vxyz arrays. + * @param _bodies + */ + public NBodyKernel(Range _range) { + range = _range; + // range = Range.create(bodies); + xyz = new float[range.getGlobalSize(0) * 3]; + vxyz = new float[range.getGlobalSize(0) * 3]; + final float maxDist = 20f; + for (int body = 0; body < (range.getGlobalSize(0) * 3); body += 3) { + + final float theta = (float) (Math.random() * Math.PI * 2); + final float phi = (float) (Math.random() * Math.PI * 2); + final float radius = (float) (Math.random() * maxDist); + + // get the 3D dimensional coordinates + xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); + xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); + xyz[body + 2] = (float) (radius * Math.cos(phi)); + + // divide into two 'spheres of bodies' by adjusting x + + if ((body % 2) == 0) { + xyz[body + 0] += maxDist * 1.5; + } else { + xyz[body + 0] -= maxDist * 1.5; + } + } + setExplicit(true); + } + + /** + * Here is the kernel entrypoint. Here is where we calculate the position of each body + */ + @Override public void run() { + final int body = getGlobalId(); + final int count = getGlobalSize(0) * 3; + final int globalId = body * 3; + + float accx = 0.f; + float accy = 0.f; + float accz = 0.f; + + final float myPosx = xyz[globalId + 0]; + final float myPosy = xyz[globalId + 1]; + final float myPosz = xyz[globalId + 2]; + for (int i = 0; i < count; i += 3) { + final float dx = xyz[i + 0] - myPosx; + final float dy = xyz[i + 1] - myPosy; + final float dz = xyz[i + 2] - myPosz; + final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); + final float s = mass * invDist * invDist * invDist; + accx = accx + (s * dx); + accy = accy + (s * dy); + accz = accz + (s * dz); + } + accx = accx * delT; + accy = accy * delT; + accz = accz * delT; + xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); + xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); + xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); + + vxyz[globalId + 0] = vxyz[globalId + 0] + accx; + vxyz[globalId + 1] = vxyz[globalId + 1] + accy; + vxyz[globalId + 2] = vxyz[globalId + 2] + accz; + } + + /** + * Render all particles to the OpenGL context + * @param gl + */ + + protected void render(GL2 gl) { + gl.glBegin(GL2.GL_QUADS); + + for (int i = 0; i < (range.getGlobalSize(0) * 3); i += 3) { + gl.glTexCoord2f(0, 1); + gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); + gl.glTexCoord2f(0, 0); + gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 0); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 1); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); + } + gl.glEnd(); + } + + } + + public static int width; + + public static int height; + + public static boolean running; + + public static Texture texture; + + public static void main(String _args[]) { + + final NBodyKernel kernel = new NBodyKernel(Range.create(Integer.getInteger("bodies", 10000))); + kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); + final JFrame frame = new JFrame("NBody"); + + final JPanel panel = new JPanel(new BorderLayout()); + final JPanel controlPanel = new JPanel(new FlowLayout()); + panel.add(controlPanel, BorderLayout.SOUTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + + // controlPanel.add(new JLabel(" Particles")); + + final String[] choices = new String[] { + // "Java Sequential", + "Java Threads", + "GPU OpenCL" + }; + + final JComboBox modeButton = new JComboBox(choices); + + modeButton.addItemListener(new ItemListener(){ + @Override public void itemStateChanged(ItemEvent e) { + final String item = (String) modeButton.getSelectedItem(); + + // if (item.equals(choices[2])) { + // modeButton = gpuMandelBrot; + // } else + if (item.equals(choices[0])) { + kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP); + + // modeButton = javaMandelBrot; + } else if (item.equals(choices[1])) { + // lifeKernel = lifeKernelGPU; + // modeButton = javaMandelBrotMultiThread; + kernel.setExecutionMode(Kernel.EXECUTION_MODE.GPU); + } + } + + }); + controlPanel.add(modeButton); + + controlPanel.add(new JLabel(" " + kernel.range.getGlobalSize(0) + " Particles")); + + final GLCapabilities caps = new GLCapabilities(null); + final GLProfile profile = caps.getGLProfile(); + caps.setDoubleBuffered(true); + caps.setHardwareAccelerated(true); + final GLCanvas canvas = new GLCanvas(caps); + + final GLUT glut = new GLUT(); + + final Dimension dimension = new Dimension(Integer.getInteger("width", 1024 + 256), + Integer.getInteger("height", 768 - 64 - 32)); + canvas.setPreferredSize(dimension); + + canvas.addGLEventListener(new GLEventListener(){ + private double ratio; + + private final float xeye = 0f; + + private final float yeye = 0f; + + private final float zeye = 100f; + + private final float xat = 0f; + + private final float yat = 0f; + + private final float zat = 0f; + + public final float zoomFactor = 1.0f; + + private int frames; + + private long last = System.currentTimeMillis(); + + @Override public void dispose(GLAutoDrawable drawable) { + + } + + @Override public void display(GLAutoDrawable drawable) { + + final GL2 gl = drawable.getGL().getGL2(); + texture.enable(gl); + texture.bind(gl); + + gl.glLoadIdentity(); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glColor3f(1f, 1f, 1f); + + final GLU glu = new GLU(); + glu.gluPerspective(45f, ratio, 0f, 1000f); + + glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); + if (running) { + kernel.execute(kernel.range); + if (kernel.isExplicit()) { + kernel.get(kernel.xyz); + } + final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + } + kernel.render(gl); + + final long now = System.currentTimeMillis(); + final long time = now - last; + frames++; + + if (running) { + final float framesPerSecond = (frames * 1000.0f) / time; + + gl.glColor3f(.5f, .5f, .5f); + gl.glRasterPos2i(-40, 38); + glut.glutBitmapString(8, String.format("%5.2f fps", framesPerSecond)); + gl.glFlush(); + } + frames = 0; + last = now; + + } + + @Override public void init(GLAutoDrawable drawable) { + final GL2 gl = drawable.getGL().getGL2(); + + gl.glShadeModel(GLLightingFunc.GL_SMOOTH); + gl.glEnable(GL.GL_BLEND); + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); + try { + final InputStream textureStream = NBody.class.getResourceAsStream("particle.jpg"); + texture = TextureIO.newTexture(textureStream, false, null); + } catch (final IOException e) { + e.printStackTrace(); + } catch (final GLException e) { + e.printStackTrace(); + } + + } + + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { + width = _width; + height = _height; + + final GL2 gl = drawable.getGL().getGL2(); + gl.glViewport(0, 0, width, height); + + ratio = (double) width / (double) height; + + } + + }); + + panel.add(canvas, BorderLayout.CENTER); + frame.getContentPane().add(panel, BorderLayout.CENTER); + final FPSAnimator animator = new FPSAnimator(canvas, 100); + + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + + animator.start(); + + } + +} diff --git a/src/main/java/com/aparapi/examples/life/Main.java b/src/main/java/com/aparapi/examples/life/Main.java index 263b9061..0a0a3596 100644 --- a/src/main/java/com/aparapi/examples/life/Main.java +++ b/src/main/java/com/aparapi/examples/life/Main.java @@ -1,280 +1,295 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.life; - -import com.aparapi.Kernel; -import com.aparapi.*; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; -import java.util.List; - -/** - * An example Aparapi application which demonstrates Conways 'Game Of Life'. - * - * Original code from Witold Bolt's site https://github.com/houp/aparapi/tree/master/samples/gameoflife. - * - * Converted to use int buffer and some performance tweaks by Gary Frost - * - * @author Wiltold Bolt - * @author Gary Frost - */ -public class Main{ - - /** - * LifeKernel represents the data parallel algorithm describing by Conway's game of life. - * - * http://en.wikipedia.org/wiki/Conway's_Game_of_Life - * - * We examine the state of each pixel and its 8 neighbors and apply the following rules. - * - * if pixel is dead (off) and number of neighbors == 3 { - * pixel is turned on - * } else if pixel is alive (on) and number of neighbors is neither 2 or 3 - * pixel is turned off - * } - * - * We use an image buffer which is 2*width*height the size of screen and we use fromBase and toBase to track which half of the buffer is being mutated for each pass. We basically - * copy from getGlobalId()+fromBase to getGlobalId()+toBase; - * - * - * Prior to each pass the values of fromBase and toBase are swapped. - * - */ - - public static class LifeKernel extends Kernel{ - - private static final int ALIVE = 0xffffff; - - private static final int DEAD = 0; - - private final int[] imageData; - - private final int width; - - private final int height; - - private final Range range; - - private int fromBase; - - private int toBase; - - public LifeKernel(int _width, int _height, BufferedImage _image) { - imageData = ((DataBufferInt) _image.getRaster().getDataBuffer()).getData(); - width = _width; - height = _height; - - final String executionMode = System.getProperty("com.aparapi.executionMode"); - if ((executionMode != null) && executionMode.equals("JTP")) { - range = Range.create(width * height, 4); - } else { - range = Range.create(width * height); - } - - System.out.println("range = " + range); - fromBase = height * width; - toBase = 0; - setExplicit(true); // This gives us a performance boost - - /** draw a line across the image **/ - for (int i = (width * (height / 2)) + (width / 10); i < ((width * ((height / 2) + 1)) - (width / 10)); i++) { - imageData[i] = LifeKernel.ALIVE; - } - - put(imageData); // Because we are using explicit buffer management we must put the imageData array - } - - public void processPixel(int gid) { - final int to = gid + toBase; - final int from = gid + fromBase; - final int x = gid % width; - final int y = gid / width; - - if (((x == 0) || (x == (width - 1)) || (y == 0) || (y == (height - 1)))) { - // This pixel is on the border of the view, just keep existing value - imageData[to] = imageData[from]; - } else { - // Count the number of neighbors. We use (value&1x) to turn pixel value into either 0 or 1 - final int neighbors = (imageData[from - 1] & 1) + // EAST - (imageData[from + 1] & 1) + // WEST - (imageData[from - width - 1] & 1) + // NORTHEAST - (imageData[from - width] & 1) + // NORTH - (imageData[(from - width) + 1] & 1) + // NORTHWEST - (imageData[(from + width) - 1] & 1) + // SOUTHEAST - (imageData[from + width] & 1) + // SOUTH - (imageData[from + width + 1] & 1); // SOUTHWEST - - // The game of life logic - if ((neighbors == 3) || ((neighbors == 2) && (imageData[from] == ALIVE))) { - imageData[to] = ALIVE; - } else { - imageData[to] = DEAD; - } - - } - } - - @Override public void run() { - final int gid = getGlobalId(); - processPixel(gid); - } - - boolean sequential = Boolean.getBoolean("sequential"); - - public void nextGeneration() { - // swap fromBase and toBase - final int swap = fromBase; - fromBase = toBase; - toBase = swap; - if (sequential) { - for (int gid = 0; gid < (width * height); gid++) { - processPixel(gid); - } - - } else { - execute(range); - } - - } - - } - - static boolean running = false; - - public static void main(String[] _args) { - - final JFrame frame = new JFrame("Game of Life"); - final int width = Integer.getInteger("width", 1024 + 512 + 256 + 128); - - final int height = Integer.getInteger("height", 768 + 256); - - // Buffer is twice the size as the screen. We will alternate between mutating data from top to bottom - // and bottom to top in alternate generation passses. The LifeKernel will track which pass is which - final BufferedImage image = new BufferedImage(width, height * 2, BufferedImage.TYPE_INT_RGB); - - final LifeKernel lifeKernel = new LifeKernel(width, height, image); - - // Create a component for viewing the offsecreen image - @SuppressWarnings("serial") final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - if (lifeKernel.isExplicit()) { - lifeKernel.get(lifeKernel.imageData); // We only pull the imageData when we intend to use it. - final List<ProfileInfo> profileInfo = lifeKernel.getProfileInfo(); - if (profileInfo != null) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " - + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - } - } - // We copy one half of the offscreen buffer to the viewer, we copy the half that we just mutated. - if (lifeKernel.fromBase == 0) { - g.drawImage(image, 0, 0, width, height, 0, 0, width, height, this); - } else { - g.drawImage(image, 0, 0, width, height, 0, height, width, 2 * height, this); - } - } - }; - - final JPanel controlPanel = new JPanel(new FlowLayout()); - frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - controlPanel.add(new JLabel(lifeKernel.getTargetDevice().getShortDescription())); - - controlPanel.add(new JLabel(" Generations/Second=")); - final JLabel generationsPerSecond = new JLabel("0.00"); - controlPanel.add(generationsPerSecond); - - // Set the default size and add to the frames content pane - viewer.setPreferredSize(new Dimension(width, height)); - frame.getContentPane().add(viewer); - - // Swing housekeeping - frame.pack(); - frame.setVisible(true); - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - - long start = System.currentTimeMillis(); - long generations = 0; - while (!running) { - try { - Thread.sleep(10); - viewer.repaint(); - } catch (final InterruptedException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - while (true) { - - lifeKernel.nextGeneration(); // Work is performed here - viewer.repaint(); // Request a repaint of the viewer (causes paintComponent(Graphics) to be called later not synchronous - generations++; - final long now = System.currentTimeMillis(); - if ((now - start) > 1000) { - generationsPerSecond.setText(String.format("%5.2f", (generations * 1000.0) / (now - start))); - start = now; - generations = 0; - } - } - - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.life; + +import com.aparapi.Kernel; +import com.aparapi.*; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import java.util.List; + +/** + * An example Aparapi application which demonstrates Conways 'Game Of Life'. + * + * Original code from Witold Bolt's site https://github.com/houp/aparapi/tree/master/samples/gameoflife. + * + * Converted to use int buffer and some performance tweaks by Gary Frost + * + * @author Wiltold Bolt + * @author Gary Frost + */ +public class Main{ + + /** + * LifeKernel represents the data parallel algorithm describing by Conway's game of life. + * + * http://en.wikipedia.org/wiki/Conway's_Game_of_Life + * + * We examine the state of each pixel and its 8 neighbors and apply the following rules. + * + * if pixel is dead (off) and number of neighbors == 3 { + * pixel is turned on + * } else if pixel is alive (on) and number of neighbors is neither 2 or 3 + * pixel is turned off + * } + * + * We use an image buffer which is 2*width*height the size of screen and we use fromBase and toBase to track which half of the buffer is being mutated for each pass. We basically + * copy from getGlobalId()+fromBase to getGlobalId()+toBase; + * + * + * Prior to each pass the values of fromBase and toBase are swapped. + * + */ + + public static class LifeKernel extends Kernel{ + + private static final int ALIVE = 0xffffff; + + private static final int DEAD = 0; + + private final int[] imageData; + + private final int width; + + private final int height; + + private final Range range; + + private int fromBase; + + private int toBase; + + public LifeKernel(int _width, int _height, BufferedImage _image) { + imageData = ((DataBufferInt) _image.getRaster().getDataBuffer()).getData(); + width = _width; + height = _height; + + final String executionMode = System.getProperty("com.aparapi.executionMode"); + if ((executionMode != null) && executionMode.equals("JTP")) { + range = Range.create(width * height, 4); + } else { + range = Range.create(width * height); + } + + System.out.println("range = " + range); + fromBase = height * width; + toBase = 0; + setExplicit(true); // This gives us a performance boost + + /** draw a line across the image **/ + for (int i = (width * (height / 2)) + (width / 10); i < ((width * ((height / 2) + 1)) - (width / 10)); i++) { + imageData[i] = LifeKernel.ALIVE; + } + + put(imageData); // Because we are using explicit buffer management we must put the imageData array + } + + public void processPixel(int gid) { + final int to = gid + toBase; + final int from = gid + fromBase; + final int x = gid % width; + final int y = gid / width; + + if (((x == 0) || (x == (width - 1)) || (y == 0) || (y == (height - 1)))) { + // This pixel is on the border of the view, just keep existing value + imageData[to] = imageData[from]; + } else { + // Count the number of neighbors. We use (value&1x) to turn pixel value into either 0 or 1 + final int neighbors = (imageData[from - 1] & 1) + // EAST + (imageData[from + 1] & 1) + // WEST + (imageData[from - width - 1] & 1) + // NORTHEAST + (imageData[from - width] & 1) + // NORTH + (imageData[(from - width) + 1] & 1) + // NORTHWEST + (imageData[(from + width) - 1] & 1) + // SOUTHEAST + (imageData[from + width] & 1) + // SOUTH + (imageData[from + width + 1] & 1); // SOUTHWEST + + // The game of life logic + if ((neighbors == 3) || ((neighbors == 2) && (imageData[from] == ALIVE))) { + imageData[to] = ALIVE; + } else { + imageData[to] = DEAD; + } + + } + } + + @Override public void run() { + final int gid = getGlobalId(); + processPixel(gid); + } + + boolean sequential = Boolean.getBoolean("sequential"); + + public void nextGeneration() { + // swap fromBase and toBase + final int swap = fromBase; + fromBase = toBase; + toBase = swap; + if (sequential) { + for (int gid = 0; gid < (width * height); gid++) { + processPixel(gid); + } + + } else { + execute(range); + } + + } + + } + + static boolean running = false; + + public static void main(String[] _args) { + + final JFrame frame = new JFrame("Game of Life"); + final int width = Integer.getInteger("width", 1024 + 512 + 256 + 128); + + final int height = Integer.getInteger("height", 768 + 256); + + // Buffer is twice the size as the screen. We will alternate between mutating data from top to bottom + // and bottom to top in alternate generation passses. The LifeKernel will track which pass is which + final BufferedImage image = new BufferedImage(width, height * 2, BufferedImage.TYPE_INT_RGB); + + final LifeKernel lifeKernel = new LifeKernel(width, height, image); + + // Create a component for viewing the offsecreen image + @SuppressWarnings("serial") final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + if (lifeKernel.isExplicit()) { + lifeKernel.get(lifeKernel.imageData); // We only pull the imageData when we intend to use it. + final List<ProfileInfo> profileInfo = lifeKernel.getProfileInfo(); + if (profileInfo != null) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + } + } + // We copy one half of the offscreen buffer to the viewer, we copy the half that we just mutated. + if (lifeKernel.fromBase == 0) { + g.drawImage(image, 0, 0, width, height, 0, 0, width, height, this); + } else { + g.drawImage(image, 0, 0, width, height, 0, height, width, 2 * height, this); + } + } + }; + + final JPanel controlPanel = new JPanel(new FlowLayout()); + frame.getContentPane().add(controlPanel, BorderLayout.SOUTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + controlPanel.add(new JLabel(lifeKernel.getTargetDevice().getShortDescription())); + + controlPanel.add(new JLabel(" Generations/Second=")); + final JLabel generationsPerSecond = new JLabel("0.00"); + controlPanel.add(generationsPerSecond); + + // Set the default size and add to the frames content pane + viewer.setPreferredSize(new Dimension(width, height)); + frame.getContentPane().add(viewer); + + // Swing housekeeping + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + long start = System.currentTimeMillis(); + long generations = 0; + while (!running) { + try { + Thread.sleep(10); + viewer.repaint(); + } catch (final InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + while (true) { + + lifeKernel.nextGeneration(); // Work is performed here + viewer.repaint(); // Request a repaint of the viewer (causes paintComponent(Graphics) to be called later not synchronous + generations++; + final long now = System.currentTimeMillis(); + if ((now - start) > 1000) { + generationsPerSecond.setText(String.format("%5.2f", (generations * 1000.0) / (now - start))); + start = now; + generations = 0; + } + } + + } +} diff --git a/src/main/java/com/aparapi/examples/mandel/Main.java b/src/main/java/com/aparapi/examples/mandel/Main.java index a9bd900d..b4427166 100644 --- a/src/main/java/com/aparapi/examples/mandel/Main.java +++ b/src/main/java/com/aparapi/examples/mandel/Main.java @@ -1,316 +1,331 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.mandel; - -import com.aparapi.Kernel; -import com.aparapi.*; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; -import java.util.List; - -/** - * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. - * - * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. - * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example - * application might suffer with sub-optimal frame refresh rate as compared to GPU. - * - * @author gfrost - * - */ - -public class Main{ - - static { - System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); -// KernelManager.setKernelManager(new KernelManager() { -// @Override -// protected List<Device.TYPE> getPreferredDeviceTypes() { -// return Collections.singletonList(Device.TYPE.CPU); -// } -// }); - } - - /** - * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. - * - * @author gfrost - * - */ - - public static class MandelKernel extends Kernel{ - - /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ - private int[] rgb; - - /** Mandelbrot image width. */ - private int width; - - /** Mandelbrot image height. */ - private int height; - - /** Maximum iterations for Mandelbrot. */ - final private int maxIterations = 64; - - /** Palette which maps iteration values to RGB values. */ - @Constant final private int pallette[] = new int[maxIterations + 1]; - - /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ - private float scale = .0f; - - private float offsetx = .0f; - - private float offsety = .0f; - - /** - * Initialize the Kernel. - * - * @param _width Mandelbrot image width - * @param _height Mandelbrot image height - * @param _rgb Mandelbrot image RGB buffer - */ - public MandelKernel(int _width, int _height, int[] _rgb) { - //Initialize palette values - for (int i = 0; i < maxIterations; i++) { - final float h = i / (float) maxIterations; - final float b = 1.0f - (h * h); - pallette[i] = Color.HSBtoRGB(h, 1f, b); - } - - width = _width; - height = _height; - rgb = _rgb; - - } - - public void resetImage(int _width, int _height, int[] _rgb) { - width = _width; - height = _height; - rgb = _rgb; - } - - public int getCount(float x, float y) { - int count = 0; - - float zx = x; - float zy = y; - float new_zx = 0f; - - // Iterate until the algorithm converges or until maxIterations are reached. - while ((count < maxIterations) && (((zx * zx) + (zy * zy)) < 8)) { - new_zx = ((zx * zx) - (zy * zy)) + x; - zy = (2 * zx * zy) + y; - zx = new_zx; - count++; - } - - return count; - } - - @Override public void run() { - - /** Determine which RGB value we are going to process (0..RGB.length). */ - final int gid = getGlobalId(); - - /** Translate the gid into an x an y value. */ - final float x = ((((gid % width) * scale) - ((scale / 2) * width)) / width) + offsetx; - - final float y = ((((gid / width) * scale) - ((scale / 2) * height)) / height) + offsety; - - int count = getCount(x, y); - - // Pull the value out of the palette for this iteration count. - rgb[gid] = pallette[count]; - } - - public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { - offsetx = _offsetx; - offsety = _offsety; - scale = _scale; - } - - public int[] getRgbs() { - return rgb; - } - } - - /** User selected zoom-in point on the Mandelbrot view. */ - public static volatile Point to = null; - - @SuppressWarnings("serial") public static void main(String[] _args) { - - final JFrame frame = new JFrame("MandelBrot"); - - /** Width of Mandelbrot view. */ - final int width = 768; - - /** Height of Mandelbrot view. */ - final int height = 768; - - /** Mandelbrot image height. */ - final Range range = Range.create(width * height); - - /** Image for Mandelbrot view. */ - final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - final BufferedImage offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - // Draw Mandelbrot image - final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - - g.drawImage(image, 0, 0, width, height, this); - } - }; - - // Set the size of JComponent which displays Mandelbrot image - viewer.setPreferredSize(new Dimension(width, height)); - - final Object doorBell = new Object(); - - // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view - viewer.addMouseListener(new MouseAdapter(){ - @Override public void mouseClicked(MouseEvent e) { - to = e.getPoint(); - synchronized (doorBell) { - doorBell.notify(); - } - } - }); - - // Swing housework to create the frame - frame.getContentPane().add(viewer); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - - // Extract the underlying RGB buffer from the image. - // Pass this to the kernel so it operates directly on the RGB buffer of the image - final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); - final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - // Create a Kernel passing the size, RGB buffer and the palette. - final MandelKernel kernel = new MandelKernel(width, height, rgb); - - final float defaultScale = 3f; - - // Set the default scale and offset, execute the kernel and force a repaint of the viewer. - kernel.setScaleAndOffset(defaultScale, -1f, 0f); - kernel.execute(range); - - System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); - viewer.repaint(); - - System.out.println("device=" + kernel.getTargetDevice()); - - // Window listener to dispose Kernel resources on user exit. - frame.addWindowListener(new WindowAdapter(){ - @Override public void windowClosing(WindowEvent _windowEvent) { - kernel.dispose(); - System.exit(0); - } - }); - - // Wait until the user selects a zoom-in point on the Mandelbrot view. - while (true) { - - // Wait for the user to click somewhere - while (to == null) { - synchronized (doorBell) { - try { - doorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - } - - float x = -1f; - float y = 0f; - float scale = defaultScale; - final float tox = ((float) (to.x - (width / 2)) / width) * scale; - final float toy = ((float) (to.y - (height / 2)) / height) * scale; - - // This is how many frames we will display as we zoom in and out. - final int frames = 128; - final long startMillis = System.currentTimeMillis(); - for (int sign = -1; sign < 2; sign += 2) { - for (int i = 0; i < (frames - 4); i++) { - scale = scale + ((sign * defaultScale) / frames); - x = x - (sign * (tox / frames)); - y = y - (sign * (toy / frames)); - - // Set the scale and offset, execute the kernel and force a repaint of the viewer. - kernel.setScaleAndOffset(scale, x, y); - kernel.execute(range); - final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " - + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - - System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); - viewer.repaint(); - } - } - - final long elapsedMillis = System.currentTimeMillis() - startMillis; - System.out.println("FPS = " + ((frames * 1000) / elapsedMillis)); - - // Reset zoom-in point. - to = null; - - } - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.mandel; + +import com.aparapi.Kernel; +import com.aparapi.*; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import java.util.List; + +/** + * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. + * + * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. + * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example + * application might suffer with sub-optimal frame refresh rate as compared to GPU. + * + * @author gfrost + * + */ + +public class Main{ + + static { + System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); +// KernelManager.setKernelManager(new KernelManager() { +// @Override +// protected List<Device.TYPE> getPreferredDeviceTypes() { +// return Collections.singletonList(Device.TYPE.CPU); +// } +// }); + } + + /** + * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. + * + * @author gfrost + * + */ + + public static class MandelKernel extends Kernel{ + + /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ + private int[] rgb; + + /** Mandelbrot image width. */ + private int width; + + /** Mandelbrot image height. */ + private int height; + + /** Maximum iterations for Mandelbrot. */ + final private int maxIterations = 64; + + /** Palette which maps iteration values to RGB values. */ + @Constant final private int pallette[] = new int[maxIterations + 1]; + + /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ + private float scale = .0f; + + private float offsetx = .0f; + + private float offsety = .0f; + + /** + * Initialize the Kernel. + * + * @param _width Mandelbrot image width + * @param _height Mandelbrot image height + * @param _rgb Mandelbrot image RGB buffer + */ + public MandelKernel(int _width, int _height, int[] _rgb) { + //Initialize palette values + for (int i = 0; i < maxIterations; i++) { + final float h = i / (float) maxIterations; + final float b = 1.0f - (h * h); + pallette[i] = Color.HSBtoRGB(h, 1f, b); + } + + width = _width; + height = _height; + rgb = _rgb; + + } + + public void resetImage(int _width, int _height, int[] _rgb) { + width = _width; + height = _height; + rgb = _rgb; + } + + public int getCount(float x, float y) { + int count = 0; + + float zx = x; + float zy = y; + float new_zx = 0f; + + // Iterate until the algorithm converges or until maxIterations are reached. + while ((count < maxIterations) && (((zx * zx) + (zy * zy)) < 8)) { + new_zx = ((zx * zx) - (zy * zy)) + x; + zy = (2 * zx * zy) + y; + zx = new_zx; + count++; + } + + return count; + } + + @Override public void run() { + + /** Determine which RGB value we are going to process (0..RGB.length). */ + final int gid = getGlobalId(); + + /** Translate the gid into an x an y value. */ + final float x = ((((gid % width) * scale) - ((scale / 2) * width)) / width) + offsetx; + + final float y = ((((gid / width) * scale) - ((scale / 2) * height)) / height) + offsety; + + int count = getCount(x, y); + + // Pull the value out of the palette for this iteration count. + rgb[gid] = pallette[count]; + } + + public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { + offsetx = _offsetx; + offsety = _offsety; + scale = _scale; + } + + public int[] getRgbs() { + return rgb; + } + } + + /** User selected zoom-in point on the Mandelbrot view. */ + public static volatile Point to = null; + + @SuppressWarnings("serial") public static void main(String[] _args) { + + final JFrame frame = new JFrame("MandelBrot"); + + /** Width of Mandelbrot view. */ + final int width = 768; + + /** Height of Mandelbrot view. */ + final int height = 768; + + /** Mandelbrot image height. */ + final Range range = Range.create(width * height); + + /** Image for Mandelbrot view. */ + final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + final BufferedImage offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + // Draw Mandelbrot image + final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + + g.drawImage(image, 0, 0, width, height, this); + } + }; + + // Set the size of JComponent which displays Mandelbrot image + viewer.setPreferredSize(new Dimension(width, height)); + + final Object doorBell = new Object(); + + // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view + viewer.addMouseListener(new MouseAdapter(){ + @Override public void mouseClicked(MouseEvent e) { + to = e.getPoint(); + synchronized (doorBell) { + doorBell.notify(); + } + } + }); + + // Swing housework to create the frame + frame.getContentPane().add(viewer); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + // Extract the underlying RGB buffer from the image. + // Pass this to the kernel so it operates directly on the RGB buffer of the image + final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); + final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); + // Create a Kernel passing the size, RGB buffer and the palette. + final MandelKernel kernel = new MandelKernel(width, height, rgb); + + final float defaultScale = 3f; + + // Set the default scale and offset, execute the kernel and force a repaint of the viewer. + kernel.setScaleAndOffset(defaultScale, -1f, 0f); + kernel.execute(range); + + System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); + viewer.repaint(); + + System.out.println("device=" + kernel.getTargetDevice()); + + // Window listener to dispose Kernel resources on user exit. + frame.addWindowListener(new WindowAdapter(){ + @Override public void windowClosing(WindowEvent _windowEvent) { + kernel.dispose(); + System.exit(0); + } + }); + + // Wait until the user selects a zoom-in point on the Mandelbrot view. + while (true) { + + // Wait for the user to click somewhere + while (to == null) { + synchronized (doorBell) { + try { + doorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + } + + float x = -1f; + float y = 0f; + float scale = defaultScale; + final float tox = ((float) (to.x - (width / 2)) / width) * scale; + final float toy = ((float) (to.y - (height / 2)) / height) * scale; + + // This is how many frames we will display as we zoom in and out. + final int frames = 128; + final long startMillis = System.currentTimeMillis(); + for (int sign = -1; sign < 2; sign += 2) { + for (int i = 0; i < (frames - 4); i++) { + scale = scale + ((sign * defaultScale) / frames); + x = x - (sign * (tox / frames)); + y = y - (sign * (toy / frames)); + + // Set the scale and offset, execute the kernel and force a repaint of the viewer. + kernel.setScaleAndOffset(scale, x, y); + kernel.execute(range); + final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + + System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); + viewer.repaint(); + } + } + + final long elapsedMillis = System.currentTimeMillis() - startMillis; + System.out.println("FPS = " + ((frames * 1000) / elapsedMillis)); + + // Reset zoom-in point. + to = null; + + } + + } + +} diff --git a/src/main/java/com/aparapi/examples/mandel/Main2D.java b/src/main/java/com/aparapi/examples/mandel/Main2D.java index 782f27be..4d43f8eb 100644 --- a/src/main/java/com/aparapi/examples/mandel/Main2D.java +++ b/src/main/java/com/aparapi/examples/mandel/Main2D.java @@ -1,276 +1,291 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.mandel; - -import com.aparapi.Kernel; -import com.aparapi.*; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; -import java.util.List; - -/** - * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. - * - * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. - * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example - * application might suffer with sub-optimal frame refresh rate as compared to GPU. - * - * @author gfrost - * - */ - -public class Main2D{ - - /** - * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. - * - * @author gfrost - * - */ - - public static class MandelKernel extends Kernel{ - - /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ - final private int rgb[]; - - /** Maximum iterations we will check for. */ - final private int maxIterations = 64; - - /** Palette maps iteration values to RGB values. */ - @Constant final private int pallette[] = new int[maxIterations + 1]; - - /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ - private float scale = .0f; - - private float offsetx = .0f; - - private float offsety = .0f; - - /** - * Initialize the Kernel. - * - * @param _rgb Mandelbrot image RGB buffer - */ - public MandelKernel(int[] _rgb) { - rgb = _rgb; - - //Initialize palette - for (int i = 0; i < maxIterations; i++) { - final float h = i / (float) maxIterations; - final float b = 1.0f - (h * h); - pallette[i] = Color.HSBtoRGB(h, 1f, b); - } - - } - - @Override public void run() { - - /** Determine which RGB value we are going to process (0..RGB.length). */ - final int gid = (getGlobalId(1) * getGlobalSize(0)) + getGlobalId(0); - - /** Translate the gid into an x an y value. */ - final float x = (((getGlobalId(0) * scale) - ((scale / 2) * getGlobalSize(0))) / getGlobalSize(0)) + offsetx; - - final float y = (((getGlobalId(1) * scale) - ((scale / 2) * getGlobalSize(1))) / getGlobalSize(1)) + offsety; - - int count = 0; - - float zx = x; - float zy = y; - float new_zx = 0f; - - // Iterate until the algorithm converges or until maxIterations are reached. - while ((count < maxIterations) && (((zx * zx) + (zy * zy)) < 8)) { - new_zx = ((zx * zx) - (zy * zy)) + x; - zy = (2 * zx * zy) + y; - zx = new_zx; - count++; - } - - // Pull the value out of the palette for this iteration count. - rgb[gid] = pallette[count]; - } - - public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { - offsetx = _offsetx; - offsety = _offsety; - scale = _scale; - } - - } - - /** User selected zoom-in point on the Mandelbrot view. */ - public static volatile Point to = null; - - @SuppressWarnings("serial") public static void main(String[] _args) { - - - final JFrame frame = new JFrame("MandelBrot"); - - /** Mandelbrot image height. */ - final Range range = Range.create2D(768, 768); - System.out.println("range= " + range); - - /** Image for Mandelbrot view. */ - final BufferedImage image = new BufferedImage(range.getGlobalSize(0), range.getGlobalSize(1), BufferedImage.TYPE_INT_RGB); - final BufferedImage offscreen = new BufferedImage(range.getGlobalSize(0), range.getGlobalSize(1), BufferedImage.TYPE_INT_RGB); - // Draw Mandelbrot image - final JComponent viewer = new JComponent(){ - @Override public void paintComponent(Graphics g) { - - g.drawImage(image, 0, 0, range.getGlobalSize(0), range.getGlobalSize(1), this); - } - }; - - // Set the size of JComponent which displays Mandelbrot image - viewer.setPreferredSize(new Dimension(range.getGlobalSize(0), range.getGlobalSize(1))); - - final Object doorBell = new Object(); - - // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view - viewer.addMouseListener(new MouseAdapter(){ - @Override public void mouseClicked(MouseEvent e) { - to = e.getPoint(); - synchronized (doorBell) { - doorBell.notify(); - } - } - }); - - // Swing housework to create the frame - frame.getContentPane().add(viewer); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - - // Extract the underlying RGB buffer from the image. - // Pass this to the kernel so it operates directly on the RGB buffer of the image - final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); - final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - // Create a Kernel passing the size, RGB buffer and the palette. - final MandelKernel kernel = new MandelKernel(rgb); - - final float defaultScale = 3f; - - // Set the default scale and offset, execute the kernel and force a repaint of the viewer. - kernel.setScaleAndOffset(defaultScale, -1f, 0f); - kernel.execute(range); - System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); - viewer.repaint(); - - System.out.println("device=" + kernel.getTargetDevice()); - - // Window listener to dispose Kernel resources on user exit. - frame.addWindowListener(new WindowAdapter(){ - @Override public void windowClosing(WindowEvent _windowEvent) { - kernel.dispose(); - System.exit(0); - } - }); - - // Wait until the user selects a zoom-in point on the Mandelbrot view. - while (true) { - - // Wait for the user to click somewhere - while (to == null) { - synchronized (doorBell) { - try { - doorBell.wait(); - } catch (final InterruptedException ie) { - ie.getStackTrace(); - } - } - } - - float x = -1f; - float y = 0f; - float scale = defaultScale; - final float tox = ((float) (to.x - (range.getGlobalSize(0) / 2)) / range.getGlobalSize(0)) * scale; - final float toy = ((float) (to.y - (range.getGlobalSize(1) / 2)) / range.getGlobalSize(1)) * scale; - - // This is how many frames we will display as we zoom in and out. - final int frames = 128; - final long startMillis = System.currentTimeMillis(); - for (int sign = -1; sign < 2; sign += 2) { - for (int i = 0; i < (frames - 4); i++) { - scale = scale + ((sign * defaultScale) / frames); - x = x - (sign * (tox / frames)); - y = y - (sign * (toy / frames)); - - // Set the scale and offset, execute the kernel and force a repaint of the viewer. - kernel.setScaleAndOffset(scale, x, y); - kernel.execute(range); - final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " - + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - - System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); - viewer.repaint(); - } - } - - final long elapsedMillis = System.currentTimeMillis() - startMillis; - System.out.println("FPS = " + ((frames * 1000) / elapsedMillis)); - - // Reset zoom-in point. - to = null; - - } - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.mandel; + +import com.aparapi.Kernel; +import com.aparapi.*; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import java.util.List; + +/** + * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. + * + * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. + * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example + * application might suffer with sub-optimal frame refresh rate as compared to GPU. + * + * @author gfrost + * + */ + +public class Main2D{ + + /** + * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. + * + * @author gfrost + * + */ + + public static class MandelKernel extends Kernel{ + + /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ + final private int rgb[]; + + /** Maximum iterations we will check for. */ + final private int maxIterations = 64; + + /** Palette maps iteration values to RGB values. */ + @Constant final private int pallette[] = new int[maxIterations + 1]; + + /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ + private float scale = .0f; + + private float offsetx = .0f; + + private float offsety = .0f; + + /** + * Initialize the Kernel. + * + * @param _rgb Mandelbrot image RGB buffer + */ + public MandelKernel(int[] _rgb) { + rgb = _rgb; + + //Initialize palette + for (int i = 0; i < maxIterations; i++) { + final float h = i / (float) maxIterations; + final float b = 1.0f - (h * h); + pallette[i] = Color.HSBtoRGB(h, 1f, b); + } + + } + + @Override public void run() { + + /** Determine which RGB value we are going to process (0..RGB.length). */ + final int gid = (getGlobalId(1) * getGlobalSize(0)) + getGlobalId(0); + + /** Translate the gid into an x an y value. */ + final float x = (((getGlobalId(0) * scale) - ((scale / 2) * getGlobalSize(0))) / getGlobalSize(0)) + offsetx; + + final float y = (((getGlobalId(1) * scale) - ((scale / 2) * getGlobalSize(1))) / getGlobalSize(1)) + offsety; + + int count = 0; + + float zx = x; + float zy = y; + float new_zx = 0f; + + // Iterate until the algorithm converges or until maxIterations are reached. + while ((count < maxIterations) && (((zx * zx) + (zy * zy)) < 8)) { + new_zx = ((zx * zx) - (zy * zy)) + x; + zy = (2 * zx * zy) + y; + zx = new_zx; + count++; + } + + // Pull the value out of the palette for this iteration count. + rgb[gid] = pallette[count]; + } + + public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { + offsetx = _offsetx; + offsety = _offsety; + scale = _scale; + } + + } + + /** User selected zoom-in point on the Mandelbrot view. */ + public static volatile Point to = null; + + @SuppressWarnings("serial") public static void main(String[] _args) { + + + final JFrame frame = new JFrame("MandelBrot"); + + /** Mandelbrot image height. */ + final Range range = Range.create2D(768, 768); + System.out.println("range= " + range); + + /** Image for Mandelbrot view. */ + final BufferedImage image = new BufferedImage(range.getGlobalSize(0), range.getGlobalSize(1), BufferedImage.TYPE_INT_RGB); + final BufferedImage offscreen = new BufferedImage(range.getGlobalSize(0), range.getGlobalSize(1), BufferedImage.TYPE_INT_RGB); + // Draw Mandelbrot image + final JComponent viewer = new JComponent(){ + @Override public void paintComponent(Graphics g) { + + g.drawImage(image, 0, 0, range.getGlobalSize(0), range.getGlobalSize(1), this); + } + }; + + // Set the size of JComponent which displays Mandelbrot image + viewer.setPreferredSize(new Dimension(range.getGlobalSize(0), range.getGlobalSize(1))); + + final Object doorBell = new Object(); + + // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view + viewer.addMouseListener(new MouseAdapter(){ + @Override public void mouseClicked(MouseEvent e) { + to = e.getPoint(); + synchronized (doorBell) { + doorBell.notify(); + } + } + }); + + // Swing housework to create the frame + frame.getContentPane().add(viewer); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + // Extract the underlying RGB buffer from the image. + // Pass this to the kernel so it operates directly on the RGB buffer of the image + final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); + final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); + // Create a Kernel passing the size, RGB buffer and the palette. + final MandelKernel kernel = new MandelKernel(rgb); + + final float defaultScale = 3f; + + // Set the default scale and offset, execute the kernel and force a repaint of the viewer. + kernel.setScaleAndOffset(defaultScale, -1f, 0f); + kernel.execute(range); + System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); + viewer.repaint(); + + System.out.println("device=" + kernel.getTargetDevice()); + + // Window listener to dispose Kernel resources on user exit. + frame.addWindowListener(new WindowAdapter(){ + @Override public void windowClosing(WindowEvent _windowEvent) { + kernel.dispose(); + System.exit(0); + } + }); + + // Wait until the user selects a zoom-in point on the Mandelbrot view. + while (true) { + + // Wait for the user to click somewhere + while (to == null) { + synchronized (doorBell) { + try { + doorBell.wait(); + } catch (final InterruptedException ie) { + ie.getStackTrace(); + } + } + } + + float x = -1f; + float y = 0f; + float scale = defaultScale; + final float tox = ((float) (to.x - (range.getGlobalSize(0) / 2)) / range.getGlobalSize(0)) * scale; + final float toy = ((float) (to.y - (range.getGlobalSize(1) / 2)) / range.getGlobalSize(1)) * scale; + + // This is how many frames we will display as we zoom in and out. + final int frames = 128; + final long startMillis = System.currentTimeMillis(); + for (int sign = -1; sign < 2; sign += 2) { + for (int i = 0; i < (frames - 4); i++) { + scale = scale + ((sign * defaultScale) / frames); + x = x - (sign * (tox / frames)); + y = y - (sign * (toy / frames)); + + // Set the scale and offset, execute the kernel and force a repaint of the viewer. + kernel.setScaleAndOffset(scale, x, y); + kernel.execute(range); + final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + + (p.getEnd() / 1000) + " " + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + + System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); + viewer.repaint(); + } + } + + final long elapsedMillis = System.currentTimeMillis() - startMillis; + System.out.println("FPS = " + ((frames * 1000) / elapsedMillis)); + + // Reset zoom-in point. + to = null; + + } + + } + +} diff --git a/src/main/java/com/aparapi/examples/mapreduce/Main.java b/src/main/java/com/aparapi/examples/mapreduce/Main.java index 48ab1fb2..7404e977 100644 --- a/src/main/java/com/aparapi/examples/mapreduce/Main.java +++ b/src/main/java/com/aparapi/examples/mapreduce/Main.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.aparapi.examples.mapreduce; import com.aparapi.Kernel; diff --git a/src/main/java/com/aparapi/examples/mdarray/BMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/BMatMul1D.java index 82e5180b..57c89928 100644 --- a/src/main/java/com/aparapi/examples/mdarray/BMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/BMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class BMatMul1D extends Kernel{ - byte[] A; - - byte[] B; - - byte[] C; - - int N; - - public BMatMul1D(byte[] A, byte[] B, byte[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] += (byte) (A[i * N + k] * B[k * N + j]); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class BMatMul1D extends Kernel{ + byte[] A; + + byte[] B; + + byte[] C; + + int N; + + public BMatMul1D(byte[] A, byte[] B, byte[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] += (byte) (A[i * N + k] * B[k * N + j]); + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/BMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/BMatMul2D.java index be315fbe..cce05282 100644 --- a/src/main/java/com/aparapi/examples/mdarray/BMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/BMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class BMatMul2D extends Kernel{ - byte[][] A; - - byte[][] B; - - byte[][] C; - - int N; - - public BMatMul2D(byte[][] A, byte[][] B, byte[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] += (byte) (A[i][k] * B[k][j]); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class BMatMul2D extends Kernel{ + byte[][] A; + + byte[][] B; + + byte[][] C; + + int N; + + public BMatMul2D(byte[][] A, byte[][] B, byte[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] += (byte) (A[i][k] * B[k][j]); + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/BMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/BMatMul3D.java index 7f7cf58b..90d85328 100644 --- a/src/main/java/com/aparapi/examples/mdarray/BMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/BMatMul3D.java @@ -1,43 +1,58 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class BMatMul3D extends Kernel{ - byte[][][] A; - - byte[][][] B; - - byte[][][] C; - - int N; - - public BMatMul3D(byte[][][] A, byte[][][] B, byte[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - int a0 = A.length; - int a1 = A[0].length; - int a2 = A[0][0].length; - for (int l = 0; l < N; l++) { - C[i][j][k] += (byte) (A[i][j][l] * B[l][j][k]); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class BMatMul3D extends Kernel{ + byte[][][] A; + + byte[][][] B; + + byte[][][] C; + + int N; + + public BMatMul3D(byte[][][] A, byte[][][] B, byte[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + int a0 = A.length; + int a1 = A[0].length; + int a2 = A[0][0].length; + for (int l = 0; l < N; l++) { + C[i][j][k] += (byte) (A[i][j][l] * B[l][j][k]); + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/DMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/DMatMul1D.java index 8a463d77..e31aab30 100644 --- a/src/main/java/com/aparapi/examples/mdarray/DMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/DMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class DMatMul1D extends Kernel{ - double[] A; - - double[] B; - - double[] C; - - int N; - - public DMatMul1D(double[] A, double[] B, double[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] += A[i * N + k] * B[k * N + j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class DMatMul1D extends Kernel{ + double[] A; + + double[] B; + + double[] C; + + int N; + + public DMatMul1D(double[] A, double[] B, double[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] += A[i * N + k] * B[k * N + j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/DMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/DMatMul2D.java index a30c901e..8b762e8f 100644 --- a/src/main/java/com/aparapi/examples/mdarray/DMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/DMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class DMatMul2D extends Kernel{ - double[][] A; - - double[][] B; - - double[][] C; - - int N; - - public DMatMul2D(double[][] A, double[][] B, double[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] += A[i][k] * B[k][j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class DMatMul2D extends Kernel{ + double[][] A; + + double[][] B; + + double[][] C; + + int N; + + public DMatMul2D(double[][] A, double[][] B, double[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] += A[i][k] * B[k][j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/DMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/DMatMul3D.java index 6c745a5a..20169745 100644 --- a/src/main/java/com/aparapi/examples/mdarray/DMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/DMatMul3D.java @@ -1,40 +1,55 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class DMatMul3D extends Kernel{ - double[][][] A; - - double[][][] B; - - double[][][] C; - - int N; - - public DMatMul3D(double[][][] A, double[][][] B, double[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - for (int l = 0; l < N; l++) { - C[i][j][k] += A[i][j][l] * B[l][j][k]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class DMatMul3D extends Kernel{ + double[][][] A; + + double[][][] B; + + double[][][] C; + + int N; + + public DMatMul3D(double[][][] A, double[][][] B, double[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + for (int l = 0; l < N; l++) { + C[i][j][k] += A[i][j][l] * B[l][j][k]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/FMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/FMatMul1D.java index 49562376..da525e03 100644 --- a/src/main/java/com/aparapi/examples/mdarray/FMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/FMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class FMatMul1D extends Kernel{ - float[] A; - - float[] B; - - float[] C; - - int N; - - public FMatMul1D(float[] A, float[] B, float[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] += A[i * N + k] * B[k * N + j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class FMatMul1D extends Kernel{ + float[] A; + + float[] B; + + float[] C; + + int N; + + public FMatMul1D(float[] A, float[] B, float[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] += A[i * N + k] * B[k * N + j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/FMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/FMatMul2D.java index eba56715..39b27831 100644 --- a/src/main/java/com/aparapi/examples/mdarray/FMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/FMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class FMatMul2D extends Kernel{ - float[][] A; - - float[][] B; - - float[][] C; - - int N; - - public FMatMul2D(float[][] A, float[][] B, float[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] += A[i][k] * B[k][j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class FMatMul2D extends Kernel{ + float[][] A; + + float[][] B; + + float[][] C; + + int N; + + public FMatMul2D(float[][] A, float[][] B, float[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] += A[i][k] * B[k][j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/FMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/FMatMul3D.java index a4fd8a09..252e558a 100644 --- a/src/main/java/com/aparapi/examples/mdarray/FMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/FMatMul3D.java @@ -1,40 +1,55 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class FMatMul3D extends Kernel{ - float[][][] A; - - float[][][] B; - - float[][][] C; - - int N; - - public FMatMul3D(float[][][] A, float[][][] B, float[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - for (int l = 0; l < N; l++) { - C[i][j][k] += A[i][j][l] * B[l][j][k]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class FMatMul3D extends Kernel{ + float[][][] A; + + float[][][] B; + + float[][][] C; + + int N; + + public FMatMul3D(float[][][] A, float[][][] B, float[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + for (int l = 0; l < N; l++) { + C[i][j][k] += A[i][j][l] * B[l][j][k]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/IMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/IMatMul1D.java index dbd7fe42..cc3b55d5 100644 --- a/src/main/java/com/aparapi/examples/mdarray/IMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/IMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class IMatMul1D extends Kernel{ - int[] A; - - int[] B; - - int[] C; - - int N; - - public IMatMul1D(int[] A, int[] B, int[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] += A[i * N + k] * B[k * N + j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class IMatMul1D extends Kernel{ + int[] A; + + int[] B; + + int[] C; + + int N; + + public IMatMul1D(int[] A, int[] B, int[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] += A[i * N + k] * B[k * N + j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/IMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/IMatMul2D.java index 69cf36fa..1bcca20c 100644 --- a/src/main/java/com/aparapi/examples/mdarray/IMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/IMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class IMatMul2D extends Kernel{ - int[][] A; - - int[][] B; - - int[][] C; - - int N; - - public IMatMul2D(int[][] A, int[][] B, int[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] += A[i][k] * B[k][j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class IMatMul2D extends Kernel{ + int[][] A; + + int[][] B; + + int[][] C; + + int N; + + public IMatMul2D(int[][] A, int[][] B, int[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] += A[i][k] * B[k][j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/IMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/IMatMul3D.java index 44017bcb..dfde5d5b 100644 --- a/src/main/java/com/aparapi/examples/mdarray/IMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/IMatMul3D.java @@ -1,40 +1,55 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class IMatMul3D extends Kernel{ - int[][][] A; - - int[][][] B; - - int[][][] C; - - int N; - - public IMatMul3D(int[][][] A, int[][][] B, int[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - for (int l = 0; l < N; l++) { - C[i][j][k] += A[i][j][l] * B[l][j][k]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class IMatMul3D extends Kernel{ + int[][][] A; + + int[][][] B; + + int[][][] C; + + int N; + + public IMatMul3D(int[][][] A, int[][][] B, int[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + for (int l = 0; l < N; l++) { + C[i][j][k] += A[i][j][l] * B[l][j][k]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/LMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/LMatMul1D.java index 7b013f93..91efc6b8 100644 --- a/src/main/java/com/aparapi/examples/mdarray/LMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/LMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class LMatMul1D extends Kernel{ - long[] A; - - long[] B; - - long[] C; - - int N; - - public LMatMul1D(long[] A, long[] B, long[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] += A[i * N + k] * B[k * N + j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class LMatMul1D extends Kernel{ + long[] A; + + long[] B; + + long[] C; + + int N; + + public LMatMul1D(long[] A, long[] B, long[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] += A[i * N + k] * B[k * N + j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/LMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/LMatMul2D.java index c541c8e5..f0f0c07f 100644 --- a/src/main/java/com/aparapi/examples/mdarray/LMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/LMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class LMatMul2D extends Kernel{ - long[][] A; - - long[][] B; - - long[][] C; - - int N; - - public LMatMul2D(long[][] A, long[][] B, long[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] += A[i][k] * B[k][j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class LMatMul2D extends Kernel{ + long[][] A; + + long[][] B; + + long[][] C; + + int N; + + public LMatMul2D(long[][] A, long[][] B, long[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] += A[i][k] * B[k][j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/LMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/LMatMul3D.java index b5460e8f..7756a488 100644 --- a/src/main/java/com/aparapi/examples/mdarray/LMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/LMatMul3D.java @@ -1,40 +1,55 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class LMatMul3D extends Kernel{ - long[][][] A; - - long[][][] B; - - long[][][] C; - - int N; - - public LMatMul3D(long[][][] A, long[][][] B, long[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - for (int l = 0; l < N; l++) { - C[i][j][k] += A[i][j][l] * B[l][j][k]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class LMatMul3D extends Kernel{ + long[][][] A; + + long[][][] B; + + long[][][] C; + + int N; + + public LMatMul3D(long[][][] A, long[][][] B, long[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + for (int l = 0; l < N; l++) { + C[i][j][k] += A[i][j][l] * B[l][j][k]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/MDArray.java b/src/main/java/com/aparapi/examples/mdarray/MDArray.java index 7414b7ea..236aed87 100644 --- a/src/main/java/com/aparapi/examples/mdarray/MDArray.java +++ b/src/main/java/com/aparapi/examples/mdarray/MDArray.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/mdarray/SMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/SMatMul1D.java index 9dfbf467..7efa5c5b 100644 --- a/src/main/java/com/aparapi/examples/mdarray/SMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/SMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class SMatMul1D extends Kernel{ - short[] A; - - short[] B; - - short[] C; - - int N; - - public SMatMul1D(short[] A, short[] B, short[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] += (short) (A[i * N + k] * B[k * N + j]); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class SMatMul1D extends Kernel{ + short[] A; + + short[] B; + + short[] C; + + int N; + + public SMatMul1D(short[] A, short[] B, short[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] += (short) (A[i * N + k] * B[k * N + j]); + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/SMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/SMatMul2D.java index c5e829c8..59437a2f 100644 --- a/src/main/java/com/aparapi/examples/mdarray/SMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/SMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class SMatMul2D extends Kernel{ - short[][] A; - - short[][] B; - - short[][] C; - - int N; - - public SMatMul2D(short[][] A, short[][] B, short[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] += (short) (A[i][k] * B[k][j]); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class SMatMul2D extends Kernel{ + short[][] A; + + short[][] B; + + short[][] C; + + int N; + + public SMatMul2D(short[][] A, short[][] B, short[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] += (short) (A[i][k] * B[k][j]); + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/SMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/SMatMul3D.java index 8828e557..603d4007 100644 --- a/src/main/java/com/aparapi/examples/mdarray/SMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/SMatMul3D.java @@ -1,40 +1,55 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class SMatMul3D extends Kernel{ - short[][][] A; - - short[][][] B; - - short[][][] C; - - int N; - - public SMatMul3D(short[][][] A, short[][][] B, short[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - for (int l = 0; l < N; l++) { - C[i][j][k] += (short) (A[i][j][l] * B[l][j][k]); - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class SMatMul3D extends Kernel{ + short[][][] A; + + short[][][] B; + + short[][][] C; + + int N; + + public SMatMul3D(short[][][] A, short[][][] B, short[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + for (int l = 0; l < N; l++) { + C[i][j][k] += (short) (A[i][j][l] * B[l][j][k]); + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/ZMatMul1D.java b/src/main/java/com/aparapi/examples/mdarray/ZMatMul1D.java index 3f0dd511..442b8c09 100644 --- a/src/main/java/com/aparapi/examples/mdarray/ZMatMul1D.java +++ b/src/main/java/com/aparapi/examples/mdarray/ZMatMul1D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class ZMatMul1D extends Kernel{ - boolean[] A; - - boolean[] B; - - boolean[] C; - - int N; - - public ZMatMul1D(boolean[] A, boolean[] B, boolean[] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i * N + j] ^= A[i * N + k] & B[k * N + j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class ZMatMul1D extends Kernel{ + boolean[] A; + + boolean[] B; + + boolean[] C; + + int N; + + public ZMatMul1D(boolean[] A, boolean[] B, boolean[] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i * N + j] ^= A[i * N + k] & B[k * N + j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/ZMatMul2D.java b/src/main/java/com/aparapi/examples/mdarray/ZMatMul2D.java index b60a4fc9..a0a6ad1a 100644 --- a/src/main/java/com/aparapi/examples/mdarray/ZMatMul2D.java +++ b/src/main/java/com/aparapi/examples/mdarray/ZMatMul2D.java @@ -1,39 +1,54 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class ZMatMul2D extends Kernel{ - boolean[][] A; - - boolean[][] B; - - boolean[][] C; - - int N; - - public ZMatMul2D(boolean[][] A, boolean[][] B, boolean[][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / N; - int j = id % N; - for (int k = 0; k < N; k++) { - C[i][j] ^= A[i][k] & B[k][j]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class ZMatMul2D extends Kernel{ + boolean[][] A; + + boolean[][] B; + + boolean[][] C; + + int N; + + public ZMatMul2D(boolean[][] A, boolean[][] B, boolean[][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / N; + int j = id % N; + for (int k = 0; k < N; k++) { + C[i][j] ^= A[i][k] & B[k][j]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/mdarray/ZMatMul3D.java b/src/main/java/com/aparapi/examples/mdarray/ZMatMul3D.java index 5d3f27f1..33aabb11 100644 --- a/src/main/java/com/aparapi/examples/mdarray/ZMatMul3D.java +++ b/src/main/java/com/aparapi/examples/mdarray/ZMatMul3D.java @@ -1,40 +1,55 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.mdarray; - -import com.aparapi.Kernel; - -class ZMatMul3D extends Kernel{ - boolean[][][] A; - - boolean[][][] B; - - boolean[][][] C; - - int N; - - public ZMatMul3D(boolean[][][] A, boolean[][][] B, boolean[][][] C, int N) { - this.A = A; - this.B = B; - this.C = C; - this.N = N; - } - - @Override public void run() { - int id = getGlobalId(); - int i = id / (N * N); - int j = (id / N) % N; - int k = id % N; - for (int l = 0; l < N; l++) { - C[i][j][k] ^= A[i][j][l] & B[l][j][k]; - } - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.mdarray; + +import com.aparapi.Kernel; + +class ZMatMul3D extends Kernel{ + boolean[][][] A; + + boolean[][][] B; + + boolean[][][] C; + + int N; + + public ZMatMul3D(boolean[][][] A, boolean[][][] B, boolean[][][] C, int N) { + this.A = A; + this.B = B; + this.C = C; + this.N = N; + } + + @Override public void run() { + int id = getGlobalId(); + int i = id / (N * N); + int j = (id / N) % N; + int k = id % N; + for (int l = 0; l < N; l++) { + C[i][j][k] ^= A[i][j][l] & B[l][j][k]; + } + } +} diff --git a/src/main/java/com/aparapi/examples/median/MedianDemo.java b/src/main/java/com/aparapi/examples/median/MedianDemo.java index 230815ac..b565839d 100644 --- a/src/main/java/com/aparapi/examples/median/MedianDemo.java +++ b/src/main/java/com/aparapi/examples/median/MedianDemo.java @@ -1,115 +1,130 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.median; - -import com.aparapi.internal.kernel.*; - -import javax.imageio.*; -import javax.swing.*; -import java.awt.*; -import java.awt.image.*; -import java.io.*; - -/** - * Demonstrate use of __private namespaces and @NoCL annotations. - */ -public class MedianDemo { - public static BufferedImage testImage; - - static { - try { - File imageFile = new File("./src/main/resources/testcard.jpg").getCanonicalFile(); - if (imageFile.exists()) { - testImage = ImageIO.read(imageFile); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void main(String[] ignored) { - final int size = 5; - System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); - boolean verbose = false; - if (verbose) - { - System.setProperty("com.aparapi.enableVerboseJNI", "true"); - System.setProperty("com.aparapi.dumpFlags", "true"); - System.setProperty("com.aparapi.enableShowGeneratedOpenCL", "true"); - System.setProperty("com.aparapi.enableVerboseJNIOpenCLResourceTracking", "true"); - System.setProperty("com.aparapi.enableExecutionModeReporting", "true"); - } - -// KernelManager.setKernelManager(new KernelManager(){ -// @Override -// protected Comparator<OpenCLDevice> getDefaultGPUComparator() { -// return new Comparator<OpenCLDevice>() { -// @Override -// public int compare(OpenCLDevice o1, OpenCLDevice o2) { -// return o2.getMaxComputeUnits() - o1.getMaxComputeUnits(); -// } -// }; -// } -// }); - - System.out.println(KernelManager.instance().bestDevice()); - - int[] argbs = testImage.getRGB(0, 0, testImage.getWidth(), testImage.getHeight(), null, 0, testImage.getWidth()); - MedianKernel7x7 kernel = createMedianKernel(argbs); - - kernel.processImages(new MedianSettings(size)); - BufferedImage out = new BufferedImage(testImage.getWidth(), testImage.getHeight(), BufferedImage.TYPE_INT_RGB); - out.setRGB(0, 0, testImage.getWidth(), testImage.getHeight(), kernel._destPixels, 0, testImage.getWidth()); - ImageIcon icon1 = new ImageIcon(testImage); - JLabel label1 = new JLabel(icon1); - ImageIcon icon2 = new ImageIcon(out); - JLabel label2 = new JLabel(icon2); - JFrame frame = new JFrame("Test Median"); - frame.setLayout(new FlowLayout()); - frame.getContentPane().add(label1); - frame.getContentPane().add(label2); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.setVisible(true); - - StringBuilder builder = new StringBuilder(); - KernelManager.instance().reportDeviceUsage(builder, true); - System.out.println(builder); - - int reps = 50; - final boolean newKernel = false; - for (int rep = 0; rep < reps; ++rep) { - if (newKernel) { - kernel.dispose(); - kernel = createMedianKernel(argbs); - } - long start = System.nanoTime(); - kernel.processImages(new MedianSettings(size)); - long elapsed = System.nanoTime() - start; - System.out.println("elapsed = " + elapsed / 1000000f + "ms"); - } - - builder = new StringBuilder(); - KernelManager.instance().reportDeviceUsage(builder, true); - System.out.println(builder); - } - - private static MedianKernel7x7 createMedianKernel(int[] argbs) { - MedianKernel7x7 kernel = new MedianKernel7x7(); - kernel._imageTypeOrdinal = MedianKernel7x7.RGB; - kernel._sourceWidth = testImage.getWidth(); - kernel._sourceHeight = testImage.getHeight(); - kernel._sourcePixels = argbs; - kernel._destPixels = new int[argbs.length]; - return kernel; - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.median; + +import com.aparapi.internal.kernel.*; + +import javax.imageio.*; +import javax.swing.*; +import java.awt.*; +import java.awt.image.*; +import java.io.*; + +/** + * Demonstrate use of __private namespaces and @NoCL annotations. + */ +public class MedianDemo { + public static BufferedImage testImage; + + static { + try { + File imageFile = new File("./src/main/resources/testcard.jpg").getCanonicalFile(); + if (imageFile.exists()) { + testImage = ImageIO.read(imageFile); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static void main(String[] ignored) { + final int size = 5; + System.setProperty("com.aparapi.dumpProfilesOnExit", "true"); + boolean verbose = false; + if (verbose) + { + System.setProperty("com.aparapi.enableVerboseJNI", "true"); + System.setProperty("com.aparapi.dumpFlags", "true"); + System.setProperty("com.aparapi.enableShowGeneratedOpenCL", "true"); + System.setProperty("com.aparapi.enableVerboseJNIOpenCLResourceTracking", "true"); + System.setProperty("com.aparapi.enableExecutionModeReporting", "true"); + } + +// KernelManager.setKernelManager(new KernelManager(){ +// @Override +// protected Comparator<OpenCLDevice> getDefaultGPUComparator() { +// return new Comparator<OpenCLDevice>() { +// @Override +// public int compare(OpenCLDevice o1, OpenCLDevice o2) { +// return o2.getMaxComputeUnits() - o1.getMaxComputeUnits(); +// } +// }; +// } +// }); + + System.out.println(KernelManager.instance().bestDevice()); + + int[] argbs = testImage.getRGB(0, 0, testImage.getWidth(), testImage.getHeight(), null, 0, testImage.getWidth()); + MedianKernel7x7 kernel = createMedianKernel(argbs); + + kernel.processImages(new MedianSettings(size)); + BufferedImage out = new BufferedImage(testImage.getWidth(), testImage.getHeight(), BufferedImage.TYPE_INT_RGB); + out.setRGB(0, 0, testImage.getWidth(), testImage.getHeight(), kernel._destPixels, 0, testImage.getWidth()); + ImageIcon icon1 = new ImageIcon(testImage); + JLabel label1 = new JLabel(icon1); + ImageIcon icon2 = new ImageIcon(out); + JLabel label2 = new JLabel(icon2); + JFrame frame = new JFrame("Test Median"); + frame.setLayout(new FlowLayout()); + frame.getContentPane().add(label1); + frame.getContentPane().add(label2); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + + StringBuilder builder = new StringBuilder(); + KernelManager.instance().reportDeviceUsage(builder, true); + System.out.println(builder); + + int reps = 50; + final boolean newKernel = false; + for (int rep = 0; rep < reps; ++rep) { + if (newKernel) { + kernel.dispose(); + kernel = createMedianKernel(argbs); + } + long start = System.nanoTime(); + kernel.processImages(new MedianSettings(size)); + long elapsed = System.nanoTime() - start; + System.out.println("elapsed = " + elapsed / 1000000f + "ms"); + } + + builder = new StringBuilder(); + KernelManager.instance().reportDeviceUsage(builder, true); + System.out.println(builder); + } + + private static MedianKernel7x7 createMedianKernel(int[] argbs) { + MedianKernel7x7 kernel = new MedianKernel7x7(); + kernel._imageTypeOrdinal = MedianKernel7x7.RGB; + kernel._sourceWidth = testImage.getWidth(); + kernel._sourceHeight = testImage.getHeight(); + kernel._sourcePixels = argbs; + kernel._destPixels = new int[argbs.length]; + return kernel; + } +} diff --git a/src/main/java/com/aparapi/examples/median/MedianKernel7x7.java b/src/main/java/com/aparapi/examples/median/MedianKernel7x7.java index 48903ca6..dddcd912 100644 --- a/src/main/java/com/aparapi/examples/median/MedianKernel7x7.java +++ b/src/main/java/com/aparapi/examples/median/MedianKernel7x7.java @@ -1,179 +1,194 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.median; - -import com.aparapi.*; - -/** - * Provides support for pixel windows of size no greater than 49 (e.g. 7x7). - * <p/> - * <p>Demonstrates use of __private array for (partial) sorting, also demonstrates @NoCl annotation for specialised use of ThreadLocal in JTP execution. - */ -public class MedianKernel7x7 extends Kernel { - public static final int CHANNEL_GRAY = -1; - public static final int CHANNEL_ALPHA = 0; - public static final int CHANNEL_RED = 1; - public static final int CHANNEL_GREEN = 2; - public static final int CHANNEL_BLUE = 3; - - protected static final int MONOCHROME = 0; - protected static final int RGB = 1; - protected static final int ARGB = 2; - - public static final int MAX_WINDOW_SIZE = 49; - - protected int _imageTypeOrdinal; - protected int[] _sourcePixels; - protected int _sourceWidth; - protected int _sourceHeight; - - protected int[] _destPixels; - - // NB could also use suffix naming instead of annotation ... field would be named _window_$private$49 - @PrivateMemorySpace(MAX_WINDOW_SIZE) - private short[] _window = new short[MAX_WINDOW_SIZE]; - @NoCL private static ThreadLocal<short[]> _threadLocalWindow = new ThreadLocal<short[]>() { - @Override - protected short[] initialValue() { - return new short[MAX_WINDOW_SIZE]; - } - }; - protected int _windowWidth; - protected int _windowHeight; - - @NoCL - public void setUpWindow() { - _window = _threadLocalWindow.get(); - } - - public void processImages(MedianSettings settings) { - _windowWidth = settings.windowWidth; - _windowHeight = settings.windowHeight; - execute(_sourceWidth * _sourceHeight); - } - - @Override - public void run() { - setUpWindow(); - int index = getGlobalId(); - int x = index % _sourceWidth; - int y = index / _sourceWidth; - - int dx0 = -(_windowWidth / 2); - int dx1 = _windowWidth + dx0; - int dy0 = -(_windowHeight / 2); - int dy1 = _windowHeight + dy0; - - int windowX0 = max(0, x + dx0); - int windowX1 = min(_sourceWidth, x + dx1); - int windowY0 = max(0, y + dy0); - int windowY1 = min(_sourceHeight, y + dy1); - - int actualPixelCount = (windowX1 - windowX0) * (windowY1 - windowY0); - int medianPixel = 0; - - if (_imageTypeOrdinal == MONOCHROME) { - populateWindow(CHANNEL_GRAY, windowX0, windowX1, windowY0, windowY1); - medianPixel = median(actualPixelCount); - } else { - int alpha = 0xff000000; - if (_imageTypeOrdinal == ARGB) { - populateWindow(CHANNEL_ALPHA, windowX0, windowX1, windowY0, windowY1); - alpha = median(actualPixelCount); - } - populateWindow(CHANNEL_RED, windowX0, windowX1, windowY0, windowY1); - int red = median(actualPixelCount); - populateWindow(CHANNEL_GREEN, windowX0, windowX1, windowY0, windowY1); - int green = median(actualPixelCount); - populateWindow(CHANNEL_BLUE, windowX0, windowX1, windowY0, windowY1); - int blue = median(actualPixelCount); - medianPixel = alpha << 24 | red << 16 | green << 8 | blue; - } - - _destPixels[index] = medianPixel; - } - - protected void populateWindow(int channel, int windowX0, int windowX1, int windowY0, int windowY1) { - int windowIndex = 0; - for (int u = windowX0; u < windowX1; ++u) { - for (int v = windowY0; v < windowY1; ++v) { - int argb = _sourcePixels[u + _sourceWidth * v]; - int sourcePixel = valueForChannel(channel, argb); - setPixelWindowValue(windowIndex, (short) sourcePixel); - ++windowIndex; - } - } - } - - protected final int valueForChannel(int channel, int argb) { - int sourcePixel = 0; - if (channel == CHANNEL_GRAY) { - sourcePixel = argb; - } else if (channel == CHANNEL_ALPHA) { - sourcePixel = (0xff000000 & argb) >>> 24; - } else if (channel == CHANNEL_RED) { - sourcePixel = (0x00ff0000 & argb) >>> 16; - } else if (channel == CHANNEL_GREEN) { - sourcePixel = (0x0000ff00 & argb) >>> 8; - } else if (channel == CHANNEL_BLUE) { - sourcePixel = 0x000000ff & argb; - } - return sourcePixel; - } - - protected void setPixelWindowValue(int windowIndex, short value) { - _window[windowIndex] = value; - } - - /** - * Fast median based on the following algorithm - * <pre> - * Author: Wirth, Niklaus - * Title: Algorithms + data structures = programs - * Publisher: Englewood Cliffs: Prentice-Hall, 1976 - * </pre> - */ - protected final int median(int actualPixelCount) { - int i, j, L, m; - short x; - - L = 0; - m = actualPixelCount - 1; - while (L < m) { - x = _window[(actualPixelCount / 2)]; - i = L; - j = m; - do { - while (_window[i] < x) { - i++; - } - while (x < _window[j]) { - j--; - } - if (i <= j) { - short temp = _window[i]; - _window[i] = _window[j]; - _window[j] = temp; - i++; - j--; - } - } while (i <= j); - - if (j < actualPixelCount / 2) { - L = i; - } - if (actualPixelCount / 2 < i) { - m = j; - } - } - return _window[(actualPixelCount / 2)]; - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.median; + +import com.aparapi.*; + +/** + * Provides support for pixel windows of size no greater than 49 (e.g. 7x7). + * <p/> + * <p>Demonstrates use of __private array for (partial) sorting, also demonstrates @NoCl annotation for specialised use of ThreadLocal in JTP execution. + */ +public class MedianKernel7x7 extends Kernel { + public static final int CHANNEL_GRAY = -1; + public static final int CHANNEL_ALPHA = 0; + public static final int CHANNEL_RED = 1; + public static final int CHANNEL_GREEN = 2; + public static final int CHANNEL_BLUE = 3; + + protected static final int MONOCHROME = 0; + protected static final int RGB = 1; + protected static final int ARGB = 2; + + public static final int MAX_WINDOW_SIZE = 49; + + protected int _imageTypeOrdinal; + protected int[] _sourcePixels; + protected int _sourceWidth; + protected int _sourceHeight; + + protected int[] _destPixels; + + // NB could also use suffix naming instead of annotation ... field would be named _window_$private$49 + @PrivateMemorySpace(MAX_WINDOW_SIZE) + private short[] _window = new short[MAX_WINDOW_SIZE]; + @NoCL private static ThreadLocal<short[]> _threadLocalWindow = new ThreadLocal<short[]>() { + @Override + protected short[] initialValue() { + return new short[MAX_WINDOW_SIZE]; + } + }; + protected int _windowWidth; + protected int _windowHeight; + + @NoCL + public void setUpWindow() { + _window = _threadLocalWindow.get(); + } + + public void processImages(MedianSettings settings) { + _windowWidth = settings.windowWidth; + _windowHeight = settings.windowHeight; + execute(_sourceWidth * _sourceHeight); + } + + @Override + public void run() { + setUpWindow(); + int index = getGlobalId(); + int x = index % _sourceWidth; + int y = index / _sourceWidth; + + int dx0 = -(_windowWidth / 2); + int dx1 = _windowWidth + dx0; + int dy0 = -(_windowHeight / 2); + int dy1 = _windowHeight + dy0; + + int windowX0 = max(0, x + dx0); + int windowX1 = min(_sourceWidth, x + dx1); + int windowY0 = max(0, y + dy0); + int windowY1 = min(_sourceHeight, y + dy1); + + int actualPixelCount = (windowX1 - windowX0) * (windowY1 - windowY0); + int medianPixel = 0; + + if (_imageTypeOrdinal == MONOCHROME) { + populateWindow(CHANNEL_GRAY, windowX0, windowX1, windowY0, windowY1); + medianPixel = median(actualPixelCount); + } else { + int alpha = 0xff000000; + if (_imageTypeOrdinal == ARGB) { + populateWindow(CHANNEL_ALPHA, windowX0, windowX1, windowY0, windowY1); + alpha = median(actualPixelCount); + } + populateWindow(CHANNEL_RED, windowX0, windowX1, windowY0, windowY1); + int red = median(actualPixelCount); + populateWindow(CHANNEL_GREEN, windowX0, windowX1, windowY0, windowY1); + int green = median(actualPixelCount); + populateWindow(CHANNEL_BLUE, windowX0, windowX1, windowY0, windowY1); + int blue = median(actualPixelCount); + medianPixel = alpha << 24 | red << 16 | green << 8 | blue; + } + + _destPixels[index] = medianPixel; + } + + protected void populateWindow(int channel, int windowX0, int windowX1, int windowY0, int windowY1) { + int windowIndex = 0; + for (int u = windowX0; u < windowX1; ++u) { + for (int v = windowY0; v < windowY1; ++v) { + int argb = _sourcePixels[u + _sourceWidth * v]; + int sourcePixel = valueForChannel(channel, argb); + setPixelWindowValue(windowIndex, (short) sourcePixel); + ++windowIndex; + } + } + } + + protected final int valueForChannel(int channel, int argb) { + int sourcePixel = 0; + if (channel == CHANNEL_GRAY) { + sourcePixel = argb; + } else if (channel == CHANNEL_ALPHA) { + sourcePixel = (0xff000000 & argb) >>> 24; + } else if (channel == CHANNEL_RED) { + sourcePixel = (0x00ff0000 & argb) >>> 16; + } else if (channel == CHANNEL_GREEN) { + sourcePixel = (0x0000ff00 & argb) >>> 8; + } else if (channel == CHANNEL_BLUE) { + sourcePixel = 0x000000ff & argb; + } + return sourcePixel; + } + + protected void setPixelWindowValue(int windowIndex, short value) { + _window[windowIndex] = value; + } + + /** + * Fast median based on the following algorithm + * <pre> + * Author: Wirth, Niklaus + * Title: Algorithms + data structures = programs + * Publisher: Englewood Cliffs: Prentice-Hall, 1976 + * </pre> + */ + protected final int median(int actualPixelCount) { + int i, j, L, m; + short x; + + L = 0; + m = actualPixelCount - 1; + while (L < m) { + x = _window[(actualPixelCount / 2)]; + i = L; + j = m; + do { + while (_window[i] < x) { + i++; + } + while (x < _window[j]) { + j--; + } + if (i <= j) { + short temp = _window[i]; + _window[i] = _window[j]; + _window[j] = temp; + i++; + j--; + } + } while (i <= j); + + if (j < actualPixelCount / 2) { + L = i; + } + if (actualPixelCount / 2 < i) { + m = j; + } + } + return _window[(actualPixelCount / 2)]; + } +} diff --git a/src/main/java/com/aparapi/examples/median/MedianSettings.java b/src/main/java/com/aparapi/examples/median/MedianSettings.java index 948042de..9c45b385 100644 --- a/src/main/java/com/aparapi/examples/median/MedianSettings.java +++ b/src/main/java/com/aparapi/examples/median/MedianSettings.java @@ -1,25 +1,40 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.median; - -public class MedianSettings { - public final int windowWidth; - public final int windowHeight; - - public MedianSettings(int windowSize) { - this(windowSize, windowSize); - } - - public MedianSettings(int windowWidth, int windowHeight) { - this.windowWidth = windowWidth; - this.windowHeight = windowHeight; - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.median; + +public class MedianSettings { + public final int windowWidth; + public final int windowHeight; + + public MedianSettings(int windowSize) { + this(windowSize, windowSize); + } + + public MedianSettings(int windowWidth, int windowHeight) { + this.windowWidth = windowWidth; + this.windowHeight = windowHeight; + } +} diff --git a/src/main/java/com/aparapi/examples/nbody/Local.java b/src/main/java/com/aparapi/examples/nbody/Local.java index 1b8fccd5..93926b16 100644 --- a/src/main/java/com/aparapi/examples/nbody/Local.java +++ b/src/main/java/com/aparapi/examples/nbody/Local.java @@ -1,375 +1,390 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ -package com.aparapi.examples.nbody; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import com.jogamp.opengl.GL; -import com.jogamp.opengl.GL2; -import com.jogamp.opengl.GLAutoDrawable; -import com.jogamp.opengl.GLCapabilities; -import com.jogamp.opengl.GLEventListener; -import com.jogamp.opengl.GLException; -import com.jogamp.opengl.awt.GLCanvas; -import com.jogamp.opengl.fixedfunc.GLLightingFunc; -import com.jogamp.opengl.glu.GLU; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.WindowConstants; - -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; -import com.jogamp.opengl.util.FPSAnimator; -import com.jogamp.opengl.util.texture.Texture; -import com.jogamp.opengl.util.texture.TextureIO; - -/** - * An NBody clone which uses local memory to cache NBody positions for execution. - * - * http://www.browndeertechnology.com/docs/BDT_OpenCL_Tutorial_NBody-rev3.html - * - * @see Main - * - * @author gfrost - * - */ -public class Local{ - - public static class NBodyKernel extends Kernel{ - protected final float delT = .005f; - - protected final float espSqr = 1.0f; - - protected final float mass = 5f; - - private final Range range; - - private final float[] xyz; // positions xy and z of bodies - - private final float[] vxyz; // velocity component of x,y and z of bodies - - @Local private final float[] localStuff; // local memory - - /** - * Constructor initializes xyz and vxyz arrays. - * @param _bodies - */ - public NBodyKernel(Range _range) { - range = _range; - localStuff = new float[range.getLocalSize(0) * 3]; - - xyz = new float[range.getGlobalSize(0) * 3]; - vxyz = new float[range.getGlobalSize(0) * 3]; - final float maxDist = 20f; - for (int body = 0; body < (range.getGlobalSize(0) * 3); body += 3) { - final float theta = (float) (Math.random() * Math.PI * 2); - final float phi = (float) (Math.random() * Math.PI * 2); - final float radius = (float) (Math.random() * maxDist); - - // get the 3D dimensional coordinates - xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); - xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); - xyz[body + 2] = (float) (radius * Math.cos(phi)); - - // divide into two 'spheres of bodies' by adjusting x - if ((body % 2) == 0) { - xyz[body + 0] += maxDist * 1.5; - } else { - xyz[body + 0] -= maxDist * 1.5; - } - } - setExplicit(true); - } - - /** - * Here is the kernel entrypoint. Here is where we calculate the position of each body - */ - @Override public void run() { - - final int globalId = getGlobalId(0) * 3; - - float accx = 0.f; - float accy = 0.f; - float accz = 0.f; - final float myPosx = xyz[globalId + 0]; - final float myPosy = xyz[globalId + 1]; - final float myPosz = xyz[globalId + 2]; - - for (int tile = 0; tile < (getGlobalSize(0) / getLocalSize(0)); tile++) { - // load one tile into local memory - final int gidx = ((tile * getLocalSize(0)) + getLocalId()) * 3; - final int lidx = getLocalId(0) * 3; - localStuff[lidx + 0] = xyz[gidx + 0]; - localStuff[lidx + 1] = xyz[gidx + 1]; - localStuff[lidx + 2] = xyz[gidx + 2]; - // Synchronize to make sure data is available for processing - localBarrier(); - - for (int i = 0; i < (getLocalSize() * 3); i += 3) { - final float dx = localStuff[i + 0] - myPosx; - final float dy = localStuff[i + 1] - myPosy; - final float dz = localStuff[i + 2] - myPosz; - final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); - final float s = mass * invDist * invDist * invDist; - accx = accx + (s * dx); - accy = accy + (s * dy); - accz = accz + (s * dz); - } - localBarrier(); - } - accx = accx * delT; - accy = accy * delT; - accz = accz * delT; - xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); - xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); - xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); - - vxyz[globalId + 0] = vxyz[globalId + 0] + accx; - vxyz[globalId + 1] = vxyz[globalId + 1] + accy; - vxyz[globalId + 2] = vxyz[globalId + 2] + accz; - } - - /** - * Render all particles to the OpenGL context - * @param gl - */ - - protected void render(GL2 gl) { - gl.glBegin(GL2.GL_QUADS); - - for (int i = 0; i < (range.getGlobalSize(0) * 3); i += 3) { - gl.glTexCoord2f(0, 1); - gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); - gl.glTexCoord2f(0, 0); - gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 0); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 1); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); - } - gl.glEnd(); - } - - } - - public static int width; - - public static int height; - - public static boolean running; - - public static void main(String _args[]) { - - final NBodyKernel kernel = new NBodyKernel(Range.create(Integer.getInteger("bodies", 8192), 256)); - - final JFrame frame = new JFrame("NBody"); - - final JPanel panel = new JPanel(new BorderLayout()); - final JPanel controlPanel = new JPanel(new FlowLayout()); - panel.add(controlPanel, BorderLayout.SOUTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - controlPanel.add(new JLabel(kernel.getExecutionMode().toString())); - - controlPanel.add(new JLabel(" Particles")); - controlPanel.add(new JTextField("" + kernel.range.getGlobalSize(0), 5)); - - controlPanel.add(new JLabel("FPS")); - final JTextField framesPerSecondTextField = new JTextField("0", 5); - - controlPanel.add(framesPerSecondTextField); - controlPanel.add(new JLabel("Score(")); - final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); - - controlPanel.add(miniLabel); - controlPanel.add(new JLabel(")")); - - final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); - - controlPanel.add(positionUpdatesPerMicroSecondTextField); - final GLCapabilities caps = new GLCapabilities(null); - caps.setDoubleBuffered(true); - caps.setHardwareAccelerated(true); - final GLCanvas canvas = new GLCanvas(caps); - final Dimension dimension = new Dimension(Integer.getInteger("width", 742), Integer.getInteger("height", 742)); - canvas.setPreferredSize(dimension); - - canvas.addGLEventListener(new GLEventListener(){ - private double ratio; - - private final float xeye = 0f; - - private final float yeye = 0f; - - private final float zeye = 100f; - - private final float xat = 0f; - - private final float yat = 0f; - - private final float zat = 0f; - - public final float zoomFactor = 1.0f; - - private int frames; - - private long last = System.currentTimeMillis(); - - @Override public void dispose(GLAutoDrawable drawable) { - - } - - @Override public void display(GLAutoDrawable drawable) { - - final GL2 gl = drawable.getGL().getGL2(); - - gl.glLoadIdentity(); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glColor3f(1f, 1f, 1f); - - final GLU glu = new GLU(); - glu.gluPerspective(45f, ratio, 0f, 1000f); - - glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); - if (running) { - kernel.execute(kernel.range); - if (kernel.isExplicit()) { - kernel.get(kernel.xyz); - } - final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - } - kernel.render(gl); - - final long now = System.currentTimeMillis(); - final long time = now - last; - frames++; - - if (time > 1000) { // We update the frames/sec every second - if (running) { - final float framesPerSecond = (frames * 1000.0f) / time; - final int updatesPerMicroSecond = (int) ((framesPerSecond * kernel.range.getGlobalSize(0) * kernel.range - .getGlobalSize(0)) / 1000000); - framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); - positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); - } - frames = 0; - last = now; - } - gl.glFlush(); - - } - - @Override public void init(GLAutoDrawable drawable) { - final GL2 gl = drawable.getGL().getGL2(); - - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - gl.glEnable(GL.GL_BLEND); - gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); - try { - final InputStream textureStream = Local.class.getResourceAsStream("particle.jpg"); - final Texture texture = TextureIO.newTexture(textureStream, false, null); - texture.enable(gl); - } catch (final IOException e) { - e.printStackTrace(); - } catch (final GLException e) { - e.printStackTrace(); - } - - } - - @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { - width = _width; - height = _height; - - final GL2 gl = drawable.getGL().getGL2(); - gl.glViewport(0, 0, width, height); - - ratio = (double) width / (double) height; - - } - - }); - - panel.add(canvas, BorderLayout.CENTER); - frame.getContentPane().add(panel, BorderLayout.CENTER); - - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - frame.pack(); - frame.setVisible(true); - - final FPSAnimator animator = new FPSAnimator(canvas, 100); - animator.start(); - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ +package com.aparapi.examples.nbody; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLException; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.fixedfunc.GLLightingFunc; +import com.jogamp.opengl.glu.GLU; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.WindowConstants; + +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; +import com.jogamp.opengl.util.FPSAnimator; +import com.jogamp.opengl.util.texture.Texture; +import com.jogamp.opengl.util.texture.TextureIO; + +/** + * An NBody clone which uses local memory to cache NBody positions for execution. + * + * http://www.browndeertechnology.com/docs/BDT_OpenCL_Tutorial_NBody-rev3.html + * + * @see Main + * + * @author gfrost + * + */ +public class Local{ + + public static class NBodyKernel extends Kernel{ + protected final float delT = .005f; + + protected final float espSqr = 1.0f; + + protected final float mass = 5f; + + private final Range range; + + private final float[] xyz; // positions xy and z of bodies + + private final float[] vxyz; // velocity component of x,y and z of bodies + + @Local private final float[] localStuff; // local memory + + /** + * Constructor initializes xyz and vxyz arrays. + * @param _bodies + */ + public NBodyKernel(Range _range) { + range = _range; + localStuff = new float[range.getLocalSize(0) * 3]; + + xyz = new float[range.getGlobalSize(0) * 3]; + vxyz = new float[range.getGlobalSize(0) * 3]; + final float maxDist = 20f; + for (int body = 0; body < (range.getGlobalSize(0) * 3); body += 3) { + final float theta = (float) (Math.random() * Math.PI * 2); + final float phi = (float) (Math.random() * Math.PI * 2); + final float radius = (float) (Math.random() * maxDist); + + // get the 3D dimensional coordinates + xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); + xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); + xyz[body + 2] = (float) (radius * Math.cos(phi)); + + // divide into two 'spheres of bodies' by adjusting x + if ((body % 2) == 0) { + xyz[body + 0] += maxDist * 1.5; + } else { + xyz[body + 0] -= maxDist * 1.5; + } + } + setExplicit(true); + } + + /** + * Here is the kernel entrypoint. Here is where we calculate the position of each body + */ + @Override public void run() { + + final int globalId = getGlobalId(0) * 3; + + float accx = 0.f; + float accy = 0.f; + float accz = 0.f; + final float myPosx = xyz[globalId + 0]; + final float myPosy = xyz[globalId + 1]; + final float myPosz = xyz[globalId + 2]; + + for (int tile = 0; tile < (getGlobalSize(0) / getLocalSize(0)); tile++) { + // load one tile into local memory + final int gidx = ((tile * getLocalSize(0)) + getLocalId()) * 3; + final int lidx = getLocalId(0) * 3; + localStuff[lidx + 0] = xyz[gidx + 0]; + localStuff[lidx + 1] = xyz[gidx + 1]; + localStuff[lidx + 2] = xyz[gidx + 2]; + // Synchronize to make sure data is available for processing + localBarrier(); + + for (int i = 0; i < (getLocalSize() * 3); i += 3) { + final float dx = localStuff[i + 0] - myPosx; + final float dy = localStuff[i + 1] - myPosy; + final float dz = localStuff[i + 2] - myPosz; + final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); + final float s = mass * invDist * invDist * invDist; + accx = accx + (s * dx); + accy = accy + (s * dy); + accz = accz + (s * dz); + } + localBarrier(); + } + accx = accx * delT; + accy = accy * delT; + accz = accz * delT; + xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); + xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); + xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); + + vxyz[globalId + 0] = vxyz[globalId + 0] + accx; + vxyz[globalId + 1] = vxyz[globalId + 1] + accy; + vxyz[globalId + 2] = vxyz[globalId + 2] + accz; + } + + /** + * Render all particles to the OpenGL context + * @param gl + */ + + protected void render(GL2 gl) { + gl.glBegin(GL2.GL_QUADS); + + for (int i = 0; i < (range.getGlobalSize(0) * 3); i += 3) { + gl.glTexCoord2f(0, 1); + gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); + gl.glTexCoord2f(0, 0); + gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 0); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 1); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); + } + gl.glEnd(); + } + + } + + public static int width; + + public static int height; + + public static boolean running; + + public static void main(String _args[]) { + + final NBodyKernel kernel = new NBodyKernel(Range.create(Integer.getInteger("bodies", 8192), 256)); + + final JFrame frame = new JFrame("NBody"); + + final JPanel panel = new JPanel(new BorderLayout()); + final JPanel controlPanel = new JPanel(new FlowLayout()); + panel.add(controlPanel, BorderLayout.SOUTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + controlPanel.add(new JLabel(kernel.getExecutionMode().toString())); + + controlPanel.add(new JLabel(" Particles")); + controlPanel.add(new JTextField("" + kernel.range.getGlobalSize(0), 5)); + + controlPanel.add(new JLabel("FPS")); + final JTextField framesPerSecondTextField = new JTextField("0", 5); + + controlPanel.add(framesPerSecondTextField); + controlPanel.add(new JLabel("Score(")); + final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); + + controlPanel.add(miniLabel); + controlPanel.add(new JLabel(")")); + + final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); + + controlPanel.add(positionUpdatesPerMicroSecondTextField); + final GLCapabilities caps = new GLCapabilities(null); + caps.setDoubleBuffered(true); + caps.setHardwareAccelerated(true); + final GLCanvas canvas = new GLCanvas(caps); + final Dimension dimension = new Dimension(Integer.getInteger("width", 742), Integer.getInteger("height", 742)); + canvas.setPreferredSize(dimension); + + canvas.addGLEventListener(new GLEventListener(){ + private double ratio; + + private final float xeye = 0f; + + private final float yeye = 0f; + + private final float zeye = 100f; + + private final float xat = 0f; + + private final float yat = 0f; + + private final float zat = 0f; + + public final float zoomFactor = 1.0f; + + private int frames; + + private long last = System.currentTimeMillis(); + + @Override public void dispose(GLAutoDrawable drawable) { + + } + + @Override public void display(GLAutoDrawable drawable) { + + final GL2 gl = drawable.getGL().getGL2(); + + gl.glLoadIdentity(); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glColor3f(1f, 1f, 1f); + + final GLU glu = new GLU(); + glu.gluPerspective(45f, ratio, 0f, 1000f); + + glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); + if (running) { + kernel.execute(kernel.range); + if (kernel.isExplicit()) { + kernel.get(kernel.xyz); + } + final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + } + kernel.render(gl); + + final long now = System.currentTimeMillis(); + final long time = now - last; + frames++; + + if (time > 1000) { // We update the frames/sec every second + if (running) { + final float framesPerSecond = (frames * 1000.0f) / time; + final int updatesPerMicroSecond = (int) ((framesPerSecond * kernel.range.getGlobalSize(0) * kernel.range + .getGlobalSize(0)) / 1000000); + framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); + positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); + } + frames = 0; + last = now; + } + gl.glFlush(); + + } + + @Override public void init(GLAutoDrawable drawable) { + final GL2 gl = drawable.getGL().getGL2(); + + gl.glShadeModel(GLLightingFunc.GL_SMOOTH); + gl.glEnable(GL.GL_BLEND); + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); + try { + final InputStream textureStream = Local.class.getResourceAsStream("particle.jpg"); + final Texture texture = TextureIO.newTexture(textureStream, false, null); + texture.enable(gl); + } catch (final IOException e) { + e.printStackTrace(); + } catch (final GLException e) { + e.printStackTrace(); + } + + } + + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { + width = _width; + height = _height; + + final GL2 gl = drawable.getGL().getGL2(); + gl.glViewport(0, 0, width, height); + + ratio = (double) width / (double) height; + + } + + }); + + panel.add(canvas, BorderLayout.CENTER); + frame.getContentPane().add(panel, BorderLayout.CENTER); + + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + + final FPSAnimator animator = new FPSAnimator(canvas, 100); + animator.start(); + + } + +} diff --git a/src/main/java/com/aparapi/examples/nbody/Main.java b/src/main/java/com/aparapi/examples/nbody/Main.java index 85e3f8f3..5f8fdfaa 100644 --- a/src/main/java/com/aparapi/examples/nbody/Main.java +++ b/src/main/java/com/aparapi/examples/nbody/Main.java @@ -1,380 +1,395 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - - */ -package com.aparapi.examples.nbody; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import com.jogamp.opengl.GL; -import com.jogamp.opengl.GL2; -import com.jogamp.opengl.GLAutoDrawable; -import com.jogamp.opengl.GLCapabilities; -import com.jogamp.opengl.GLEventListener; -import com.jogamp.opengl.GLException; -import com.jogamp.opengl.GLProfile; -import com.jogamp.opengl.awt.GLCanvas; -import com.jogamp.opengl.fixedfunc.GLLightingFunc; -import com.jogamp.opengl.glu.GLU; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.WindowConstants; - -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; -import com.jogamp.opengl.util.FPSAnimator; -import com.jogamp.opengl.util.texture.Texture; -import com.jogamp.opengl.util.texture.TextureData; -import com.jogamp.opengl.util.texture.TextureIO; - -/** - * NBody implementing demonstrating Aparapi kernels. - * - * For a description of the NBody problem. - * - * @see http://en.wikipedia.org/wiki/N-body_problem - * - * We use JOGL to render the bodies. - * @see http://jogamp.org/jogl/www/ - * - * @author gfrost - * - */ -public class Main{ - - public static class NBodyKernel extends Kernel{ - protected final float delT = .005f; - - protected final float espSqr = 1.0f; - - protected final float mass = 5f; - - private final Range range; - - private final float[] xyz; // positions xy and z of bodies - - private final float[] vxyz; // velocity component of x,y and z of bodies - - /** - * Constructor initializes xyz and vxyz arrays. - * - * @param _bodies - */ - public NBodyKernel(Range _range) { - range = _range; - // range = Range.create(bodies); - xyz = new float[range.getGlobalSize(0) * 3]; - vxyz = new float[range.getGlobalSize(0) * 3]; - final float maxDist = 20f; - for (int body = 0; body < (range.getGlobalSize(0) * 3); body += 3) { - - final float theta = (float) (Math.random() * Math.PI * 2); - final float phi = (float) (Math.random() * Math.PI * 2); - final float radius = (float) (Math.random() * maxDist); - - // get the 3D dimensional coordinates - xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); - xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); - xyz[body + 2] = (float) (radius * Math.cos(phi)); - - // divide into two 'spheres of bodies' by adjusting x - - if ((body % 2) == 0) { - xyz[body + 0] += maxDist * 1.5; - } else { - xyz[body + 0] -= maxDist * 1.5; - } - } - setExplicit(true); - } - - /** - * Here is the kernel entrypoint. Here is where we calculate the position of each body - */ - @Override public void run() { - final int body = getGlobalId(); - final int count = getGlobalSize(0) * 3; - final int globalId = body * 3; - - float accx = 0.f; - float accy = 0.f; - float accz = 0.f; - - final float myPosx = xyz[globalId + 0]; - final float myPosy = xyz[globalId + 1]; - final float myPosz = xyz[globalId + 2]; - for (int i = 0; i < count; i += 3) { - final float dx = xyz[i + 0] - myPosx; - final float dy = xyz[i + 1] - myPosy; - final float dz = xyz[i + 2] - myPosz; - final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); - final float s = mass * invDist * invDist * invDist; - accx = accx + (s * dx); - accy = accy + (s * dy); - accz = accz + (s * dz); - } - accx = accx * delT; - accy = accy * delT; - accz = accz * delT; - xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); - xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); - xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); - - vxyz[globalId + 0] = vxyz[globalId + 0] + accx; - vxyz[globalId + 1] = vxyz[globalId + 1] + accy; - vxyz[globalId + 2] = vxyz[globalId + 2] + accz; - } - - /** - * Render all particles to the OpenGL context - * - * @param gl - */ - - protected void render(GL2 gl) { - gl.glBegin(GL2.GL_QUADS); - - for (int i = 0; i < (range.getGlobalSize(0) * 3); i += 3) { - gl.glTexCoord2f(0, 1); - gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); - gl.glTexCoord2f(0, 0); - gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 0); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 1); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); - } - gl.glEnd(); - } - - } - - public static int width; - - public static int height; - - public static boolean running; - - static Texture texture; - - public static void main(String _args[]) { - - //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libawt.dylib"); - //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libjawt.dylib"); - final NBodyKernel kernel = new NBodyKernel(Range.create(Integer.getInteger("bodies", 8192))); - - final JFrame frame = new JFrame("NBody"); - - final JPanel panel = new JPanel(new BorderLayout()); - final JPanel controlPanel = new JPanel(new FlowLayout()); - panel.add(controlPanel, BorderLayout.NORTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - controlPanel.add(new JLabel(kernel.getExecutionMode().toString())); - - controlPanel.add(new JLabel(" Particles")); - controlPanel.add(new JTextField("" + kernel.range.getGlobalSize(0), 5)); - - controlPanel.add(new JLabel("FPS")); - final JTextField framesPerSecondTextField = new JTextField("0", 5); - - controlPanel.add(framesPerSecondTextField); - controlPanel.add(new JLabel("Score(")); - final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); - - controlPanel.add(miniLabel); - controlPanel.add(new JLabel(")")); - - final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); - - controlPanel.add(positionUpdatesPerMicroSecondTextField); - final GLCapabilities caps = new GLCapabilities(null); - final GLProfile profile = caps.getGLProfile(); - caps.setDoubleBuffered(true); - caps.setHardwareAccelerated(true); - final GLCanvas canvas = new GLCanvas(caps); - - final Dimension dimension = new Dimension(Integer.getInteger("width", 742 - 64), Integer.getInteger("height", 742 - 64)); - canvas.setPreferredSize(dimension); - - canvas.addGLEventListener(new GLEventListener(){ - private double ratio; - - private final float xeye = 0f; - - private final float yeye = 0f; - - private final float zeye = 100f; - - private final float xat = 0f; - - private final float yat = 0f; - - private final float zat = 0f; - - public final float zoomFactor = 1.0f; - - private int frames; - - private long last = System.currentTimeMillis(); - - @Override public void dispose(GLAutoDrawable drawable) { - - } - - @Override public void display(GLAutoDrawable drawable) { - - final GL2 gl = drawable.getGL().getGL2(); - texture.enable(gl); - texture.bind(gl); - gl.glLoadIdentity(); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glColor3f(1f, 1f, 1f); - - final GLU glu = new GLU(); - glu.gluPerspective(45f, ratio, 0f, 1000f); - - glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); - if (running) { - kernel.execute(kernel.range); - if (kernel.isExplicit()) { - kernel.get(kernel.xyz); - } - final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); - if ((profileInfo != null) && (profileInfo.size() > 0)) { - for (final ProfileInfo p : profileInfo) { - System.out.print(" " + p.getType() + " " + p.getLabel() + ((p.getEnd() - p.getStart()) / 1000) + "us"); - } - System.out.println(); - } - } - kernel.render(gl); - - final long now = System.currentTimeMillis(); - final long time = now - last; - frames++; - - if (time > 1000) { // We update the frames/sec every second - if (running) { - final float framesPerSecond = (frames * 1000.0f) / time; - final int updatesPerMicroSecond = (int) ((framesPerSecond * kernel.range.getGlobalSize(0) * kernel.range - .getGlobalSize(0)) / 1000000); - framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); - positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); - } - frames = 0; - last = now; - } - gl.glFlush(); - - } - - @Override public void init(GLAutoDrawable drawable) { - final GL2 gl = drawable.getGL().getGL2(); - - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - gl.glEnable(GL.GL_BLEND); - gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); - gl.glEnable(GL.GL_TEXTURE_2D); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); - try { - final InputStream textureStream = Main.class.getResourceAsStream("particle.jpg"); - TextureData data = TextureIO.newTextureData(profile, textureStream, false, "jpg"); - texture = TextureIO.newTexture(data); - } catch (final IOException e) { - e.printStackTrace(); - } catch (final GLException e) { - e.printStackTrace(); - } - - } - - @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { - width = _width; - height = _height; - - final GL2 gl = drawable.getGL().getGL2(); - gl.glViewport(0, 0, width, height); - - ratio = (double) width / (double) height; - - } - - }); - - panel.add(canvas, BorderLayout.CENTER); - frame.getContentPane().add(panel, BorderLayout.CENTER); - - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - frame.pack(); - frame.setVisible(true); - final FPSAnimator animator = new FPSAnimator(canvas, 100); - - animator.start(); - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + + */ +package com.aparapi.examples.nbody; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLException; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.fixedfunc.GLLightingFunc; +import com.jogamp.opengl.glu.GLU; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.WindowConstants; + +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; +import com.jogamp.opengl.util.FPSAnimator; +import com.jogamp.opengl.util.texture.Texture; +import com.jogamp.opengl.util.texture.TextureData; +import com.jogamp.opengl.util.texture.TextureIO; + +/** + * NBody implementing demonstrating Aparapi kernels. + * + * For a description of the NBody problem. + * + * @see http://en.wikipedia.org/wiki/N-body_problem + * + * We use JOGL to render the bodies. + * @see http://jogamp.org/jogl/www/ + * + * @author gfrost + * + */ +public class Main{ + + public static class NBodyKernel extends Kernel{ + protected final float delT = .005f; + + protected final float espSqr = 1.0f; + + protected final float mass = 5f; + + private final Range range; + + private final float[] xyz; // positions xy and z of bodies + + private final float[] vxyz; // velocity component of x,y and z of bodies + + /** + * Constructor initializes xyz and vxyz arrays. + * + * @param _bodies + */ + public NBodyKernel(Range _range) { + range = _range; + // range = Range.create(bodies); + xyz = new float[range.getGlobalSize(0) * 3]; + vxyz = new float[range.getGlobalSize(0) * 3]; + final float maxDist = 20f; + for (int body = 0; body < (range.getGlobalSize(0) * 3); body += 3) { + + final float theta = (float) (Math.random() * Math.PI * 2); + final float phi = (float) (Math.random() * Math.PI * 2); + final float radius = (float) (Math.random() * maxDist); + + // get the 3D dimensional coordinates + xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); + xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); + xyz[body + 2] = (float) (radius * Math.cos(phi)); + + // divide into two 'spheres of bodies' by adjusting x + + if ((body % 2) == 0) { + xyz[body + 0] += maxDist * 1.5; + } else { + xyz[body + 0] -= maxDist * 1.5; + } + } + setExplicit(true); + } + + /** + * Here is the kernel entrypoint. Here is where we calculate the position of each body + */ + @Override public void run() { + final int body = getGlobalId(); + final int count = getGlobalSize(0) * 3; + final int globalId = body * 3; + + float accx = 0.f; + float accy = 0.f; + float accz = 0.f; + + final float myPosx = xyz[globalId + 0]; + final float myPosy = xyz[globalId + 1]; + final float myPosz = xyz[globalId + 2]; + for (int i = 0; i < count; i += 3) { + final float dx = xyz[i + 0] - myPosx; + final float dy = xyz[i + 1] - myPosy; + final float dz = xyz[i + 2] - myPosz; + final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); + final float s = mass * invDist * invDist * invDist; + accx = accx + (s * dx); + accy = accy + (s * dy); + accz = accz + (s * dz); + } + accx = accx * delT; + accy = accy * delT; + accz = accz * delT; + xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); + xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); + xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); + + vxyz[globalId + 0] = vxyz[globalId + 0] + accx; + vxyz[globalId + 1] = vxyz[globalId + 1] + accy; + vxyz[globalId + 2] = vxyz[globalId + 2] + accz; + } + + /** + * Render all particles to the OpenGL context + * + * @param gl + */ + + protected void render(GL2 gl) { + gl.glBegin(GL2.GL_QUADS); + + for (int i = 0; i < (range.getGlobalSize(0) * 3); i += 3) { + gl.glTexCoord2f(0, 1); + gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); + gl.glTexCoord2f(0, 0); + gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 0); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 1); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); + } + gl.glEnd(); + } + + } + + public static int width; + + public static int height; + + public static boolean running; + + static Texture texture; + + public static void main(String _args[]) { + + //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libawt.dylib"); + //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libjawt.dylib"); + final NBodyKernel kernel = new NBodyKernel(Range.create(Integer.getInteger("bodies", 8192))); + + final JFrame frame = new JFrame("NBody"); + + final JPanel panel = new JPanel(new BorderLayout()); + final JPanel controlPanel = new JPanel(new FlowLayout()); + panel.add(controlPanel, BorderLayout.NORTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + controlPanel.add(new JLabel(kernel.getExecutionMode().toString())); + + controlPanel.add(new JLabel(" Particles")); + controlPanel.add(new JTextField("" + kernel.range.getGlobalSize(0), 5)); + + controlPanel.add(new JLabel("FPS")); + final JTextField framesPerSecondTextField = new JTextField("0", 5); + + controlPanel.add(framesPerSecondTextField); + controlPanel.add(new JLabel("Score(")); + final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); + + controlPanel.add(miniLabel); + controlPanel.add(new JLabel(")")); + + final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); + + controlPanel.add(positionUpdatesPerMicroSecondTextField); + final GLCapabilities caps = new GLCapabilities(null); + final GLProfile profile = caps.getGLProfile(); + caps.setDoubleBuffered(true); + caps.setHardwareAccelerated(true); + final GLCanvas canvas = new GLCanvas(caps); + + final Dimension dimension = new Dimension(Integer.getInteger("width", 742 - 64), Integer.getInteger("height", 742 - 64)); + canvas.setPreferredSize(dimension); + + canvas.addGLEventListener(new GLEventListener(){ + private double ratio; + + private final float xeye = 0f; + + private final float yeye = 0f; + + private final float zeye = 100f; + + private final float xat = 0f; + + private final float yat = 0f; + + private final float zat = 0f; + + public final float zoomFactor = 1.0f; + + private int frames; + + private long last = System.currentTimeMillis(); + + @Override public void dispose(GLAutoDrawable drawable) { + + } + + @Override public void display(GLAutoDrawable drawable) { + + final GL2 gl = drawable.getGL().getGL2(); + texture.enable(gl); + texture.bind(gl); + gl.glLoadIdentity(); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glColor3f(1f, 1f, 1f); + + final GLU glu = new GLU(); + glu.gluPerspective(45f, ratio, 0f, 1000f); + + glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); + if (running) { + kernel.execute(kernel.range); + if (kernel.isExplicit()) { + kernel.get(kernel.xyz); + } + final List<ProfileInfo> profileInfo = kernel.getProfileInfo(); + if ((profileInfo != null) && (profileInfo.size() > 0)) { + for (final ProfileInfo p : profileInfo) { + System.out.print(" " + p.getType() + " " + p.getLabel() + ((p.getEnd() - p.getStart()) / 1000) + "us"); + } + System.out.println(); + } + } + kernel.render(gl); + + final long now = System.currentTimeMillis(); + final long time = now - last; + frames++; + + if (time > 1000) { // We update the frames/sec every second + if (running) { + final float framesPerSecond = (frames * 1000.0f) / time; + final int updatesPerMicroSecond = (int) ((framesPerSecond * kernel.range.getGlobalSize(0) * kernel.range + .getGlobalSize(0)) / 1000000); + framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); + positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); + } + frames = 0; + last = now; + } + gl.glFlush(); + + } + + @Override public void init(GLAutoDrawable drawable) { + final GL2 gl = drawable.getGL().getGL2(); + + gl.glShadeModel(GLLightingFunc.GL_SMOOTH); + gl.glEnable(GL.GL_BLEND); + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); + gl.glEnable(GL.GL_TEXTURE_2D); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); + try { + final InputStream textureStream = Main.class.getResourceAsStream("particle.jpg"); + TextureData data = TextureIO.newTextureData(profile, textureStream, false, "jpg"); + texture = TextureIO.newTexture(data); + } catch (final IOException e) { + e.printStackTrace(); + } catch (final GLException e) { + e.printStackTrace(); + } + + } + + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { + width = _width; + height = _height; + + final GL2 gl = drawable.getGL().getGL2(); + gl.glViewport(0, 0, width, height); + + ratio = (double) width / (double) height; + + } + + }); + + panel.add(canvas, BorderLayout.CENTER); + frame.getContentPane().add(panel, BorderLayout.CENTER); + + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + final FPSAnimator animator = new FPSAnimator(canvas, 100); + + animator.start(); + + } + +} diff --git a/src/main/java/com/aparapi/examples/nbody/Seq.java b/src/main/java/com/aparapi/examples/nbody/Seq.java index b5e269e3..54a128b6 100644 --- a/src/main/java/com/aparapi/examples/nbody/Seq.java +++ b/src/main/java/com/aparapi/examples/nbody/Seq.java @@ -1,371 +1,386 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - - */ -package com.aparapi.examples.nbody; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import com.jogamp.opengl.GL; -import com.jogamp.opengl.GL2; -import com.jogamp.opengl.GLAutoDrawable; -import com.jogamp.opengl.GLCapabilities; -import com.jogamp.opengl.GLEventListener; -import com.jogamp.opengl.GLException; -import com.jogamp.opengl.GLProfile; -import com.jogamp.opengl.awt.GLCanvas; -import com.jogamp.opengl.fixedfunc.GLLightingFunc; -import com.jogamp.opengl.glu.GLU; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.WindowConstants; - -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; -import com.jogamp.opengl.util.FPSAnimator; -import com.jogamp.opengl.util.texture.Texture; -import com.jogamp.opengl.util.texture.TextureData; -import com.jogamp.opengl.util.texture.TextureIO; - -/** - * NBody implemented sequentially - * - * For a description of the NBody problem. - * - * @see http://en.wikipedia.org/wiki/N-body_problem - * - * We use JOGL to render the bodies. - * @see http://jogamp.org/jogl/www/ - * - * @author gfrost - * - */ -public class Seq{ - - public static class NBodyKernel { - protected final float delT = .005f; - - protected final float espSqr = 1.0f; - - protected final float mass = 5f; - - private final int bodies; - - private final float[] xyz; // positions xy and z of bodies - - private final float[] vxyz; // velocity component of x,y and z of bodies - - /** - * Constructor initializes xyz and vxyz arrays. - * - * @param _bodies - */ - public NBodyKernel(int _bodies) { - bodies = _bodies; - xyz = new float[bodies * 3]; - vxyz = new float[bodies * 3]; - final float maxDist = 20f; - for (int body = 0; body < (bodies * 3); body += 3) { - - final float theta = (float) (Math.random() * Math.PI * 2); - final float phi = (float) (Math.random() * Math.PI * 2); - final float radius = (float) (Math.random() * maxDist); - - // get the 3D dimensional coordinates - xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); - xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); - xyz[body + 2] = (float) (radius * Math.cos(phi)); - - // divide into two 'spheres of bodies' by adjusting x - - if ((body % 2) == 0) { - xyz[body + 0] += maxDist * 1.5; - } else { - xyz[body + 0] -= maxDist * 1.5; - } - } - } - - /** - * Here is the kernel entrypoint. Here is where we calculate the position of each body - */ - public void run() { - final int count = bodies * 3; - for (int body = 0; body < bodies; body++){ - final int globalId = body * 3; - - float accx = 0.f; - float accy = 0.f; - float accz = 0.f; - - final float myPosx = xyz[globalId + 0]; - final float myPosy = xyz[globalId + 1]; - final float myPosz = xyz[globalId + 2]; - for (int i = 0; i < count; i += 3) { - final float dx = xyz[i + 0] - myPosx; - final float dy = xyz[i + 1] - myPosy; - final float dz = xyz[i + 2] - myPosz; - final float invDist = 1f/((float)Math.sqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr)); - final float s = mass * invDist * invDist * invDist; - accx = accx + (s * dx); - accy = accy + (s * dy); - accz = accz + (s * dz); - } - accx = accx * delT; - accy = accy * delT; - accz = accz * delT; - xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); - xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); - xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); - - vxyz[globalId + 0] = vxyz[globalId + 0] + accx; - vxyz[globalId + 1] = vxyz[globalId + 1] + accy; - vxyz[globalId + 2] = vxyz[globalId + 2] + accz; - } - } - - /** - * Render all particles to the OpenGL context - * - * @param gl - */ - - protected void render(GL2 gl) { - gl.glBegin(GL2.GL_QUADS); - - for (int i = 0; i < (bodies * 3); i += 3) { - gl.glTexCoord2f(0, 1); - gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); - gl.glTexCoord2f(0, 0); - gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 0); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); - gl.glTexCoord2f(1, 1); - gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); - } - gl.glEnd(); - } - - } - - public final static int bodies = Integer.getInteger("bodies", 8192); - - public static int width; - - public static int height; - - public static boolean running; - - static Texture texture; - - public static void main(String _args[]) { - - //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libawt.dylib"); - //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libjawt.dylib"); - final NBodyKernel kernel = new NBodyKernel(bodies); - - final JFrame frame = new JFrame("NBody"); - - final JPanel panel = new JPanel(new BorderLayout()); - final JPanel controlPanel = new JPanel(new FlowLayout()); - panel.add(controlPanel, BorderLayout.SOUTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - controlPanel.add(new JLabel("SEQ")); - - controlPanel.add(new JLabel(" Particles")); - controlPanel.add(new JTextField("" + bodies, 5)); - - controlPanel.add(new JLabel("FPS")); - final JTextField framesPerSecondTextField = new JTextField("0", 5); - - controlPanel.add(framesPerSecondTextField); - controlPanel.add(new JLabel("Score(")); - final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); - - controlPanel.add(miniLabel); - controlPanel.add(new JLabel(")")); - - final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); - - controlPanel.add(positionUpdatesPerMicroSecondTextField); - final GLCapabilities caps = new GLCapabilities(null); - final GLProfile profile = caps.getGLProfile(); - caps.setDoubleBuffered(true); - caps.setHardwareAccelerated(true); - final GLCanvas canvas = new GLCanvas(caps); - - final Dimension dimension = new Dimension(Integer.getInteger("width", 742 - 64), Integer.getInteger("height", 742 - 64)); - canvas.setPreferredSize(dimension); - - canvas.addGLEventListener(new GLEventListener(){ - private double ratio; - - private final float xeye = 0f; - - private final float yeye = 0f; - - private final float zeye = 100f; - - private final float xat = 0f; - - private final float yat = 0f; - - private final float zat = 0f; - - public final float zoomFactor = 1.0f; - - private int frames; - - private long last = System.currentTimeMillis(); - - @Override public void dispose(GLAutoDrawable drawable) { - - } - - @Override public void display(GLAutoDrawable drawable) { - - final GL2 gl = drawable.getGL().getGL2(); - - texture.enable(gl); - texture.bind(gl); - gl.glLoadIdentity(); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glColor3f(1f, 1f, 1f); - - final GLU glu = new GLU(); - glu.gluPerspective(45f, ratio, 0f, 1000f); - - glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); - if (running) { - kernel.run(); - } - kernel.render(gl); - - final long now = System.currentTimeMillis(); - final long time = now - last; - frames++; - - if (time > 1000) { // We update the frames/sec every second - if (running) { - final float framesPerSecond = (frames * 1000.0f) / time; - final int updatesPerMicroSecond = (int) ((framesPerSecond * bodies * bodies) / 1000000); - framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); - positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); - } - frames = 0; - last = now; - } - gl.glFlush(); - - } - - @Override public void init(GLAutoDrawable drawable) { - final GL2 gl = drawable.getGL().getGL2(); - - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - gl.glEnable(GL.GL_BLEND); - gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); - gl.glEnable(GL.GL_TEXTURE_2D); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); - try { - final InputStream textureStream = Seq.class.getResourceAsStream("particle.jpg"); - TextureData data = TextureIO.newTextureData(profile, textureStream, false, "jpg"); - texture = TextureIO.newTexture(data); - } catch (final IOException e) { - e.printStackTrace(); - } catch (final GLException e) { - e.printStackTrace(); - } - - } - - @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { - width = _width; - height = _height; - - final GL2 gl = drawable.getGL().getGL2(); - gl.glViewport(0, 0, width, height); - - ratio = (double) width / (double) height; - - } - - }); - - panel.add(canvas, BorderLayout.CENTER); - frame.getContentPane().add(panel, BorderLayout.CENTER); - final FPSAnimator animator = new FPSAnimator(canvas, 100); - - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - frame.pack(); - frame.setVisible(true); - - animator.start(); - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + + */ +package com.aparapi.examples.nbody; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLException; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.fixedfunc.GLLightingFunc; +import com.jogamp.opengl.glu.GLU; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.WindowConstants; + +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; +import com.jogamp.opengl.util.FPSAnimator; +import com.jogamp.opengl.util.texture.Texture; +import com.jogamp.opengl.util.texture.TextureData; +import com.jogamp.opengl.util.texture.TextureIO; + +/** + * NBody implemented sequentially + * + * For a description of the NBody problem. + * + * @see http://en.wikipedia.org/wiki/N-body_problem + * + * We use JOGL to render the bodies. + * @see http://jogamp.org/jogl/www/ + * + * @author gfrost + * + */ +public class Seq{ + + public static class NBodyKernel { + protected final float delT = .005f; + + protected final float espSqr = 1.0f; + + protected final float mass = 5f; + + private final int bodies; + + private final float[] xyz; // positions xy and z of bodies + + private final float[] vxyz; // velocity component of x,y and z of bodies + + /** + * Constructor initializes xyz and vxyz arrays. + * + * @param _bodies + */ + public NBodyKernel(int _bodies) { + bodies = _bodies; + xyz = new float[bodies * 3]; + vxyz = new float[bodies * 3]; + final float maxDist = 20f; + for (int body = 0; body < (bodies * 3); body += 3) { + + final float theta = (float) (Math.random() * Math.PI * 2); + final float phi = (float) (Math.random() * Math.PI * 2); + final float radius = (float) (Math.random() * maxDist); + + // get the 3D dimensional coordinates + xyz[body + 0] = (float) (radius * Math.cos(theta) * Math.sin(phi)); + xyz[body + 1] = (float) (radius * Math.sin(theta) * Math.sin(phi)); + xyz[body + 2] = (float) (radius * Math.cos(phi)); + + // divide into two 'spheres of bodies' by adjusting x + + if ((body % 2) == 0) { + xyz[body + 0] += maxDist * 1.5; + } else { + xyz[body + 0] -= maxDist * 1.5; + } + } + } + + /** + * Here is the kernel entrypoint. Here is where we calculate the position of each body + */ + public void run() { + final int count = bodies * 3; + for (int body = 0; body < bodies; body++){ + final int globalId = body * 3; + + float accx = 0.f; + float accy = 0.f; + float accz = 0.f; + + final float myPosx = xyz[globalId + 0]; + final float myPosy = xyz[globalId + 1]; + final float myPosz = xyz[globalId + 2]; + for (int i = 0; i < count; i += 3) { + final float dx = xyz[i + 0] - myPosx; + final float dy = xyz[i + 1] - myPosy; + final float dz = xyz[i + 2] - myPosz; + final float invDist = 1f/((float)Math.sqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr)); + final float s = mass * invDist * invDist * invDist; + accx = accx + (s * dx); + accy = accy + (s * dy); + accz = accz + (s * dz); + } + accx = accx * delT; + accy = accy * delT; + accz = accz * delT; + xyz[globalId + 0] = myPosx + (vxyz[globalId + 0] * delT) + (accx * .5f * delT); + xyz[globalId + 1] = myPosy + (vxyz[globalId + 1] * delT) + (accy * .5f * delT); + xyz[globalId + 2] = myPosz + (vxyz[globalId + 2] * delT) + (accz * .5f * delT); + + vxyz[globalId + 0] = vxyz[globalId + 0] + accx; + vxyz[globalId + 1] = vxyz[globalId + 1] + accy; + vxyz[globalId + 2] = vxyz[globalId + 2] + accz; + } + } + + /** + * Render all particles to the OpenGL context + * + * @param gl + */ + + protected void render(GL2 gl) { + gl.glBegin(GL2.GL_QUADS); + + for (int i = 0; i < (bodies * 3); i += 3) { + gl.glTexCoord2f(0, 1); + gl.glVertex3f(xyz[i + 0], xyz[i + 1] + 1, xyz[i + 2]); + gl.glTexCoord2f(0, 0); + gl.glVertex3f(xyz[i + 0], xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 0); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1], xyz[i + 2]); + gl.glTexCoord2f(1, 1); + gl.glVertex3f(xyz[i + 0] + 1, xyz[i + 1] + 1, xyz[i + 2]); + } + gl.glEnd(); + } + + } + + public final static int bodies = Integer.getInteger("bodies", 8192); + + public static int width; + + public static int height; + + public static boolean running; + + static Texture texture; + + public static void main(String _args[]) { + + //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libawt.dylib"); + //System.load("/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/libjawt.dylib"); + final NBodyKernel kernel = new NBodyKernel(bodies); + + final JFrame frame = new JFrame("NBody"); + + final JPanel panel = new JPanel(new BorderLayout()); + final JPanel controlPanel = new JPanel(new FlowLayout()); + panel.add(controlPanel, BorderLayout.SOUTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + controlPanel.add(new JLabel("SEQ")); + + controlPanel.add(new JLabel(" Particles")); + controlPanel.add(new JTextField("" + bodies, 5)); + + controlPanel.add(new JLabel("FPS")); + final JTextField framesPerSecondTextField = new JTextField("0", 5); + + controlPanel.add(framesPerSecondTextField); + controlPanel.add(new JLabel("Score(")); + final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); + + controlPanel.add(miniLabel); + controlPanel.add(new JLabel(")")); + + final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); + + controlPanel.add(positionUpdatesPerMicroSecondTextField); + final GLCapabilities caps = new GLCapabilities(null); + final GLProfile profile = caps.getGLProfile(); + caps.setDoubleBuffered(true); + caps.setHardwareAccelerated(true); + final GLCanvas canvas = new GLCanvas(caps); + + final Dimension dimension = new Dimension(Integer.getInteger("width", 742 - 64), Integer.getInteger("height", 742 - 64)); + canvas.setPreferredSize(dimension); + + canvas.addGLEventListener(new GLEventListener(){ + private double ratio; + + private final float xeye = 0f; + + private final float yeye = 0f; + + private final float zeye = 100f; + + private final float xat = 0f; + + private final float yat = 0f; + + private final float zat = 0f; + + public final float zoomFactor = 1.0f; + + private int frames; + + private long last = System.currentTimeMillis(); + + @Override public void dispose(GLAutoDrawable drawable) { + + } + + @Override public void display(GLAutoDrawable drawable) { + + final GL2 gl = drawable.getGL().getGL2(); + + texture.enable(gl); + texture.bind(gl); + gl.glLoadIdentity(); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glColor3f(1f, 1f, 1f); + + final GLU glu = new GLU(); + glu.gluPerspective(45f, ratio, 0f, 1000f); + + glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); + if (running) { + kernel.run(); + } + kernel.render(gl); + + final long now = System.currentTimeMillis(); + final long time = now - last; + frames++; + + if (time > 1000) { // We update the frames/sec every second + if (running) { + final float framesPerSecond = (frames * 1000.0f) / time; + final int updatesPerMicroSecond = (int) ((framesPerSecond * bodies * bodies) / 1000000); + framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); + positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); + } + frames = 0; + last = now; + } + gl.glFlush(); + + } + + @Override public void init(GLAutoDrawable drawable) { + final GL2 gl = drawable.getGL().getGL2(); + + gl.glShadeModel(GLLightingFunc.GL_SMOOTH); + gl.glEnable(GL.GL_BLEND); + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); + gl.glEnable(GL.GL_TEXTURE_2D); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); + try { + final InputStream textureStream = Seq.class.getResourceAsStream("particle.jpg"); + TextureData data = TextureIO.newTextureData(profile, textureStream, false, "jpg"); + texture = TextureIO.newTexture(data); + } catch (final IOException e) { + e.printStackTrace(); + } catch (final GLException e) { + e.printStackTrace(); + } + + } + + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { + width = _width; + height = _height; + + final GL2 gl = drawable.getGL().getGL2(); + gl.glViewport(0, 0, width, height); + + ratio = (double) width / (double) height; + + } + + }); + + panel.add(canvas, BorderLayout.CENTER); + frame.getContentPane().add(panel, BorderLayout.CENTER); + final FPSAnimator animator = new FPSAnimator(canvas, 100); + + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + + animator.start(); + + } + +} diff --git a/src/main/java/com/aparapi/examples/oopnbody/Body.java b/src/main/java/com/aparapi/examples/oopnbody/Body.java index 2f2fb9a4..804d8ed2 100644 --- a/src/main/java/com/aparapi/examples/oopnbody/Body.java +++ b/src/main/java/com/aparapi/examples/oopnbody/Body.java @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * This product currently only contains code developed by authors * of specific components, as identified by the source code files. diff --git a/src/main/java/com/aparapi/examples/oopnbody/Main.java b/src/main/java/com/aparapi/examples/oopnbody/Main.java index 2b6d4046..fae1ac0d 100644 --- a/src/main/java/com/aparapi/examples/oopnbody/Main.java +++ b/src/main/java/com/aparapi/examples/oopnbody/Main.java @@ -1,384 +1,399 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - - */ -package com.aparapi.examples.oopnbody; - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.ArrayList; -import java.util.Arrays; - -import com.jogamp.opengl.GL; -import com.jogamp.opengl.GL2; -import com.jogamp.opengl.GLAutoDrawable; -import com.jogamp.opengl.GLCapabilities; -import com.jogamp.opengl.GLEventListener; -import com.jogamp.opengl.GLException; -import com.jogamp.opengl.GLProfile; -import com.jogamp.opengl.awt.GLCanvas; -import com.jogamp.opengl.fixedfunc.GLLightingFunc; -import com.jogamp.opengl.glu.GLU; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.WindowConstants; - -import com.aparapi.Kernel; -import com.aparapi.ProfileInfo; -import com.aparapi.Range; - -import com.jogamp.opengl.util.FPSAnimator; -import com.jogamp.opengl.util.texture.Texture; -import com.jogamp.opengl.util.texture.TextureIO; - -/** - * NBody implementing demonstrating Aparapi kernels. - * - * For a description of the NBody problem. - * - * @see http://en.wikipedia.org/wiki/N-body_problem - * - * We use JOGL to render the bodies. - * @see http://jogamp.org/jogl/www/ - * - * @author gfrost - * - */ -public class Main{ - - public static class NBodyKernel extends Kernel{ - - protected final float delT = .005f; - - protected final float espSqr = 1.0f; - - protected final float mass = 5f; - - private final Range range; - - public Body[] bodies; - - /** - * Constructor initializes xyz and vxyz arrays. - * - * @param _bodies - */ - public NBodyKernel(Range _range) { - range = _range; - bodies = new Body[range.getGlobalSize(0)]; - - final float maxDist = 20f; - for (int body = 0; body < range.getGlobalSize(0); body++) { - final float theta = (float) (Math.random() * Math.PI * 2); - final float phi = (float) (Math.random() * Math.PI * 2); - final float radius = (float) (Math.random() * maxDist); - - // get the 3D dimensional coordinates - float x = (float) (radius * Math.cos(theta) * Math.sin(phi)); - float y = (float) (radius * Math.sin(theta) * Math.sin(phi)); - float z = (float) (radius * Math.cos(phi)); - - // divide into two 'spheres of bodies' by adjusting x - if ((body % 2) == 0) { - x += maxDist * 1.5; - } else { - x -= maxDist * 1.5; - } - bodies[body] = new Body(x, y, z, 5f); - } - - Body.allBodies = bodies; - } - - /** - * Here is the kernel entrypoint. Here is where we calculate the position of each body - */ - @Override public void run() { - final int body = getGlobalId(); - - float accx = 0.f; - float accy = 0.f; - float accz = 0.f; - - float myPosx = bodies[body].getX(); - float myPosy = bodies[body].getY(); - float myPosz = bodies[body].getZ(); - - for (int i = 0; i < getGlobalSize(0); i++) { - - final float dx = bodies[i].getX() - myPosx; - final float dy = bodies[i].getY() - myPosy; - final float dz = bodies[i].getZ() - myPosz; - final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); - final float s = bodies[i].getM() * invDist * invDist * invDist; - accx = accx + (s * dx); - accy = accy + (s * dy); - accz = accz + (s * dz); - } - - accx = accx * delT; - accy = accy * delT; - accz = accz * delT; - bodies[body].setX(myPosx + (bodies[body].getVx() * delT) + (accx * .5f * delT)); - bodies[body].setY(myPosy + (bodies[body].getVy() * delT) + (accy * .5f * delT)); - bodies[body].setZ(myPosz + (bodies[body].getVz() * delT) + (accz * .5f * delT)); - - bodies[body].setVx(bodies[body].getVx() + accx); - bodies[body].setVy(bodies[body].getVy() + accy); - bodies[body].setVz(bodies[body].getVz() + accz); - } - - /** - * Render all particles to the OpenGL context - * - * @param gl - */ - - protected void render(GL2 gl) { - gl.glBegin(GL2.GL_QUADS); - int sz = range.getGlobalSize(0); - for (int i = 0; i < sz; i++) { - - if (i < (sz / 2)) { - gl.glColor3f(1f, 0f, 0f); - } else if (i < (sz * 0.666)) { - gl.glColor3f(0f, 1f, 0f); - } else { - gl.glColor3f(0f, 0f, 1f); - } - - Body currBody = bodies[i]; - - gl.glTexCoord2f(0, 1); - gl.glVertex3f(currBody.getX(), currBody.getY() + 1, currBody.getZ()); - gl.glTexCoord2f(0, 0); - gl.glVertex3f(currBody.getX(), currBody.getY(), currBody.getZ()); - gl.glTexCoord2f(1, 0); - gl.glVertex3f(currBody.getX() + 1, currBody.getY(), currBody.getZ()); - gl.glTexCoord2f(1, 1); - gl.glVertex3f(currBody.getX() + 1, currBody.getY() + 1, currBody.getZ()); - - } - gl.glEnd(); - } - } - - public static int width; - - public static int height; - - public static boolean running; - - public static Texture texture = null; - - public static void main(String _args[]) { - final int bodyCount = Integer.getInteger("bodies", 8192); - - //final Main kernel = new Main(bodyCount); - final NBodyKernel kernel = new NBodyKernel(Range.create(bodyCount)); - - final JFrame frame = new JFrame("NBody"); - - final JPanel panel = new JPanel(new BorderLayout()); - final JPanel controlPanel = new JPanel(new FlowLayout()); - panel.add(controlPanel, BorderLayout.SOUTH); - - final JButton startButton = new JButton("Start"); - - startButton.addActionListener(new ActionListener(){ - @Override public void actionPerformed(ActionEvent e) { - running = true; - startButton.setEnabled(false); - } - }); - controlPanel.add(startButton); - //controlPanel.add(new JLabel(kernel.getExecutionMode().toString())); - - controlPanel.add(new JLabel(" Particles")); - controlPanel.add(new JTextField("" + bodyCount, 5)); - - controlPanel.add(new JLabel("FPS")); - final JTextField framesPerSecondTextField = new JTextField("0", 5); - - controlPanel.add(framesPerSecondTextField); - controlPanel.add(new JLabel("Score(")); - final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); - - controlPanel.add(miniLabel); - controlPanel.add(new JLabel(")")); - - final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); - - controlPanel.add(positionUpdatesPerMicroSecondTextField); - final GLCapabilities caps = new GLCapabilities(null); - final GLProfile profile = caps.getGLProfile(); - caps.setDoubleBuffered(true); - caps.setHardwareAccelerated(true); - final GLCanvas canvas = new GLCanvas(caps); - - final Dimension dimension = new Dimension(Integer.getInteger("width", 742 - 64), Integer.getInteger("height", 742 - 64)); - canvas.setPreferredSize(dimension); - - canvas.addGLEventListener(new GLEventListener(){ - private double ratio; - - private final float xeye = 0f; - - private final float yeye = 0f; - - private final float zeye = 100f; - - private final float xat = 0f; - - private final float yat = 0f; - - private final float zat = 0f; - - public final float zoomFactor = 1.0f; - - private int frames; - - private long last = System.currentTimeMillis(); - - @Override public void dispose(GLAutoDrawable drawable) { - - } - - @Override public void display(GLAutoDrawable drawable) { - - final GL2 gl = drawable.getGL().getGL2(); - texture.enable(gl); - texture.bind(gl); - gl.glLoadIdentity(); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - gl.glColor3f(1f, 1f, 1f); - - final GLU glu = new GLU(); - glu.gluPerspective(45f, ratio, 0f, 1000f); - - glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); - if (running) { - //Arrays.parallel(bodies.toArray(new Body[1])).forEach(b -> {b.nextMove();}); - kernel.execute(kernel.range); - - } - kernel.render(gl); - - final long now = System.currentTimeMillis(); - final long time = now - last; - frames++; - - if (time > 1000) { // We update the frames/sec every second - if (running) { - final float framesPerSecond = (frames * 1000.0f) / time; - final int updatesPerMicroSecond = (int) ((framesPerSecond * bodyCount * bodyCount) / 1000000); - framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); - positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); - } - frames = 0; - last = now; - } - gl.glFlush(); - - } - - @Override public void init(GLAutoDrawable drawable) { - final GL2 gl = drawable.getGL().getGL2(); - - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - gl.glEnable(GL.GL_BLEND); - gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); - - gl.glEnable(GL.GL_TEXTURE_2D); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); - try { - final InputStream textureStream = Main.class.getResourceAsStream("particle.jpg"); - texture = TextureIO.newTexture(textureStream, false, null); - texture.enable(gl); - } catch (final IOException e) { - e.printStackTrace(); - } catch (final GLException e) { - e.printStackTrace(); - } - - } - - @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { - width = _width; - height = _height; - - final GL2 gl = drawable.getGL().getGL2(); - gl.glViewport(0, 0, width, height); - - ratio = (double) width / (double) height; - - } - - }); - - panel.add(canvas, BorderLayout.CENTER); - frame.getContentPane().add(panel, BorderLayout.CENTER); - final FPSAnimator animator = new FPSAnimator(canvas, 100); - - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - frame.pack(); - frame.setVisible(true); - - animator.start(); - - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + + */ +package com.aparapi.examples.oopnbody; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; + +import com.jogamp.opengl.GL; +import com.jogamp.opengl.GL2; +import com.jogamp.opengl.GLAutoDrawable; +import com.jogamp.opengl.GLCapabilities; +import com.jogamp.opengl.GLEventListener; +import com.jogamp.opengl.GLException; +import com.jogamp.opengl.GLProfile; +import com.jogamp.opengl.awt.GLCanvas; +import com.jogamp.opengl.fixedfunc.GLLightingFunc; +import com.jogamp.opengl.glu.GLU; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.WindowConstants; + +import com.aparapi.Kernel; +import com.aparapi.ProfileInfo; +import com.aparapi.Range; + +import com.jogamp.opengl.util.FPSAnimator; +import com.jogamp.opengl.util.texture.Texture; +import com.jogamp.opengl.util.texture.TextureIO; + +/** + * NBody implementing demonstrating Aparapi kernels. + * + * For a description of the NBody problem. + * + * @see http://en.wikipedia.org/wiki/N-body_problem + * + * We use JOGL to render the bodies. + * @see http://jogamp.org/jogl/www/ + * + * @author gfrost + * + */ +public class Main{ + + public static class NBodyKernel extends Kernel{ + + protected final float delT = .005f; + + protected final float espSqr = 1.0f; + + protected final float mass = 5f; + + private final Range range; + + public Body[] bodies; + + /** + * Constructor initializes xyz and vxyz arrays. + * + * @param _bodies + */ + public NBodyKernel(Range _range) { + range = _range; + bodies = new Body[range.getGlobalSize(0)]; + + final float maxDist = 20f; + for (int body = 0; body < range.getGlobalSize(0); body++) { + final float theta = (float) (Math.random() * Math.PI * 2); + final float phi = (float) (Math.random() * Math.PI * 2); + final float radius = (float) (Math.random() * maxDist); + + // get the 3D dimensional coordinates + float x = (float) (radius * Math.cos(theta) * Math.sin(phi)); + float y = (float) (radius * Math.sin(theta) * Math.sin(phi)); + float z = (float) (radius * Math.cos(phi)); + + // divide into two 'spheres of bodies' by adjusting x + if ((body % 2) == 0) { + x += maxDist * 1.5; + } else { + x -= maxDist * 1.5; + } + bodies[body] = new Body(x, y, z, 5f); + } + + Body.allBodies = bodies; + } + + /** + * Here is the kernel entrypoint. Here is where we calculate the position of each body + */ + @Override public void run() { + final int body = getGlobalId(); + + float accx = 0.f; + float accy = 0.f; + float accz = 0.f; + + float myPosx = bodies[body].getX(); + float myPosy = bodies[body].getY(); + float myPosz = bodies[body].getZ(); + + for (int i = 0; i < getGlobalSize(0); i++) { + + final float dx = bodies[i].getX() - myPosx; + final float dy = bodies[i].getY() - myPosy; + final float dz = bodies[i].getZ() - myPosz; + final float invDist = rsqrt((dx * dx) + (dy * dy) + (dz * dz) + espSqr); + final float s = bodies[i].getM() * invDist * invDist * invDist; + accx = accx + (s * dx); + accy = accy + (s * dy); + accz = accz + (s * dz); + } + + accx = accx * delT; + accy = accy * delT; + accz = accz * delT; + bodies[body].setX(myPosx + (bodies[body].getVx() * delT) + (accx * .5f * delT)); + bodies[body].setY(myPosy + (bodies[body].getVy() * delT) + (accy * .5f * delT)); + bodies[body].setZ(myPosz + (bodies[body].getVz() * delT) + (accz * .5f * delT)); + + bodies[body].setVx(bodies[body].getVx() + accx); + bodies[body].setVy(bodies[body].getVy() + accy); + bodies[body].setVz(bodies[body].getVz() + accz); + } + + /** + * Render all particles to the OpenGL context + * + * @param gl + */ + + protected void render(GL2 gl) { + gl.glBegin(GL2.GL_QUADS); + int sz = range.getGlobalSize(0); + for (int i = 0; i < sz; i++) { + + if (i < (sz / 2)) { + gl.glColor3f(1f, 0f, 0f); + } else if (i < (sz * 0.666)) { + gl.glColor3f(0f, 1f, 0f); + } else { + gl.glColor3f(0f, 0f, 1f); + } + + Body currBody = bodies[i]; + + gl.glTexCoord2f(0, 1); + gl.glVertex3f(currBody.getX(), currBody.getY() + 1, currBody.getZ()); + gl.glTexCoord2f(0, 0); + gl.glVertex3f(currBody.getX(), currBody.getY(), currBody.getZ()); + gl.glTexCoord2f(1, 0); + gl.glVertex3f(currBody.getX() + 1, currBody.getY(), currBody.getZ()); + gl.glTexCoord2f(1, 1); + gl.glVertex3f(currBody.getX() + 1, currBody.getY() + 1, currBody.getZ()); + + } + gl.glEnd(); + } + } + + public static int width; + + public static int height; + + public static boolean running; + + public static Texture texture = null; + + public static void main(String _args[]) { + final int bodyCount = Integer.getInteger("bodies", 8192); + + //final Main kernel = new Main(bodyCount); + final NBodyKernel kernel = new NBodyKernel(Range.create(bodyCount)); + + final JFrame frame = new JFrame("NBody"); + + final JPanel panel = new JPanel(new BorderLayout()); + final JPanel controlPanel = new JPanel(new FlowLayout()); + panel.add(controlPanel, BorderLayout.SOUTH); + + final JButton startButton = new JButton("Start"); + + startButton.addActionListener(new ActionListener(){ + @Override public void actionPerformed(ActionEvent e) { + running = true; + startButton.setEnabled(false); + } + }); + controlPanel.add(startButton); + //controlPanel.add(new JLabel(kernel.getExecutionMode().toString())); + + controlPanel.add(new JLabel(" Particles")); + controlPanel.add(new JTextField("" + bodyCount, 5)); + + controlPanel.add(new JLabel("FPS")); + final JTextField framesPerSecondTextField = new JTextField("0", 5); + + controlPanel.add(framesPerSecondTextField); + controlPanel.add(new JLabel("Score(")); + final JLabel miniLabel = new JLabel("<html><small>calcs</small><hr/><small>µsec</small></html>"); + + controlPanel.add(miniLabel); + controlPanel.add(new JLabel(")")); + + final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5); + + controlPanel.add(positionUpdatesPerMicroSecondTextField); + final GLCapabilities caps = new GLCapabilities(null); + final GLProfile profile = caps.getGLProfile(); + caps.setDoubleBuffered(true); + caps.setHardwareAccelerated(true); + final GLCanvas canvas = new GLCanvas(caps); + + final Dimension dimension = new Dimension(Integer.getInteger("width", 742 - 64), Integer.getInteger("height", 742 - 64)); + canvas.setPreferredSize(dimension); + + canvas.addGLEventListener(new GLEventListener(){ + private double ratio; + + private final float xeye = 0f; + + private final float yeye = 0f; + + private final float zeye = 100f; + + private final float xat = 0f; + + private final float yat = 0f; + + private final float zat = 0f; + + public final float zoomFactor = 1.0f; + + private int frames; + + private long last = System.currentTimeMillis(); + + @Override public void dispose(GLAutoDrawable drawable) { + + } + + @Override public void display(GLAutoDrawable drawable) { + + final GL2 gl = drawable.getGL().getGL2(); + texture.enable(gl); + texture.bind(gl); + gl.glLoadIdentity(); + gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + gl.glColor3f(1f, 1f, 1f); + + final GLU glu = new GLU(); + glu.gluPerspective(45f, ratio, 0f, 1000f); + + glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f); + if (running) { + //Arrays.parallel(bodies.toArray(new Body[1])).forEach(b -> {b.nextMove();}); + kernel.execute(kernel.range); + + } + kernel.render(gl); + + final long now = System.currentTimeMillis(); + final long time = now - last; + frames++; + + if (time > 1000) { // We update the frames/sec every second + if (running) { + final float framesPerSecond = (frames * 1000.0f) / time; + final int updatesPerMicroSecond = (int) ((framesPerSecond * bodyCount * bodyCount) / 1000000); + framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond)); + positionUpdatesPerMicroSecondTextField.setText(String.format("%4d", updatesPerMicroSecond)); + } + frames = 0; + last = now; + } + gl.glFlush(); + + } + + @Override public void init(GLAutoDrawable drawable) { + final GL2 gl = drawable.getGL().getGL2(); + + gl.glShadeModel(GLLightingFunc.GL_SMOOTH); + gl.glEnable(GL.GL_BLEND); + gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); + + gl.glEnable(GL.GL_TEXTURE_2D); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); + try { + final InputStream textureStream = Main.class.getResourceAsStream("particle.jpg"); + texture = TextureIO.newTexture(textureStream, false, null); + texture.enable(gl); + } catch (final IOException e) { + e.printStackTrace(); + } catch (final GLException e) { + e.printStackTrace(); + } + + } + + @Override public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) { + width = _width; + height = _height; + + final GL2 gl = drawable.getGL().getGL2(); + gl.glViewport(0, 0, width, height); + + ratio = (double) width / (double) height; + + } + + }); + + panel.add(canvas, BorderLayout.CENTER); + frame.getContentPane().add(panel, BorderLayout.CENTER); + final FPSAnimator animator = new FPSAnimator(canvas, 100); + + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + + animator.start(); + + } + +} diff --git a/src/main/java/com/aparapi/examples/progress/LongRunningKernel.java b/src/main/java/com/aparapi/examples/progress/LongRunningKernel.java index a510b643..7cae85a2 100644 --- a/src/main/java/com/aparapi/examples/progress/LongRunningKernel.java +++ b/src/main/java/com/aparapi/examples/progress/LongRunningKernel.java @@ -1,41 +1,56 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.progress; - -import com.aparapi.Kernel; - -/** - * Kernel which performs very many meaningless calculations, used to demonstrate progress tracking and cancellation of multi-pass Kernels. - */ -public class LongRunningKernel extends Kernel { - - public static final int RANGE = 20000; - private static final int REPETITIONS = 1 * 1000 * 1000; - - public final long[] data = new long[RANGE]; - - @Override - public void run() { - int id = getGlobalId(); - if (id == 0) { - report(); - } - for (int rep = 0; rep < REPETITIONS; ++rep) { - data[id] += (int) sqrt(1); - } - } - - @NoCL - public void report() { - int passId = getPassId(); - System.out.println("Java execution: passId = " + passId); - } -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.progress; + +import com.aparapi.Kernel; + +/** + * Kernel which performs very many meaningless calculations, used to demonstrate progress tracking and cancellation of multi-pass Kernels. + */ +public class LongRunningKernel extends Kernel { + + public static final int RANGE = 20000; + private static final int REPETITIONS = 1 * 1000 * 1000; + + public final long[] data = new long[RANGE]; + + @Override + public void run() { + int id = getGlobalId(); + if (id == 0) { + report(); + } + for (int rep = 0; rep < REPETITIONS; ++rep) { + data[id] += (int) sqrt(1); + } + } + + @NoCL + public void report() { + int passId = getPassId(); + System.out.println("Java execution: passId = " + passId); + } +} diff --git a/src/main/java/com/aparapi/examples/progress/MultiPassKernelSwingWorkerDemo.java b/src/main/java/com/aparapi/examples/progress/MultiPassKernelSwingWorkerDemo.java index 87bac218..1f11c54a 100644 --- a/src/main/java/com/aparapi/examples/progress/MultiPassKernelSwingWorkerDemo.java +++ b/src/main/java/com/aparapi/examples/progress/MultiPassKernelSwingWorkerDemo.java @@ -1,142 +1,157 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.progress; - -import com.aparapi.*; -import com.aparapi.internal.kernel.*; -import com.aparapi.util.swing.MultiPassKernelSwingWorker; - -import javax.swing.*; -import javax.swing.plaf.nimbus.NimbusLookAndFeel; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * Demonstrates progress tracking and cancellation for multi-pass kernels, via {@link MultiPassKernelSwingWorker}. - */ -public class MultiPassKernelSwingWorkerDemo { - - private static final int PASS_COUNT = 200; - private static JButton startButton; - private static JButton cancelButton; - private static JProgressBar progress; - private static JLabel status = new JLabel("Press Start", JLabel.CENTER); - private static LongRunningKernel kernel; - private static MultiPassKernelSwingWorker worker; - - private static final boolean TEST_JTP = false; - - public static void main(String[] ignored) throws Exception { - if (TEST_JTP) { - KernelManager.setKernelManager(KernelManagers.JTP_ONLY); - } - kernel = new LongRunningKernel(); - - UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName()); - JPanel rootPanel = new JPanel(); - rootPanel.setLayout(new BorderLayout()); - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER)); - startButton = new JButton("Start"); - cancelButton = new JButton("Cancel"); - startButton.setEnabled(true); - startButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - start(); - } - }); - cancelButton.setEnabled(false); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - cancel(); - } - }); - buttons.add(startButton); - buttons.add(cancelButton); - rootPanel.add(buttons, BorderLayout.SOUTH); - - progress = new JProgressBar(new DefaultBoundedRangeModel(0, 0, 0, PASS_COUNT)); - - rootPanel.add(status, BorderLayout.CENTER); - rootPanel.add(progress, BorderLayout.NORTH); - - JFrame frame = new JFrame("MultiPassKernelSwingWorker Demo"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.getContentPane().add(rootPanel); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - } - - private static MultiPassKernelSwingWorker createWorker() { - return new MultiPassKernelSwingWorker(kernel) { - @Override - protected void executeKernel(Kernel kernel) { - int range; - if (TEST_JTP) { - range = LongRunningKernel.RANGE / 1000; - } else { - range = LongRunningKernel.RANGE; - } - kernel.execute(range, PASS_COUNT); - } - - @Override - protected void updatePassId(int passId) { - updateProgress(passId); - } - - @Override - protected void done() { - updateProgress(KernelRunner.PASS_ID_COMPLETED_EXECUTION); - startButton.setEnabled(true); - cancelButton.setEnabled(false); - } - }; - } - - private static void start() { - if (!SwingUtilities.isEventDispatchThread()) { - throw new IllegalStateException(); - } - - startButton.setEnabled(false); - cancelButton.setEnabled(true); - worker = createWorker(); - worker.execute(); - System.out.println("Started execution of MultiPassKernelSwingWorker"); - } - - private static void updateProgress(int passId) { - int progressValue; - if (passId >= 0) { - progressValue = passId; - status.setText("passId = " + passId); - } else if (passId == KernelRunner.PASS_ID_PREPARING_EXECUTION) { - progressValue = 0; - status.setText("Preparing"); - } else if (passId == KernelRunner.PASS_ID_COMPLETED_EXECUTION) { - progressValue = PASS_COUNT; - status.setText("Complete"); - } else { - progressValue = 0; - status.setText("Illegal status " + passId); - } - progress.getModel().setValue(progressValue); - } - - private static void cancel() { - worker.cancelExecution(); - } -} - +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.progress; + +import com.aparapi.*; +import com.aparapi.internal.kernel.*; +import com.aparapi.util.swing.MultiPassKernelSwingWorker; + +import javax.swing.*; +import javax.swing.plaf.nimbus.NimbusLookAndFeel; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * Demonstrates progress tracking and cancellation for multi-pass kernels, via {@link MultiPassKernelSwingWorker}. + */ +public class MultiPassKernelSwingWorkerDemo { + + private static final int PASS_COUNT = 200; + private static JButton startButton; + private static JButton cancelButton; + private static JProgressBar progress; + private static JLabel status = new JLabel("Press Start", JLabel.CENTER); + private static LongRunningKernel kernel; + private static MultiPassKernelSwingWorker worker; + + private static final boolean TEST_JTP = false; + + public static void main(String[] ignored) throws Exception { + if (TEST_JTP) { + KernelManager.setKernelManager(KernelManagers.JTP_ONLY); + } + kernel = new LongRunningKernel(); + + UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName()); + JPanel rootPanel = new JPanel(); + rootPanel.setLayout(new BorderLayout()); + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER)); + startButton = new JButton("Start"); + cancelButton = new JButton("Cancel"); + startButton.setEnabled(true); + startButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + start(); + } + }); + cancelButton.setEnabled(false); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancel(); + } + }); + buttons.add(startButton); + buttons.add(cancelButton); + rootPanel.add(buttons, BorderLayout.SOUTH); + + progress = new JProgressBar(new DefaultBoundedRangeModel(0, 0, 0, PASS_COUNT)); + + rootPanel.add(status, BorderLayout.CENTER); + rootPanel.add(progress, BorderLayout.NORTH); + + JFrame frame = new JFrame("MultiPassKernelSwingWorker Demo"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(rootPanel); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static MultiPassKernelSwingWorker createWorker() { + return new MultiPassKernelSwingWorker(kernel) { + @Override + protected void executeKernel(Kernel kernel) { + int range; + if (TEST_JTP) { + range = LongRunningKernel.RANGE / 1000; + } else { + range = LongRunningKernel.RANGE; + } + kernel.execute(range, PASS_COUNT); + } + + @Override + protected void updatePassId(int passId) { + updateProgress(passId); + } + + @Override + protected void done() { + updateProgress(KernelRunner.PASS_ID_COMPLETED_EXECUTION); + startButton.setEnabled(true); + cancelButton.setEnabled(false); + } + }; + } + + private static void start() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + + startButton.setEnabled(false); + cancelButton.setEnabled(true); + worker = createWorker(); + worker.execute(); + System.out.println("Started execution of MultiPassKernelSwingWorker"); + } + + private static void updateProgress(int passId) { + int progressValue; + if (passId >= 0) { + progressValue = passId; + status.setText("passId = " + passId); + } else if (passId == KernelRunner.PASS_ID_PREPARING_EXECUTION) { + progressValue = 0; + status.setText("Preparing"); + } else if (passId == KernelRunner.PASS_ID_COMPLETED_EXECUTION) { + progressValue = PASS_COUNT; + status.setText("Complete"); + } else { + progressValue = 0; + status.setText("Illegal status " + passId); + } + progress.getModel().setValue(progressValue); + } + + private static void cancel() { + worker.cancelExecution(); + } +} + diff --git a/src/main/java/com/aparapi/examples/progress/ProgressAndCancelDemo.java b/src/main/java/com/aparapi/examples/progress/ProgressAndCancelDemo.java index 6dcd759a..0b3b8a4b 100644 --- a/src/main/java/com/aparapi/examples/progress/ProgressAndCancelDemo.java +++ b/src/main/java/com/aparapi/examples/progress/ProgressAndCancelDemo.java @@ -1,176 +1,191 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -package com.aparapi.examples.progress; - -import com.aparapi.internal.kernel.*; - -import javax.swing.*; -import javax.swing.plaf.nimbus.*; -import java.awt.*; -import java.awt.event.*; - -/** - * Demonstrates progress tracking and cancellation for multi-pass kernels. - */ -public class ProgressAndCancelDemo { - - private static final int PASS_COUNT = 200; - private static final int POLL_SLEEP = 50; - private static JButton startButton; - private static JButton cancelButton; - private static JProgressBar progress; - private static JLabel status = new JLabel("Press Start", JLabel.CENTER); - - private static LongRunningKernel kernel; - private static Timer timer; - - private static final boolean TEST_JTP = false; - - public static void main(String[] ignored) throws Exception { - - System.setProperty("com.aparapi.enableShowGeneratedOpenCL", "true"); - System.setProperty("com.aparapi.enableVerboseJNI", "true"); - System.setProperty("com.aparapi.dumpFlags", "true"); - System.setProperty("com.aparapi.enableVerboseJNIOpenCLResourceTracking", "true"); - System.setProperty("com.aparapi.enableExecutionModeReporting", "true"); - - kernel = new LongRunningKernel(); - if (TEST_JTP) { - KernelManager.setKernelManager(KernelManagers.JTP_ONLY); - } - Thread asynchReader = new Thread() { - @Override - public void run() { - while (true) { - try { - int cancelState = kernel.getCancelState(); - int passId = kernel.getCurrentPass(); - System.out.println("cancel = " + cancelState + ", passId = " + passId); - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }; - //asynchReader.start(); - UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName()); - JPanel rootPanel = new JPanel(); - rootPanel.setLayout(new BorderLayout()); - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER)); - startButton = new JButton("Start"); - cancelButton = new JButton("Cancel"); - startButton.setEnabled(true); - startButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - start(); - } - }); - cancelButton.setEnabled(false); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - cancel(); - } - }); - buttons.add(startButton); - buttons.add(cancelButton); - rootPanel.add(buttons, BorderLayout.SOUTH); - - progress = new JProgressBar(new DefaultBoundedRangeModel(0, 0, 0, PASS_COUNT)); - - rootPanel.add(status, BorderLayout.CENTER); - rootPanel.add(progress, BorderLayout.NORTH); - - JFrame frame = new JFrame("Progress and Cancel Demo"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.getContentPane().add(rootPanel); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - } - - private static void start() { - if (!SwingUtilities.isEventDispatchThread()) { - throw new IllegalStateException(); - } - Thread executionThread = new Thread() { - @Override - public void run() { - executeKernel(); - } - }; - executionThread.start(); - updateProgress(); - timer = new Timer(POLL_SLEEP, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateProgress(); - } - }); - timer.setCoalesce(false); - timer.setRepeats(true); - timer.start(); - System.out.println("Started on EDT"); - } - - private static void updateProgress() { - int passId = kernel.getCurrentPass(); - int progressValue; - if (passId >= 0) { - progressValue = passId; - status.setText("passId = " + passId); - } else if (passId == KernelRunner.PASS_ID_PREPARING_EXECUTION) { - progressValue = 0; - status.setText("Preparing"); - } else if (passId == KernelRunner.PASS_ID_COMPLETED_EXECUTION) { - progressValue = PASS_COUNT; - status.setText("Complete"); - } else { - progressValue = 0; - status.setText("Illegal status " + passId); - } - progress.getModel().setValue(progressValue); - } - - private static void cancel() { - kernel.cancelMultiPass(); - } - - private static void executeKernel() { - System.out.println("Starting execution"); - startButton.setEnabled(false); - cancelButton.setEnabled(true); - try { - int range; - if (TEST_JTP) { - range = LongRunningKernel.RANGE / 1000; - } else { - range = LongRunningKernel.RANGE; - } - kernel.execute(range, PASS_COUNT); - } catch (Throwable t) { - t.printStackTrace(); - } finally { - System.out.println("Finished execution"); - System.out.println("kernel.data[0] = " + kernel.data[0]); - if (timer != null) { - timer.stop(); - timer = null; - } - startButton.setEnabled(true); - cancelButton.setEnabled(false); - updateProgress(); - } - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +package com.aparapi.examples.progress; + +import com.aparapi.internal.kernel.*; + +import javax.swing.*; +import javax.swing.plaf.nimbus.*; +import java.awt.*; +import java.awt.event.*; + +/** + * Demonstrates progress tracking and cancellation for multi-pass kernels. + */ +public class ProgressAndCancelDemo { + + private static final int PASS_COUNT = 200; + private static final int POLL_SLEEP = 50; + private static JButton startButton; + private static JButton cancelButton; + private static JProgressBar progress; + private static JLabel status = new JLabel("Press Start", JLabel.CENTER); + + private static LongRunningKernel kernel; + private static Timer timer; + + private static final boolean TEST_JTP = false; + + public static void main(String[] ignored) throws Exception { + + System.setProperty("com.aparapi.enableShowGeneratedOpenCL", "true"); + System.setProperty("com.aparapi.enableVerboseJNI", "true"); + System.setProperty("com.aparapi.dumpFlags", "true"); + System.setProperty("com.aparapi.enableVerboseJNIOpenCLResourceTracking", "true"); + System.setProperty("com.aparapi.enableExecutionModeReporting", "true"); + + kernel = new LongRunningKernel(); + if (TEST_JTP) { + KernelManager.setKernelManager(KernelManagers.JTP_ONLY); + } + Thread asynchReader = new Thread() { + @Override + public void run() { + while (true) { + try { + int cancelState = kernel.getCancelState(); + int passId = kernel.getCurrentPass(); + System.out.println("cancel = " + cancelState + ", passId = " + passId); + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + }; + //asynchReader.start(); + UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName()); + JPanel rootPanel = new JPanel(); + rootPanel.setLayout(new BorderLayout()); + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER)); + startButton = new JButton("Start"); + cancelButton = new JButton("Cancel"); + startButton.setEnabled(true); + startButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + start(); + } + }); + cancelButton.setEnabled(false); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + cancel(); + } + }); + buttons.add(startButton); + buttons.add(cancelButton); + rootPanel.add(buttons, BorderLayout.SOUTH); + + progress = new JProgressBar(new DefaultBoundedRangeModel(0, 0, 0, PASS_COUNT)); + + rootPanel.add(status, BorderLayout.CENTER); + rootPanel.add(progress, BorderLayout.NORTH); + + JFrame frame = new JFrame("Progress and Cancel Demo"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(rootPanel); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void start() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + Thread executionThread = new Thread() { + @Override + public void run() { + executeKernel(); + } + }; + executionThread.start(); + updateProgress(); + timer = new Timer(POLL_SLEEP, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateProgress(); + } + }); + timer.setCoalesce(false); + timer.setRepeats(true); + timer.start(); + System.out.println("Started on EDT"); + } + + private static void updateProgress() { + int passId = kernel.getCurrentPass(); + int progressValue; + if (passId >= 0) { + progressValue = passId; + status.setText("passId = " + passId); + } else if (passId == KernelRunner.PASS_ID_PREPARING_EXECUTION) { + progressValue = 0; + status.setText("Preparing"); + } else if (passId == KernelRunner.PASS_ID_COMPLETED_EXECUTION) { + progressValue = PASS_COUNT; + status.setText("Complete"); + } else { + progressValue = 0; + status.setText("Illegal status " + passId); + } + progress.getModel().setValue(progressValue); + } + + private static void cancel() { + kernel.cancelMultiPass(); + } + + private static void executeKernel() { + System.out.println("Starting execution"); + startButton.setEnabled(false); + cancelButton.setEnabled(true); + try { + int range; + if (TEST_JTP) { + range = LongRunningKernel.RANGE / 1000; + } else { + range = LongRunningKernel.RANGE; + } + kernel.execute(range, PASS_COUNT); + } catch (Throwable t) { + t.printStackTrace(); + } finally { + System.out.println("Finished execution"); + System.out.println("kernel.data[0] = " + kernel.data[0]); + if (timer != null) { + timer.stop(); + timer = null; + } + startButton.setEnabled(true); + cancelButton.setEnabled(false); + updateProgress(); + } + } + +} diff --git a/src/main/java/com/aparapi/examples/squares/Main.java b/src/main/java/com/aparapi/examples/squares/Main.java index e7f3bf8e..0c97fae8 100644 --- a/src/main/java/com/aparapi/examples/squares/Main.java +++ b/src/main/java/com/aparapi/examples/squares/Main.java @@ -1,106 +1,121 @@ -/** - * This product currently only contains code developed by authors - * of specific components, as identified by the source code files. - * - * Since product implements StAX API, it has dependencies to StAX API - * classes. - * - * For additional credits (generally to people who reported problems) - * see CREDITS file. - */ -/* -Copyright (c) 2010-2011, Advanced Micro Devices, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following -disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following -disclaimer in the documentation and/or other materials provided with the distribution. - -Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products -derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export -laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through -774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, -you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of -Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration -Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, -E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups -D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject -to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 -of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations -under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. - -*/ - -package com.aparapi.examples.squares; - -import com.aparapi.Kernel; -import com.aparapi.Range; - -/** - * An example Aparapi application which computes and displays squares of a set of 512 input values. - * While executing on GPU using Aparpi framework, each square value is computed in a separate kernel invocation and - * can thus maximize performance by optimally utilizing all GPU computing units - * - * @author gfrost - * - */ - -public class Main{ - - public static void main(String[] _args) { - - final int size = 512; - - /** Input float array for which square values need to be computed. */ - final float[] values = new float[size]; - - /** Initialize input array. */ - for (int i = 0; i < size; i++) { - values[i] = i; - } - - /** Output array which will be populated with square values of corresponding input array elements. */ - final float[] squares = new float[size]; - - /** Aparapi Kernel which computes squares of input array elements and populates them in corresponding elements of - * output array. - **/ - Kernel kernel = new Kernel(){ - @Override public void run() { - int gid = getGlobalId(); - squares[gid] = values[gid] * values[gid]; - } - }; - - // Execute Kernel. - - kernel.execute(Range.create(512)); - - // Report target execution mode: GPU or JTP (Java Thread Pool). - System.out.println("Device = " + kernel.getTargetDevice().getShortDescription()); - - // Display computed square values. - for (int i = 0; i < size; i++) { - System.out.printf("%6.0f %8.0f\n", values[i], squares[i]); - } - - // Dispose Kernel resources. - kernel.dispose(); - } - -} +/** + * Copyright (c) 2016 - 2017 Syncleus, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This product currently only contains code developed by authors + * of specific components, as identified by the source code files. + * + * Since product implements StAX API, it has dependencies to StAX API + * classes. + * + * For additional credits (generally to people who reported problems) + * see CREDITS file. + */ +/* +Copyright (c) 2010-2011, Advanced Micro Devices, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the +following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following +disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export +laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through +774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR, +you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of +Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration +Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1, +E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups +D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject +to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774 +of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations +under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/. + +*/ + +package com.aparapi.examples.squares; + +import com.aparapi.Kernel; +import com.aparapi.Range; + +/** + * An example Aparapi application which computes and displays squares of a set of 512 input values. + * While executing on GPU using Aparpi framework, each square value is computed in a separate kernel invocation and + * can thus maximize performance by optimally utilizing all GPU computing units + * + * @author gfrost + * + */ + +public class Main{ + + public static void main(String[] _args) { + + final int size = 512; + + /** Input float array for which square values need to be computed. */ + final float[] values = new float[size]; + + /** Initialize input array. */ + for (int i = 0; i < size; i++) { + values[i] = i; + } + + /** Output array which will be populated with square values of corresponding input array elements. */ + final float[] squares = new float[size]; + + /** Aparapi Kernel which computes squares of input array elements and populates them in corresponding elements of + * output array. + **/ + Kernel kernel = new Kernel(){ + @Override public void run() { + int gid = getGlobalId(); + squares[gid] = values[gid] * values[gid]; + } + }; + + // Execute Kernel. + + kernel.execute(Range.create(512)); + + // Report target execution mode: GPU or JTP (Java Thread Pool). + System.out.println("Device = " + kernel.getTargetDevice().getShortDescription()); + + // Display computed square values. + for (int i = 0; i < size; i++) { + System.out.printf("%6.0f %8.0f\n", values[i], squares[i]); + } + + // Dispose Kernel resources. + kernel.dispose(); + } + +} -- GitLab