summaryrefslogtreecommitdiff
path: root/public/assets/javascripts/rectangles/models/surface.js
blob: 448722b9ee740bd5e37af66bfb6211d4e408247a (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
(function(){

	var vec2, Rect
	if ('window' in this) {
		vec2 = window.vec2
		Rect = window.Rect
	}
	else {
		vec2 = require('./vec2')
		Rect = require('./rect')
	}
	
	var Surface = function (face){
		this.width = 0
		this.height = 0
		this.faces = []
		if (face) {
			this.add(face)
		}
	}
	Surface.prototype.add = function(rect){
		this.faces.push(rect)
		this.width += rect.width()
		this.height = Math.max(this.height, rect.height())
	}
	Surface.prototype.fits_scale = function(v, scale){
		v = v.clone().mul(scale)
		return this.fits(v)
	}
	Surface.prototype.fits = function(v){
		var faces = this.faces
		var scratch
		if (this.width < v.a || this.height < v.b) {
			return null
		}
		for (var i = 0; i < faces.length; i++) {
			if (faces[i].fits(v)) {
				return faces[i]
			}
		}
		scratch = new Rect (0,0,0,0)
		for (var i = 0; i < faces.length; i++) {
			if (faces[i].y.length() < v.b) {
				continue
			}
			scratch.x.a = faces[i].x.a
			scratch.x.b = faces[i].x.b
			scratch.y.a = faces[i].y.a
			scratch.y.b = faces[i].y.b
			SEARCH: for (var j = i+1; j < faces.length; j++) {
				if (faces[j].y.a > scratch.y.a) {
					scratch.y.a = faces[j].y.a
				}
				if (faces[j].y.b < scratch.y.b) {
					scratch.y.b = faces[j].y.b
				}
				if (scratch.y.b <= scratch.y.a || scratch.y.length() < v.b) {
					break SEARCH
				}
				scratch.x.b = faces[j].x.b
				if (scratch.fits(v)) {
					return scratch
				}
			}
		}
		return null
	}
	Surface.prototype.place = function(v, index){
		var face, faces = this.faces
	}
	Surface.prototype.bounds = function(index){
		var bounds = faces[index].clone()
		var height = faces[index].height()

		for (var i = index-1; i > 0; i--) {
			var face = faces[i]
			if (face.y.length() < height) {
				continue
			}
			if (face.y.a > bounds.y.a) {
				continue
			}
			if (face.y.b < bounds.y.b) {
				continue
			}
			bounds.x.a = bounds.x.a
		}
		
		for (var i = index+1; i < faces.length; i++) {
			var face = faces[i]
			if (face.y.length() < height) {
				continue
			}
			if (face.y.a > bounds.y.a) {
				continue
			}
			if (face.y.b < bounds.y.b) {
				continue
			}
			bounds.x.b = bounds.x.b
		}
		return bounds
	}
	
	if ('window' in this) {
		window.Surface = Surface
	}
	else {
		module.exports = Surface
	}
})()