Snippets

Tomas Sinkunas AE Script: Shape to Circle

Created by Tomas Sinkunas last modified
  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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/**********************************************************************************************
    Shape to Circle v.1.1
    Copyright (c) 2017 Tomas Šinkūnas. All rights reserved.
    www.rendertom.com

    Description:
    	Morpth any shape into a circle.

	Change log:
		v1.1.1 - 2017 05 20
			- Disabled Custom Radius drop down menu upon loading script as dockable panel.

		v1.1 - 2017 05 14
			- Center of the circle is calculated from shapes bounding box.
			- Adds more radius selection options: "Bounding Box Height" and "Bounding Box Width"

		v1.0 - 2017 05 10
			- Initial release

	Released as open-source under the MIT license:

		The MIT License (MIT)
		Copyright (c) 2017 Tomas Šinkūnas www.renderTom.com
		Permission is hereby granted, free of charge, to any person obtaining a copy of this
		software and associated documentation files (the "Software"), to deal in the Software
		without restriction, including without limitation the rights to use, copy, modify, merge,
		publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
		to whom the Software is furnished to do so, subject to the following conditions:

		The above copyright notice and this permission notice shall be included in all copies or
		substantial portions of the Software.

		THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
		INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
		PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
		FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
		OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
		DEALINGS IN THE SOFTWARE.

**********************************************************************************************/

(function(thisObj) {

	scriptBuildUI(thisObj)

	function scriptBuildUI(thisObj) {
		var win = (thisObj instanceof Panel) ? thisObj : new Window("palette", "Shape to Circle", undefined, {
			resizeable: true
		});
		win.alignChildren = ["fill", "top"];
		win.spacing = 5;
		var grpCustomRadius = win.add("group");
		var checkCustomRadius = grpCustomRadius.add("checkbox", undefined, "Custom Radius");
		checkCustomRadius.value = true;
		checkCustomRadius.onClick = function() {
			etCustomRadius.enabled = this.value;
			ddRadius.enabled = !this.value;
		}
		var etCustomRadius = grpCustomRadius.add("edittext", undefined, "200");
		etCustomRadius.alignment = ["fill", "top"];

		var ddRadius = win.add("dropdownlist", undefined, ["Average from Center", "Bounding Box Height", "Bounding Box Width", "Maximum from Center", "Minimum from Center"]);
		ddRadius.selection = 0;
		ddRadius.enabled = false;

		var button = win.add("button", undefined, "Do It!");
		button.onClick = function() {
			if (etCustomRadius.enabled) {
				if (isNaN(etCustomRadius.text) || parseInt(etCustomRadius.text) < 0) {
					etCustomRadius.active = true;
					return alert("Please enter vadid radius value.");
				} else {
					main(parseInt(etCustomRadius.text));
				}
			} else {
				main(ddRadius.selection.text);
			}
		};

		win.onShow = function() {
			checkCustomRadius.onClick();
		};

		win.onResizing = win.onResize = function() {
			this.layout.resize();
		};

		win instanceof Window
			? (win.center(), win.show())
			: (win.layout.layout(true), win.layout.resize());
	}

	function main(radiusFromUI) {
		try {
			var radius = radiusFromUI;
			var distanceArray = [];

			var composition = getActiveComposition();
			var selectedLayers = getSelectedLayers(composition);
			var allShapeProperties = getAllShapeProperties(selectedLayers);
			if (allShapeProperties.length === 0)
				throw new Error("Please select Path property.");

			var pathValue, circleShape,
				boundingBox = [],
				centerCoordinates = [],
				circlePoints = [];

			app.beginUndoGroup("Shape to Circle");

			for (var j = 0, jl = allShapeProperties.length; j < jl; j++) {
				pathValue = allShapeProperties[j].value;
				boundingBox = getBoundingBox(pathValue);
				centerCoordinates = averageInArray(boundingBox);

				if (isNaN(radiusFromUI)) {
					distanceArray = getDistanceFromCenter(centerCoordinates, pathValue.vertices);
					if (radiusFromUI.match("Average")) radius = averageInArray(distanceArray);
					else if (radiusFromUI.match("Width")) radius = (boundingBox[1][0] - boundingBox[0][0]) / 2;
					else if (radiusFromUI.match("Height")) radius = (boundingBox[1][1] - boundingBox[0][1]) / 2;
					else if (radiusFromUI.match("Maximum")) radius = Math.max.apply(null, distanceArray);
					else if (radiusFromUI.match("Minimum")) radius = Math.min.apply(null, distanceArray);
				}

				circlePoints = pointsToCircle(centerCoordinates, radius, pathValue);

				circleShape = new Shape();
				circleShape.vertices = circlePoints.vertices;
				circleShape.inTangents = circlePoints.inTangents;
				circleShape.outTangents = circlePoints.outTangents;
				circleShape.closed = pathValue.closed;

				allShapeProperties[j].numKeys === 0
					? allShapeProperties[j].setValue(circleShape)
					: allShapeProperties[j].setValueAtTime(composition.time, circleShape);

			}
			app.endUndoGroup();
		} catch (e) {
			alert(e.message);
		}
	}

// -----------------------------------------------
	function getActiveComposition() {
		var composition = app.project.activeItem;
		if (!composition || !(composition instanceof CompItem))
			throw new Error("Please select composition first.");
		return composition;
	};

	function getAllShapeProperties(selectedLayers) {
		var allShapeProperties = [];
		var layerShapeProperties = [];
		for (var i = 0, il = selectedLayers.length; i < il; i++) {
			layerShapeProperties = getLayerShapeProperties(selectedLayers[i]);
			if (layerShapeProperties.length > 0) {
				allShapeProperties = allShapeProperties.concat(layerShapeProperties);
			}
		}
		return allShapeProperties;
	};

	function getLayerShapeProperties(layer) {
		var shapeProperties = [];
		var prop;
		var selectedProperties = layer.selectedProperties;
		for (var i = 0, il = selectedProperties.length; i < il; i++) {
			prop = selectedProperties[i];

			if (prop.matchName === "ADBE Vector Shape - Group") {
				if (prop.property("ADBE Vector Shape").selected === true) {
					continue
				} else {
					shapeProperties.push(prop.property("ADBE Vector Shape"))
				}
			} else if (prop.matchName === "ADBE Mask Atom") {
				if (prop.property("ADBE Mask Shape").selected === true) {
					continue
				} else {
					shapeProperties.push(prop.property("ADBE Mask Shape"))
				}
			} else if (prop.matchName.match("ADBE Vector Shape|ADBE Mask Shape")) {
				shapeProperties.push(prop)
			}
		}
		return shapeProperties;
	};

	function getSelectedLayers(composition) {
		var selectedLayers = composition.selectedLayers;
		if (selectedLayers.length === 0)
			throw new Error("Please select layer first.");
		return selectedLayers;
	};

// -----------------------------------------------
	function averageInArray(verticesArray) {
		return sumArray(verticesArray) / verticesArray.length;
	};

	function clockwiseDirection(vertices) {
		// http://stackoverflow.com/questions/14505565/detect-if-a-set-of-points-in-an-array-that-are-the-vertices-of-a-complex-polygon
		var polygonArea = getPoligonArea(vertices);
		return polygonArea > 0;
	};

	function distanceBetweenPoints(point1, point2) {
		var deltaX = point1[0] - point2[0];
		var deltaY = point1[1] - point2[1];
		var distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
		return distance;
	};

	function getAngle(point1, point2) {
		var distanceX = point2[0] - point1[0];
		var distanceY = point2[1] - point1[1];
		var theta = Math.atan2(distanceY, distanceX);
		return theta;
	};

	function getBoundingBox(pathValue) {
		var bezierPoints = toBezierPoints(pathValue),
			xValues = [],
			yValues = [],
			segmentBoundingBox = {};

		for (var i = 0, il = bezierPoints.length; i < il; i++) {
			segmentBoundingBox = getBoundsOfCurve(bezierPoints[i][0], bezierPoints[i][1], bezierPoints[i][2], bezierPoints[i][3]);
			xValues.push(segmentBoundingBox.left);
			xValues.push(segmentBoundingBox.right);
			yValues.push(segmentBoundingBox.top);
			yValues.push(segmentBoundingBox.bottom);
		}

		return [
			[Math.min.apply(null, xValues), Math.min.apply(null, yValues)],
			[Math.max.apply(null, xValues), Math.max.apply(null, yValues)]
		];
	};

	function getBoundsOfCurve(p1, p2, p3, p4) {
		// http://stackoverflow.com/questions/2587751/an-algorithm-to-find-bounding-box-of-closed-bezier-curves
		var tvalues = [],
			xvalues = [],
			yvalues = [],
			a, b, c, t, roots;

		for (var i = 0; i < 2; ++i) {
			if (i === 0) {
				b = 6 * p1[0] - 12 * p2[0] + 6 * p3[0];
				a = -3 * p1[0] + 9 * p2[0] - 9 * p3[0] + 3 * p4[0];
				c = 3 * p2[0] - 3 * p1[0];
			} else {
				b = 6 * p1[1] - 12 * p2[1] + 6 * p3[1];
				a = -3 * p1[1] + 9 * p2[1] - 9 * p3[1] + 3 * p4[1];
				c = 3 * p2[1] - 3 * p1[1];
			}

			if (Math.abs(a) < 1e-12) { // Numerical robustness
				if (Math.abs(b) < 1e-12) continue; // Numerical robustness

				t = -c / b;
				if (0 < t && t < 1) tvalues.push(t);
				continue;
			}

			// Solve Quadratic Equation
			roots = quadraticEquation(a, b, c);
			if (!roots) continue;
			if (0 < roots.root1 && roots.root1 < 1) tvalues.push(roots.root1);
			if (0 < roots.root2 && roots.root2 < 1) tvalues.push(roots.root2);

		}

		var u, j = tvalues.length;
		while (j--) {
			t = tvalues[j];
			u = 1 - t;
			xvalues[j] = (u * u * u * p1[0]) + (3 * u * u * t * p2[0]) + (3 * u * t * t * p3[0]) + (t * t * t * p4[0]);
			yvalues[j] = (u * u * u * p1[1]) + (3 * u * u * t * p2[1]) + (3 * u * t * t * p3[1]) + (t * t * t * p4[1]);
		}

		xvalues.push(p1[0], p4[0]);
		yvalues.push(p1[1], p4[1]);

		return {
			left: Math.min.apply(null, xvalues),
			top: Math.min.apply(null, yvalues),
			right: Math.max.apply(null, xvalues),
			bottom: Math.max.apply(null, yvalues),
		};
	};

	function getDistanceFromCenter(center, vertices) {
		var distanceFromCenter;
		var distanceArray = [];
		for (var i = 0, il = vertices.length; i < il; i++) {
			distanceFromCenter = distanceBetweenPoints(center, vertices[i]);
			distanceArray.push(distanceFromCenter);
		}
		return distanceArray;
	};

	function getHandleLength(numPoints, radius) {
		return radius * getMagicNumber() * 4 / numPoints;
	};

	function getMagicNumber() {
		// http://stackoverflow.com/questions/1734745/how-to-create-circle-with-bézier-curves
		// https://people-mozilla.org/~jmuizelaar/Riskus354.pdf
		return (4 / 3) * Math.tan(Math.PI / (2 * 4));
	}

	function getPointCoordinates(center, radius, angle) {
		return [
			center[0] + radius * Math.cos(angle),
			center[1] + radius * Math.sin(angle)
		]
	};

	function getPoligonArea(vertices) {
		var area = j = 0;
		for (var i = 0, il = vertices.length; i < il; i++) {
			j = (i + 1) % vertices.length;
			area += vertices[i][0] * vertices[j][1];
			area -= vertices[j][0] * vertices[i][1];
		}
		return area / 2;
	};

	function pointsToCircle(center, radius, pathValue) {
		var angle, anchor, handle;
		var vertices = pathValue.vertices;
		var numPoints = vertices.length;
		var slice = 2 * Math.PI / numPoints;
		var handleLength = getHandleLength(numPoints, radius);
		var angleOffset = getAngle(center, vertices[0]);

		var newCoordinates = {
			vertices: [],
			inTangents: [],
			outTangents: []
		};

		if (clockwiseDirection(vertices)) {
			for (var i = 0; i < numPoints; i++) {
				angle = slice * i + angleOffset;

				anchor = getPointCoordinates(center, radius, angle);
				handle = getPointCoordinates(anchor, handleLength, angle + Math.PI / 2);

				newCoordinates.vertices.push(anchor);
				newCoordinates.inTangents.push(anchor - handle);
				newCoordinates.outTangents.push(handle - anchor);
			}
		} else {
			for (var i = numPoints; i > 0; i--) {
				angle = slice * i + angleOffset;

				anchor = getPointCoordinates(center, radius, angle);
				handle = getPointCoordinates(anchor, handleLength, angle + Math.PI / 2);

				newCoordinates.vertices.push(anchor);
				newCoordinates.inTangents.push(handle - anchor);
				newCoordinates.outTangents.push(anchor - handle);
			}

		}

		// Add additional point to close the circle
		if (!pathValue.closed) {
			newCoordinates.vertices.push(newCoordinates.vertices[0]);
			newCoordinates.inTangents.push(newCoordinates.inTangents[0]);
			newCoordinates.outTangents.push(newCoordinates.outTangents[0]);
		}

		return newCoordinates;
	};

	function quadraticEquation(a, b, c) {
		var D = b * b - 4 * a * c; // D is the discriminant of the quadratic equation
		if (D < 0) return null; // If the discriminant is negative, then there are no real roots
		var sqrtD = Math.sqrt(D); // If the discriminant is positive, then there are two distinct roots

		return {
			root1: (-b + sqrtD) / (2 * a),
			root2: (-b - sqrtD) / (2 * a)
		}
	};

	function sumArray(array) {
		var totalSum = array[0];
		for (var i = 1, il = array.length; i < il; i++)
			totalSum += array[i];
		return totalSum;
	};

	function toBezierPoints(pathValue) {
		var valuesArray = [],
			p1, p2, p3, p4;

		for (var i = 0, il = pathValue.vertices.length - 1; i < il; i++) {
			p1 = pathValue.vertices[i];
			p2 = pathValue.vertices[i] + pathValue.outTangents[i];
			p3 = pathValue.inTangents[i + 1] + pathValue.vertices[i + 1]
			p4 = pathValue.vertices[i + 1];

			valuesArray.push([p1, p2, p3, p4]);
		}

		if (pathValue.closed) {
			p1 = pathValue.vertices[pathValue.vertices.length - 1];
			p2 = pathValue.vertices[pathValue.vertices.length - 1] + pathValue.outTangents[pathValue.outTangents.length - 1];
			p3 = pathValue.inTangents[0] + pathValue.vertices[0]
			p4 = pathValue.vertices[0];

			valuesArray.push([p1, p2, p3, p4]);
		}

		return valuesArray;
	};
})(this);

Comments (0)