Refactoring EditableCanvas in DrawboxEditable and other classes
This commit is contained in:
@ -1,7 +1,7 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<classpath>
|
<classpath>
|
||||||
<classpathentry kind="src" path="src"/>
|
<classpathentry kind="src" path="src"/>
|
||||||
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk-24">
|
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-22">
|
||||||
<attributes>
|
<attributes>
|
||||||
<attribute name="module" value="true"/>
|
<attribute name="module" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
eclipse.preferences.version=1
|
eclipse.preferences.version=1
|
||||||
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
||||||
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
|
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
|
||||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=15
|
org.eclipse.jdt.core.compiler.codegen.targetPlatform=22
|
||||||
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
|
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
|
||||||
org.eclipse.jdt.core.compiler.compliance=23
|
org.eclipse.jdt.core.compiler.compliance=22
|
||||||
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
|
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
|
||||||
org.eclipse.jdt.core.compiler.debug.localVariable=generate
|
org.eclipse.jdt.core.compiler.debug.localVariable=generate
|
||||||
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
|
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
|
||||||
@ -12,4 +12,4 @@ org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
|
|||||||
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
|
||||||
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
|
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
|
||||||
org.eclipse.jdt.core.compiler.release=enabled
|
org.eclipse.jdt.core.compiler.release=enabled
|
||||||
org.eclipse.jdt.core.compiler.source=15
|
org.eclipse.jdt.core.compiler.source=22
|
||||||
|
|||||||
BIN
res/NewName.png
Normal file
BIN
res/NewName.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
BIN
res/newtest.png
Normal file
BIN
res/newtest.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 98 KiB |
@ -20,4 +20,9 @@
|
|||||||
<property default="3 2 252 1 253 605 6 608" name="drawbox" type="string"/>
|
<property default="3 2 252 1 253 605 6 608" name="drawbox" type="string"/>
|
||||||
<property default="Rectangle 0 0 96 98" name="hitbox" type="string"/>
|
<property default="Rectangle 0 0 96 98" name="hitbox" type="string"/>
|
||||||
</objecttype>
|
</objecttype>
|
||||||
|
<objecttype color="000000" name="newtest">
|
||||||
|
<property default="solid" name="class" type="string"/>
|
||||||
|
<property default="0 0 0 0 0 0 0 0" name="drawbox" type="string"/>
|
||||||
|
<property default="Rectangle 0 0 0 0" name="hitbox" type="string"/>
|
||||||
|
</objecttype>
|
||||||
</objecttypes>
|
</objecttypes>
|
||||||
|
|||||||
18
src/events/EntityHitboxChangedEvent.java
Normal file
18
src/events/EntityHitboxChangedEvent.java
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package events;
|
||||||
|
|
||||||
|
import model.Entity;
|
||||||
|
import model.Hitbox;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Structure-like class no getters
|
||||||
|
*/
|
||||||
|
public class EntityHitboxChangedEvent {
|
||||||
|
public Hitbox hitbox;
|
||||||
|
//storing entity object instead of just entity name will allow to get entity data without extra calls
|
||||||
|
public Entity owner;
|
||||||
|
|
||||||
|
public EntityHitboxChangedEvent(Hitbox hitbox, Entity owner) {
|
||||||
|
this.hitbox = hitbox;
|
||||||
|
this.owner = owner;
|
||||||
|
}
|
||||||
|
}
|
||||||
7
src/events/EntityHitboxChangedListener.java
Normal file
7
src/events/EntityHitboxChangedListener.java
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package events;
|
||||||
|
|
||||||
|
public interface EntityHitboxChangedListener {
|
||||||
|
|
||||||
|
void hitboxChanged(EntityHitboxChangedEvent event);
|
||||||
|
|
||||||
|
}
|
||||||
@ -1,5 +0,0 @@
|
|||||||
package gui;
|
|
||||||
|
|
||||||
public class CircleRenderingFunction implements ShapeRenderingFunction {
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,5 +1,6 @@
|
|||||||
package gui;
|
package gui;
|
||||||
|
|
||||||
|
import java.awt.BorderLayout;
|
||||||
import java.awt.Color;
|
import java.awt.Color;
|
||||||
import java.awt.Graphics2D;
|
import java.awt.Graphics2D;
|
||||||
import java.awt.event.ActionEvent;
|
import java.awt.event.ActionEvent;
|
||||||
@ -16,146 +17,48 @@ import javax.swing.JTabbedPane;
|
|||||||
|
|
||||||
import events.EntityDrawboxChangedEvent;
|
import events.EntityDrawboxChangedEvent;
|
||||||
import events.EntityDrawboxChangedListener;
|
import events.EntityDrawboxChangedListener;
|
||||||
|
import gui.render.DrawboxRectengleRenderingFunction;
|
||||||
import model.Drawbox;
|
import model.Drawbox;
|
||||||
import model.Point;
|
import model.Point;
|
||||||
import repository.Project;
|
import repository.Project;
|
||||||
|
|
||||||
public class DrawboxEditor extends Editable {
|
public class DrawboxEditor extends Editable {
|
||||||
|
|
||||||
private List<Point> drawboxPoints;
|
|
||||||
private List<Point> basePoints;
|
|
||||||
Logger logger = Logger.getLogger("gui.DrawboxRectangleEditor");
|
Logger logger = Logger.getLogger("gui.DrawboxRectangleEditor");
|
||||||
Point currentPoint = new Point(0, 0);
|
|
||||||
private List<EntityDrawboxChangedListener> listeners = new ArrayList<>();
|
|
||||||
|
|
||||||
|
|
||||||
DrawboxEditor(ListGUI listGUI) {
|
DrawboxEditor(ListGUI listGUI) {
|
||||||
super(listGUI);
|
super(listGUI);
|
||||||
|
//Если будет ошибка, попробовать в Editable прокинуть canvas, как сделано с ListGUI
|
||||||
|
canvas = new EditableCanvas(entity, image);
|
||||||
|
add(canvas,BorderLayout.CENTER);
|
||||||
|
canvas.setBackground(Color.GRAY);
|
||||||
|
canvas.setDrawboxRectengleRenderingFunction();
|
||||||
|
canvas.setVisible(true);
|
||||||
logger.setLevel(Level.CONFIG);
|
logger.setLevel(Level.CONFIG);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void drawing(Graphics2D g) {
|
|
||||||
Drawbox drawbox = entity.getDrawbox();
|
|
||||||
drawboxPoints = drawbox.getDrawboxlistPoints();
|
|
||||||
basePoints = drawbox.getbaseListPoints();
|
|
||||||
logger.finest("drawbox point size: "+ drawboxPoints.size());
|
|
||||||
for(Point p: drawboxPoints)
|
|
||||||
logger.finest("DrawBoxPoint: ["+ p.x + ":"+p.y+"]");
|
|
||||||
for(Point p: basePoints)
|
|
||||||
logger.finest("BasePoint: ["+ p.x + ":"+p.y+"]");
|
|
||||||
|
|
||||||
if(drawboxPoints.size() >= 1 && drawboxPoints.size() < 4) {
|
|
||||||
Point lastPoint = drawboxPoints.get(drawboxPoints.size()-1);
|
|
||||||
g.drawLine((int)lastPoint.x, (int)lastPoint.y, (int)currentPoint.x, (int)currentPoint.y);
|
|
||||||
for(int i = 0; i < drawboxPoints.size()-1;i++) {
|
|
||||||
int x1 = (int)drawboxPoints.get(i).x;
|
|
||||||
int y1 = (int)drawboxPoints.get(i).y;
|
|
||||||
int x2 = (int)drawboxPoints.get(i+1).x;
|
|
||||||
int y2 = (int)drawboxPoints.get(i+1).y;
|
|
||||||
g.drawLine(x1, y1, x2, y2);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for(int i = 0; i < drawboxPoints.size();i++) {
|
|
||||||
int x1 = (int)drawboxPoints.get(i % drawboxPoints.size()).x;
|
|
||||||
int y1 = (int)drawboxPoints.get(i % drawboxPoints.size()).y;
|
|
||||||
int x2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).x;
|
|
||||||
int y2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).y;
|
|
||||||
g.drawLine(x1, y1, x2, y2);
|
|
||||||
}
|
|
||||||
// ОТРИСОВКА ОСНОВАНИЯ
|
|
||||||
g.setColor(Color.BLUE);
|
|
||||||
for(int i = 0; i < basePoints.size()-1;i++) {
|
|
||||||
int x1 = (int)basePoints.get(i).x;
|
|
||||||
int y1 = (int)basePoints.get(i).y;
|
|
||||||
int x2 = (int)basePoints.get(i+1).x;
|
|
||||||
int y2 = (int)basePoints.get(i+1).y;
|
|
||||||
g.drawLine(x1, y1+3, x2, y2+3);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void saveDataInEntity() {
|
|
||||||
entity.setDrawbox(new Drawbox(drawboxPoints));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void mousePressed(MouseEvent e) {
|
public void mousePressed(MouseEvent e) {
|
||||||
|
|
||||||
if(drawboxPoints.size() < 4) {
|
|
||||||
Point p = new Point(e.getX(), e.getY());
|
|
||||||
drawboxPoints.add(p);
|
|
||||||
if(drawboxPoints.size() == 4) {
|
|
||||||
sortingDrawboxPoints();
|
|
||||||
saveDataInEntity();
|
|
||||||
//при выборе 4-й точки и формировании данных drawbox, уведомляем всех подписчит
|
|
||||||
if(listeners!=null) {
|
|
||||||
notifySubscribers();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/*Точки должны идти в определенном порядке:
|
|
||||||
* левая верхняя точка, правая верхняя, нижняя правая, нижняя левая;
|
|
||||||
* Обе нижние точки, т.е. 3 и 4 являются основанием - хардкод.
|
|
||||||
* P.s. возможно это не критично, и в сторе предусмотрено, что бы они сортировались,
|
|
||||||
* но на данном этапе на всякий случай стоит так поступить*/
|
|
||||||
private void sortingDrawboxPoints() {
|
|
||||||
//окей, это написано плохо, но... Похуй, пляшем)
|
|
||||||
Collections.sort(
|
|
||||||
drawboxPoints,
|
|
||||||
(point1, point2) -> Float.compare(point1.y, point2.y)
|
|
||||||
);
|
|
||||||
if(drawboxPoints.get(0).x>drawboxPoints.get(1).x) {
|
|
||||||
Collections.swap(drawboxPoints, 0, 1);
|
|
||||||
}
|
|
||||||
if(drawboxPoints.get(2).x<drawboxPoints.get(3).x) {
|
|
||||||
Collections.swap(drawboxPoints, 2, 3);
|
|
||||||
}
|
|
||||||
/*Багтест, проверка очередности построения точек
|
|
||||||
*
|
|
||||||
* System.out.println("_______________");
|
|
||||||
int i = 0;
|
|
||||||
for (Point point : drawboxPoints) {
|
|
||||||
System.out.println("Point["+i+"]: ("+point.x+" ; "+point.y+");");
|
|
||||||
i++;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void mouseMoved(MouseEvent e) {
|
public void mouseMoved(MouseEvent e) {
|
||||||
currentPoint.x = e.getX();
|
|
||||||
currentPoint.y = e.getY();
|
|
||||||
repaint();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public void subscribe(EntityDrawboxChangedListener listener) {
|
|
||||||
listeners.add(listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void unsubscribe(EntityDrawboxChangedListener listener) {
|
|
||||||
listeners.remove(listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void notifySubscribers() {
|
|
||||||
for (EntityDrawboxChangedListener listener : listeners) {
|
|
||||||
listener.drawboxChanged(
|
|
||||||
new EntityDrawboxChangedEvent(entity.getDrawbox(), entity)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public void clearPoints(){
|
public void clearPoints(){
|
||||||
|
|
||||||
}
|
}
|
||||||
// эта штука очищает точки при нажатии универскальной кнопки очистки в Main GUI. Это следует рефакторнуть и вместо передачи события сюда,
|
// эта штука очищает точки при нажатии универскальной кнопки очистки в Main GUI. Это следует рефакторнуть и вместо передачи события сюда,
|
||||||
// обрабатывать его прямо в Main GUI(лямбдой) вызывая отсюда только метод в духе clearPoints()
|
// обрабатывать его прямо в Main GUI(лямбдой) вызывая отсюда только метод в духе clearPoints()
|
||||||
@Override
|
/*@Override
|
||||||
public void actionPerformed(ActionEvent e) {
|
public void actionPerformed(ActionEvent e) {
|
||||||
JTabbedPane parent = (JTabbedPane) getParent();
|
JTabbedPane parent = (JTabbedPane) getParent();
|
||||||
if(parent.getSelectedComponent() == this){
|
if(parent.getSelectedComponent() == this){
|
||||||
@ -165,6 +68,7 @@ public class DrawboxEditor extends Editable {
|
|||||||
repaint();
|
repaint();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}*/
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
package gui;
|
package gui;
|
||||||
|
|
||||||
|
import java.awt.Dimension;
|
||||||
import java.awt.Graphics;
|
import java.awt.Graphics;
|
||||||
import java.awt.Graphics2D;
|
import java.awt.Graphics2D;
|
||||||
import java.awt.event.ActionListener;
|
import java.awt.event.ActionListener;
|
||||||
@ -10,6 +11,8 @@ import java.awt.image.BufferedImage;
|
|||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import javax.swing.ImageIcon;
|
||||||
|
import javax.swing.JButton;
|
||||||
import javax.swing.JList;
|
import javax.swing.JList;
|
||||||
import javax.swing.JPanel;
|
import javax.swing.JPanel;
|
||||||
import javax.swing.event.ListSelectionEvent;
|
import javax.swing.event.ListSelectionEvent;
|
||||||
@ -18,7 +21,7 @@ import javax.swing.event.ListSelectionListener;
|
|||||||
import model.Entity;
|
import model.Entity;
|
||||||
import repository.Project;
|
import repository.Project;
|
||||||
|
|
||||||
public abstract class Editable extends JPanel implements MouseListener, MouseMotionListener, ListSelectionListener, ActionListener {
|
public abstract class Editable extends JPanel implements MouseListener, MouseMotionListener, ListSelectionListener {
|
||||||
|
|
||||||
protected ListGUI listGUI;
|
protected ListGUI listGUI;
|
||||||
protected Entity entity;
|
protected Entity entity;
|
||||||
@ -40,9 +43,7 @@ public abstract class Editable extends JPanel implements MouseListener, MouseMot
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public abstract void drawing(Graphics2D g);
|
|
||||||
public abstract void saveDataInEntity();
|
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return selectedEntityName;
|
return selectedEntityName;
|
||||||
}
|
}
|
||||||
@ -55,14 +56,7 @@ public abstract class Editable extends JPanel implements MouseListener, MouseMot
|
|||||||
entity = Project.getInstance().getEntityByName(name);
|
entity = Project.getInstance().getEntityByName(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void paintComponent(Graphics g) {
|
|
||||||
super.paintComponent(g);
|
|
||||||
g.drawImage(image, 0, 0, this);
|
|
||||||
if(entity != null) {
|
|
||||||
drawing((Graphics2D)g);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// из mouse motion listener'a
|
// из mouse motion listener'a
|
||||||
@Override
|
@Override
|
||||||
@ -96,8 +90,21 @@ public abstract class Editable extends JPanel implements MouseListener, MouseMot
|
|||||||
}
|
}
|
||||||
image = Project.getInstance().loadImageByName(selectedEntityName);
|
image = Project.getInstance().loadImageByName(selectedEntityName);
|
||||||
//TODO: if(image == null) вызов FileChooser'a и выбор изображения
|
//TODO: if(image == null) вызов FileChooser'a и выбор изображения
|
||||||
|
|
||||||
this.repaint();
|
this.repaint();
|
||||||
|
//canvas.repaint();
|
||||||
|
System.out.println(" Edit image = " + image);
|
||||||
|
System.out.println("---");
|
||||||
|
System.out.println(" Canvas image = " + image);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private JButton createButton(String text,ActionListener listener,String pathImage) {
|
||||||
|
JButton button = new JButton(new ImageIcon(pathImage));
|
||||||
|
button.addActionListener(listener);
|
||||||
|
button.setContentAreaFilled(false);
|
||||||
|
button.setFocusPainted(false);
|
||||||
|
button.setPreferredSize(new Dimension(72, 38));
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,96 @@
|
|||||||
package gui;
|
package gui;
|
||||||
|
|
||||||
import javax.swing.JPanel;
|
import java.awt.Graphics;
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.event.MouseEvent;
|
||||||
|
import java.awt.event.MouseListener;
|
||||||
|
import java.awt.event.MouseMotionListener;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
|
||||||
|
import javax.swing.JPanel;
|
||||||
|
import javax.swing.event.ListSelectionEvent;
|
||||||
|
import javax.swing.event.ListSelectionListener;
|
||||||
|
|
||||||
|
import gui.render.DrawboxRectengleRenderingFunction;
|
||||||
|
import gui.render.ShapeRenderingFunction;
|
||||||
|
import model.Entity;
|
||||||
|
import repository.Project;
|
||||||
|
|
||||||
|
public class EditableCanvas extends JPanel implements MouseListener, MouseMotionListener, ListSelectionListener {
|
||||||
|
|
||||||
|
DrawboxRectengleRenderingFunction drawboxRectengleRenderFunct;
|
||||||
|
ShapeRenderingFunction renderingFunction;
|
||||||
|
Entity entity;
|
||||||
|
BufferedImage image;
|
||||||
|
|
||||||
|
|
||||||
|
public EditableCanvas(Entity entity, BufferedImage image) {
|
||||||
|
this.entity = entity;
|
||||||
|
this.image = image;
|
||||||
|
drawboxRectengleRenderFunct = new DrawboxRectengleRenderingFunction(entity);
|
||||||
|
drawboxRectengleRenderFunct.subscribe(Project.getInstance()); // подписка: Project получит данные ввиде обьекта Event, содержащий данные drawbox при отрисовке последней точки из 4-х.
|
||||||
|
//hitboxPanel.subscribe(Project.getInstance());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public void drawing(Graphics2D g) {
|
||||||
|
if(renderingFunction!=null) {
|
||||||
|
renderingFunction.drawing(g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDrawboxRectengleRenderingFunction() {
|
||||||
|
renderingFunction = drawboxRectengleRenderFunct;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseMoved(MouseEvent e) {
|
||||||
|
if(renderingFunction!=null) {
|
||||||
|
renderingFunction.mouseMoved(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseClicked(MouseEvent e) {
|
||||||
|
if(renderingFunction!=null) {
|
||||||
|
renderingFunction.mouseClicked(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mousePressed(MouseEvent e) {
|
||||||
|
if(renderingFunction!=null) {
|
||||||
|
renderingFunction.mousePressed(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void paintComponent(Graphics g) {
|
||||||
|
super.paintComponent(g);
|
||||||
|
g.drawImage(image, 0, 0, this);
|
||||||
|
if(entity != null) {
|
||||||
|
drawing((Graphics2D)g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseDragged(MouseEvent e) {}
|
||||||
|
@Override
|
||||||
|
public void mouseReleased(MouseEvent e) {}
|
||||||
|
@Override
|
||||||
|
public void mouseEntered(MouseEvent e) {}
|
||||||
|
@Override
|
||||||
|
public void mouseExited(MouseEvent e) {}
|
||||||
|
@Override
|
||||||
|
public void valueChanged(ListSelectionEvent e) {
|
||||||
|
//this.repaint();
|
||||||
|
//System.out.println(" Canvas image = " + image);
|
||||||
|
}
|
||||||
|
|
||||||
public class EditableCanvas extends JPanel {
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,9 +3,15 @@ package gui;
|
|||||||
import java.awt.Graphics2D;
|
import java.awt.Graphics2D;
|
||||||
import java.awt.event.ActionEvent;
|
import java.awt.event.ActionEvent;
|
||||||
import java.awt.event.MouseEvent;
|
import java.awt.event.MouseEvent;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import javax.swing.JTabbedPane;
|
import javax.swing.JTabbedPane;
|
||||||
|
|
||||||
|
import events.EntityDrawboxChangedEvent;
|
||||||
|
import events.EntityDrawboxChangedListener;
|
||||||
|
import events.EntityHitboxChangedEvent;
|
||||||
|
import events.EntityHitboxChangedListener;
|
||||||
import model.Hitbox;
|
import model.Hitbox;
|
||||||
import model.Point;
|
import model.Point;
|
||||||
|
|
||||||
@ -14,13 +20,13 @@ public class HitboxEditor extends Editable {
|
|||||||
Point firstIsoPoint = null;
|
Point firstIsoPoint = null;
|
||||||
Point currentIsoPoint = new Point(0,0);
|
Point currentIsoPoint = new Point(0,0);
|
||||||
Point firstCartesianPoint = new Point(0,0), currentCartesianPoint = new Point(0,0);
|
Point firstCartesianPoint = new Point(0,0), currentCartesianPoint = new Point(0,0);
|
||||||
|
private List<EntityHitboxChangedListener> listeners = new ArrayList<>();
|
||||||
HitboxEditor(ListGUI listGUI) {
|
HitboxEditor(ListGUI listGUI) {
|
||||||
super(listGUI);
|
super(listGUI);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
//@Override
|
||||||
public void drawing(Graphics2D g) {
|
//public void drawing(Graphics2D g) {
|
||||||
/*Hitbox nowHitbox = entity.getHitbox();
|
/*Hitbox nowHitbox = entity.getHitbox();
|
||||||
//if(firstIsoPoint != null) {
|
//if(firstIsoPoint != null) {
|
||||||
int x1,y1,x2,y2;
|
int x1,y1,x2,y2;
|
||||||
@ -39,14 +45,8 @@ public class HitboxEditor extends Editable {
|
|||||||
g.drawLine(x1, y1, x2, y2);
|
g.drawLine(x1, y1, x2, y2);
|
||||||
//}
|
//}
|
||||||
*/
|
*/
|
||||||
}
|
//}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void saveDataInEntity() {
|
|
||||||
// saveDataInEntity - сохранение данных в сущности.
|
|
||||||
//Она нам тут не нужна.
|
|
||||||
//Все данные и так лежат где необходимо, используя ссылки.
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void mouseClicked(MouseEvent e) {
|
public void mouseClicked(MouseEvent e) {
|
||||||
@ -85,8 +85,28 @@ public class HitboxEditor extends Editable {
|
|||||||
}
|
}
|
||||||
}*/
|
}*/
|
||||||
}
|
}
|
||||||
|
public void subscribe(EntityHitboxChangedListener listener) {
|
||||||
@Override
|
listeners.add(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unsubscribe(EntityHitboxChangedListener listener) {
|
||||||
|
listeners.remove(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
//НАДО ДОБАВИТЬ ЧТО БЫ ПОД КОНЕЦ РИСОВАНИЯ ХИТБОКСА ОНО ВЫЗЫВАЛО ФУНКЦИЮ И ВСЕ СОХРАНЯЛО.
|
||||||
|
//СОХРАНЕНИЕ УЖЕ РЕАЛИЗОВАНО.
|
||||||
|
//НО НЕ ДОБАВЛЕН ВЫЗОВ ФУНКЦИИ И НЕ ОФОРМЛЕНА ПОДПИСКА
|
||||||
|
//UPD: вроде подписку оформил в MainGUI;
|
||||||
|
|
||||||
|
private void notifySubscribers() {
|
||||||
|
for (EntityHitboxChangedListener listener : listeners) {
|
||||||
|
listener.hitboxChanged(
|
||||||
|
new EntityHitboxChangedEvent(entity.getHitbox(), entity)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//это старая очистка которая пока убрана. В будущем будет убрана вовсе, после рефакторинга.
|
||||||
|
/*@Override
|
||||||
public void actionPerformed(ActionEvent e) {
|
public void actionPerformed(ActionEvent e) {
|
||||||
JTabbedPane parent = (JTabbedPane) getParent();
|
JTabbedPane parent = (JTabbedPane) getParent();
|
||||||
if(parent.getSelectedComponent() == this){
|
if(parent.getSelectedComponent() == this){
|
||||||
@ -96,7 +116,7 @@ public class HitboxEditor extends Editable {
|
|||||||
repaint();
|
repaint();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}*/
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -43,7 +43,7 @@ public class MainGUI extends JFrame{
|
|||||||
|
|
||||||
drawBoxPanel = new DrawboxEditor(list);
|
drawBoxPanel = new DrawboxEditor(list);
|
||||||
hitboxPanel = new HitboxEditor(list);
|
hitboxPanel = new HitboxEditor(list);
|
||||||
list.registerJListListener(drawBoxPanel);
|
list.registerJListListener(drawBoxPanel);
|
||||||
list.registerJListListener(hitboxPanel);
|
list.registerJListListener(hitboxPanel);
|
||||||
|
|
||||||
OpenXMLFileButtonListener = new OpenXMLFileButtonListener(list);
|
OpenXMLFileButtonListener = new OpenXMLFileButtonListener(list);
|
||||||
@ -59,8 +59,8 @@ public class MainGUI extends JFrame{
|
|||||||
TopButtonBar.setBorder(BorderFactory.createLoweredBevelBorder());
|
TopButtonBar.setBorder(BorderFactory.createLoweredBevelBorder());
|
||||||
add(TopButtonBar,BorderLayout.NORTH);
|
add(TopButtonBar,BorderLayout.NORTH);
|
||||||
|
|
||||||
clearLinesJButton.addActionListener(drawBoxPanel);
|
//clearLinesJButton.addActionListener(drawBoxPanel); - ранее регистрировались слушатели для кнопки очистки.
|
||||||
clearLinesJButton.addActionListener(hitboxPanel);
|
//clearLinesJButton.addActionListener(hitboxPanel);
|
||||||
|
|
||||||
|
|
||||||
editorPane = new JTabbedPane();
|
editorPane = new JTabbedPane();
|
||||||
@ -70,8 +70,7 @@ public class MainGUI extends JFrame{
|
|||||||
editorPane.addTab("Hitbox", hitboxPanel);
|
editorPane.addTab("Hitbox", hitboxPanel);
|
||||||
editorPane.addTab("Drawbox", drawBoxPanel);
|
editorPane.addTab("Drawbox", drawBoxPanel);
|
||||||
repaint();
|
repaint();
|
||||||
drawBoxPanel.subscribe(Project.getInstance()); // подписка: Project получит данные ввиде обьекта Event, содержащий данные drawbox при отрисовке последней точки из 4-х.
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@Override
|
@Override
|
||||||
public void paint(Graphics g){
|
public void paint(Graphics g){
|
||||||
|
|||||||
@ -1,5 +0,0 @@
|
|||||||
package gui;
|
|
||||||
|
|
||||||
public class RectengleRenderingFunction implements ShapeRenderingFunction {
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
package gui;
|
|
||||||
|
|
||||||
public interface ShapeRenderingFunction {
|
|
||||||
|
|
||||||
}
|
|
||||||
150
src/gui/render/DrawboxRectengleRenderingFunction.java
Normal file
150
src/gui/render/DrawboxRectengleRenderingFunction.java
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
package gui.render;
|
||||||
|
|
||||||
|
import java.awt.Color;
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.event.MouseEvent;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import events.EntityDrawboxChangedEvent;
|
||||||
|
import events.EntityDrawboxChangedListener;
|
||||||
|
import model.Drawbox;
|
||||||
|
import model.Entity;
|
||||||
|
import model.Point;
|
||||||
|
|
||||||
|
public class DrawboxRectengleRenderingFunction implements ShapeRenderingFunction {
|
||||||
|
private List<Point> drawboxPoints;
|
||||||
|
private List<Point> basePoints;
|
||||||
|
Point currentPoint = new Point(0, 0);
|
||||||
|
private List<EntityDrawboxChangedListener> listeners = new ArrayList<>();
|
||||||
|
Entity entity;
|
||||||
|
Logger logger = Logger.getLogger("gui.DrawboxRectangleEditor");
|
||||||
|
public DrawboxRectengleRenderingFunction(Entity entity) {
|
||||||
|
this.entity = entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawing(Graphics2D g) {
|
||||||
|
Drawbox drawbox = entity.getDrawbox();
|
||||||
|
drawboxPoints = drawbox.getDrawboxlistPoints();
|
||||||
|
basePoints = drawbox.getbaseListPoints();
|
||||||
|
logger.finest("drawbox point size: "+ drawboxPoints.size());
|
||||||
|
for(Point p: drawboxPoints)
|
||||||
|
logger.finest("DrawBoxPoint: ["+ p.x + ":"+p.y+"]");
|
||||||
|
for(Point p: basePoints)
|
||||||
|
logger.finest("BasePoint: ["+ p.x + ":"+p.y+"]");
|
||||||
|
|
||||||
|
if(drawboxPoints.size() >= 1 && drawboxPoints.size() < 4) {
|
||||||
|
Point lastPoint = drawboxPoints.get(drawboxPoints.size()-1);
|
||||||
|
g.drawLine((int)lastPoint.x, (int)lastPoint.y, (int)currentPoint.x, (int)currentPoint.y);
|
||||||
|
for(int i = 0; i < drawboxPoints.size()-1;i++) {
|
||||||
|
int x1 = (int)drawboxPoints.get(i).x;
|
||||||
|
int y1 = (int)drawboxPoints.get(i).y;
|
||||||
|
int x2 = (int)drawboxPoints.get(i+1).x;
|
||||||
|
int y2 = (int)drawboxPoints.get(i+1).y;
|
||||||
|
g.drawLine(x1, y1, x2, y2);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for(int i = 0; i < drawboxPoints.size();i++) {
|
||||||
|
int x1 = (int)drawboxPoints.get(i % drawboxPoints.size()).x;
|
||||||
|
int y1 = (int)drawboxPoints.get(i % drawboxPoints.size()).y;
|
||||||
|
int x2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).x;
|
||||||
|
int y2 = (int)drawboxPoints.get((i+1) % drawboxPoints.size()).y;
|
||||||
|
g.drawLine(x1, y1, x2, y2);
|
||||||
|
}
|
||||||
|
// ОТРИСОВКА ОСНОВАНИЯ
|
||||||
|
g.setColor(Color.BLUE);
|
||||||
|
for(int i = 0; i < basePoints.size()-1;i++) {
|
||||||
|
int x1 = (int)basePoints.get(i).x;
|
||||||
|
int y1 = (int)basePoints.get(i).y;
|
||||||
|
int x2 = (int)basePoints.get(i+1).x;
|
||||||
|
int y2 = (int)basePoints.get(i+1).y;
|
||||||
|
g.drawLine(x1, y1+3, x2, y2+3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mousePressed(MouseEvent e) {
|
||||||
|
if(drawboxPoints.size() < 4) {
|
||||||
|
Point p = new Point(e.getX(), e.getY());
|
||||||
|
drawboxPoints.add(p);
|
||||||
|
if(drawboxPoints.size() == 4) {
|
||||||
|
sortingDrawboxPoints();
|
||||||
|
saveDataInEntity();
|
||||||
|
//при выборе 4-й точки и формировании данных drawbox, уведомляем всех подписчит
|
||||||
|
if(listeners!=null) {
|
||||||
|
notifySubscribers();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseClicked(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseMoved(MouseEvent e) {
|
||||||
|
currentPoint.x = e.getX();
|
||||||
|
currentPoint.y = e.getY();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*Точки должны идти в определенном порядке:
|
||||||
|
* левая верхняя точка, правая верхняя, нижняя правая, нижняя левая;
|
||||||
|
* Обе нижние точки, т.е. 3 и 4 являются основанием - хардкод.
|
||||||
|
* P.s. возможно это не критично, и в сторе предусмотрено, что бы они сортировались,
|
||||||
|
* но на данном этапе на всякий случай стоит так поступить*/
|
||||||
|
private void sortingDrawboxPoints() {
|
||||||
|
//окей, это написано плохо, но... Похуй, пляшем)
|
||||||
|
Collections.sort(
|
||||||
|
drawboxPoints,
|
||||||
|
(point1, point2) -> Float.compare(point1.y, point2.y)
|
||||||
|
);
|
||||||
|
if(drawboxPoints.get(0).x>drawboxPoints.get(1).x) {
|
||||||
|
Collections.swap(drawboxPoints, 0, 1);
|
||||||
|
}
|
||||||
|
if(drawboxPoints.get(2).x<drawboxPoints.get(3).x) {
|
||||||
|
Collections.swap(drawboxPoints, 2, 3);
|
||||||
|
}
|
||||||
|
/*Багтест, проверка очередности построения точек
|
||||||
|
*
|
||||||
|
* System.out.println("_______________");
|
||||||
|
int i = 0;
|
||||||
|
for (Point point : drawboxPoints) {
|
||||||
|
System.out.println("Point["+i+"]: ("+point.x+" ; "+point.y+");");
|
||||||
|
i++;
|
||||||
|
}*/
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void subscribe(EntityDrawboxChangedListener listener) {
|
||||||
|
listeners.add(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unsubscribe(EntityDrawboxChangedListener listener) {
|
||||||
|
listeners.remove(listener);
|
||||||
|
}
|
||||||
|
//
|
||||||
|
private void notifySubscribers() {
|
||||||
|
for (EntityDrawboxChangedListener listener : listeners) {
|
||||||
|
listener.drawboxChanged(
|
||||||
|
new EntityDrawboxChangedEvent(entity.getDrawbox(), entity)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void saveDataInEntity() {
|
||||||
|
entity.setDrawbox(new Drawbox(drawboxPoints));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
32
src/gui/render/HitboxCircleRenderingFunction.java
Normal file
32
src/gui/render/HitboxCircleRenderingFunction.java
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package gui.render;
|
||||||
|
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.event.MouseEvent;
|
||||||
|
|
||||||
|
public class HitboxCircleRenderingFunction implements ShapeRenderingFunction {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawing(Graphics2D g) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mousePressed(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseClicked(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseMoved(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
32
src/gui/render/HitboxRectengleRenderingFunction.java
Normal file
32
src/gui/render/HitboxRectengleRenderingFunction.java
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package gui.render;
|
||||||
|
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.event.MouseEvent;
|
||||||
|
|
||||||
|
public class HitboxRectengleRenderingFunction implements ShapeRenderingFunction {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawing(Graphics2D g) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mousePressed(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseClicked(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mouseMoved(MouseEvent e) {
|
||||||
|
// TODO Auto-generated method stub
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
12
src/gui/render/ShapeRenderingFunction.java
Normal file
12
src/gui/render/ShapeRenderingFunction.java
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package gui.render;
|
||||||
|
|
||||||
|
import java.awt.Graphics2D;
|
||||||
|
import java.awt.event.MouseEvent;
|
||||||
|
|
||||||
|
public interface ShapeRenderingFunction {
|
||||||
|
void drawing(Graphics2D g);
|
||||||
|
public void mousePressed(MouseEvent e);
|
||||||
|
public void mouseClicked(MouseEvent e);
|
||||||
|
public void mouseMoved(MouseEvent e);
|
||||||
|
//private void notifySubscribers() ?? надо ли? подумать
|
||||||
|
}
|
||||||
@ -46,16 +46,20 @@ public class Drawbox {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Возвращает все точки дравбокса через пробел.
|
/* @Override
|
||||||
@Override
|
|
||||||
public String toString() {
|
public String toString() {
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
//Возвращает все точки дравбокса через пробел.
|
||||||
|
public String listPointsToString() {
|
||||||
String stringDrawbox="";
|
String stringDrawbox="";
|
||||||
for (Point point : drawboxlistPoints) {
|
for (Point point : drawboxlistPoints) {
|
||||||
stringDrawbox+=((int)point.x)+" "+((int)point.y)+" "; //(int) because it is for XML
|
stringDrawbox+=((int)point.x)+" "+((int)point.y)+" "; //(int) because it is for XML
|
||||||
}
|
}
|
||||||
return stringDrawbox;
|
return stringDrawbox;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public List<Point> getDrawboxlistPoints() {
|
public List<Point> getDrawboxlistPoints() {
|
||||||
return drawboxlistPoints;
|
return drawboxlistPoints;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,14 +15,21 @@ public class Entity {
|
|||||||
thisName = new String(name);
|
thisName = new String(name);
|
||||||
thisDrawbox = new Drawbox(drawbox);
|
thisDrawbox = new Drawbox(drawbox);
|
||||||
setImage(sprite); // updates entity width and height, should be called before creating hitbox
|
setImage(sprite); // updates entity width and height, should be called before creating hitbox
|
||||||
thisHitbox = new Hitbox(hitbox,this);
|
if(hitbox != null) {
|
||||||
|
String[] dataHitbox = hitbox.split(" ");
|
||||||
|
System.out.println("Создается обьект /"+name+"/. Shape Hitbox = /"+dataHitbox[0]+"/. Размер dataHitbox = /"+dataHitbox.length+"/.");
|
||||||
|
if(dataHitbox[0].equals("Rectangle")) {
|
||||||
|
thisHitbox = new HitboxRectangle(dataHitbox,this);
|
||||||
|
}else if(dataHitbox[0].equals("Circle")) {
|
||||||
|
thisHitbox = new HitboxCircle(dataHitbox,this);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
// при добавлении новой сущности по умолчанию создается у нее прямоугольный хитбокс
|
||||||
public Entity(String name) {
|
public Entity(String name) {
|
||||||
this.thisName = name;
|
this.thisName = name;
|
||||||
this.thisHitbox = new Hitbox();
|
this.thisHitbox = new HitboxRectangle("Rectangle",this);
|
||||||
this.thisDrawbox = new Drawbox();
|
this.thisDrawbox = new Drawbox();
|
||||||
thisHitbox.setOwnerEntity(this);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String outName) {
|
public void setName(String outName) {
|
||||||
|
|||||||
@ -3,34 +3,35 @@ package model;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class Hitbox {
|
public abstract class Hitbox {
|
||||||
String shape = null;// shape - Форма хитбокса. Понадобится при написании сохранения. Один из параметров в xml-file.
|
String shape = null;// shape - Форма хитбокса. Понадобится при написании сохранения. Один из параметров в xml-file.
|
||||||
Point referencePoint = new Point(0, 0); //Точка отсчета хитбокса, от нее рассчитывается высота+ширина/радиус(при круге) хитбокса.
|
Point referencePoint = new Point(0, 0); //Точка отсчета хитбокса, от нее рассчитывается высота+ширина/радиус(при круге) хитбокса.
|
||||||
Entity owner;
|
Entity owner;
|
||||||
|
|
||||||
public Hitbox(){
|
public Hitbox(){
|
||||||
}
|
}
|
||||||
|
//Либо так передавать shape, либо создать setShape. Но по сути shape определяется при создании обьекта, и тогда set - предоставление не нужных возможностей.
|
||||||
public Hitbox(String shape){
|
public Hitbox(String shape){
|
||||||
this.shape = new String(shape);
|
this.shape = new String(shape);
|
||||||
}
|
}
|
||||||
|
|
||||||
//informationHitbox - default="Rectangle 0 0 96 98"
|
//informationHitbox - default="Rectangle 0 0 96 98"
|
||||||
|
//Предварительно, я бы сказал что вообще этот конструктор бесполезен и его можно удалить,
|
||||||
|
// т.к. Hitbox конструктор вызывается из дочерних элементов, а они уже владеют всей необходимой инфой, и entity owner задают сами
|
||||||
|
// кстати забавно. сейчас устанавливается entity через serOwnerEntity, но как будто этот метод тоже излишек, ведь владелец хитбокса только один.
|
||||||
|
//Но нет. у нас может быть хитбокс создан программно раньше entity, помню было такое где то, так что этот метод еще обоснован.
|
||||||
public Hitbox(String informationHitbox, Entity owner){
|
public Hitbox(String informationHitbox, Entity owner){
|
||||||
if(informationHitbox!= null) {
|
if(informationHitbox!= null) {
|
||||||
setOwnerEntity(owner);
|
setOwnerEntity(owner);
|
||||||
String[] informations = informationHitbox.split(" ");
|
String[] informations = informationHitbox.split(" ");
|
||||||
shape = new String(informations[0]);
|
shape = new String(informations[0]);
|
||||||
if(shape.equals("Rectangle")) {
|
|
||||||
/*parseStringToRectangleHitbox(informations);
|
|
||||||
createCartesianPointsFromWidthAndHeigh();
|
|
||||||
convertCartesianPointsToIso();
|
|
||||||
printToConsole();*/
|
|
||||||
}else if(shape.equals("Circle")) {
|
|
||||||
//parseStringToCircleHitbox(informations);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public abstract String listPointsToString();
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param result - Point object to store the result
|
* @param result - Point object to store the result
|
||||||
* @return x and y converted to isometic coords
|
* @return x and y converted to isometic coords
|
||||||
|
|||||||
@ -5,12 +5,22 @@ public class HitboxCircle extends Hitbox {
|
|||||||
|
|
||||||
public HitboxCircle(String[] dataHitbox, Entity owner){
|
public HitboxCircle(String[] dataHitbox, Entity owner){
|
||||||
super(dataHitbox[0]);
|
super(dataHitbox[0]);
|
||||||
|
setOwnerEntity(owner);
|
||||||
parseStringToCircleHitbox(dataHitbox);
|
parseStringToCircleHitbox(dataHitbox);
|
||||||
}
|
}
|
||||||
|
public HitboxCircle(String shape, Entity owner){
|
||||||
|
super(shape);
|
||||||
|
setOwnerEntity(owner);
|
||||||
|
radiusHitbox = 0;
|
||||||
|
}
|
||||||
private void parseStringToCircleHitbox(String[] informations) {
|
private void parseStringToCircleHitbox(String[] informations) {
|
||||||
referencePoint.x = Float.parseFloat(informations[1]);
|
referencePoint.x = Float.parseFloat(informations[1]);
|
||||||
referencePoint.y = Float.parseFloat(informations[2]);
|
referencePoint.y = Float.parseFloat(informations[2]);
|
||||||
radiusHitbox = Float.parseFloat(informations[3]);
|
radiusHitbox = Float.parseFloat(informations[3]);
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
|
public String listPointsToString() {
|
||||||
|
return "Circle"+referencePoint.x+referencePoint.x+" "+referencePoint.y+" "+radiusHitbox;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,7 +8,9 @@ public class HitboxRectangle extends Hitbox {
|
|||||||
private List<Point> listPointsCartesian = new ArrayList<Point>();
|
private List<Point> listPointsCartesian = new ArrayList<Point>();
|
||||||
private float widthHitbox = 0,heightHitbox = 0; // Ширина и высота хитбокса в декартовых координатах.
|
private float widthHitbox = 0,heightHitbox = 0; // Ширина и высота хитбокса в декартовых координатах.
|
||||||
|
|
||||||
public HitboxRectangle(){
|
public HitboxRectangle(String shape, Entity owner){
|
||||||
|
super(shape);
|
||||||
|
setOwnerEntity(owner);
|
||||||
initListsPoints();
|
initListsPoints();
|
||||||
}
|
}
|
||||||
public HitboxRectangle(String shape,List<Point> listPointsIso,List<Point> listPointsCartesian){
|
public HitboxRectangle(String shape,List<Point> listPointsIso,List<Point> listPointsCartesian){
|
||||||
@ -85,4 +87,8 @@ public class HitboxRectangle extends Hitbox {
|
|||||||
public List<Point> getListPointsCartesian() {
|
public List<Point> getListPointsCartesian() {
|
||||||
return listPointsCartesian;
|
return listPointsCartesian;
|
||||||
}
|
}
|
||||||
|
@Override
|
||||||
|
public String listPointsToString() {
|
||||||
|
return "Rectangle "+referencePoint.x+" "+referencePoint.y+" "+widthHitbox+" "+heightHitbox;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -32,6 +32,8 @@ import org.xml.sax.SAXException;
|
|||||||
|
|
||||||
import events.EntityDrawboxChangedEvent;
|
import events.EntityDrawboxChangedEvent;
|
||||||
import events.EntityDrawboxChangedListener;
|
import events.EntityDrawboxChangedListener;
|
||||||
|
import events.EntityHitboxChangedEvent;
|
||||||
|
import events.EntityHitboxChangedListener;
|
||||||
import exception.DuplicateEntryException;
|
import exception.DuplicateEntryException;
|
||||||
import launch.Launcher;
|
import launch.Launcher;
|
||||||
import model.Entity;
|
import model.Entity;
|
||||||
@ -41,7 +43,7 @@ import model.Entity;
|
|||||||
* Класс данных, который оперирует их сохранением, загрузкой, и хранением в памяти.
|
* Класс данных, который оперирует их сохранением, загрузкой, и хранением в памяти.
|
||||||
* ВАЖНО: данный класс хранит так же актуальную копию XML-представления файла
|
* ВАЖНО: данный класс хранит так же актуальную копию XML-представления файла
|
||||||
* */
|
* */
|
||||||
public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
|
public class Project implements Iterable<Entity>, EntityDrawboxChangedListener, EntityHitboxChangedListener {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Путь к XML по-умолчанию.
|
* Путь к XML по-умолчанию.
|
||||||
@ -125,7 +127,7 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Загружает типы сущностей из файла с заданным именем и расположением.<br>
|
* Загружает типы сущностей из файла с заданным именем и расположением.<br>0
|
||||||
* */
|
* */
|
||||||
public void load() throws SAXException, IOException, ParserConfigurationException {
|
public void load() throws SAXException, IOException, ParserConfigurationException {
|
||||||
listEntity.clear();
|
listEntity.clear();
|
||||||
@ -237,14 +239,14 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
|
|||||||
Element drawboxProperty = document.createElement("property");
|
Element drawboxProperty = document.createElement("property");
|
||||||
drawboxProperty.setAttribute("name", "drawbox");
|
drawboxProperty.setAttribute("name", "drawbox");
|
||||||
drawboxProperty.setAttribute("type", "string");
|
drawboxProperty.setAttribute("type", "string");
|
||||||
drawboxProperty.setAttribute("default", ""); // empty, because on creation there is no drawbox yet
|
drawboxProperty.setAttribute("default", "0 0 0 0 0 0 0 0"); // empty, because on creation there is no drawbox yet
|
||||||
objecttypeElement.appendChild(drawboxProperty);
|
objecttypeElement.appendChild(drawboxProperty);
|
||||||
|
|
||||||
// format: <property name="hitbox" type="string" default="HITBOX_TYPE OFFSET_X OFFSET_Y SIZE"/>
|
// format: <property name="hitbox" type="string" default="HITBOX_TYPE OFFSET_X OFFSET_Y SIZE"/>
|
||||||
Element hitboxProperty = document.createElement("property");
|
Element hitboxProperty = document.createElement("property");
|
||||||
hitboxProperty.setAttribute("name", "hitbox");
|
hitboxProperty.setAttribute("name", "hitbox");
|
||||||
hitboxProperty.setAttribute("type", "string");
|
hitboxProperty.setAttribute("type", "string");
|
||||||
hitboxProperty.setAttribute("default", ""); // empty, no hitbox yet
|
hitboxProperty.setAttribute("default", "Rectangle 0 0 0 0"); // empty, no hitbox yet
|
||||||
objecttypeElement.appendChild(hitboxProperty);
|
objecttypeElement.appendChild(hitboxProperty);
|
||||||
|
|
||||||
//printXMlToConsole(); //DEBUG!
|
//printXMlToConsole(); //DEBUG!
|
||||||
@ -355,7 +357,27 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
|
|||||||
//we have hitbox, drawbox and class, gotta set the right one
|
//we have hitbox, drawbox and class, gotta set the right one
|
||||||
Element propertyElement = ((Element)properties.item(i));
|
Element propertyElement = ((Element)properties.item(i));
|
||||||
if (propertyElement.getAttribute("name").equals("drawbox")) {
|
if (propertyElement.getAttribute("name").equals("drawbox")) {
|
||||||
propertyElement.setAttribute("default", event.owner.getDrawbox().toString());
|
propertyElement.setAttribute("default", event.owner.getDrawbox().listPointsToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получение события при отрисовке нового Hitbox, для изменения XML-дерева.
|
||||||
|
* Объект event хранит в себе ссылку на новый объект Hitbox и объект entity, для которой он был создан.
|
||||||
|
* */
|
||||||
|
@Override
|
||||||
|
public void hitboxChanged(EntityHitboxChangedEvent event) {
|
||||||
|
String entityName = event.owner.getName();
|
||||||
|
Node entityToUpdate = getEntityXMLNodeByName(entityName);
|
||||||
|
NodeList properties = entityToUpdate.getChildNodes();
|
||||||
|
for(int i = 0; i < properties.getLength(); i++) {
|
||||||
|
if(properties.item(i) instanceof Element) { // ignoring #text nodes
|
||||||
|
//we have hitbox, drawbox and class, gotta set the right one
|
||||||
|
Element propertyElement = ((Element)properties.item(i));
|
||||||
|
if (propertyElement.getAttribute("name").equals("hitbox")) {
|
||||||
|
propertyElement.setAttribute("default", event.owner.getHitbox().listPointsToString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -388,6 +410,8 @@ public class Project implements Iterable<Entity>, EntityDrawboxChangedListener {
|
|||||||
stripEmptyElements(child);
|
stripEmptyElements(child);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
//в момент окончания рисования, в зависимости в какой мы рисуем вкладке хитбокса,
|
//в момент окончания рисования, в зависимости в какой мы рисуем вкладке хитбокса,
|
||||||
//в зависимости от того в какой панельке(jpanel)и подклассе интерфейса Editable
|
//в зависимости от того в какой панельке(jpanel)и подклассе интерфейса Editable
|
||||||
|
|||||||
Reference in New Issue
Block a user