DisjointRectSet.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibGfx/DisjointRectSet.h>
  27. namespace Gfx {
  28. void DisjointRectSet::add(const Rect& new_rect)
  29. {
  30. for (auto& rect : m_rects) {
  31. if (rect.contains(new_rect))
  32. return;
  33. }
  34. m_rects.append(new_rect);
  35. if (m_rects.size() > 1)
  36. shatter();
  37. }
  38. void DisjointRectSet::shatter()
  39. {
  40. Vector<Rect, 32> output;
  41. output.ensure_capacity(m_rects.size());
  42. bool pass_had_intersections = false;
  43. do {
  44. pass_had_intersections = false;
  45. output.clear_with_capacity();
  46. for (size_t i = 0; i < m_rects.size(); ++i) {
  47. auto& r1 = m_rects[i];
  48. for (size_t j = 0; j < m_rects.size(); ++j) {
  49. if (i == j)
  50. continue;
  51. auto& r2 = m_rects[j];
  52. if (!r1.intersects(r2))
  53. continue;
  54. pass_had_intersections = true;
  55. auto pieces = r1.shatter(r2);
  56. for (auto& piece : pieces)
  57. output.append(piece);
  58. m_rects.remove(i);
  59. for (; i < m_rects.size(); ++i)
  60. output.append(m_rects[i]);
  61. goto next_pass;
  62. }
  63. output.append(r1);
  64. }
  65. next_pass:
  66. swap(output, m_rects);
  67. } while (pass_had_intersections);
  68. }
  69. }