shaman.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package renderer
  5. import (
  6. "fmt"
  7. "regexp"
  8. "strings"
  9. "strconv"
  10. "github.com/g3n/engine/gls"
  11. "github.com/g3n/engine/material"
  12. "github.com/g3n/engine/renderer/shaders"
  13. )
  14. // Regular expression to parse #include <name> [quantity] directive
  15. var rexInclude *regexp.Regexp
  16. const indexParameter = "{i}"
  17. func init() {
  18. rexInclude = regexp.MustCompile(`#include\s+<(.*)>\s*(?:\[(.*)]|)`)
  19. }
  20. // ShaderSpecs describes the specification of a compiled shader program
  21. type ShaderSpecs struct {
  22. Name string // Shader name
  23. Version string // GLSL version
  24. ShaderUnique bool // indicates if shader is independent of lights and textures
  25. UseLights material.UseLights // Bitmask indicating which lights to consider
  26. AmbientLightsMax int // Current number of ambient lights
  27. DirLightsMax int // Current Number of directional lights
  28. PointLightsMax int // Current Number of point lights
  29. SpotLightsMax int // Current Number of spot lights
  30. MatTexturesMax int // Current Number of material textures
  31. Defines gls.ShaderDefines // Additional shader defines
  32. }
  33. // ProgSpecs represents a compiled shader program along with its specs
  34. type ProgSpecs struct {
  35. program *gls.Program // program object
  36. specs ShaderSpecs // associated specs
  37. }
  38. // Shaman is the shader manager
  39. type Shaman struct {
  40. gs *gls.GLS // Reference to OpenGL state
  41. includes map[string]string // include files sources
  42. shadersm map[string]string // maps shader name to its template
  43. proginfo map[string]shaders.ProgramInfo // maps name of the program to ProgramInfo
  44. programs []ProgSpecs // list of compiled programs with specs
  45. specs ShaderSpecs // Current shader specs
  46. }
  47. // NewShaman creates and returns a pointer to a new shader manager
  48. func NewShaman(gs *gls.GLS) *Shaman {
  49. sm := new(Shaman)
  50. sm.Init(gs)
  51. return sm
  52. }
  53. // Init initializes the shader manager
  54. func (sm *Shaman) Init(gs *gls.GLS) {
  55. sm.gs = gs
  56. sm.includes = make(map[string]string)
  57. sm.shadersm = make(map[string]string)
  58. sm.proginfo = make(map[string]shaders.ProgramInfo)
  59. }
  60. // AddDefaultShaders adds to this shader manager all default
  61. // include chunks, shaders and programs statically registered.
  62. func (sm *Shaman) AddDefaultShaders() error {
  63. for _, name := range shaders.Includes() {
  64. sm.AddChunk(name, shaders.IncludeSource(name))
  65. }
  66. for _, name := range shaders.Shaders() {
  67. sm.AddShader(name, shaders.ShaderSource(name))
  68. }
  69. for _, name := range shaders.Programs() {
  70. sm.proginfo[name] = shaders.GetProgramInfo(name)
  71. }
  72. return nil
  73. }
  74. // AddChunk adds a shader chunk with the specified name and source code
  75. func (sm *Shaman) AddChunk(name, source string) {
  76. sm.includes[name] = source
  77. }
  78. // AddShader adds a shader program with the specified name and source code
  79. func (sm *Shaman) AddShader(name, source string) {
  80. sm.shadersm[name] = source
  81. }
  82. // AddProgram adds a program with the specified name and associated vertex
  83. // and fragment shaders names (previously registered)
  84. func (sm *Shaman) AddProgram(name, vertexName, fragName string, others ...string) {
  85. geomName := ""
  86. if len(others) > 0 {
  87. geomName = others[0]
  88. }
  89. sm.proginfo[name] = shaders.ProgramInfo{
  90. Vertex: vertexName,
  91. Fragment: fragName,
  92. Geometry: geomName,
  93. }
  94. }
  95. // SetProgram sets the shader program to satisfy the specified specs.
  96. // Returns an indication if the current shader has changed and a possible error
  97. // when creating a new shader program.
  98. // Receives a copy of the specs because it changes the fields which specify the
  99. // number of lights depending on the UseLights flags.
  100. func (sm *Shaman) SetProgram(s *ShaderSpecs) (bool, error) {
  101. // Checks material use lights bit mask
  102. var specs ShaderSpecs
  103. specs.copy(s)
  104. if (specs.UseLights & material.UseLightAmbient) == 0 {
  105. specs.AmbientLightsMax = 0
  106. }
  107. if (specs.UseLights & material.UseLightDirectional) == 0 {
  108. specs.DirLightsMax = 0
  109. }
  110. if (specs.UseLights & material.UseLightPoint) == 0 {
  111. specs.PointLightsMax = 0
  112. }
  113. if (specs.UseLights & material.UseLightSpot) == 0 {
  114. specs.SpotLightsMax = 0
  115. }
  116. // If current shader specs are the same as the specified specs, nothing to do.
  117. if sm.specs.equals(&specs) {
  118. return false, nil
  119. }
  120. // Search for compiled program with the specified specs
  121. for _, pinfo := range sm.programs {
  122. if pinfo.specs.equals(&specs) {
  123. sm.gs.UseProgram(pinfo.program)
  124. sm.specs = specs
  125. return true, nil
  126. }
  127. }
  128. // Generates new program with the specified specs
  129. prog, err := sm.GenProgram(&specs)
  130. if err != nil {
  131. return false, err
  132. }
  133. log.Debug("Created new shader:%v", specs.Name)
  134. // Save specs as current specs, adds new program to the list and activates the program
  135. sm.specs = specs
  136. sm.programs = append(sm.programs, ProgSpecs{prog, specs})
  137. sm.gs.UseProgram(prog)
  138. return true, nil
  139. }
  140. // GenProgram generates shader program from the specified specs
  141. func (sm *Shaman) GenProgram(specs *ShaderSpecs) (*gls.Program, error) {
  142. // Get info for the specified shader program
  143. progInfo, ok := sm.proginfo[specs.Name]
  144. if !ok {
  145. return nil, fmt.Errorf("Program:%s not found", specs.Name)
  146. }
  147. // Sets the defines map
  148. defines := map[string]string{}
  149. defines["AMB_LIGHTS"] = strconv.Itoa(specs.AmbientLightsMax)
  150. defines["DIR_LIGHTS"] = strconv.Itoa(specs.DirLightsMax)
  151. defines["POINT_LIGHTS"] = strconv.Itoa(specs.PointLightsMax)
  152. defines["SPOT_LIGHTS"] = strconv.Itoa(specs.SpotLightsMax)
  153. defines["MAT_TEXTURES"] = strconv.Itoa(specs.MatTexturesMax)
  154. // Adds additional material and geometry defines from the specs parameter
  155. for name, value := range specs.Defines {
  156. defines[name] = value
  157. }
  158. // Get vertex shader source
  159. vertexSource, ok := sm.shadersm[progInfo.Vertex]
  160. if !ok {
  161. return nil, fmt.Errorf("Vertex shader:%s not found", progInfo.Vertex)
  162. }
  163. // Pre-process vertex shader source
  164. vertexSource, err := sm.preprocess(vertexSource, defines)
  165. if err != nil {
  166. return nil, err
  167. }
  168. //fmt.Printf("vertexSource:%s\n", vertexSource)
  169. // Get fragment shader source
  170. fragSource, ok := sm.shadersm[progInfo.Fragment]
  171. if err != nil {
  172. return nil, fmt.Errorf("Fragment shader:%s not found", progInfo.Fragment)
  173. }
  174. // Pre-process fragment shader source
  175. fragSource, err = sm.preprocess(fragSource, defines)
  176. if err != nil {
  177. return nil, err
  178. }
  179. //fmt.Printf("fragSource:%s\n", fragSource)
  180. // Checks for optional geometry shader compiled template
  181. var geomSource = ""
  182. if progInfo.Geometry != "" {
  183. // Get geometry shader source
  184. geomSource, ok = sm.shadersm[progInfo.Geometry]
  185. if !ok {
  186. return nil, fmt.Errorf("Geometry shader:%s not found", progInfo.Geometry)
  187. }
  188. // Pre-process geometry shader source
  189. geomSource, err = sm.preprocess(geomSource, defines)
  190. if err != nil {
  191. return nil, err
  192. }
  193. }
  194. // Creates shader program
  195. prog := sm.gs.NewProgram()
  196. prog.AddShader(gls.VERTEX_SHADER, vertexSource)
  197. prog.AddShader(gls.FRAGMENT_SHADER, fragSource)
  198. if progInfo.Geometry != "" {
  199. prog.AddShader(gls.GEOMETRY_SHADER, geomSource)
  200. }
  201. err = prog.Build()
  202. if err != nil {
  203. return nil, err
  204. }
  205. return prog, nil
  206. }
  207. func (sm *Shaman) preprocess(source string, defines map[string]string) (string, error) {
  208. // If defines map supplied, generate prefix with glsl version directive first,
  209. // followed by "#define" directives
  210. var prefix = ""
  211. if defines != nil { // This is only true for the outer call
  212. prefix = fmt.Sprintf("#version %s\n", GLSL_VERSION)
  213. for name, value := range defines {
  214. prefix = prefix + fmt.Sprintf("#define %s %s\n", name, value)
  215. }
  216. }
  217. return sm.processIncludes(prefix+source, defines)
  218. }
  219. // preprocess preprocesses the specified source prefixing it with optional defines directives
  220. // contained in "defines" parameter and replaces '#include <name>' directives
  221. // by the respective source code of include chunk of the specified name.
  222. // The included "files" are also processed recursively.
  223. func (sm *Shaman) processIncludes(source string, defines map[string]string) (string, error) {
  224. // Find all string submatches for the "#include <name>" directive
  225. matches := rexInclude.FindAllStringSubmatch(source, 100)
  226. if len(matches) == 0 {
  227. return source, nil
  228. }
  229. // For each directive found, replace the name by the respective include chunk source code
  230. //var newSource = source
  231. for _, m := range matches {
  232. incFullMatch := m[0]
  233. incName := m[1]
  234. incQuantityVariable := m[2]
  235. // Get the source of the include chunk with the match <name>
  236. incSource := sm.includes[incName]
  237. if len(incSource) == 0 {
  238. return "", fmt.Errorf("Include:[%s] not found", incName)
  239. }
  240. // Preprocess the include chunk source code
  241. incSource, err := sm.processIncludes(incSource, defines)
  242. if err != nil {
  243. return "", err
  244. }
  245. // Skip line
  246. incSource = "\n" + incSource
  247. // Process include quantity variable if provided
  248. if incQuantityVariable != "" {
  249. incQuantityString, defined := defines[incQuantityVariable]
  250. if defined { // Only process #include if quantity variable is defined
  251. incQuantity, err := strconv.Atoi(incQuantityString)
  252. if err != nil {
  253. return "", err
  254. }
  255. // Check for iterated includes and populate index parameter
  256. if incQuantity > 0 {
  257. repeatedIncludeSource := ""
  258. for i := 0; i < incQuantity; i++ {
  259. // Replace all occurrences of the index parameter with the current index i.
  260. repeatedIncludeSource += strings.Replace(incSource, indexParameter, strconv.Itoa(i), -1)
  261. }
  262. incSource = repeatedIncludeSource
  263. }
  264. } else {
  265. incSource = ""
  266. }
  267. }
  268. // Replace all occurrences of the include directive with its processed source code
  269. source = strings.Replace(source, incFullMatch, incSource, -1)
  270. }
  271. return source, nil
  272. }
  273. // copy copies other spec into this
  274. func (ss *ShaderSpecs) copy(other *ShaderSpecs) {
  275. *ss = *other
  276. if other.Defines != nil {
  277. ss.Defines = *gls.NewShaderDefines()
  278. ss.Defines.Add(&other.Defines)
  279. }
  280. }
  281. // equals compares two ShaderSpecs and returns true if they are effectively equal.
  282. func (ss *ShaderSpecs) equals(other *ShaderSpecs) bool {
  283. if ss.Name != other.Name {
  284. return false
  285. }
  286. if other.ShaderUnique {
  287. return true
  288. }
  289. if ss.AmbientLightsMax == other.AmbientLightsMax &&
  290. ss.DirLightsMax == other.DirLightsMax &&
  291. ss.PointLightsMax == other.PointLightsMax &&
  292. ss.SpotLightsMax == other.SpotLightsMax &&
  293. ss.MatTexturesMax == other.MatTexturesMax &&
  294. ss.Defines.Equals(&other.Defines) {
  295. return true
  296. }
  297. return false
  298. }