Matrix effect funzionante, scie fluide

This commit is contained in:
2026-01-28 14:16:20 +01:00
parent aae83af88a
commit a263079089
5 changed files with 288 additions and 297 deletions

View File

@@ -1,138 +1,147 @@
package matrix;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
public class ColonnaLettere extends JPanel {
private static final char[] MATRIX_CHARS = (
"ヲァィゥェォャュョッ" +
"アイウエオカキクケコ" +
"サシスセソタチツテト" +
"ナニヌネノハヒフヘホ" +
"マミムメモヤユヨ" +
"ラリルレロワン" +
"0123456789@#$%&*+-/=<>()"
).toCharArray();
private final List<Lettera> lettere = new ArrayList<>();
private final int larghezza;
private final int yEnd;
private BufferedImage buffer;
private Graphics2D bufferG;
private boolean raggiuntoFondo = false;
private float spawnTimer = 0f;
private final float spawnInterval; // tempo tra una lettera e l'altra
private final float dissolveSpeed; // velocità dissolvenza
private final float dissolveStep;
private final int stepY; // distanza verticale tra lettere
public Logo logo;
private final int xPos;
public ColonnaLettere(int x, int yStart, int yEnd, int larghezza) {
if (yEnd <= yStart) {
throw new IllegalArgumentException("Altezza colonna non valida: " + yEnd);
}
this.larghezza = larghezza;
this.yEnd = yEnd;
this.stepY = larghezza;
this.xPos = x;
this.dissolveStep = generaFloatCasuale(0.02f, 0.05f);
setOpaque(false);
setBounds(x, yStart, larghezza, yEnd - yStart);
creaNuovaLettera(); // prima lettera
}
// getter
public int getXPos() {
return xPos;
}
private char randomMatrixChar() {
return MATRIX_CHARS[
ThreadLocalRandom.current().nextInt(MATRIX_CHARS.length)
];
}
/* ===================== UPDATE ===================== */
// CHIAMATA DAL TIMER DEL FORM
public void aggiorna() {
// dissolve lettere esistenti
for (Lettera l : lettere) {
l.dissolve(dissolveStep);
}
lettere.removeIf(l -> l.getAlpha() <= 0);
// aggiungi lettera finché non raggiungi il fondo
if (!raggiuntoFondo) {
float nuovaY = lettere.isEmpty()
? 0
: lettere.get(lettere.size() - 1).getPosition().y + stepY;
if (nuovaY + stepY <= yEnd) {
creaNuovaLettera(nuovaY);
} else {
raggiuntoFondo = true;
}
}
repaint();
}
public boolean isVuota() {
return raggiuntoFondo && lettere.isEmpty();
}
/* ===================== LETTERE ===================== */
private void creaNuovaLettera() {
creaNuovaLettera(0);
}
private void creaNuovaLettera(float y) {
char c = randomMatrixChar();
int fontSize = larghezza;
Font font = new Font("Monospaced", Font.BOLD, fontSize);
Canvas canvas = new Canvas();
FontMetrics fm = canvas.getFontMetrics(font);
int charWidth = fm.charWidth(c);
if (charWidth > 0) {
fontSize = (int) ((float) larghezza / charWidth * fontSize);
}
Lettera l = new Lettera(
new Point2D.Float(0, y + fm.getAscent()),
Color.GREEN,
fontSize,
c
// buffer ARGB per trasparenza
this.buffer = new BufferedImage(
larghezza,
yEnd - yStart,
BufferedImage.TYPE_INT_ARGB
);
lettere.add(l);
setBounds(x, yStart, larghezza, yEnd - yStart);
setOpaque(false); // 🔥 FONDAMENTALE
setBackground(new Color(0,0,0,0)); // trasparente
bufferG = buffer.createGraphics();
bufferG.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON
);
bufferG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
spawnInterval = ThreadLocalRandom.current().nextFloat(0.05f, 0.15f);
dissolveSpeed = ThreadLocalRandom.current().nextFloat(0.1f, 0.6f);
// prima lettera
spawnLettera();
}
private float generaFloatCasuale(float min, float max) {
return min + (max - min) * ThreadLocalRandom.current().nextFloat();
// ================= UPDATE =================
public void aggiorna(float deltaTime) {
// Sfuma leggermente il buffer per creare scia trasparente
Graphics2D g2 = (Graphics2D) buffer.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f));
g2.setColor(new Color(0,0,0,255)); // trasparente
g2.fillRect(0, 0, buffer.getWidth(), buffer.getHeight());
g2.dispose();
spawnTimer += deltaTime;
if (spawnTimer >= spawnInterval) {
spawnTimer = 0f;
spawnLettera();
}
for (Lettera l : lettere) {
bufferG.setFont(new Font("Monospaced", Font.PLAIN, l.getDimensione()));
bufferG.setColor(new Color(
0,
255,
70,
Math.round(l.getAlpha() * 255) // alpha dinamico per dissolvenza
));
bufferG.drawString(
String.valueOf(l.getCarattere()),
l.getPosizione().x,
l.getPosizione().y
);
}
for (Iterator<Lettera> it = lettere.iterator(); it.hasNext();) {
Lettera l = it.next();
l.dissolve(dissolveSpeed * deltaTime); // diminuisce alpha
//l.dissolve(dissolveSpeed * deltaTime); // diminuisce alpha
//l.dissolve(dissolveSpeed * deltaTime); // riduce alpha
//l.muovi(deltaTime); // sposta y
if (!l.isViva()) it.remove(); // rimuove quando alpha = 0
}
repaint();
}
/* ===================== DRAW ===================== */
// ================= SPAWN =================
private void spawnLettera() {
float y = lettere.isEmpty()
? larghezza
: lettere.get(lettere.size() - 1).getPosizione().y + larghezza;
if (y > yEnd) return;
char c = Matrix.MATRIX_CHARS[ThreadLocalRandom.current().nextInt(Matrix.MATRIX_CHARS.length)];
Lettera l = new Lettera(0, y, c, larghezza);
l.setAlpha(1f); // piena luminosità
l.setNuova(true); // flag per lettera appena generata
lettere.add(l);
}
// ================= STATO =================
public boolean isVuota() {
return lettere.isEmpty();
}
public List<Lettera> getLettere() {
return lettere;
}
// ================= DRAW =================
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Lettera l : lettere) {
l.draw(g2);
Color colore;
if (!l.isNuova()) {
colore = new Color(0, 255, 0, Math.round(l.getAlpha() * 255));
} else {
colore = new Color(0, 255, 0);
l.setNuova(false);
}
//Color colore = new Color(0, 255, 70, Math.round(l.getAlpha() * 255));
g2.setColor(colore);
g2.setFont(new Font("Monospaced", Font.PLAIN, l.getDimensione()));
g2.drawString(String.valueOf(l.getCarattere()), l.getPosizione().x, l.getPosizione().y);
}
}
Iterable<Lettera> getLettere() {
return this.lettere;
}
}

View File

@@ -1,108 +1,63 @@
package matrix;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.Color;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
public class Lettera {
private Point2D.Float position;
private final char carattere;
private final int dimensione;
private final Point2D.Float posizione;
private Color colore;
private float alpha;
private int dimensione;
private char carattere;
private BufferedImage buffer; // immagine della lettera
private Shape shape; // shape della lettera
// Costruttore
public Lettera(Point2D.Float position, Color colore, int dimensione, char carattere) {
this.position = position;
this.colore = colore;
this.dimensione = dimensione;
public Lettera(float x, float y, char carattere, int dimensione) {
this.carattere = carattere;
this.dimensione = dimensione;
this.posizione = new Point2D.Float(x, y);
this.colore = Color.GREEN;
this.alpha = 1.0f;
generaBuffer();
}
private void generaBuffer() {
Font font = new Font("Monospaced", Font.BOLD, dimensione);
FontRenderContext frc = new FontRenderContext(null, true, true);
GlyphVector gv = font.createGlyphVector(frc, String.valueOf(carattere));
shape = gv.getOutline();
private boolean nuova = false; // flag prima lettera
Rectangle bounds = shape.getBounds();
buffer = new BufferedImage(bounds.width + 2, bounds.height + 2, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = buffer.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(colore);
g2.translate(-bounds.x, -bounds.y); // porta la lettera all'inizio del buffer
g2.fill(shape);
g2.dispose();
}
// Disegna la lettera sul Graphics2D
public void draw(Graphics2D g2) {
int x = (int) position.x;
int y = (int) position.y;
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, Math.min(1.0f, Math.max(0, alpha)));
g2.setComposite(ac);
g2.drawImage(buffer, x, y, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
public boolean isNuova() { return nuova; }
public void setNuova(boolean nuova) { this.nuova = nuova; }
// ===== GETTER =====
public char getCarattere() {
return carattere;
}
// Aggiorna la trasparenza per far dissolvere la lettera
public void dissolve(float step) {
alpha -= step;
if (alpha < 0) alpha = 0;
public int getDimensione() {
return dimensione;
}
public Point2D.Float getPosizione() {
return posizione;
}
// Getter per alpha (utile per sapere se è scomparsa)
public float getAlpha() {
return alpha;
}
// Setter e getter aggiuntivi se vuoi spostare o cambiare colore
public void setPosition(Point2D.Float pos) {
this.position = pos;
}
public Point2D.Float getPosition() {
return position;
public void setAlpha(float alfa){
this.alpha=alfa;
}
public Color getColore() {
return colore;
}
// ===== SETTER =====
public void setColore(Color colore) {
this.colore = colore;
}
public Color getColore() {
return colore;
// ===== LOGICA =====
public void dissolve(float amount) {
alpha -= amount;
if (alpha < 0f) alpha = 0f;
}
public Shape getShapeAtPosition() {
AffineTransform at = AffineTransform.getTranslateInstance(
position.x,
position.y
);
return at.createTransformedShape(shape);
}
public Area getAreaAtPosition() {
AffineTransform at = AffineTransform.getTranslateInstance(
position.x,
position.y
);
return new Area(at.createTransformedShape(shape));
}
public Area getWorldArea(int colX, int colY) {
AffineTransform at = new AffineTransform();
at.translate(colX + position.x, colY + position.y);
return new Area(at.createTransformedShape(shape));
}
// getter e setter
public int getDimensione() { return dimensione; }
public boolean isViva() {
return alpha > 0f;
}
}

67
src/matrix/LogoMask.java Normal file
View File

@@ -0,0 +1,67 @@
package matrix;
import java.awt.*;
import java.awt.image.BufferedImage;
public class LogoMask {
private final BufferedImage mask;
private final BufferedImage glow;
private final int x, y;
public LogoMask(BufferedImage logo, int x, int y) {
this.x = x;
this.y = y;
mask = new BufferedImage(
logo.getWidth(),
logo.getHeight(),
BufferedImage.TYPE_INT_ARGB
);
glow = new BufferedImage(
logo.getWidth(),
logo.getHeight(),
BufferedImage.TYPE_INT_ARGB
);
// copia logo → mask
Graphics2D g = mask.createGraphics();
g.drawImage(logo, 0, 0, null);
g.dispose();
}
// chiamata quando una lettera passa sopra
public void accendiPixel(int worldX, int worldY, int size, Color c) {
int lx = worldX - x;
int ly = worldY - y;
if (lx < 0 || ly < 0 ||
lx >= mask.getWidth() ||
ly >= mask.getHeight()) return;
int alpha = (mask.getRGB(lx, ly) >> 24) & 0xff;
if (alpha == 0) return; // pixel logo trasparente
Graphics2D g = glow.createGraphics();
g.setComposite(AlphaComposite.SrcOver);
g.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 200));
g.fillRect(lx, ly, size, size);
g.dispose();
}
// dissolve del logo
public void sfuma() {
Graphics2D g = glow.createGraphics();
g.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.85f)
);
g.setColor(Color.BLACK);
g.fillRect(0, 0, glow.getWidth(), glow.getHeight());
g.dispose();
}
public void draw(Graphics2D g) {
g.drawImage(glow, x, y, null);
}
}

View File

@@ -11,7 +11,15 @@ import java.awt.Color;
* @author mstc
*/
public class Matrix {
public static final char[] MATRIX_CHARS = (
"ヲァィゥェォャュョッ" +
"アイウエオカキクケコ" +
"サシスセソタチツテト" +
"ナニヌネノハヒフヘホ" +
"マミムメモヤユヨ" +
"ラリルレロワン" +
"01010101010101010101010101010"
).toCharArray();
/**
* @param args the command line arguments
*/

View File

@@ -5,15 +5,9 @@
package matrix;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Area;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
@@ -27,150 +21,108 @@ public class MatrixForm extends JFrame {
private final List<ColonnaLettere> colonne = new ArrayList<>();
private int maxColonne = 100;
private final int yStart = 0;
private int yEnd = 600;
private final int larghezzaMin = 10;
private final int larghezzaMax = 25;
private int maxColonne;
private final int larghezzaMin = 5;
private final int larghezzaMax = 16;
private Logo logo;
// POSIZIONE LOGO (ORA ESISTE)
private int logoX;
private int logoY;
private long lastTime = System.nanoTime();
public MatrixForm() {
setTitle("Matrix Test");
// === FINESTRA ===
getContentPane().setBackground(Color.BLACK);
setLayout(null);
setTitle("Matrix");
setBackground(Color.BLACK);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// listener resize (SENZA @Override)
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
yEnd = getHeight();
maxColonne = Math.max(1, getWidth() / larghezzaMin);
// carica logo
try {
logo = new Logo("/home/mstc/Immagini/logo.png");
if (getHeight() <= 0) return;
// posizione iniziale logo
logoX = (getWidth() - logo.getWidth()) / 2;
logoY = (getHeight() - logo.getHeight()) / 2;
} catch (IOException ex) {
ex.printStackTrace();
}
if (logo != null) {
logoX = (getWidth() - logo.getWidth()) / 2;
logoY = (getHeight() - logo.getHeight()) / 2;
}
resetColonne();
}
});
setVisible(true);
setVisible(true);
// crea colonne iniziali
for (int i = 0; i < maxColonne; i++) {
aggiungiNuovaColonna();
}
// timer principale
Timer timer = new Timer(16, e -> aggiornaColonne());
// === TIMER (30 FPS circa) ===
Timer timer = new Timer(33, e -> aggiorna());
timer.start();
}
// =========================
// LOGICA
// =========================
private void aggiungiNuovaColonna() {
private void aggiorna() {
long now = System.nanoTime();
float deltaTime = (now - lastTime) / 1_000_000_000f;
lastTime = now;
int larghezza = ThreadLocalRandom.current()
.nextInt(larghezzaMin, larghezzaMax + 1);
int x = ThreadLocalRandom.current()
.nextInt(0, Math.max(1, getWidth() - larghezza));
ColonnaLettere col = new ColonnaLettere(
x,
yStart,
getHeight(),
larghezza
);
colonne.add(col);
add(col);
}
private void aggiornaColonne() {
// aggiorna colonne
for (int i = colonne.size() - 1; i >= 0; i--) {
ColonnaLettere col = colonne.get(i);
col.aggiorna();
ColonnaLettere c = colonne.get(i);
c.aggiorna(deltaTime);
if (col.isVuota()) {
remove(col);
if (c.isVuota()) {
remove(c);
colonne.remove(i);
}
}
// sostituisci colonne mancanti
// mantieni sempre il numero massimo
while (colonne.size() < maxColonne) {
aggiungiNuovaColonna();
aggiungiColonna();
}
// controllo collisione lettere-logo
for (ColonnaLettere col : colonne) {
for (Lettera l : col.getLettere()) {
int lx = col.getXPos() + (int) l.getPosition().x;
int ly = (int) l.getPosition().y;
// if (lx >= logoX && lx < logoX + logo.getWidth() &&
// ly >= logoY && ly < logoY + logo.getHeight() &&
// logo.isLogoPixel(lx - logoX, ly - logoY)) {
//
// l.dissolve(0.2f);
// logo.accendiPixel(lx - logoX, ly - logoY, l.getDimensione(), l.getAlpha()-0.10f);
// }
}
}
logo.sfuma();
repaint();
}
// DISEGNO
@Override
public void paint(Graphics g) {
super.paint(g);
private void calcolaColonne() {
maxColonne = Math.max(1, getWidth() / larghezzaMin)+100;
if (logo != null) {
logo.disegna((Graphics2D) g, logoX, logoY);
for (int i = 0; i < maxColonne; i++) {
aggiungiColonna();
}
}
private void resetColonne() {
colonne.forEach(this::remove);
colonne.clear();
calcolaColonne();
}
private void aggiungiColonna() {
int h = getHeight();
if (h <= 0) return; // 🔥 salva la vita
int larghezza = ThreadLocalRandom.current()
.nextInt(larghezzaMin, larghezzaMax + 1);
int x = ThreadLocalRandom.current()
.nextInt(0, Math.max(1, getWidth() - larghezza));
ColonnaLettere col = new ColonnaLettere(
x,
0,
h,
larghezza
);
colonne.add(col);
add(col);
}
//private void aggiungiNuovaColonna() {
// int larghezza = ThreadLocalRandom.current().nextInt(16, 32);
// int x = ThreadLocalRandom.current().nextInt(0, Math.max(1, getWidth() - larghezza));
//
// ColonnaLettere col = new ColonnaLettere(
// x,
// 0,
// getHeight(),
// larghezza
// );
//
// colonne.add(col);
// add(col);
//}
/**
* This method is called from within the constructor to initialize the form.