summaryrefslogtreecommitdiff
path: root/public/assets/javascripts/rectangles/engine/scenery/randomize.js
blob: 4f1144a35f885b5ef39b2108b479c78c0c5c9598 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
  // get the list of media we want to place
  var media_data = $(".mediaContainer").toArray().map(function(el){
    return $(el).data("media")
  })
  Scenery.randomize( media_data )
*/

Scenery.randomize = function (media_data) {
  var media_list = media_data.map(function(media){
    var width, height
    if (media.width > media.height) {
      width = Math.min(300, media.width)
      height = media.height/media.width * width
    }
    else {
      height = Math.min(300, media.height)
      width = media.width/media.height * height
    }
    return {
      dimensions: new vec2( width, height ),
      media: media,
    }
  })

  // get a list of all walls
  var walls = {}
  Walls.forEach(function(wall){
    walls[wall.id] = wall
  })

  // remove the walls that already have stuff on them
  Scenery.forEach(function(scenery){
    delete walls[scenery.wall.id] 
  })

  var wall_ids = _.keys(walls)
  if (! wall_ids.length) {
    return
  }

  // randomize walls
  shuffle(wall_ids)

  // assign each of the media to the walls, until we run out of either
  media_list.some(function(media){
    if (wall_ids.length == 0) {
      return true
    }
  
    var i, fits = -1

    for (i = 0; i < wall_ids.length; i++) {
      if (walls[wall_ids[i]].surface.fits(media.dimensions)) {
        // walls[wall_ids[i]]
        fits = i
        break
      }
    }

    if (fits != -1) {
      var wall = walls[wall_ids[fits]]
      wall_ids.splice(fits, 1)
    
      Scenery.add({
        media: media.media,
        wall: wall,
        index: 0,
      })
    }
    else {
      // artwork won't fit anywhere??
    }
  
    return false
  })
}