renderer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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].IMaterial().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].IGraphic().GetGraphic()
  254. gr2 := grmats[j].IGraphic().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.IMaterial().GetMaterial()
  320. geom := grmat.IGraphic().GetGeometry()
  321. gr := grmat.IGraphic().GetGraphic()
  322. // Add defines from material and geometry
  323. r.specs.Defines = *gls.NewShaderDefines()
  324. r.specs.Defines.Add(&mat.ShaderDefines)
  325. r.specs.Defines.Add(&geom.ShaderDefines)
  326. r.specs.Defines.Add(&gr.ShaderDefines)
  327. // Sets the shader specs for this material and sets shader program
  328. r.specs.Name = mat.Shader()
  329. r.specs.ShaderUnique = mat.ShaderUnique()
  330. r.specs.UseLights = mat.UseLights()
  331. r.specs.MatTexturesMax = mat.TextureCount()
  332. // Set active program and apply shader specs
  333. _, err = r.shaman.SetProgram(&r.specs)
  334. if err != nil {
  335. return
  336. }
  337. // Setup lights (transfer lights' uniforms)
  338. for idx, l := range r.ambLights {
  339. l.RenderSetup(r.gs, &r.rinfo, idx)
  340. r.stats.Lights++
  341. }
  342. for idx, l := range r.dirLights {
  343. l.RenderSetup(r.gs, &r.rinfo, idx)
  344. r.stats.Lights++
  345. }
  346. for idx, l := range r.pointLights {
  347. l.RenderSetup(r.gs, &r.rinfo, idx)
  348. r.stats.Lights++
  349. }
  350. for idx, l := range r.spotLights {
  351. l.RenderSetup(r.gs, &r.rinfo, idx)
  352. r.stats.Lights++
  353. }
  354. // Render this graphic material
  355. grmat.Render(r.gs, &r.rinfo)
  356. r.stats.Graphics++
  357. }
  358. }
  359. renderGraphicMaterials(r.grmatsOpaque) // Render opaque objects (front to back)
  360. if err != nil {
  361. return err
  362. }
  363. renderGraphicMaterials(r.grmatsTransp) // Render transparent objects (back to front)
  364. return err
  365. }
  366. // renderGui renders the Gui
  367. func (r *Renderer) renderGui() error {
  368. // If no 3D scene was rendered sets Gui panels as renderable for background
  369. // User must define the colors
  370. if (len(r.rgraphics) == 0) && (len(r.cgraphics) == 0) {
  371. r.panelGui.SetRenderable(true)
  372. if r.panel3D != nil {
  373. r.panel3D.SetRenderable(true)
  374. }
  375. } else {
  376. r.panelGui.SetRenderable(false)
  377. if r.panel3D != nil {
  378. r.panel3D.SetRenderable(false)
  379. }
  380. }
  381. // Clears list of panels to render
  382. r.panList = r.panList[0:0]
  383. // Redraw all GUI elements elements (panel3D == nil and 3D scene drawn)
  384. if r.redrawGui {
  385. r.appendPanel(r.panelGui)
  386. // Redraw GUI elements only if changed
  387. // Set the number of frame buffers to draw these changes
  388. } else if r.checkChanged(r.panelGui) {
  389. r.appendPanel(r.panelGui)
  390. r.frameCount = r.frameBuffers
  391. // No change, but need to update frame buffers
  392. } else if r.frameCount > 0 {
  393. r.appendPanel(r.panelGui)
  394. // No change, draw only panels over 3D if any
  395. } else {
  396. r.getPanelsOver3D()
  397. }
  398. if len(r.panList) == 0 {
  399. return nil
  400. }
  401. // Updates panels bounds and relative positions
  402. r.panelGui.GetPanel().UpdateMatrixWorld()
  403. // Disable the scissor test which could have been set by the 3D scene renderer
  404. // and then clear the depth buffer, so the panels will be rendered over the 3D scene.
  405. r.gs.Disable(gls.SCISSOR_TEST)
  406. r.gs.Clear(gls.DEPTH_BUFFER_BIT)
  407. // Render panels
  408. for i := 0; i < len(r.panList); i++ {
  409. err := r.renderPanel(r.panList[i])
  410. if err != nil {
  411. return err
  412. }
  413. }
  414. r.frameCount--
  415. r.rendered = true
  416. return nil
  417. }
  418. // getPanelsOver3D builds list of panels over 3D to be rendered
  419. func (r *Renderer) getPanelsOver3D() {
  420. // If panel3D not set or renderable, nothing to do
  421. if r.panel3D == nil || r.panel3D.Renderable() {
  422. return
  423. }
  424. // Internal recursive function to check if any child of the
  425. // specified panel is unbounded and over 3D.
  426. // If it is, it is inserted in the list of panels to render.
  427. var checkUnbounded func(pan *gui.Panel)
  428. checkUnbounded = func(pan *gui.Panel) {
  429. for i := 0; i < len(pan.Children()); i++ {
  430. child := pan.Children()[i].(gui.IPanel).GetPanel()
  431. if !child.Bounded() && r.checkPanelOver3D(child) {
  432. r.appendPanel(child)
  433. continue
  434. }
  435. checkUnbounded(child)
  436. }
  437. }
  438. // For all children of the Gui, checks if it is over the 3D panel
  439. children := r.panelGui.GetPanel().Children()
  440. for i := 0; i < len(children); i++ {
  441. pan := children[i].(gui.IPanel).GetPanel()
  442. if !pan.Visible() {
  443. continue
  444. }
  445. if r.checkPanelOver3D(pan) {
  446. r.appendPanel(pan)
  447. continue
  448. }
  449. // Current child is not over 3D but can have an unbounded child which is
  450. checkUnbounded(pan)
  451. }
  452. }
  453. // renderPanel renders the specified panel and all its children
  454. // and then sets the panel as not changed.
  455. func (r *Renderer) renderPanel(ipan gui.IPanel) error {
  456. // If panel not visible, ignore it and all its children
  457. pan := ipan.GetPanel()
  458. if !pan.Visible() {
  459. pan.SetChanged(false)
  460. return nil
  461. }
  462. // If panel is renderable, renders it
  463. if pan.Renderable() {
  464. // Sets shader program for the panel's material
  465. grmat := pan.GetGraphic().Materials()[0]
  466. mat := grmat.IMaterial().GetMaterial()
  467. r.specs.Name = mat.Shader()
  468. r.specs.ShaderUnique = mat.ShaderUnique()
  469. _, err := r.shaman.SetProgram(&r.specs)
  470. if err != nil {
  471. return err
  472. }
  473. // Render this panel's graphic material
  474. grmat.Render(r.gs, &r.rinfo)
  475. r.stats.Panels++
  476. }
  477. pan.SetChanged(false)
  478. // Renders this panel children
  479. for i := 0; i < len(pan.Children()); i++ {
  480. err := r.renderPanel(pan.Children()[i].(gui.IPanel))
  481. if err != nil {
  482. return err
  483. }
  484. }
  485. return nil
  486. }
  487. // appendPanel appends the specified panel to the list of panels to render.
  488. // Currently there is no need to check for duplicates.
  489. func (r *Renderer) appendPanel(ipan gui.IPanel) {
  490. r.panList = append(r.panList, ipan)
  491. }
  492. // checkChanged checks if the specified panel or any of its children is changed
  493. func (r *Renderer) checkChanged(ipan gui.IPanel) bool {
  494. // Unbounded panels are checked even if not visible
  495. pan := ipan.GetPanel()
  496. if !pan.Bounded() && pan.Changed() {
  497. pan.SetChanged(false)
  498. return true
  499. }
  500. // Ignore invisible panel and its children
  501. if !pan.Visible() {
  502. return false
  503. }
  504. if pan.Changed() && pan.Renderable() {
  505. return true
  506. }
  507. for i := 0; i < len(pan.Children()); i++ {
  508. res := r.checkChanged(pan.Children()[i].(gui.IPanel))
  509. if res {
  510. return res
  511. }
  512. }
  513. return false
  514. }
  515. // checkPanelOver3D checks if the specified panel is over
  516. // the area where the 3D scene will be rendered.
  517. func (r *Renderer) checkPanelOver3D(ipan gui.IPanel) bool {
  518. pan := ipan.GetPanel()
  519. if !pan.Visible() {
  520. return false
  521. }
  522. if r.panel3D.GetPanel().Intersects(pan) {
  523. return true
  524. }
  525. return false
  526. }