main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2022 The Ebitengine Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "image"
  18. "image/color"
  19. "log"
  20. "github.com/hajimehoshi/ebiten/v2"
  21. "github.com/hajimehoshi/ebiten/v2/ebitenutil"
  22. )
  23. const (
  24. cx = 32
  25. cy = 32
  26. )
  27. type Game struct {
  28. offscreen *ebiten.Image
  29. subImages [cx][cy]*ebiten.Image
  30. }
  31. func (g *Game) Update() error {
  32. return nil
  33. }
  34. func (g *Game) Draw(screen *ebiten.Image) {
  35. if g.offscreen == nil {
  36. s := screen.Bounds().Size()
  37. g.offscreen = ebiten.NewImage(s.X, s.Y)
  38. }
  39. // Use various sub-images as rendering destination.
  40. // This is a proof-of-concept of efficient rendering with sub-images (#2232).
  41. sw, sh := screen.Bounds().Dx(), screen.Bounds().Dy()
  42. cw := sw / cx
  43. ch := sh / cy
  44. for j := 0; j < cy; j++ {
  45. for i := 0; i < cx; i++ {
  46. img := g.subImages[i][j]
  47. if img == nil {
  48. r := image.Rect(cw*i, ch*j, cw*(i+1), ch*(j+1))
  49. img = g.offscreen.SubImage(r).(*ebiten.Image)
  50. g.subImages[i][j] = img
  51. }
  52. // Rendering onto a sub image should be efficient,
  53. // but this is not efficient some environments like browsers (#2471).
  54. clr := color.RGBA{byte(0xff * float64(i) / cx), byte(0xff * float64(j) / cx), 0, 0xff}
  55. img.Fill(clr)
  56. }
  57. }
  58. screen.DrawImage(g.offscreen, nil)
  59. ebitenutil.DebugPrint(screen, fmt.Sprintf("FPS: %0.2f, TPS: %0.2f", ebiten.ActualFPS(), ebiten.ActualTPS()))
  60. }
  61. func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
  62. return 640, 480
  63. }
  64. func main() {
  65. ebiten.SetWindowTitle("Sub-images as rendering destinations (Ebitengine Demo)")
  66. if err := ebiten.RunGame(&Game{}); err != nil {
  67. log.Fatal(err)
  68. }
  69. }