1 /*
   2  * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.scenario.effect.compiler.backend.sw.sse;
  27 
  28 import java.io.InputStreamReader;
  29 import java.io.Reader;
  30 import java.util.Collection;
  31 import java.util.Comparator;
  32 import java.util.HashMap;
  33 import java.util.HashSet;
  34 import java.util.Map;
  35 import java.util.Set;
  36 import java.util.SortedSet;
  37 import java.util.TreeSet;
  38 import com.sun.scenario.effect.compiler.JSLParser;
  39 import com.sun.scenario.effect.compiler.model.BaseType;
  40 import com.sun.scenario.effect.compiler.model.Qualifier;
  41 import com.sun.scenario.effect.compiler.model.Type;
  42 import com.sun.scenario.effect.compiler.model.Variable;
  43 import com.sun.scenario.effect.compiler.tree.FuncDef;
  44 import com.sun.scenario.effect.compiler.tree.ProgramUnit;
  45 import com.sun.scenario.effect.compiler.tree.TreeScanner;
  46 import org.antlr.stringtemplate.StringTemplate;
  47 import org.antlr.stringtemplate.StringTemplateGroup;
  48 import org.antlr.stringtemplate.language.DefaultTemplateLexer;
  49 
  50 /**
  51  */
  52 public class SSEBackend extends TreeScanner {
  53 
  54     private final JSLParser parser;
  55     private final String body;
  56 
  57     public SSEBackend(JSLParser parser, ProgramUnit program) {
  58         // TODO: will be removed once we clean up static usage
  59         resetStatics();
  60 
  61         this.parser = parser;
  62 
  63         SSETreeScanner scanner = new SSETreeScanner();
  64         scanner.scan(program);
  65         this.body = scanner.getResult();
  66     }
  67 
  68     public static class GenCode {
  69         public String javaCode;
  70         public String nativeCode;
  71     }
  72 
  73     private static void appendGetRelease(StringBuilder get,
  74                                          StringBuilder rel,
  75                                          String ctype,
  76                                          String cbufName, String jarrayName)
  77     {
  78         get.append("j" + ctype + " *" + cbufName + " = (j" + ctype + " *)");
  79         get.append("env->GetPrimitiveArrayCritical(" + jarrayName + ", 0);\n");
  80         get.append("if (" + cbufName + " == NULL) return;\n");
  81         rel.append("env->ReleasePrimitiveArrayCritical(" + jarrayName + ", " + cbufName + ", JNI_ABORT);\n");
  82     }
  83 
  84     private static SortedSet<Variable> getSortedVars(Collection<Variable> unsortedVars) {
  85         Comparator<Variable> c = (v0, v1) -> v0.getName().compareTo(v1.getName());
  86         SortedSet<Variable> sortedVars = new TreeSet<Variable>(c);
  87         sortedVars.addAll(unsortedVars);
  88         return sortedVars;
  89     }
  90 
  91     public final GenCode getGenCode(String effectName,
  92                                     String peerName,
  93                                     String genericsName,
  94                                     String interfaceName)
  95     {
  96         Map<String, Variable> vars = parser.getSymbolTable().getGlobalVariables();
  97         StringBuilder genericsDecl = new StringBuilder();
  98         StringBuilder interfaceDecl = new StringBuilder();
  99         StringBuilder constants = new StringBuilder();
 100         StringBuilder samplers = new StringBuilder();
 101         StringBuilder cleanup = new StringBuilder();
 102         StringBuilder srcRects = new StringBuilder();
 103         StringBuilder posDecls = new StringBuilder();
 104         StringBuilder pixInitY = new StringBuilder();
 105         StringBuilder pixInitX = new StringBuilder();
 106         StringBuilder posIncrY = new StringBuilder();
 107         StringBuilder posInitY = new StringBuilder();
 108         StringBuilder posIncrX = new StringBuilder();
 109         StringBuilder posInitX = new StringBuilder();
 110         StringBuilder jparams = new StringBuilder();
 111         StringBuilder jparamDecls = new StringBuilder();
 112         StringBuilder cparamDecls = new StringBuilder();
 113         StringBuilder arrayGet = new StringBuilder();
 114         StringBuilder arrayRelease = new StringBuilder();
 115 
 116         appendGetRelease(arrayGet, arrayRelease, "int", "dst", "dst_arr");
 117 
 118         // TODO: only need to declare these if pixcoord is referenced
 119         // somewhere in the program...
 120         pixInitY.append("float pixcoord_y = (float)dy;\n");
 121         pixInitX.append("float pixcoord_x = (float)dx;\n");
 122 
 123         // this step isn't strictly necessary but helps give some predictability
 124         // to the generated jar/nativelib so that the method signatures have
 125         // a consistent parameter ordering on all platforms for each build,
 126         // which may help debugging (see RT-4475)
 127         SortedSet<Variable> sortedVars = getSortedVars(vars.values());
 128         for (Variable v : sortedVars) {
 129             if (v.getQualifier() == Qualifier.CONST && v.getConstValue() == null) {
 130                 // this must be a special built-in variable (e.g. pos0);
 131                 // these are handled elsewhere, so just continue...
 132                 continue;
 133             }
 134 
 135             Type t = v.getType();
 136             BaseType bt = t.getBaseType();
 137             String vtype = bt.toString();
 138             String vname = v.getName();
 139             if (v.getQualifier() != null && bt != BaseType.SAMPLER) {
 140                 String accName = v.getAccessorName();
 141                 if (v.isArray()) {
 142                     // TODO: we currently assume that param arrays will be
 143                     // stored in NIO Int/FloatBuffers, but the inner loop
 144                     // expects to access them as Java arrays, so we convert
 145                     // here; this is obviously bad for performance, so we need
 146                     // to come up with a better system soon...
 147                     String bufType = (bt == BaseType.FLOAT) ?
 148                         "FloatBuffer" : "IntBuffer";
 149                     String bufName = vname + "_buf";
 150                     String arrayName = vname + "_arr";
 151                     constants.append(bufType + " " + bufName + " = " + accName + "();\n");
 152                     constants.append(vtype + "[] " + arrayName);
 153                     constants.append(" = new " + vtype + "[");
 154                     constants.append(bufName + ".capacity()];\n");
 155                     constants.append(bufName + ".get(" + arrayName + ");\n");
 156                     jparams.append(",\n");
 157                     jparams.append(arrayName);
 158                     jparamDecls.append(",\n");
 159                     jparamDecls.append(vtype + "[] " + vname);
 160                     cparamDecls.append(",\n");
 161                     cparamDecls.append("j" + vtype + "Array " + vname);
 162                     appendGetRelease(arrayGet, arrayRelease, vtype, arrayName, vname);
 163                 } else {
 164                     if (t.isVector()) {
 165                         String arrayName = vname + "_arr";
 166                         constants.append(vtype + "[] " + arrayName + " = " + accName + "();\n");
 167                         jparams.append(",\n");
 168                         jparamDecls.append(",\n");
 169                         cparamDecls.append(",\n");
 170                         for (int i = 0; i < t.getNumFields(); i++) {
 171                             if (i > 0) {
 172                                 jparams.append(", ");
 173                                 jparamDecls.append(", ");
 174                                 cparamDecls.append(", ");
 175                             }
 176                             String vn = vname + getSuffix(i);
 177                             jparams.append(arrayName + "[" + i + "]");
 178                             jparamDecls.append(vtype + " " + vn);
 179                             cparamDecls.append("j" + vtype + " " + vn);
 180                         }
 181                     } else {
 182                         constants.append(vtype + " " + vname);
 183                         if (v.getQualifier() == Qualifier.CONST) {
 184                             constants.append(" = " + v.getConstValue());
 185                         } else {
 186                             constants.append(" = " + accName + "()");
 187                         }
 188                         constants.append(";\n");
 189                         jparams.append(",\n");
 190                         jparams.append(vname);
 191                         jparamDecls.append(",\n");
 192                         jparamDecls.append(vtype + " " + vname);
 193                         cparamDecls.append(",\n");
 194                         cparamDecls.append("j" + vtype + " " + vname);
 195                     }
 196                 }
 197             } else if (v.getQualifier() == Qualifier.PARAM && bt == BaseType.SAMPLER) {
 198                 int i = v.getReg();
 199                 if (t == Type.FSAMPLER) {
 200                     samplers.append("FloatMap src" + i + " = (FloatMap)getSamplerData(" + i + ");\n");
 201                     samplers.append("int src" + i + "x = 0;\n");
 202                     samplers.append("int src" + i + "y = 0;\n");
 203                     samplers.append("int src" + i + "w = src" + i + ".getWidth();\n");
 204                     samplers.append("int src" + i + "h = src" + i + ".getHeight();\n");
 205                     samplers.append("int src" + i + "scan = src" + i + ".getWidth();\n");
 206                     samplers.append("float[] " + vname + " = src" + i + ".getData();\n");
 207 
 208                     arrayGet.append("float " + vname + "_vals[4];\n");
 209 
 210                     // TODO: for now, assume [0,0,1,1]
 211                     srcRects.append("float[] src" + i + "Rect = new float[] {0,0,1,1};\n");
 212 
 213                     jparams.append(",\n");
 214                     jparams.append(vname);
 215 
 216                     jparamDecls.append(",\n");
 217                     jparamDecls.append("float[] " + vname + "_arr");
 218 
 219                     cparamDecls.append(",\n");
 220                     cparamDecls.append("jfloatArray " + vname + "_arr");
 221 
 222                     appendGetRelease(arrayGet, arrayRelease, "float", vname, vname + "_arr");
 223                 } else {
 224                     if (t == Type.LSAMPLER) {
 225                         samplers.append("HeapImage src" + i + " = (HeapImage)inputs[" + i + "].getUntransformedImage();\n");
 226                     } else {
 227                         samplers.append("HeapImage src" + i + " = (HeapImage)inputs[" + i + "].getTransformedImage(dstBounds);\n");
 228                         cleanup.append("inputs[" + i + "].releaseTransformedImage(src" + i + ");\n");
 229                     }
 230                     samplers.append("int src" + i + "x = 0;\n");
 231                     samplers.append("int src" + i + "y = 0;\n");
 232                     samplers.append("int src" + i + "w = src" + i + ".getPhysicalWidth();\n");
 233                     samplers.append("int src" + i + "h = src" + i + ".getPhysicalHeight();\n");
 234                     samplers.append("int src" + i + "scan = src" + i + ".getScanlineStride();\n");
 235                     samplers.append("int[] " + vname + " =\n");
 236                     samplers.append("    src" + i + ".getPixelArray();\n");
 237 
 238                     samplers.append("Rectangle src" + i + "Bounds = new Rectangle(");
 239                     samplers.append("src" + i + "x, ");
 240                     samplers.append("src" + i + "y, ");
 241                     samplers.append("src" + i + "w, ");
 242                     samplers.append("src" + i + "h);\n");
 243                     if (t == Type.LSAMPLER) {
 244                         samplers.append("Rectangle src" + i + "InputBounds = inputs[" + i + "].getUntransformedBounds();\n");
 245                         samplers.append("BaseTransform src" + i + "Transform = inputs[" + i + "].getTransform();\n");
 246                     } else {
 247                         samplers.append("Rectangle src" + i + "InputBounds = inputs[" + i + "].getTransformedBounds(dstBounds);\n");
 248                         samplers.append("BaseTransform src" + i + "Transform = BaseTransform.IDENTITY_TRANSFORM;\n");
 249                     }
 250                     samplers.append("setInputBounds(" + i + ", src" + i + "InputBounds);\n");
 251                     samplers.append("setInputNativeBounds(" + i + ", src" + i + "Bounds);\n");
 252 
 253                     if (t == Type.LSAMPLER) {
 254                         arrayGet.append("float " + vname + "_vals[4];\n");
 255                     }
 256 
 257                     // the source rect decls need to come after all calls to
 258                     // setInput[Native]Bounds() for all inputs (since the
 259                     // getSourceRegion() impl may need to query the bounds of
 260                     // other inputs, as is the case in PhongLighting)...
 261                     srcRects.append("float[] src" + i + "Rect = new float[4];\n");
 262                     // Note that we only allocate 4 floats here because none
 263                     // of the loops can deal with fully mapped inputs.  Only
 264                     // shaders that declare LSAMPLERs would require mapped
 265                     // inputs and so far that is only Perspective and
 266                     // Displacement, both of which override getTC() and return
 267                     // only 4 values.
 268                     srcRects.append("getTextureCoordinates(" + i + ", src" + i + "Rect,\n");
 269                     srcRects.append("                      src" + i + "InputBounds.x, src" + i + "InputBounds.y,\n");
 270                     srcRects.append("                      src" + i + "w, src" + i + "h,\n");
 271                     srcRects.append("                      dstBounds, src" + i + "Transform);\n");
 272 
 273                     jparams.append(",\n");
 274                     jparams.append(vname);
 275 
 276                     jparamDecls.append(",\n");
 277                     jparamDecls.append("int[] " + vname + "_arr");
 278 
 279                     cparamDecls.append(",\n");
 280                     cparamDecls.append("jintArray " + vname + "_arr");
 281 
 282                     appendGetRelease(arrayGet, arrayRelease, "int", vname, vname + "_arr");
 283                 }
 284 
 285                 posDecls.append("float inc" + i + "_x = (src" + i + "Rect_x2 - src" + i + "Rect_x1) / dstw;\n");
 286                 posDecls.append("float inc" + i + "_y = (src" + i + "Rect_y2 - src" + i + "Rect_y1) / dsth;\n");
 287 
 288                 posInitY.append("float pos" + i + "_y = src" + i + "Rect_y1 + inc" + i + "_y*0.5f;\n");
 289                 posInitX.append("float pos" + i + "_x = src" + i + "Rect_x1 + inc" + i + "_x*0.5f;\n");
 290                 posIncrX.append("pos" + i + "_x += inc" + i + "_x;\n");
 291                 posIncrY.append("pos" + i + "_y += inc" + i + "_y;\n");
 292 
 293                 jparams.append(",\n");
 294                 jparams.append("src" + i + "Rect[0], src" + i + "Rect[1],\n");
 295                 jparams.append("src" + i + "Rect[2], src" + i + "Rect[3],\n");
 296                 jparams.append("src" + i + "w, src" + i + "h, src" + i + "scan");
 297 
 298                 jparamDecls.append(",\n");
 299                 jparamDecls.append("float src" + i + "Rect_x1, float src" + i + "Rect_y1,\n");
 300                 jparamDecls.append("float src" + i + "Rect_x2, float src" + i + "Rect_y2,\n");
 301                 jparamDecls.append("int src" + i + "w, int src" + i + "h, int src" + i + "scan");
 302 
 303                 cparamDecls.append(",\n");
 304                 cparamDecls.append("jfloat src" + i + "Rect_x1, jfloat src" + i + "Rect_y1,\n");
 305                 cparamDecls.append("jfloat src" + i + "Rect_x2, jfloat src" + i + "Rect_y2,\n");
 306                 cparamDecls.append("jint src" + i + "w, jint src" + i + "h, jint src" + i + "scan");
 307             }
 308         }
 309 
 310         if (genericsName != null) {
 311             genericsDecl.append("<"+genericsName+">");
 312         }
 313 
 314         if (interfaceName != null) {
 315             interfaceDecl.append("implements "+interfaceName);
 316         }
 317 
 318         Reader template = new InputStreamReader(getClass().getResourceAsStream("SSEJavaGlue.stg"));
 319         StringTemplateGroup group = new StringTemplateGroup(template, DefaultTemplateLexer.class);
 320         StringTemplate jglue = group.getInstanceOf("glue");
 321         jglue.setAttribute("effectName", effectName);
 322         jglue.setAttribute("peerName", peerName);
 323         jglue.setAttribute("genericsDecl", genericsDecl.toString());
 324         jglue.setAttribute("interfaceDecl", interfaceDecl.toString());
 325         jglue.setAttribute("usercode", usercode.toString());
 326         jglue.setAttribute("samplers", samplers.toString());
 327         jglue.setAttribute("cleanup", cleanup.toString());
 328         jglue.setAttribute("srcRects", srcRects.toString());
 329         jglue.setAttribute("constants", constants.toString());
 330         jglue.setAttribute("params", jparams.toString());
 331         jglue.setAttribute("paramDecls", jparamDecls.toString());
 332 
 333         template = new InputStreamReader(getClass().getResourceAsStream("SSENativeGlue.stg"));
 334         group = new StringTemplateGroup(template, DefaultTemplateLexer.class);
 335         StringTemplate cglue = group.getInstanceOf("glue");
 336         cglue.setAttribute("peerName", peerName);
 337         cglue.setAttribute("jniName", peerName.replace("_", "_1"));
 338         cglue.setAttribute("paramDecls", cparamDecls.toString());
 339         cglue.setAttribute("arrayGet", arrayGet.toString());
 340         cglue.setAttribute("arrayRelease", arrayRelease.toString());
 341         cglue.setAttribute("posDecls", posDecls.toString());
 342         cglue.setAttribute("pixInitY", pixInitY.toString());
 343         cglue.setAttribute("pixInitX", pixInitX.toString());
 344         cglue.setAttribute("posIncrY", posIncrY.toString());
 345         cglue.setAttribute("posInitY", posInitY.toString());
 346         cglue.setAttribute("posIncrX", posIncrX.toString());
 347         cglue.setAttribute("posInitX", posInitX.toString());
 348         cglue.setAttribute("body", body);
 349 
 350         GenCode gen = new GenCode();
 351         gen.javaCode = jglue.toString();
 352         gen.nativeCode = cglue.toString();
 353         return gen;
 354     }
 355 
 356     // TODO: need better mechanism for querying fields
 357     private static char[] fields = {'x', 'y', 'z', 'w'};
 358     public static String getSuffix(int i) {
 359         return "_" + fields[i];
 360     }
 361 
 362     static int getFieldIndex(char field) {
 363         switch (field) {
 364         case 'r':
 365         case 'x':
 366             return 0;
 367         case 'g':
 368         case 'y':
 369             return 1;
 370         case 'b':
 371         case 'z':
 372             return 2;
 373         case 'a':
 374         case 'w':
 375             return 3;
 376         default:
 377             throw new InternalError();
 378         }
 379     }
 380 
 381     // TODO: these shouldn't be implemented as a static method
 382     private static Map<String, FuncDef> funcDefs = new HashMap<String, FuncDef>();
 383     static void putFuncDef(FuncDef def) {
 384         funcDefs.put(def.getFunction().getName(), def);
 385     }
 386     static FuncDef getFuncDef(String name) {
 387         return funcDefs.get(name);
 388     }
 389 
 390     private static Set<String> resultVars = new HashSet<String>();
 391     static boolean isResultVarDeclared(String vname) {
 392         return resultVars.contains(vname);
 393     }
 394     static void declareResultVar(String vname) {
 395         resultVars.add(vname);
 396     }
 397 
 398     private static StringBuilder usercode = new StringBuilder();
 399     static void addGlueBlock(String block) {
 400         usercode.append(block);
 401     }
 402 
 403     private static void resetStatics() {
 404         funcDefs.clear();
 405         resultVars.clear();
 406         usercode = new StringBuilder();
 407     }
 408 }