renderer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. "github.com/g3n/engine/camera"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/graphic"
  10. "github.com/g3n/engine/gui"
  11. "github.com/g3n/engine/light"
  12. "github.com/g3n/engine/math32"
  13. "sort"
  14. )
  15. // Renderer renders a 3D scene and/or a 2D GUI on the current window.
  16. type Renderer struct {
  17. gs *gls.GLS
  18. shaman Shaman // Internal shader manager
  19. stats Stats // Renderer statistics
  20. prevStats Stats // Renderer statistics for previous frame
  21. scene core.INode // Node containing 3D scene to render
  22. panelGui gui.IPanel // Panel containing GUI to render
  23. panel3D gui.IPanel // Panel which contains the 3D scene
  24. ambLights []*light.Ambient // Array of ambient lights for last scene
  25. dirLights []*light.Directional // Array of directional lights for last scene
  26. pointLights []*light.Point // Array of point
  27. spotLights []*light.Spot // Array of spot lights for the scene
  28. others []core.INode // Other nodes (audio, players, etc)
  29. rgraphics []*graphic.Graphic // Array of rendered graphics
  30. cgraphics []*graphic.Graphic // Array of rendered graphics
  31. grmatsOpaque []*graphic.GraphicMaterial // Array of rendered opaque graphic materials for scene
  32. grmatsTransp []*graphic.GraphicMaterial // Array of rendered transparent graphic materials for scene
  33. rinfo core.RenderInfo // Preallocated Render info
  34. specs ShaderSpecs // Preallocated Shader specs
  35. sortObjects bool // Flag indicating whether objects should be sorted before rendering
  36. redrawGui bool // Flag indicating the gui must be redrawn completely
  37. rendered bool // Flag indicating if anything was rendered
  38. panList []gui.IPanel // list of panels to render
  39. frameBuffers int // Number of frame buffers
  40. frameCount int // Current number of frame buffers to write
  41. }
  42. // Stats describes how many object types were rendered.
  43. // It is cleared at the start of each render.
  44. type Stats struct {
  45. Graphics int // Number of graphic objects rendered
  46. Lights int // Number of lights rendered
  47. Panels int // Number of Gui panels rendered
  48. Others int // Number of other objects rendered
  49. }
  50. // NewRenderer creates and returns a pointer to a new Renderer.
  51. func NewRenderer(gs *gls.GLS) *Renderer {
  52. r := new(Renderer)
  53. r.gs = gs
  54. r.shaman.Init(gs)
  55. r.ambLights = make([]*light.Ambient, 0)
  56. r.dirLights = make([]*light.Directional, 0)
  57. r.pointLights = make([]*light.Point, 0)
  58. r.spotLights = make([]*light.Spot, 0)
  59. r.others = make([]core.INode, 0)
  60. r.rgraphics = make([]*graphic.Graphic, 0)
  61. r.cgraphics = make([]*graphic.Graphic, 0)
  62. r.grmatsOpaque = make([]*graphic.GraphicMaterial, 0)
  63. r.grmatsTransp = make([]*graphic.GraphicMaterial, 0)
  64. r.panList = make([]gui.IPanel, 0)
  65. r.frameBuffers = 2
  66. r.sortObjects = true
  67. return r
  68. }
  69. // AddDefaultShaders adds to this renderer's shader manager all default
  70. // include chunks, shaders and programs statically registered.
  71. func (r *Renderer) AddDefaultShaders() error {
  72. return r.shaman.AddDefaultShaders()
  73. }
  74. // AddChunk adds a shader chunk with the specified name and source code.
  75. func (r *Renderer) AddChunk(name, source string) {
  76. r.shaman.AddChunk(name, source)
  77. }
  78. // AddShader adds a shader program with the specified name and source code.
  79. func (r *Renderer) AddShader(name, source string) {
  80. r.shaman.AddShader(name, source)
  81. }
  82. // AddProgram adds the program with the specified name,
  83. // with associated vertex and fragment shaders (previously registered).
  84. func (r *Renderer) AddProgram(name, vertex, frag string, others ...string) {
  85. r.shaman.AddProgram(name, vertex, frag, others...)
  86. }
  87. // SetGui sets the gui panel which contains the Gui to render.
  88. // If set to nil, no Gui will be rendered.
  89. func (r *Renderer) SetGui(gui gui.IPanel) {
  90. r.panelGui = gui
  91. }
  92. // SetGuiPanel3D sets the gui panel inside which the 3D scene is shown.
  93. // This informs the renderer that the Gui elements over this panel
  94. // must be redrawn even if they didn't change.
  95. // This panel panel must not be renderable, otherwise it will cover the 3D scene.
  96. func (r *Renderer) SetGuiPanel3D(panel3D gui.IPanel) {
  97. r.panel3D = panel3D
  98. }
  99. // Panel3D returns the current gui panel over the 3D scene.
  100. func (r *Renderer) Panel3D() gui.IPanel {
  101. return r.panel3D
  102. }
  103. // SetScene sets the 3D scene to be rendered.
  104. // If set to nil, no 3D scene will be rendered.
  105. func (r *Renderer) SetScene(scene core.INode) {
  106. r.scene = scene
  107. }
  108. // Stats returns a copy of the statistics for the last frame.
  109. // Should be called after the frame was rendered.
  110. func (r *Renderer) Stats() Stats {
  111. return r.stats
  112. }
  113. // SetObjectSorting sets whether objects will be sorted before rendering.
  114. func (r *Renderer) SetObjectSorting(sort bool) {
  115. r.sortObjects = sort
  116. }
  117. // ObjectSorting returns whether objects will be sorted before rendering.
  118. func (r *Renderer) ObjectSorting() bool {
  119. return r.sortObjects
  120. }
  121. // Render renders the previously set Scene and Gui using the specified camera.
  122. // Returns an indication if anything was rendered and an error.
  123. func (r *Renderer) Render(icam camera.ICamera) (bool, error) {
  124. r.redrawGui = false
  125. r.rendered = false
  126. r.stats = Stats{}
  127. // Renders the 3D scene
  128. if r.scene != nil {
  129. err := r.renderScene(r.scene, icam)
  130. if err != nil {
  131. return r.rendered, err
  132. }
  133. }
  134. // Renders the Gui over the 3D scene
  135. if r.panelGui != nil {
  136. err := r.renderGui()
  137. if err != nil {
  138. return r.rendered, err
  139. }
  140. }
  141. r.prevStats = r.stats
  142. return r.rendered, nil
  143. }
  144. // renderScene renders the 3D scene using the specified camera.
  145. func (r *Renderer) renderScene(iscene core.INode, icam camera.ICamera) error {
  146. // Updates world matrices of all scene nodes
  147. iscene.UpdateMatrixWorld()
  148. scene := iscene.GetNode()
  149. // Builds RenderInfo calls RenderSetup for all visible nodes
  150. icam.ViewMatrix(&r.rinfo.ViewMatrix)
  151. icam.ProjMatrix(&r.rinfo.ProjMatrix)
  152. // Clear scene arrays
  153. r.ambLights = r.ambLights[0:0]
  154. r.dirLights = r.dirLights[0:0]
  155. r.pointLights = r.pointLights[0:0]
  156. r.spotLights = r.spotLights[0:0]
  157. r.others = r.others[0:0]
  158. r.rgraphics = r.rgraphics[0:0]
  159. r.cgraphics = r.cgraphics[0:0]
  160. r.grmatsOpaque = r.grmatsOpaque[0:0]
  161. r.grmatsTransp = r.grmatsTransp[0:0]
  162. // Prepare for frustum culling
  163. var proj math32.Matrix4
  164. proj.MultiplyMatrices(&r.rinfo.ProjMatrix, &r.rinfo.ViewMatrix)
  165. frustum := math32.NewFrustumFromMatrix(&proj)
  166. // Internal function to classify a node and its children
  167. var classifyNode func(inode core.INode)
  168. classifyNode = func(inode core.INode) {
  169. // If node not visible, ignore
  170. node := inode.GetNode()
  171. if !node.Visible() {
  172. return
  173. }
  174. // Checks if node is a Graphic
  175. igr, ok := inode.(graphic.IGraphic)
  176. if ok {
  177. if igr.Renderable() {
  178. gr := igr.GetGraphic()
  179. // Frustum culling
  180. if igr.Cullable() {
  181. mw := gr.MatrixWorld()
  182. geom := igr.GetGeometry()
  183. bb := geom.BoundingBox()
  184. bb.ApplyMatrix4(&mw)
  185. if frustum.IntersectsBox(&bb) {
  186. // Append graphic to list of graphics to be rendered
  187. r.rgraphics = append(r.rgraphics, gr)
  188. } else {
  189. // Append graphic to list of culled graphics
  190. r.cgraphics = append(r.cgraphics, gr)
  191. }
  192. } else {
  193. // Append graphic to list of graphics to be rendered
  194. r.rgraphics = append(r.rgraphics, gr)
  195. }
  196. }
  197. // Node is not a Graphic
  198. } else {
  199. // Checks if node is a Light
  200. il, ok := inode.(light.ILight)
  201. if ok {
  202. switch l := il.(type) {
  203. case *light.Ambient:
  204. r.ambLights = append(r.ambLights, l)
  205. case *light.Directional:
  206. r.dirLights = append(r.dirLights, l)
  207. case *light.Point:
  208. r.pointLights = append(r.pointLights, l)
  209. case *light.Spot:
  210. r.spotLights = append(r.spotLights, l)
  211. default:
  212. panic("Invalid light type")
  213. }
  214. // Other nodes
  215. } else {
  216. r.others = append(r.others, inode)
  217. }
  218. }
  219. // Classify node children
  220. for _, ichild := range node.Children() {
  221. classifyNode(ichild)
  222. }
  223. }
  224. // Classify all scene nodes
  225. classifyNode(scene)
  226. //log.Debug("Rendered/Culled: %v/%v", len(r.grmats), len(r.cgrmats))
  227. // Sets lights count in shader specs
  228. r.specs.AmbientLightsMax = len(r.ambLights)
  229. r.specs.DirLightsMax = len(r.dirLights)
  230. r.specs.PointLightsMax = len(r.pointLights)
  231. r.specs.SpotLightsMax = len(r.spotLights)
  232. // Pre-calculate MV and MVP matrices and compile lists of opaque and transparent graphic materials
  233. for _, gr := range r.rgraphics {
  234. // Calculate MV and MVP matrices for all graphics to be rendered
  235. gr.CalculateMatrices(r.gs, &r.rinfo)
  236. // Append all graphic materials of this graphic to list of graphic materials to be rendered
  237. materials := gr.Materials()
  238. for i := 0; i < len(materials); i++ {
  239. if materials[i].GetMaterial().GetMaterial().Transparent() {
  240. r.grmatsTransp = append(r.grmatsTransp, &materials[i])
  241. } else {
  242. r.grmatsOpaque = append(r.grmatsOpaque, &materials[i])
  243. }
  244. }
  245. }
  246. // TODO: If both GraphicMaterials belong to same Graphic we might want to keep their relative order...
  247. // Z-sort graphic materials (opaque front-to-back and transparent back-to-front)
  248. if r.sortObjects {
  249. // Internal function to render a list of graphic materials
  250. var zSortGraphicMaterials func(grmats []*graphic.GraphicMaterial, backToFront bool)
  251. zSortGraphicMaterials = func(grmats []*graphic.GraphicMaterial, backToFront bool) {
  252. sort.Slice(grmats, func(i, j int) bool {
  253. gr1 := grmats[i].GetGraphic().GetGraphic()
  254. gr2 := grmats[j].GetGraphic().GetGraphic()
  255. // Check for user-supplied render order
  256. rO1 := gr1.RenderOrder()
  257. rO2 := gr2.RenderOrder()
  258. if rO1 != rO2 {
  259. return rO1 < rO2
  260. }
  261. mvm1 := gr1.ModelViewMatrix()
  262. mvm2 := gr2.ModelViewMatrix()
  263. g1pos := gr1.Position()
  264. g2pos := gr2.Position()
  265. g1pos.ApplyMatrix4(mvm1)
  266. g2pos.ApplyMatrix4(mvm2)
  267. if backToFront {
  268. return g1pos.Z < g2pos.Z
  269. }
  270. return g1pos.Z > g2pos.Z
  271. })
  272. }
  273. zSortGraphicMaterials(r.grmatsOpaque, false) // Sort opaque graphics front to back
  274. zSortGraphicMaterials(r.grmatsTransp, true) // Sort transparent graphics back to front
  275. }
  276. // Render other nodes (audio players, etc)
  277. for i := 0; i < len(r.others); i++ {
  278. inode := r.others[i]
  279. if !inode.GetNode().Visible() {
  280. continue
  281. }
  282. r.others[i].Render(r.gs)
  283. r.stats.Others++
  284. }
  285. // If there is graphic material to render or there was in the previous frame
  286. // it is necessary to clear the screen.
  287. if len(r.grmatsOpaque) > 0 || len(r.grmatsTransp) > 0 || r.prevStats.Graphics > 0 {
  288. // If the 3D scene to draw is to be confined to user specified panel
  289. // sets scissor to avoid erasing gui elements outside of this panel
  290. if r.panel3D != nil {
  291. pos := r.panel3D.GetPanel().Pospix()
  292. width, height := r.panel3D.GetPanel().Size()
  293. // Get scale of window (for HiDPI support)
  294. sX64, sY64 := r.panel3D.Root().Window().Scale()
  295. sX := float32(sX64)
  296. sY := float32(sY64)
  297. // Modify position and height of scissor according to window scale (for HiDPI support)
  298. width *= sX
  299. height *= sY
  300. pos.X *= sX
  301. pos.Y *= sY
  302. _, _, _, viewheight := r.gs.GetViewport()
  303. r.gs.Enable(gls.SCISSOR_TEST)
  304. r.gs.Scissor(int32(pos.X), viewheight-int32(pos.Y)-int32(height), uint32(width), uint32(height))
  305. } else {
  306. r.gs.Disable(gls.SCISSOR_TEST)
  307. r.redrawGui = true
  308. }
  309. // Clears the area inside the current scissor
  310. r.gs.Clear(gls.DEPTH_BUFFER_BIT | gls.STENCIL_BUFFER_BIT | gls.COLOR_BUFFER_BIT)
  311. r.rendered = true
  312. }
  313. err := error(nil)
  314. // Internal function to render a list of graphic materials
  315. var renderGraphicMaterials func(grmats []*graphic.GraphicMaterial)
  316. renderGraphicMaterials = func(grmats []*graphic.GraphicMaterial) {
  317. // For each *GraphicMaterial
  318. for _, grmat := range grmats {
  319. mat := grmat.GetMaterial().GetMaterial()
  320. geom := grmat.GetGraphic().GetGeometry()
  321. // Add defines from material and geometry
  322. r.specs.Defines = *gls.NewShaderDefines()
  323. r.specs.Defines.Add(&mat.ShaderDefines)
  324. r.specs.Defines.Add(&geom.ShaderDefines)
  325. // Sets the shader specs for this material and sets shader program
  326. r.specs.Name = mat.Shader()
  327. r.specs.ShaderUnique = mat.ShaderUnique()
  328. r.specs.UseLights = mat.UseLights()
  329. r.specs.MatTexturesMax = mat.TextureCount()
  330. // Set active program and apply shader specs
  331. _, err = r.shaman.SetProgram(&r.specs)
  332. if err != nil {
  333. return
  334. }
  335. // Setup lights (transfer lights' uniforms)
  336. for idx, l := range r.ambLights {
  337. l.RenderSetup(r.gs, &r.rinfo, idx)
  338. r.stats.Lights++
  339. }
  340. for idx, l := range r.dirLights {
  341. l.RenderSetup(r.gs, &r.rinfo, idx)
  342. r.stats.Lights++
  343. }
  344. for idx, l := range r.pointLights {
  345. l.RenderSetup(r.gs, &r.rinfo, idx)
  346. r.stats.Lights++
  347. }
  348. for idx, l := range r.spotLights {
  349. l.RenderSetup(r.gs, &r.rinfo, idx)
  350. r.stats.Lights++
  351. }
  352. // Render this graphic material
  353. grmat.Render(r.gs, &r.rinfo)
  354. r.stats.Graphics++
  355. }
  356. }
  357. renderGraphicMaterials(r.grmatsOpaque) // Render opaque objects (front to back)
  358. renderGraphicMaterials(r.grmatsTransp) // Render transparent objects (back to front)
  359. return err
  360. }
  361. // renderGui renders the Gui
  362. func (r *Renderer) renderGui() error {
  363. // If no 3D scene was rendered sets Gui panels as renderable for background
  364. // User must define the colors
  365. if (len(r.rgraphics) == 0) && (len(r.cgraphics) == 0) {
  366. r.panelGui.SetRenderable(true)
  367. if r.panel3D != nil {
  368. r.panel3D.SetRenderable(true)
  369. }
  370. } else {
  371. r.panelGui.SetRenderable(false)
  372. if r.panel3D != nil {
  373. r.panel3D.SetRenderable(false)
  374. }
  375. }
  376. // Clears list of panels to render
  377. r.panList = r.panList[0:0]
  378. // Redraw all GUI elements elements (panel3D == nil and 3D scene drawn)
  379. if r.redrawGui {
  380. r.appendPanel(r.panelGui)
  381. // Redraw GUI elements only if changed
  382. // Set the number of frame buffers to draw these changes
  383. } else if r.checkChanged(r.panelGui) {
  384. r.appendPanel(r.panelGui)
  385. r.frameCount = r.frameBuffers
  386. // No change, but need to update frame buffers
  387. } else if r.frameCount > 0 {
  388. r.appendPanel(r.panelGui)
  389. // No change, draw only panels over 3D if any
  390. } else {
  391. r.getPanelsOver3D()
  392. }
  393. if len(r.panList) == 0 {
  394. return nil
  395. }
  396. // Updates panels bounds and relative positions
  397. r.panelGui.GetPanel().UpdateMatrixWorld()
  398. // Disable the scissor test which could have been set by the 3D scene renderer
  399. // and then clear the depth buffer, so the panels will be rendered over the 3D scene.
  400. r.gs.Disable(gls.SCISSOR_TEST)
  401. r.gs.Clear(gls.DEPTH_BUFFER_BIT)
  402. // Render panels
  403. for i := 0; i < len(r.panList); i++ {
  404. err := r.renderPanel(r.panList[i])
  405. if err != nil {
  406. return err
  407. }
  408. }
  409. r.frameCount--
  410. r.rendered = true
  411. return nil
  412. }
  413. // getPanelsOver3D builds list of panels over 3D to be rendered
  414. func (r *Renderer) getPanelsOver3D() {
  415. // If panel3D not set or renderable, nothing to do
  416. if r.panel3D == nil || r.panel3D.Renderable() {
  417. return
  418. }
  419. // Internal recursive function to check if any child of the
  420. // specified panel is unbounded and over 3D.
  421. // If it is, it is inserted in the list of panels to render.
  422. var checkUnbounded func(pan *gui.Panel)
  423. checkUnbounded = func(pan *gui.Panel) {
  424. for i := 0; i < len(pan.Children()); i++ {
  425. child := pan.Children()[i].(gui.IPanel).GetPanel()
  426. if !child.Bounded() && r.checkPanelOver3D(child) {
  427. r.appendPanel(child)
  428. continue
  429. }
  430. checkUnbounded(child)
  431. }
  432. }
  433. // For all children of the Gui, checks if it is over the 3D panel
  434. children := r.panelGui.GetPanel().Children()
  435. for i := 0; i < len(children); i++ {
  436. pan := children[i].(gui.IPanel).GetPanel()
  437. if !pan.Visible() {
  438. continue
  439. }
  440. if r.checkPanelOver3D(pan) {
  441. r.appendPanel(pan)
  442. continue
  443. }
  444. // Current child is not over 3D but can have an unbounded child which is
  445. checkUnbounded(pan)
  446. }
  447. }
  448. // renderPanel renders the specified panel and all its children
  449. // and then sets the panel as not changed.
  450. func (r *Renderer) renderPanel(ipan gui.IPanel) error {
  451. // If panel not visible, ignore it and all its children
  452. pan := ipan.GetPanel()
  453. if !pan.Visible() {
  454. pan.SetChanged(false)
  455. return nil
  456. }
  457. // If panel is renderable, renders it
  458. if pan.Renderable() {
  459. // Sets shader program for the panel's material
  460. grmat := pan.GetGraphic().Materials()[0]
  461. mat := grmat.GetMaterial().GetMaterial()
  462. r.specs.Name = mat.Shader()
  463. r.specs.ShaderUnique = mat.ShaderUnique()
  464. _, err := r.shaman.SetProgram(&r.specs)
  465. if err != nil {
  466. return err
  467. }
  468. // Render this panel's graphic material
  469. grmat.Render(r.gs, &r.rinfo)
  470. r.stats.Panels++
  471. }
  472. pan.SetChanged(false)
  473. // Renders this panel children
  474. for i := 0; i < len(pan.Children()); i++ {
  475. err := r.renderPanel(pan.Children()[i].(gui.IPanel))
  476. if err != nil {
  477. return err
  478. }
  479. }
  480. return nil
  481. }
  482. // appendPanel appends the specified panel to the list of panels to render.
  483. // Currently there is no need to check for duplicates.
  484. func (r *Renderer) appendPanel(ipan gui.IPanel) {
  485. r.panList = append(r.panList, ipan)
  486. }
  487. // checkChanged checks if the specified panel or any of its children is changed
  488. func (r *Renderer) checkChanged(ipan gui.IPanel) bool {
  489. // Unbounded panels are checked even if not visible
  490. pan := ipan.GetPanel()
  491. if !pan.Bounded() && pan.Changed() {
  492. pan.SetChanged(false)
  493. return true
  494. }
  495. // Ignore invisible panel and its children
  496. if !pan.Visible() {
  497. return false
  498. }
  499. if pan.Changed() && pan.Renderable() {
  500. return true
  501. }
  502. for i := 0; i < len(pan.Children()); i++ {
  503. res := r.checkChanged(pan.Children()[i].(gui.IPanel))
  504. if res {
  505. return res
  506. }
  507. }
  508. return false
  509. }
  510. // checkPanelOver3D checks if the specified panel is over
  511. // the area where the 3D scene will be rendered.
  512. func (r *Renderer) checkPanelOver3D(ipan gui.IPanel) bool {
  513. pan := ipan.GetPanel()
  514. if !pan.Visible() {
  515. return false
  516. }
  517. if r.panel3D.GetPanel().Intersects(pan) {
  518. return true
  519. }
  520. return false
  521. }