1 /*************************************************************************/
2 /*  texture_region_editor_plugin.cpp                                      */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
10 /*                                                                       */
11 /* Author: Mariano Suligoy                                               */
12 /*                                                                       */
13 /* Permission is hereby granted, free of charge, to any person obtaining */
14 /* a copy of this software and associated documentation files (the       */
15 /* "Software"), to deal in the Software without restriction, including   */
16 /* without limitation the rights to use, copy, modify, merge, publish,   */
17 /* distribute, sublicense, and/or sell copies of the Software, and to    */
18 /* permit persons to whom the Software is furnished to do so, subject to */
19 /* the following conditions:                                             */
20 /*                                                                       */
21 /* The above copyright notice and this permission notice shall be        */
22 /* included in all copies or substantial portions of the Software.       */
23 /*                                                                       */
24 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
25 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
26 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
27 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
28 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
29 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
30 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
31 /*************************************************************************/
32 
33 #include "texture_region_editor_plugin.h"
34 #include "core/core_string_names.h"
35 #include "os/input.h"
36 #include "os/keyboard.h"
37 #include "scene/gui/check_box.h"
38 
draw_margin_line(Control * edit_draw,Vector2 from,Vector2 to)39 void draw_margin_line(Control *edit_draw, Vector2 from, Vector2 to) {
40 	Vector2 line = (to - from).normalized() * 10;
41 	while ((to - from).length_squared() > 200) {
42 		edit_draw->draw_line(from, from + line, Color(0.97, 0.2, 0.2), 2);
43 		from += line * 2;
44 	}
45 }
46 
_region_draw()47 void TextureRegionEditor::_region_draw() {
48 	Ref<Texture> base_tex = NULL;
49 	if (node_sprite)
50 		base_tex = node_sprite->get_texture();
51 	else if (node_patch9)
52 		base_tex = node_patch9->get_texture();
53 	else if (obj_styleBox.is_valid())
54 		base_tex = obj_styleBox->get_texture();
55 	else if (atlas_tex.is_valid())
56 		base_tex = atlas_tex->get_atlas();
57 	if (base_tex.is_null())
58 		return;
59 
60 	Matrix32 mtx;
61 	mtx.elements[2] = -draw_ofs;
62 	mtx.scale_basis(Vector2(draw_zoom, draw_zoom));
63 
64 	VS::get_singleton()->canvas_item_set_clip(edit_draw->get_canvas_item(), true);
65 	VS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(), mtx);
66 	edit_draw->draw_texture(base_tex, Point2());
67 	VS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(), Matrix32());
68 
69 	if (snap_mode == SNAP_GRID) {
70 		Size2 s = edit_draw->get_size();
71 		int last_cell;
72 
73 		if (snap_step.x != 0) {
74 			if (snap_separation.x == 0)
75 				for (int i = 0; i < s.width; i++) {
76 					int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / snap_step.x));
77 					if (i == 0)
78 						last_cell = cell;
79 					if (last_cell != cell)
80 						edit_draw->draw_line(Point2(i, 0), Point2(i, s.height), Color(0.3, 0.7, 1, 0.3));
81 					last_cell = cell;
82 				}
83 			else
84 				for (int i = 0; i < s.width; i++) {
85 					int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / (snap_step.x + snap_separation.x)));
86 					if (i == 0)
87 						last_cell = cell;
88 					if (last_cell != cell)
89 						edit_draw->draw_rect(Rect2(i - snap_separation.x * draw_zoom, 0, snap_separation.x * draw_zoom, s.height), Color(0.3, 0.7, 1, 0.3));
90 					last_cell = cell;
91 				}
92 		}
93 
94 		if (snap_step.y != 0) {
95 			if (snap_separation.y == 0)
96 				for (int i = 0; i < s.height; i++) {
97 					int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / snap_step.y));
98 					if (i == 0)
99 						last_cell = cell;
100 					if (last_cell != cell)
101 						edit_draw->draw_line(Point2(0, i), Point2(s.width, i), Color(0.3, 0.7, 1, 0.3));
102 					last_cell = cell;
103 				}
104 			else
105 				for (int i = 0; i < s.height; i++) {
106 					int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / (snap_step.y + snap_separation.y)));
107 					if (i == 0)
108 						last_cell = cell;
109 					if (last_cell != cell)
110 						edit_draw->draw_rect(Rect2(0, i - snap_separation.y * draw_zoom, s.width, snap_separation.y * draw_zoom), Color(0.3, 0.7, 1, 0.3));
111 					last_cell = cell;
112 				}
113 		}
114 	} else if (snap_mode == SNAP_AUTOSLICE) {
115 		for (List<Rect2>::Element *E = autoslice_cache.front(); E; E = E->next()) {
116 			Rect2 r = E->get();
117 			Vector2 endpoints[4] = {
118 				mtx.basis_xform(r.pos),
119 				mtx.basis_xform(r.pos + Vector2(r.size.x, 0)),
120 				mtx.basis_xform(r.pos + r.size),
121 				mtx.basis_xform(r.pos + Vector2(0, r.size.y))
122 			};
123 			for (int i = 0; i < 4; i++) {
124 				int next = (i + 1) % 4;
125 				edit_draw->draw_line(endpoints[i] - draw_ofs, endpoints[next] - draw_ofs, Color(0.3, 0.7, 1, 1), 2);
126 			}
127 		}
128 	}
129 
130 	Ref<Texture> select_handle = get_icon("EditorHandle", "EditorIcons");
131 
132 	Rect2 scroll_rect(Point2(), mtx.basis_xform(base_tex->get_size()));
133 	scroll_rect.expand_to(mtx.basis_xform(edit_draw->get_size()));
134 
135 	Vector2 endpoints[4] = {
136 		mtx.basis_xform(rect.pos),
137 		mtx.basis_xform(rect.pos + Vector2(rect.size.x, 0)),
138 		mtx.basis_xform(rect.pos + rect.size),
139 		mtx.basis_xform(rect.pos + Vector2(0, rect.size.y))
140 	};
141 	Color color(0.9, 0.5, 0.5);
142 	for (int i = 0; i < 4; i++) {
143 
144 		int prev = (i + 3) % 4;
145 		int next = (i + 1) % 4;
146 
147 		Vector2 ofs = ((endpoints[i] - endpoints[prev]).normalized() + ((endpoints[i] - endpoints[next]).normalized())).normalized();
148 		ofs *= 1.4144 * (select_handle->get_size().width / 2);
149 
150 		edit_draw->draw_line(endpoints[i] - draw_ofs, endpoints[next] - draw_ofs, color, 2);
151 
152 		if (snap_mode != SNAP_AUTOSLICE)
153 			edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs);
154 
155 		ofs = (endpoints[next] - endpoints[i]) / 2;
156 		ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2);
157 
158 		if (snap_mode != SNAP_AUTOSLICE)
159 			edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs);
160 
161 		scroll_rect.expand_to(endpoints[i]);
162 	}
163 
164 	scroll_rect = scroll_rect.grow(200);
165 	updating_scroll = true;
166 	hscroll->set_min(scroll_rect.pos.x);
167 	hscroll->set_max(scroll_rect.pos.x + scroll_rect.size.x);
168 	hscroll->set_page(edit_draw->get_size().x);
169 	hscroll->set_val(draw_ofs.x);
170 	hscroll->set_step(0.001);
171 
172 	vscroll->set_min(scroll_rect.pos.y);
173 	vscroll->set_max(scroll_rect.pos.y + scroll_rect.size.y);
174 	vscroll->set_page(edit_draw->get_size().y);
175 	vscroll->set_val(draw_ofs.y);
176 	vscroll->set_step(0.001);
177 	updating_scroll = false;
178 
179 	float margins[4];
180 	if (node_patch9 || obj_styleBox.is_valid()) {
181 		if (node_patch9) {
182 			margins[0] = node_patch9->get_patch_margin(MARGIN_TOP);
183 			margins[1] = node_patch9->get_patch_margin(MARGIN_BOTTOM);
184 			margins[2] = node_patch9->get_patch_margin(MARGIN_LEFT);
185 			margins[3] = node_patch9->get_patch_margin(MARGIN_RIGHT);
186 		} else if (obj_styleBox.is_valid()) {
187 			margins[0] = obj_styleBox->get_margin_size(MARGIN_TOP);
188 			margins[1] = obj_styleBox->get_margin_size(MARGIN_BOTTOM);
189 			margins[2] = obj_styleBox->get_margin_size(MARGIN_LEFT);
190 			margins[3] = obj_styleBox->get_margin_size(MARGIN_RIGHT);
191 		}
192 		Vector2 pos[4] = {
193 			mtx.basis_xform(Vector2(0, margins[0])) + Vector2(0, endpoints[0].y - draw_ofs.y),
194 			-mtx.basis_xform(Vector2(0, margins[1])) + Vector2(0, endpoints[2].y - draw_ofs.y),
195 			mtx.basis_xform(Vector2(margins[2], 0)) + Vector2(endpoints[0].x - draw_ofs.x, 0),
196 			-mtx.basis_xform(Vector2(margins[3], 0)) + Vector2(endpoints[2].x - draw_ofs.x, 0)
197 		};
198 
199 		draw_margin_line(edit_draw, pos[0], pos[0] + Vector2(edit_draw->get_size().x, 0));
200 		draw_margin_line(edit_draw, pos[1], pos[1] + Vector2(edit_draw->get_size().x, 0));
201 		draw_margin_line(edit_draw, pos[2], pos[2] + Vector2(0, edit_draw->get_size().y));
202 		draw_margin_line(edit_draw, pos[3], pos[3] + Vector2(0, edit_draw->get_size().y));
203 	}
204 }
205 
_region_input(const InputEvent & p_input)206 void TextureRegionEditor::_region_input(const InputEvent &p_input) {
207 	Matrix32 mtx;
208 	mtx.elements[2] = -draw_ofs;
209 	mtx.scale_basis(Vector2(draw_zoom, draw_zoom));
210 
211 	Vector2 endpoints[8] = {
212 		mtx.xform(rect.pos) + Vector2(-4, -4),
213 		mtx.xform(rect.pos + Vector2(rect.size.x / 2, 0)) + Vector2(0, -4),
214 		mtx.xform(rect.pos + Vector2(rect.size.x, 0)) + Vector2(4, -4),
215 		mtx.xform(rect.pos + Vector2(rect.size.x, rect.size.y / 2)) + Vector2(4, 0),
216 		mtx.xform(rect.pos + rect.size) + Vector2(4, 4),
217 		mtx.xform(rect.pos + Vector2(rect.size.x / 2, rect.size.y)) + Vector2(0, 4),
218 		mtx.xform(rect.pos + Vector2(0, rect.size.y)) + Vector2(-4, 4),
219 		mtx.xform(rect.pos + Vector2(0, rect.size.y / 2)) + Vector2(-4, 0)
220 	};
221 
222 	if (p_input.type == InputEvent::MOUSE_BUTTON) {
223 
224 		const InputEventMouseButton &mb = p_input.mouse_button;
225 
226 		if (mb.button_index == BUTTON_LEFT) {
227 
228 			if (mb.pressed) {
229 				if (node_patch9 || obj_styleBox.is_valid()) {
230 					edited_margin = -1;
231 					float margins[4];
232 					if (node_patch9) {
233 						margins[0] = node_patch9->get_patch_margin(MARGIN_TOP);
234 						margins[1] = node_patch9->get_patch_margin(MARGIN_BOTTOM);
235 						margins[2] = node_patch9->get_patch_margin(MARGIN_LEFT);
236 						margins[3] = node_patch9->get_patch_margin(MARGIN_RIGHT);
237 					} else if (obj_styleBox.is_valid()) {
238 						margins[0] = obj_styleBox->get_margin_size(MARGIN_TOP);
239 						margins[1] = obj_styleBox->get_margin_size(MARGIN_BOTTOM);
240 						margins[2] = obj_styleBox->get_margin_size(MARGIN_LEFT);
241 						margins[3] = obj_styleBox->get_margin_size(MARGIN_RIGHT);
242 					}
243 					Vector2 pos[4] = {
244 						mtx.basis_xform(rect.pos + Vector2(0, margins[0])) - draw_ofs,
245 						mtx.basis_xform(rect.pos + rect.size - Vector2(0, margins[1])) - draw_ofs,
246 						mtx.basis_xform(rect.pos + Vector2(margins[2], 0)) - draw_ofs,
247 						mtx.basis_xform(rect.pos + rect.size - Vector2(margins[3], 0)) - draw_ofs
248 					};
249 					if (Math::abs(mb.y - pos[0].y) < 8) {
250 						edited_margin = 0;
251 						prev_margin = margins[0];
252 					} else if (Math::abs(mb.y - pos[1].y) < 8) {
253 						edited_margin = 1;
254 						prev_margin = margins[1];
255 					} else if (Math::abs(mb.x - pos[2].x) < 8) {
256 						edited_margin = 2;
257 						prev_margin = margins[2];
258 					} else if (Math::abs(mb.x - pos[3].x) < 8) {
259 						edited_margin = 3;
260 						prev_margin = margins[3];
261 					}
262 					if (edited_margin >= 0) {
263 						drag_from = Vector2(mb.x, mb.y);
264 						drag = true;
265 					}
266 				}
267 				if (edited_margin < 0 && snap_mode == SNAP_AUTOSLICE) {
268 					Vector2 point = mtx.affine_inverse().xform(Vector2(mb.x, mb.y));
269 					for (List<Rect2>::Element *E = autoslice_cache.front(); E; E = E->next()) {
270 						if (E->get().has_point(point)) {
271 							rect = E->get();
272 							if (Input::get_singleton()->is_key_pressed(KEY_CONTROL) && !(Input::get_singleton()->is_key_pressed(KEY_SHIFT | KEY_ALT))) {
273 								Rect2 r;
274 								if (node_sprite)
275 									r = node_sprite->get_region_rect();
276 								else if (node_patch9)
277 									r = node_patch9->get_region_rect();
278 								else if (obj_styleBox.is_valid())
279 									r = obj_styleBox->get_region_rect();
280 								else if (atlas_tex.is_valid())
281 									r = atlas_tex->get_region();
282 								rect.expand_to(r.pos);
283 								rect.expand_to(r.pos + r.size);
284 							}
285 							undo_redo->create_action("Set Region Rect");
286 							if (node_sprite) {
287 								undo_redo->add_do_method(node_sprite, "set_region_rect", rect);
288 								undo_redo->add_undo_method(node_sprite, "set_region_rect", node_sprite->get_region_rect());
289 							} else if (node_patch9) {
290 								undo_redo->add_do_method(node_patch9, "set_region_rect", rect);
291 								undo_redo->add_undo_method(node_patch9, "set_region_rect", node_patch9->get_region_rect());
292 							} else if (obj_styleBox.is_valid()) {
293 								undo_redo->add_do_method(obj_styleBox.ptr(), "set_region_rect", rect);
294 								undo_redo->add_undo_method(obj_styleBox.ptr(), "set_region_rect", obj_styleBox->get_region_rect());
295 							} else if (atlas_tex.is_valid()) {
296 								undo_redo->add_do_method(atlas_tex.ptr(), "set_region", rect);
297 								undo_redo->add_undo_method(atlas_tex.ptr(), "set_region", atlas_tex->get_region());
298 							}
299 							undo_redo->add_do_method(edit_draw, "update");
300 							undo_redo->add_undo_method(edit_draw, "update");
301 							undo_redo->commit_action();
302 							break;
303 						}
304 					}
305 				} else if (edited_margin < 0) {
306 					drag_from = mtx.affine_inverse().xform(Vector2(mb.x, mb.y));
307 					if (snap_mode == SNAP_PIXEL)
308 						drag_from = drag_from.snapped(Vector2(1, 1));
309 					else if (snap_mode == SNAP_GRID)
310 						drag_from = snap_point(drag_from);
311 					drag = true;
312 					if (node_sprite)
313 						rect_prev = node_sprite->get_region_rect();
314 					else if (node_patch9)
315 						rect_prev = node_patch9->get_region_rect();
316 					else if (obj_styleBox.is_valid())
317 						rect_prev = obj_styleBox->get_region_rect();
318 					else if (atlas_tex.is_valid())
319 						rect_prev = atlas_tex->get_region();
320 
321 					for (int i = 0; i < 8; i++) {
322 						Vector2 tuv = endpoints[i];
323 						if (tuv.distance_to(Vector2(mb.x, mb.y)) < 8) {
324 							drag_index = i;
325 						}
326 					}
327 
328 					if (drag_index == -1) {
329 						creating = true;
330 						rect = Rect2(drag_from, Size2());
331 					}
332 				}
333 
334 			} else if (drag) {
335 				if (edited_margin >= 0) {
336 					undo_redo->create_action("Set Margin");
337 					static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT };
338 					if (node_patch9) {
339 						undo_redo->add_do_method(node_patch9, "set_patch_margin", m[edited_margin], node_patch9->get_patch_margin(m[edited_margin]));
340 						undo_redo->add_undo_method(node_patch9, "set_patch_margin", m[edited_margin], prev_margin);
341 					} else if (obj_styleBox.is_valid()) {
342 						undo_redo->add_do_method(obj_styleBox.ptr(), "set_margin_size", m[edited_margin], obj_styleBox->get_margin_size(m[edited_margin]));
343 						undo_redo->add_undo_method(obj_styleBox.ptr(), "set_margin_size", m[edited_margin], prev_margin);
344 						obj_styleBox->emit_signal(CoreStringNames::get_singleton()->changed);
345 					}
346 					edited_margin = -1;
347 				} else {
348 					undo_redo->create_action("Set Region Rect");
349 					if (node_sprite) {
350 						undo_redo->add_do_method(node_sprite, "set_region_rect", node_sprite->get_region_rect());
351 						undo_redo->add_undo_method(node_sprite, "set_region_rect", rect_prev);
352 					} else if (atlas_tex.is_valid()) {
353 						undo_redo->add_do_method(atlas_tex.ptr(), "set_region", atlas_tex->get_region());
354 						undo_redo->add_undo_method(atlas_tex.ptr(), "set_region", rect_prev);
355 					} else if (node_patch9) {
356 					} else if (node_patch9) {
357 						undo_redo->add_do_method(node_patch9, "set_region_rect", node_patch9->get_region_rect());
358 						undo_redo->add_undo_method(node_patch9, "set_region_rect", rect_prev);
359 					} else if (obj_styleBox.is_valid()) {
360 						undo_redo->add_do_method(obj_styleBox.ptr(), "set_region_rect", obj_styleBox->get_region_rect());
361 						undo_redo->add_undo_method(obj_styleBox.ptr(), "set_region_rect", rect_prev);
362 					}
363 					drag_index = -1;
364 				}
365 				undo_redo->add_do_method(edit_draw, "update");
366 				undo_redo->add_undo_method(edit_draw, "update");
367 				undo_redo->commit_action();
368 				drag = false;
369 				creating = false;
370 			}
371 
372 		} else if (mb.button_index == BUTTON_RIGHT && mb.pressed) {
373 
374 			if (drag) {
375 				drag = false;
376 				if (edited_margin >= 0) {
377 					static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT };
378 					if (node_patch9)
379 						node_patch9->set_patch_margin(m[edited_margin], prev_margin);
380 					if (obj_styleBox.is_valid())
381 						obj_styleBox->set_margin_size(m[edited_margin], prev_margin);
382 					edited_margin = -1;
383 				} else {
384 					apply_rect(rect_prev);
385 					rect = rect_prev;
386 					edit_draw->update();
387 					drag_index = -1;
388 				}
389 			}
390 		} else if (mb.button_index == BUTTON_WHEEL_UP && mb.pressed) {
391 			_zoom_in();
392 		} else if (mb.button_index == BUTTON_WHEEL_DOWN && mb.pressed) {
393 			_zoom_out();
394 		}
395 	} else if (p_input.type == InputEvent::MOUSE_MOTION) {
396 
397 		const InputEventMouseMotion &mm = p_input.mouse_motion;
398 
399 		if (mm.button_mask & BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
400 
401 			Vector2 draged(mm.relative_x, mm.relative_y);
402 			hscroll->set_val(hscroll->get_val() - draged.x);
403 			vscroll->set_val(vscroll->get_val() - draged.y);
404 
405 		} else if (drag) {
406 
407 			if (edited_margin >= 0) {
408 				float new_margin;
409 				if (edited_margin == 0)
410 					new_margin = prev_margin + (mm.y - drag_from.y) / draw_zoom;
411 				else if (edited_margin == 1)
412 					new_margin = prev_margin - (mm.y - drag_from.y) / draw_zoom;
413 				else if (edited_margin == 2)
414 					new_margin = prev_margin + (mm.x - drag_from.x) / draw_zoom;
415 				else if (edited_margin == 3)
416 					new_margin = prev_margin - (mm.x - drag_from.x) / draw_zoom;
417 				if (new_margin < 0)
418 					new_margin = 0;
419 				static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT };
420 				if (node_patch9)
421 					node_patch9->set_patch_margin(m[edited_margin], new_margin);
422 				if (obj_styleBox.is_valid())
423 					obj_styleBox->set_margin_size(m[edited_margin], new_margin);
424 			} else {
425 				Vector2 new_pos = mtx.affine_inverse().xform(Vector2(mm.x, mm.y));
426 				if (snap_mode == SNAP_PIXEL)
427 					new_pos = new_pos.snapped(Vector2(1, 1));
428 				else if (snap_mode == SNAP_GRID)
429 					new_pos = snap_point(new_pos);
430 
431 				if (creating) {
432 					rect = Rect2(drag_from, Size2());
433 					rect.expand_to(new_pos);
434 					apply_rect(rect);
435 					edit_draw->update();
436 					return;
437 				}
438 
439 				switch (drag_index) {
440 					case 0: {
441 						Vector2 p = rect_prev.pos + rect_prev.size;
442 						rect = Rect2(p, Size2());
443 						rect.expand_to(new_pos);
444 						apply_rect(rect);
445 					} break;
446 					case 1: {
447 						Vector2 p = rect_prev.pos + Vector2(0, rect_prev.size.y);
448 						rect = Rect2(p, Size2(rect_prev.size.x, 0));
449 						rect.expand_to(new_pos);
450 						apply_rect(rect);
451 					} break;
452 					case 2: {
453 						Vector2 p = rect_prev.pos + Vector2(0, rect_prev.size.y);
454 						rect = Rect2(p, Size2());
455 						rect.expand_to(new_pos);
456 						apply_rect(rect);
457 					} break;
458 					case 3: {
459 						Vector2 p = rect_prev.pos;
460 						rect = Rect2(p, Size2(0, rect_prev.size.y));
461 						rect.expand_to(new_pos);
462 						apply_rect(rect);
463 					} break;
464 					case 4: {
465 						Vector2 p = rect_prev.pos;
466 						rect = Rect2(p, Size2());
467 						rect.expand_to(new_pos);
468 						apply_rect(rect);
469 					} break;
470 					case 5: {
471 						Vector2 p = rect_prev.pos;
472 						rect = Rect2(p, Size2(rect_prev.size.x, 0));
473 						rect.expand_to(new_pos);
474 						apply_rect(rect);
475 					} break;
476 					case 6: {
477 						Vector2 p = rect_prev.pos + Vector2(rect_prev.size.x, 0);
478 						rect = Rect2(p, Size2());
479 						rect.expand_to(new_pos);
480 						apply_rect(rect);
481 					} break;
482 					case 7: {
483 						Vector2 p = rect_prev.pos + Vector2(rect_prev.size.x, 0);
484 						rect = Rect2(p, Size2(0, rect_prev.size.y));
485 						rect.expand_to(new_pos);
486 						apply_rect(rect);
487 					} break;
488 				}
489 			}
490 			edit_draw->update();
491 		}
492 	}
493 }
494 
_scroll_changed(float)495 void TextureRegionEditor::_scroll_changed(float) {
496 	if (updating_scroll)
497 		return;
498 
499 	draw_ofs.x = hscroll->get_val();
500 	draw_ofs.y = vscroll->get_val();
501 	edit_draw->update();
502 }
503 
_set_snap_mode(int p_mode)504 void TextureRegionEditor::_set_snap_mode(int p_mode) {
505 	snap_mode_button->get_popup()->set_item_checked(snap_mode, false);
506 	snap_mode = p_mode;
507 	snap_mode_button->set_text(snap_mode_button->get_popup()->get_item_text(p_mode));
508 	snap_mode_button->get_popup()->set_item_checked(snap_mode, true);
509 
510 	if (snap_mode == SNAP_GRID)
511 		hb_grid->show();
512 	else
513 		hb_grid->hide();
514 
515 	edit_draw->update();
516 }
517 
_set_snap_off_x(float p_val)518 void TextureRegionEditor::_set_snap_off_x(float p_val) {
519 	snap_offset.x = p_val;
520 	edit_draw->update();
521 }
522 
_set_snap_off_y(float p_val)523 void TextureRegionEditor::_set_snap_off_y(float p_val) {
524 	snap_offset.y = p_val;
525 	edit_draw->update();
526 }
527 
_set_snap_step_x(float p_val)528 void TextureRegionEditor::_set_snap_step_x(float p_val) {
529 	snap_step.x = p_val;
530 	edit_draw->update();
531 }
532 
_set_snap_step_y(float p_val)533 void TextureRegionEditor::_set_snap_step_y(float p_val) {
534 	snap_step.y = p_val;
535 	edit_draw->update();
536 }
537 
_set_snap_sep_x(float p_val)538 void TextureRegionEditor::_set_snap_sep_x(float p_val) {
539 	snap_separation.x = p_val;
540 	edit_draw->update();
541 }
542 
_set_snap_sep_y(float p_val)543 void TextureRegionEditor::_set_snap_sep_y(float p_val) {
544 	snap_separation.y = p_val;
545 	edit_draw->update();
546 }
547 
_zoom_in()548 void TextureRegionEditor::_zoom_in() {
549 	if (draw_zoom < 8) {
550 		draw_zoom *= 2;
551 		edit_draw->update();
552 	}
553 }
554 
_zoom_reset()555 void TextureRegionEditor::_zoom_reset() {
556 	if (draw_zoom == 1) return;
557 	draw_zoom = 1;
558 	edit_draw->update();
559 }
560 
_zoom_out()561 void TextureRegionEditor::_zoom_out() {
562 	if (draw_zoom > 0.25) {
563 		draw_zoom /= 2;
564 		edit_draw->update();
565 	}
566 }
567 
apply_rect(const Rect2 & rect)568 void TextureRegionEditor::apply_rect(const Rect2 &rect) {
569 	if (node_sprite)
570 		node_sprite->set_region_rect(rect);
571 	else if (node_patch9)
572 		node_patch9->set_region_rect(rect);
573 	else if (obj_styleBox.is_valid())
574 		obj_styleBox->set_region_rect(rect);
575 	else if (atlas_tex.is_valid())
576 		atlas_tex->set_region(rect);
577 }
578 
_notification(int p_what)579 void TextureRegionEditor::_notification(int p_what) {
580 	switch (p_what) {
581 		case NOTIFICATION_READY: {
582 			zoom_out->set_icon(get_icon("ZoomLess", "EditorIcons"));
583 			zoom_reset->set_icon(get_icon("ZoomReset", "EditorIcons"));
584 			zoom_in->set_icon(get_icon("ZoomMore", "EditorIcons"));
585 			icon_zoom->set_texture(get_icon("Zoom", "EditorIcons"));
586 		} break;
587 	}
588 }
589 
_node_removed(Object * p_obj)590 void TextureRegionEditor::_node_removed(Object *p_obj) {
591 	if (p_obj == node_sprite || p_obj == node_patch9 || p_obj == obj_styleBox.ptr() || p_obj == atlas_tex.ptr()) {
592 		node_patch9 = NULL;
593 		node_sprite = NULL;
594 		obj_styleBox = Ref<StyleBox>(NULL);
595 		atlas_tex = Ref<AtlasTexture>(NULL);
596 		hide();
597 	}
598 }
599 
_bind_methods()600 void TextureRegionEditor::_bind_methods() {
601 	ObjectTypeDB::bind_method(_MD("_edit_region"), &TextureRegionEditor::_edit_region);
602 	ObjectTypeDB::bind_method(_MD("_region_draw"), &TextureRegionEditor::_region_draw);
603 	ObjectTypeDB::bind_method(_MD("_region_input"), &TextureRegionEditor::_region_input);
604 	ObjectTypeDB::bind_method(_MD("_scroll_changed"), &TextureRegionEditor::_scroll_changed);
605 	ObjectTypeDB::bind_method(_MD("_node_removed"), &TextureRegionEditor::_node_removed);
606 	ObjectTypeDB::bind_method(_MD("_set_snap_mode"), &TextureRegionEditor::_set_snap_mode);
607 	ObjectTypeDB::bind_method(_MD("_set_snap_off_x"), &TextureRegionEditor::_set_snap_off_x);
608 	ObjectTypeDB::bind_method(_MD("_set_snap_off_y"), &TextureRegionEditor::_set_snap_off_y);
609 	ObjectTypeDB::bind_method(_MD("_set_snap_step_x"), &TextureRegionEditor::_set_snap_step_x);
610 	ObjectTypeDB::bind_method(_MD("_set_snap_step_y"), &TextureRegionEditor::_set_snap_step_y);
611 	ObjectTypeDB::bind_method(_MD("_set_snap_sep_x"), &TextureRegionEditor::_set_snap_sep_x);
612 	ObjectTypeDB::bind_method(_MD("_set_snap_sep_y"), &TextureRegionEditor::_set_snap_sep_y);
613 	ObjectTypeDB::bind_method(_MD("_zoom_in"), &TextureRegionEditor::_zoom_in);
614 	ObjectTypeDB::bind_method(_MD("_zoom_reset"), &TextureRegionEditor::_zoom_reset);
615 	ObjectTypeDB::bind_method(_MD("_zoom_out"), &TextureRegionEditor::_zoom_out);
616 }
617 
edit(Object * p_obj)618 void TextureRegionEditor::edit(Object *p_obj) {
619 	if (node_sprite && node_sprite->is_connected("texture_changed", this, "_edit_region"))
620 		node_sprite->disconnect("texture_changed", this, "_edit_region");
621 	if (node_patch9 && node_patch9->is_connected("texture_changed", this, "_edit_region"))
622 		node_patch9->disconnect("texture_changed", this, "_edit_region");
623 	if (obj_styleBox.is_valid() && obj_styleBox->is_connected("texture_changed", this, "_edit_region"))
624 		obj_styleBox->disconnect("texture_changed", this, "_edit_region");
625 	if (atlas_tex.is_valid() && atlas_tex->is_connected("atlas_changed", this, "_edit_region"))
626 		atlas_tex->disconnect("atlas_changed", this, "_edit_region");
627 	if (p_obj) {
628 		node_sprite = p_obj->cast_to<Sprite>();
629 		node_patch9 = p_obj->cast_to<Patch9Frame>();
630 		if (p_obj->cast_to<StyleBoxTexture>())
631 			obj_styleBox = Ref<StyleBoxTexture>(p_obj->cast_to<StyleBoxTexture>());
632 		if (p_obj->cast_to<AtlasTexture>()) {
633 			atlas_tex = Ref<AtlasTexture>(p_obj->cast_to<AtlasTexture>());
634 			atlas_tex->connect("atlas_changed", this, "_edit_region");
635 		} else {
636 			p_obj->connect("texture_changed", this, "_edit_region");
637 		}
638 		p_obj->add_change_receptor(this);
639 		p_obj->connect("exit_tree", this, "_node_removed", varray(p_obj), CONNECT_ONESHOT);
640 		_edit_region();
641 	} else {
642 		if (node_sprite)
643 			node_sprite->disconnect("exit_tree", this, "_node_removed");
644 		else if (node_patch9)
645 			node_patch9->disconnect("exit_tree", this, "_node_removed");
646 		else if (obj_styleBox.is_valid())
647 			obj_styleBox->disconnect("exit_tree", this, "_node_removed");
648 		else if (atlas_tex.is_valid())
649 			atlas_tex->disconnect("exit_tree", this, "_node_removed");
650 
651 		node_sprite = NULL;
652 		node_patch9 = NULL;
653 		obj_styleBox = Ref<StyleBoxTexture>(NULL);
654 		atlas_tex = Ref<AtlasTexture>(NULL);
655 	}
656 	edit_draw->update();
657 }
658 
_changed_callback(Object * p_changed,const char * p_prop)659 void TextureRegionEditor::_changed_callback(Object *p_changed, const char *p_prop) {
660 	if ((String)p_prop == "region_rect") {
661 		_edit_region();
662 	}
663 }
664 
_edit_region()665 void TextureRegionEditor::_edit_region() {
666 	Ref<Texture> texture = NULL;
667 	if (node_sprite)
668 		texture = node_sprite->get_texture();
669 	else if (node_patch9)
670 		texture = node_patch9->get_texture();
671 	else if (obj_styleBox.is_valid())
672 		texture = obj_styleBox->get_texture();
673 	else if (atlas_tex.is_valid())
674 		texture = atlas_tex->get_atlas();
675 
676 	if (texture.is_null()) {
677 		return;
678 	}
679 
680 	autoslice_cache.clear();
681 	Image i;
682 	if (i.load(texture->get_path()) == OK) {
683 		BitMap bm;
684 		bm.create_from_image_alpha(i);
685 		for (int y = 0; y < i.get_height(); y++) {
686 			for (int x = 0; x < i.get_width(); x++) {
687 				if (bm.get_bit(Point2(x, y))) {
688 					bool found = false;
689 					for (List<Rect2>::Element *E = autoslice_cache.front(); E; E = E->next()) {
690 						Rect2 grown = E->get().grow(1.5);
691 						if (grown.has_point(Point2(x, y))) {
692 							E->get().expand_to(Point2(x, y));
693 							E->get().expand_to(Point2(x + 1, y + 1));
694 							x = E->get().pos.x + E->get().size.x - 1;
695 							bool merged = true;
696 							while (merged) {
697 								merged = false;
698 								bool queue_erase = false;
699 								for (List<Rect2>::Element *F = autoslice_cache.front(); F; F = F->next()) {
700 									if (queue_erase) {
701 										autoslice_cache.erase(F->prev());
702 										queue_erase = false;
703 									}
704 									if (F == E)
705 										continue;
706 									if (E->get().grow(1).intersects(F->get())) {
707 										E->get().expand_to(F->get().pos);
708 										E->get().expand_to(F->get().pos + F->get().size);
709 										if (F->prev()) {
710 											F = F->prev();
711 											autoslice_cache.erase(F->next());
712 										} else {
713 											queue_erase = true;
714 											//Cant delete the first rect in the list.
715 										}
716 										merged = true;
717 									}
718 								}
719 							}
720 							found = true;
721 							break;
722 						}
723 					}
724 					if (!found) {
725 						Rect2 new_rect(x, y, 1, 1);
726 						autoslice_cache.push_back(new_rect);
727 					}
728 				}
729 			}
730 		}
731 	}
732 
733 	if (node_sprite)
734 		rect = node_sprite->get_region_rect();
735 	else if (node_patch9)
736 		rect = node_patch9->get_region_rect();
737 	else if (obj_styleBox.is_valid())
738 		rect = obj_styleBox->get_region_rect();
739 	else if (atlas_tex.is_valid())
740 		rect = atlas_tex->get_region();
741 
742 	edit_draw->update();
743 }
744 
_snap_scalar(float p_offset,float p_step,float separation,float p_target)745 inline float _snap_scalar(float p_offset, float p_step, float separation, float p_target) {
746 	if (p_step != 0) {
747 		float a = Math::stepify(p_target - p_offset, p_step + separation) + p_offset;
748 		float b = a;
749 		if (p_target >= 0)
750 			b -= separation;
751 		else
752 			b += p_step;
753 		return (Math::abs(p_target - a) < Math::abs(p_target - b)) ? a : b;
754 	}
755 	return p_target;
756 }
757 
snap_point(Vector2 p_target) const758 Vector2 TextureRegionEditor::snap_point(Vector2 p_target) const {
759 	if (snap_mode == SNAP_GRID) {
760 		p_target.x = _snap_scalar(snap_offset.x, snap_step.x, snap_separation.x, p_target.x);
761 		p_target.y = _snap_scalar(snap_offset.y, snap_step.y, snap_separation.y, p_target.y);
762 	}
763 
764 	return p_target;
765 }
766 
TextureRegionEditor(EditorNode * p_editor)767 TextureRegionEditor::TextureRegionEditor(EditorNode *p_editor) {
768 	node_sprite = NULL;
769 	node_patch9 = NULL;
770 	obj_styleBox = Ref<StyleBoxTexture>(NULL);
771 	atlas_tex = Ref<AtlasTexture>(NULL);
772 	editor = p_editor;
773 	undo_redo = editor->get_undo_redo();
774 
775 	snap_step = Vector2(10, 10);
776 	snap_separation = Vector2(0, 0);
777 	edited_margin = -1;
778 	drag_index = -1;
779 	drag = false;
780 	snap_mode = SNAP_NONE;
781 
782 	VBoxContainer *main_vb = memnew(VBoxContainer);
783 	add_child(main_vb);
784 	main_vb->set_area_as_parent_rect(0);
785 	HBoxContainer *hb_tools = memnew(HBoxContainer);
786 	main_vb->add_child(hb_tools);
787 
788 	hb_tools->add_child(memnew(Label(TTR("Snap Mode:"))));
789 
790 	snap_mode_button = memnew(MenuButton);
791 	hb_tools->add_child(snap_mode_button);
792 	snap_mode_button->set_text(TTR("<None>"));
793 	PopupMenu *p = snap_mode_button->get_popup();
794 	p->add_item(TTR("<None>"), 0);
795 	p->add_item(TTR("Pixel Snap"), 1);
796 	p->add_item(TTR("Grid Snap"), 2);
797 	p->add_item(TTR("Auto Slice"), 3);
798 	for (int i = 0; i < 4; i++)
799 		p->set_item_as_checkable(i, true);
800 	p->set_item_checked(0, true);
801 	p->connect("item_pressed", this, "_set_snap_mode");
802 	hb_grid = memnew(HBoxContainer);
803 	hb_tools->add_child(hb_grid);
804 	hb_grid->add_child(memnew(VSeparator));
805 
806 	hb_grid->add_child(memnew(Label(TTR("Offset:"))));
807 
808 	sb_off_x = memnew(SpinBox);
809 	sb_off_x->set_min(-256);
810 	sb_off_x->set_max(256);
811 	sb_off_x->set_step(1);
812 	sb_off_x->set_val(snap_offset.x);
813 	sb_off_x->set_suffix("px");
814 	sb_off_x->connect("value_changed", this, "_set_snap_off_x");
815 	hb_grid->add_child(sb_off_x);
816 
817 	sb_off_y = memnew(SpinBox);
818 	sb_off_y->set_min(-256);
819 	sb_off_y->set_max(256);
820 	sb_off_y->set_step(1);
821 	sb_off_y->set_val(snap_offset.y);
822 	sb_off_y->set_suffix("px");
823 	sb_off_y->connect("value_changed", this, "_set_snap_off_y");
824 	hb_grid->add_child(sb_off_y);
825 
826 	hb_grid->add_child(memnew(VSeparator));
827 	hb_grid->add_child(memnew(Label(TTR("Step:"))));
828 
829 	sb_step_x = memnew(SpinBox);
830 	sb_step_x->set_min(-256);
831 	sb_step_x->set_max(256);
832 	sb_step_x->set_step(1);
833 	sb_step_x->set_val(snap_step.x);
834 	sb_step_x->set_suffix("px");
835 	sb_step_x->connect("value_changed", this, "_set_snap_step_x");
836 	hb_grid->add_child(sb_step_x);
837 
838 	sb_step_y = memnew(SpinBox);
839 	sb_step_y->set_min(-256);
840 	sb_step_y->set_max(256);
841 	sb_step_y->set_step(1);
842 	sb_step_y->set_val(snap_step.y);
843 	sb_step_y->set_suffix("px");
844 	sb_step_y->connect("value_changed", this, "_set_snap_step_y");
845 	hb_grid->add_child(sb_step_y);
846 
847 	hb_grid->add_child(memnew(VSeparator));
848 	hb_grid->add_child(memnew(Label(TTR("Separation:"))));
849 
850 	sb_sep_x = memnew(SpinBox);
851 	sb_sep_x->set_min(0);
852 	sb_sep_x->set_max(256);
853 	sb_sep_x->set_step(1);
854 	sb_sep_x->set_val(snap_separation.x);
855 	sb_sep_x->set_suffix("px");
856 	sb_sep_x->connect("value_changed", this, "_set_snap_sep_x");
857 	hb_grid->add_child(sb_sep_x);
858 
859 	sb_sep_y = memnew(SpinBox);
860 	sb_sep_y->set_min(0);
861 	sb_sep_y->set_max(256);
862 	sb_sep_y->set_step(1);
863 	sb_sep_y->set_val(snap_separation.y);
864 	sb_sep_y->set_suffix("px");
865 	sb_sep_y->connect("value_changed", this, "_set_snap_sep_y");
866 	hb_grid->add_child(sb_sep_y);
867 
868 	hb_grid->hide();
869 
870 	HBoxContainer *main_hb = memnew(HBoxContainer);
871 	main_vb->add_child(main_hb);
872 	edit_draw = memnew(Control);
873 	main_hb->add_child(edit_draw);
874 	main_hb->set_v_size_flags(SIZE_EXPAND_FILL);
875 	edit_draw->set_h_size_flags(SIZE_EXPAND_FILL);
876 
877 	Control *separator = memnew(Control);
878 	separator->set_h_size_flags(Control::SIZE_EXPAND_FILL);
879 	hb_tools->add_child(separator);
880 
881 	icon_zoom = memnew(TextureFrame);
882 	hb_tools->add_child(icon_zoom);
883 
884 	zoom_out = memnew(ToolButton);
885 	zoom_out->connect("pressed", this, "_zoom_out");
886 	hb_tools->add_child(zoom_out);
887 
888 	zoom_reset = memnew(ToolButton);
889 	zoom_reset->connect("pressed", this, "_zoom_reset");
890 	hb_tools->add_child(zoom_reset);
891 
892 	zoom_in = memnew(ToolButton);
893 	zoom_in->connect("pressed", this, "_zoom_in");
894 	hb_tools->add_child(zoom_in);
895 
896 	vscroll = memnew(VScrollBar);
897 	main_hb->add_child(vscroll);
898 	vscroll->connect("value_changed", this, "_scroll_changed");
899 	hscroll = memnew(HScrollBar);
900 	main_vb->add_child(hscroll);
901 	hscroll->connect("value_changed", this, "_scroll_changed");
902 
903 	edit_draw->connect("draw", this, "_region_draw");
904 	edit_draw->connect("input_event", this, "_region_input");
905 	draw_zoom = 1.0;
906 	updating_scroll = false;
907 }
908 
edit(Object * p_node)909 void TextureRegionEditorPlugin::edit(Object *p_node) {
910 	region_editor->edit(p_node);
911 }
912 
handles(Object * p_obj) const913 bool TextureRegionEditorPlugin::handles(Object *p_obj) const {
914 	return p_obj->is_type("Sprite") || p_obj->is_type("Patch9Frame") || p_obj->is_type("StyleBoxTexture") || p_obj->is_type("AtlasTexture");
915 }
916 
make_visible(bool p_visible)917 void TextureRegionEditorPlugin::make_visible(bool p_visible) {
918 	if (p_visible) {
919 		region_button->show();
920 		if (region_button->is_pressed())
921 			region_editor->show();
922 	} else {
923 		region_button->hide();
924 		region_editor->edit(NULL);
925 		region_editor->hide();
926 	}
927 }
928 
get_state() const929 Dictionary TextureRegionEditorPlugin::get_state() const {
930 
931 	Dictionary state;
932 	state["zoom"] = region_editor->draw_zoom;
933 	state["snap_offset"] = region_editor->snap_offset;
934 	state["snap_step"] = region_editor->snap_step;
935 	state["snap_separation"] = region_editor->snap_separation;
936 	state["snap_mode"] = region_editor->snap_mode;
937 	return state;
938 }
939 
set_state(const Dictionary & p_state)940 void TextureRegionEditorPlugin::set_state(const Dictionary &p_state) {
941 
942 	Dictionary state = p_state;
943 	if (state.has("zoom")) {
944 		region_editor->draw_zoom = p_state["zoom"];
945 	}
946 
947 	if (state.has("snap_step")) {
948 		Vector2 s = state["snap_step"];
949 		region_editor->sb_step_x->set_val(s.x);
950 		region_editor->sb_step_y->set_val(s.y);
951 		region_editor->snap_step = s;
952 	}
953 
954 	if (state.has("snap_offset")) {
955 		Vector2 ofs = state["snap_offset"];
956 		region_editor->sb_off_x->set_val(ofs.x);
957 		region_editor->sb_off_y->set_val(ofs.y);
958 		region_editor->snap_offset = ofs;
959 	}
960 
961 	if (state.has("snap_separation")) {
962 		Vector2 sep = state["snap_separation"];
963 		region_editor->sb_sep_x->set_val(sep.x);
964 		region_editor->sb_sep_y->set_val(sep.y);
965 		region_editor->snap_separation = sep;
966 	}
967 
968 	if (state.has("snap_mode")) {
969 		region_editor->_set_snap_mode(state["snap_mode"]);
970 	}
971 }
972 
TextureRegionEditorPlugin(EditorNode * p_node)973 TextureRegionEditorPlugin::TextureRegionEditorPlugin(EditorNode *p_node) {
974 	editor = p_node;
975 	region_editor = memnew(TextureRegionEditor(p_node));
976 
977 	region_button = p_node->add_bottom_panel_item(TTR("Texture Region"), region_editor);
978 	region_button->set_tooltip(TTR("Texture Region Editor"));
979 
980 	region_editor->set_custom_minimum_size(Size2(0, 200));
981 	region_editor->hide();
982 	region_button->hide();
983 }
984