processing4 icon indicating copy to clipboard operation
processing4 copied to clipboard

Support for #include in PShader (Enhancement)

Open processing-bot opened this issue 3 years ago • 3 comments

Created by: patriciogonzalezvivo

Although #include routines are defined by Khronos as an extension they are left for the environment/framework running the GL driver to implement. The reason for that is the required access to file system. Implementing #include routines are fairly straight forward with a couple of gotchas to avoid, like: relative paths and infinite recursions. Most serious CG engines support them because their advantages on modularity, reusability and clearer code. For Processing this also could mean support for LYGIA a rich shader library pack with useful resources for creative coders and artist. I made a simple implementations of a #include parser in this repository together with some examples on how it can be use.

void loadSource(String current_folder, String filename, ArrayList<String> source) {
  println("search for", filename, "in", current_folder);
  File file = new File(current_folder,filename);
  String url = file.getPath().substring(1);
  println("open", url);
  String[] lines = loadStrings(url); 
  
  for (int i = 0; i < lines.length; i++) {
    String line = lines[i];
    String line_trim = line.trim();
    if (line_trim.startsWith("#include")){
      String include_file = line_trim.substring("#include".length()).replace("\"", "").trim();
      File f = new File(current_folder,include_file);
      loadSource(f.getParent(), f.getName(), source);
    } else {
      source.add(line + System.getProperty("line.separator") );
    }
  }
}

Adding this feature to createShader() to parse both vert and frag shaders shouldn't be hard and potentially bring numerous advantages.

cc @codeanticode @SableRaf @cacheflowe

processing-bot avatar Oct 07 '22 14:10 processing-bot

It would be good to store the separator instead of calling System.getProperty("line.separator") a lot of times. Also, I think when something like this gets implemented that it should be a bit smarter, and keep track of the original line numbers and source file for a line. That way if there is a compile error for the shader, then the offending line can be reported.

clankill3r avatar Oct 08 '22 11:10 clankill3r

Agree, a map of included lines would be ideal.

patriciogonzalezvivo avatar Oct 10 '22 15:10 patriciogonzalezvivo

@patriciogonzalezvivo thanks so much for suggesting this enhancement, let me look into it a bit closer and I will get back to you with more insightful comments as soon as I can :-)

codeanticode avatar Oct 11 '22 12:10 codeanticode